Advertisement
Guest User

Untitled

a guest
Dec 14th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.16 KB | None | 0 0
  1. package ru.crystals.settester;
  2.  
  3. import com.codeborne.selenide.WebDriverRunner;
  4. import io.qameta.allure.Attachment;
  5. import org.apache.commons.io.FileUtils;
  6. import org.hamcrest.Matchers;
  7. import org.openqa.selenium.*;
  8. import org.openqa.selenium.chrome.ChromeDriverService;
  9. import org.openqa.selenium.chrome.ChromeOptions;
  10. import org.openqa.selenium.firefox.*;
  11. import org.openqa.selenium.remote.Augmenter;
  12. import org.openqa.selenium.remote.DesiredCapabilities;
  13. import org.openqa.selenium.remote.RemoteWebDriver;
  14. import org.openqa.selenium.remote.service.DriverService;
  15. import org.openqa.selenium.support.ui.WebDriverWait;
  16. import org.testng.ITestResult;
  17. import org.testng.Reporter;
  18. import org.testng.annotations.AfterMethod;
  19.  
  20. import ru.crystals.settester.config.BrowserDriver;
  21. import ru.crystals.settester.config.FlashPlugin;
  22. import ru.crystals.testingtools.config.impl.Config;
  23. import ru.crystals.settester.tools.AllureLogger;
  24. import ru.crystals.testingtools.matchers.Getter;
  25. import ru.crystals.settester.matchers.Wait;
  26. import ru.crystals.settester.pages.cucumber.basic.LoginPage;
  27. import ru.crystals.settester.pages.cucumber.basic.MainPage;
  28. import ru.crystals.settester.pages.testng.basic.PageNotOpenedException;
  29. import ru.crystals.settester.pages.cucumber.basic.PageObject;
  30.  
  31. import java.io.File;
  32. import java.io.IOException;
  33. import java.lang.reflect.Method;
  34. import java.net.MalformedURLException;
  35. import java.net.URL;
  36. import java.util.Collections;
  37. import java.util.HashMap;
  38. import java.util.Map;
  39. import java.util.concurrent.TimeUnit;
  40.  
  41. import static java.lang.String.format;
  42.  
  43. /**
  44. * Объектное представление web-браузера.
  45. * <p/>
  46. * На данный момент реализация рассчитана только на GoogleChrome.
  47. * <p/>
  48. * <i>Все, что касается взаимодействия с браузером, должно быть описано здесь</i>
  49. *
  50. * @author Vladimir Popov &lt;v.popov@crystals.ru&gt;
  51. */
  52.  
  53. public class Browser {
  54.  
  55. protected static final AllureLogger log = new AllureLogger(Browser.class);
  56.  
  57. /**
  58. * Время ожидания контейнера с swf на странице
  59. */
  60. private static final long DRIVER_WAIT_TIMEOUT = Config.GUI_TESTS_TIMEOUT;
  61. private static final int IMPLICIT_WAIT = 15; //sec
  62.  
  63. private final DesiredCapabilities capabilities;
  64. private final GeckoDriverService driverService;
  65.  
  66. private String downloadPath = null;
  67.  
  68. // Драйвер всегда должен быть скрыт. Не надо делать его торчащим наружу!
  69. private WebDriver driver;
  70. private WebDriverWait driverWait;
  71.  
  72. /**
  73. * Возвращает текущий открытый в брайзере url.
  74. */
  75. public URL getCurrentUrl() {
  76. try {
  77. return new URL(driver.getCurrentUrl());
  78. } catch (MalformedURLException e) {
  79. throw new RuntimeException(e);
  80. }
  81. }
  82.  
  83. /**
  84. * Очищает кеш браузера, создает новый инстанс {@link LoginPage} и открывает {@link LoginPage#getUrlPath() соответствующий url}.
  85. *
  86. * @return новый экземпляр {@link LoginPage}
  87. */
  88. public LoginPage openLoginPage() {
  89. try {
  90. clearCache();
  91. return openPage(LoginPage.class);
  92. } catch (MalformedURLException e) {
  93. throw new PageNotOpenedException(e);
  94. }
  95. }
  96.  
  97. /**
  98. * Очищает кеш браузера, создает новый инстанс {@link MainPage} и открывает {@link MainPage#getUrlPath() соответствующий url}.
  99. *
  100. * @return новый экземпляр {@link MainPage}
  101. */
  102. public MainPage openMainPage() {
  103. try {
  104. return openPage(MainPage.class);
  105. } catch (MalformedURLException e) {
  106. throw new PageNotOpenedException(e);
  107. }
  108. }
  109.  
  110. /**
  111. * Проверяет, что в данный момент открыта именно ожидаемая страница.
  112. */
  113. public boolean isOpenedPage(Class<? extends PageObject> pageClass) {
  114. PageObject page = PageObject.createPageInstance(pageClass, driver);
  115. return page.isOpened();
  116. }
  117.  
  118. /**
  119. * Запускает сервис Selenium, открывает браузер (запускает процесс в системе) и, если url не null, открывает страницу с указанным адресом.<br/>
  120. * <i>Перед открытием страницы (вне зависимости передан url или нет) очищает cookies браузера!</i>
  121. *
  122. * @param url адрес, который будет открыт в браузере после запуска.
  123. */
  124. public void run(URL url) throws OpenBrowserException {
  125. if (!driverService.isRunning()) {
  126. // При закрытии jvm закроем и браузер
  127. Runtime.getRuntime().addShutdownHook(new Thread() {
  128. @Override
  129. public synchronized void run() {
  130. if (Browser.this.driverService.isRunning()) {
  131. Browser.this.driverService.stop();
  132. }
  133. }
  134. });
  135. try {
  136. driverService.start();
  137. } catch (IOException e) {
  138. throw new OpenBrowserException("Exception on start driver service", e);
  139. }
  140. }
  141. // инициализируем драйвер
  142. driver = new RemoteWebDriver(driverService.getUrl(), capabilities);
  143. driver.manage().timeouts().implicitlyWait(IMPLICIT_WAIT, TimeUnit.SECONDS);
  144. driver.manage().window().maximize();
  145. driverWait = new WebDriverWait(driver, DRIVER_WAIT_TIMEOUT);
  146. clearCache();
  147. // открываем сразу указанный url
  148. if (url != null) {
  149. driver.get(url.toString());
  150. log.info("Opened url " + url.toString());
  151. }
  152.  
  153. setSelenideOptions();
  154. }
  155.  
  156. /**
  157. * Очищает кеш браузера.
  158. */
  159. public void clearCache() {
  160. driver.manage().deleteAllCookies();
  161. }
  162.  
  163. /**
  164. * Закрывает браузер
  165. */
  166. public void close() {
  167. driver.quit();
  168. }
  169.  
  170. /**
  171. * Обновить страницу браузера
  172. */
  173. public <T extends PageObject> T refreshBrowser(Class<T> pageClass) throws MalformedURLException {
  174. driver.navigate().refresh();
  175. return openPage(pageClass);
  176. }
  177.  
  178. /**
  179. * Проверяет запущен ли браузер.
  180. *
  181. * @return true если браузер запущен.
  182. */
  183. public boolean isRun() {
  184. // http://stackoverflow.com/questions/27616470/webdriver-how-to-check-if-browser-still-exists-or-still-open
  185. return driver != null && !driver.toString().contains("null") && driverService.isRunning();
  186. }
  187.  
  188. /**
  189. * Создает экземпляр объекта, представляющего собой браузер.
  190. */
  191. public Browser() {
  192. Map<String,String> environment = Collections.singletonMap("MOZ_PLUGIN_PATH", new FlashPlugin().getFile().getAbsoluteFile().getParent());
  193.  
  194. 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";
  195.  
  196. FirefoxProfile profile = new FirefoxProfile();
  197. profile.setPreference("dom.ipc.plugins.enabled.libpepflashplayer.so", "true");
  198. profile.setPreference("plugin.state.flash", 2);
  199. profile.setPreference("browser.download.folderList",2);
  200. profile.setPreference("browser.download.dir", getDownloadPath());
  201. profile.setPreference("browser.download.useDownloadDir", true);
  202. profile.setPreference("browser.helperApps.neverAsk.saveToDisk", mimeTypes);
  203. profile.setPreference("browser.download.manager.showWhenStarting", false);
  204. profile.setPreference("pdfjs.disabled", true);
  205.  
  206. /*
  207. FirefoxBinary firefoxBinary = new FirefoxBinary();
  208. //firefoxBinary.addCommandLineOptions("--headless");
  209. firefoxBinary.addCommandLineOptions();
  210. */
  211.  
  212. FirefoxOptions options = new FirefoxOptions();
  213. // options.setBinary(firefoxBinary);
  214. options.setCapability(FirefoxDriver.PROFILE, profile);
  215. options.setLogLevel(FirefoxDriverLogLevel.ERROR);
  216.  
  217. driverService = new GeckoDriverService.Builder()
  218. .usingDriverExecutable(new BrowserDriver().getDriver())
  219. .usingAnyFreePort()
  220. .withEnvironment(environment)
  221. .withLogFile(new File("geckodriver.log"))
  222. .build();
  223.  
  224. capabilities = DesiredCapabilities.firefox();
  225.  
  226. capabilities.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options);
  227. }
  228.  
  229. private void setSelenideOptions() {
  230. if (driver != null) {
  231. WebDriverRunner.setWebDriver(driver);
  232. }
  233. }
  234.  
  235. /**
  236. * Создает новый {@link PageObject объект страницы} и выполняет в браузере переход по соответствующему странице
  237. * {@link PageObject#getUrlPath() адресу}.
  238. *
  239. * @param pageClass класс открываемой страницы.
  240. * @param <T> тип открываемой страницы
  241. * @return новый экземпляр страницы.
  242. * @throws MalformedURLException при генерировании url страницы отностильно текущего хоста.
  243. */
  244. private <T extends PageObject> T openPage(Class<T> pageClass) throws MalformedURLException {
  245. if (!isRun()) {
  246. throw new IllegalStateException("Browser is not run");
  247. }
  248. final T page = PageObject.createPageInstance(pageClass, driver);
  249. URL url = new URL(getCurrentUrl(), page.getUrlPath());
  250. driver.get(url.toString());
  251. checkThatSWFIsReady(page);
  252. final Boolean pageIsOpened = Wait.wait((Getter<Boolean>) () -> page.isOpened(), Matchers.is(true));
  253. if (!pageIsOpened) {
  254. throw new PageNotOpenedException(format("Page %s is not opened in browser. Current url is %s, expected url path %s",
  255. page, driver.getCurrentUrl(), page.getUrlPath()));
  256. }
  257. return page;
  258. }
  259.  
  260. private void checkThatSWFIsReady(PageObject page) throws PageNotOpenedException {
  261. try {
  262. driverWait.until(driver -> !driver.findElements(By.id("isSWFReady")).isEmpty());
  263. } catch (TimeoutException e) {
  264. throw new PageNotOpenedException(format("Time for waiting page [%s] expired", page));
  265. }
  266. }
  267.  
  268. /**
  269. * Делает снимок экрана в байтовом представлении.
  270. *
  271. * @return массив байтов, представляющих собой скриншот.
  272. *
  273. */
  274. @Attachment(value = "Screen when test fails", type = "image/png")
  275. public byte[] takeScreenshot() {
  276. WebDriver augmentedDriver = new Augmenter().augment(driver);
  277. return ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.BYTES);
  278. }
  279.  
  280. @AfterMethod(alwaysRun = true)
  281. public void printTestResult(Method method, ITestResult result) throws Exception {
  282. if (result.getStatus() == ITestResult.FAILURE) {
  283. System.setProperty("org.uncommons.reportng.escape-output", "false");
  284.  
  285. WebDriver augmentedDriver = new Augmenter().augment(driver);
  286. File scrFile = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
  287. String filePatch = "screenshots/" + System.currentTimeMillis() + ".png";
  288.  
  289. takeScreenshot();
  290.  
  291. FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + Config.REPORT_FOLDER + filePatch));
  292.  
  293. String screenshot = "<table><tr><td><font style=\"text-decoration: underline;\" size=\"3\" color=\"red\"><b>"
  294. + method.getDeclaringClass() + "." + method.getName() + " finished with ERROR</b></font></td></tr> ";
  295.  
  296. Reporter.log(screenshot);
  297. Reporter.log("<tr><td><a href=\""+ filePatch +"\"><img src=\"" + filePatch + "\" alt=\"\""+ "height='120' width='120'/></td></tr> ");
  298. }
  299. }
  300.  
  301. public String getDownloadPath() {
  302. if (downloadPath == null) {
  303. File downloadDir = new File(String.format("%s/testing_reports", System.getProperty("user.home")));
  304.  
  305. if (!downloadDir.exists()) {
  306. if (downloadDir.mkdir()) {
  307. downloadPath = downloadDir.getAbsolutePath();
  308. } else {
  309. log.info("Не удалось создать каталог: " + downloadDir.getAbsolutePath());
  310. }
  311. } else {
  312. downloadPath = downloadDir.getAbsolutePath();
  313. }
  314. }
  315. return downloadPath;
  316. }
  317.  
  318. public WebDriver getDriver() {
  319. return driver;
  320. }
  321. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement