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

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