Skip to content

Commit

Permalink
Solved problems:
Browse files Browse the repository at this point in the history
- Solved the problems with the overwritting logs
- Refractored BaseLoggedTest and BrowserUsers to show correctly the user that is performing the actions
- Removing deprecated use of URL
- Smells provided by sonarlint solved
- Removed spaces and format
  • Loading branch information
augustocristian committed Jul 29, 2024
1 parent 93a9279 commit fea767b
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 125 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,13 @@
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);
protected static final Class<? extends WebDriver> chrome = ChromeDriver.class;
protected static final Class<? extends WebDriver> firefox = FirefoxDriver.class;
public static String TEACHER_BROWSER;
Expand All @@ -50,26 +45,24 @@ public class BaseLoggedTest {
protected static String TEST_NAME = "DEFAULT";
protected static String TJOB_NAME = "TJobDef";
protected final static int DEPTH = 3;

public WebDriver driver;
protected BrowserUser user;

public static final Logger log = LoggerFactory.getLogger(BaseLoggedTest.class);

public BaseLoggedTest() {
}

@BeforeAll
static void setupAll() { // 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
log.error("The properties file cannot be loaded, cause {}",ex.getStackTrace().toString());
}

// Check if running outside ElasTest
// The existence of the ET_EUS_API indicates that its being executed in Jenkins, so set-up the chrom and firefox instances
if (System.getenv("ET_EUS_API") == null) {
// Setup drivers for Chrome and Firefox
ChromeDriverManager.getInstance(chrome).setup();
Expand All @@ -85,26 +78,22 @@ 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
APP_URL = System.getProperty("app.url", LOCALHOST);

// Set HOST if APP_URL is not null
if (APP_URL != null) {
HOST = APP_URL;
}
}

// Set browser types for teacher and student
TEACHER_BROWSER = System.getenv("TEACHER_BROWSER");
STUDENT_BROWSER = System.getenv("STUDENT_BROWSER");

// Default to Chrome if browser types are not defined or are not Firefox
TEACHER_BROWSER = (TEACHER_BROWSER == null || !TEACHER_BROWSER.equals(FIREFOX)) ? CHROME : TEACHER_BROWSER;
STUDENT_BROWSER = (STUDENT_BROWSER == null || !STUDENT_BROWSER.equals(FIREFOX)) ? CHROME : STUDENT_BROWSER;

log.info("Using URL {} to connect to OpenVidu-app", APP_URL);
}

Expand All @@ -113,36 +102,29 @@ void setup(TestInfo info) { //65 lines
if (info.getTestMethod().isPresent()) {
TEST_NAME = info.getTestMethod().get().getName();
}
log.info("##### Start test: " + TEST_NAME);
log.info("##### Start test: {}", TEST_NAME);
TJOB_NAME = System.getProperty("dirtarget");

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

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

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

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

log.info("Navigating to {}", APP_URL);

u.getDriver().get(APP_URL);
Expand All @@ -160,19 +142,18 @@ protected BrowserUser setupBrowser(String browser, String testName,
}

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

if (user != null) {
log.info("##### Finish test: {} - Driver {}", TEST_NAME, this.user.getDriver());
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);
}

user.dispose();
}
}
Expand All @@ -192,28 +173,24 @@ protected void quickLogin(BrowserUser user, String userEmail,
private void login(BrowserUser user, String userEmail, String userPass,
boolean slow) { //24 lines
user.setOnSession(true);
user.setClientData(userEmail.split("@")[0]);
log.info("Logging in user {} with mail '{}'", user.getClientData(), userEmail);
Wait.waitForPageLoaded(user.getDriver());

user.waitUntil(ExpectedConditions.elementToBeClickable(By.cssSelector("#download-button")), "The button searched by CSS #download-button is not clickable");
openDialog("#download-button", user);
Wait.waitForPageLoaded(user.getDriver());
user.waitUntil(ExpectedConditions.presenceOfElementLocated(By.id("email")), "The email field is not present");
// Find form elements (login modal is already opened)
WebElement userNameField = user.getDriver().findElement(By.id("email"));

user.waitUntil(ExpectedConditions.presenceOfElementLocated(By.id("password")), "The password field is not present");
WebElement userPassField = user.getDriver().findElement(By.id("password"));
// Fill input fields
userNameField.sendKeys(userEmail);
if (slow)
waitSeconds(3);

userPassField.sendKeys(userPass);

if (slow)
waitSeconds(3);

// Ensure fields contain what has been entered
Assertions.assertEquals(userNameField.getAttribute("value"), userEmail);
Assertions.assertEquals(userPassField.getAttribute("value"), userPass);
Expand All @@ -224,57 +201,41 @@ 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 instanceof NotLoggedException) {
log.error("The user {} is not logged in", user.getClientData());}
else {
log.error("The web element with the user data was 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"))
.click();

}
user.getWaiter().until(ExpectedConditions
.elementToBeClickable(By.cssSelector("#exit-icon")));
user.getWaiter().until(ExpectedConditions.elementToBeClickable(By.cssSelector("#exit-icon")));
user.getDriver().findElement(By.cssSelector("#exit-icon")).click();
}
try {
// Up bar menu

user.getWaiter()
.until(ExpectedConditions.elementToBeClickable(
By.cssSelector("#arrow-drop-down")));

user.getDriver().findElement(By.cssSelector("#arrow-drop-down"))
.click();

user.getWaiter().until(ExpectedConditions
.elementToBeClickable(By.cssSelector("#logout-button")));
user.getDriver().findElement(By.cssSelector("#logout-button"))
.click();
user.getWaiter().until(ExpectedConditions.elementToBeClickable(By.cssSelector("#arrow-drop-down")));
user.getDriver().findElement(By.cssSelector("#arrow-drop-down")).click();
user.getWaiter().until(ExpectedConditions.elementToBeClickable(By.cssSelector("#logout-button")));
user.getDriver().findElement(By.cssSelector("#logout-button")).click();
} catch (TimeoutException e) {
// Shrunk menu
user.getWaiter()
.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector("a.button-collapse")));
user.getDriver().findElement(By.cssSelector("a.button-collapse"))
.click();
user.getWaiter().until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a.button-collapse")));
user.getDriver().findElement(By.cssSelector("a.button-collapse")).click();

user.getWaiter().until(ExpectedConditions.elementToBeClickable(
By.xpath("//ul[@id='nav-mobile']//a[text() = 'Logout']")));
user.getDriver()
.findElement(By.xpath(
"//ul[@id='nav-mobile']//a[text() = 'Logout']"))
.click();
user.getDriver().findElement(By.xpath("//ul[@id='nav-mobile']//a[text() = 'Logout']")).click();
}
user.setOnSession(false);
log.info("Logging out successful for {}", user.getClientData());
Expand All @@ -298,9 +259,7 @@ protected void openDialog(String cssSelector, BrowserUser user) {
user.getClientData(), cssSelector);

Wait.waitForPageLoaded(user.getDriver());
user.waitUntil(
ExpectedConditions
.elementToBeClickable(By.cssSelector(cssSelector)),
user.waitUntil(ExpectedConditions.elementToBeClickable(By.cssSelector(cssSelector)),
"Button for opening the dialog not clickable");

user.getDriver().findElement(By.cssSelector(cssSelector)).click();
Expand All @@ -309,36 +268,26 @@ 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 by clicking CSS for user {}", user.getClientData());
}

protected void openDialog(WebElement el, BrowserUser user) {//8lines
log.info("User {} opening dialog by web element '{}'",
user.getClientData(), el);
user.waitUntil(ExpectedConditions.elementToBeClickable(el),
"Button for opening the dialog not clickable");
log.info("User {} opening dialog by web element '{}'", user.getClientData(), el);
user.waitUntil(ExpectedConditions.elementToBeClickable(el), "Button for opening the dialog not clickable");
el.click();
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());
user.waitUntil(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[contains(@class, 'modal-overlay') and contains(@style, 'opacity: 0.5')]")), "Dialog not opened");
log.info("Dialog opened by web element for user {}", user.getClientData());
}

protected void waitForDialogClosed(String dialogId, String errorMessage,
BrowserUser user) {//14 lines
log.info("User {} waiting for dialog with id '{}' to be closed",
user.getClientData(), dialogId);
user.waitUntil(ExpectedConditions
.presenceOfElementLocated(By.xpath("//div[@id='" + dialogId
+ "' and contains(@class, 'my-modal-class') and contains(@style, 'opacity: 0') and contains(@style, 'display: none')]")),
"Dialog not closed. Reason: " + errorMessage);
user.waitUntil(
ExpectedConditions.invisibilityOfElementLocated(
By.cssSelector(".modal.my-modal-class.open")),
user.waitUntil(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@id='" + dialogId
+ "' and contains(@class, 'my-modal-class') and contains(@style, 'opacity: 0') and contains(@style, 'display: none')]")), "Dialog not closed. Reason: " + errorMessage);
user.waitUntil(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".modal.my-modal-class.open")),
"Dialog not closed. Reason: " + errorMessage);
user.waitUntil(
ExpectedConditions.numberOfElementsToBe(
By.cssSelector(".modal-overlay"), 0),
user.waitUntil(ExpectedConditions.numberOfElementsToBe(By.cssSelector(".modal-overlay"), 0),
"Dialog not closed. Reason: " + errorMessage);
log.info("Dialog closed for user {}", user.getClientData());
}
Expand All @@ -347,16 +296,14 @@ protected void waitSeconds(int seconds) {
try {
Thread.sleep(1000L * seconds);
} catch (InterruptedException e) {
e.printStackTrace();
log.error("The waitSeconds was interrupted");
}

}

public String getUserName(BrowserUser user, boolean goBack, String host) throws NotLoggedException, ElementNotFoundException {
log.info("[INI]getUserName");
//Wait to settings button to be present
try {

Wait.notTooMuch(user.getDriver()).until(ExpectedConditions.visibilityOfElementLocated(SETTINGS_BUTTON));
WebElement settings_button = Wait.notTooMuch(user.getDriver()).until(ExpectedConditions.elementToBeClickable(SETTINGS_BUTTON));

Expand All @@ -372,16 +319,13 @@ 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 userUIName = name_placeholder.getText().trim();

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

return userUIName;
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,17 @@

import java.time.Duration;

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

public class BrowserUser {

public static final Logger log = LoggerFactory.getLogger(BrowserUser.class);
protected final String clientData;
protected String clientData;
protected final int timeOfWaitInSeconds;
protected WebDriver driver;
protected boolean isOnSession;
protected WebDriverWait waiter;

public BrowserUser(String clientData, int timeOfWaitInSeconds) {
this.clientData = clientData;
public BrowserUser( int timeOfWaitInSeconds) {
this.timeOfWaitInSeconds = timeOfWaitInSeconds;
this.isOnSession = false;
}
Expand All @@ -48,14 +45,12 @@ public WebDriver getDriver() {
return this.driver;
}


public WebDriverWait getWaiter() {
return this.waiter;
}

public void waitUntil(ExpectedCondition<?> condition, String errorMessage) {
try {

this.waiter.until(condition);
} catch (org.openqa.selenium.TimeoutException timeout) {
log.error(errorMessage);
Expand All @@ -66,7 +61,7 @@ public void waitUntil(ExpectedCondition<?> condition, String errorMessage) {
public String getClientData() {
return this.clientData;
}

public void setClientData(String clientData) {this.clientData = clientData;}
protected void configureDriver() {
this.waiter = new WebDriverWait(this.driver, Duration.ofSeconds(this.timeOfWaitInSeconds));
}
Expand Down
Loading

0 comments on commit fea767b

Please sign in to comment.