Files
homework_1/src/main/java/ru/kovbasa/pages/MainPage.java

100 lines
3.4 KiB
Java

package ru.kovbasa.pages;
import com.google.inject.Inject;
import org.openqa.selenium.By;
import org.openqa.selenium.ElementClickInterceptedException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.WebDriverWait;
import ru.kovbasa.config.TestConfig;
import ru.kovbasa.driver.WebDriverProvider;
import ru.kovbasa.utils.PageUtils;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class MainPage {
private final WebDriver driver;
private final By menuLearningByTitle = By.cssSelector("span[title='Обучение']");
private final By menuLearningByText = By.xpath("//span[normalize-space()='Обучение']");
private final By categories = By.cssSelector("a[href*='/categories/']");
@Inject
public MainPage(WebDriverProvider provider) {
this.driver = provider.getDriver();
}
public MainPage open() {
driver.get(TestConfig.getBaseUrl());
return this;
}
public String clickRandomCategory() {
PageUtils.removeBottomBanner(driver);
final WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));
List<WebElement> els = findVisibleCategories(wait);
if (els.isEmpty()) {
clickLearningMenu(wait);
els = wait.until(drv -> {
final List<WebElement> found = drv.findElements(categories).stream()
.filter(WebElement::isDisplayed)
.toList();
return found.isEmpty() ? null : found;
});
}
final WebElement chosen = els.get(ThreadLocalRandom.current().nextInt(els.size()));
final String href = chosen.getAttribute("href");
System.out.println("Selected category href = " + href);
((JavascriptExecutor) driver)
.executeScript("arguments[0].scrollIntoView({block:'center'});", chosen);
try {
chosen.click();
} catch (ElementClickInterceptedException ignored) {
new Actions(driver).moveToElement(chosen).click().perform();
}
final String categorySlug = href.substring(href.lastIndexOf('/') + 1);
if (!driver.getCurrentUrl().contains(categorySlug)) {
driver.get(TestConfig.getBaseUrl() + "/catalog/courses?categories=" + categorySlug);
}
return href;
}
private List<WebElement> findVisibleCategories(WebDriverWait wait) {
return wait.until(drv -> drv.findElements(categories).stream()
.filter(WebElement::isDisplayed)
.toList());
}
private void clickLearningMenu(WebDriverWait wait) {
WebElement menu = null;
try {
menu = wait.until(drv -> drv.findElement(menuLearningByTitle));
} catch (NoSuchElementException ignored) {
} catch (org.openqa.selenium.TimeoutException ignored) {
}
if (menu == null) {
menu = wait.until(drv -> drv.findElement(menuLearningByText));
}
try {
menu.click();
} catch (ElementClickInterceptedException ignored) {
((JavascriptExecutor) driver).executeScript("arguments[0].click();", menu);
}
}
}