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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.tests.tb3;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.StringWriter;
  20. import java.lang.reflect.Field;
  21. import java.net.URL;
  22. import java.util.ArrayList;
  23. import java.util.Arrays;
  24. import java.util.Collections;
  25. import java.util.HashSet;
  26. import java.util.List;
  27. import java.util.Set;
  28. import java.util.logging.Level;
  29. import org.apache.commons.io.IOUtils;
  30. import org.apache.commons.lang3.StringUtils;
  31. import org.apache.http.HttpHost;
  32. import org.apache.http.HttpResponse;
  33. import org.apache.http.impl.client.DefaultHttpClient;
  34. import org.apache.http.message.BasicHttpEntityEnclosingRequest;
  35. import org.junit.Assert;
  36. import org.junit.Rule;
  37. import org.junit.runner.RunWith;
  38. import org.openqa.selenium.By;
  39. import org.openqa.selenium.Dimension;
  40. import org.openqa.selenium.JavascriptExecutor;
  41. import org.openqa.selenium.NoSuchElementException;
  42. import org.openqa.selenium.WebDriver;
  43. import org.openqa.selenium.WebElement;
  44. import org.openqa.selenium.interactions.Actions;
  45. import org.openqa.selenium.interactions.HasInputDevices;
  46. import org.openqa.selenium.interactions.Keyboard;
  47. import org.openqa.selenium.interactions.Mouse;
  48. import org.openqa.selenium.interactions.internal.Coordinates;
  49. import org.openqa.selenium.internal.Locatable;
  50. import org.openqa.selenium.remote.DesiredCapabilities;
  51. import org.openqa.selenium.remote.HttpCommandExecutor;
  52. import org.openqa.selenium.remote.RemoteWebDriver;
  53. import org.openqa.selenium.support.ui.ExpectedCondition;
  54. import org.openqa.selenium.support.ui.ExpectedConditions;
  55. import org.openqa.selenium.support.ui.WebDriverWait;
  56. import com.google.gwt.thirdparty.guava.common.base.Joiner;
  57. import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium;
  58. import com.vaadin.server.LegacyApplication;
  59. import com.vaadin.server.UIProvider;
  60. import com.vaadin.testbench.TestBenchDriverProxy;
  61. import com.vaadin.testbench.TestBenchElement;
  62. import com.vaadin.testbench.annotations.BrowserConfiguration;
  63. import com.vaadin.testbench.elements.CheckBoxElement;
  64. import com.vaadin.testbench.elements.LabelElement;
  65. import com.vaadin.testbench.elements.TableElement;
  66. import com.vaadin.testbench.elements.VerticalLayoutElement;
  67. import com.vaadin.testbench.parallel.Browser;
  68. import com.vaadin.testbench.parallel.BrowserUtil;
  69. import com.vaadin.testbench.parallel.ParallelTest;
  70. import com.vaadin.tests.components.AbstractTestUIWithLog;
  71. import com.vaadin.ui.UI;
  72. import elemental.json.JsonObject;
  73. import elemental.json.impl.JsonUtil;
  74. /**
  75. * Base class for TestBench 3+ tests. All TB3+ tests in the project should
  76. * extend this class.
  77. *
  78. * Provides:
  79. * <ul>
  80. * <li>Helpers for browser selection</li>
  81. * <li>Hub connection setup and teardown</li>
  82. * <li>Automatic generation of URL for a given test on the development server
  83. * using {@link #getUIClass()} or by automatically finding an enclosing UI class
  84. * and based on requested features, e.g. {@link #isDebug()}, {@link #isPush()}</li>
  85. * <li>Generic helpers for creating TB3+ tests</li>
  86. * </ul>
  87. *
  88. * @author Vaadin Ltd
  89. */
  90. @RunWith(TB3Runner.class)
  91. public abstract class AbstractTB3Test extends ParallelTest {
  92. @Rule
  93. public RetryOnFail retry = new RetryOnFail();
  94. /**
  95. * Height of the screenshots we want to capture
  96. */
  97. private static final int SCREENSHOT_HEIGHT = 850;
  98. /**
  99. * Width of the screenshots we want to capture
  100. */
  101. private static final int SCREENSHOT_WIDTH = 1500;
  102. /**
  103. * Timeout used by the TB grid
  104. */
  105. private static final int BROWSER_TIMEOUT_IN_MS = 30 * 1000;
  106. protected static DesiredCapabilities PHANTOMJS2() {
  107. DesiredCapabilities phantomjs2 = new VaadinBrowserFactory().create(
  108. Browser.PHANTOMJS, "2");
  109. // Hack for the test cluster
  110. phantomjs2
  111. .setCapability("phantomjs.binary.path", "/usr/bin/phantomjs2");
  112. return phantomjs2;
  113. }
  114. private boolean debug = false;
  115. private boolean push = false;
  116. static {
  117. com.vaadin.testbench.Parameters
  118. .setScreenshotComparisonCursorDetection(true);
  119. }
  120. /**
  121. * Connect to the hub using a remote web driver, set the canvas size and
  122. * opens the initial URL as specified by {@link #getTestUrl()}
  123. *
  124. * @throws Exception
  125. */
  126. @Override
  127. public void setup() throws Exception {
  128. super.setup();
  129. int w = SCREENSHOT_WIDTH;
  130. int h = SCREENSHOT_HEIGHT;
  131. if (BrowserUtil.isIE8(super.getDesiredCapabilities())) {
  132. // IE8 gets size wrong, who would have guessed...
  133. w += 4;
  134. h += 4;
  135. }
  136. try {
  137. testBench().resizeViewPortTo(w, h);
  138. } catch (UnsupportedOperationException e) {
  139. // Opera does not support this...
  140. }
  141. }
  142. /**
  143. * Method for closing the tested application.
  144. */
  145. protected void closeApplication() {
  146. if (driver != null) {
  147. try {
  148. openTestURL("closeApplication");
  149. } catch (Exception e) {
  150. e.printStackTrace();
  151. }
  152. }
  153. }
  154. protected WebElement getTooltipErrorElement() {
  155. WebElement tooltip = getDriver().findElement(
  156. com.vaadin.testbench.By.className("v-tooltip"));
  157. return tooltip.findElement(By.className("v-errormessage"));
  158. }
  159. protected WebElement getTooltipElement() {
  160. return getDriver().findElement(
  161. com.vaadin.testbench.By.className("v-tooltip-text"));
  162. }
  163. protected Coordinates getCoordinates(TestBenchElement element) {
  164. return ((Locatable) element.getWrappedElement()).getCoordinates();
  165. }
  166. private boolean hasDebugMessage(String message) {
  167. return getDebugMessage(message) != null;
  168. }
  169. private WebElement getDebugMessage(String message) {
  170. return driver.findElement(By.xpath(String.format(
  171. "//span[@class='v-debugwindow-message' and text()='%s']",
  172. message)));
  173. }
  174. protected void waitForDebugMessage(final String expectedMessage) {
  175. waitForDebugMessage(expectedMessage, 30);
  176. }
  177. protected void waitForDebugMessage(final String expectedMessage, int timeout) {
  178. waitUntil(new ExpectedCondition<Boolean>() {
  179. @Override
  180. public Boolean apply(WebDriver input) {
  181. return hasDebugMessage(expectedMessage);
  182. }
  183. }, timeout);
  184. }
  185. protected void clearDebugMessages() {
  186. driver.findElement(
  187. By.xpath("//button[@class='v-debugwindow-button' and @title='Clear log']"))
  188. .click();
  189. }
  190. protected void waitUntilRowIsVisible(final TableElement table, final int row) {
  191. waitUntil(new ExpectedCondition<Object>() {
  192. @Override
  193. public Object apply(WebDriver input) {
  194. try {
  195. return table.getCell(row, 0) != null;
  196. } catch (NoSuchElementException e) {
  197. return false;
  198. }
  199. }
  200. });
  201. }
  202. protected void scrollTable(TableElement table, int rows, int rowToWait) {
  203. testBenchElement(table.findElement(By.className("v-scrollable")))
  204. .scroll(rows * 30);
  205. waitUntilRowIsVisible(table, rowToWait);
  206. }
  207. /**
  208. * Opens the given test (defined by {@link #getTestUrl()}, optionally with
  209. * debug window and/or push (depending on {@link #isDebug()} and
  210. * {@link #isPush()}.
  211. */
  212. protected void openTestURL() {
  213. openTestURL(new String[0]);
  214. }
  215. /**
  216. * Opens the given test (defined by {@link #getTestUrl()}, optionally with
  217. * debug window and/or push (depending on {@link #isDebug()} and
  218. * {@link #isPush()}.
  219. */
  220. protected void openTestURL(String... parameters) {
  221. openTestURL(getUIClass(), parameters);
  222. }
  223. /**
  224. * Opens the given test (defined by {@link #getTestUrl()}, optionally with
  225. * debug window and/or push (depending on {@link #isDebug()} and
  226. * {@link #isPush()}.
  227. */
  228. protected void openTestURL(Class<?> uiClass, String... parameters) {
  229. openTestURL(uiClass, new HashSet<String>(Arrays.asList(parameters)));
  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.size() > 0) {
  240. url += "?" + Joiner.on("&").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 teh 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.singletonList(Browser.FIREFOX
  289. .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. protected Object executeScript(String script, Object... args) {
  326. return ((JavascriptExecutor) getDriver()).executeScript(script, args);
  327. }
  328. /**
  329. * Find a Vaadin element based on its id given using Component.setId
  330. *
  331. * @param id
  332. * The id to locate
  333. * @return
  334. */
  335. public WebElement vaadinElementById(String id) {
  336. return driver.findElement(vaadinLocatorById(id));
  337. }
  338. /**
  339. * Finds a {@link By} locator based on the part of a TB2 style locator
  340. * following the :: (e.g.
  341. * vaadin=runLabelModes::PID_Scheckboxaction-Enabled/domChild[0] ->
  342. * PID_Scheckboxaction-Enabled/domChild[0]).
  343. *
  344. * @param vaadinLocator
  345. * The part following :: of the vaadin locator string
  346. * @return
  347. */
  348. public org.openqa.selenium.By vaadinLocator(String vaadinLocator) {
  349. String base = getApplicationId(getDeploymentPath());
  350. base += "::";
  351. return com.vaadin.testbench.By.vaadin(base + vaadinLocator);
  352. }
  353. /**
  354. * Constructs a {@link By} locator for the id given using Component.setId
  355. *
  356. * @param id
  357. * The id to locate
  358. * @return a locator for the given id
  359. */
  360. public By vaadinLocatorById(String id) {
  361. return vaadinLocator("PID_S" + id);
  362. }
  363. /**
  364. * Waits up to 10s for the given condition to become true. Use e.g. as
  365. * {@link #waitUntil(ExpectedConditions.textToBePresentInElement(by, text))}
  366. *
  367. * @param condition
  368. * the condition to wait for to become true
  369. */
  370. protected <T> void waitUntil(ExpectedCondition<T> condition) {
  371. waitUntil(condition, 10);
  372. }
  373. /**
  374. * Waits the given number of seconds for the given condition to become true.
  375. * Use e.g. as {@link
  376. * #waitUntil(ExpectedConditions.textToBePresentInElement(by, text))}
  377. *
  378. * @param condition
  379. * the condition to wait for to become true
  380. */
  381. protected <T> void waitUntil(ExpectedCondition<T> condition,
  382. long timeoutInSeconds) {
  383. new WebDriverWait(driver, timeoutInSeconds).until(condition);
  384. }
  385. /**
  386. * Waits up to 10s for the given condition to become false. Use e.g. as
  387. * {@link #waitUntilNot(ExpectedConditions.textToBePresentInElement(by,
  388. * text))}
  389. *
  390. * @param condition
  391. * the condition to wait for to become false
  392. */
  393. protected <T> void waitUntilNot(ExpectedCondition<T> condition) {
  394. waitUntilNot(condition, 10);
  395. }
  396. /**
  397. * Waits the given number of seconds for the given condition to become
  398. * false. Use e.g. as {@link
  399. * #waitUntilNot(ExpectedConditions.textToBePresentInElement(by, text))}
  400. *
  401. * @param condition
  402. * the condition to wait for to become false
  403. */
  404. protected <T> void waitUntilNot(ExpectedCondition<T> condition,
  405. long timeoutInSeconds) {
  406. waitUntil(ExpectedConditions.not(condition), timeoutInSeconds);
  407. }
  408. protected void waitForElementPresent(final By by) {
  409. waitUntil(ExpectedConditions.presenceOfElementLocated(by));
  410. }
  411. protected void waitForElementNotPresent(final By by) {
  412. waitUntil(new ExpectedCondition<Boolean>() {
  413. @Override
  414. public Boolean apply(WebDriver input) {
  415. return input.findElements(by).isEmpty();
  416. }
  417. });
  418. }
  419. protected void waitForElementVisible(final By by) {
  420. waitUntil(ExpectedConditions.visibilityOfElementLocated(by));
  421. }
  422. /**
  423. * Checks if the given element has the given class name.
  424. *
  425. * Matches only full class names, i.e. has ("foo") does not match
  426. * class="foobar"
  427. *
  428. * @param element
  429. * @param className
  430. * @return
  431. */
  432. protected boolean hasCssClass(WebElement element, String className) {
  433. String classes = element.getAttribute("class");
  434. if (classes == null || classes.isEmpty()) {
  435. return (className == null || className.isEmpty());
  436. }
  437. for (String cls : classes.split(" ")) {
  438. if (className.equals(cls)) {
  439. return true;
  440. }
  441. }
  442. return false;
  443. }
  444. /**
  445. * For tests extending {@link AbstractTestUIWithLog}, returns the element
  446. * for the Nth log row
  447. *
  448. * @param rowNr
  449. * The log row to retrieve
  450. * @return the Nth log row
  451. */
  452. protected WebElement getLogRowElement(int rowNr) {
  453. return vaadinElementById("Log_row_" + rowNr);
  454. }
  455. /**
  456. * For tests extending {@link AbstractTestUIWithLog}, returns the text in
  457. * the Nth log row
  458. *
  459. * @param rowNr
  460. * The log row to retrieve text for
  461. * @return the text in the log row
  462. */
  463. protected String getLogRow(int rowNr) {
  464. return getLogRowElement(rowNr).getText();
  465. }
  466. /**
  467. * Asserts that {@literal a} is &gt;= {@literal b}
  468. *
  469. * @param message
  470. * The message to include in the {@link AssertionError}
  471. * @param a
  472. * @param b
  473. * @throws AssertionError
  474. * If comparison fails
  475. */
  476. public static final <T> void assertGreaterOrEqual(String message,
  477. Comparable<T> a, T b) throws AssertionError {
  478. if (a.compareTo(b) >= 0) {
  479. return;
  480. }
  481. throw new AssertionError(decorate(message, a, b));
  482. }
  483. /**
  484. * Asserts that {@literal a} is &gt; {@literal b}
  485. *
  486. * @param message
  487. * The message to include in the {@link AssertionError}
  488. * @param a
  489. * @param b
  490. * @throws AssertionError
  491. * If comparison fails
  492. */
  493. public static final <T> void assertGreater(String message, Comparable<T> a,
  494. T b) throws AssertionError {
  495. if (a.compareTo(b) > 0) {
  496. return;
  497. }
  498. throw new AssertionError(decorate(message, a, b));
  499. }
  500. /**
  501. * Asserts that {@literal a} is &lt;= {@literal b}
  502. *
  503. * @param message
  504. * The message to include in the {@link AssertionError}
  505. * @param a
  506. * @param b
  507. * @throws AssertionError
  508. * If comparison fails
  509. */
  510. public static final <T> void assertLessThanOrEqual(String message,
  511. Comparable<T> a, T b) throws AssertionError {
  512. if (a.compareTo(b) <= 0) {
  513. return;
  514. }
  515. throw new AssertionError(decorate(message, a, b));
  516. }
  517. /**
  518. * Asserts that {@literal a} is &lt; {@literal b}
  519. *
  520. * @param message
  521. * The message to include in the {@link AssertionError}
  522. * @param a
  523. * @param b
  524. * @throws AssertionError
  525. * If comparison fails
  526. */
  527. public static final <T> void assertLessThan(String message,
  528. Comparable<T> a, T b) throws AssertionError {
  529. if (a.compareTo(b) < 0) {
  530. return;
  531. }
  532. throw new AssertionError(decorate(message, a, b));
  533. }
  534. private static <T> String decorate(String message, Comparable<T> a, T b) {
  535. message = message.replace("{0}", a.toString());
  536. message = message.replace("{1}", b.toString());
  537. return message;
  538. }
  539. /**
  540. * Returns the path that should be used for the test. The path contains the
  541. * full path (appended to hostname+port) and must start with a slash.
  542. *
  543. * @param push
  544. * true if "?debug" should be added
  545. * @param debug
  546. * true if /run-push should be used instead of /run
  547. *
  548. * @return The URL path to the UI class to test
  549. */
  550. protected String getDeploymentPath() {
  551. Class<?> uiClass = getUIClass();
  552. if (uiClass != null) {
  553. return getDeploymentPath(uiClass);
  554. }
  555. throw new IllegalArgumentException("Unable to determine path for "
  556. + getClass().getCanonicalName());
  557. }
  558. /**
  559. * Returns the UI class the current test is connected to (or in special
  560. * cases UIProvider or LegacyApplication). Uses the enclosing class if the
  561. * test class is a static inner class to a UI class.
  562. *
  563. * Test which are not enclosed by a UI class must implement this method and
  564. * return the UI class they want to test.
  565. *
  566. * Note that this method will update the test name to the enclosing class to
  567. * be compatible with TB2 screenshot naming
  568. *
  569. * @return the UI class the current test is connected to
  570. */
  571. protected Class<?> getUIClass() {
  572. try {
  573. // Convention: SomeUITest uses the SomeUI UI class
  574. String uiClassName = getClass().getName().replaceFirst("Test$", "");
  575. Class<?> cls = Class.forName(uiClassName);
  576. if (isSupportedRunnerClass(cls)) {
  577. return cls;
  578. }
  579. } catch (Exception e) {
  580. }
  581. throw new RuntimeException(
  582. "Could not determine UI class. Ensure the test is named UIClassTest and is in the same package as the UIClass");
  583. }
  584. /**
  585. * @return true if the given class is supported by ApplicationServletRunner
  586. */
  587. @SuppressWarnings("deprecation")
  588. private boolean isSupportedRunnerClass(Class<?> cls) {
  589. if (UI.class.isAssignableFrom(cls)) {
  590. return true;
  591. }
  592. if (UIProvider.class.isAssignableFrom(cls)) {
  593. return true;
  594. }
  595. if (LegacyApplication.class.isAssignableFrom(cls)) {
  596. return true;
  597. }
  598. return false;
  599. }
  600. /**
  601. * Returns whether to run the test in debug mode (with the debug console
  602. * open) or not
  603. *
  604. * @return true to run with the debug window open, false by default
  605. */
  606. protected final boolean isDebug() {
  607. return debug;
  608. }
  609. /**
  610. * Sets whether to run the test in debug mode (with the debug console open)
  611. * or not.
  612. *
  613. * @param debug
  614. * true to open debug window, false otherwise
  615. */
  616. protected final void setDebug(boolean debug) {
  617. this.debug = debug;
  618. }
  619. /**
  620. * Returns whether to run the test with push enabled (using /run-push) or
  621. * not. Note that push tests can and should typically be created using @Push
  622. * on the UI instead of overriding this method
  623. *
  624. * @return true if /run-push is used, false otherwise
  625. */
  626. protected final boolean isPush() {
  627. return push;
  628. }
  629. /**
  630. * Sets whether to run the test with push enabled (using /run-push) or not.
  631. * Note that push tests can and should typically be created using @Push on
  632. * the UI instead of overriding this method
  633. *
  634. * @param push
  635. * true to use /run-push in the test, false otherwise
  636. */
  637. protected final void setPush(boolean push) {
  638. this.push = push;
  639. }
  640. /**
  641. * Returns the path for the given UI class when deployed on the test server.
  642. * The path contains the full path (appended to hostname+port) and must
  643. * start with a slash.
  644. *
  645. * This method takes into account {@link #isPush()} and {@link #isDebug()}
  646. * when the path is generated.
  647. *
  648. * @param uiClass
  649. * @param push
  650. * true if "?debug" should be added
  651. * @param debug
  652. * true if /run-push should be used instead of /run
  653. * @return The path to the given UI class
  654. */
  655. protected String getDeploymentPath(Class<?> uiClass) {
  656. String runPath = "/run";
  657. if (isPush()) {
  658. runPath = "/run-push";
  659. }
  660. if (UI.class.isAssignableFrom(uiClass)
  661. || UIProvider.class.isAssignableFrom(uiClass)
  662. || LegacyApplication.class.isAssignableFrom(uiClass)) {
  663. return runPath + "/" + uiClass.getCanonicalName();
  664. } else {
  665. throw new IllegalArgumentException(
  666. "Unable to determine path for enclosing class "
  667. + uiClass.getCanonicalName());
  668. }
  669. }
  670. /**
  671. * Used to determine what URL to initially open for the test
  672. *
  673. * @return The base URL for the test. Does not include a trailing slash.
  674. */
  675. protected String getBaseURL() {
  676. return "http://" + getDeploymentHostname() + ":" + getDeploymentPort();
  677. }
  678. /**
  679. * Generates the application id based on the URL in a way compatible with
  680. * VaadinServletService.
  681. *
  682. * @param pathWithQueryParameters
  683. * The path part of the URL, possibly still containing query
  684. * parameters
  685. * @return The application ID string used in Vaadin locators
  686. */
  687. private String getApplicationId(String pathWithQueryParameters) {
  688. // Remove any possible URL parameters
  689. String pathWithoutQueryParameters = pathWithQueryParameters.replaceAll(
  690. "\\?.*", "");
  691. if ("".equals(pathWithoutQueryParameters)) {
  692. return "ROOT";
  693. }
  694. // Retain only a-z and numbers
  695. return pathWithoutQueryParameters.replaceAll("[^a-zA-Z0-9]", "");
  696. }
  697. /**
  698. * Sleeps for the given number of ms but ensures that the browser connection
  699. * does not time out.
  700. *
  701. * @param timeoutMillis
  702. * Number of ms to wait
  703. * @throws InterruptedException
  704. */
  705. protected void sleep(int timeoutMillis) throws InterruptedException {
  706. while (timeoutMillis > 0) {
  707. int d = Math.min(BROWSER_TIMEOUT_IN_MS, timeoutMillis);
  708. Thread.sleep(d);
  709. timeoutMillis -= d;
  710. // Do something to keep the connection alive
  711. getDriver().getTitle();
  712. }
  713. }
  714. /**
  715. * Called by the test runner whenever there is an exception in the test that
  716. * will cause termination of the test
  717. *
  718. * @param t
  719. * the throwable which caused the termination
  720. */
  721. public void onUncaughtException(Throwable t) {
  722. // Do nothing by default
  723. }
  724. /**
  725. * Returns the mouse object for doing mouse commands
  726. *
  727. * @return Returns the mouse
  728. */
  729. public Mouse getMouse() {
  730. return ((HasInputDevices) getDriver()).getMouse();
  731. }
  732. /**
  733. * Returns the keyboard object for controlling keyboard events
  734. *
  735. * @return Return the keyboard
  736. */
  737. public Keyboard getKeyboard() {
  738. return ((HasInputDevices) getDriver()).getKeyboard();
  739. }
  740. public void hitButton(String id) {
  741. if (BrowserUtil.isPhantomJS(getDesiredCapabilities())) {
  742. driver.findElement(By.id(id)).click();
  743. } else {
  744. WebDriverBackedSelenium selenium = new WebDriverBackedSelenium(
  745. driver, driver.getCurrentUrl());
  746. selenium.keyPress("id=" + id, "\\13");
  747. }
  748. }
  749. protected void openDebugLogTab() {
  750. waitUntil(new ExpectedCondition<Boolean>() {
  751. @Override
  752. public Boolean apply(WebDriver input) {
  753. WebElement element = getDebugLogButton();
  754. return element != null;
  755. }
  756. }, 15);
  757. getDebugLogButton().click();
  758. }
  759. private WebElement getDebugLogButton() {
  760. return findElement(By.xpath("//button[@title='Debug message log']"));
  761. }
  762. protected void assertNoDebugMessage(Level level) {
  763. // class="v-debugwindow-row Level.getName()"
  764. List<WebElement> logElements = driver
  765. .findElements(By.xpath(String
  766. .format("//div[@class='v-debugwindow-row %s']/span[@class='v-debugwindow-message']",
  767. level.getName())));
  768. if (!logElements.isEmpty()) {
  769. String logRows = "";
  770. for (WebElement e : logElements) {
  771. logRows += "\n" + e.getText();
  772. }
  773. Assert.fail("Found debug messages with level " + level.getName()
  774. + ": " + logRows);
  775. }
  776. }
  777. /**
  778. * Should the "require window focus" be enabled for Internet Explorer.
  779. * RequireWindowFocus makes tests more stable but seems to be broken with
  780. * certain commands such as sendKeys. Therefore it is not enabled by default
  781. * for all tests
  782. *
  783. * @return true, to use the "require window focus" feature, false otherwise
  784. */
  785. protected boolean requireWindowFocusForIE() {
  786. return false;
  787. }
  788. /**
  789. * Should the "enable persistent hover" be enabled for Internet Explorer.
  790. *
  791. * Persistent hovering causes continuous firing of mouse over events at the
  792. * last location the mouse cursor has been moved to. This is to avoid
  793. * problems where the real mouse cursor is inside the browser window and
  794. * Internet Explorer uses that location for some undefined operation
  795. * (http://
  796. * jimevansmusic.blogspot.fi/2012/06/whats-wrong-with-internet-explorer
  797. * .html)
  798. *
  799. * @return true, to use the "persistent hover" feature, false otherwise
  800. */
  801. protected boolean usePersistentHoverForIE() {
  802. return true;
  803. }
  804. // FIXME: Remove this once TB4 getRemoteControlName works properly
  805. private RemoteWebDriver getRemoteDriver() {
  806. WebDriver d = getDriver();
  807. if (d instanceof TestBenchDriverProxy) {
  808. try {
  809. Field f = TestBenchDriverProxy.class
  810. .getDeclaredField("actualDriver");
  811. f.setAccessible(true);
  812. return (RemoteWebDriver) f.get(d);
  813. } catch (Exception e) {
  814. e.printStackTrace();
  815. }
  816. }
  817. if (d instanceof RemoteWebDriver) {
  818. return (RemoteWebDriver) d;
  819. }
  820. return null;
  821. }
  822. // FIXME: Remove this once TB4 getRemoteControlName works properly
  823. protected String getRemoteControlName() {
  824. try {
  825. RemoteWebDriver d = getRemoteDriver();
  826. if (d == null) {
  827. return null;
  828. }
  829. HttpCommandExecutor ce = (HttpCommandExecutor) d
  830. .getCommandExecutor();
  831. String hostName = ce.getAddressOfRemoteServer().getHost();
  832. int port = ce.getAddressOfRemoteServer().getPort();
  833. HttpHost host = new HttpHost(hostName, port);
  834. DefaultHttpClient client = new DefaultHttpClient();
  835. URL sessionURL = new URL("http://" + hostName + ":" + port
  836. + "/grid/api/testsession?session=" + d.getSessionId());
  837. BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(
  838. "POST", sessionURL.toExternalForm());
  839. HttpResponse response = client.execute(host, r);
  840. JsonObject object = extractObject(response);
  841. URL myURL = new URL(object.getString("proxyId"));
  842. if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
  843. return myURL.getHost();
  844. }
  845. } catch (Exception e) {
  846. e.printStackTrace();
  847. }
  848. return null;
  849. }
  850. protected boolean logContainsText(String string) {
  851. List<String> logs = getLogs();
  852. for (String text : logs) {
  853. if (text.contains(string)) {
  854. return true;
  855. }
  856. }
  857. return false;
  858. }
  859. protected List<String> getLogs() {
  860. VerticalLayoutElement log = $(VerticalLayoutElement.class).id("Log");
  861. List<LabelElement> logLabels = log.$(LabelElement.class).all();
  862. List<String> logTexts = new ArrayList<String>();
  863. for (LabelElement label : logLabels) {
  864. logTexts.add(label.getText());
  865. }
  866. return logTexts;
  867. }
  868. private static JsonObject extractObject(HttpResponse resp)
  869. throws IOException {
  870. InputStream contents = resp.getEntity().getContent();
  871. StringWriter writer = new StringWriter();
  872. IOUtils.copy(contents, writer, "UTF8");
  873. return JsonUtil.parse(writer.toString());
  874. }
  875. protected void click(CheckBoxElement checkbox) {
  876. WebElement cb = checkbox.findElement(By.xpath("input"));
  877. if (BrowserUtil.isChrome(getDesiredCapabilities())) {
  878. testBenchElement(cb).click(0, 0);
  879. } else {
  880. cb.click();
  881. }
  882. }
  883. protected boolean isLoadingIndicatorVisible() {
  884. WebElement loadingIndicator = findElement(By
  885. .className("v-loading-indicator"));
  886. return loadingIndicator.isDisplayed();
  887. }
  888. protected void waitUntilLoadingIndicatorNotVisible() {
  889. waitUntil(new ExpectedCondition<Boolean>() {
  890. @Override
  891. public Boolean apply(WebDriver input) {
  892. WebElement loadingIndicator = input.findElement(By
  893. .className("v-loading-indicator"));
  894. return !loadingIndicator.isDisplayed();
  895. }
  896. });
  897. }
  898. /**
  899. * Selects a menu item. By default, this will click on the menu item.
  900. *
  901. * @param menuCaption
  902. * caption of the menu item
  903. */
  904. protected void selectMenu(String menuCaption) {
  905. selectMenu(menuCaption, true);
  906. }
  907. /**
  908. * Selects a menu item.
  909. *
  910. * @param menuCaption
  911. * caption of the menu item
  912. * @param click
  913. * <code>true</code> if should click the menu item;
  914. * <code>false</code> if not
  915. */
  916. protected void selectMenu(String menuCaption, boolean click) {
  917. WebElement menuElement = getMenuElement(menuCaption);
  918. Dimension size = menuElement.getSize();
  919. new Actions(getDriver()).moveToElement(menuElement, size.width - 10,
  920. size.height / 2).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. return getDriver().findElement(
  937. By.xpath("//span[text() = '" + menuCaption + "']"));
  938. }
  939. /**
  940. * Selects a submenu described by a path of menus from the first MenuBar in
  941. * the UI.
  942. *
  943. * @param menuCaptions
  944. * array of menu captions
  945. */
  946. protected void selectMenuPath(String... menuCaptions) {
  947. selectMenu(menuCaptions[0], true);
  948. // Move to the menu item opened below the menu bar.
  949. new Actions(getDriver()).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(40, 0).build().perform();
  955. }
  956. selectMenu(menuCaptions[menuCaptions.length - 1], true);
  957. }
  958. /**
  959. * Asserts that an element is present
  960. *
  961. * @param by
  962. * the locatore for the element
  963. */
  964. protected void assertElementPresent(By by) {
  965. Assert.assertTrue("Element is not present", isElementPresent(by));
  966. }
  967. /**
  968. * Asserts that an element is not present
  969. *
  970. * @param by
  971. * the locatore for the element
  972. */
  973. protected void assertElementNotPresent(By by) {
  974. Assert.assertFalse("Element is present", isElementPresent(by));
  975. }
  976. /**
  977. * Asserts that no error notifications are shown. Requires the use of
  978. * "?debug" as exceptions are otherwise not shown as notifications.
  979. */
  980. protected void assertNoErrorNotifications() {
  981. Assert.assertTrue(
  982. "Debug window must be open to be able to see error notifications",
  983. isDebugWindowOpen());
  984. Assert.assertFalse(
  985. "Error notification with client side exception is shown",
  986. isElementPresent(By.className("v-Notification-error")));
  987. }
  988. private boolean isDebugWindowOpen() {
  989. return isElementPresent(By.className("v-debugwindow"));
  990. }
  991. }