Skip to content

Commit

Permalink
Fix zombie processes created by FullTeaching test suite (#145)
Browse files Browse the repository at this point in the history
* Changes to deal with zombie processes

Refractoring to the base test class, making all test cases parametrized
and avoiding differences between test cases
Also minor fixes related to smells that sonar and IntelliJ detect

* Fixing the ReplyToCommentTest

* Changes requested:

- Removing exceptions where its handling its not appropiate.
- Removing blank and double-blank lines

* Changes requested:
- Adding exception to logintest

* Changes requested by Linter:
- Not used imports
- Replace string concatenation with {}
- Replace <= lists with .empty method
  • Loading branch information
augustocristian committed Aug 20, 2024
1 parent 93a9279 commit 1fbb567
Show file tree
Hide file tree
Showing 36 changed files with 350 additions and 654 deletions.
4 changes: 2 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,9 @@
<!-- Plugins -->

<build>
<!-- Temporal patch, comment this to avoid unexpected behaviour -->
<!-- To avoid problems with concurrency we change the directories of the reports and outputs -->
<testOutputDirectory>${basedir}/target/test-classes/${dirtarget}</testOutputDirectory>

<outputDirectory>${basedir}/target/classes/${dirtarget}</outputDirectory>
<plugins>
<!-- Jacoco Plugin for Jesus -->
<plugin>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,18 @@

import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import static com.fullteaching.e2e.no_elastest.common.Constants.*;
import static java.lang.invoke.MethodHandles.lookup;
import static org.openqa.selenium.logging.LogType.BROWSER;
import static org.slf4j.LoggerFactory.getLogger;

public class BaseLoggedTest {

public static final String CHROME = "chrome";
// For use another host
//protected static final String host= SetUp.getHost();
public static final String FIREFOX = "firefox";
public static final String EDGE = "edge";
public static final Logger log = LoggerFactory.getLogger(BaseLoggedTest.class);
Expand All @@ -41,7 +40,6 @@ public class BaseLoggedTest {
public static String TEACHER_BROWSER;
public static String STUDENT_BROWSER;
public static String BROWSER_NAME;
public static String course_title;
protected static String HOST = LOCALHOST;
protected static String userName;
protected static String userMail;
Expand All @@ -53,21 +51,18 @@ public class BaseLoggedTest {

public WebDriver driver;
protected BrowserUser user;
protected BrowserUser student;
protected List<BrowserUser> studentBrowserUserList;

public BaseLoggedTest() {
}

@BeforeAll
static void setupAll() { // 28 lines
static void setupAll() throws IOException { // 28 lines
// Initialize properties
properties = new Properties();

try {
// Load a properties file for reading
properties.load(new FileInputStream("src/test/resources/inputs/test.properties"));
} catch (IOException ex) {
ex.printStackTrace(); // Consider logging the exception instead of printing the stack trace
}
// Load a properties file for reading
properties.load(new FileInputStream("src/test/resources/inputs/test.properties"));

// Check if running outside ElasTest
if (System.getenv("ET_EUS_API") == null) {
Expand All @@ -85,7 +80,7 @@ static void setupAll() { // 28 lines
TJOB_NAME = envTJobName;
PORT = envPort;
APP_URL = envUrl + TJOB_NAME + ":" + PORT + "/";
log.debug("The URL is" + APP_URL);
log.debug("The URL is {}" , APP_URL);
HOST = APP_URL;
} else {
// Check if app.url system property is defined
Expand All @@ -109,38 +104,36 @@ static void setupAll() { // 28 lines
}

@BeforeEach
void setup(TestInfo info) { //65 lines
void setup(TestInfo info) throws URISyntaxException, MalformedURLException {
if (info.getTestMethod().isPresent()) {
TEST_NAME = info.getTestMethod().get().getName();
userName=info.getDisplayName().split(",")[2];
}
log.info("##### Start test: " + TEST_NAME);
TJOB_NAME = System.getProperty("dirtarget");
log.info("##### Start test: {}" , TEST_NAME);

user = setupBrowser("chrome", TJOB_NAME + "_" + TEST_NAME, userMail, WAIT_SECONDS);
driver = user.getDriver();
this.user = setupBrowser("chrome", TJOB_NAME + "-" +TEST_NAME, userName, WAIT_SECONDS);

this.driver = this.user.getDriver();
}

protected BrowserUser setupBrowser(String browser, String testName,
String userIdentifier, int secondsOfWait) {
String userIdentifier, int secondsOfWait) throws URISyntaxException, MalformedURLException {
BrowserUser u;
log.info("Starting browser ({})", browser);

switch (browser) {
case FIREFOX:
BROWSER_NAME = FIREFOX;
u = new FirefoxUser(userIdentifier, secondsOfWait, testName,
userIdentifier);
u = new FirefoxUser(userIdentifier, secondsOfWait, testName);
break;
case EDGE:
BROWSER_NAME = EDGE;
u = new EdgeUser(userIdentifier, secondsOfWait, testName,
userIdentifier);
u = new EdgeUser(userIdentifier, secondsOfWait, testName);
break;

default:
BROWSER_NAME = CHROME;
u = new ChromeUser(userIdentifier, secondsOfWait, testName,
userIdentifier);
u = new ChromeUser(userIdentifier, secondsOfWait, testName);
}

log.info("Navigating to {}", APP_URL);
Expand All @@ -160,37 +153,58 @@ protected BrowserUser setupBrowser(String browser, String testName,
}

@AfterEach
void tearDown(TestInfo testInfo) { //13 lines

if (user != null) {
void tearDown() { //13 lines
if (this.user != null) {
log.info("##### Finish test: {} - Driver {}", TEST_NAME, this.user.getDriver());
log.info("Browser console at the end of the test");
LogEntries logEntries = user.getDriver().manage().logs().get(BROWSER);
logEntries.forEach((entry) -> log.info("[{}] {} {}",
logEntries.forEach(entry -> log.info("[{}] {} {}",
new Date(entry.getTimestamp()), entry.getLevel(),
entry.getMessage()));
if (this.user.isOnSession()) {
this.logout(this.user);
}

this.user.dispose();
}

if (this.student != null) {
log.info("##### Finish test: {} - Driver {}",TEST_NAME, this.student.getDriver());
log.info("Browser console at the end of the test");
LogEntries logEntries = student.getDriver().manage().logs().get(BROWSER);
logEntries.forEach(entry -> log.info("[{}] {} {}",
new Date(entry.getTimestamp()), entry.getLevel(),
entry.getMessage()));
if (user.isOnSession()) {
this.logout(user);
if (this.student.isOnSession()) {
this.logout(student);
}

user.dispose();
student.dispose();}
//Logout and exit list of Students
if (this.studentBrowserUserList!=null) {
for (BrowserUser memberStudent : this.studentBrowserUserList) {
if (memberStudent.isOnSession()) {
this.logout(memberStudent);
}
memberStudent.dispose();
}
}
}

protected void slowLogin(BrowserUser user, String userEmail,
String userPass) {//24 lines
String userPass) throws NotLoggedException, ElementNotFoundException, InterruptedException {//24 lines
log.info("Slow login");
this.login(user, userEmail, userPass, true);
}

protected void quickLogin(BrowserUser user, String userEmail,
String userPass) { //24 lines
String userPass) throws NotLoggedException, ElementNotFoundException, InterruptedException { //24 lines
log.info("Quick login");
this.login(user, userEmail, userPass, false);
}

private void login(BrowserUser user, String userEmail, String userPass,
boolean slow) { //24 lines
boolean slow) throws NotLoggedException, ElementNotFoundException, InterruptedException { //24 lines
user.setOnSession(true);
log.info("Logging in user {} with mail '{}'", user.getClientData(), userEmail);
Wait.waitForPageLoaded(user.getDriver());
Expand Down Expand Up @@ -221,22 +235,15 @@ private void login(BrowserUser user, String userEmail, String userPass,

user.waitUntil(ExpectedConditions.presenceOfElementLocated(COURSE_LIST), "The Course list is not present");
user.waitUntil(ExpectedConditions.elementToBeClickable(By.id(("course-list"))), "Course list is not clickable");
try {
userName = getUserName(user, true, APP_URL);
} catch (NotLoggedException | ElementNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

userName = getUserName(user, true, APP_URL);
log.info("Logging in successful for user {}", user.getClientData());

}

protected void logout(BrowserUser user) { //43 lines
// log.info("Logging out {}", user.getClientData());
log.info("Logging out {}", user.getClientData());

if (user.getDriver().findElements(By.cssSelector("#fixed-icon"))
.size() > 0) {
if (!user.getDriver().findElements(By.cssSelector("#fixed-icon")).isEmpty()) {
// Get out of video session page
if (!isClickable("#exit-icon", user)) { // Side menu not opened
user.getDriver().findElement(By.cssSelector("#fixed-icon"))
Expand Down Expand Up @@ -309,7 +316,7 @@ protected void openDialog(String cssSelector, BrowserUser user) {
"//div[contains(@class, 'modal-overlay') and contains(@style, 'opacity: 0.5')]")),
"Dialog not opened");

log.info("Dialog opened for user {}", user.getClientData());
log.info("Dialog opened using css selector for user {}", user.getClientData());
}

protected void openDialog(WebElement el, BrowserUser user) {//8lines
Expand All @@ -321,7 +328,7 @@ protected void openDialog(WebElement el, BrowserUser user) {//8lines
user.waitUntil(ExpectedConditions.presenceOfElementLocated(By.xpath(
"//div[contains(@class, 'modal-overlay') and contains(@style, 'opacity: 0.5')]")),
"Dialog not opened");
log.info("Dialog opened for user {}", user.getClientData());
log.info("Dialog using webelement for user {}", user.getClientData());
}

protected void waitForDialogClosed(String dialogId, String errorMessage,
Expand All @@ -343,13 +350,8 @@ protected void waitForDialogClosed(String dialogId, String errorMessage,
log.info("Dialog closed for user {}", user.getClientData());
}

protected void waitSeconds(int seconds) {
try {
protected void waitSeconds(int seconds) throws InterruptedException {
Thread.sleep(1000L * seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}

}

public String getUserName(BrowserUser user, boolean goBack, String host) throws NotLoggedException, ElementNotFoundException {
Expand All @@ -372,16 +374,15 @@ public String getUserName(BrowserUser user, boolean goBack, String host) throws

WebElement name_placeholder = Wait.notTooMuch(user.getDriver()).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(USERNAME_XPATH)));

String userName = name_placeholder.getText().trim();
String userNameTag = name_placeholder.getText().trim();

if (goBack) {
user.getDriver().navigate().back();
}
//Check if the username is the expected
log.info("[END] getUserName");
return userName;

return userNameTag;
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@

import java.time.Duration;

import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;

public class BrowserUser {

Expand All @@ -48,7 +46,6 @@ public WebDriver getDriver() {
return this.driver;
}


public WebDriverWait getWaiter() {
return this.waiter;
}
Expand Down Expand Up @@ -86,4 +83,4 @@ public boolean isOnSession() {
public void setOnSession(boolean onSession) {
isOnSession = onSession;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,11 @@
import org.openqa.selenium.support.ui.WebDriverWait;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

Expand All @@ -41,25 +39,18 @@
public class ChromeUser extends BrowserUser {
ChromeOptions options = new ChromeOptions();

public ChromeUser(String userName, int timeOfWaitInSeconds, String testName, String userIdentifier) {
super(userName, timeOfWaitInSeconds);
public ChromeUser(String userIdentifier, int timeOfWaitInSeconds, String testName) throws URISyntaxException, MalformedURLException {
super(userIdentifier, timeOfWaitInSeconds);
log.info("Starting the configuration of the web browser");
log.debug(String.format("The Test names are: %s", testName));

LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(BROWSER, ALL);
options.setCapability("goog:loggingPrefs", logPrefs);

//Problems with the max attempt of retry, solved with : https://github.com/aerokube/selenoid/issues/1124 solved with --disable-gpu
// options.addArguments("--disable-gpu"); Commented for the moment
//Problems with flakiness due to screen resolution solved with --start-maximized
String[] arguments = {"--no-sandbox", "--disable-dev-shm-usage", "--allow-elevated-browser", "--disable-gpu", "--start-maximized"};

log.debug("Adding the arguments ({})", Arrays.toString(arguments));
for (String argument : arguments
) {
options.addArguments(argument);
}

options.addArguments("--start-maximized");
options.setAcceptInsecureCerts(true);
//This capability is to store the logs of the test case
log.debug("Added Capabilities of acceptInsecureCerts and ignore alarms");
Expand All @@ -68,42 +59,30 @@ public ChromeUser(String userName, int timeOfWaitInSeconds, String testName, Str
log.info("Using the Local WebDriver ()");
this.driver = new ChromeDriver(options);
} else {
try {

Map<String, Object> selenoidOptions = new HashMap<>();
log.info("Using the remote WebDriver (Selenoid)");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH:mm");
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yy-MM-dd-HH:mm");
LocalDateTime now = LocalDateTime.now();
String baseName = System.getProperty("tjob_name") + "-" + dtf.format(now) + "-" + testName + "-" + userIdentifier ;
log.debug("The data of this test are stored into .mp4 and .log files named: {}" , baseName);
log.debug("Adding all the extra capabilities needed: {testName,enableVideo,enableVNC,name,enableLog,videoName,screenResolution}");
//CAPABILITIES FOR SELENOID

selenoidOptions.put("testName", testName + "_" + userIdentifier + "_" + format.format(new Date()));
//CAPABILITIES FOR SELENOID RETORCH
selenoidOptions.put("testName", testName + "-" + userIdentifier + "-" + dtf.format(now));
selenoidOptions.put("enableVideo", true);
selenoidOptions.put("enableVNC", true);
selenoidOptions.put("name", testName + "-" + userIdentifier);

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yy-MM-dd-HH:mm");
LocalDateTime now = LocalDateTime.now();
String logName = System.getProperty("tjob_name") + "-" + dtf.format(now) + "-" + testName + "-" + userIdentifier + ".log";
String videoName = System.getProperty("tjob_name") + "-" + dtf.format(now) + "-" + testName + "-" + userIdentifier + ".mp4";
log.debug("The data of this test would be stored into: video name " + videoName + " and the log is " + logName);

selenoidOptions.put("enableLog", true);
selenoidOptions.put("logName ", logName);
selenoidOptions.put("videoName", videoName);

selenoidOptions.put("logName ", String.format("%s%s",baseName.replaceAll("\\s","") , ".log"));
selenoidOptions.put("videoName", String.format("%s%s",baseName.replaceAll("\\s","") ,".mp4"));
selenoidOptions.put("screenResolution", "1920x1080x24");

options.setCapability("selenoid:options", selenoidOptions);

//END CAPABILITIES FOR SELENOID RETORCH
log.debug("Configuring the remote WebDriver ");
RemoteWebDriver remote = new RemoteWebDriver(new URL("http://selenoid:4444/wd/hub"), options);
RemoteWebDriver remote = new RemoteWebDriver(new URI("http://selenoid:4444/wd/hub").toURL(), options);
log.debug("Configuring the Local File Detector");
remote.setFileDetector(new LocalFileDetector());
this.driver = remote;
} catch (MalformedURLException e) {
throw new RuntimeException("Exception creating eusApiURL", e);
}
}
log.debug("Configure the driver connection timeouts at ({})", this.timeOfWaitInSeconds);
new WebDriverWait(driver, Duration.ofSeconds(this.timeOfWaitInSeconds));
Expand Down
Loading

0 comments on commit 1fbb567

Please sign in to comment.