Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.crystals.settester;
- import com.codeborne.selenide.WebDriverRunner;
- import io.qameta.allure.Attachment;
- import org.apache.commons.io.FileUtils;
- import org.hamcrest.Matchers;
- import org.openqa.selenium.*;
- import org.openqa.selenium.chrome.ChromeDriverService;
- import org.openqa.selenium.chrome.ChromeOptions;
- import org.openqa.selenium.firefox.*;
- import org.openqa.selenium.remote.Augmenter;
- import org.openqa.selenium.remote.DesiredCapabilities;
- import org.openqa.selenium.remote.RemoteWebDriver;
- import org.openqa.selenium.remote.service.DriverService;
- import org.openqa.selenium.support.ui.WebDriverWait;
- import org.testng.ITestResult;
- import org.testng.Reporter;
- import org.testng.annotations.AfterMethod;
- import ru.crystals.settester.config.BrowserDriver;
- import ru.crystals.settester.config.FlashPlugin;
- import ru.crystals.testingtools.config.impl.Config;
- import ru.crystals.settester.tools.AllureLogger;
- import ru.crystals.testingtools.matchers.Getter;
- import ru.crystals.settester.matchers.Wait;
- import ru.crystals.settester.pages.cucumber.basic.LoginPage;
- import ru.crystals.settester.pages.cucumber.basic.MainPage;
- import ru.crystals.settester.pages.testng.basic.PageNotOpenedException;
- import ru.crystals.settester.pages.cucumber.basic.PageObject;
- import java.io.File;
- import java.io.IOException;
- import java.lang.reflect.Method;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.util.Collections;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.concurrent.TimeUnit;
- import static java.lang.String.format;
- /**
- * Объектное представление web-браузера.
- * <p/>
- * На данный момент реализация рассчитана только на GoogleChrome.
- * <p/>
- * <i>Все, что касается взаимодействия с браузером, должно быть описано здесь</i>
- *
- * @author Vladimir Popov <v.popov@crystals.ru>
- */
- public class Browser {
- protected static final AllureLogger log = new AllureLogger(Browser.class);
- /**
- * Время ожидания контейнера с swf на странице
- */
- private static final long DRIVER_WAIT_TIMEOUT = Config.GUI_TESTS_TIMEOUT;
- private static final int IMPLICIT_WAIT = 15; //sec
- private final DesiredCapabilities capabilities;
- private final GeckoDriverService driverService;
- private String downloadPath = null;
- // Драйвер всегда должен быть скрыт. Не надо делать его торчащим наружу!
- private WebDriver driver;
- private WebDriverWait driverWait;
- /**
- * Возвращает текущий открытый в брайзере url.
- */
- public URL getCurrentUrl() {
- try {
- return new URL(driver.getCurrentUrl());
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * Очищает кеш браузера, создает новый инстанс {@link LoginPage} и открывает {@link LoginPage#getUrlPath() соответствующий url}.
- *
- * @return новый экземпляр {@link LoginPage}
- */
- public LoginPage openLoginPage() {
- try {
- clearCache();
- return openPage(LoginPage.class);
- } catch (MalformedURLException e) {
- throw new PageNotOpenedException(e);
- }
- }
- /**
- * Очищает кеш браузера, создает новый инстанс {@link MainPage} и открывает {@link MainPage#getUrlPath() соответствующий url}.
- *
- * @return новый экземпляр {@link MainPage}
- */
- public MainPage openMainPage() {
- try {
- return openPage(MainPage.class);
- } catch (MalformedURLException e) {
- throw new PageNotOpenedException(e);
- }
- }
- /**
- * Проверяет, что в данный момент открыта именно ожидаемая страница.
- */
- public boolean isOpenedPage(Class<? extends PageObject> pageClass) {
- PageObject page = PageObject.createPageInstance(pageClass, driver);
- return page.isOpened();
- }
- /**
- * Запускает сервис Selenium, открывает браузер (запускает процесс в системе) и, если url не null, открывает страницу с указанным адресом.<br/>
- * <i>Перед открытием страницы (вне зависимости передан url или нет) очищает cookies браузера!</i>
- *
- * @param url адрес, который будет открыт в браузере после запуска.
- */
- public void run(URL url) throws OpenBrowserException {
- if (!driverService.isRunning()) {
- // При закрытии jvm закроем и браузер
- Runtime.getRuntime().addShutdownHook(new Thread() {
- @Override
- public synchronized void run() {
- if (Browser.this.driverService.isRunning()) {
- Browser.this.driverService.stop();
- }
- }
- });
- try {
- driverService.start();
- } catch (IOException e) {
- throw new OpenBrowserException("Exception on start driver service", e);
- }
- }
- // инициализируем драйвер
- driver = new RemoteWebDriver(driverService.getUrl(), capabilities);
- driver.manage().timeouts().implicitlyWait(IMPLICIT_WAIT, TimeUnit.SECONDS);
- driver.manage().window().maximize();
- driverWait = new WebDriverWait(driver, DRIVER_WAIT_TIMEOUT);
- clearCache();
- // открываем сразу указанный url
- if (url != null) {
- driver.get(url.toString());
- log.info("Opened url " + url.toString());
- }
- setSelenideOptions();
- }
- /**
- * Очищает кеш браузера.
- */
- public void clearCache() {
- driver.manage().deleteAllCookies();
- }
- /**
- * Закрывает браузер
- */
- public void close() {
- driver.quit();
- }
- /**
- * Обновить страницу браузера
- */
- public <T extends PageObject> T refreshBrowser(Class<T> pageClass) throws MalformedURLException {
- driver.navigate().refresh();
- return openPage(pageClass);
- }
- /**
- * Проверяет запущен ли браузер.
- *
- * @return true если браузер запущен.
- */
- public boolean isRun() {
- // http://stackoverflow.com/questions/27616470/webdriver-how-to-check-if-browser-still-exists-or-still-open
- return driver != null && !driver.toString().contains("null") && driverService.isRunning();
- }
- /**
- * Создает экземпляр объекта, представляющего собой браузер.
- */
- public Browser() {
- Map<String,String> environment = Collections.singletonMap("MOZ_PLUGIN_PATH", new FlashPlugin().getFile().getAbsoluteFile().getParent());
- String mimeTypes = "application/vnd.ms-excel,text/xml,application/x-excel,application/x-msexcel,application/xhtml+xml,application/octet-stream,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/pdf";
- FirefoxProfile profile = new FirefoxProfile();
- profile.setPreference("dom.ipc.plugins.enabled.libpepflashplayer.so", "true");
- profile.setPreference("plugin.state.flash", 2);
- profile.setPreference("browser.download.folderList",2);
- profile.setPreference("browser.download.dir", getDownloadPath());
- profile.setPreference("browser.download.useDownloadDir", true);
- profile.setPreference("browser.helperApps.neverAsk.saveToDisk", mimeTypes);
- profile.setPreference("browser.download.manager.showWhenStarting", false);
- profile.setPreference("pdfjs.disabled", true);
- /*
- FirefoxBinary firefoxBinary = new FirefoxBinary();
- //firefoxBinary.addCommandLineOptions("--headless");
- firefoxBinary.addCommandLineOptions();
- */
- FirefoxOptions options = new FirefoxOptions();
- // options.setBinary(firefoxBinary);
- options.setCapability(FirefoxDriver.PROFILE, profile);
- options.setLogLevel(FirefoxDriverLogLevel.ERROR);
- driverService = new GeckoDriverService.Builder()
- .usingDriverExecutable(new BrowserDriver().getDriver())
- .usingAnyFreePort()
- .withEnvironment(environment)
- .withLogFile(new File("geckodriver.log"))
- .build();
- capabilities = DesiredCapabilities.firefox();
- capabilities.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options);
- }
- private void setSelenideOptions() {
- if (driver != null) {
- WebDriverRunner.setWebDriver(driver);
- }
- }
- /**
- * Создает новый {@link PageObject объект страницы} и выполняет в браузере переход по соответствующему странице
- * {@link PageObject#getUrlPath() адресу}.
- *
- * @param pageClass класс открываемой страницы.
- * @param <T> тип открываемой страницы
- * @return новый экземпляр страницы.
- * @throws MalformedURLException при генерировании url страницы отностильно текущего хоста.
- */
- private <T extends PageObject> T openPage(Class<T> pageClass) throws MalformedURLException {
- if (!isRun()) {
- throw new IllegalStateException("Browser is not run");
- }
- final T page = PageObject.createPageInstance(pageClass, driver);
- URL url = new URL(getCurrentUrl(), page.getUrlPath());
- driver.get(url.toString());
- checkThatSWFIsReady(page);
- final Boolean pageIsOpened = Wait.wait((Getter<Boolean>) () -> page.isOpened(), Matchers.is(true));
- if (!pageIsOpened) {
- throw new PageNotOpenedException(format("Page %s is not opened in browser. Current url is %s, expected url path %s",
- page, driver.getCurrentUrl(), page.getUrlPath()));
- }
- return page;
- }
- private void checkThatSWFIsReady(PageObject page) throws PageNotOpenedException {
- try {
- driverWait.until(driver -> !driver.findElements(By.id("isSWFReady")).isEmpty());
- } catch (TimeoutException e) {
- throw new PageNotOpenedException(format("Time for waiting page [%s] expired", page));
- }
- }
- /**
- * Делает снимок экрана в байтовом представлении.
- *
- * @return массив байтов, представляющих собой скриншот.
- *
- */
- @Attachment(value = "Screen when test fails", type = "image/png")
- public byte[] takeScreenshot() {
- WebDriver augmentedDriver = new Augmenter().augment(driver);
- return ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.BYTES);
- }
- @AfterMethod(alwaysRun = true)
- public void printTestResult(Method method, ITestResult result) throws Exception {
- if (result.getStatus() == ITestResult.FAILURE) {
- System.setProperty("org.uncommons.reportng.escape-output", "false");
- WebDriver augmentedDriver = new Augmenter().augment(driver);
- File scrFile = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
- String filePatch = "screenshots/" + System.currentTimeMillis() + ".png";
- takeScreenshot();
- FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + Config.REPORT_FOLDER + filePatch));
- String screenshot = "<table><tr><td><font style=\"text-decoration: underline;\" size=\"3\" color=\"red\"><b>"
- + method.getDeclaringClass() + "." + method.getName() + " finished with ERROR</b></font></td></tr> ";
- Reporter.log(screenshot);
- Reporter.log("<tr><td><a href=\""+ filePatch +"\"><img src=\"" + filePatch + "\" alt=\"\""+ "height='120' width='120'/></td></tr> ");
- }
- }
- public String getDownloadPath() {
- if (downloadPath == null) {
- File downloadDir = new File(String.format("%s/testing_reports", System.getProperty("user.home")));
- if (!downloadDir.exists()) {
- if (downloadDir.mkdir()) {
- downloadPath = downloadDir.getAbsolutePath();
- } else {
- log.info("Не удалось создать каталог: " + downloadDir.getAbsolutePath());
- }
- } else {
- downloadPath = downloadDir.getAbsolutePath();
- }
- }
- return downloadPath;
- }
- public WebDriver getDriver() {
- return driver;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement