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 43KB

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