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

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