You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AbstractTB3Test.java 40KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. package com.vaadin.tests.tb3;
  2. import static org.junit.Assert.assertEquals;
  3. import static org.junit.Assert.assertFalse;
  4. import static org.junit.Assert.assertTrue;
  5. import static org.junit.Assert.fail;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.StringWriter;
  9. import java.lang.reflect.Field;
  10. import java.net.URL;
  11. import java.util.ArrayList;
  12. import java.util.Arrays;
  13. import java.util.Collections;
  14. import java.util.HashSet;
  15. import java.util.List;
  16. import java.util.Set;
  17. import java.util.logging.Level;
  18. import org.apache.commons.io.IOUtils;
  19. import org.apache.commons.lang3.StringUtils;
  20. import org.apache.http.HttpHost;
  21. import org.apache.http.HttpResponse;
  22. import org.apache.http.impl.client.DefaultHttpClient;
  23. import org.apache.http.message.BasicHttpEntityEnclosingRequest;
  24. import org.junit.Rule;
  25. import org.junit.rules.TestName;
  26. import org.junit.runner.Description;
  27. import org.junit.runner.RunWith;
  28. import org.openqa.selenium.By;
  29. import org.openqa.selenium.Dimension;
  30. import org.openqa.selenium.JavascriptExecutor;
  31. import org.openqa.selenium.NoSuchElementException;
  32. import org.openqa.selenium.WebDriver;
  33. import org.openqa.selenium.WebElement;
  34. import org.openqa.selenium.interactions.Actions;
  35. import org.openqa.selenium.interactions.HasInputDevices;
  36. import org.openqa.selenium.interactions.Keyboard;
  37. import org.openqa.selenium.interactions.Mouse;
  38. import org.openqa.selenium.interactions.internal.Coordinates;
  39. import org.openqa.selenium.internal.Locatable;
  40. import org.openqa.selenium.internal.WrapsElement;
  41. import org.openqa.selenium.remote.DesiredCapabilities;
  42. import org.openqa.selenium.remote.HttpCommandExecutor;
  43. import org.openqa.selenium.remote.RemoteWebDriver;
  44. import org.openqa.selenium.support.ui.ExpectedCondition;
  45. import org.openqa.selenium.support.ui.ExpectedConditions;
  46. import com.vaadin.server.LegacyApplication;
  47. import com.vaadin.server.UIProvider;
  48. import com.vaadin.testbench.ScreenshotOnFailureRule;
  49. import com.vaadin.testbench.TestBenchDriverProxy;
  50. import com.vaadin.testbench.TestBenchElement;
  51. import com.vaadin.testbench.annotations.BrowserConfiguration;
  52. import com.vaadin.testbench.elements.CheckBoxElement;
  53. import com.vaadin.testbench.elements.LabelElement;
  54. import com.vaadin.testbench.elements.TableElement;
  55. import com.vaadin.testbench.elements.VerticalLayoutElement;
  56. import com.vaadin.testbench.parallel.Browser;
  57. import com.vaadin.testbench.parallel.BrowserUtil;
  58. import com.vaadin.testbench.parallel.ParallelTest;
  59. import com.vaadin.ui.UI;
  60. import elemental.json.JsonObject;
  61. import elemental.json.impl.JsonUtil;
  62. /**
  63. * Base class for TestBench 3+ tests. All TB3+ tests in the project should
  64. * extend this class.
  65. *
  66. * Provides:
  67. * <ul>
  68. * <li>Helpers for browser selection</li>
  69. * <li>Hub connection setup and teardown</li>
  70. * <li>Automatic generation of URL for a given test on the development server
  71. * using {@link #getUIClass()} or by automatically finding an enclosing UI class
  72. * and based on requested features, e.g. {@link #isDebug()},
  73. * {@link #isPush()}</li>
  74. * <li>Generic helpers for creating TB3+ tests</li>
  75. * </ul>
  76. *
  77. * @author Vaadin Ltd
  78. */
  79. @RunWith(TB3Runner.class)
  80. public abstract class AbstractTB3Test extends ParallelTest {
  81. @Rule
  82. public TestName testName = new TestName();
  83. {
  84. // Override default screenshotOnFailureRule to close application
  85. screenshotOnFailure = new ScreenshotOnFailureRule(this, true) {
  86. @Override
  87. protected void finished(Description description) {
  88. closeApplication();
  89. super.finished(description);
  90. }
  91. };
  92. }
  93. /**
  94. * Height of the screenshots we want to capture
  95. */
  96. private static final int SCREENSHOT_HEIGHT = 850;
  97. /**
  98. * Width of the screenshots we want to capture
  99. */
  100. private static final int SCREENSHOT_WIDTH = 1500;
  101. /**
  102. * Timeout used by the TB grid
  103. */
  104. private static final int BROWSER_TIMEOUT_IN_MS = 30 * 1000;
  105. private boolean debug = false;
  106. private boolean push = false;
  107. static {
  108. com.vaadin.testbench.Parameters
  109. .setScreenshotComparisonCursorDetection(true);
  110. }
  111. /**
  112. * Connect to the hub using a remote web driver, set the canvas size and
  113. * opens the initial URL as specified by {@link #getTestUrl()}
  114. *
  115. * @throws Exception
  116. */
  117. @Override
  118. public void setup() throws Exception {
  119. super.setup();
  120. int w = SCREENSHOT_WIDTH;
  121. int h = SCREENSHOT_HEIGHT;
  122. try {
  123. testBench().resizeViewPortTo(w, h);
  124. } catch (UnsupportedOperationException e) {
  125. // Opera does not support this...
  126. }
  127. }
  128. /**
  129. * Method for closing the tested application.
  130. */
  131. protected void closeApplication() {
  132. if (getDriver() != null) {
  133. try {
  134. openTestURL("closeApplication");
  135. } catch (Exception e) {
  136. e.printStackTrace();
  137. }
  138. }
  139. }
  140. protected WebElement getTooltipErrorElement() {
  141. WebElement tooltip = getDriver()
  142. .findElement(com.vaadin.testbench.By.className("v-tooltip"));
  143. return tooltip.findElement(By.className("v-errormessage"));
  144. }
  145. protected WebElement getTooltipElement() {
  146. return getDriver().findElement(
  147. com.vaadin.testbench.By.className("v-tooltip-text"));
  148. }
  149. protected Coordinates getCoordinates(TestBenchElement element) {
  150. return ((Locatable) element.getWrappedElement()).getCoordinates();
  151. }
  152. private boolean hasDebugMessage(String message) {
  153. return getDebugMessage(message) != null;
  154. }
  155. private WebElement getDebugMessage(String message) {
  156. return driver.findElement(By.xpath(String.format(
  157. "//span[@class='v-debugwindow-message' and text()='%s']",
  158. message)));
  159. }
  160. protected void minimizeDebugWindow() {
  161. if (findElement(By.className("v-debugwindow-tabs")).isDisplayed()) {
  162. findElements(By.className("v-debugwindow-button")).stream()
  163. .filter(e -> e.getAttribute("title").equals("Minimize"))
  164. .findFirst().ifPresent(WebElement::click);
  165. }
  166. }
  167. protected void showDebugWindow() {
  168. if (!findElement(By.className("v-debugwindow-tabs")).isDisplayed()) {
  169. findElements(By.className("v-debugwindow-button")).stream()
  170. .filter(e -> e.getAttribute("title").equals("Minimize"))
  171. .findFirst().ifPresent(WebElement::click);
  172. }
  173. }
  174. protected void waitForDebugMessage(final String expectedMessage) {
  175. waitForDebugMessage(expectedMessage, 30);
  176. }
  177. protected void waitForDebugMessage(final String expectedMessage,
  178. int timeout) {
  179. waitUntil(input -> hasDebugMessage(expectedMessage), timeout);
  180. }
  181. protected void clearDebugMessages() {
  182. driver.findElement(By.xpath(
  183. "//button[@class='v-debugwindow-button' and @title='Clear log']"))
  184. .click();
  185. }
  186. protected void waitUntilRowIsVisible(final TableElement table,
  187. final int row) {
  188. waitUntil(input -> {
  189. try {
  190. return table.getCell(row, 0) != null;
  191. } catch (NoSuchElementException e) {
  192. return false;
  193. }
  194. });
  195. }
  196. protected void scrollTable(TableElement table, int rows, int rowToWait) {
  197. testBenchElement(table.findElement(By.className("v-scrollable")))
  198. .scroll(rows * 30);
  199. waitUntilRowIsVisible(table, rowToWait);
  200. }
  201. /**
  202. * Opens the given test (defined by {@link #getTestUrl()}, optionally with
  203. * debug window and/or push (depending on {@link #isDebug()} and
  204. * {@link #isPush()}.
  205. */
  206. protected void openTestURL() {
  207. openTestURL(new String[0]);
  208. }
  209. /**
  210. * Opens the given test (defined by {@link #getTestUrl()}, optionally with
  211. * debug window and/or push (depending on {@link #isDebug()} and
  212. * {@link #isPush()}.
  213. */
  214. protected void openTestURL(String... parameters) {
  215. openTestURL(getUIClass(), parameters);
  216. }
  217. /**
  218. * Opens the given test (defined by {@link #getTestUrl()}, optionally with
  219. * debug window and/or push (depending on {@link #isDebug()} and
  220. * {@link #isPush()}.
  221. */
  222. protected void openTestURL(Class<?> uiClass, String... parameters) {
  223. openTestURL(uiClass, new HashSet<>(Arrays.asList(parameters)));
  224. }
  225. private void openTestURL(Class<?> uiClass, Set<String> parameters) {
  226. String url = getTestURL(uiClass);
  227. if (isDebug()) {
  228. parameters.add("debug");
  229. }
  230. if (LegacyApplication.class.isAssignableFrom(uiClass)) {
  231. parameters.add("restartApplication");
  232. }
  233. if (!parameters.isEmpty()) {
  234. url += "?" + StringUtils.join(parameters, "&");
  235. }
  236. driver.get(url);
  237. }
  238. /**
  239. * Returns the full URL to be used for the test
  240. *
  241. * @return the full URL for the test
  242. */
  243. protected String getTestUrl() {
  244. return StringUtils.strip(getBaseURL(), "/") + getDeploymentPath();
  245. }
  246. /**
  247. * Returns the full URL to be used for the test for the provided UI class.
  248. *
  249. * @return the full URL for the test
  250. */
  251. protected String getTestURL(Class<?> uiClass) {
  252. return StringUtils.strip(getBaseURL(), "/")
  253. + getDeploymentPath(uiClass);
  254. }
  255. /**
  256. * Used to determine what URL to initially open for the test
  257. *
  258. * @return the host name of development server
  259. */
  260. protected abstract String getDeploymentHostname();
  261. /**
  262. * Used to determine what port the test is running on
  263. *
  264. * @return The port the test is running on, by default 8888
  265. */
  266. protected abstract int getDeploymentPort();
  267. /**
  268. * Produces a collection of browsers to run the test on. This method is
  269. * executed by the test runner when determining how many test methods to
  270. * invoke and with what parameters. For each returned value a test method is
  271. * ran and before running that,
  272. * {@link #setDesiredCapabilities(DesiredCapabilities)} is invoked with the
  273. * value returned by this method.
  274. *
  275. * This method is not static to allow overriding it in sub classes. By
  276. * default runs the test only on Firefox
  277. *
  278. * @return The browsers to run the test on
  279. */
  280. @BrowserConfiguration
  281. public List<DesiredCapabilities> getBrowsersToTest() {
  282. return Collections
  283. .singletonList(Browser.FIREFOX.getDesiredCapabilities());
  284. }
  285. /**
  286. * Finds an element based on the part of a TB2 style locator following the
  287. * :: (e.g. vaadin=runLabelModes::PID_Scheckboxaction-Enabled/domChild[0] ->
  288. * PID_Scheckboxaction-Enabled/domChild[0]).
  289. *
  290. * @param vaadinLocator
  291. * The part following :: of the vaadin locator string
  292. * @return
  293. */
  294. protected WebElement vaadinElement(String vaadinLocator) {
  295. return driver.findElement(vaadinLocator(vaadinLocator));
  296. }
  297. /**
  298. * Uses JavaScript to determine the currently focused element.
  299. *
  300. * @return Focused element or null
  301. */
  302. protected WebElement getFocusedElement() {
  303. Object focusedElement = executeScript("return document.activeElement");
  304. if (null != focusedElement) {
  305. return (WebElement) focusedElement;
  306. } else {
  307. return null;
  308. }
  309. }
  310. /**
  311. * Executes the given Javascript
  312. *
  313. * @param script
  314. * the script to execute
  315. * @return whatever
  316. * {@link org.openqa.selenium.JavascriptExecutor#executeScript(String, Object...)}
  317. * returns
  318. */
  319. protected Object executeScript(String script, Object... args) {
  320. return ((JavascriptExecutor) getDriver()).executeScript(script, args);
  321. }
  322. /**
  323. * Find a Vaadin element based on its id given using Component.setId
  324. *
  325. * @param id
  326. * The id to locate
  327. * @return
  328. */
  329. public WebElement vaadinElementById(String id) {
  330. return driver.findElement(By.id(id));
  331. }
  332. /**
  333. * Finds a {@link By} locator based on the part of a TB2 style locator
  334. * following the :: (e.g.
  335. * vaadin=runLabelModes::PID_Scheckboxaction-Enabled/domChild[0] ->
  336. * PID_Scheckboxaction-Enabled/domChild[0]).
  337. *
  338. * @param vaadinLocator
  339. * The part following :: of the vaadin locator string
  340. * @return
  341. */
  342. public org.openqa.selenium.By vaadinLocator(String vaadinLocator) {
  343. String base = getApplicationId(getDeploymentPath());
  344. base += "::";
  345. return com.vaadin.testbench.By.vaadin(base + vaadinLocator);
  346. }
  347. /**
  348. * Constructs a {@link By} locator for the id given using Component.setId
  349. *
  350. * @param id
  351. * The id to locate
  352. * @return a locator for the given id
  353. */
  354. public By vaadinLocatorById(String id) {
  355. return vaadinLocator("PID_S" + id);
  356. }
  357. /**
  358. * Waits up to 10s for the given condition to become false. Use e.g. as
  359. * {@link #waitUntilNot(ExpectedConditions.textToBePresentInElement(by,
  360. * text))}
  361. *
  362. * @param condition
  363. * the condition to wait for to become false
  364. */
  365. protected <T> void waitUntilNot(ExpectedCondition<T> condition) {
  366. waitUntilNot(condition, 10);
  367. }
  368. /**
  369. * Waits the given number of seconds for the given condition to become
  370. * false. Use e.g. as
  371. * {@link #waitUntilNot(ExpectedConditions.textToBePresentInElement(by,
  372. * text))}
  373. *
  374. * @param condition
  375. * the condition to wait for to become false
  376. */
  377. protected <T> void waitUntilNot(ExpectedCondition<T> condition,
  378. long timeoutInSeconds) {
  379. waitUntil(ExpectedConditions.not(condition), timeoutInSeconds);
  380. }
  381. protected void waitForElementPresent(final By by) {
  382. waitUntil(ExpectedConditions.presenceOfElementLocated(by));
  383. }
  384. protected void waitForElementNotPresent(final By by) {
  385. waitUntil(input -> input.findElements(by).isEmpty());
  386. }
  387. protected void waitForElementVisible(final By by) {
  388. waitUntil(ExpectedConditions.visibilityOfElementLocated(by));
  389. }
  390. /**
  391. * Checks if the given element has the given class name.
  392. *
  393. * Matches only full class names, i.e. has ("foo") does not match
  394. * class="foobar"
  395. *
  396. * @param element
  397. * @param className
  398. * @return
  399. */
  400. protected boolean hasCssClass(WebElement element, String className) {
  401. String classes = element.getAttribute("class");
  402. if (classes == null || classes.isEmpty()) {
  403. return (className == null || className.isEmpty());
  404. }
  405. for (String cls : classes.split(" ")) {
  406. if (className.equals(cls)) {
  407. return true;
  408. }
  409. }
  410. return false;
  411. }
  412. /**
  413. * For tests extending AbstractTestUIWithLog, returns the element for the
  414. * Nth log row
  415. *
  416. * @param rowNr
  417. * The log row to retrieve
  418. * @return the Nth log row
  419. */
  420. protected WebElement getLogRowElement(int rowNr) {
  421. return vaadinElementById("Log_row_" + rowNr);
  422. }
  423. /**
  424. * For tests extending AbstractTestUIWithLog, returns the text in the Nth
  425. * log row
  426. *
  427. * @param rowNr
  428. * The log row to retrieve text for
  429. * @return the text in the log row
  430. */
  431. protected String getLogRow(int rowNr) {
  432. return getLogRowElement(rowNr).getText();
  433. }
  434. /**
  435. * Asserts that {@literal a} is &gt;= {@literal b}
  436. *
  437. * @param message
  438. * The message to include in the {@link AssertionError}
  439. * @param a
  440. * @param b
  441. * @throws AssertionError
  442. * If comparison fails
  443. */
  444. public static final <T> void assertGreaterOrEqual(String message,
  445. Comparable<T> a, T b) throws AssertionError {
  446. if (a.compareTo(b) >= 0) {
  447. return;
  448. }
  449. throw new AssertionError(decorate(message, a, b));
  450. }
  451. /**
  452. * Asserts that {@literal a} is &gt; {@literal b}
  453. *
  454. * @param message
  455. * The message to include in the {@link AssertionError}
  456. * @param a
  457. * @param b
  458. * @throws AssertionError
  459. * If comparison fails
  460. */
  461. public static final <T> void assertGreater(String message, Comparable<T> a,
  462. T b) throws AssertionError {
  463. if (a.compareTo(b) > 0) {
  464. return;
  465. }
  466. throw new AssertionError(decorate(message, a, b));
  467. }
  468. /**
  469. * Asserts that {@literal a} is &lt;= {@literal b}
  470. *
  471. * @param message
  472. * The message to include in the {@link AssertionError}
  473. * @param a
  474. * @param b
  475. * @throws AssertionError
  476. * If comparison fails
  477. */
  478. public static final <T> void assertLessThanOrEqual(String message,
  479. Comparable<T> a, T b) throws AssertionError {
  480. if (a.compareTo(b) <= 0) {
  481. return;
  482. }
  483. throw new AssertionError(decorate(message, a, b));
  484. }
  485. /**
  486. * Asserts that {@literal a} is &lt; {@literal b}
  487. *
  488. * @param message
  489. * The message to include in the {@link AssertionError}
  490. * @param a
  491. * @param b
  492. * @throws AssertionError
  493. * If comparison fails
  494. */
  495. public static final <T> void assertLessThan(String message, Comparable<T> a,
  496. T b) throws AssertionError {
  497. if (a.compareTo(b) < 0) {
  498. return;
  499. }
  500. throw new AssertionError(decorate(message, a, b));
  501. }
  502. private static <T> String decorate(String message, Comparable<T> a, T b) {
  503. message = message.replace("{0}", a.toString());
  504. message = message.replace("{1}", b.toString());
  505. return message;
  506. }
  507. /**
  508. * Returns the path that should be used for the test. The path contains the
  509. * full path (appended to hostname+port) and must start with a slash.
  510. *
  511. * @param push
  512. * true if "?debug" should be added
  513. * @param debug
  514. * true if /run-push should be used instead of /run
  515. *
  516. * @return The URL path to the UI class to test
  517. */
  518. protected String getDeploymentPath() {
  519. Class<?> uiClass = getUIClass();
  520. if (uiClass != null) {
  521. return getDeploymentPath(uiClass);
  522. }
  523. throw new IllegalArgumentException("Unable to determine path for "
  524. + getClass().getCanonicalName());
  525. }
  526. /**
  527. * Returns the UI class the current test is connected to (or in special
  528. * cases UIProvider or LegacyApplication). Uses the enclosing class if the
  529. * test class is a static inner class to a UI class.
  530. *
  531. * Test which are not enclosed by a UI class must implement this method and
  532. * return the UI class they want to test.
  533. *
  534. * Note that this method will update the test name to the enclosing class to
  535. * be compatible with TB2 screenshot naming
  536. *
  537. * @return the UI class the current test is connected to
  538. */
  539. protected Class<?> getUIClass() {
  540. try {
  541. // Convention: SomeUITest uses the SomeUI UI class
  542. String uiClassName = getClass().getName().replaceFirst("Test$", "");
  543. Class<?> cls = Class.forName(uiClassName);
  544. if (isSupportedRunnerClass(cls)) {
  545. return cls;
  546. }
  547. } catch (Exception e) {
  548. }
  549. throw new RuntimeException(
  550. "Could not determine UI class. Ensure the test is named UIClassTest and is in the same package as the UIClass");
  551. }
  552. /**
  553. * @return true if the given class is supported by ApplicationServletRunner
  554. */
  555. @SuppressWarnings("deprecation")
  556. private boolean isSupportedRunnerClass(Class<?> cls) {
  557. if (UI.class.isAssignableFrom(cls)) {
  558. return true;
  559. }
  560. if (UIProvider.class.isAssignableFrom(cls)) {
  561. return true;
  562. }
  563. if (LegacyApplication.class.isAssignableFrom(cls)) {
  564. return true;
  565. }
  566. return false;
  567. }
  568. /**
  569. * Returns whether to run the test in debug mode (with the debug console
  570. * open) or not
  571. *
  572. * @return true to run with the debug window open, false by default
  573. */
  574. protected final boolean isDebug() {
  575. return debug;
  576. }
  577. /**
  578. * Sets whether to run the test in debug mode (with the debug console open)
  579. * or not.
  580. *
  581. * @param debug
  582. * true to open debug window, false otherwise
  583. */
  584. protected final void setDebug(boolean debug) {
  585. this.debug = debug;
  586. }
  587. /**
  588. * Returns whether to run the test with push enabled (using /run-push) or
  589. * not. Note that push tests can and should typically be created using @Push
  590. * on the UI instead of overriding this method
  591. *
  592. * @return true if /run-push is used, false otherwise
  593. */
  594. protected final boolean isPush() {
  595. return push;
  596. }
  597. /**
  598. * Sets whether to run the test with push enabled (using /run-push) or not.
  599. * Note that push tests can and should typically be created using @Push on
  600. * the UI instead of overriding this method
  601. *
  602. * @param push
  603. * true to use /run-push in the test, false otherwise
  604. */
  605. protected final void setPush(boolean push) {
  606. this.push = push;
  607. }
  608. /**
  609. * Returns the path for the given UI class when deployed on the test server.
  610. * The path contains the full path (appended to hostname+port) and must
  611. * start with a slash.
  612. *
  613. * This method takes into account {@link #isPush()} and {@link #isDebug()}
  614. * when the path is generated.
  615. *
  616. * @param uiClass
  617. * @param push
  618. * true if "?debug" should be added
  619. * @param debug
  620. * true if /run-push should be used instead of /run
  621. * @return The path to the given UI class
  622. */
  623. protected String getDeploymentPath(Class<?> uiClass) {
  624. String runPath = "/run";
  625. if (isPush()) {
  626. runPath = "/run-push";
  627. }
  628. if (UI.class.isAssignableFrom(uiClass)
  629. || UIProvider.class.isAssignableFrom(uiClass)
  630. || LegacyApplication.class.isAssignableFrom(uiClass)) {
  631. return runPath + "/" + uiClass.getCanonicalName();
  632. } else {
  633. throw new IllegalArgumentException(
  634. "Unable to determine path for enclosing class "
  635. + uiClass.getCanonicalName());
  636. }
  637. }
  638. /**
  639. * Used to determine what URL to initially open for the test
  640. *
  641. * @return The base URL for the test. Does not include a trailing slash.
  642. */
  643. protected String getBaseURL() {
  644. return "http://" + getDeploymentHostname() + ":" + getDeploymentPort();
  645. }
  646. /**
  647. * Generates the application id based on the URL in a way compatible with
  648. * VaadinServletService.
  649. *
  650. * @param pathWithQueryParameters
  651. * The path part of the URL, possibly still containing query
  652. * parameters
  653. * @return The application ID string used in Vaadin locators
  654. */
  655. private String getApplicationId(String pathWithQueryParameters) {
  656. // Remove any possible URL parameters
  657. String pathWithoutQueryParameters = pathWithQueryParameters
  658. .replaceAll("\\?.*", "");
  659. if (pathWithoutQueryParameters.isEmpty()) {
  660. return "ROOT";
  661. }
  662. // Retain only a-z and numbers
  663. return pathWithoutQueryParameters.replaceAll("[^a-zA-Z0-9]", "");
  664. }
  665. /**
  666. * Sleeps for the given number of ms but ensures that the browser connection
  667. * does not time out.
  668. *
  669. * @param timeoutMillis
  670. * Number of ms to wait
  671. */
  672. protected void sleep(int timeoutMillis) {
  673. while (timeoutMillis > 0) {
  674. int d = Math.min(BROWSER_TIMEOUT_IN_MS, timeoutMillis);
  675. try {
  676. Thread.sleep(d);
  677. } catch (InterruptedException e) {
  678. throw new RuntimeException(e);
  679. }
  680. timeoutMillis -= d;
  681. // Do something to keep the connection alive
  682. getDriver().getTitle();
  683. }
  684. }
  685. /**
  686. * Called by the test runner whenever there is an exception in the test that
  687. * will cause termination of the test
  688. *
  689. * @param t
  690. * the throwable which caused the termination
  691. */
  692. public void onUncaughtException(Throwable t) {
  693. // Do nothing by default
  694. }
  695. /**
  696. * Returns the mouse object for doing mouse commands
  697. *
  698. * @return Returns the mouse
  699. */
  700. public Mouse getMouse() {
  701. return ((HasInputDevices) getDriver()).getMouse();
  702. }
  703. /**
  704. * Returns the keyboard object for controlling keyboard events
  705. *
  706. * @return Return the keyboard
  707. */
  708. public Keyboard getKeyboard() {
  709. return ((HasInputDevices) getDriver()).getKeyboard();
  710. }
  711. public void hitButton(String id) {
  712. driver.findElement(By.id(id)).click();
  713. }
  714. protected void openDebugLogTab() {
  715. waitUntil(input -> {
  716. WebElement element = getDebugLogButton();
  717. return element != null;
  718. }, 15);
  719. getDebugLogButton().click();
  720. }
  721. private WebElement getDebugLogButton() {
  722. return findElement(By.xpath("//button[@title='Debug message log']"));
  723. }
  724. protected void assertNoDebugMessage(Level level) {
  725. // class="v-debugwindow-row Level.getName()"
  726. List<WebElement> logElements = driver.findElements(By.xpath(String
  727. .format("//div[@class='v-debugwindow-row %s']/span[@class='v-debugwindow-message']",
  728. level.getName())));
  729. if (!logElements.isEmpty()) {
  730. String logRows = "";
  731. for (WebElement e : logElements) {
  732. logRows += "\n" + e.getText();
  733. }
  734. fail("Found debug messages with level " + level.getName() + ": "
  735. + logRows);
  736. }
  737. }
  738. /**
  739. * Should the "require window focus" be enabled for Internet Explorer.
  740. * RequireWindowFocus makes tests more stable but seems to be broken with
  741. * certain commands such as sendKeys. Therefore it is not enabled by default
  742. * for all tests
  743. *
  744. * @return true, to use the "require window focus" feature, false otherwise
  745. */
  746. protected boolean requireWindowFocusForIE() {
  747. return false;
  748. }
  749. /**
  750. * Should the "enable persistent hover" be enabled for Internet Explorer.
  751. *
  752. * Persistent hovering causes continuous firing of mouse over events at the
  753. * last location the mouse cursor has been moved to. This is to avoid
  754. * problems where the real mouse cursor is inside the browser window and
  755. * Internet Explorer uses that location for some undefined operation
  756. * (http://
  757. * jimevansmusic.blogspot.fi/2012/06/whats-wrong-with-internet-explorer
  758. * .html)
  759. *
  760. * @return true, to use the "persistent hover" feature, false otherwise
  761. */
  762. protected boolean usePersistentHoverForIE() {
  763. return true;
  764. }
  765. /**
  766. * Should the "native events" be enabled for Internet Explorer.
  767. * <p>
  768. * Native events sometimes cause failure in clicking on buttons/checkboxes
  769. * but are possibly needed for some operations.
  770. *
  771. * @return true, to use "native events", false to use generated Javascript
  772. * events
  773. */
  774. protected boolean useNativeEventsForIE() {
  775. return true;
  776. }
  777. // FIXME: Remove this once TB4 getRemoteControlName works properly
  778. private RemoteWebDriver getRemoteDriver() {
  779. WebDriver d = getDriver();
  780. if (d instanceof TestBenchDriverProxy) {
  781. try {
  782. Field f = TestBenchDriverProxy.class
  783. .getDeclaredField("actualDriver");
  784. f.setAccessible(true);
  785. return (RemoteWebDriver) f.get(d);
  786. } catch (Exception e) {
  787. e.printStackTrace();
  788. }
  789. }
  790. if (d instanceof RemoteWebDriver) {
  791. return (RemoteWebDriver) d;
  792. }
  793. return null;
  794. }
  795. // FIXME: Remove this once TB4 getRemoteControlName works properly
  796. protected String getRemoteControlName() {
  797. try {
  798. RemoteWebDriver d = getRemoteDriver();
  799. if (d == null) {
  800. return null;
  801. }
  802. HttpCommandExecutor ce = (HttpCommandExecutor) d
  803. .getCommandExecutor();
  804. String hostName = ce.getAddressOfRemoteServer().getHost();
  805. int port = ce.getAddressOfRemoteServer().getPort();
  806. HttpHost host = new HttpHost(hostName, port);
  807. try (DefaultHttpClient client = new DefaultHttpClient()) {
  808. URL sessionURL = new URL("http://" + hostName + ":" + port
  809. + "/grid/api/testsession?session=" + d.getSessionId());
  810. BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(
  811. "POST", sessionURL.toExternalForm());
  812. HttpResponse response = client.execute(host, r);
  813. JsonObject object = extractObject(response);
  814. URL myURL = new URL(object.getString("proxyId"));
  815. if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
  816. return myURL.getHost();
  817. }
  818. }
  819. } catch (Exception e) {
  820. e.printStackTrace();
  821. }
  822. return null;
  823. }
  824. protected boolean logContainsText(String string) {
  825. List<String> logs = getLogs();
  826. for (String text : logs) {
  827. if (text.contains(string)) {
  828. return true;
  829. }
  830. }
  831. return false;
  832. }
  833. protected List<String> getLogs() {
  834. VerticalLayoutElement log = $(VerticalLayoutElement.class).id("Log");
  835. List<LabelElement> logLabels = log.$(LabelElement.class).all();
  836. List<String> logTexts = new ArrayList<>();
  837. for (LabelElement label : logLabels) {
  838. logTexts.add(label.getText());
  839. }
  840. return logTexts;
  841. }
  842. private static JsonObject extractObject(HttpResponse resp)
  843. throws IOException {
  844. InputStream contents = resp.getEntity().getContent();
  845. StringWriter writer = new StringWriter();
  846. IOUtils.copy(contents, writer, "UTF8");
  847. return JsonUtil.parse(writer.toString());
  848. }
  849. protected void click(CheckBoxElement checkbox) {
  850. WebElement cb = checkbox.findElement(By.xpath("input"));
  851. if (BrowserUtil.isChrome(getDesiredCapabilities())) {
  852. testBenchElement(cb).click(0, 0);
  853. } else if (BrowserUtil.isFirefox(getDesiredCapabilities())) {
  854. // Firefox workaround
  855. getCommandExecutor().executeScript("arguments[0].click()", cb);
  856. } else {
  857. cb.click();
  858. }
  859. }
  860. protected void clickElement(WebElement element) {
  861. if (BrowserUtil.isFirefox(getDesiredCapabilities())) {
  862. // Workaround for Selenium/TB and Firefox 45 issue
  863. ((TestBenchElement) (element)).clickHiddenElement();
  864. } else {
  865. element.click();
  866. }
  867. }
  868. protected void contextClickElement(WebElement element) {
  869. if (BrowserUtil.isFirefox(getDesiredCapabilities())) {
  870. // Workaround for Selenium/TB and Firefox 45 issue
  871. getCommandExecutor().executeScript(
  872. "var ev = document.createEvent('HTMLEvents'); ev.initEvent('contextmenu', true, false); arguments[0].dispatchEvent(ev);",
  873. element);
  874. } else {
  875. new Actions(getDriver()).contextClick(element).perform();
  876. }
  877. }
  878. protected boolean isLoadingIndicatorVisible() {
  879. WebElement loadingIndicator = findElement(
  880. By.className("v-loading-indicator"));
  881. return loadingIndicator.isDisplayed();
  882. }
  883. protected void waitUntilLoadingIndicatorVisible() {
  884. waitUntil(input -> isLoadingIndicatorVisible());
  885. }
  886. protected void waitUntilLoadingIndicatorNotVisible() {
  887. waitUntil(input -> !isLoadingIndicatorVisible());
  888. }
  889. /**
  890. * Selects a menu item. By default, this will click on the menu item.
  891. *
  892. * @param menuCaption
  893. * caption of the menu item
  894. */
  895. protected void selectMenu(String menuCaption) {
  896. selectMenu(menuCaption, true);
  897. }
  898. /**
  899. * Selects a menu item.
  900. *
  901. * @param menuCaption
  902. * caption of the menu item
  903. * @param click
  904. * <code>true</code> if should click the menu item;
  905. * <code>false</code> if not
  906. */
  907. protected void selectMenu(String menuCaption, boolean click) {
  908. WebElement menuElement = getMenuElement(menuCaption);
  909. Dimension size = menuElement.getSize();
  910. new Actions(getDriver())
  911. .moveToElement(menuElement, size.width - 10, size.height / 2)
  912. .perform();
  913. if (click) {
  914. new Actions(getDriver()).click().perform();
  915. }
  916. }
  917. /**
  918. * Finds the menu item from the DOM based on menu item caption.
  919. *
  920. * @param menuCaption
  921. * caption of the menu item
  922. * @return the found menu item
  923. * @throws NoSuchElementException
  924. * if menu item is not found
  925. */
  926. protected WebElement getMenuElement(String menuCaption)
  927. throws NoSuchElementException {
  928. // Need the parent span to obtain the correct size
  929. return getDriver().findElement(
  930. By.xpath("//span[text() = '" + menuCaption + "']/.."));
  931. }
  932. /**
  933. * Selects a submenu described by a path of menus from the first MenuBar in
  934. * the UI.
  935. *
  936. * @param menuCaptions
  937. * array of menu captions
  938. */
  939. protected void selectMenuPath(String... menuCaptions) {
  940. selectMenu(menuCaptions[0], true);
  941. // Move to the menu item opened below the menu bar.
  942. new Actions(getDriver())
  943. .moveByOffset(0,
  944. getMenuElement(menuCaptions[0]).getSize().getHeight())
  945. .perform();
  946. for (int i = 1; i < menuCaptions.length - 1; i++) {
  947. selectMenu(menuCaptions[i]);
  948. new Actions(getDriver()).moveByOffset(40, 0).build().perform();
  949. }
  950. selectMenu(menuCaptions[menuCaptions.length - 1], true);
  951. }
  952. /**
  953. * Asserts that an element is present
  954. *
  955. * @param by
  956. * the locator for the element
  957. */
  958. protected void assertElementPresent(By by) {
  959. assertTrue("Element is not present", isElementPresent(by));
  960. }
  961. /**
  962. * Asserts that an element is not present
  963. *
  964. * @param by
  965. * the locator for the element
  966. */
  967. protected void assertElementNotPresent(By by) {
  968. assertFalse("Element is present", isElementPresent(by));
  969. }
  970. /**
  971. * Asserts that no error notifications are shown. Requires the use of
  972. * "?debug" as exceptions are otherwise not shown as notifications.
  973. */
  974. protected void assertNoErrorNotifications() {
  975. assertFalse("Error notification with client side exception is shown",
  976. isNotificationPresent("error"));
  977. }
  978. /**
  979. * Asserts that no system notifications are shown.
  980. */
  981. protected void assertNoSystemNotifications() {
  982. assertFalse("Error notification with system error exception is shown",
  983. isNotificationPresent("system"));
  984. }
  985. /**
  986. * Asserts that a system notification is shown.
  987. */
  988. protected void assertSystemNotification() {
  989. assertTrue(
  990. "Error notification with system error exception is not shown",
  991. isNotificationPresent("system"));
  992. }
  993. private boolean isNotificationPresent(String type) {
  994. if ("error".equals(type)) {
  995. assertTrue(
  996. "Debug window must be open to be able to see error notifications",
  997. isDebugWindowOpen());
  998. }
  999. return isElementPresent(By.className("v-Notification-" + type));
  1000. }
  1001. private boolean isDebugWindowOpen() {
  1002. return isElementPresent(By.className("v-debugwindow"));
  1003. }
  1004. protected void assertNoHorizontalScrollbar(WebElement element,
  1005. String errorMessage) {
  1006. assertHasHorizontalScrollbar(element, errorMessage, false);
  1007. }
  1008. protected void assertHorizontalScrollbar(WebElement element,
  1009. String errorMessage) {
  1010. assertHasHorizontalScrollbar(element, errorMessage, true);
  1011. }
  1012. private void assertHasHorizontalScrollbar(WebElement element,
  1013. String errorMessage, boolean expected) {
  1014. // IE rounds clientWidth/clientHeight down and scrollHeight/scrollWidth
  1015. // up, so using clientWidth/clientHeight will fail if the element height
  1016. // is not an integer
  1017. int clientWidth = getClientWidth(element);
  1018. int scrollWidth = getScrollWidth(element);
  1019. boolean hasScrollbar = scrollWidth > clientWidth;
  1020. String message = "The element should";
  1021. if (!expected) {
  1022. message += " not";
  1023. }
  1024. message += " have a horizontal scrollbar (scrollWidth: " + scrollWidth
  1025. + ", clientWidth: " + clientWidth + "): " + errorMessage;
  1026. assertEquals(message, expected, hasScrollbar);
  1027. }
  1028. protected void assertNoVerticalScrollbar(WebElement element,
  1029. String errorMessage) {
  1030. // IE rounds clientWidth/clientHeight down and scrollHeight/scrollWidth
  1031. // up, so using clientWidth/clientHeight will fail if the element height
  1032. // is not an integer
  1033. int clientHeight = getClientHeight(element);
  1034. int scrollHeight = getScrollHeight(element);
  1035. boolean hasScrollbar = scrollHeight > clientHeight;
  1036. assertFalse(
  1037. "The element should not have a vertical scrollbar (scrollHeight: "
  1038. + scrollHeight + ", clientHeight: " + clientHeight
  1039. + "): " + errorMessage,
  1040. hasScrollbar);
  1041. }
  1042. protected int getScrollHeight(WebElement element) {
  1043. return ((Number) executeScript("return arguments[0].scrollHeight;",
  1044. element)).intValue();
  1045. }
  1046. protected int getScrollWidth(WebElement element) {
  1047. return ((Number) executeScript("return arguments[0].scrollWidth;",
  1048. element)).intValue();
  1049. }
  1050. /**
  1051. * Returns client height rounded up instead of as double because of IE9
  1052. * issues: https://dev.vaadin.com/ticket/18469
  1053. */
  1054. protected int getClientHeight(WebElement e) {
  1055. String script = "var cs = window.getComputedStyle(arguments[0]);"
  1056. + "return Math.ceil(parseFloat(cs.height)+parseFloat(cs.paddingTop)+parseFloat(cs.paddingBottom));";
  1057. return ((Number) executeScript(script, e)).intValue();
  1058. }
  1059. /**
  1060. * Returns client width rounded up instead of as double because of IE9
  1061. * issues: https://dev.vaadin.com/ticket/18469
  1062. */
  1063. protected int getClientWidth(WebElement e) {
  1064. String script = "var cs = window.getComputedStyle(arguments[0]);"
  1065. + "var h = parseFloat(cs.width)+parseFloat(cs.paddingLeft)+parseFloat(cs.paddingRight);"
  1066. + "return Math.ceil(h);";
  1067. return ((Number) executeScript(script, e)).intValue();
  1068. }
  1069. protected void assertElementsEquals(WebElement expectedElement,
  1070. WebElement actualElement) {
  1071. while (expectedElement instanceof WrapsElement) {
  1072. expectedElement = ((WrapsElement) expectedElement)
  1073. .getWrappedElement();
  1074. }
  1075. while (actualElement instanceof WrapsElement) {
  1076. actualElement = ((WrapsElement) actualElement).getWrappedElement();
  1077. }
  1078. assertEquals(expectedElement, actualElement);
  1079. }
  1080. protected WebElement getActiveElement() {
  1081. return (WebElement) executeScript("return document.activeElement;");
  1082. }
  1083. protected void waitForThemeToChange(final String theme) {
  1084. final WebElement rootDiv = findElement(
  1085. By.xpath("//div[contains(@class,'v-app')]"));
  1086. waitUntil(input -> {
  1087. String rootClass = rootDiv.getAttribute("class").trim();
  1088. return rootClass.contains(theme);
  1089. }, 30);
  1090. }
  1091. }