Advertisement
Guest User

Untitled

a guest
Dec 14th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.26 KB | None | 0 0
  1. package ru.crystals.settester.test;
  2.  
  3. import io.qameta.allure.Attachment;
  4. import org.apache.commons.io.FileUtils;
  5. import org.openqa.selenium.OutputType;
  6. import org.openqa.selenium.TakesScreenshot;
  7. import org.openqa.selenium.WebDriver;
  8. import org.openqa.selenium.firefox.*;
  9. import org.openqa.selenium.remote.Augmenter;
  10. import org.openqa.selenium.remote.DesiredCapabilities;
  11. import org.openqa.selenium.remote.RemoteWebDriver;
  12. import org.openqa.selenium.remote.UnreachableBrowserException;
  13. import org.testng.IExecutionListener;
  14. import org.testng.ITestContext;
  15. import org.testng.ITestResult;
  16. import org.testng.Reporter;
  17. import org.testng.annotations.AfterClass;
  18. import org.testng.annotations.AfterMethod;
  19. import org.testng.annotations.BeforeClass;
  20. import org.testng.annotations.Listeners;
  21. import ru.crystals.settester.config.BrowserDriver;
  22. import ru.crystals.settester.config.FlashPlugin;
  23. import ru.crystals.settester.tools.AllureLogger;
  24. import ru.crystals.settester.utils.DisinsectorTools;
  25. import ru.crystals.testingtools.config.impl.Config;
  26.  
  27. import java.io.File;
  28. import java.io.IOException;
  29. import java.lang.reflect.Method;
  30. import java.util.Collections;
  31. import java.util.Map;
  32. import java.util.concurrent.TimeUnit;
  33.  
  34.  
  35. @Listeners(ru.crystals.settester.test.AbstractBrowserTest.class)
  36. public class AbstractBrowserTest extends AbstractTest implements IExecutionListener {
  37.  
  38. protected static final AllureLogger log = new AllureLogger(AbstractBrowserTest.class);
  39.  
  40. protected static String downloadPath = null;
  41.  
  42. private WebDriver driver;
  43.  
  44. private static final int IMPLICIT_WAIT = 15; //sec
  45. private static GeckoDriverService service;
  46. private static boolean firstRun = true;
  47.  
  48. // Запущен ли драйвер сервис
  49. private static boolean serviceStatus = false;
  50.  
  51. public WebDriver getDriver() {
  52. return driver;
  53. }
  54.  
  55. @BeforeClass(alwaysRun = true)
  56. public void setupWebDriver(ITestContext context) {
  57.  
  58. driver = createDriver();
  59. driver.manage().timeouts().implicitlyWait(IMPLICIT_WAIT, TimeUnit.SECONDS);
  60. driver.manage().window().maximize();
  61. driver.manage().deleteAllCookies();
  62.  
  63. if (firstRun) {
  64. downloadPath = getDownloadPath();
  65. clearDownloadDir();
  66. }
  67. }
  68.  
  69. private WebDriver createDriver() {
  70. int retryAttempt = 0;
  71. int retryCount = 10;
  72. DesiredCapabilities capabilities = DesiredCapabilities.firefox();
  73.  
  74. 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";
  75.  
  76. FirefoxProfile profile = new FirefoxProfile();
  77. profile.setPreference("dom.ipc.plugins.enabled.libpepflashplayer.so", "true");
  78. profile.setPreference("plugin.state.flash", 2);
  79. profile.setPreference("browser.download.folderList",2);
  80. profile.setPreference("browser.download.dir", getDownloadPath());
  81. profile.setPreference("browser.download.useDownloadDir", true);
  82. profile.setPreference("browser.helperApps.neverAsk.saveToDisk", mimeTypes);
  83. profile.setPreference("browser.download.manager.showWhenStarting", false);
  84. profile.setPreference("pdfjs.disabled", true);
  85.  
  86. /*
  87. FirefoxBinary firefoxBinary = new FirefoxBinary();
  88. //firefoxBinary.addCommandLineOptions("--headless");
  89. firefoxBinary.addCommandLineOptions();
  90. */
  91.  
  92. FirefoxOptions options = new FirefoxOptions();
  93. // options.setBinary(firefoxBinary);
  94. options.setCapability(FirefoxDriver.PROFILE, profile);
  95. options.setLogLevel(FirefoxDriverLogLevel.ERROR);
  96.  
  97. capabilities.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options);
  98.  
  99. while (retryAttempt <= retryCount) {
  100. try {
  101. retryAttempt++;
  102. driver = new RemoteWebDriver(service.getUrl(), capabilities);
  103. return driver;
  104. } catch (UnreachableBrowserException e) {
  105. try {
  106. Thread.sleep(10000);
  107. } catch (InterruptedException e1) {
  108. e1.printStackTrace();
  109. }
  110. if (retryAttempt > retryCount) {
  111. log.error("Remote Web Driver cannot be reached at this moment");
  112. }
  113. }
  114. }
  115. return null;
  116. }
  117.  
  118. @AfterClass(alwaysRun = true)
  119. public void close(ITestContext contx) {
  120. driver.quit();
  121. }
  122.  
  123. @Attachment(value = "Screen when test fails", type = "image/png")
  124. public byte[] saveScreenshot(WebDriver driver) {
  125. return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
  126. }
  127.  
  128. @AfterMethod(alwaysRun = true)
  129. public void printTestResult(Method method, ITestResult result) throws Exception {
  130. if (result.getStatus() == ITestResult.FAILURE) {
  131. System.setProperty("org.uncommons.reportng.escape-output", "false");
  132.  
  133. WebDriver augmentedDriver = new Augmenter().augment(driver);
  134. File scrFile = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
  135. String filePatch = "screenshots/" + System.currentTimeMillis() + ".png";
  136.  
  137. saveScreenshot(augmentedDriver);
  138.  
  139. FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + Config.REPORT_FOLDER + filePatch));
  140.  
  141. String screenshot = "<table><tr><td><font style=\"text-decoration: underline;\" size=\"3\" color=\"red\"><b>"
  142. + method.getDeclaringClass() + "." + method.getName() + " finished with ERROR</b></font></td></tr> ";
  143.  
  144. Reporter.log(screenshot);
  145. Reporter.log("<tr><td><a href=\"" + filePatch + "\"><img src=\"" + filePatch + "\" alt=\"\"" + "height='120' width='120'/></td></tr> ");
  146. }
  147.  
  148. super.printTestResult(method, result);
  149. }
  150.  
  151.  
  152. private String getDownloadPath() {
  153. if (downloadPath == null) {
  154. setDownloadPath();
  155. }
  156. return downloadPath;
  157. }
  158.  
  159. private void setDownloadPath() {
  160. File downloadDir = new File(String.format("%s/testing_reports", System.getProperty("user.home")));
  161.  
  162. if (!downloadDir.exists()) {
  163. if (downloadDir.mkdir()) {
  164. downloadPath = downloadDir.getAbsolutePath();
  165. } else {
  166. log.info("Не удалось создать каталог: " + downloadDir.getAbsolutePath());
  167. }
  168. } else {
  169. downloadPath = downloadDir.getAbsolutePath();
  170. }
  171. }
  172.  
  173. /*
  174. * Удаление всех возможных старых файлов отчетов
  175. */
  176. private void clearDownloadDir() {
  177. firstRun = false;
  178. DisinsectorTools.removeOldReport(getDownloadPath(), "*.xls");
  179. DisinsectorTools.removeOldReport(getDownloadPath(), "*.pdf");
  180. DisinsectorTools.removeOldReport(getDownloadPath(), "*.xlsx");
  181. }
  182.  
  183. public synchronized void onExecutionStart() {
  184. if (!serviceStatus) {
  185. try {
  186. Map<String,String> environment = Collections.singletonMap("MOZ_PLUGIN_PATH", new FlashPlugin().getFile().getAbsoluteFile().getParent());
  187. service = new GeckoDriverService.Builder()
  188. .usingDriverExecutable(new BrowserDriver().getDriver())
  189. .usingAnyFreePort()
  190. .withEnvironment(environment)
  191. .withLogFile(new File("geckodriver.log"))
  192. .build();
  193. log.info("Старт сервиса управления драйвером...");
  194. service.start();
  195. serviceStatus = true;
  196. } catch (IOException e) {
  197. e.printStackTrace();
  198. }
  199. }
  200. }
  201.  
  202. @Override
  203. public synchronized void onExecutionFinish() {
  204. if (service.isRunning()) {
  205. Runtime.getRuntime().addShutdownHook(new Thread() {
  206. @Override
  207. public synchronized void run() {
  208. if (service.isRunning()) {
  209. service.stop();
  210. }
  211. }
  212. });
  213. }
  214. }
  215. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement