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

AbstractTB3Test.java 40KB

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