Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.crystals.settester.test;
- import io.qameta.allure.Attachment;
- import org.apache.commons.io.FileUtils;
- import org.openqa.selenium.OutputType;
- import org.openqa.selenium.TakesScreenshot;
- import org.openqa.selenium.WebDriver;
- 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.UnreachableBrowserException;
- import org.testng.IExecutionListener;
- import org.testng.ITestContext;
- import org.testng.ITestResult;
- import org.testng.Reporter;
- import org.testng.annotations.AfterClass;
- import org.testng.annotations.AfterMethod;
- import org.testng.annotations.BeforeClass;
- import org.testng.annotations.Listeners;
- import ru.crystals.settester.config.BrowserDriver;
- import ru.crystals.settester.config.FlashPlugin;
- import ru.crystals.settester.tools.AllureLogger;
- import ru.crystals.settester.utils.DisinsectorTools;
- import ru.crystals.testingtools.config.impl.Config;
- import java.io.File;
- import java.io.IOException;
- import java.lang.reflect.Method;
- import java.util.Collections;
- import java.util.Map;
- import java.util.concurrent.TimeUnit;
- @Listeners(ru.crystals.settester.test.AbstractBrowserTest.class)
- public class AbstractBrowserTest extends AbstractTest implements IExecutionListener {
- protected static final AllureLogger log = new AllureLogger(AbstractBrowserTest.class);
- protected static String downloadPath = null;
- private WebDriver driver;
- private static final int IMPLICIT_WAIT = 15; //sec
- private static GeckoDriverService service;
- private static boolean firstRun = true;
- // Запущен ли драйвер сервис
- private static boolean serviceStatus = false;
- public WebDriver getDriver() {
- return driver;
- }
- @BeforeClass(alwaysRun = true)
- public void setupWebDriver(ITestContext context) {
- driver = createDriver();
- driver.manage().timeouts().implicitlyWait(IMPLICIT_WAIT, TimeUnit.SECONDS);
- driver.manage().window().maximize();
- driver.manage().deleteAllCookies();
- if (firstRun) {
- downloadPath = getDownloadPath();
- clearDownloadDir();
- }
- }
- private WebDriver createDriver() {
- int retryAttempt = 0;
- int retryCount = 10;
- DesiredCapabilities capabilities = DesiredCapabilities.firefox();
- 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);
- capabilities.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options);
- while (retryAttempt <= retryCount) {
- try {
- retryAttempt++;
- driver = new RemoteWebDriver(service.getUrl(), capabilities);
- return driver;
- } catch (UnreachableBrowserException e) {
- try {
- Thread.sleep(10000);
- } catch (InterruptedException e1) {
- e1.printStackTrace();
- }
- if (retryAttempt > retryCount) {
- log.error("Remote Web Driver cannot be reached at this moment");
- }
- }
- }
- return null;
- }
- @AfterClass(alwaysRun = true)
- public void close(ITestContext contx) {
- driver.quit();
- }
- @Attachment(value = "Screen when test fails", type = "image/png")
- public byte[] saveScreenshot(WebDriver driver) {
- return ((TakesScreenshot) driver).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";
- saveScreenshot(augmentedDriver);
- 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> ");
- }
- super.printTestResult(method, result);
- }
- private String getDownloadPath() {
- if (downloadPath == null) {
- setDownloadPath();
- }
- return downloadPath;
- }
- private void setDownloadPath() {
- 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();
- }
- }
- /*
- * Удаление всех возможных старых файлов отчетов
- */
- private void clearDownloadDir() {
- firstRun = false;
- DisinsectorTools.removeOldReport(getDownloadPath(), "*.xls");
- DisinsectorTools.removeOldReport(getDownloadPath(), "*.pdf");
- DisinsectorTools.removeOldReport(getDownloadPath(), "*.xlsx");
- }
- public synchronized void onExecutionStart() {
- if (!serviceStatus) {
- try {
- Map<String,String> environment = Collections.singletonMap("MOZ_PLUGIN_PATH", new FlashPlugin().getFile().getAbsoluteFile().getParent());
- service = new GeckoDriverService.Builder()
- .usingDriverExecutable(new BrowserDriver().getDriver())
- .usingAnyFreePort()
- .withEnvironment(environment)
- .withLogFile(new File("geckodriver.log"))
- .build();
- log.info("Старт сервиса управления драйвером...");
- service.start();
- serviceStatus = true;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- @Override
- public synchronized void onExecutionFinish() {
- if (service.isRunning()) {
- Runtime.getRuntime().addShutdownHook(new Thread() {
- @Override
- public synchronized void run() {
- if (service.isRunning()) {
- service.stop();
- }
- }
- });
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement