Skip to content

Commit

Permalink
Changes to deal with zombie processes
Browse files Browse the repository at this point in the history
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
  • Loading branch information
augustocristian committed Aug 16, 2024
1 parent 93a9279 commit b277862
Show file tree
Hide file tree
Showing 21 changed files with 217 additions and 343 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,6 +51,8 @@ public class BaseLoggedTest {

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

public BaseLoggedTest() {
}
Expand All @@ -66,7 +66,7 @@ static void setupAll() { // 28 lines
// 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
log.error("Properties file could not be loaded");
}

// Check if running outside ElasTest
Expand All @@ -85,7 +85,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,19 +109,18 @@ static void setupAll() { // 28 lines
}

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

user = setupBrowser("chrome", TJOB_NAME + "_" + TEST_NAME, userMail, WAIT_SECONDS);
driver = user.getDriver();
this.user = setupBrowser("chrome", TJOB_NAME + "_" + info.getTestMethod().get().getName(), "Teacher", 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);

Expand Down Expand Up @@ -160,20 +159,41 @@ protected BrowserUser setupBrowser(String browser, String testName,
}

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

if (user != null) {
log.info("##### Finish test: {} - Driver {}", TEST_NAME, this.user.getDriver());
void tearDown(TestInfo info) { //13 lines
if (this.user != null) {
log.info("##### Finish test: {} - Driver {}", info.getTestMethod().get().getName(), 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 (user.isOnSession()) {
this.logout(user);
if (this.user.isOnSession()) {
this.logout(this.user);
}

user.dispose();
this.user.dispose();
}

if (this.student != null) {
log.info("##### Finish test: {} - Driver {}", info.getTestMethod().get().getName(), 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 (this.student.isOnSession()) {
this.logout(student);
}

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();
}
}
}

Expand Down Expand Up @@ -224,19 +244,21 @@ private void login(BrowserUser user, String userEmail, String userPass,
try {
userName = getUserName(user, true, APP_URL);
} catch (NotLoggedException | ElementNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if (e.getClass().isInstance(NotLoggedException.class)){
log.error("The user {} was not logged",user.getClientData());}
else{
log.error("The userName field not found" );
}
}

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 +331,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 +343,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 @@ -347,7 +369,7 @@ protected void waitSeconds(int seconds) {
try {
Thread.sleep(1000L * seconds);
} catch (InterruptedException e) {
e.printStackTrace();
log.error("Thread.sleep interrupted");
}

}
Expand All @@ -372,14 +394,14 @@ 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;

}

Expand Down
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 Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
import org.openqa.selenium.support.ui.WebDriverWait;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
Expand All @@ -41,25 +42,19 @@
public class ChromeUser extends BrowserUser {
ChromeOptions options = new ChromeOptions();

public ChromeUser(String userName, int timeOfWaitInSeconds, String testName, String userIdentifier) {
public ChromeUser(String userName, int timeOfWaitInSeconds, String testName, String userIdentifier) throws URISyntaxException, MalformedURLException {
super(userName, timeOfWaitInSeconds);
log.info("Starting the configuration of the web browser");
log.debug(String.format("The Test names are: %s", testName));
log.debug(String.format("The Test name is: %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,8 +63,6 @@ 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");
Expand All @@ -85,7 +78,7 @@ public ChromeUser(String userName, int timeOfWaitInSeconds, String testName, Str
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);
log.debug("The data of this test would be stored into: video name: {} and the log name: {} " , videoName,logName);

selenoidOptions.put("enableLog", true);
selenoidOptions.put("logName ", logName);
Expand All @@ -97,13 +90,10 @@ public ChromeUser(String userName, int timeOfWaitInSeconds, String testName, Str

//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
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
import org.openqa.selenium.support.ui.WebDriverWait;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
Expand All @@ -36,7 +37,7 @@
public class EdgeUser extends BrowserUser {
EdgeOptions options = new EdgeOptions();

public EdgeUser(String userName, int timeOfWaitInSeconds, String testName, String userIdentifier) {
public EdgeUser(String userName, int timeOfWaitInSeconds, String testName, String userIdentifier) throws URISyntaxException {
super(userName, timeOfWaitInSeconds);
log.info(String.format("The Test names are: %s", testName));

Expand Down Expand Up @@ -67,7 +68,7 @@ public EdgeUser(String userName, int timeOfWaitInSeconds, String testName, Strin
LocalDateTime now = LocalDateTime.now();
String logName = dtf.format(now) + "-" + testName + "-" + userIdentifier + ".log";
String videoName = 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);
log.debug("The data of this test would be stored into: video name {} and the log is {}", videoName,logName);

selenoidOptions.put("enableLog", true);
selenoidOptions.put("logName ", logName);
Expand All @@ -79,7 +80,7 @@ public EdgeUser(String userName, int timeOfWaitInSeconds, String testName, Strin

//END CAPABILITIES FOR SELENOID RETORCH

RemoteWebDriver remote = new RemoteWebDriver(new URL(eusApiURL), options);
RemoteWebDriver remote = new RemoteWebDriver(new URI(eusApiURL).toURL(), options);
remote.setFileDetector(new LocalFileDetector());


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
import org.openqa.selenium.remote.RemoteWebDriver;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
Expand All @@ -35,7 +36,7 @@
public class FirefoxUser extends BrowserUser {
FirefoxOptions options = new FirefoxOptions();

public FirefoxUser(String userName, int timeOfWaitInSeconds, String testName, String userIdentifier) {
public FirefoxUser(String userName, int timeOfWaitInSeconds, String testName, String userIdentifier) throws URISyntaxException {
super(userName, timeOfWaitInSeconds);
//TO-DO Firefox configuration has changed, review it.
FirefoxProfile profile = new FirefoxProfile();
Expand Down Expand Up @@ -74,8 +75,7 @@ public FirefoxUser(String userName, int timeOfWaitInSeconds, String testName, St
LocalDateTime now = LocalDateTime.now();
String logName = dtf.format(now) + "-" + testName + "-" + userIdentifier + ".log";
String videoName = 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);

log.debug("The data of this test would be stored into: video name {} and the log is {}", videoName,logName);
selenoidOptions.put("enableLog", true);
selenoidOptions.put("logName ", logName);
selenoidOptions.put("videoName", videoName);
Expand All @@ -86,7 +86,7 @@ public FirefoxUser(String userName, int timeOfWaitInSeconds, String testName, St

//END CAPABILITIES FOR SELENOID RETORCH

RemoteWebDriver remote = new RemoteWebDriver(new URL(eusApiURL), options);
RemoteWebDriver remote = new RemoteWebDriver(new URI(eusApiURL).toURL(), options);
remote.setFileDetector(new LocalFileDetector());


Expand All @@ -99,7 +99,6 @@ public FirefoxUser(String userName, int timeOfWaitInSeconds, String testName, St
}
}

//this.driver.manage().timeouts().setScriptTimeout(this.timeOfWaitInSeconds, TimeUnit.SECONDS);

this.configureDriver();
}
Expand Down
Loading

0 comments on commit b277862

Please sign in to comment.