diff --git a/.gitignore b/.gitignore index 62802d0..f0a982d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ -*.log -target/ -.metadata/ .idea/ .DS_Store -venv/ \ No newline at end of file +venv/ +*.py[cod] +.eggs/ +*.egg-info/ +dist/ \ No newline at end of file diff --git a/helium-java/.gitignore b/helium-java/.gitignore deleted file mode 100644 index cc50321..0000000 --- a/helium-java/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -*.iml -.classpath -.project -.settings/ diff --git a/helium-java/build.py b/helium-java/build.py deleted file mode 100644 index 8eec118..0000000 --- a/helium-java/build.py +++ /dev/null @@ -1,25 +0,0 @@ -from build_impl import unzip_replacing_top_lvl_dir -from helium.util.system import get_canonical_os_name as get_platform, \ - is_windows -from os import chmod -from os.path import join, dirname -import sys - -def pre_integration_test(project_version, artifactFinalName): - zip_file = _get_target_path( - '%s-%s.zip' % (artifactFinalName, get_platform()) - ) - unzip_replacing_top_lvl_dir(zip_file, _get_target_path('test-dist')) - # we need to change the execution rights to make this work on OSX - if not is_windows(): - chmod(_get_target_path('test-dist/webdrivers/chromedriver'), 0o755) - -def _get_proj_path(*rel_path): - rel_path = '/'.join(rel_path) - return join(dirname(__file__), *rel_path.split('/')) - -def _get_target_path(*rel_path): - return _get_proj_path('target/' + '/'.join(rel_path)) - -if __name__ == '__main__': - globals()[sys.argv[1]](*sys.argv[2:]) \ No newline at end of file diff --git a/helium-java/pom.xml b/helium-java/pom.xml deleted file mode 100644 index b69b97f..0000000 --- a/helium-java/pom.xml +++ /dev/null @@ -1,499 +0,0 @@ - - 4.0.0 - - com.heliumhq - helium - 2.0.4-SNAPSHOT - - helium-java - jar - - - ${basedir}/src/integrationtest/java - - - ${project.build.directory}/integrationtest-classes - - - ${basedir}/src/systemtest/java - - ${basedir}/src/site/java - - ${project.build.directory}/systemtest-classes - - - ${project.build.directory}/site-classes - - ${basedir}/.. - 2.16 - 1.8 - 1.8 - - - - chrome - - true - - performRelease - true - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - ${maven-failsafe-plugin.version} - - - perform-integrationtests-chrome - - integration-test - - - - chrome - ${heliumPythonInttestPythonpath} - - ${inttestOutputDirectory}/failsafe-reports/failsafe-summary-chrome.xml - - - - verify-integrationtests-chrome - - verify - - - ${inttestOutputDirectory}/failsafe-reports/failsafe-summary-chrome.xml - - - - - - - - - firefox - - - performRelease - true - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - ${maven-failsafe-plugin.version} - - - perform-integrationtests-firefox - - integration-test - - - - firefox - ${heliumPythonInttestPythonpath} - - ${inttestOutputDirectory}/failsafe-reports/failsafe-summary-firefox.xml - - - - verify-integrationtests-firefox - - verify - - - ${inttestOutputDirectory}/failsafe-reports/failsafe-summary-firefox.xml - - - - - - - - - ie - - - performRelease - true - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - ${maven-failsafe-plugin.version} - - - perform-integrationtests-ie - - integration-test - - - - ie - ${heliumPythonInttestPythonpath} - - ${inttestOutputDirectory}/failsafe-reports/failsafe-summary-ie.xml - - - - verify-integrationtests-ie - - verify - - - - ${inttestOutputDirectory}/failsafe-reports/failsafe-summary-ie.xml - - - - - - - - - - - - org.seleniumhq.selenium - selenium-java - ${selenium.version} - - - cglib - cglib-nodep - - - org.seleniumhq.selenium - selenium-htmlunit-driver - - - commons-io - commons-io - - - org.seleniumhq.selenium - selenium-iphone-driver - - - org.seleniumhq.selenium - selenium-android-driver - - - org.seleniumhq.selenium - selenium-safari-driver - - - org.webbitserver - webbit - - - commons-codec - commons-codec - - - - - junit - junit - 4.11 - test - - - com.googlecode.junit-toolbox - junit-toolbox - 1.8 - test - - - org.hamcrest - hamcrest-all - 1.3 - test - - - - com.sun - tools - 1.8.0 - system - ${java.home}/../lib/tools.jar - - - - ${project.artifactId}-${project.version} - - ${basedir}/src/unittest/java - - - ${project.build.directory}/unittest-classes - - - - maven-antrun-plugin - - - ${maven-antrun-plugin.version} - - - create-test-class-output-directories - pre-integration-test - - - - - - - - run - - - - create-site-class-output-directory - pre-site - - - - - - - run - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 1.8 - - - add-inttest-systest-sources - pre-integration-test - - add-test-source - - - - ${inttestSourceDirectory} - ${systestSourceDirectory} - - - - - add-site-sources - pre-site - - add-source - - - - ${siteSourceDirectory} - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - - default-testCompile - test-compile - - testCompile - - - - compile-integrationtests - pre-integration-test - - testCompile - - - - helium_systemtest/** - - - ${inttestOutputDirectory} - - - - - compile-systemtests - pre-integration-test - - testCompile - - - - ${systestOutputDirectory} - - - - - compile-site-classes - pre-site - - compile - - - - ${siteOutputDirectory} - - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - pre-integration-test - pre-integration-test - - exec - - - python - ${basedir} - - build.py - pre_integration_test - ${project.version} - ${project.build.finalName} - - - ${buildPythonpath} - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.16 - - false - - - - maven-assembly-plugin - 2.4 - - - package - - single - - - - - ${basedir}/src/main/assembly/win.xml - - - ${basedir}/src/main/assembly/macosx.xml - - - ${basedir}/src/main/assembly/linux.xml - - - - ${project.build.directory} - - true - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - ${maven-failsafe-plugin.version} - - - ${inttestOutputDirectory} - ${inttestOutputDirectory}/failsafe-reports - - **/*IT.java - **/inttest_api/APITestSuite.* - - - **/inttest_api/*IT.* - - false - - - - perform-systemtests - - integration-test - - - ${systestOutputDirectory} - ${systestOutputDirectory}/failsafe-reports - - **/*ST.java - - ${systestOutputDirectory}/failsafe-reports/failsafe-summary-systemtests.xml - - - - verify-systemtests - - verify - - - ${systestOutputDirectory}/failsafe-reports - ${systestOutputDirectory}/failsafe-reports/failsafe-summary-systemtests.xml - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.4 - - com.heliumhq.site.HeliumAPIDoclet - ${siteOutputDirectory} - com.heliumhq - - -apiclass com.heliumhq.API - -d ${project.build.directory}/site - -f helium-java-api.ctp - - - - - - - - - - attach-javadocs - none - - - site - - javadoc - - - - - - - diff --git a/helium-java/src/integrationtest/java/com/heliumhq/Environment.java b/helium-java/src/integrationtest/java/com/heliumhq/Environment.java deleted file mode 100644 index 3101808..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/Environment.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.heliumhq; - -import static com.heliumhq.api_impl.application_context.DevelopmentAPIConfig. - getHeliumFile; - -public class Environment { - - public static String getIntegrationtestResource(String relPath) { - return getHeliumFile("src/integrationtest/resources/" + relPath); - } - - public static String getITFileURL(String page) { - return pathToFileURL(getIntegrationtestResource(page)); - } - - private static String pathToFileURL(String path) { - return "file:///" + path.replace("\\", "/"); - } - -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/NoDriverIT.java b/helium-java/src/integrationtest/java/com/heliumhq/NoDriverIT.java deleted file mode 100644 index 7ff0ce1..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/NoDriverIT.java +++ /dev/null @@ -1,218 +0,0 @@ -package com.heliumhq; - -import com.heliumhq.api_impl.APIImpl; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import static com.heliumhq.API.*; - -public class NoDriverIT { - - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - @Test - public void testGoToRequiresDriver() { - checkRequiresDriver(); - goTo("google.com"); - } - - @Test - public void testWriteRequiresDriver() { - checkRequiresDriver(); - write("foo"); - } - - @Test - public void testPressRequiresDriver() { - checkRequiresDriver(); - press(ENTER); - } - - @Test - public void testClickRequiresDriver() { - checkRequiresDriver(); - click("Sign in"); - } - - @Test - public void testDoubleclickRequiresDriver() { - checkRequiresDriver(); - doubleclick("Sign in"); - } - - @Test - public void testDragRequiresDriver() { - checkRequiresDriver(); - drag("Drag me", to("Drop here")); - } - - @Test - public void testFindAllRequiresDriver() { - checkRequiresDriver(); - findAll(Button()); - } - - @Test - public void testScrollDownRequiresDriver() { - checkRequiresDriver(); - scrollDown(); - } - - @Test - public void testScrollUpRequiresDriver() { - checkRequiresDriver(); - scrollUp(); - } - - @Test - public void testScrollRightRequiresDriver() { - checkRequiresDriver(); - scrollRight(); - } - - @Test - public void testScrollLeftRequiresDriver() { - checkRequiresDriver(); - scrollLeft(); - } - - @Test - public void testHoverRequiresDriver() { - checkRequiresDriver(); - hover("Hi there!"); - } - - @Test - public void testRightclickRequiresDriver() { - checkRequiresDriver(); - rightclick("Hi there!"); - } - - @Test - public void testSelectRequiresDriver() { - checkRequiresDriver(); - select("Language", "English"); - } - - @Test - public void testDragFileRequiresDriver() { - checkRequiresDriver(); - dragFile("C\\test.txt", to("Here")); - } - - @Test - public void testAttachFileRequiresDriver() { - checkRequiresDriver(); - attachFile("C\\test.txt"); - } - - @Test - public void testRefreshRequiresDriver() { - checkRequiresDriver(); - refresh(); - } - - @Test - public void testWaitUntilRequiresDriver() { - checkRequiresDriver(); - waitUntil(null); - } - - @Test - public void testSwitchToRequiresDriver() { - checkRequiresDriver(); - switchTo("Popup"); - } - - @Test - public void testKillBrowserRequiresDriver() { - checkRequiresDriver(); - switchTo("Popup"); - } - - @Test - public void testHighlightRequiresDriver() { - checkRequiresDriver(); - switchTo("Popup"); - } - - @Test - public void test$RequiresDriver() { - checkRequiresDriver(); - $("#home"); - } - - @Test - public void testTextRequiresDriver() { - checkRequiresDriver(); - Text("Home"); - } - - @Test - public void testLinkRequiresDriver() { - checkRequiresDriver(); - Link("Home"); - } - - @Test - public void testListItemRequiresDriver() { - checkRequiresDriver(); - ListItem("Home"); - } - - @Test - public void testButtonRequiresDriver() { - checkRequiresDriver(); - Button("Home"); - } - - @Test - public void testImageRequiresDriver() { - checkRequiresDriver(); - Image("Logo"); - } - - @Test - public void testTextFieldRequiresDriver() { - checkRequiresDriver(); - TextField("File name"); - } - - @Test - public void testComboBoxRequiresDriver() { - checkRequiresDriver(); - ComboBox("Language"); - } - - @Test - public void testCheckBoxRequiresDriver() { - checkRequiresDriver(); - CheckBox("True?"); - } - - @Test - public void testRadioButtonRequiresDriver() { - checkRequiresDriver(); - RadioButton("Option A"); - } - - @Test - public void testWindowRequiresDriver() { - checkRequiresDriver(); - Window("Main"); - } - - @Test - public void testAlertRequiresDriver() { - checkRequiresDriver(); - Alert(); - } - - private void checkRequiresDriver() { - expectedEx.expect(RuntimeException.class); - expectedEx.expectMessage(APIImpl.DRIVER_REQUIRED_MESSAGE); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/PythonServer.java b/helium-java/src/integrationtest/java/com/heliumhq/PythonServer.java deleted file mode 100644 index 7003d15..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/PythonServer.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.heliumhq; - -import java.io.IOException; - -import static com.heliumhq.api_impl.application_context.DevelopmentAPIConfig. - getHeliumDir; -import static com.heliumhq.api_impl.application_context.DevelopmentAPIConfig. - getHeliumFile; -import static com.heliumhq.inttest_api.util.Processes.waitForProcessOutput; - -public class PythonServer { - - private final String pyFile; - private final String serverStartedMessage; - private Process pythonServer; - - public PythonServer(String pyFile, String serverStartedMessage) { - this.pyFile = pyFile; - this.serverStartedMessage = serverStartedMessage; - } - - public void start() throws IOException { - String pyFilePath = getHeliumFile("helium-python/" + pyFile); - ProcessBuilder pb = new ProcessBuilder("python", pyFilePath); - String pythonpath = System.getenv("PYTHONPATH"); - pb.environment().put("PYTHONPATH", pythonpath); - pb.directory(getHeliumDir()); - pb.redirectErrorStream(true); - pythonServer = pb.start(); - waitForProcessOutput(pythonServer, serverStartedMessage); - } - - public void stop() { - pythonServer.destroy(); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/ResourceLocatorIT.java b/helium-java/src/integrationtest/java/com/heliumhq/ResourceLocatorIT.java deleted file mode 100644 index 6a2e3e0..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/ResourceLocatorIT.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.heliumhq; - -import com.heliumhq.environment.ResourceLocator; -import org.junit.Before; -import org.junit.Test; - -import java.io.File; - -import static com.heliumhq.Environment.getIntegrationtestResource; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -public class ResourceLocatorIT { - - private String rootDir; - - @Before - public void setUp() { - rootDir = getIntegrationtestResource("inttest_environment"); - } - - @Test - public void testLocateFile() { - ResourceLocator resourceLocator = new ResourceLocator(rootDir); - String result = resourceLocator.locate("file.txt"); - assertNotNull(result); - assertTrue(new File(result).exists()); - } - - @Test - public void testLocateFileInDir() { - ResourceLocator resourceLocator = new ResourceLocator(rootDir); - String result = resourceLocator.locate("dir", "file_in_dir.txt"); - assertNotNull(result); - assertTrue(new File(result).exists()); - } - - @Test - public void testLocateNonExistentFile() { - ResourceLocator resourceLocator = new ResourceLocator(rootDir); - String result = resourceLocator.locate("non-existent file"); - assertNotNull(result); - } - - @Test - public void testMultipleRootDirectories() { - ResourceLocator resourceLocator = new ResourceLocator( - rootDir, getIntegrationtestResource("inttest_environment/dir") - ); - String result = resourceLocator.locate("file_in_dir.txt"); - assertNotNull(result); - assertTrue(new File(result).exists()); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/TemporaryImplicitWait.java b/helium-java/src/integrationtest/java/com/heliumhq/TemporaryImplicitWait.java deleted file mode 100644 index 0be3b0b..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/TemporaryImplicitWait.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.heliumhq; - -import static com.heliumhq.API.Config; - -public class TemporaryImplicitWait { - private double implicitWaitSecsBefore; - public TemporaryImplicitWait(double value) { - implicitWaitSecsBefore = Config.getImplicitWaitSecs(); - Config.setImplicitWaitSecs(value); - } - public void end() { - Config.setImplicitWaitSecs(implicitWaitSecsBefore); - } -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/api_impl/TextImplIT.java b/helium-java/src/integrationtest/java/com/heliumhq/api_impl/TextImplIT.java deleted file mode 100644 index 2775d62..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/api_impl/TextImplIT.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.inttest_api.BrowserAT; -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import org.junit.Test; -import org.openqa.selenium.By; -import org.openqa.selenium.WebElement; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -public class TextImplIT extends BrowserAT { - @Override - protected String getPage() { - return "inttest_text_impl.html"; - } - @Test - public void testEmptySearchTextXPath() { - String xpath = - new TextImpl(new WebDriverWrapper(driver)).getSearchTextXPath(); - List textElements = driver.findElements(By.xpath(xpath)); - List texts = new ArrayList(); - for (WebElement w : textElements) - texts.add(w.getAttribute("innerHTML")); - Collections.sort(texts); - assertEquals( - Arrays.asList("A paragraph", "A paragraph inside a div", - "Another paragraph inside the div"), - texts - ); - } -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/$IT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/$IT.java deleted file mode 100644 index 46bc205..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/$IT.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; - -import static com.heliumhq.API.$; - -public class $IT extends BrowserAT { - - @Override - protected String getPage() { - return "inttest_gui_elements.html"; - } - - @Test - public void testFindById() { - assertFindsEltWithId($("#checkBoxId"), "checkBoxId"); - } - - @Test - public void testFindByName() { - assertFindsEltWithId($("@checkBoxName"), "checkBoxId"); - } - - @Test - public void testFindByClass() { - assertFindsEltWithId($(".checkBoxClass"), "checkBoxId"); - } - - @Test - public void testFindByXPath() { - assertFindsEltWithId( - $("//input[@type=\"checkbox\" and @id=\"checkBoxId\"]"), - "checkBoxId" - ); - } - - @Test - public void testFindByCssSelector() { - assertFindsEltWithId($("input.checkBoxClass"), "checkBoxId"); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/APITestSuite.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/APITestSuite.java deleted file mode 100644 index 1a3147d..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/APITestSuite.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.heliumhq.inttest_api; - -import com.googlecode.junittoolbox.SuiteClasses; -import com.googlecode.junittoolbox.WildcardPatternSuite; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.runner.RunWith; -import org.openqa.selenium.WebDriver; - -import static com.heliumhq.inttest_api.BrowserAT.startBrowser; -import static com.heliumhq.API.killBrowser; - -@RunWith(WildcardPatternSuite.class) -@SuiteClasses("**/*IT.class") -public class APITestSuite { - - static WebDriver TEST_BROWSER = null; - - @BeforeClass - public static void setUpClass() { - TEST_BROWSER = startBrowser(); - } - - @AfterClass - public static void tearDownClass() { - if (TEST_BROWSER != null) - killBrowser(); - TEST_BROWSER = null; - } - -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/AlertAT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/AlertAT.java deleted file mode 100644 index 86f50c6..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/AlertAT.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.openqa.selenium.UnhandledAlertException; - -import static com.heliumhq.API.*; -import static com.heliumhq.util.System.isOSX; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; - -public abstract class AlertAT extends BrowserAT { - - private final static String UNHANDLED_ALERT_EXCEPTION_MSG = - "This command is not supported when an alert is present. To accept " + - "the alert (this usually corresponds to clicking 'OK') use `Alert()." + - "accept()`. To dismiss the alert (ie. 'cancel' it), use `Alert()." + - "dismiss()`. If the alert contains a text field, you can use " + - "write(...) to set its value. Eg.: `write('hi there!')`."; - - @Override - protected String getPage() { - return "inttest_alert.html"; - } - - public abstract String getLinkToOpenAlert(); - - public abstract String getExpectedAlertText(); - - public abstract String getExpectedAlertAcceptedResult(); - - public String getExpectedAlertDismissedResult() { - return getExpectedAlertAcceptedResult(); - } - - @Before - public void setUp() { - super.setUp(); - click(getLinkToOpenAlert()); - waitUntil(Alert().exists); - } - - @After - public void tearDown() { - if (Alert().exists()) - // We need to call .accept() instead of .dismiss() here to work - // around ChromeDriver bug 764: - // https://code.google.com/p/chromedriver/issues/detail?id=764 - Alert().accept(); - } - - @Test - public void testAlertExists() { - assertTrue(Alert().exists()); - } - - @Test - public void testAlertTextExists() { - assertTrue(Alert(getExpectedAlertText()).exists()); - } - - @Test - public void testAlertTextNotExists() { - assertFalse(Alert("Wrong text").exists()); - } - - @Test - public void testAlertText() { - assertEquals(getExpectedAlertText(), Alert().getText()); - } - - @Test - public void testAlertAccept() throws InterruptedException { - Alert().accept(); - expectResult(getExpectedAlertAcceptedResult()); - } - - @Test - public void testAlertDismiss() throws InterruptedException { - // Chrome driver on OSX does not support dismissing JS alerts. - // See: https://code.google.com/p/chromedriver/issues/detail?id=764 - assumeTrue(! (isOSX() && getTestBrowserName().equals("chrome"))); - Alert().dismiss(); - expectResult(getExpectedAlertDismissedResult()); - } - - @Test - public void testClickWithOpenAlertRaisesException() { - expectUnhandledAlertException(); - click("OK"); - } - - @Test - public void testPressWithOpenAlertRaisesException() { - expectUnhandledAlertException(); - press(ENTER); - } - - /** - * This method waits up to one second for the given result to appear. It - * should not be needed but Chrome sometimes returns from - * .accept()/.dismiss() before the JavaScript in inttest_alert.html has set - * the corresponding result. - */ - protected void expectResult(String expectedResult) - throws InterruptedException { - long ONE_SECOND = 1000; - long startTime = System.currentTimeMillis(); - while (System.currentTimeMillis() < startTime + ONE_SECOND) { - String actualResult = readResultFromBrowser(300); - if (actualResult.equals(expectedResult)) - return; - Thread.sleep(200); - } - assertEquals(expectedResult, readResultFromBrowser()); - } - - protected void expectUnhandledAlertException() { - expectedEx.expect(UnhandledAlertException.class); - expectedEx.expectMessage(UNHANDLED_ALERT_EXCEPTION_MSG); - } - - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/AlertIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/AlertIT.java deleted file mode 100644 index f6ba131..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/AlertIT.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.heliumhq.inttest_api; - -public class AlertIT extends AlertAT { - - @Override - public String getLinkToOpenAlert() { - return "Display alert"; - } - - @Override - public String getExpectedAlertText() { - return "Hello World!"; - } - - @Override - public String getExpectedAlertAcceptedResult() { - return "Alert displayed"; - } - -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/AriaIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/AriaIT.java deleted file mode 100644 index 0c883cf..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/AriaIT.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; - -import static com.heliumhq.API.Button; -import static com.heliumhq.API.TextField; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class AriaIT extends BrowserAT { - - protected String getPage() { - return "inttest_aria.html"; - } - - @Test - public void testAriaLabelButtonExists() { - assertTrue(Button("Close").exists()); - } - - @Test - public void testAriaLabelButtonIsEnabled() { - assertTrue(Button("Close").isEnabled()); - } - - @Test - public void testAriaLabelDisabledButtonIsEnabled() { - assertFalse(Button("Disabled Close").isEnabled()); - } - - @Test - public void testAriaLabelNonExistentButton() { - assertFalse(Button("This doesnt exist").exists()); - } - - @Test - public void testAriaLabelDivButtonExists() { - assertTrue(Button("Attach files").exists()); - } - - @Test - public void testAriaLabelDivButtonIsEnabled() { - assertTrue(Button("Attach files").isEnabled()); - } - - @Test - public void testAriaLabelDivDisabledButtonIsEnabled() { - assertFalse(Button("Disabled Attach files").isEnabled()); - } - - @Test - public void testAriaLabelSubmitButtonExists() { - assertTrue(Button("Submit").exists()); - } - - @Test - public void testAriaTextboxExists() { - assertTrue(TextField("Textbox").exists()); - } - - @Test - public void testAriaTextboxValue() { - assertEquals("Textbox value", TextField("Textbox").getValue()); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/BoundAlertReprIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/BoundAlertReprIT.java deleted file mode 100644 index 87c4561..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/BoundAlertReprIT.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertEquals; - -public class BoundAlertReprIT extends BrowserAT { - - @Override - protected String getPage() { - return "inttest_alert.html"; - } - - @Override @Before - public void setUp() { - super.setUp(); - click("Display alert"); - } - - @Test - public void testBoundAlertRepr() { - Alert alert = Alert(); - // Bind alert: - alert.getText(); - assertEquals("Alert(\"Hello World!\")", alert.toString()); - } - - @Test - public void testBoundAlertReprWithPartialSearchText() { - Alert alert = Alert("Hello"); - // Bind alert: - alert.getText(); - assertEquals("Alert(\"Hello World!\")", alert.toString()); - } - - @After - public void tearDown() { - Alert().accept(); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/BoundReprIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/BoundReprIT.java deleted file mode 100644 index 37bcf3e..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/BoundReprIT.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertEquals; - -public class BoundReprIT extends BrowserAT { - - @Override - protected String getPage() { - return "inttest_gui_elements.html"; - } - - @Test - public void testBound$Repr() { - $ bound$ = bind($("#checkBoxId")); - assertHtmlEltWithMultipleAttributesEquals( - "", - bound$.toString() - ); - } - - @Test - public void testBound$ReprLongContent() { - $ body = bind($("body")); - assertEquals("...", body.toString()); - } - - @Test - public void testBoundButtonRepr() { - Button boundButton = bind(Button("Enabled Button")); - assertEquals( - "", - boundButton.toString() - ); - } - - @Test - public void testBoundLinkReprNestedTag() { - Link link = bind(Link("Link with title")); - assertHtmlEltWithMultipleAttributesEquals( - "...", link.toString() - ); - } - - @Test - public void testBoundReprDuplicateButton() { - assertEquals( - "[," + - " ," + - " ," + - " ]", - findAll(Button("Duplicate Button")).toString() - ); - } - - @Test - public void testBoundWindowRepr() { - Window boundWindow = bind(Window()); - assertEquals( - "Window(\"Test page for browser system tests\")", - boundWindow.toString() - ); - } - - @Test - public void testBoundWindowReprWithSearchText() { - Window boundWindow = bind(Window("Test page for")); - assertEquals( - "Window(\"Test page for browser system tests\")", - boundWindow.toString() - ); - } - - private H bind(H predicate) { - // Reading a property such as webElement waits for the element to exist - // and binds the predicate to it: - predicate.getWebElement(); - return predicate; - } - - private Window bind(Window predicate) { - // Reading a property such as the handle waits for the window to exist - // and binds the predicate to it: - predicate.getHandle(); - return predicate; - } - - private void assertHtmlEltWithMultipleAttributesEquals( - String expected, String actual - ) { - String[] expectedComponents = expected.split(">", 2); - String[] actualComponents = actual.split(">", 2); - String expStartTag = expectedComponents[0]; - String expRemainder = expectedComponents[1]; - String actStartTag = actualComponents[0]; - String actRemainder = actualComponents[1]; - String attributesRE = "[a-zA-Z]+=\"[^\"]+\""; - List expAttributes = findAllRegex(attributesRE, expStartTag); - List actAttributes = findAllRegex(attributesRE, actStartTag); - assertEquals( - new HashSet(expAttributes), - new HashSet(actAttributes) - ); - assertEquals(expRemainder, actRemainder); - } - - private List findAllRegex(String regex, String s) { - List result = new ArrayList(); - Matcher m = Pattern.compile(regex).matcher(s); - while (m.find()) - result.add(m.group()); - return result; - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/BrowserAT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/BrowserAT.java deleted file mode 100644 index 338a8dd..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/BrowserAT.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.heliumhq.inttest_api; - -import com.heliumhq.Environment; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeTrue; - -public abstract class BrowserAT { - - protected static WebDriver driver; - - @BeforeClass - public static void setUpClass() { - if (APITestSuite.TEST_BROWSER != null) { - driver = APITestSuite.TEST_BROWSER; - setDriver(driver); - } else - driver = startBrowser(); - } - - public static WebDriver startBrowser() { - return startBrowser(null); - } - - public static WebDriver startBrowser(String url) { - String testBrowserName = getTestBrowserName(); - if (testBrowserName.equals("chrome")) - return startChrome(url, true); - else if (testBrowserName.equals("ie")) { - assumeTrue(System.getProperty("os.name").startsWith("Windows")); - return startIE(url); - } else { - assert testBrowserName.equals("firefox"); - return startFirefox(url, true); - } - } - - protected static String getTestBrowserName() { - String result = System.getenv("TEST_BROWSER"); - return result != null ? result : "chrome"; - } - - @Before - public void setUp() { - goTo(getURL()); - } - - protected String getURL() { - return Environment.getITFileURL(getPage()); - } - - protected String getPage() { - throw new UnsupportedOperationException( - "To be overridden by subclasses." - ); - } - - protected String readResultFromBrowser() throws InterruptedException { - long THREE_SECONDS = 3000; - return readResultFromBrowser(THREE_SECONDS); - } - protected String readResultFromBrowser(long timeout) throws InterruptedException { - long startTime = System.currentTimeMillis(); - while (System.currentTimeMillis() < startTime + timeout) { - String result = - driver.findElement(By.id("result")).getAttribute("innerHTML"); - if (! result.equals("")) - return result; - Thread.sleep(200); - } - return ""; - } - - protected void assertFindsEltWithId(HTMLElement predicate, String id) { - assertEquals(id, predicate.getWebElement().getAttribute("id")); - } - - @AfterClass - public static void tearDownClass() { - if (driver != APITestSuite.TEST_BROWSER) - killBrowser(); - } - -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/ClickIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/ClickIT.java deleted file mode 100644 index 5fab756..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/ClickIT.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.heliumhq.inttest_api; - -import com.heliumhq.TemporaryImplicitWait; -import org.junit.Test; -import org.openqa.selenium.NoSuchElementException; - -import static com.heliumhq.API.click; -import static org.junit.Assert.assertEquals; - -public class ClickIT extends BrowserAT { - protected String getPage() { - return "inttest_click.html"; - } - @Test - public void testClick() throws InterruptedException { - click("Click me!"); - assertEquals("Success!", readResultFromBrowser()); - } - @Test(expected = NoSuchElementException.class) - public void testClickNonExistentElement() { - TemporaryImplicitWait tempImplicitWait = new TemporaryImplicitWait(1); - try { - click("Non-existent"); - } finally { - tempImplicitWait.end(); - } - } -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/ConfirmationDialogIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/ConfirmationDialogIT.java deleted file mode 100644 index cfa94a7..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/ConfirmationDialogIT.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.heliumhq.inttest_api; - -public class ConfirmationDialogIT extends AlertAT { - @Override - public String getLinkToOpenAlert() { - return "Ask for confirmation"; - } - - @Override - public String getExpectedAlertText() { - return "Proceed?"; - } - - @Override - public String getExpectedAlertAcceptedResult() { - return "Accepted"; - } - - @Override - public String getExpectedAlertDismissedResult() { - return "Dismissed"; - } -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/DoubleclickIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/DoubleclickIT.java deleted file mode 100644 index 956ddb9..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/DoubleclickIT.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; - -import static com.heliumhq.API.doubleclick; -import static org.junit.Assert.assertEquals; - -public class DoubleclickIT extends BrowserAT { - protected String getPage() { - return "inttest_doubleclick.html"; - } - @Test - public void testDoubleclick() throws InterruptedException { - doubleclick("Doubleclick here."); - assertEquals("Success!", readResultFromBrowser()); - } -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/DragIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/DragIT.java deleted file mode 100644 index 43fc92e..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/DragIT.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; -import org.openqa.selenium.By; -import org.openqa.selenium.Dimension; -import org.openqa.selenium.WebElement; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertEquals; - -public class DragIT extends BrowserAT { - - private WebElement dragTarget; - - @Override - public void setUp() { - super.setUp(); - dragTarget = driver.findElement(By.id("target")); - } - - @Override - protected String getPage() { - return "inttest_drag/default.html"; - } - - @Test - public void testDrag() throws InterruptedException { - drag("Drag me.", to(dragTarget)); - assertEquals("Success!", readResultFromBrowser()); - } - - @Test - public void testDragToPoint() throws InterruptedException { - org.openqa.selenium.Point location = dragTarget.getLocation(); - Dimension size = dragTarget.getSize(); - Point targetPoint = Point( - location.getX() + size.getWidth() / 2, - location.getY() + size.getHeight() / 2 - ); - drag("Drag me.", to(targetPoint)); - assertEquals("Success!", readResultFromBrowser()); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/FileUploadIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/FileUploadIT.java deleted file mode 100644 index 5f02377..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/FileUploadIT.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; - -import static com.heliumhq.API.*; -import static com.heliumhq.Environment.getIntegrationtestResource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -public class FileUploadIT extends BrowserAT { - - private final String fileToUpload = getIntegrationtestResource( - "inttest_file_upload/upload_this.png" - ); - - @Override - protected String getPage() { - return "inttest_file_upload/inttest_file_upload.html"; - } - - @Test - public void testNormalFileUploadIsNotTextField() { - assertFalse(TextField("Normal file upload").exists()); - } - - @Test - public void testAttachFileToNormalFileUpload() throws InterruptedException { - attachFile(fileToUpload, to("Normal file upload")); - assertEquals("Success!", readResultFromBrowser()); - } - - @Test - public void testAttachFileNoTo() throws InterruptedException { - attachFile(fileToUpload); - assertEquals("Success!", readResultFromBrowser()); - } - - @Test - public void testAttachFileToPoint() throws InterruptedException { - attachFile( - fileToUpload, - to(Text("Normal file upload").getTopLeft().withOffset(200, 10)) - ); - assertEquals("Success!", readResultFromBrowser()); - } - - @Test - public void testDragFileToAppearingDropArea() throws InterruptedException { - dragFile(fileToUpload, to("Drop the file here!")); - assertEquals("Success!", readResultFromBrowser()); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/FindAllIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/FindAllIT.java deleted file mode 100644 index 6d285d2..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/FindAllIT.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; -import org.openqa.selenium.StaleElementReferenceException; - -import java.util.Collections; -import java.util.List; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -public class FindAllIT extends BrowserAT { - - protected String getPage() { - return "inttest_gui_elements.html"; - } - - @Test - public void testFindAllDuplicateButton() { - assertEquals(4, findAll(Button("Duplicate Button")).size()); - } - - @Test - public void testFindAllDuplicateButtonToRightOf() { - assertEquals( - 2, findAll(Button("Duplicate Button", toRightOf("Row 1"))).size() - ); - } - - @Test - public void testFindAllDuplicateButtonBelowToRightOf() { - assertEquals( - 1, findAll(Button( - "Duplicate Button", below("Column 1"), toRightOf("Row 1") - )).size() - ); - } - - @Test - public void testFindAllNonExistentButton() { - assertEquals( - Collections.EMPTY_LIST, findAll(Button("Non-existent Button")) - ); - } - - @Test - public void testFindAllYieldsApiElements() { - assertTrue( - findAll(TextField("Example Text Field")).get(0) instanceof TextField - ); - } - - @Test - public void testInteractWithFoundElements() { - List allTFs = findAll(TextField()); - TextField exampleTF = null; - for (TextField textField : allTFs) { - String id; - try { - id = textField.getWebElement().getAttribute("id"); - } catch (StaleElementReferenceException e) { - // This may happen for found web elements in different iframes. - // TODO: Improve this, eg. by adding a .getId() property to - // TextField (/HTMLElement) which handles this problem. - continue; - } - if (id.equals("exampleTextFieldId")) - exampleTF = textField; - } - assertNotNull(exampleTF); - write("testInteractWithFoundElements", into(exampleTF)); - assertEquals( - "testInteractWithFoundElements", - TextField("Example Text Field").getValue() - ); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/GUIElementsIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/GUIElementsIT.java deleted file mode 100644 index e830695..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/GUIElementsIT.java +++ /dev/null @@ -1,491 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static com.heliumhq.API.*; -import static org.junit.Assert.*; - -public class GUIElementsIT extends BrowserAT { - @Override - protected String getPage() { - return "inttest_gui_elements.html"; - } - - @BeforeClass - public static void setUpClass() { - BrowserAT.setUpClass(); - // If a test does fail, ensure it happens quickly: - implicitWaitSecsBefore = Config.getImplicitWaitSecs(); - Config.setImplicitWaitSecs(.5); - } - private static double implicitWaitSecsBefore; - - @AfterClass - public static void tearDownClass() { - Config.setImplicitWaitSecs(implicitWaitSecsBefore); - BrowserAT.tearDownClass(); - } - - // Button tests: - @Test - public void testButtonExists() { - assertTrue(Button("Enabled Button").exists()); - } - @Test - public void testSubmitButtonExists() { - assertTrue(Button("Submit Button").exists()); - } - @Test - public void testSubmitButtonExistsLowerCase() { - assertTrue(Button("submit button").exists()); - } - @Test - public void testInputButtonExists() { - assertTrue(Button("Input Button").exists()); - } - @Test - public void testButtonNotExists() { - assertFalse(Button("Nonexistent Button").exists()); - } - @Test - public void testTextFieldDoesNotExistAsButton() { - assertFalse(Button("Example Text Field").exists()); - } - @Test - public void testEnabledButton() { - assertTrue(Button("Enabled Button").isEnabled()); - } - @Test - public void testDisabledButton() { - assertFalse(Button("Disabled Button").isEnabled()); - } - @Test - public void testButtonNoText() { - assertEquals(2, findAll(Button(toRightOf("Row 1"))).size()); - } - @Test - public void testDivButtonExists() { - assertTrue(Button("DIV with role=button").exists()); - } - @Test - public void testButtonTagButtonExists() { - assertTrue(Button("Button tag without type").exists()); - } - @Test - public void testSubmitButtonCanBeFoundByTitle() { - assertTrue(Button("submitButtonTitle").exists()); - } - - // TextField tests: - @Test - public void testTextFieldExists() { - assertTrue(TextField("Example Text Field").exists()); - } - @Test - public void testTextFieldLowerCaseExists() { - assertTrue(TextField("example text field").exists()); - } - @Test - public void testTextFieldInSecondColExists() { - assertTrue(TextField("Another Text Field").exists()); - } - @Test - public void testTextFieldNotExists() { - assertFalse(TextField("Nonexistent TextField").exists()); - } - @Test - public void testTextFieldIsEditableFalse() { - assertFalse(TextField("ReadOnly Text Field").isEditable()); - } - @Test - public void testTextFieldIsEditable() { - assertTrue(TextField("Example Text Field").isEditable()); - } - @Test - public void testTextFieldIsEnabled() { - assertTrue(TextField("Example Text Field").isEnabled()); - } - @Test - public void testTextFieldIsEnabledFalse() { - assertFalse(TextField("Disabled Text Field").isEnabled()); - } - @Test - public void testTextFieldValue() { - assertEquals("Lorem ipsum", TextField("Example Text Field").getValue()); - } - @Test - public void testTextFieldWithPlaceholderExists() { - assertTrue(TextField("Placeholder Text Field").exists()); - } - @Test - public void testTextFieldNoTypeSpecifiedWithPlaceholderExists() { - assertTrue(TextField("Placeholder Text Field without type").exists()); - } - @Test - public void testEmptyTextFieldValue() { - assertEquals("", TextField("Empty Text Field").getValue()); - } - @Test - public void testReadReadonlyTextField() { - assertEquals( - "This is read only", TextField("ReadOnly Text Field").getValue() - ); - } - @Test - public void testReadDisabledTextField() { - assertEquals( - "This is disabled", TextField("Disabled Text Field").getValue() - ); - } - @Test - public void testReadGermanTextField() { - assertEquals( - "Heizölrückstoßabdämpfung", TextField("Deutsch").getValue() - ); - } - @Test - public void testTextFieldInputTypeUpperCaseText() { - assertTrue(TextField("Input type=Text").exists()); - } - @Test - public void testWriteIntoLabelledTextField() { - write("Some text", into("Labelled Text Field")); - assertEquals("Some text", TextField("Labelled Text Field").getValue()); - } - @Test - public void testRequiredTextFieldMarkedWithAsteriskExists() { - assertTrue(TextField("Required Text Field").exists()); - } - @Test - public void testTextFieldLabelledByFreeText() { - assertEquals( - "TF labelled by free text", - TextField("Text field labelled by free text").getValue() - ); - } - @Test - public void testInputTypeTel() { - assertFindsEltWithId(TextField("Input type=tel"), "inputTypeTel"); - } - @Test - public void testTextFieldToRightOfTextField() { - assertFindsEltWithId( - TextField(toRightOf(TextField("Required Text Field"))), - "inputTypeTel" - ); - } - @Test - public void testContenteditableParagraph() { - assertFindsEltWithId( - TextField("contenteditable Paragraph"), "contenteditableParagraphId" - ); - } - @Ignore( - "Searches where the element is in an iframe different from the label " + - "are not yet implemented." - ) - @Test - public void testTextfieldInIframe() { - assertFindsEltWithId( - TextField("TextField in iframe"), "textfieldInIframeId" - ); - } - - // ComboBox tests: - @Test - public void testComboBoxExists() { - assertTrue(ComboBox("Drop Down List").exists()); - } - @Test - public void testComboBoxExistsLowerCase() { - assertTrue(ComboBox("drop down list").exists()); - } - @Test - public void testDropDownListIsEditableFalse() { - assertFalse(ComboBox("Drop Down List").isEditable()); - } - @Test - public void testEditableComboBoxIsEditable() { - assertTrue(ComboBox("Editable ComboBox").isEditable()); - } - @Test - public void testComboBoxOptions() { - List options = ComboBox("Drop Down List").getOptions(); - assertEquals( - options, Arrays.asList("Option One", "Option Two", "Option Three") - ); - } - @Test - public void testReadsValueOfComboBox() { - assertEquals("Option One", ComboBox("Drop Down List").getValue()); - } - @Test - public void testSelectValueFromComboBox() { - assertEquals("Option One", ComboBox("Drop Down List").getValue()); - select("Drop Down List", "Option Two"); - assertEquals("Option Two", ComboBox("Drop Down List").getValue()); - select(ComboBox("Drop Down List"), "Option Three"); - assertEquals("Option Three", ComboBox("Drop Down List").getValue()); - } - @Test - public void testComboBoxIdentifiedByValue() { - ComboBox comboBox = ComboBox("Select a value..."); - assertTrue(comboBox.exists()); - assertEquals("Select a value...", comboBox.getValue()); - assertFalse(comboBox.isEditable()); - assertEquals( - Arrays.asList("Select a value...", "Value 1"), comboBox.getOptions() - ); - } - @Test - public void testComboBoxPrecededByComboWithNameAsLabel() { - assertEquals( - "combo1", ComboBox("Combo1").getWebElement().getAttribute("id") - ); - } - - // CheckBox tests: - @Test - public void testCheckBoxExists() { - assertTrue(CheckBox("CheckBox").exists()); - } - @Test - public void testCheckBoxExistsLowerCase() { - assertTrue(CheckBox("checkbox").exists()); - } - @Test - public void testLeftHandSideCheckBoxExists() { - assertTrue(CheckBox("LHS CheckBox").exists()); - } - @Test - public void testCheckBoxNotExists() { - assertFalse(CheckBox("Nonexistent CheckBox").exists()); - } - @Test - public void testTextFieldDoesNotExistAsCheckBox() { - assertFalse(CheckBox("Empty Text Field").exists()); - } - @Test - public void testTickedCheckBoxExists() { - assertTrue(CheckBox("Ticked CheckBox").exists()); - } - @Test - public void testTickedCheckBoxIsEnabled() { - assertTrue(CheckBox("Ticked CheckBox").isEnabled()); - } - @Test - public void testRightLabelledCheckBoxExists() { - assertTrue(CheckBox("Right Labeled CheckBox").exists()); - } - @Test - public void testLeftLabelledCheckBoxExists() { - assertTrue(CheckBox("Left Labeled CheckBox").exists()); - } - @Test - public void testDisabledCheckBoxExists() { - assertTrue(CheckBox("Disabled CheckBox").exists()); - } - @Test - public void testTickedCheckBoxIsChecked() { - assertTrue(CheckBox("Ticked CheckBox").isChecked()); - } - @Test - public void testRightLabelledCheckBoxIsNotChecked() { - assertFalse(CheckBox("Right Labeled CheckBox").isChecked()); - } - @Test - public void testLeftLabelledCheckBoxIsNotChecked() { - assertFalse(CheckBox("Left Labeled CheckBox").isChecked()); - } - @Test - public void testDisabledCheckBoxIsNotChecked() { - assertFalse(CheckBox("Disabled CheckBox").isChecked()); - } - @Test - public void testUntickCheckBox() { - CheckBox tickedCheckBox = CheckBox("Ticked CheckBox"); - click(tickedCheckBox); - assertFalse(tickedCheckBox.isChecked()); - } - @Test - public void testDisabledCheckBoxIsNotEnabled() { - assertFalse(CheckBox("Disabled CheckBox").isEnabled()); - } - @Test - public void testCheckBoxEnclosedByLabel() { - assertFindsEltWithId( - CheckBox("CheckBox enclosed by label"), "checkBoxEnclosedByLabel" - ); - } - @Test - public void testCheckboxesLabelledByFreeText() { - assertTrue(CheckBox("unchecked").exists()); - assertTrue(CheckBox("checked").exists()); - assertTrue(CheckBox("checked").isChecked()); - assertFalse(CheckBox("unchecked").isChecked()); - } - - // RadioButton tests: - @Test - public void testFirstRadioButtonExists() { - assertTrue(RadioButton("RadioButton 1").exists()); - } - @Test - public void testFirstRadioButtonExistsLowerCase() { - assertTrue(RadioButton("radiobutton 1").exists()); - } - @Test - public void testSecondRadioButtonExists() { - assertTrue(RadioButton("RadioButton 2").exists()); - } - @Test - public void testLeftLabelledRadioButtonOneExists() { - assertTrue(RadioButton("Left Labeled RadioButton 1").exists()); - } - @Test - public void testLeftLabelledRadioButtonTwoExists() { - assertTrue(RadioButton("Left Labeled RadioButton 2").exists()); - } - @Test - public void testFirstRadioButtonIsSelected() { - assertTrue(RadioButton("RadioButton 1").isSelected()); - } - @Test - public void testSecondRadioButtonIsNotSelected() { - assertFalse(RadioButton("RadioButton 2").isSelected()); - } - @Test - public void testSelectSecondRadioButton() { - click(RadioButton("RadioButton 2")); - assertFalse(RadioButton("RadioButton 1").isSelected()); - assertTrue(RadioButton("RadioButton 2").isSelected()); - } - @Test - public void testRadioButtonNotExists() { - assertFalse(RadioButton("Nonexistent option").exists()); - } - @Test - public void testTextFieldIsNotARadioButton() { - assertFalse(RadioButton("Empty Text Field").exists()); - } - @Test - public void testRadioButtonsLabelledByFreeText() { - assertTrue(RadioButton("male").exists()); - assertTrue(RadioButton("female").exists()); - assertTrue(RadioButton("male").isSelected()); - assertFalse(RadioButton("female").isSelected()); - } - - // Text tests: - @Test - public void testTextExistsSubmitButton() { - assertTrue(Text("Submit Button").exists()); - } - @Test - public void testTextExistsSubmitButtonLowerCase() { - assertTrue(Text("submit button").exists()); - } - @Test - public void testTextExistsLinkWithTitle() { - assertTrue(Text("Link with title").exists()); - } - @Test - public void testTextExistsLinkWithTitleLowerCase() { - assertTrue(Text("link with title").exists()); - } - @Test - public void testTextWithLeadingNbspExists() { - assertTrue(Text("Text with leading  ").exists()); - } - @Test - public void testReadTextValue() { - assertEquals(Text(toRightOf(Text("EUR/USD"))).getValue(), "1.3487"); - } - @Test - public void testFreeTextNotSurroundedByTagsExists() { - assertTrue(Text("Free text not surrounded by tags").exists()); - } - @Test - public void testTextWithApostrophe() { - assertTrue(Text("Your email's been sent!").exists()); - } - @Test - public void testTextWithDoubleQuotes() { - assertTrue(Text("He said \"double quotes\".").exists()); - } - @Test - public void testTextWithSingleAndDoubleQuotes() { - assertTrue(Text("Single'quote. Double\"quote.").exists()); - } - @Test - public void testTextUppercaseUmlaut() { - assertTrue(Text("VERÖFFENTLICHEN").exists()); - } - - // Link tests: - @Test - public void testLinkExists() { - assertTrue(Link("Link").exists()); - } - @Test - public void testLinkWithTitleExists() { - assertTrue(Link("Link with title").exists()); - } - @Test - public void testLinkNoText() { - assertEquals(4, findAll(Link()).size()); - } - @Test - public void testSpanWithRoleLinkExistsAsLink() { - assertTrue(Link("Span with role=link").exists()); - } - @Test - public void testLinkHref() { - assertEquals("http://heliumhq.com/", Link("heliumhq.com").getHref()); - } - @Test - public void testLinkEmptyHref() { - assertEquals("", Link("Link with empty href").getHref()); - } - - // ListItem tests: - @Test - public void testListItemNoText() { - List allListItems = findAll( - ListItem(below("HTML Unordered List")) - ); - Set texts = new HashSet(); - for (ListItem listItem : allListItems) - texts.add(listItem.getWebElement().getText()); - assertEquals( - new HashSet(Arrays.asList("ListItem 1", "ListItem 2")), - texts - ); - } - - // Image tests: - @Test - public void testImageNotExists() { - assertFalse(Image("Non-existent").exists()); - } - @Test - public void testImageExists() { - assertTrue(Image("Dolphin").exists()); - } - - // Misc tests: - @Test - public void testTextFieldComboBoxWithSameName() { - TextField textField = TextField("Language"); - ComboBox comboBox = ComboBox("Language"); - assertNotEquals(textField.getY(), comboBox.getY()); - } -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/HighlightIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/HighlightIT.java deleted file mode 100644 index 8ff98d1..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/HighlightIT.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.heliumhq.inttest_api; - -import com.heliumhq.TemporaryImplicitWait; -import org.junit.Test; -import org.openqa.selenium.NoSuchElementException; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertTrue; - -public class HighlightIT extends BrowserAT { - - @Override - protected String getPage() { - return "inttest_gui_elements.html"; - } - - @Test - public void testHighlight() { - Button button = Button("Input Button"); - highlight(button); - checkIsHighlighted(button); - } - - @Test - public void testHighlightString() { - highlight("Text with id"); - checkIsHighlighted(Text("Text with id")); - } - - @Test(expected = NoSuchElementException.class) - public void testHighlightNonexistent() { - TemporaryImplicitWait tempImplicitWait = new TemporaryImplicitWait(0.5); - try { - highlight(Button("foo")); - } finally { - tempImplicitWait.end(); - } - } - - private void checkIsHighlighted(HTMLElement htmlElement) { - String style = htmlElement.getWebElement().getAttribute("style"); - assertTrue(style, style.contains("border: 2px solid red;")); - assertTrue(style, style.contains("font-weight: bold;")); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/HoverIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/HoverIT.java deleted file mode 100644 index 2d1c220..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/HoverIT.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.heliumhq.inttest_api; - -import com.heliumhq.TemporaryImplicitWait; -import org.junit.Before; -import org.junit.Test; -import org.openqa.selenium.NoSuchElementException; - -import java.awt.*; - -import static com.heliumhq.API.hover; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assume.assumeThat; - -public class HoverIT extends BrowserAT { - protected String getPage() { - return "inttest_hover.html"; - } - @Override - @Before - public void setUp() { - // This test fails if the mouse cursor happens to be over one of the - // links in inttest_hover.html. Move the mouse cursor to (0, 0) to - // prevent spurious test failures: - moveMouseCursorToOrigin(); - super.setUp(); - } - private void moveMouseCursorToOrigin() { - try { - new Robot().mouseMove(0, 0); - } catch (AWTError error) { - if (error.getMessage().contains("Assistive Technology not found")) - throw new RuntimeException( - "You need to install the Java Access Bridge! Please " + - "follow the instructions at http://docs.oracle.com/" + - "javase/accessbridge/2.0.2/setup.htm.", error - ); - else - throw error; - } catch (AWTException e) { - throw new RuntimeException(e); - } - } - @Test - public void testHoverOne() throws InterruptedException { - hover("Dropdown 1"); - String result = readResultFromBrowser(); - assertEquals( - "Got unexpected result " + result + ". Maybe the mouse cursor " + - "was over the browser window and interfered with the test?", - "Dropdown 1", result - ); - } - @Test - public void testHoverTwoConsecutively() throws InterruptedException { - assumeThat( - "This test fails on the CI server when no VNC viewer is watching." + - " When recording a video and inspecting afterwards, it appears " + - "that the test fails because the dropdown elements 'Item A', etc." + - " disappear too quickly after hovering 'Dropdown 2'.", - getTestBrowserName(), is(equalTo("firefox")) - ); - hover("Dropdown 2"); - hover("Item C"); - String result = readResultFromBrowser(); - assertEquals( - "Got unexpected result " + result + ". Maybe the mouse cursor " + - "was over the browser window and interfered with the test?", - "Dropdown 2 - Item C", result - ); - } - @Test - public void testHoverHidden() { - TemporaryImplicitWait temporaryWait = new TemporaryImplicitWait(1); - try { - NoSuchElementException expectedException = null; - try { - hover("Item C"); - } catch (NoSuchElementException e) { - expectedException = e; - } - assertNotNull( - "Didn't receive expected NoSuchElementException. Maybe the " + - "mouse cursor was over the browser window and interfered " + - "with the test?", expectedException - ); - } finally { - temporaryWait.end(); - } - } -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/Html5DragIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/Html5DragIT.java deleted file mode 100644 index f41c896..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/Html5DragIT.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; -import org.openqa.selenium.By; - -import static com.heliumhq.API.drag; -import static com.heliumhq.API.to; -import static org.junit.Assert.assertEquals; - -public class Html5DragIT extends BrowserAT { - @Override - protected String getPage() { - return "inttest_drag/html5.html"; - } - @Test - public void testHtml5Drag() throws InterruptedException { - drag("Drag me.", to(driver.findElement(By.id("target")))); - assertEquals("Success!", readResultFromBrowser()); - } -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/IESSLIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/IESSLIT.java deleted file mode 100644 index 015388f..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/IESSLIT.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.heliumhq.inttest_api; - -import com.heliumhq.PythonServer; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -import static com.heliumhq.API.*; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeThat; - -public class IESSLIT extends BrowserAT { - - public static final int SSL_SERVER_PORT = 4443; - - private PythonServer sslServer; - - @Before - public void setUp() { - assumeThat(getTestBrowserName(), is(equalTo("ie"))); - sslServer = new PythonServer( - "src/integrationtest/python/helium_integrationtest/inttest_api/" + - "apitest_ie_ssl.py", - String.format("SSL server started on port %s.", SSL_SERVER_PORT) - ); - try { - sslServer.start(); - } catch (IOException e) { - throw new RuntimeException(e); - } - super.setUp(); - } - - @Override - protected String getURL() { - return String.format("https://localhost:%s", SSL_SERVER_PORT); - } - - @Test - public void testContinue() { - click("Continue to this website (not recommended)."); - assertTrue(Text("Directory listing").exists()); - } - - @After - public void tearDown() { - if (sslServer != null) - sslServer.stop(); - } - -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/IframeIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/IframeIT.java deleted file mode 100644 index dd596d8..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/IframeIT.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; - -import static com.heliumhq.API.getDriver; -import static com.heliumhq.API.Text; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class IframeIT extends BrowserAT { - @Override - protected String getPage() { - return "inttest_iframe/main.html"; - } - @Test - public void testTextInIframeExists() { - assertTrue(Text("This text is inside an iframe.").exists()); - } - @Test - public void testTextInNestedIframeExists() { - assertTrue(Text("This text is inside a nested iframe.").exists()); - } - @Test - public void testFindsElementInParentIframe() { - testTextInNestedIframeExists(); - // Now we're "focused" on the nested IFrame. Check that we can still - // find the element an the parent IFrame: - testTextInIframeExists(); - } - @Test - public void testAccessAttributesAcrossIframes() { - Text text = Text("This text is inside an iframe."); - assertEquals("This text is inside an iframe.", text.getValue()); - getDriver().switchTo().defaultContent(); - assertEquals("This text is inside an iframe.", text.getValue()); - } -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/ImplicitWaitIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/ImplicitWaitIT.java deleted file mode 100644 index 2cd4fcb..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/ImplicitWaitIT.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.heliumhq.inttest_api; - - -import com.heliumhq.TemporaryImplicitWait; -import org.junit.Test; -import org.openqa.selenium.NoSuchElementException; - -import static com.heliumhq.API.click; -import static org.junit.Assert.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.greaterThan; - -public class ImplicitWaitIT extends BrowserAT { - @Override - protected String getPage() { - return "inttest_implicit_wait.html"; - } - @Test - public void testClickTextImplicitWait() throws InterruptedException { - click("Click me!"); - long startTime = System.currentTimeMillis(); - click("Now click me!"); - long endTime = System.currentTimeMillis(); - assertEquals("Success!", readResultFromBrowser()); - assertThat(endTime - startTime, is(greaterThan(3000L))); - } - @Test(expected = NoSuchElementException.class) - public void testClickTextNoImplicitWait() { - TemporaryImplicitWait temporaryWait = new TemporaryImplicitWait(0); - try { - click("Non-existent"); - } finally { - temporaryWait.end(); - } - } - @Test(expected = NoSuchElementException.class) - public void testClickTextTooSmallImplicitWait() { - TemporaryImplicitWait temporaryWait = new TemporaryImplicitWait(1); - try { - click("Click me!"); - click("Now click me!"); - } finally { - temporaryWait.end(); - } - } -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/KillServiceAtExitAT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/KillServiceAtExitAT.java deleted file mode 100644 index 16de05a..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/KillServiceAtExitAT.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.heliumhq.inttest_api; - -import com.heliumhq.inttest_api.util.ProcessInfo; -import com.heliumhq.inttest_api.util.Processes; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static com.heliumhq.inttest_api.util.Processes.waitForProcessOutput; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; - -public abstract class KillServiceAtExitAT { - - private final static String BROWSER_STARTED_MSG = - KillServiceAtExitAT.class.getSimpleName() + - " successfully started the browser."; - - private List runningServicesBefore; - private List runningBrowsersBefore; - - @Test - public void testKillServiceAtExit() throws IOException, - InterruptedException { - startBrowserInSubProcess(); - assertEquals(Collections.EMPTY_LIST, getNewRunningServices()); - } - - /** - * Starts public static void main(...) below in a new process. - */ - private void startBrowserInSubProcess() throws IOException, - InterruptedException { - String classpath = System.getProperty("java.class.path"); - ProcessBuilder pb = new ProcessBuilder( - "java", "-cp", classpath, getClass().getCanonicalName(), - // Supply test class to let main(...) below access the - // implementation of startBrowser(). - getClass().getCanonicalName() - ); - pb.redirectErrorStream(true); - Process subProcess = pb.start(); - waitForProcessOutput(subProcess, BROWSER_STARTED_MSG); - subProcess.waitFor(); - } - - private List getNewRunningServices() throws IOException { - List result = getRunningServices(); - result.removeAll(runningServicesBefore); - return result; - } - - @Before - public void setUp() throws IOException { - runningServicesBefore = getRunningServices(); - runningBrowsersBefore = getRunningBrowsers(); - } - - @After - public void tearDown() throws IOException { - for (ProcessInfo service : getNewRunningServices()) - service.kill(); - for (ProcessInfo browser : getNewRunningBrowsers()) - browser.kill(); - } - - private List getNewRunningBrowsers() throws IOException { - List result = getRunningBrowsers(); - result.removeAll(runningBrowsersBefore); - return result; - } - - private List getRunningServices() throws IOException { - return getRunningProcesses(getServiceProcessNames()); - } - - private List getRunningBrowsers() throws IOException { - return getRunningProcesses(asList(getBrowserProcessName())); - } - - private List getRunningProcesses(List imageNames) - throws IOException { - List result = new ArrayList(); - for (ProcessInfo process : Processes.getRunningProcesses()) - if (imageNames.contains(process.getName())) - result.add(process); - return result; - } - - protected abstract List getServiceProcessNames(); - - protected abstract String getBrowserProcessName(); - - public static void main(String[] args) throws ClassNotFoundException, - NoSuchMethodException, IllegalAccessException, - InvocationTargetException, InstantiationException { - Class testClass = Class.forName(args[0]); - KillServiceAtExitAT testInstance = - (KillServiceAtExitAT) testClass.getConstructor().newInstance(); - testInstance.startBrowser(); - System.out.println(BROWSER_STARTED_MSG); - System.out.flush(); - System.exit(0); - } - - protected abstract void startBrowser(); - -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/KillServiceAtExitChromeIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/KillServiceAtExitChromeIT.java deleted file mode 100644 index 1735c82..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/KillServiceAtExitChromeIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.heliumhq.inttest_api; - -import java.io.IOException; -import java.util.List; -import org.junit.Ignore; - -import static com.heliumhq.API.startChrome; -import static com.heliumhq.util.System.isWindows; -import static com.heliumhq.inttest_api.BrowserAT.getTestBrowserName; -import static java.util.Arrays.asList; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assume.assumeThat; - -@Ignore("Fails on recent versions of Chrome") -public class KillServiceAtExitChromeIT extends KillServiceAtExitAT { - - @Override - public void testKillServiceAtExit() throws IOException, - InterruptedException { - assumeThat(getTestBrowserName(), is(equalTo("chrome"))); - super.testKillServiceAtExit(); - } - - protected List getServiceProcessNames() { - if (isWindows()) - return asList("chromedriver.exe"); - return asList("chromedriver"); - } - - protected String getBrowserProcessName() { - return "chrome" + (isWindows() ? ".exe" : ""); - } - - protected void startBrowser() { - startChrome(); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/KillServiceAtExitIEIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/KillServiceAtExitIEIT.java deleted file mode 100644 index 0502b81..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/KillServiceAtExitIEIT.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.heliumhq.inttest_api; - -import java.io.IOException; -import java.util.List; - -import static com.heliumhq.API.startIE; -import static com.heliumhq.util.System.isWindows; -import static com.heliumhq.inttest_api.BrowserAT.getTestBrowserName; -import static java.util.Arrays.asList; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assume.assumeThat; -import static org.junit.Assume.assumeTrue; - -public class KillServiceAtExitIEIT extends KillServiceAtExitAT { - - @Override - public void testKillServiceAtExit() throws IOException, - InterruptedException { - assumeThat(getTestBrowserName(), is(equalTo("ie"))); - assumeTrue(isWindows()); - super.testKillServiceAtExit(); - } - - protected List getServiceProcessNames() { - return asList("IEDriverServer.exe"); - } - - protected String getBrowserProcessName() { - return "iexplore.exe"; - } - - protected void startBrowser() { - startIE(); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/MultipleWindowIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/MultipleWindowIT.java deleted file mode 100644 index 239a45d..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/MultipleWindowIT.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.heliumhq.inttest_api; - -import com.heliumhq.Environment; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertTrue; - -public class MultipleWindowIT extends WindowIT { - /** - * The purpose of this IT is to run the same tests as WindowIT, but with an - * additional pop up window open. - */ - @BeforeClass - public static void setUpClass() { - WindowIT.setUpClass(); - goTo(Environment.getITFileURL("inttest_window/inttest_window.html")); - click("Click here to open a popup."); - waitUntil(Window("inttest_window - popup").exists); - } - - @Test - public void testPopupWindowExists() { - assertTrue(Window("inttest_window - popup").exists()); - } - - @Override - public void setUp() { - // Don't let super goTo(...). - } - - @AfterClass - public static void tearDownClass() { - String popupWindowHandle = Window("inttest_window - popup").getHandle(); - String mainWindowHandle = Window("inttest_window").getHandle(); - getDriver().switchTo().window(popupWindowHandle).close(); - getDriver().switchTo().window(mainWindowHandle); - WindowIT.tearDownClass(); - } -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/PointIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/PointIT.java deleted file mode 100644 index 09c1c8c..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/PointIT.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.heliumhq.API.*; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeThat; - -public class PointIT extends BrowserAT { - - @Override - protected String getPage() { - return "inttest_point.html"; - } - - @Override - public void setUp() { - assumeThat( - "This test currently fails because of a bug with Firefox 27.0.1 " + - "and Selenium 2.39.0:" + - "https://code.google.com/p/selenium/issues/detail?id=7005", - getTestBrowserName(), is(not(equalTo("firefox"))) - ); - super.setUp(); - } - - @Test - public void testTopLeft() { - assertIsInRange(Point(2, 3), Button("Button 1").getTopLeft(), 0, 1); - } - - private void assertIsInRange( - Point expected, Point actual, int deltaX, int deltaY - ) { - assertAround(expected.getX(), actual.getX(), deltaX); - assertAround(expected.getY(), actual.getY(), deltaY); - } - - private void assertAround(int expected, int actual, int delta) { - assertAround(expected, actual, delta, ""); - } - - private void assertAround( - int expected, int actual, int delta, String message - ) { - assertThat(message, actual, greaterThanOrEqualTo(expected - delta)); - assertThat(message, actual, lessThanOrEqualTo(expected + delta)); - } - - @Test - public void testClickTopLeft() throws InterruptedException { - click(Button("Button 1").getTopLeft()); - assertResultIs("Button 1 clicked at offset (0, 0).", 1, 1); - } - - @Test - public void testClickPoint() throws InterruptedException { - click(Point(39, 13)); - assertResultIs("Button 1 clicked at offset (37, 10).", 0, 1); - } - - @Test - public void testClickTopLeftOffset() throws InterruptedException { - click(Button("Button 3").getTopLeft().withOffset(3, 4)); - assertResultIs("Button 3 clicked at offset (3, 4)."); - } - - @Test - public void testHoverTopLeft() throws InterruptedException { - hover(Button("Button 1").getTopLeft()); - assertResultIs("Button 1 hovered at offset (0, 0).", 1, 1); - } - - @Test - public void testHoverPoint() throws InterruptedException { - hover(Point(39, 13)); - assertResultIs("Button 1 hovered at offset (37, 10).", 0, 1); - } - - @Test - public void testHoverTopLeftOffset() throws InterruptedException { - hover(Button("Button 3").getTopLeft().withOffset(3, 4)); - assertResultIs("Button 3 hovered at offset (3, 4)."); - } - - @Test - public void testRightclickTopLeft() throws InterruptedException { - rightclick(Button("Button 1").getTopLeft()); - assertResultIs("Button 1 rightclicked at offset (0, 0).", 1, 1); - } - - @Test - public void testRightclickPoint() throws InterruptedException { - rightclick(Point(39, 13)); - assertResultIs("Button 1 rightclicked at offset (37, 10).", 0, 1); - } - - @Test - public void testRightclickTopLeftOffset() throws InterruptedException { - rightclick(Button("Button 3").getTopLeft().withOffset(3, 4)); - assertResultIs("Button 3 rightclicked at offset (3, 4)."); - } - - @Test - public void testDoubleclickTopLeft() throws InterruptedException { - doubleclick(Button("Button 1").getTopLeft()); - assertResultIs("Button 1 doubleclicked at offset (0, 0).", 1, 1); - } - - @Test - public void testDoubleclickPoint() throws InterruptedException { - doubleclick(Point(39, 13)); - assertResultIs("Button 1 doubleclicked at offset (37, 10).", 0, 1); - } - - @Test - public void testDoubleclickTopLeftOffset() throws InterruptedException { - doubleclick(Button("Button 3").getTopLeft().withOffset(3, 4)); - assertResultIs("Button 3 doubleclicked at offset (3, 4)."); - } - - private void assertResultIs(String expected) throws InterruptedException { - assertResultIs(expected, 0, 0); - } - - private void assertResultIs(String expected, int deltaX, int deltaY) - throws InterruptedException { - String actual = readResultFromBrowser(); - String expectedOffset = extractOffset(expected); - String actualOffset = extractOffset(actual); - int expectedX = extractOffsetX(expectedOffset); - int expectedY = extractOffsetY(expectedOffset); - int actualX = extractOffsetX(actualOffset); - int actualY = extractOffsetY(actualOffset); - assertAround(expectedX, actualX, deltaX); - assertAround(expectedY, actualY, deltaY); - assertAround( - expectedX, actualX, deltaX, - String.format( - "Offset (%s, %s) is not in expected range (%s+-%s, %s+-%s)", - actualX, actualY, expectedX, deltaX, expectedY, deltaY - ) - ); - assertAround( - expectedY, actualY, deltaY, - String.format( - "Offset (%s, %s) is not in expected range (%s+-%s, %s+-%s)", - actualX, actualY, expectedX, deltaX, expectedY, deltaY - ) - ); - String expectedPrefix = expected.split(expectedOffset)[0]; - String expectedSuffix = expected.split(expectedOffset)[1]; - String actualPrefix = actual.split(actualOffset)[0]; - String actualSuffix = actual.split(actualOffset)[1]; - assertEquals(expectedPrefix, actualPrefix); - assertEquals(expectedSuffix, actualSuffix); - } - - private String extractOffset(String resultInBrowser) { - Pattern p = Pattern.compile("(\\([^,]+, [^\\)]+\\))"); - Matcher m = p.matcher(resultInBrowser); - assertTrue(resultInBrowser, m.find()); - return m.group(1); - } - - private int extractOffsetX(String offset) { - return Integer.parseInt(offset.substring(1, offset.indexOf(','))); - } - - private int extractOffsetY(String offset) { - return Integer.parseInt( - offset.substring(offset.indexOf(", ") + 2, offset.length() - 1) - ); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/PressIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/PressIT.java deleted file mode 100644 index e5dead9..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/PressIT.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; - -import static com.heliumhq.API.SHIFT; -import static com.heliumhq.API.TextField; -import static com.heliumhq.API.press; -import static org.junit.Assert.assertEquals; - -public class PressIT extends BrowserAT { - - @Override - protected String getPage() { - return "inttest_write.html"; - } - - @Test - public void testPressSingleCharacter() { - press("a"); - assertEquals("a", TextField("Autofocus text field").getValue()); - } - - @Test - public void testPressUpperCaseCharacter() { - press("A"); - assertEquals("A", TextField("Autofocus text field").getValue()); - } - - @Test - public void testPressShiftPlusLowerCaseCharacter() { - press(SHIFT + "a"); - assertEquals("A", TextField("Autofocus text field").getValue()); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/PromptIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/PromptIT.java deleted file mode 100644 index 79981d4..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/PromptIT.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.heliumhq.inttest_api; - -import com.heliumhq.TemporaryImplicitWait; -import org.junit.Test; -import org.openqa.selenium.NoSuchElementException; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertEquals; - -public class PromptIT extends AlertAT { - - @Override - public String getLinkToOpenAlert() { - return "Prompt for value"; - } - - @Override - public String getExpectedAlertText() { - return "Please enter a value"; - } - - @Override - public String getExpectedAlertAcceptedResult() { - return "Value entered: "; - } - - @Test - public void testWriteValue() throws InterruptedException { - write("1"); - Alert().accept(); - expectResult("Value entered: 1"); - } - - @Test - public void testWriteIntoLabelRaisesException() { - expectUnhandledAlertException(); - write("3", into("Please enter a value")); - } - - @Test - public void testWriteIntoTextFieldRaisesException() { - expectUnhandledAlertException(); - write("4", into(TextField("Please enter a value"))); - } - - @Test - public void testWriteIntoNonExistentLabelRaisesException() { - expectUnhandledAlertException(); - write("5", into("Please enter a value")); - } - - @Test - public void testWriteIntoAlert() throws InterruptedException { - write("7", into(Alert())); - Alert().accept(); - expectResult("Value entered: 7"); - } - - @Test - public void testWriteIntoLabelledAlert() throws InterruptedException { - write("8", into(Alert(getExpectedAlertText()))); - Alert().accept(); - expectResult("Value entered: 8"); - } - - @Test(expected = NoSuchElementException.class) - public void testWriteIntoNonExistentAlert() { - TemporaryImplicitWait temporaryWait = new TemporaryImplicitWait(1); - try { - write("8", into(Alert("Non-existent"))); - } finally { - temporaryWait.end(); - } - } - -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/RightclickIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/RightclickIT.java deleted file mode 100644 index eedbd17..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/RightclickIT.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Ignore; -import org.junit.Test; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertEquals; - -public class RightclickIT extends BrowserAT { - protected String getPage() { - return "inttest_rightclick.html"; - } - @Test - public void testSimpleRightclick() throws InterruptedException { - rightclick("Perform a normal rightclick here."); - assertEquals("Normal rightclick performed.", readResultFromBrowser()); - } - @Test - public void testRightClickSelectNormalItem() throws InterruptedException { - rightclick("Rightclick here for context menu."); - click("Normal item"); - assertEquals("Normal item selected.", readResultFromBrowser()); - } - @Ignore("This test is too unstable.") @Test - public void testRightClickSelectSubItem() throws InterruptedException { - rightclick("Rightclick here for context menu."); - hover("Item with sub items"); - click("Sub item 1"); - assertEquals("Sub item 1 selected.", readResultFromBrowser()); - } -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/ScrollIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/ScrollIT.java deleted file mode 100644 index 07a8b95..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/ScrollIT.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.After; -import org.junit.Test; -import org.openqa.selenium.JavascriptExecutor; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertEquals; - -public class ScrollIT extends BrowserAT { - protected String getPage() { - return "inttest_scroll.html"; - } - @Test - public void testScrollUpWhenAtTopOfPage() { - scrollUp(); - assertScrollPositionEquals(0, 0); - } - @Test - public void testScrollDown() { - scrollDown(); - assertScrollPositionEquals(0, 100); - } - @Test - public void testScrollDownThenUp() { - scrollDown(); - scrollUp(); - assertScrollPositionEquals(0, 0); - } - @Test - public void testScrollDownTwiceThenUp() { - scrollDown(175); - scrollUp(100); - assertScrollPositionEquals(0, 75); - } - @Test - public void testScrollLeftWhenAtStartOfPage() { - scrollLeft(); - assertScrollPositionEquals(0, 0); - } - @Test - public void testScrollRight() { - scrollRight(); - assertScrollPositionEquals(100, 0); - } - @Test - public void testScrollRightThenLeft() { - scrollRight(); - scrollLeft(); - assertScrollPositionEquals(0, 0); - } - @Test - public void testScrollRightTwiceThenLeft() { - scrollRight(175); - scrollLeft(100); - assertScrollPositionEquals(75, 0); - } - - @After - public void tearDown() { - // Recent versions of Chrome(Driver) don't reset the scroll position - // when reloading the page. Force-reset it: - ((JavascriptExecutor) driver).executeScript("window.scrollTo(0, 0);"); - } - - private void assertScrollPositionEquals(long x, long y) { - JavascriptExecutor jsExecutor = (JavascriptExecutor) getDriver(); - long scrollPositionX = (Long) jsExecutor.executeScript( - "return window.pageXOffset || " + - "document.documentElement.scrollLeft || " + - "document.body.scrollLeft" - ); - assertEquals(x, scrollPositionX); - long scrollPositionY = (Long) jsExecutor.executeScript( - "return window.pageYOffset || " + - "document.documentElement.scrollTop || " + - "document.body.scrollTop;" - ); - assertEquals(y, scrollPositionY); - } -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/StartGoToIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/StartGoToIT.java deleted file mode 100644 index d61a693..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/StartGoToIT.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openqa.selenium.WebDriver; - -import java.net.MalformedURLException; - -import static com.heliumhq.API.goTo; -import static com.heliumhq.inttest_api.BrowserAT.startBrowser; -import static com.heliumhq.Environment.getITFileURL; -import static org.junit.Assert.assertEquals; - -public class StartGoToIT { - - private String url; - private WebDriver driver; - - @Before - public void setUp() { - url = getITFileURL("inttest_start_go_to.html"); - driver = null; - } - - @Test - public void testGoTo() throws MalformedURLException { - driver = startBrowser(); - goTo(url); - assertUrlEquals(url, driver.getCurrentUrl()); - } - - private void assertUrlEquals(String expected, String actual) throws - MalformedURLException { - expected = expected.toLowerCase().replace('\\', '/') - .replace("file:///", "file://") - .replace("file:///", "file://"); - actual = actual.toLowerCase().replace('\\', '/') - .replace("file:///", "file://") - .replace("file:///", "file://"); - assertEquals(expected, actual); - } - - @Test - public void testStartWithUrl() throws MalformedURLException { - driver = startBrowser(url); - assertUrlEquals(url, driver.getCurrentUrl()); - } - - @After - public void tearDown() { - if (driver != null) - driver.quit(); - } -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/TablesIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/TablesIT.java deleted file mode 100644 index 17f970a..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/TablesIT.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.heliumhq.inttest_api; - -import com.heliumhq.API; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertEquals; - -public class TablesIT extends BrowserAT { - - @Override - protected String getPage() { - return "inttest_tables.html"; - } - - @Test - public void test$BelowAbove() { - List secondTableCells = findAll( - $("table > tbody > tr > td", - below(Text("Table no. 2")), - above(Text("Table no. 3")) - ) - ); - assertEquals(9, secondTableCells.toArray().length); - assertEquals( - Arrays.asList( - "T2R1C1", "T2R1C2", "T2R1C3", - "T2R2C1", "T2R2C2", "T2R2C3", - "T2R3C1", "T2R3C2", "T2R3C3" - ), - convertToSortedStringArray(secondTableCells) - ); - } - - @Test - public void test$ReadTableColumn() { - List<$> emailCells = findAll( - $("table > tbody > tr > td", below("Email")) - ); - assertEquals(3, emailCells.toArray().length); - assertEquals( - Arrays.asList( - "email1@domain.com", "email2@domain.com", "email3@domain.com" - ), - convertToSortedStringArray(emailCells) - ); - } - - @Test - public void testTextBelowToLeftOf() { - assertEquals( - "Abdul", - Text(below("Name"), toLeftOf("email2@domain.com")).getValue() - ); - } - - private List convertToSortedStringArray(List<$> elements) { - List cellTexts = new ArrayList(); - for ($ cell : elements) - cellTexts.add(cell.getWebElement().getText()); - Collections.sort(cellTexts); - return cellTexts; - } - -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/UnboundReprIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/UnboundReprIT.java deleted file mode 100644 index 22c0928..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/UnboundReprIT.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertEquals; - -public class UnboundReprIT extends BrowserAT { - - @Override - protected String getPage() { - return "inttest_gui_elements.html"; - } - - @Test - public void testUnbound$Repr() { - assertEquals( - "$(\".cssClass\")", $(".cssClass").toString() - ); - } - - @Test - public void testUnbound$ReprBelow() { - assertEquals( - "$(\".cssClass\", below(\"Home\"))", - $(".cssClass", below("Home")).toString() - ); - } - - @Test - public void testUnboundTextRepr() { - assertEquals( - "Text(\"Hello World!\")", Text("Hello World!").toString() - ); - } - - @Test - public void testUnboundLinkRepr() { - assertEquals( - "Link(\"Download\")", Link("Download").toString() - ); - } - - @Test - public void testUnboundListItemRepr() { - assertEquals( - "ListItem(\"Home\")", ListItem("Home").toString() - ); - } - - @Test - public void testUnboundButtonRepr() { - assertEquals( - "Button(\"Home\")", Button("Home").toString() - ); - } - - @Test - public void testUnboundImageRepr() { - assertEquals( - "Image(\"Logo\")", Image("Logo").toString() - ); - } - - @Test - public void testUnboundTextFieldRepr() { - assertEquals( - "TextField(\"File name\")", TextField("File name").toString() - ); - } - - @Test - public void testUnboundComboBoxRepr() { - assertEquals( - "ComboBox(\"Language\")", ComboBox("Language").toString() - ); - } - - @Test - public void testUnboundCheckBoxRepr() { - assertEquals( - "CheckBox(\"True?\")", CheckBox("True?").toString() - ); - } - - @Test - public void testUnboundRadioButtonRepr() { - assertEquals( - "RadioButton(\"Option A\")", RadioButton("Option A").toString() - ); - } - - @Test - public void testUnboundWindowRepr() { - assertEquals( - "Window(\"Main\")", Window("Main").toString() - ); - } - - @Test - public void testUnboundAlertRepr() { - assertEquals( - "Alert()", Alert().toString() - ); - } - - @Test - public void testUnboundAlertReprWithSearchText() { - assertEquals( - "Alert(\"Hello World\")", Alert("Hello World").toString() - ); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WaitUntilIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WaitUntilIT.java deleted file mode 100644 index 2695639..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WaitUntilIT.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; -import org.openqa.selenium.By; -import org.openqa.selenium.TimeoutException; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.support.ui.ExpectedCondition; - -import static com.heliumhq.API.*; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.openqa.selenium.support.ui.ExpectedConditions. - presenceOfElementLocated; - -public class WaitUntilIT extends BrowserAT { - - @Override - protected String getPage() { - return "inttest_wait_until.html"; - } - - @Test - public void testWaitUntilTextExists() { - click("Click me!"); - long startTime = System.currentTimeMillis(); - waitUntil(Text("Success!").exists); - long endTime = System.currentTimeMillis(); - assertThat(endTime - startTime, is(greaterThan(800L))); - } - - @Test - public void testWaitUntilPresenceOfElementLocated() { - click("Click me!"); - long startTime = System.currentTimeMillis(); - waitUntil(presenceOfElementLocated(By.id("result"))); - long endTime = System.currentTimeMillis(); - assertThat(endTime - startTime, is(greaterThan(800L))); - } - - @Test(expected = TimeoutException.class) - public void testWaitUntilLambdaExpires() { - ExpectedCondition FALSE = new ExpectedCondition() { - @Override - public Boolean apply(WebDriver input) { - return false; - } - }; - waitUntil(FALSE, timeoutSecs(1)); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WindowHandlingIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WindowHandlingIT.java deleted file mode 100644 index 1d203a3..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WindowHandlingIT.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.After; -import org.junit.Test; -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.support.ui.ExpectedCondition; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class WindowHandlingIT extends BrowserAT { - - private String mainWindowHandle; - - @Override - protected String getPage() { - return "inttest_window_handling/main.html"; - } - - @Test - public void testWriteWritesInActiveWindow() { - write("Main window"); - assertEquals("Main window", getValue("mainTextField")); - openPopup(); - write("Popup"); - assertEquals("Popup", getValue("popupTextField")); - } - - @Test - public void testWriteSearchesInActiveWindow() { - write("Main window", into("Text field")); - assertEquals("Main window", getValue("mainTextField")); - openPopup(); - write("Popup", into("Text field")); - assertEquals("Popup", getValue("popupTextField")); - } - - @Test - public void testSwitchToSearchTextField() { - write("Main window", into("Text field")); - assertEquals("Main window", TextField("Text field").getValue()); - openPopup(); - write("Popup", into("Text field")); - assertEquals("Popup", TextField("Text field").getValue()); - switchTo("inttest_window_handling - Main"); - assertEquals("Main window", TextField("Text field").getValue()); - } - - @Test - public void testHandlesClosedWindowGracefully() { - openPopup(); - getDriver().close(); - boolean isBackInMainWindow = Link("Open popup").exists(); - assertTrue(isBackInMainWindow); - } - - @Test - public void testSwitchToAfterWindowClosed() { - openPopup(); - getDriver().close(); - switchTo("inttest_window_handling - Main"); - } - - public void setUp() { - super.setUp(); - mainWindowHandle = driver.getWindowHandle(); - } - - @After - public void tearDown() { - for (String windowHandle : driver.getWindowHandles()) { - if (! windowHandle.equals(mainWindowHandle)) { - driver.switchTo().window(windowHandle); - driver.close(); - driver.switchTo().window(mainWindowHandle); - } - } - } - - private String getValue(String elementId) { - return driver.findElement(By.id(elementId)).getAttribute("value"); - } - - private void openPopup() { - click("Open popup"); - waitUntil(isInPopup); - } - - private ExpectedCondition isInPopup = - new ExpectedCondition() { - public Boolean apply(WebDriver driver) { - String title = driver.getTitle(); - return title.equals("inttest_window_handling - Popup"); - } - }; - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WindowHandlingOnStartBrowserIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WindowHandlingOnStartBrowserIT.java deleted file mode 100644 index 8563d89..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WindowHandlingOnStartBrowserIT.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Before; -import org.junit.Test; - -import static com.heliumhq.API.Text; -import static org.junit.Assert.assertTrue; - -public class WindowHandlingOnStartBrowserIT extends BrowserAT { - - @Override - protected String getPage() { - return "inttest_window_handling/main_immediate_popup.html"; - } - - @Test - public void testSwitchesToPopup() { - assertTrue(Text("In popup.").exists()); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WindowIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WindowIT.java deleted file mode 100644 index bea4170..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WindowIT.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; - -import static com.heliumhq.API.Window; -import static com.heliumhq.util.StringUtils.isEmpty; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -public class WindowIT extends BrowserAT { - - @Override - protected String getPage() { - return "inttest_window/inttest_window.html"; - } - - @Test - public void testWindowExists() { - assertTrue(Window("inttest_window").exists()); - } - - @Test - public void testWindowNotExists() { - assertFalse(Window("non-existent").exists()); - } - - @Test - public void testNoArgWindowExists() { - assertTrue(Window().exists()); - } - - @Test - public void testHandle() { - String handle = Window("inttest_window").getHandle(); - assertFalse(handle, isEmpty(handle)); - } - - @Test - public void testTitle() { - assertEquals("inttest_window", Window("inttest_window").getTitle()); - } -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WriteIT.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WriteIT.java deleted file mode 100644 index f4db4af..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/WriteIT.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.heliumhq.inttest_api; - -import org.junit.Test; - -import static com.heliumhq.API.*; -import static org.junit.Assert.assertEquals; - -public class WriteIT extends BrowserAT { - - @Override - protected String getPage() { - return "inttest_write.html"; - } - - @Test - public void testWrite() { - write("Hello World!"); - assertEquals( - "Hello World!", TextField("Autofocus text field").getValue() - ); - } - - @Test - public void testWriteInto() { - write("Hi there!", into("Normal text field")); - assertEquals("Hi there!", TextField("Normal text field").getValue()); - } - - @Test - public void testWriteIntoTextFieldToRightOf() { - write("Hi there!", into(TextField(toRightOf("Normal text field")))); - assertEquals("Hi there!", TextField("Normal text field").getValue()); - } - -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/util/ProcessInfo.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/util/ProcessInfo.java deleted file mode 100644 index f1a9e0d..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/util/ProcessInfo.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.heliumhq.inttest_api.util; - -import java.io.IOException; - -import static com.heliumhq.util.System.isWindows; - -public class ProcessInfo { - - private final int id; - private final String name; - - public ProcessInfo(int id, String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public String getName() { - return name; - } - - public void kill() throws IOException { - String killCmd; - if (isWindows()) - killCmd = "taskkill /PID " + id; - else - killCmd = "kill " + id; - Runtime.getRuntime().exec(killCmd); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - ProcessInfo that = (ProcessInfo) o; - - if (id != that.id) return false; - if (name != null ? !name.equals(that.name) : that.name != null) - return false; - - return true; - } - - @Override - public int hashCode() { - int result = id; - result = 31 * result + (name != null ? name.hashCode() : 0); - return result; - } - - public String toString() { - return String.format("Process(%s, %s)", id, name); - } - -} diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/util/ProcessResult.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/util/ProcessResult.java deleted file mode 100644 index 48f08e1..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/util/ProcessResult.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.heliumhq.inttest_api.util; - -public class ProcessResult { - private final int returnCode; - private final String output; - public ProcessResult(int returnCode, String output) { - this.returnCode = returnCode; - this.output = output; - } - public int getReturnCode() { - return returnCode; - } - public String getOutput() { - return output; - } -} \ No newline at end of file diff --git a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/util/Processes.java b/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/util/Processes.java deleted file mode 100644 index 6ea7687..0000000 --- a/helium-java/src/integrationtest/java/com/heliumhq/inttest_api/util/Processes.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.heliumhq.inttest_api.util; - -import org.apache.commons.exec.CommandLine; -import org.apache.commons.exec.DefaultExecutor; -import org.apache.commons.exec.PumpStreamHandler; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; - -import static com.heliumhq.util.System.isWindows; -import static org.junit.Assert.assertTrue; - -public class Processes { - - public static List getRunningProcesses() throws IOException { - if (isWindows()) - return getRunningProcessesWindows(); - else - return getRunningProcessesUnixLike(); - } - - private static List getRunningProcessesWindows() - throws IOException { - List result = new ArrayList(); - Process p = Runtime.getRuntime().exec("tasklist.exe /fo csv /nh"); - BufferedReader input = - new BufferedReader(new InputStreamReader(p.getInputStream())); - String line; - while ((line = input.readLine()) != null) { - String[] columns = line.split("\""); - String name = columns[1]; - int pid = Integer.parseInt(columns[3]); - result.add(new ProcessInfo(pid, name)); - } - return result; - } - - private static List getRunningProcessesUnixLike() - throws IOException { - List result = new ArrayList(); - Process p = Runtime.getRuntime().exec("ps -e"); - BufferedReader input = - new BufferedReader(new InputStreamReader(p.getInputStream())); - String line; - // Skip to below header line: - while ((line = input.readLine()) != null) - if (line.trim().startsWith("PID")) - break; - while ((line = input.readLine()) != null) { - String[] columns = line.trim().split("\\s+"); - int pid = Integer.parseInt(columns[0]); - String name = columns[columns.length - 1]; - result.add(new ProcessInfo(pid, name)); - } - return result; - } - - public static void waitForProcessOutput(Process process, String output) - throws IOException { - BufferedReader stderrReader = new BufferedReader( - new InputStreamReader(process.getInputStream()) - ); - String actualOutput = ""; - int numLinesToRead = 10; // Don't wait forever - String line; - while (numLinesToRead > 0 && (line = stderrReader.readLine()) != null) { - actualOutput += line + "\n"; - if (line.equals(output)) - numLinesToRead = 0; - else - numLinesToRead --; - } - assertTrue(actualOutput, actualOutput.contains(output)); - } - - public static ProcessResult execCapturingOutput(String command) throws - IOException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - CommandLine commandLine = CommandLine.parse(command); - DefaultExecutor exec = new DefaultExecutor(); - PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); - exec.setStreamHandler(streamHandler); - // Don't throw exception if exit value != 0: - exec.setExitValues(null); - int returnCode = exec.execute(commandLine); - return new ProcessResult(returnCode, outputStream.toString()); - } - -} diff --git a/helium-java/src/main/assembly/linux.xml b/helium-java/src/main/assembly/linux.xml deleted file mode 100644 index a6e814c..0000000 --- a/helium-java/src/main/assembly/linux.xml +++ /dev/null @@ -1,30 +0,0 @@ - - linux - - zip - - ${project.artifactId}-${project.version} - - - ${parentBasedir}/src/main/resources/linux - - webdrivers/* - - . - 0755 - - - ${project.build.directory}/dist-base - . - - - - - heliumlib - - - \ No newline at end of file diff --git a/helium-java/src/main/assembly/macosx.xml b/helium-java/src/main/assembly/macosx.xml deleted file mode 100644 index 81b4b0e..0000000 --- a/helium-java/src/main/assembly/macosx.xml +++ /dev/null @@ -1,30 +0,0 @@ - - macosx - - zip - - ${project.artifactId}-${project.version} - - - ${parentBasedir}/src/main/resources/macosx - - webdrivers/* - - . - 0755 - - - ${project.build.directory}/dist-base - . - - - - - heliumlib - - - \ No newline at end of file diff --git a/helium-java/src/main/assembly/win.xml b/helium-java/src/main/assembly/win.xml deleted file mode 100644 index fdc512b..0000000 --- a/helium-java/src/main/assembly/win.xml +++ /dev/null @@ -1,26 +0,0 @@ - - win - - zip - - ${project.artifactId}-${project.version} - - - ${parentBasedir}/src/main/resources/win - - webdrivers/* - - . - 0755 - - - - - heliumlib - - - \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/API.java b/helium-java/src/main/java/com/heliumhq/API.java deleted file mode 100644 index 129813c..0000000 --- a/helium-java/src/main/java/com/heliumhq/API.java +++ /dev/null @@ -1,1949 +0,0 @@ -package com.heliumhq; - -import com.heliumhq.api_impl.*; -import org.openqa.selenium.Keys; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.ui.ExpectedCondition; - -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.List; - -import static com.heliumhq.api_impl.application_context.ApplicationContext. - getApplicationContext; - -/** - * Helium is a library that makes web automation as simple as giving - * instructions to a colleague, looking over his/her shoulder at a screen. - *

- * The public functions and classes of Helium are listed below. If you wish to - * use them in your scripts, all that is required is the following import: - * - * {@code - * import static com.heliumhq.API.*;} - */ -public class API { - - public static WebDriver startFirefox() { - return getAPIImpl().startFirefoxImpl(); - } - public static WebDriver startFirefox(boolean headless) { - return getAPIImpl().startFirefoxImpl(headless); - } - public static WebDriver startFirefox(String url) { - return getAPIImpl().startFirefoxImpl(url); - } - - /** - * Starts an instance of Firefox. You can optionally open a URL and/or start - * Firefox in headless mode. For instance: - * - * {@code - * startFirefox(); - * startFirefox("google.com"); - * startFirefox(true); - * startFirefox("google.com", true);} - * - * Helium does not automatically close the browser when Java shuts down. To - * terminate the browser at the end of your script, use the following - * command: - * - * {@code - * killBrowser();} - * - * @param url The URL to open. - * @return a Selenium {@link org.openqa.selenium.WebDriver} object - * representing the newly opened browser. - */ - public static WebDriver startFirefox(String url, boolean headless) { - return getAPIImpl().startFirefoxImpl(url, headless); - } - - public static WebDriver startChrome() { - return getAPIImpl().startChromeImpl(); - } - public static WebDriver startChrome(boolean headless) { - return getAPIImpl().startChromeImpl(headless); - } - public static WebDriver startChrome(String url) { - return getAPIImpl().startChromeImpl(url); - } - - /** - * Starts an instance of Google Chrome. You can optionally open a URL and/or - * start Chrome in headless mode. For instance: - * - * {@code - * startChrome(); - * startChrome("google.com"); - * startChrome(true); - * startChrome("google.com", true);} - * - * When Java shuts down, Helium cleans up all resources used for controlling - * the browser (such as the ChromeDriver process), but does not close the - * browser itself. To terminate the browser at the end of your script, use - * the following command: - * - * {@code - * killBrowser();} - * - * @param url The URL to open. - * @param headless Whether Chrome should be started in headless mode. - * Defaults to false. - * @return a Selenium {@link org.openqa.selenium.WebDriver} object - * representing the newly opened browser. - */ - public static WebDriver startChrome(String url, boolean headless) { - return getAPIImpl().startChromeImpl(url, headless); - } - - public static WebDriver startIE() { - return getAPIImpl().startIEImpl(); - } - - /** - * (Windows only) Starts an instance of Internet Explorer, optionally - * opening the specified URL. For instance: - * - * {@code - * startIE(); - * startIE("google.com");} - * - * When Java shuts down, Helium cleans up all resources used for controlling - * the browser (such as the IEDriverServer process), but does not close the - * browser itself. To terminate the browser at the end of your script, use - * the following command: - * - * {@code - * killBrowser();} - * - * @param url The URL to open. - * @return a Selenium {@link org.openqa.selenium.WebDriver} object - * representing the newly opened browser. - */ - public static WebDriver startIE(String url) { - return getAPIImpl().startIEImpl(url); - } - - /** - * Opens the specified URL in the current web browser window. For instance: - * - * {@code - * goTo("google.com");} - * - * @param url The URL to open. - */ - public static void goTo(String url) { - getAPIImpl().goToImpl(url); - } - - /** - * Sets the Selenium {@link org.openqa.selenium.WebDriver} used to execute - * Helium commands. See also {@link API#getDriver()}. - * - * @param driver The new WebDriver against which all future Helium commands - * will be issued. - */ - public static void setDriver(WebDriver driver) { - getAPIImpl().setDriverImpl(driver); - } - - /** - * Returns the Selenium {@link org.openqa.selenium.WebDriver} currently used - * by Helium to execute all commands. Each Helium command such as - * click("Login"); is translated to a sequence of Selenium - * commands that are issued to this driver. - * - * @return A {@link org.openqa.selenium.WebDriver} object. - */ - public static WebDriver getDriver() { - return getAPIImpl().getDriverImpl(); - } - - public static void write(String text) { - getAPIImpl().writeImpl(text); - } - - /** - * Types the given text into the active window. If parameter 'into' is - * given, writes the text into the text field or element identified by that - * parameter. Common examples of 'write' are: - * - * {@code - * write("Hello World!"); - * write("user12345", into("Username:")); - * write("Michael", into(Alert("Please enter your name")));} - * - * As you can see in the above examples, the function - * {@link API#into} is used to make the script more readable. - * - * @param text The text to be written. - * @param into The element to write into. - */ - public static void write(String text, String into) { - getAPIImpl().writeImpl(text, into); - } - public static void write(String text, WebElement into) { - getAPIImpl().writeImpl(text, into); - } - public static void write(String text, HTMLElement into) { - getAPIImpl().writeImpl(text, into.getImpl()); - } - public static void write(String text, Alert into) { - getAPIImpl().writeImpl(text, into.getImpl()); - } - - /** - * The purpose of the function 'into' is to make Helium scripts more - * readable. It simply returns the parameter passed into it. It lets you - * write: - * - * {@code - * write("user12345", into("Username:"));} - * - * instead of the much less readable: - * - * {@code - * write("user12345", "Username:");} - * - * @param element The element to return. - * @return The element parameter. - * @see com.heliumhq.API#to - */ - public static String into(String element) { - return element; - } - public static WebElement into(WebElement element) { - return element; - } - public static HTMLElement into(HTMLElement element) { - return element; - } - public static Alert into(Alert element) { - return element; - } - - /** - * Presses the given key or key combination. To press a normal letter key - * such as "a" simply call press for it: - * - * {@code - * press("a");} - * - * You can also simulate the pressing of upper case characters that way:: - * - * {@code - * press("A");} - * - * The special keys you can press are those given by Selenium's enum - * {@link org.openqa.selenium.Keys}. Helium makes all those keys available - * through its namespace, so you can just use them without having to refer - * to {@link org.openqa.selenium.Keys}. For instance, to press the Enter - * key: - * - * {@code - * press(ENTER);} - * - * To press several keys at the same time, concatenate them with - * +. For example, to press Control + a, call: - * - * {@code - * press(CONTROL + "a");} - * - * @param key The key or combination of keys to press. - */ - public static void press(CharSequence key) { - getAPIImpl().pressImpl(key); - } - - public final static CharSequence NULL = Keys.NULL; - public final static CharSequence CANCEL = Keys.CANCEL; - public final static CharSequence HELP = Keys.HELP; - public final static CharSequence BACK_SPACE = Keys.BACK_SPACE; - public final static CharSequence TAB = Keys.TAB; - public final static CharSequence CLEAR = Keys.CLEAR; - public final static CharSequence RETURN = Keys.RETURN; - public final static CharSequence ENTER = Keys.ENTER; - public final static CharSequence SHIFT = Keys.SHIFT; - public final static CharSequence LEFT_SHIFT = Keys.LEFT_SHIFT; - public final static CharSequence CONTROL = Keys.CONTROL; - public final static CharSequence LEFT_CONTROL = Keys.LEFT_CONTROL; - public final static CharSequence ALT = Keys.ALT; - public final static CharSequence LEFT_ALT = Keys.LEFT_ALT; - public final static CharSequence PAUSE = Keys.PAUSE; - public final static CharSequence ESCAPE = Keys.ESCAPE; - public final static CharSequence SPACE = Keys.SPACE; - public final static CharSequence PAGE_UP = Keys.PAGE_UP; - public final static CharSequence PAGE_DOWN = Keys.PAGE_DOWN; - public final static CharSequence END = Keys.END; - public final static CharSequence HOME = Keys.HOME; - public final static CharSequence LEFT = Keys.LEFT; - public final static CharSequence ARROW_LEFT = Keys.ARROW_LEFT; - public final static CharSequence UP = Keys.UP; - public final static CharSequence ARROW_UP = Keys.ARROW_UP; - public final static CharSequence RIGHT = Keys.RIGHT; - public final static CharSequence ARROW_RIGHT = Keys.ARROW_RIGHT; - public final static CharSequence DOWN = Keys.DOWN; - public final static CharSequence ARROW_DOWN = Keys.ARROW_DOWN; - public final static CharSequence INSERT = Keys.INSERT; - public final static CharSequence DELETE = Keys.DELETE; - public final static CharSequence SEMICOLON = Keys.SEMICOLON; - public final static CharSequence EQUALS = Keys.EQUALS; - public final static CharSequence NUMPAD0 = Keys.NUMPAD0; - public final static CharSequence NUMPAD1 = Keys.NUMPAD1; - public final static CharSequence NUMPAD2 = Keys.NUMPAD2; - public final static CharSequence NUMPAD3 = Keys.NUMPAD3; - public final static CharSequence NUMPAD4 = Keys.NUMPAD4; - public final static CharSequence NUMPAD5 = Keys.NUMPAD5; - public final static CharSequence NUMPAD6 = Keys.NUMPAD6; - public final static CharSequence NUMPAD7 = Keys.NUMPAD7; - public final static CharSequence NUMPAD8 = Keys.NUMPAD8; - public final static CharSequence NUMPAD9 = Keys.NUMPAD9; - public final static CharSequence MULTIPLY = Keys.MULTIPLY; - public final static CharSequence ADD = Keys.ADD; - public final static CharSequence SEPARATOR = Keys.SEPARATOR; - public final static CharSequence SUBTRACT = Keys.SUBTRACT; - public final static CharSequence DECIMAL = Keys.DECIMAL; - public final static CharSequence DIVIDE = Keys.DIVIDE; - public final static CharSequence F1 = Keys.F1; - public final static CharSequence F2 = Keys.F2; - public final static CharSequence F3 = Keys.F3; - public final static CharSequence F4 = Keys.F4; - public final static CharSequence F5 = Keys.F5; - public final static CharSequence F6 = Keys.F6; - public final static CharSequence F7 = Keys.F7; - public final static CharSequence F8 = Keys.F8; - public final static CharSequence F9 = Keys.F9; - public final static CharSequence F10 = Keys.F10; - public final static CharSequence F11 = Keys.F11; - public final static CharSequence F12 = Keys.F12; - public final static CharSequence META = Keys.META; - public final static CharSequence COMMAND = Keys.COMMAND; - - /** - * Clicks on the given element or point. Common examples are: - * - * {@code - * click("Sign in"); - * click(Button("OK")); - * click(Point(200, 300)); - * click(ComboBox("File type").getTopLeft().withOffset(50, 0));} - * - * @param element The element to click. - */ - public static void click(String element) { - getAPIImpl().clickImpl(element); - } - public static void click(WebElement element) { - getAPIImpl().clickImpl(element); - } - public static void click(HTMLElement element) { - getAPIImpl().clickImpl(element.getImpl()); - } - - /** - * @param point The point to click. - */ - public static void click(Point point) { - getAPIImpl().clickImpl(point); - } - - /** - * Performs a double click on the given element or point. Common examples - * are: - * - * {@code - * doubleclick("Double click here"); - * doubleclick(Image("Directories")); - * doubleclick(Point(200, 300)); - * click(ComboBox("File type").getTopLeft().withOffset(50, 0));} - * - * @param element The element to double click. - */ - public static void doubleclick(String element) { - getAPIImpl().doubleclickImpl(element); - } - public static void doubleclick(WebElement element) { - getAPIImpl().doubleclickImpl(element); - } - public static void doubleclick(HTMLElement element) { - getAPIImpl().doubleclickImpl(element.getImpl()); - } - - /** - * @param point The point to double click. - */ - public static void doubleclick(Point point) { - getAPIImpl().doubleclickImpl(point); - } - - /** - * Drags the given element or point to the given location. For example: - * - * {@code - * drag("Drag me!", to("Drop here."));} - * - * The dragging is performed by hovering the mouse cursor over - * element, pressing and holding the left mouse button, moving - * the mouse cursor over to, and then releasing the left mouse - * button again. - * - * @param element The element or point to drag. - * @param to The place to drop the dragged element. - */ - public static void drag(String element, String to) { - getAPIImpl().dragImpl(element, to); - } - public static void drag(String element, WebElement to) { - getAPIImpl().dragImpl(element, to); - } - public static void drag(String element, HTMLElement to) { - getAPIImpl().dragImpl(element, to.getImpl()); - } - public static void drag(String element, Point to) { - getAPIImpl().dragImpl(element, to); - } - public static void drag(WebElement element, String to) { - getAPIImpl().dragImpl(element, to); - } - public static void drag(WebElement element, WebElement to) { - getAPIImpl().dragImpl(element, to); - } - public static void drag(WebElement element, HTMLElement to) { - getAPIImpl().dragImpl(element, to.getImpl()); - } - public static void drag(WebElement element, Point to) { - getAPIImpl().dragImpl(element, to); - } - public static void drag(HTMLElement element, String to) { - getAPIImpl().dragImpl(element.getImpl(), to); - } - public static void drag(HTMLElement element, WebElement to) { - getAPIImpl().dragImpl(element.getImpl(), to); - } - public static void drag(HTMLElement element, HTMLElement to) { - getAPIImpl().dragImpl(element.getImpl(), to.getImpl()); - } - public static void drag(HTMLElement element, Point to) { - getAPIImpl().dragImpl(element.getImpl(), to); - } - public static void drag(Point element, String to) { - getAPIImpl().dragImpl(element, to); - } - public static void drag(Point element, WebElement to) { - getAPIImpl().dragImpl(element, to); - } - public static void drag(Point element, HTMLElement to) { - getAPIImpl().dragImpl(element, to.getImpl()); - } - public static void drag(Point element, Point to) { - getAPIImpl().dragImpl(element, to); - } - - /** - * Lets you find all occurrences of the given GUI element predicate. For - * instance, the following statement returns a list of all buttons with - * label "Open": - * - * {@code - * findAll(Button("Open"));} - * - * Other examples are: - * - * {@code - * findAll(Window()); - * findAll(TextField("Address line 1"));} - * - * The function returns a list of elements of the same type as the passed-in - * parameter. For instance, findAll(Button(...)); yields - * an object of type List<Button>. - * - * @param predicate Any {@link com.heliumhq.API.GUIElement}. - * @return A list of occurrences of the given predicate on the current page. - */ - public static List findAll(G predicate) { - List result = new ArrayList(); - for (Object impl : getAPIImpl().findAllImpl(predicate.getImpl())) - try { - Constructor constructor = (Constructor) predicate. - getClass().getDeclaredConstructor(impl.getClass()); - constructor.setAccessible(true); - result.add(constructor.newInstance(impl)); - } catch (Exception e) { - throw new RuntimeException(e); - } - return result; - } - - public static void scrollDown() { - getAPIImpl().scrollDownImpl(); - } - - /** - * Scrolls down the page. The distance scrolled can be given by parameter - * numPixels, and defaults to 100. - * - * @param numPixels The distance to scroll in pixels. - */ - public static void scrollDown(int numPixels) { - getAPIImpl().scrollDownImpl(numPixels); - } - - public static void scrollUp() { - getAPIImpl().scrollUpImpl(); - } - - /** - * Scrolls up the page. The distance scrolled can be given by parameter - * numPixels, and defaults to 100. - * - * @param numPixels The distance to scroll in pixels. - */ - public static void scrollUp(int numPixels) { - getAPIImpl().scrollUpImpl(numPixels); - } - - public static void scrollRight() { - getAPIImpl().scrollRightImpl(); - } - - /** - * Scrolls the page to the right. The distance scrolled can be given by - * parameter numPixels, and defaults to 100. - * - * @param numPixels The distance to scroll in pixels. - */ - public static void scrollRight(int numPixels) { - getAPIImpl().scrollRightImpl(numPixels); - } - - public static void scrollLeft() { - getAPIImpl().scrollLeftImpl(); - } - - /** - * Scrolls the page to the left. The distance scrolled can be given by - * parameter numPixels, and defaults to 100. - * - * @param numPixels The distance to scroll in pixels. - */ - public static void scrollLeft(int numPixels) { - getAPIImpl().scrollLeftImpl(numPixels); - } - - /** - * Hovers the mouse cursor over the given element or point. For example: - * - * {@code - * hover("File size"); - * hover(Button("OK")); - * hover(Link("Download")); - * hover(Point(200, 300)); - * hover(ComboBox("File type").getTopLeft().withOffset(50, 0));} - * - * @param element The element to hover. - */ - public static void hover(String element) { - getAPIImpl().hoverImpl(element); - } - public static void hover(WebElement element) { - getAPIImpl().hoverImpl(element); - } - public static void hover(HTMLElement element) { - getAPIImpl().hoverImpl(element.getImpl()); - } - - /** - * @param point The point to hover. - */ - public static void hover(Point point) { - getAPIImpl().hoverImpl(point); - } - - /** - * Performs a right click on the given element or point. For example: - * - * {@code - * rightclick("Something"); - * rightclick(Point(200, 300)); - * rightclick(Image("captcha"));} - * - * @param element The element to right click. - */ - public static void rightclick(String element) { - getAPIImpl().rightclickImpl(element); - } - public static void rightclick(WebElement element) { - getAPIImpl().rightclickImpl(element); - } - public static void rightclick(HTMLElement element) { - getAPIImpl().rightclickImpl(element.getImpl()); - } - - /** - * @param point The point to right click. - */ - public static void rightclick(Point point) { - getAPIImpl().rightclickImpl(point); - } - - /** - * Selects a value from a combo box. For example: - * - * {@code - * select("Language", "English"); - * select(ComboBox("Language"), "English");} - * - * @param comboBox The combo box whose value should be changed. - * @param value The visible value of the combo box to be selected. - */ - public static void select(String comboBox, String value) { - getAPIImpl().selectImpl(comboBox, value); - } - public static void select(ComboBox comboBox, String value) { - getAPIImpl().selectImpl(comboBox.getImpl(), value); - } - - /** - * Simulates the dragging of a file from the computer over the browser - * window and dropping it over the given element. This allows, for example, - * to attach files to emails in Gmail: - * - * {@code - * click("COMPOSE"); - * write("example@gmail.com", into("To")); - * write("Email subject", into("Subject")); - * dragFile("C:\\Documents\\notes.txt", to("Drop files here"));} - * - * As you can see in the above example, the function {@link API#to} is used - * to make the script more readable. - * - * @param filePath The path of the file to be attached. - * @param to The element to drop the dragged file on. - */ - public static void dragFile(String filePath, String to) { - getAPIImpl().dragFileImpl(filePath, to); - } - public static void dragFile(String filePath, WebElement to) { - getAPIImpl().dragFileImpl(filePath, to); - } - public static void dragFile(String filePath, HTMLElement to) { - getAPIImpl().dragFileImpl(filePath, to.getImpl()); - } - - /** - * The purpose of the function 'to' is to make Helium scripts more - * readable. It simply returns the parameter passed into it. It lets you - * write: - * - * {@code - * attachFile("c:/test.txt", to("Please select a file:"));} - * - * instead of the much less readable: - * - * {@code - * attachFile("c:/test.txt", "Please select a file:");} - * - * Similarly, to can be used with {@link API#dragFile}: - * - * {@code - * dragFile("C:\\Documents\\notes.txt", to("Drop files here"));} - * - * @param element The element to return. - * @return The element parameter. - * @see com.heliumhq.API#into - */ - public static String to(String element) { - return element; - } - public static WebElement to(WebElement element) { - return element; - } - public static HTMLElement to(HTMLElement element) { - return element; - } - public static Point to(Point element) { - return element; - } - - public static void attachFile(String filePath) { - getAPIImpl().attachFileImpl(filePath); - } - - /** - * Allows attaching a file to a file input element or point. For instance: - * - * {@code - * attachFile("c:/test.txt", to("Please select a file:"));} - * - * The file input element is identified by its label. If you omit the - * to parameter, then Helium attaches the file to the first - * file input element it finds on the page. - * - * As you can see in the above example, the function {@link API#to} is used - * to make the script more readable. - * - * @param filePath The path of the file to be attached. - * @param to The file input element to which to attach the file. - */ - public static void attachFile(String filePath, String to) { - getAPIImpl().attachFileImpl(filePath, to); - } - public static void attachFile(String filePath, WebElement to) { - getAPIImpl().attachFileImpl(filePath, to); - } - public static void attachFile(String filePath, HTMLElement to) { - getAPIImpl().attachFileImpl(filePath, to.getImpl()); - } - public static void attachFile(String filePath, Point to) { - getAPIImpl().attachFileImpl(filePath, to); - } - - /** - * Refreshes the current page. If an alert dialog is open, then Helium first - * closes it. - */ - public static void refresh() { - getAPIImpl().refreshImpl(); - } - - public static void waitUntil(ExpectedCondition condition) { - getAPIImpl().waitUntilImpl(condition); - } - public static void waitUntil( - ExpectedCondition condition, long timeoutSecs - ) { - getAPIImpl().waitUntilImpl(condition, timeoutSecs); - } - - /** - * Waits until the given condition becomes true. This is most commonly used - * to wait for an element to exist: - * - * {@code - * waitUntil(Text("Finished!").exists);} - * - * You can wait for any boolean property exposed by Helium's GUI elements - * this way. Here are some further examples: - * - * {@code - * waitUntil(Button("Download").isEnabled); - * waitUntil(Link("Proceed").exists); - * waitUntil(TextField("Credit card number").isEditable); - * ...} - * - * In general, waitUntil accepts any Selenium - * {@link org.openqa.selenium.support.ui.ExpectedCondition}. For instance, - * you can use {@link org.openqa.selenium.support.ui.ExpectedConditions#not( - *org.openqa.selenium.support.ui.ExpectedCondition)} - * to negate a condition: - * - * {@code - * import static org.openqa.selenium.support.ui.ExpectedConditions.not; - * ... - * waitUntil(not(Text("Processing...").exists));} - * - * The parameter timeoutSecs controls how long Helium waits for - * the condition to become true. If it does not become true within the given - * number of seconds, then a {@link org.openqa.selenium.TimeoutException} - * is thrown. - * - * intervalSecs specifies how long Helium waits in between - * consecutive checks of the condition. The default of 0.5 - * makes Helium check every 500ms. - * - * It is recommended to use the functions {@link API#timeoutSecs(long)} and - * {@link API#intervalSecs(double)} when specifying the time parameters for - * improved readability. For example: - * - * {@code - * waitUntil(Text("Done!").exists, timeoutSecs(15), intervalSecs(1));} - * - * @param condition The condition to wait for. - * @param timeoutSecs The timeout after which Helium aborts the wait, in - * seconds. Default: 10. - * @param intervalSecs The number of seconds Helium waits between - * consecutive checks of the given condition. - * Default: 0.5 (500 ms). - * @throws org.openqa.selenium.TimeoutException if the given condition isn't - * fulfilled within timeoutSecs. - */ - public static void waitUntil( - ExpectedCondition condition, long timeoutSecs, - double intervalSecs - ) { - getAPIImpl().waitUntilImpl(condition, timeoutSecs, intervalSecs); - } - - /** - * This function is used to improve the readability of Helium scripts that - * use {@link API#waitUntil}. It simply returns the parameter passed into - * it. It lets you write: - * - * {@code - * waitUntil(Text(...).exists, timeoutSecs(10));} - * - * instead of the less readable: - * - * {@code - * waitUntil(Text(...).exists, 10);} - * - * @param timeoutSecs The timeout to be passed into waitUntil. - * @return the timeoutSecs parameter passed when calling this function. - */ - public static long timeoutSecs(long timeoutSecs) { - return timeoutSecs; - } - /** - * Similarly to {@link API#timeoutSecs(long)}, this function is used to - * improve the readability of Helium scripts that use {@link API#waitUntil}. - * It simply returns the parameter passed into it. It lets you write: - * - * {@code - * waitUntil(Text(...).exists, timeoutSecs(10), intervalSecs(1));} - * - * instead of the less readable: - * - * {@code - * waitUntil(Text(...).exists, timeoutSecs(10), 1);} - * - * @param intervalSecs The wait interval to be passed into waitUntil. - * @return the intervalSecs parameter passed when calling this function. - */ - public static double intervalSecs(double intervalSecs) { - return intervalSecs; - } - - /** - * This class contains Helium's run-time configuration. To modify Helium's - * behaviour, simply set the properties of this class. For instance: - * - * {@code - * Config.setImplicitWaitSecs(0);} - */ - public static class Config { - private Config() {} - private static double implicitWaitSecs = 10; - /** - * Suppose you have a script that executes the following command: - * - * {@code - * click("Download");} - * - * If the "Download" element is not immediately available, then Helium - * by default waits up to 10 seconds before throwing a - * {@link org.openqa.selenium.NoSuchElementException}. This is useful in - * situations where the page takes slightly longer to load, or a GUI - * element only appears after a certain time (eg. after an AJAX - * request). - *

- * The function Config.setImplicitWaitSecs(...) lets you - * configure the timeout before Helium throws a - * {@link org.openqa.selenium.NoSuchElementException} when an element - * cannot be found. For instance, to increase the timeout to 30 seconds, - * you can call: - * - * {@code - * Config.setImplicitWaitSecs(30);} - * - * To disable Helium's implicit waits entirely, you can call: - * - * {@code - * Config.setImplicitWaitSecs(0);} - * - * Helium's implicit waits do not affect commands {@link API#findAll} or - * {@link GUIElement#exists()}. Note also that calling - * setImplicitWaitSecs(...) does not affect the underlying - * Selenium driver (see {@link API#getDriver()}). - *

- * For the best results, it is recommended to not use Selenium's - * .implicitlyWait(...) in conjunction with Helium. - * - * @param value The new timeout, in seconds, after which Helium - * throws - * {@link org.openqa.selenium.NoSuchElementException} - * when GUI elements cannot be found. - */ - public static void setImplicitWaitSecs(double value) { - implicitWaitSecs = value; - } - /** - * Returns the number of seconds (as a double) Helium waits - * before throwing a {@link org.openqa.selenium.NoSuchElementException} - * when a GUI element cannot be found. Please see - * {@link com.heliumhq.API.Config#setImplicitWaitSecs(double)} for a - * more comprehensive description of this feature. - */ - public static double getImplicitWaitSecs() { - return implicitWaitSecs; - } - } - - /** - * Abstract base class for all GUI elements identifiable by Helium: - *

- *

    - *
  • All {@link com.heliumhq.API.HTMLElement}s
  • - *
  • {@link API#Alert(java.lang.String)}
  • - *
  • {@link API#Window(java.lang.String)}
  • - *
- */ - public static abstract class GUIElement { - private final GUIElementImpl impl; - private GUIElement(GUIElementImpl impl) { - this.impl = impl; - } - /** - * Returns true if this GUI element exists, - * false otherwise. - */ - public boolean exists() { - return impl.exists(); - } - /** - * An {@link org.openqa.selenium.support.ui.ExpectedCondition} that can - * be used in conjunction with {@link com.heliumhq.API#waitUntil( - * org.openqa.selenium.support.ui.ExpectedCondition)} to wait for this - * GUI element to exist. For example, to wait until a certain text is - * shown on the page, one can use: - * - * {@code - * waitUntil(Text("Email sent").exists);} - * - * The same pattern can be used for Helium's other GUI elements: - * waitUntil(Button(...).exists);, - * waitUntil(CheckBox(...).exists);, - * waitUntil(Window(...).exists); etc. - */ - public final ExpectedCondition exists = - new ExpectedCondition() { - @Override - public Boolean apply(WebDriver input) { - return exists(); - } - }; - @Override - public String toString() { - return impl.toString(getClass().getSimpleName()); - } - GUIElementImpl getImpl() { - return impl; - } - } - - /** - * Abstract base class for HTML elements identifiable by Helium on a web - * page: - *

- *

    - *
  • {@link API#Text(java.lang.String, - * com.heliumhq.api_impl.SearchRegion...)}
  • - *
  • {@link API#Link(java.lang.String, - * com.heliumhq.api_impl.SearchRegion...)}
  • - *
  • {@link API#ListItem(java.lang.String, - * com.heliumhq.api_impl.SearchRegion...)}
  • - *
  • {@link API#Button(java.lang.String, - * com.heliumhq.api_impl.SearchRegion...)}
  • - *
  • {@link API#Image(java.lang.String, - * com.heliumhq.api_impl.SearchRegion...)}
  • - *
  • {@link API#TextField(java.lang.String, - * com.heliumhq.api_impl.SearchRegion...)}
  • - *
  • {@link API#ComboBox(java.lang.String, - * com.heliumhq.api_impl.SearchRegion...)}
  • - *
  • {@link API#CheckBox(java.lang.String, - * com.heliumhq.api_impl.SearchRegion...)}
  • - *
  • {@link API#RadioButton(java.lang.String, - * com.heliumhq.api_impl.SearchRegion...)}
  • - *
- */ - public static abstract class HTMLElement extends GUIElement { - private HTMLElement(HTMLElementImpl impl) { - super(impl); - } - /** - * Returns an int giving the width of this HTML element, in - * pixels. - */ - public int getWidth() { - return getImpl().getWidth(); - } - /** - * Returns an int giving the height of this HTML element, - * in pixels. - */ - public int getHeight() { - return getImpl().getHeight(); - } - /** - * Returns an int giving the x-coordinate of the top-left - * point of this UI element. - */ - public int getX() { - return getImpl().getX(); - } - /** - * Returns an int giving the y-coordinate of the top-left - * point of this UI element. - */ - public int getY() { - return getImpl().getY(); - } - /** - * Returns the top left corner of this element, as a - * {@link com.heliumhq.API.Point}. This point has exactly the - * coordinates given by this element's .getX() and - * .getY() properties. getTopLeft() is for - * instance useful for clicking at an offset of an element: - * - * {@code - * click(Button("OK").getTopLeft().withOffset(30, 15));} - */ - public Point getTopLeft() { - return getImpl().getTopLeft(); - } - /** - * Returns the Selenium {@link org.openqa.selenium.WebElement} - * corresponding to this element. - */ - public WebElement getWebElement() { - return getImpl().getWebElement(); - } - HTMLElementImpl getImpl() { - return (HTMLElementImpl) super.getImpl(); - } - } - - /** - * Switches to the given browser window. For example: - * - * {@code - * switchTo("Google");} - * - * This searches for a browser window whose title contains "Google", and - * activates it. - * - * If there are multiple windows with the same title, then you can use - * {@link API#findAll} to find all open windows, pick out the one you want - * and pass that to switchTo. For example, the following - * snippet switches to the first window in the list of open windows: - * - * {@code - * switchTo(findAll(Window()).get(0));} - * - * @param windowTitle The title of the window to switch to. - */ - public static void switchTo(String windowTitle) { - getAPIImpl().switchToImpl(windowTitle); - } - - /** - * @param window The window to switch to. - */ - public static void switchTo(Window window) { - getAPIImpl().switchToImpl(window.getImpl()); - } - - /** - * Closes the current browser with all associated windows and potentially - * open dialogs. Dialogs opened as a response to the browser closing (eg. - * "Are you sure you want to leave this page?") are also ignored and closed. - *

- * This function is most commonly used to close the browser at the end of an - * automation run: - * - * {@code - * startChrome(); - * ... - * // Close Chrome: - * killBrowser();} - */ - public static void killBrowser() { - getAPIImpl().killBrowserImpl(); - } - - /** - * Highlights the given element on the page by drawing a red rectangle - * around it. This is useful for debugging purposes. For example: - * - * {@code - * highlight("Helium"); - * highlight(Button("Sign in"));} - * - * @param element The element to highlight. - */ - public static void highlight(String element) { - getAPIImpl().highlightImpl(element); - } - public static void highlight(HTMLElement element) { - getAPIImpl().highlightImpl(element.getImpl()); - } - public static void highlight(WebElement element) { - getAPIImpl().highlightImpl(element); - } - - /** - * A jQuery-style selector for identifying HTML elements by ID, name, CSS - * class, CSS selector or XPath. For example: Say you have an element with - * ID "myId" on a web page, such as <div id="myId" .../>. - * Then you can identify this element using $ as follows: - * - * {@code - * $("#myId")} - * - * The parameter which you pass to $(...) is interpreted by - * Helium according to these rules: - * - *

    - *
  • If it starts with an @, then it identifies elements - * by HTML name. Eg. $("@btnName") identifies - * an element with name="btnName".
  • - *
  • If it starts with //, then Helium interprets it as - * an XPath.
  • - *
  • Otherwise, Helium interprets it as a CSS selector. This in - * particular lets you write $("#myId") to identify an - * element with id="myId", or $(".myClass") - * to identify elements with class="myClass".
  • - *
- * @param selector The selector used to identify the HTML element(s). - * @param searchRegion The search region to find the text in. - * See the documentation of {@link API#below}.* - */ - public static $ $(String selector, SearchRegion... searchRegion) { - return new $(getAPIImpl().$Impl(selector, searchRegion)); - } - - public static class $ extends HTMLElement { - private $($Impl impl) { - super(impl); - } - } - - /** - * Lets you identify any text or label on a web page. This is most useful - * for checking whether a particular text exists: - * - * {@code - * if (Text("Do you want to proceed?").exists()) - * click("Yes");} - * - * {@link com.heliumhq.API.Text} also makes it possible to read plain text - * data from a web page. For example, suppose you have a table of people's - * email addresses. Then you can read John's email addresses as follows: - * - * {@code - * Text(below("Email"), toRightOf("John")).getValue()} - * - * Similarly to below and toRightOf, the keyword - * parameters {@link API#above} and {@link API#toLeftOf} can be used to - * search for texts above and to the left of other web elements. - * - * @param text The text to identify. - * @param searchRegion The search region to find the text in. - * See the documentation of {@link API#below}. - */ - public static Text Text(String text, SearchRegion... searchRegion) { - return new Text(getAPIImpl().TextImpl(text, searchRegion)); - } - public static Text Text(SearchRegion... searchRegion) { - return new Text(getAPIImpl().TextImpl(searchRegion)); - } - public static class Text extends HTMLElement { - private Text(TextImpl impl) { - super(impl); - } - /** - * Returns the current value of this Text object, as a - * {@link java.lang.String}. - */ - public String getValue() { - return getImpl().getValue(); - } - TextImpl getImpl() { - return (TextImpl) super.getImpl(); - } - } - - /** - * Lets you identify a link on a web page. A typical usage of - * Link is: - * - * {@code - * click(Link("Sign in"));} - * - * You can also read a Link's properties. This is most - * typically used to check for a link's existence before clicking on it: - * - * {@code - * if (Link("Sign in").exists()) - * click(Link("Sign in"));} - * - * When there are multiple occurrences of a link on a page, you can - * disambiguate between them using {@link API#below}, {@link API#toRightOf}, - * {@link API#above} and {@link API#toLeftOf}. For instance: - * - * {@code - * click(Link("Block User", toRightOf("John Doe")));} - * - * @param text The link text or title. - * @param searchRegion The search region to find the link in. - * See the documentation of {@link API#below}. - */ - public static Link Link(String text, SearchRegion... searchRegion) { - return new Link(getAPIImpl().LinkImpl(text, searchRegion)); - } - public static Link Link(SearchRegion... searchRegion) { - return new Link(getAPIImpl().LinkImpl(searchRegion)); - } - public static class Link extends HTMLElement { - private Link(LinkImpl impl) { - super(impl); - } - /** - * Returns the URL of the page the link goes to, as a - * {@link java.lang.String}. If there is no value, null is returned. - */ - public String getHref() { - return ((LinkImpl)getImpl()).getHref(); - } - } - - /** - * Lets you identify a list item (HTML <li> element) on a - * web page. This is often useful for interacting with elements of a - * navigation bar: - * - * {@code - * click(ListItem("News Feed"));} - * - * In other cases such as an automated test, you might want to query the - * properties of a ListItem. For example, the following snippet - * checks whether a list item with text "List item 1" exists, and raises an - * error if not: - * - * {@code - * if (! ListItem("List item 1").exists()) - * throw new AssertionError("List item 1 does not exist");} - * - * When there are multiple occurrences of a list item on a page, you can - * disambiguate between them using the functions {@link API#below}, - * {@link API#toRightOf}, {@link API#above} and {@link API#toLeftOf}. - * For instance: - * {@code - * click(ListItem("List item 1", below("My first list:")));} - * - * @param text The text (label) of the list item. - * @param searchRegion The search region to find the list item in. - * See the documentation of {@link API#below}. - */ - public static ListItem ListItem(String text, SearchRegion... searchRegion) { - return new ListItem(getAPIImpl().ListItemImpl(text, searchRegion)); - } - public static ListItem ListItem(SearchRegion... searchRegion) { - return new ListItem(getAPIImpl().ListItemImpl(searchRegion)); - } - public static class ListItem extends HTMLElement { - private ListItem(ListItemImpl impl) { - super(impl); - } - } - - /** - * Lets you identify a button on a web page. A typical usage of - * Button is: - * - * {@code - * click(Button("Log In"));} - * - * Button also lets you read a button's properties. For - * example, the following snippet clicks button "OK" only if it exists: - * - * {@code - * if (Button("OK").exists()) - * click(Button("OK"));} - * - * When there are multiple occurrences of a button on a page, you can - * disambiguate between them using the functions {@link API#below}, - * {@link API#toRightOf}, {@link API#above} and {@link API#toLeftOf}. For - * instance: - * - * {@code - * click(Button("Log In", below(TextField("Password"))));} - * - * @param text The button label. - * @param searchRegion The search region to find the button in. - * See the documentation of {@link API#below}. - */ - public static Button Button(String text, SearchRegion... searchRegion) { - return new Button(getAPIImpl().ButtonImpl(text, searchRegion)); - } - public static Button Button(SearchRegion... searchRegion) { - return new Button(getAPIImpl().ButtonImpl(searchRegion)); - } - public static class Button extends HTMLElement { - private Button(ButtonImpl impl) { - super(impl); - } - /** - * Returns true if this button can currently be interacted - * with, false otherwise. - */ - public boolean isEnabled() { - return getImpl().isEnabled(); - } - /** - * An {@link org.openqa.selenium.support.ui.ExpectedCondition} that can - * be used in conjunction with {@link com.heliumhq.API#waitUntil( - * org.openqa.selenium.support.ui.ExpectedCondition)} to wait for this - * Button to become enabled. For example: - * - * {@code - * waitUntil(Button("Submit").isEnabled);} - */ - public final ExpectedCondition isEnabled = - new ExpectedCondition() { - @Override - public Boolean apply(WebDriver input) { - return isEnabled(); - } - }; - ButtonImpl getImpl() { - return (ButtonImpl) super.getImpl(); - } - } - - /** - * Lets you identify an image (HTML <img> element) on a - * web page. Typically, this is done via the image's alt text. For instance: - * - * {@code - * click(Image("Helium Logo"));} - * - * You can also query an image's properties. For example, the following - * snippet clicks on the image with alt text "Helium Logo" only if it - * exists: - * - * {@code - * if (Image("Helium Logo").exists()) - * click(Image("Helium Logo"));} - * - * When there are multiple occurrences of an image on a page, you can - * disambiguate between them using the functions {@link API#below}, - * {@link API#toRightOf}, {@link API#above} and {@link API#toLeftOf}. For - * instance: - * - * {@code - * click(Image("Helium Logo", toLeftOf(ListItem("Download"))));} - * - * @param alt The image's alt text. - * @param searchRegion The search region to find the image in. - * See the documentation of {@link API#below}. - */ - public static Image Image(String alt, SearchRegion... searchRegion) { - return new Image(getAPIImpl().ImageImpl(alt, searchRegion)); - } - public static Image Image(SearchRegion... searchRegion) { - return new Image(getAPIImpl().ImageImpl(searchRegion)); - } - public static class Image extends HTMLElement { - private Image(ImageImpl impl) { - super(impl); - } - } - - /** - * Lets you identify a text field on a web page. This is most typically done - * to read the value of a text field. For example: - * - * {@code - * TextField("First name").getValue()} - * - * This returns the value of the "First name" text field. If it is empty, - * the empty string "" is returned. - * - * When there are multiple occurrences of a text field on a page, you can - * disambiguate between them using the functions {@link API#below}, - * {@link API#toRightOf}, {@link API#above} and {@link API#toLeftOf}. For - * instance: - * - * {@code - * TextField("Address line 1", below("Billing Address:")).getValue()} - * - * @param label The label (human-visible name) of the text field. - * @param searchRegion The search region to find the text field in. - * See the documentation of {@link API#below}. - */ - public static TextField TextField( - String label, SearchRegion... searchRegion - ) { - return new TextField(getAPIImpl().TextFieldImpl(label, searchRegion)); - } - public static TextField TextField(SearchRegion... searchRegion) { - return new TextField(getAPIImpl().TextFieldImpl(searchRegion)); - } - public static class TextField extends HTMLElement { - private TextField(TextFieldImpl impl) { - super(impl); - } - /** - * Returns the current value of this text field, as a - * {@link java.lang.String}. If there is no value, "" is returned. - */ - public String getValue() { - return getImpl().getValue(); - } - /** - * Returns a boolean indicating whether this text field can - * currently be interacted with. - *

- * The difference between a text field being 'enabled' and 'editable' is - * mostly visual: If a text field is not enabled, it is usually greyed - * out, whereas if it is not editable it looks normal. See also - * {@link TextField#isEditable()}. - */ - public boolean isEnabled() { - return getImpl().isEnabled(); - } - /** - * An {@link org.openqa.selenium.support.ui.ExpectedCondition} that can - * be used in conjunction with {@link com.heliumhq.API#waitUntil( - * org.openqa.selenium.support.ui.ExpectedCondition)} to wait for this - * TextField to become enabled. For example: - * - * {@code - * waitUntil(TextField("Subject").isEnabled);} - */ - public final ExpectedCondition isEnabled = - new ExpectedCondition() { - @Override - public Boolean apply(WebDriver input) { - return isEnabled(); - } - }; - /** - * Returns true if the value of the text field can be - * modified, false otherwise. - *

- * The difference between a text field being 'enabled' and 'editable' is - * mostly visual: If a text field is not enabled, it is usually greyed - * out, whereas if it is not editable it looks normal. See also - * {@link TextField#isEnabled()}. - */ - public boolean isEditable() { - return getImpl().isEditable(); - } - /** - * An {@link org.openqa.selenium.support.ui.ExpectedCondition} that can - * be used in conjunction with {@link com.heliumhq.API#waitUntil( - * org.openqa.selenium.support.ui.ExpectedCondition)} to wait for this - * TextField to become editable. For example: - * - * {@code - * waitUntil(TextField("Is active").isEditable);} - */ - public final ExpectedCondition isEditable = - new ExpectedCondition() { - @Override - public Boolean apply(WebDriver input) { - return isEditable(); - } - }; - TextFieldImpl getImpl() { - return (TextFieldImpl) super.getImpl(); - } - } - - /** - * Lets you identify a combo box on a web page. This can for instance be - * used to determine the current value of a combo box: - * {@code - * ComboBox("Language").getValue()} - * - * A ComboBox may be editable, which means that it is possible - * to type in arbitrary values in addition to selecting from a predefined - * drop-down list of values. The property - * {@link com.heliumhq.API.ComboBox#isEditable()} can be used to - * determine whether this is the case for a particular combo box instance. - * - * When there are multiple occurrences of a combo box on a page, you can - * disambiguate between them using the functions {@link API#below}, - * {@link API#toRightOf}, {@link API#above} and {@link API#toLeftOf}. For - * instance: - * - * {@code - * select(ComboBox(toRightOf("John Doe"), below("Status")), "Active")} - * - * This sets the Status of John Doe to Active on the page. - * - * @param label The label (human-visible name) of the combo box. - * @param searchRegion The search region to find the combo box in. - * See the documentation of {@link API#below}. - */ - public static ComboBox ComboBox( - String label, SearchRegion... searchRegion - ) { - return new ComboBox(getAPIImpl().ComboBoxImpl(label, searchRegion)); - } - public static ComboBox ComboBox(SearchRegion... searchRegion) { - return new ComboBox(getAPIImpl().ComboBoxImpl(searchRegion)); - } - public static class ComboBox extends HTMLElement { - private ComboBox(ComboBoxImpl impl) { - super(impl); - } - /** - * Returns true if this combo box allows entering an - * arbitrary text in addition to selecting predefined values from a - * drop-down list. Otherwise, returns false. - */ - public boolean isEditable() { - return getImpl().isEditable(); - } - /** - * An {@link org.openqa.selenium.support.ui.ExpectedCondition} that can - * be used in conjunction with {@link com.heliumhq.API#waitUntil( - * org.openqa.selenium.support.ui.ExpectedCondition)} to wait for this - * ComboBox to become editable. For example: - * - * {@code - * waitUntil(ComboBox("Region").isEditable);} - */ - public final ExpectedCondition isEditable = - new ExpectedCondition() { - @Override - public Boolean apply(WebDriver input) { - return isEditable(); - } - }; - /** - * Returns a List<String> of all possible options - * available to choose from in the combo box. - */ - public List getOptions() { - return getImpl().getOptions(); - } - /** - * Returns the currently selected combo box value, as a - * {@link java.lang.String}. - */ - public String getValue() { - return getImpl().getValue(); - } - ComboBoxImpl getImpl() { - return (ComboBoxImpl) super.getImpl(); - } - } - - /** - * Lets you identify a check box on a web page. To tick a currently - * unselected check box, use: - * - * {@code - * click(CheckBox("I agree"));} - * - * CheckBox also lets you read the properties of a check box. - * For example, - * the method {@link com.heliumhq.API.CheckBox#isChecked()} can be used to - * only click a check box if it isn't already checked: - * - * {@code - * if (! CheckBox("I agree").isChecked()) - * click(CheckBox("I agree"));} - * - * When there are multiple occurrences of a check box on a page, you can - * disambiguate between them using the functions {@link API#below}, - * {@link API#toRightOf}, {@link API#above} and {@link API#toLeftOf}. For - * instance: - * - * {@code - * click(CheckBox("Stay signed in", below(Button("Sign in"))));} - * - * @param label The label (human-visible name) of the check box. - * @param searchRegion The search region to find the check box in. - * See the documentation of {@link API#below}. - */ - public static CheckBox CheckBox( - String label, SearchRegion... searchRegion - ) { - return new CheckBox(getAPIImpl().CheckBoxImpl(label, searchRegion)); - } - public static CheckBox CheckBox(SearchRegion... searchRegion) { - return new CheckBox(getAPIImpl().CheckBoxImpl(searchRegion)); - } - public static class CheckBox extends HTMLElement { - private CheckBox(CheckBoxImpl impl) { - super(impl); - } - /** - * Returns true if this check box can currently be - * interacted with, false otherwise. - */ - public boolean isEnabled() { - return getImpl().isEnabled(); - } - /** - * An {@link org.openqa.selenium.support.ui.ExpectedCondition} that can - * be used in conjunction with {@link com.heliumhq.API#waitUntil( - * org.openqa.selenium.support.ui.ExpectedCondition)} to wait for this - * CheckBox to become enabled. For example: - * - * {@code - * waitUntil(CheckBox("I agree").isEnabled);} - */ - public final ExpectedCondition isEnabled = - new ExpectedCondition() { - @Override - public Boolean apply(WebDriver input) { - return isEnabled(); - } - }; - /** - * Returns true if this check box is checked (selected). - * false otherwise. - */ - public boolean isChecked() { - return getImpl().isChecked(); - } - /** - * An {@link org.openqa.selenium.support.ui.ExpectedCondition} that can - * be used in conjunction with {@link com.heliumhq.API#waitUntil( - * org.openqa.selenium.support.ui.ExpectedCondition)} to wait for this - * CheckBox to become checked. For example: - * - * {@code - * waitUntil(CheckBox("Is active").isChecked);} - */ - public final ExpectedCondition isChecked = - new ExpectedCondition() { - @Override - public Boolean apply(WebDriver input) { - return isChecked(); - } - }; - CheckBoxImpl getImpl() { - return (CheckBoxImpl) super.getImpl(); - } - } - - /** - * Lets you identify a radio button on a web page. To select a currently - * unselected radio button, use: - * - * {@code - * click(RadioButton("Windows"))} - * - * RadioButton also lets you read the properties of a radio - * button. For example, the method - * {@link com.heliumhq.API.RadioButton#isSelected()} can be used to only - * click a radio button if it isn't already selected: - * - * {@code - * if (! RadioButton("Windows").is_selected()) - * click(RadioButton("Windows"));} - * - * When there are multiple occurrences of a radio button on a page, you can - * disambiguate between them using the functions {@link API#below}, - * {@link API#toRightOf}, {@link API#above} and {@link API#toLeftOf}. For - * instance: - * - * {@code - * click(RadioButton("I accept", below("License Agreement")));} - * - * @param label The label (human-visible name) of the radio button. - * @param searchRegion The search region to find the radio button in. - * See the documentation of {@link API#below}. - */ - public static RadioButton RadioButton( - String label, SearchRegion... searchRegion - ) { - return new RadioButton( - getAPIImpl().RadioButtonImpl(label, searchRegion) - ); - } - public static RadioButton RadioButton(SearchRegion... searchRegion) { - return new RadioButton(getAPIImpl().RadioButtonImpl(searchRegion)); - } - public static class RadioButton extends HTMLElement { - private RadioButton(RadioButtonImpl impl) { - super(impl); - } - /** - * Returns true if this radio button is selected, - * false otherwise. - */ - public boolean isSelected() { - return getImpl().isSelected(); - } - /** - * An {@link org.openqa.selenium.support.ui.ExpectedCondition} that can - * be used in conjunction with {@link com.heliumhq.API#waitUntil( - * org.openqa.selenium.support.ui.ExpectedCondition)} to wait for this - * RadioButton to become checked. For example: - * - * {@code - * waitUntil(RadioButton("Express shipping").isSelected);} - */ - public final ExpectedCondition isSelected = - new ExpectedCondition() { - @Override - public Boolean apply(WebDriver input) { - return isSelected(); - } - }; - RadioButtonImpl getImpl() { - return (RadioButtonImpl) super.getImpl(); - } - } - - /** - * Lets you identify individual windows of the currently open browser - * session. - * - * @param title The title of the window you wish to identify. - */ - public static Window Window(String title) { - return new Window(getAPIImpl().WindowImpl(title)); - } - public static Window Window() { - return new Window(getAPIImpl().WindowImpl()); - } - public static class Window extends GUIElement { - private Window(WindowImpl impl) { - super(impl); - } - /** - * Returns the title of this Window, as a {@link java.lang.String}. - */ - public String getTitle() { - return getImpl().getTitle(); - } - /** - * Returns the Selenium driver window handle assigned to this window (a - * {@link java.lang.String}). Note that this window handle is simply an - * abstract identifier and bears no relationship to the corresponding - * operating system handle (HWND on Windows). - */ - public String getHandle() { - return getImpl().getHandle(); - } - WindowImpl getImpl() { - return (WindowImpl) super.getImpl(); - } - } - - - /** - * Lets you identify and interact with JavaScript alert boxes. - * - * @param text The text displayed in the alert box you wish to identify. - */ - public static Alert Alert(String text) { - return new Alert(getAPIImpl().AlertImpl(text)); - } - public static Alert Alert() { - return new Alert(getAPIImpl().AlertImpl()); - } - public static class Alert extends GUIElement { - private Alert(AlertImpl impl) { - super(impl); - } - /** - * Returns the text displayed in this alert box, as a - * {@link java.lang.String}. - */ - public String getText() { - return getImpl().getText(); - } - /** - * Accepts this alert. This typically corresponds to clicking the "OK" - * button inside the alert. The typical way to use this method is: - * - * {@code - * Alert().accept();} - * - * This accepts the currently open alert. - */ - public void accept() { - getImpl().accept(); - } - /** - * Dismisses this alert. This typically corresponds to clicking the - * "Cancel" or "Close" button of the alert. The typical way to use this - * method is: - * - * {@code - * Alert().dismiss();} - * - * This dismisses the currently open alert. - */ - public void dismiss() { - getImpl().dismiss(); - } - AlertImpl getImpl() { - return (AlertImpl) super.getImpl(); - } - } - - /** - * A clickable point. To create a Point at on offset of an existing point, - * use {@link com.heliumhq.API.Point#withOffset(int, int)}: - * - * {@code - * Point point = Point(10, 25); - * point.withOffset(15, 5); // Point(25, 30);} - * - * @param x The x coordinate of the point. - * @param y The y coordinate of the point. - */ - public static Point Point(int x, int y) { - return new Point(x, y); - } - public static class Point { - private int x, y; - private Point(int x, int y) { - this.x = x; - this.y = y; - } - /** - * Returns the x-coordinate of this point. - */ - public int getX() { - return x; - } - /** - * Returns the y-coordinate of this point. - */ - public int getY() { - return y; - } - /** - * Returns a new Point with coordinates relative to this Point's - * coordinates. - * - * @param dx The distance of the new Point to this Point on the - * horizontal axis. - * @param dy The distance of the new Point to this Point on the - * vertical axis. - * @return a new Point with coordinates (x + dx, y + dy) if this Point - * has coordinates (x, y). - */ - public Point withOffset(int dx, int dy) { - return new Point(x + dx, y + dy); - } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Point point = (Point) o; - - if (x != point.x) return false; - if (y != point.y) return false; - - return true; - } - @Override - public int hashCode() { - int result = x; - result = 31 * result + y; - return result; - } - } - - /** - * This function is one of the four functions that can be used to perform - * relative HTML element searches. For a description of this feature, please - * consult {@link API#below}. - * - * @param text The text to the left of which a search should be - * performed. - */ - public static SearchRegion toLeftOf(String text) { - return toLeftOf(Text(text)); - } - - /** - * @param element The element to the left of which a search should be - * performed. - */ - public static SearchRegion toLeftOf(HTMLElement element) { - return getAPIImpl().toLeftOf(element.getImpl()); - } - - /** - * This function is one of the four functions that can be used to perform - * relative HTML element searches. For a description of this feature, please - * consult {@link API#below}. - * - * @param text The text to the right of which a search should be - * performed. - */ - public static SearchRegion toRightOf(String text) { - return toRightOf(Text(text)); - } - - /** - * @param element The element to the left of which a search should be - * performed. - */ - public static SearchRegion toRightOf(HTMLElement element) { - return getAPIImpl().toRightOf(element.getImpl()); - } - - /** - * This function is one of the four functions that can be used to perform - * relative HTML element searches. For a description of this feature, please - * consult {@link API#below}. - * - * @param text The text above which a search should be performed. - */ - public static SearchRegion above(String text) { - return above(Text(text)); - } - - /** - * @param element The element above which a search should be performed. - */ - public static SearchRegion above(HTMLElement element) { - return getAPIImpl().above(element.getImpl()); - } - - /** - * The function below and its sister functions - * {@link API#toRightOf}, {@link API#above} and {@link API#toLeftOf} make it - * possible to disambiguate multiple occurrences of a HTML element on a - * page. Most typically, this occurs when working with tables. For example, - * suppose you have a table of user accounts with buttons for blocking - * them on a page. Then you can use the following snippet to disable the - * user account of "John Doe": - * - * {@code - * click(Button("Block account", toRightOf("John Doe"));} - * - * Relative GUI element searches like this can be nested and combined - * arbitrarily with Helium's other functions. For example: - * - * {@code - * click(CheckBox(below("Has read permissions"), toRightOf("Bob")));} - * - * This clicks on the check box below text "Has read permissions" and to the - * right of text "Bob". - * - * @param text The text below which a search should be performed. - */ - public static SearchRegion below(String text) { - return below(Text(text)); - } - - /** - * @param element The element below which a search should be performed. - */ - public static SearchRegion below(HTMLElement element) { - return getAPIImpl().below(element.getImpl()); - } - - private static APIImpl getAPIImpl() { - return getApplicationContext().getAPIImpl(); - } - -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/$Impl.java b/helium-java/src/main/java/com/heliumhq/api_impl/$Impl.java deleted file mode 100644 index d962143..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/$Impl.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import com.heliumhq.selenium_wrappers.WebElementWrapper; -import org.openqa.selenium.By; -import org.openqa.selenium.WebElement; - -import java.util.ArrayList; -import java.util.List; - -public class $Impl extends HTMLElementImpl { - - private final String selector; - - $Impl( - WebDriverWrapper driver, String selector, SearchRegion... searchRegions - ) { - super(driver, searchRegions); - this.selector = selector; - } - - @Override - protected Object[] getConstructorArgsBeforeSearchRegions() { - return new Object[] {selector}; - } - - @Override - protected List findAllInCurrFrame() { - if (selector.startsWith("@")) - return wrap(driver.findElements(By.name(selector.substring(1)))); - if (selector.startsWith("//")) - return wrap(driver.findElements(By.xpath(selector))); - return wrap(driver.findElements(By.cssSelector(selector))); - } - - private List wrap(List elements) { - List result = new ArrayList(); - for (WebElement element : elements) - result.add(new WebElementWrapper(driver, element)); - return result; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/APICommandImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/APICommandImpl.java deleted file mode 100644 index d3245df..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/APICommandImpl.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import org.openqa.selenium.UnhandledAlertException; - -import java.util.HashSet; -import java.util.Set; - -abstract class APICommandImpl implements Runnable { - - private final WebDriverWrapper driver; - - APICommandImpl(WebDriverWrapper driver) { - this.driver = driver; - } - - APICommandImpl handleUnexpectedAlert() { - return new APICommandImpl(driver) { - @Override - public void run() { - try { - APICommandImpl.this.run(); - } catch (UnhandledAlertException e) { - throwUnhandledAlertExceptionWithNiceMsg(); - } - } - private void throwUnhandledAlertExceptionWithNiceMsg() { - throw new UnhandledAlertException( - "This command is not supported when an alert is present. " + - "To accept the alert (this usually corresponds to " + - "clicking 'OK') use `Alert().accept()`. To dismiss the " + - "alert (ie. 'cancel' it), use `Alert().dismiss()`. If " + - "the alert contains a text field, you can use write(...) " + - "to set its value. Eg.: `write('hi there!')`." - ); - - } - }; - } - - APICommandImpl mightSpawnWindow() { - return new APICommandImpl(driver) { - @Override - public void run() { - if (driver.isIE() && new AlertImpl(driver).exists()) { - // Accessing .window_handles in IE when an alert is present - // raises an UnexpectedAlertPresentException. When - // DesiredCapability 'unexpectedAlertBehaviour' is not - // 'ignore' (the default is 'dismiss'), this leads to the - // alert being closed. Since we don't want to - // unintentionally close alert dialogs, we therefore do not - // access .window_handles in IE when an alert is present. - APICommandImpl.this.run(); - return; - } - Set windowHandlesBefore = - driver.unwrap().getWindowHandles(); - APICommandImpl.this.run(); - // As above, don't access .window_handles in IE if an alert is - // present: - if (!(driver.isIE() && new AlertImpl(driver).exists())) { - if (driver.isFirefox()) - // Unlike Chrome, Firefox does not wait for new windows - // to open. Give it a little time to do so: - try { - Thread.sleep(200); - } catch (InterruptedException e) {} - Set newWindowHandles = new HashSet( - driver.unwrap().getWindowHandles() - ); - newWindowHandles.removeAll(windowHandlesBefore); - if (!newWindowHandles.isEmpty()) - driver.switchTo().window( - newWindowHandles.iterator().next() - ); - } - } - }; - } - - void execute() { - run(); - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/APIImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/APIImpl.java deleted file mode 100644 index 5fe239b..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/APIImpl.java +++ /dev/null @@ -1,1107 +0,0 @@ -package com.heliumhq.api_impl; - -import com.google.common.collect.ImmutableList; -import com.heliumhq.environment.ResourceLocator; -import com.heliumhq.errors.HeliumError; -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import com.heliumhq.selenium_wrappers.WebElementWrapper; -import com.heliumhq.util.Tuple; -import org.openqa.selenium.*; -import org.openqa.selenium.chrome.ChromeDriver; -import org.openqa.selenium.chrome.ChromeDriverService; -import org.openqa.selenium.chrome.ChromeOptions; -import org.openqa.selenium.firefox.FirefoxBinary; -import org.openqa.selenium.firefox.FirefoxDriver; -import org.openqa.selenium.firefox.FirefoxOptions; -import org.openqa.selenium.firefox.GeckoDriverService; -import org.openqa.selenium.ie.InternetExplorerDriver; -import org.openqa.selenium.ie.InternetExplorerDriverService; -import org.openqa.selenium.interactions.Actions; -import org.openqa.selenium.remote.CapabilityType; -import org.openqa.selenium.remote.DesiredCapabilities; -import org.openqa.selenium.support.ui.ExpectedCondition; -import org.openqa.selenium.support.ui.Select; -import org.openqa.selenium.support.ui.WebDriverWait; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import static com.heliumhq.API.Point; -import static com.heliumhq.util.System.*; - -public class APIImpl { - - public static final String DRIVER_REQUIRED_MESSAGE = - "This operation requires a browser window. Please call one of " + - "the following functions first:\n" + - " * startChrome()\n" + - " * startFirefox()\n" + - " * startIE()\n" + - " * setDriver(...)"; - - private final ResourceLocator resourceLocator; - private WebDriverWrapper driver; - - public APIImpl(ResourceLocator resourceLocator) { - this.resourceLocator = resourceLocator; - } - - public WebDriver startFirefoxImpl() { - return startFirefoxImpl(null); - } - public WebDriver startFirefoxImpl(String url) { - return startFirefoxImpl(url, false); - } - public WebDriver startFirefoxImpl(boolean headless) { - return startFirefoxImpl(null, headless); - } - public WebDriver startFirefoxImpl (String url, boolean headless) { - FirefoxDriver firefox = startFirefoxDriver(headless); - return start(firefox, url); - } - private FirefoxDriver startFirefoxDriver(boolean headless) { - GeckoDriverService service = getGeckoDriverService(); - Runtime.getRuntime().addShutdownHook( - new DriverServiceDestroyer(service) - ); - FirefoxOptions options = new FirefoxOptions(); - if (headless) { - FirefoxBinary binary = new FirefoxBinary(); - binary.addCommandLineOptions("--headless"); - options.setBinary(binary); - } - return new FirefoxDriver(service, options); - } - private GeckoDriverService getGeckoDriverService() { - File driver = locateWebDriver("geckodriver"); - if (driver.exists()) { - ensureDriverIsExecutable(driver); - return new GeckoDriverService.Builder() - .usingDriverExecutable(driver) - .withLogFile(new File(isWindows() ? "nul" : "/dev/null")) - .build(); - } else - return GeckoDriverService.createDefaultService(); - } - - private void ensureDriverIsExecutable(File driver) { - if (! driver.canExecute()) - if (! driver.setExecutable(true)) - throw new HeliumError(String.format( - "The driver located at %s is not executable.", - driver.getAbsolutePath() - )); - } - - public WebDriver startChromeImpl() { - return startChromeImpl(null); - } - public WebDriver startChromeImpl(String url) { - return startChromeImpl(url, false); - } - public WebDriver startChromeImpl(boolean headless) { - return startChromeImpl(null, headless); - } - public WebDriver startChromeImpl(String url, boolean headless) { - ChromeDriver chromeDriver = startChromeDriver(headless); - return start(chromeDriver, url); - } - - private ChromeDriver startChromeDriver(boolean headless) { - ChromeOptions chromeOptions = getChromeOptions(headless); - ChromeDriverService service = getChromeDriverService(); - Runtime.getRuntime().addShutdownHook( - new DriverServiceDestroyer(service) - ); - return new ChromeDriver(service, chromeOptions); - } - - private ChromeOptions getChromeOptions(boolean headless) { - ChromeOptions result = new ChromeOptions(); - if (headless) - result.addArguments("--headless"); - return result; - } - - private ChromeDriverService getChromeDriverService() { - File driver = locateWebDriver("chromedriver"); - if (driver.exists()) { - ensureDriverIsExecutable(driver); - ChromeDriverService.Builder serviceBuilder = - new ChromeDriverService.Builder(); - return serviceBuilder - // Prevent verbose messages 'ChromeDriver started' on stderr: - .withSilent(true) - .usingAnyFreePort() - .usingDriverExecutable(driver) - .build(); - } else - return ChromeDriverService.createDefaultService(); - } - - private File locateWebDriver(String driverName) { - if (isWindows()) - driverName += ".exe"; - return new File(resourceLocator.locate("webdrivers", driverName)); - } - - public WebDriver startIEImpl() { - return startIEImpl(null); - } - public WebDriver startIEImpl(String url) { - File driverExe = locateWebDriver("IEDriverServer.exe"); - InternetExplorerDriverService.Builder serviceBuilder = - new InternetExplorerDriverService.Builder() - .usingAnyFreePort(). - // Prevent verbose messages 'IEDriver started', 'IEDriver - // listening', 'IEDriver stopped' on stderr: - withSilent(true); - if (driverExe.exists()) - serviceBuilder = serviceBuilder.usingDriverExecutable(driverExe); - InternetExplorerDriverService service = serviceBuilder.build(); - Runtime.getRuntime().addShutdownHook( - new DriverServiceDestroyer(service) - ); - InternetExplorerDriver ieBrowser; - try { - ieBrowser = new InternetExplorerDriver(service); - } catch (WebDriverException e) { - WebDriverException excToRaise = e; - if (e.getMessage().contains( - "Protected Mode settings are not the same for all zones." - )) - excToRaise = new WebDriverException( - "Error launching IE: Protected Mode settings are not the " + - "same for all zones. Please follow these steps: " + - "http://heliumhq.com/docs/internet_explorer#protected_mode" - ); - throw excToRaise; - } - return start(ieBrowser, url); - } - - private WebDriver start(WebDriver browser, String url) { - setDriverImpl(browser); - if (url != null) - goToImpl(url); - return getDriverImpl(); - } - - public void goToImpl(final String url) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - driver.get((!url.contains("://") ? "http://" : "") + url); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - - public void setDriverImpl(WebDriver driver) { - this.driver = new WebDriverWrapper(driver); - } - - public WebDriver getDriverImpl() { - return driver == null ? null : driver.unwrap(); - } - - public void writeImpl(final String text) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - if (new AlertImpl(driver).exists()) - writeImpl(text, new AlertImpl(driver)); - else - driver.switchTo().activeElement().sendKeys(text); - } - }).mightSpawnWindow().execute(); - } - public void writeImpl(String text, String into) { - writeImpl(text, new TextFieldImpl(requireDriver(), into)); - } - public void writeImpl(String text, WebElement into) { - writeImpl(text, new WebElementWrapper(driver, into)); - } - private void writeImpl(final String text, final WebElementWrapper into) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - into.unwrap().clear(); - into.unwrap().sendKeys(text); - driver.setLastManipulatedElement(into); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - public void writeImpl(final String text, final HTMLElementImpl into) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - into.perform(new Action() { - @Override - void performOn(WebElementWrapper elementWrapper) { - writeImpl(text, elementWrapper); - } - }); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - public void writeImpl(String text, AlertImpl into) { - into.write(text); - } - - public void pressImpl(final CharSequence key) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - driver.switchTo().activeElement().sendKeys(key); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - - public final CharSequence NULL = Keys.NULL; - public final CharSequence CANCEL = Keys.CANCEL; - public final CharSequence HELP = Keys.HELP; - public final CharSequence BACK_SPACE = Keys.BACK_SPACE; - public final CharSequence TAB = Keys.TAB; - public final CharSequence CLEAR = Keys.CLEAR; - public final CharSequence RETURN = Keys.RETURN; - public final CharSequence ENTER = Keys.ENTER; - public final CharSequence SHIFT = Keys.SHIFT; - public final CharSequence LEFT_SHIFT = Keys.LEFT_SHIFT; - public final CharSequence CONTROL = Keys.CONTROL; - public final CharSequence LEFT_CONTROL = Keys.LEFT_CONTROL; - public final CharSequence ALT = Keys.ALT; - public final CharSequence LEFT_ALT = Keys.LEFT_ALT; - public final CharSequence PAUSE = Keys.PAUSE; - public final CharSequence ESCAPE = Keys.ESCAPE; - public final CharSequence SPACE = Keys.SPACE; - public final CharSequence PAGE_UP = Keys.PAGE_UP; - public final CharSequence PAGE_DOWN = Keys.PAGE_DOWN; - public final CharSequence END = Keys.END; - public final CharSequence HOME = Keys.HOME; - public final CharSequence LEFT = Keys.LEFT; - public final CharSequence ARROW_LEFT = Keys.ARROW_LEFT; - public final CharSequence UP = Keys.UP; - public final CharSequence ARROW_UP = Keys.ARROW_UP; - public final CharSequence RIGHT = Keys.RIGHT; - public final CharSequence ARROW_RIGHT = Keys.ARROW_RIGHT; - public final CharSequence DOWN = Keys.DOWN; - public final CharSequence ARROW_DOWN = Keys.ARROW_DOWN; - public final CharSequence INSERT = Keys.INSERT; - public final CharSequence DELETE = Keys.DELETE; - public final CharSequence SEMICOLON = Keys.SEMICOLON; - public final CharSequence EQUALS = Keys.EQUALS; - public final CharSequence NUMPAD0 = Keys.NUMPAD0; - public final CharSequence NUMPAD1 = Keys.NUMPAD1; - public final CharSequence NUMPAD2 = Keys.NUMPAD2; - public final CharSequence NUMPAD3 = Keys.NUMPAD3; - public final CharSequence NUMPAD4 = Keys.NUMPAD4; - public final CharSequence NUMPAD5 = Keys.NUMPAD5; - public final CharSequence NUMPAD6 = Keys.NUMPAD6; - public final CharSequence NUMPAD7 = Keys.NUMPAD7; - public final CharSequence NUMPAD8 = Keys.NUMPAD8; - public final CharSequence NUMPAD9 = Keys.NUMPAD9; - public final CharSequence MULTIPLY = Keys.MULTIPLY; - public final CharSequence ADD = Keys.ADD; - public final CharSequence SEPARATOR = Keys.SEPARATOR; - public final CharSequence SUBTRACT = Keys.SUBTRACT; - public final CharSequence DECIMAL = Keys.DECIMAL; - public final CharSequence DIVIDE = Keys.DIVIDE; - public final CharSequence F1 = Keys.F1; - public final CharSequence F2 = Keys.F2; - public final CharSequence F3 = Keys.F3; - public final CharSequence F4 = Keys.F4; - public final CharSequence F5 = Keys.F5; - public final CharSequence F6 = Keys.F6; - public final CharSequence F7 = Keys.F7; - public final CharSequence F8 = Keys.F8; - public final CharSequence F9 = Keys.F9; - public final CharSequence F10 = Keys.F10; - public final CharSequence F11 = Keys.F11; - public final CharSequence F12 = Keys.F12; - public final CharSequence META = Keys.META; - public final CharSequence COMMAND = Keys.COMMAND; - - public void clickImpl(String element) { - clickImpl(toClickableText(element)); - } - private ClickableText toClickableText(String element) { - return new ClickableText(requireDriver(), element); - } - public void clickImpl(WebElement element) { - clickImpl(new WebElementWrapper(driver, element)); - } - private void clickImpl(final WebElementWrapper elementWrapper) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - elementWrapper.unwrap().click(); - driver.setLastManipulatedElement(elementWrapper); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - public void clickImpl(final HTMLElementImpl element) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - element.perform(new Action() { - @Override - void performOn(WebElementWrapper element) { - clickImpl(element); - } - }); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - public void clickImpl(final Point point) { - handleOffset(point, new Action() { - @Override - void performOn(Actions actions) { - actions.click(); - } - }); - } - private void handleOffset(final Point point, final Action action) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - Tuple eltAndOffset = - pointToElementAndOffset(point); - WebElementWrapper element = eltAndOffset.getFirst(); - Point offset = eltAndOffset.getSecond(); - Actions actions = driver.action().moveToElement( - element.unwrap(), offset.getX(), offset.getY() - ); - action.performOn(actions); - actions.perform(); - driver.setLastManipulatedElement(element); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - private Tuple pointToElementAndOffset( - Point point - ) { - final WebDriverWrapper driver = requireDriver(); - WebElementWrapper element = new WebElementWrapper( - driver, - (WebElement) driver.executeScript(String.format( - "return document.elementFromPoint(%s, %s);", - point.getX(), point.getY() - )) - ); - Point offset = point.withOffset( - -element.getLocation().getLeft(), - -element.getLocation().getTop() - ); - if (offset.equals(Point(0, 0)) && driver.isFirefox()) - // In some CSS settings (eg. inttest_point.html), the (0, 0) point - // of buttons in Firefox is not clickable! The reason for this is - // that Firefox styles buttons to not be perfect squares, but have - // an indent in the corners. This workaround makes - // click(btn.getTopLeft()) work even when this happens: - offset = Point(1, 1); - return new Tuple(element, offset); - } - private WebElementWrapper pointToElement(Point to) { - return pointToElementAndOffset(to).getFirst(); - } - - public void doubleclickImpl(String element) { - doubleclickImpl(toClickableText(element)); - } - public void doubleclickImpl(WebElement element) { - doubleclickImpl(new WebElementWrapper(driver, element)); - } - private void doubleclickImpl(final WebElementWrapper elementWrapper) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - driver.action().doubleClick(elementWrapper.unwrap()).perform(); - driver.setLastManipulatedElement(elementWrapper); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - public void doubleclickImpl(final HTMLElementImpl element) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - element.perform(new Action() { - @Override - void performOn(WebElementWrapper element) { - doubleclickImpl(element); - } - }); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - public void doubleclickImpl(final Point point) { - handleOffset(point, new Action() { - @Override - void performOn(Actions actions) { - actions.doubleClick(); - } - }); - } - - public void dragImpl(String element, String to) { - dragImpl(toClickableText(element), toClickableText(to)); - } - public void dragImpl(String element, WebElement to) { - dragImpl(toClickableText(element), new WebElementWrapper(driver, to)); - } - public void dragImpl(String element, HTMLElementImpl to) { - dragImpl(toClickableText(element), to); - } - public void dragImpl(String element, Point to) { - dragImpl(toClickableText(element), pointToElement(to)); - } - public void dragImpl(WebElement element, String to) { - dragImpl(new WebElementWrapper(driver, element), toClickableText(to)); - } - public void dragImpl(WebElement element, WebElement to) { - dragImpl( - new WebElementWrapper(driver, element), - new WebElementWrapper(driver, to) - ); - } - private void dragImpl(WebElementWrapper element, WebElementWrapper to) { - DragHelper dragHelper = new DragHelper(this); - dragHelper.begin(); - try { - dragHelper.startDragging(element); - driver.setLastManipulatedElement(element); - dragHelper.dropOnTarget(to); - driver.setLastManipulatedElement(to); - } finally { - dragHelper.end(); - } - } - private void dragImpl(WebElementWrapper element, HTMLElementImpl to) { - final DragHelper dragHelper = new DragHelper(this); - dragHelper.begin(); - try { - dragHelper.startDragging(element); - driver.setLastManipulatedElement(element); - to.perform( - new Action() { - @Override - void performOn(WebElementWrapper target) { - dragHelper.dropOnTarget(target); - driver.setLastManipulatedElement(target); - } - } - ); - } finally { - dragHelper.end(); - } - } - private void dragImpl(HTMLElementImpl element, WebElementWrapper to) { - final DragHelper dragHelper = new DragHelper(this); - dragHelper.begin(); - try { - element.perform( - new Action() { - @Override - void performOn(WebElementWrapper elementToDrag) { - dragHelper.startDragging(elementToDrag); - driver.setLastManipulatedElement(elementToDrag); - } - } - ); - dragHelper.dropOnTarget(to); - driver.setLastManipulatedElement(to); - } finally { - dragHelper.end(); - } - } - public void dragImpl(HTMLElementImpl element, HTMLElementImpl to) { - final DragHelper dragHelper = new DragHelper(this); - dragHelper.begin(); - try { - element.perform( - new Action() { - @Override - void performOn(WebElementWrapper elementToDrag) { - dragHelper.startDragging(elementToDrag); - driver.setLastManipulatedElement(elementToDrag); - } - } - ); - to.perform( - new Action() { - @Override - void performOn(WebElementWrapper target) { - dragHelper.dropOnTarget(target); - driver.setLastManipulatedElement(target); - } - } - ); - } finally { - dragHelper.end(); - } - } - public void dragImpl(WebElement element, HTMLElementImpl to) { - dragImpl(new WebElementWrapper(driver, element), to); - } - public void dragImpl(WebElement element, Point to) { - dragImpl(new WebElementWrapper(driver, element), pointToElement(to)); - } - public void dragImpl(HTMLElementImpl element, String to) { - dragImpl(element, toClickableText(to)); - } - public void dragImpl(HTMLElementImpl element, WebElement to) { - dragImpl(element, new WebElementWrapper(driver, to)); - } - public void dragImpl(HTMLElementImpl element, Point to) { - dragImpl(element, pointToElement(to)); - } - public void dragImpl(Point element, String to) { - dragImpl(pointToElement(element), toClickableText(to)); - } - public void dragImpl(Point element, WebElement to) { - dragImpl(pointToElement(element), new WebElementWrapper(driver, to)); - } - public void dragImpl(Point element, HTMLElementImpl to) { - dragImpl(pointToElement(element), to); - } - public void dragImpl(Point element, Point to) { - dragImpl(pointToElement(element), pointToElement(to)); - } - private void pressMouseOn(String element) { - pressMouseOn(toClickableText(element)); - } - private void pressMouseOn(WebElement element) { - pressMouseOn(new WebElementWrapper(driver, element)); - } - void pressMouseOn(final WebElementWrapper elementWrapper) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - driver.action().clickAndHold(elementWrapper.unwrap()).perform(); - driver.setLastManipulatedElement(elementWrapper); - } - }).handleUnexpectedAlert().execute(); - } - private void pressMouseOn(final HTMLElementImpl element) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - element.perform(new Action() { - @Override - void performOn(WebElementWrapper elementWrapper) { - pressMouseOn(elementWrapper); - } - }); - } - }).handleUnexpectedAlert().execute(); - } - private void pressMouseOn(Point point) { - handleOffset(point, new Action() { - @Override - void performOn(Actions actions) { - actions.clickAndHold(); - } - }); - } - private void releaseMouseOver(String element) { - releaseMouseOver(toClickableText(element)); - } - private void releaseMouseOver(WebElement element) { - releaseMouseOver(new WebElementWrapper(driver, element)); - } - void releaseMouseOver(final WebElementWrapper elementWrapper) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - driver.action().moveToElement(elementWrapper.unwrap()) - .release().perform(); - driver.setLastManipulatedElement(elementWrapper); - } - }).handleUnexpectedAlert().execute(); - } - private void releaseMouseOver(final HTMLElementImpl element) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - element.perform(new Action() { - @Override - void performOn(WebElementWrapper elementWrapper) { - releaseMouseOver(elementWrapper); - } - }); - } - }).handleUnexpectedAlert().execute(); - } - private void releaseMouseOver(Point point) { - handleOffset(point, new Action() { - @Override - void performOn(Actions actions) { - actions.release(); - } - }); - } - - public > List> findAllImpl( - final G predicateImpl - ) { - final WebDriverWrapper driver = requireDriver(); - final List> result = - new ArrayList>(); - (new APICommandImpl(driver) { - @Override - public void run() { - for (GUIElementImpl boundGuiElementImpl : - predicateImpl.findAll()) - result.add(boundGuiElementImpl); - } - }).handleUnexpectedAlert().execute(); - return result; - } - - public void scrollDownImpl() { - scrollDownImpl(100); - } - public void scrollDownImpl(int numPixels) { - scrollBy(0, numPixels); - } - - public void scrollUpImpl() { - scrollUpImpl(100); - } - public void scrollUpImpl(int numPixels) { - scrollBy(0, -numPixels); - } - - public void scrollRightImpl() { - scrollRightImpl(100); - } - public void scrollRightImpl(int numPixels) { - scrollBy(numPixels, 0); - } - - public void scrollLeftImpl() { - scrollLeftImpl(100); - } - public void scrollLeftImpl(int numPixels) { - scrollBy(-numPixels, 0); - } - - private void scrollBy(final int dxPixels, final int dyPixels) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - driver.executeScript( - "window.scrollBy(arguments[0], arguments[1]);", - dxPixels, dyPixels - ); - } - }).handleUnexpectedAlert().execute(); - } - - public void hoverImpl(String element) { - hoverImpl(toClickableText(element)); - } - public void hoverImpl(WebElement element) { - hoverImpl(new WebElementWrapper(driver, element)); - } - private void hoverImpl(final WebElementWrapper element) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - driver.action().moveToElement(element.unwrap()).perform(); - driver.setLastManipulatedElement(element); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - public void hoverImpl(final HTMLElementImpl element) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - element.perform(new Action() { - @Override - void performOn(WebElementWrapper elementWrapper) { - hoverImpl(elementWrapper); - } - }); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - public void hoverImpl(Point point) { - handleOffset(point, new Action() { - @Override - void performOn(Actions actions) { - // Nothing to do here. At this point, the mouse will have - // already been hovered over the correct position. - } - }); - } - - public void rightclickImpl(String element) { - rightclickImpl(toClickableText(element)); - } - public void rightclickImpl(WebElement element) { - rightclickImpl(new WebElementWrapper(driver, element)); - } - private void rightclickImpl(final WebElementWrapper wrapper) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - driver.action().contextClick(wrapper.unwrap()).perform(); - driver.setLastManipulatedElement(wrapper); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - public void rightclickImpl(final HTMLElementImpl element) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - element.perform(new Action() { - @Override - void performOn(WebElementWrapper elementWrapper) { - rightclickImpl(elementWrapper); - } - }); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - public void rightclickImpl(Point point) { - handleOffset(point, new Action() { - @Override - void performOn(Actions actions) { - actions.contextClick(); - } - }); - } - - public void selectImpl(String comboBox, String value) { - this.selectImpl(ComboBoxImpl(comboBox), value); - } - public void selectImpl(ComboBoxImpl comboBox, String value) { - new Select(comboBox.getWebElement()).selectByVisibleText(value); - } - - public void dragFileImpl(String filePath, String to) { - dragFileImpl(filePath, toClickableText(to)); - } - public void dragFileImpl(String filePath, WebElement to) { - dragFileImpl(filePath, new WebElementWrapper(driver, to)); - } - private void dragFileImpl( - final String filePath, final WebElementWrapper to - ) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - DragAndDropFile dragAndDrop = - new DragAndDropFile(driver, filePath); - dragAndDrop.begin(); - try { - // Some web apps (Gmail in particular) only register for the - // 'drop' event when user has dragged the file over the - // document. We therefore simulate this dragging over the - // document first: - dragAndDrop.dragOverDocument(); - dragAndDrop.dropOn(to); - driver.setLastManipulatedElement(to); - } finally { - dragAndDrop.end(); - } - } - }).handleUnexpectedAlert().execute(); - } - public void dragFileImpl(final String filePath, final HTMLElementImpl to) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - final DragAndDropFile dragAndDrop = - new DragAndDropFile(driver, filePath); - dragAndDrop.begin(); - try { - // Some web apps (Gmail in particular) only register for the - // 'drop' event when user has dragged the file over the - // document. We therefore simulate this dragging over the - // document first: - dragAndDrop.dragOverDocument(); - to.perform(new Action() { - @Override - void performOn(WebElementWrapper element) { - dragAndDrop.dropOn(element); - driver.setLastManipulatedElement(element); - } - }); - } finally { - dragAndDrop.end(); - } - } - }).handleUnexpectedAlert().execute(); - } - - public void attachFileImpl(String filePath) { - attachFileImpl(filePath, new FileInput(requireDriver())); - } - public void attachFileImpl(String filePath, String to) { - attachFileImpl(filePath, new FileInput(requireDriver(), to)); - } - public void attachFileImpl(String filePath, WebElement to) { - attachFileImpl(filePath, new WebElementWrapper(driver, to)); - } - private void attachFileImpl( - final String filePath, final WebElementWrapper to - ) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - to.unwrap().sendKeys(filePath); - driver.setLastManipulatedElement(to); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - public void attachFileImpl( - final String filePath, final HTMLElementImpl to - ) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - to.perform(new Action() { - @Override - void performOn(WebElementWrapper element) { - attachFileImpl(filePath, element); - } - }); - } - }).handleUnexpectedAlert().mightSpawnWindow().execute(); - } - public void attachFileImpl(final String filePath, Point to) { - attachFileImpl(filePath, pointToElement(to)); - } - - public void refreshImpl() { - final WebDriverWrapper driver = requireDriver(); - if (new AlertImpl(driver).exists()) - refreshWithAlert(); - else - refreshNoAlert(); - } - private void refreshNoAlert() { - requireDriver().unwrap().navigate().refresh(); - } - private void refreshWithAlert() { - new AlertImpl(requireDriver()).accept(); - refreshNoAlert(); - } - - public void waitUntilImpl(ExpectedCondition condition) { - waitUntilImpl(condition, 10); - } - public void waitUntilImpl( - ExpectedCondition condition, long timeoutSecs - ) { - waitUntilImpl(condition, timeoutSecs, 0.5); - } - public void waitUntilImpl( - ExpectedCondition condition, long timeoutSecs, - double intervalSecs - ) { - final WebDriverWrapper driver = requireDriver(); - long intervalMillis = (long) Math.ceil(intervalSecs / 1000); - WebDriverWait wait = - new WebDriverWait(driver.unwrap(), timeoutSecs, intervalMillis); - wait.until(condition); - } - - public void switchToImpl(String windowTitle) { - switchToImpl(new WindowImpl(requireDriver(), windowTitle)); - } - public void switchToImpl(final WindowImpl window) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - driver.switchTo().window(window.getHandle()); - } - }).handleUnexpectedAlert().execute(); - } - - public void killBrowserImpl() { - requireDriver().unwrap().quit(); - driver = null; - } - - public void highlightImpl(String element) { - highlightImpl(new TextImpl(requireDriver(), element)); - } - public void highlightImpl(HTMLElementImpl element) { - highlightImpl(element.getFirstOccurrence()); - } - private void highlightImpl(WebElementWrapper elementWrapper) { - highlightImpl(elementWrapper.unwrap()); - } - public void highlightImpl(final WebElement element) { - final WebDriverWrapper driver = requireDriver(); - (new APICommandImpl(driver) { - @Override - public void run() { - String previousStyle = element.getAttribute("style"); - driver.executeScript( - "arguments[0].setAttribute(" + - "'style', 'border: 2px solid red; font-weight: bold;'" + - ");", element - ); - driver.executeScript( - "var target = arguments[0];" + - "var previousStyle = arguments[1];" + - "setTimeout(" + - "function() {" + - "target.setAttribute('style', previousStyle);" + - "}, 2000" + - ");", element, previousStyle - ); - } - }).handleUnexpectedAlert().execute(); - } - - public $Impl $Impl(String selector, SearchRegion... searchRegions) { - return new $Impl(requireDriver(), selector, searchRegions); - } - - public TextImpl TextImpl(SearchRegion... searchRegions) { - return new TextImpl(requireDriver(), searchRegions); - } - public TextImpl TextImpl( - String text, SearchRegion... searchRegions - ) { - return new TextImpl(requireDriver(), text, searchRegions); - } - - public LinkImpl LinkImpl(SearchRegion... searchRegions) { - return new LinkImpl(requireDriver(), searchRegions); - } - public LinkImpl LinkImpl( - String text, SearchRegion... searchRegions - ) { - return new LinkImpl(requireDriver(), text, searchRegions); - } - - public ListItemImpl ListItemImpl(SearchRegion... searchRegions) { - return new ListItemImpl(requireDriver(), searchRegions); - } - public ListItemImpl ListItemImpl( - String text, SearchRegion... searchRegions - ) { - return new ListItemImpl(requireDriver(), text, searchRegions); - } - - public ButtonImpl ButtonImpl(SearchRegion... searchRegions) { - return new ButtonImpl(requireDriver(), searchRegions); - } - public ButtonImpl ButtonImpl( - String text, SearchRegion... searchRegions - ) { - return new ButtonImpl(requireDriver(), text, searchRegions); - } - - public ImageImpl ImageImpl(SearchRegion... searchRegions) { - return new ImageImpl(requireDriver(), searchRegions); - } - public ImageImpl ImageImpl( - String alt, SearchRegion... searchRegions - ) { - return new ImageImpl(requireDriver(), alt, searchRegions); - } - - public TextFieldImpl TextFieldImpl(SearchRegion... searchRegions) { - return new TextFieldImpl(requireDriver(), searchRegions); - } - public TextFieldImpl TextFieldImpl( - String label, SearchRegion... searchRegions - ) { - return new TextFieldImpl(requireDriver(), label, searchRegions); - } - - public ComboBoxImpl ComboBoxImpl(SearchRegion... searchRegions) { - return new ComboBoxImpl(requireDriver(), searchRegions); - } - public ComboBoxImpl ComboBoxImpl( - String label, SearchRegion... searchRegions - ) { - return new ComboBoxImpl(requireDriver(), label, searchRegions); - } - - public CheckBoxImpl CheckBoxImpl(SearchRegion... searchRegions) { - return new CheckBoxImpl(requireDriver(), searchRegions); - } - public CheckBoxImpl CheckBoxImpl( - String label, SearchRegion... searchRegions - ) { - return new CheckBoxImpl(requireDriver(), label, searchRegions); - } - - public RadioButtonImpl RadioButtonImpl( - SearchRegion... searchRegions - ) { - return new RadioButtonImpl(requireDriver(), searchRegions); - } - public RadioButtonImpl RadioButtonImpl( - String label, SearchRegion... searchRegions - ) { - return new RadioButtonImpl(requireDriver(), label, searchRegions); - } - - public WindowImpl WindowImpl() { - return new WindowImpl(requireDriver()); - } - public WindowImpl WindowImpl(String title) { - return new WindowImpl(requireDriver(), title); - } - - public AlertImpl AlertImpl() { - return new AlertImpl(requireDriver()); - } - - public AlertImpl AlertImpl(String text) { - return new AlertImpl(requireDriver(), text); - } - - public SearchRegion toLeftOf(HTMLElementImpl element) { - return new SearchRegion(SearchDirection.TO_LEFT_OF, element); - } - public SearchRegion toRightOf(HTMLElementImpl element) { - return new SearchRegion(SearchDirection.TO_RIGHT_OF, element); - } - public SearchRegion above(HTMLElementImpl element) { - return new SearchRegion(SearchDirection.ABOVE, element); - } - public SearchRegion below(HTMLElementImpl element) { - return new SearchRegion(SearchDirection.BELOW, element); - } - - WebDriverWrapper requireDriver() { - if (driver == null) - throw new RuntimeException(DRIVER_REQUIRED_MESSAGE); - return driver; - } - -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/Action.java b/helium-java/src/main/java/com/heliumhq/api_impl/Action.java deleted file mode 100644 index 7ab3fc8..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/Action.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.heliumhq.api_impl; - -abstract class Action { - abstract void performOn(T element); -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/AlertImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/AlertImpl.java deleted file mode 100644 index 7ef85f9..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/AlertImpl.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import org.openqa.selenium.NoAlertPresentException; -import org.openqa.selenium.WebDriverException; - -import java.util.ArrayList; -import java.util.List; - -public class AlertImpl extends GUIElementImpl { - - private final String searchText; - - public AlertImpl(WebDriverWrapper driver) { - this(driver, null); - } - - public AlertImpl(WebDriverWrapper driver, String searchText) { - super(driver); - this.searchText = searchText; - } - - @Override - protected Iterable findAllOccurrences() { - List result = - new ArrayList(); - try { - org.openqa.selenium.Alert alert = driver.switchTo().alert(); - String text = alert.getText(); - if (searchText == null || - (text != null && text.startsWith(searchText))) - result.add(alert); - } catch (NoAlertPresentException e) { - // alert hasn't been added to result so no need to do anything here. - } - return result; - } - - public String getText() { - return getFirstOccurrence().getText(); - } - - public void accept() { - org.openqa.selenium.Alert firstOccurrence = getFirstOccurrence(); - try { - firstOccurrence.accept(); - } catch (WebDriverException e) { - // Attempt to work around Selenium issue 3544: - // https://code.google.com/p/selenium/issues/detail?id=3544 - String msg = e.getMessage(); - if (msg != null && msg.matches( - "a\\.document\\.getElementsByTagName\\([^\\)]*\\)\\[0\\] " + - "is undefined")) { - try { - Thread.sleep(250); - } catch (InterruptedException e2) {} - firstOccurrence.accept(); - } else { - throw e; - } - } - } - - public void dismiss() { - getFirstOccurrence().dismiss(); - } - - @Override - protected Object[] getConstructorArgs() { - String text = isBound() ? getText() : searchText; - return new Object[] {text}; - } - - void write(String text) { - getFirstOccurrence().sendKeys(text); - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/ButtonImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/ButtonImpl.java deleted file mode 100644 index 0f3b77e..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/ButtonImpl.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; - -import static com.heliumhq.util.XPath.predicate; -import static com.heliumhq.util.XPath.predicateOr; -import static com.heliumhq.util.StringUtils.isEmpty; - -public class ButtonImpl extends HTMLElementContainingText { - - public ButtonImpl(WebDriverWrapper driver, SearchRegion... searchRegions) { - super(driver, searchRegions); - } - - public ButtonImpl( - WebDriverWrapper driver, String text, SearchRegion... searchRegions - ) { - super(driver, text, searchRegions); - } - - protected String getXPathNodeSelector() { - return "button"; - } - - public boolean isEnabled() { - String ariaDisabled = - getFirstOccurrence().getAttribute("aria-disabled"); - return super.isEnabled() && ( - isEmpty(ariaDisabled) || ariaDisabled.equalsIgnoreCase("false") - ); - } - - @Override - protected String getXPath() { - String hasAriaLabel = matches.xpath("@aria-label", searchText); - String hasText = matches.xpath(".", searchText); - String hasTextOrAriaLabel = predicateOr(hasAriaLabel, hasText); - return super.getXPath() + " | " + getInputButtonXPath() + " | " + - "//*[@role='button']" + hasTextOrAriaLabel + " | " + - "//button" + predicate(hasAriaLabel); - } - - String getInputButtonXPath() { - String hasText; - if (!isEmpty(searchText)) { - String hasValue = matches.xpath("@value", searchText); - String hasLabel = matches.xpath("@label", searchText); - String hasAriaLabel = matches.xpath("@aria-label", searchText); - String hasTitle = matches.xpath("@title", searchText); - hasText = predicateOr(hasValue, hasLabel, hasAriaLabel, hasTitle); - } else - hasText = ""; - return "//input[@type='submit' or @type='button']" + hasText; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/CheckBoxImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/CheckBoxImpl.java deleted file mode 100644 index 9d166dd..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/CheckBoxImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; - -public class CheckBoxImpl extends LabelledElement { - - public CheckBoxImpl( - WebDriverWrapper driver, SearchRegion... searchRegions - ) { - super(driver, searchRegions); - } - - public CheckBoxImpl( - WebDriverWrapper driver, String label, SearchRegion... searchRegions - ) { - super(driver, label, searchRegions); - } - - public boolean isEnabled() { - return super.isEnabled(); - } - - public boolean isChecked() { - return getFirstOccurrence().getAttribute("checked") != null; - } - - @Override - protected String getXPath() { - return "//input[@type='checkbox']"; - } - - @Override - protected SearchDirection getPrimarySearchDirection() { - return SearchDirection.TO_LEFT_OF; - } - - @Override - protected SearchDirection getSecondarySearchDirection() { - return SearchDirection.TO_RIGHT_OF; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/ClickableText.java b/helium-java/src/main/java/com/heliumhq/api_impl/ClickableText.java deleted file mode 100644 index 543c2c9..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/ClickableText.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; - -class ClickableText extends CompositeElement { - - private final String searchText; - - ClickableText(WebDriverWrapper driver) { - this(driver, null); - } - - ClickableText(WebDriverWrapper driver, String searchText) { - super(driver); - this.searchText = searchText; - } - - @Override - protected HTMLElementImpl[] getElements() { - return new HTMLElementImpl[] { - new ButtonImpl(driver, searchText), - new TextImpl(driver, searchText) - }; - } - - @Override - protected Object[] getConstructorArgsBeforeSearchRegions() { - return new Object[] {searchText}; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/ComboBoxIdentifiedByDisplayedValue.java b/helium-java/src/main/java/com/heliumhq/api_impl/ComboBoxIdentifiedByDisplayedValue.java deleted file mode 100644 index 43a36c6..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/ComboBoxIdentifiedByDisplayedValue.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import com.heliumhq.selenium_wrappers.WebElementWrapper; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.ui.Select; - -import java.util.ArrayList; -import java.util.List; - -public class ComboBoxIdentifiedByDisplayedValue - extends HTMLElementContainingText { - - public ComboBoxIdentifiedByDisplayedValue( - WebDriverWrapper driver, String text, SearchRegion... searchRegions - ) { - super(driver, text, searchRegions); - } - - @Override - protected String getXPathNodeSelector() { - return "option"; - } - - @Override - protected String getXPath() { - return super.getXPath() + "/ancestor::select[1]"; - } - - @Override - protected List findAllInCurrFrame() { - List allCbsWithAMatchingValue = - super.findAllInCurrFrame(); - List result = new ArrayList(); - for (WebElementWrapper cb : allCbsWithAMatchingValue) { - Select select = new Select(cb.unwrap()); - for (WebElement selectedOption : select.getAllSelectedOptions()) - if (matches.text(selectedOption.getText(), searchText)) { - result.add(cb); - break; - } - } - return result; - } -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/ComboBoxIdentifiedByLabel.java b/helium-java/src/main/java/com/heliumhq/api_impl/ComboBoxIdentifiedByLabel.java deleted file mode 100644 index 59a26a5..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/ComboBoxIdentifiedByLabel.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; - -public class ComboBoxIdentifiedByLabel extends LabelledElement { - - ComboBoxIdentifiedByLabel( - WebDriverWrapper driver, String label, SearchRegion... searchRegions - ) { - super(driver, label, searchRegions); - } - - @Override - protected String getXPath() { - return "//select | //input[@list]"; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/ComboBoxImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/ComboBoxImpl.java deleted file mode 100644 index 4d23ae0..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/ComboBoxImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.ui.Select; - -import java.util.ArrayList; -import java.util.List; - -public class ComboBoxImpl extends CompositeElement { - - private final String label; - - public ComboBoxImpl( - WebDriverWrapper driver, SearchRegion... searchRegions - ) { - this(driver, null, searchRegions); - } - - public ComboBoxImpl( - WebDriverWrapper driver, String label, SearchRegion... searchRegions - ) { - super(driver, searchRegions); - this.label = label; - } - - @Override - protected HTMLElementImpl[] getElements() { - return new HTMLElementImpl[] { - new ComboBoxIdentifiedByDisplayedValue( - driver, label, searchRegions - ), - new ComboBoxIdentifiedByLabel(driver, label, searchRegions) - }; - } - - public boolean isEditable() { - return ! "select".equals(getFirstOccurrence().getTagName()); - } - - public String getValue() { - WebElement selectedOption = getSelectDriver().getFirstSelectedOption(); - if (selectedOption != null) { - return selectedOption.getText(); - } - return null; - } - - public List getOptions() { - List result = new ArrayList(); - for (WebElement option : getSelectDriver().getOptions()) - result.add(option.getText()); - return result; - } - - @Override - protected Object[] getConstructorArgsBeforeSearchRegions() { - return new Object[] {label}; - } - - private Select getSelectDriver() { - return new Select(getWebElement()); - } - -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/CompositeElement.java b/helium-java/src/main/java/com/heliumhq/api_impl/CompositeElement.java deleted file mode 100644 index edb8aa7..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/CompositeElement.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import com.heliumhq.selenium_wrappers.WebElementWrapper; -import com.heliumhq.util.Generator; - -import java.util.*; - -import static java.util.Arrays.asList; - -abstract class CompositeElement extends HTMLElementImpl { - - private GUIElementImpl firstElement; - - CompositeElement(WebDriverWrapper driver, SearchRegion... searchRegions) { - super(driver, searchRegions); - } - - protected GUIElementImpl getFirstElement() { - if (firstElement == null) { - bindToFirstOccurrence(); - // findAllInCurrFrame() below now sets firstElement. - } - return firstElement; - } - - protected abstract HTMLElementImpl[] getElements(); - - @Override - protected Iterable findAllInCurrFrame() { - return new Generator() { - - List alreadyYielded; - Iterator elements; - HTMLElementImpl element; - Iterator boundGuiEltImpls; - - @Override - protected WebElementWrapper generateNext() { - if (alreadyYielded == null) - alreadyYielded = new ArrayList(); - if (elements == null) - elements = asList(getElements()).iterator(); - while (true) { - if (element == null) - element = elements.next(); - if (boundGuiEltImpls == null) - boundGuiEltImpls = - element.findAllInCurrFrame().iterator(); - while (boundGuiEltImpls.hasNext()) { - WebElementWrapper boundGuiEltImpl = - boundGuiEltImpls.next(); - if (firstElement == null) - firstElement = element; - if (!alreadyYielded.contains(boundGuiEltImpl)) { - alreadyYielded.add(boundGuiEltImpl); - return boundGuiEltImpl; - } - } - element = null; - boundGuiEltImpls = null; - } - } - - }; - } - -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/DragAndDropFile.java b/helium-java/src/main/java/com/heliumhq/api_impl/DragAndDropFile.java deleted file mode 100644 index 192259c..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/DragAndDropFile.java +++ /dev/null @@ -1,184 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import com.heliumhq.selenium_wrappers.WebElementWrapper; -import com.heliumhq.util.Tuple; -import org.openqa.selenium.WebElement; - -class DragAndDropFile { - - private final WebDriverWrapper driver; - private final String filePath; - private WebElement fileInputElement; - private JavaScriptInterval dragoverEvent; - - DragAndDropFile(WebDriverWrapper driver, String filePath) { - this.driver = driver; - this.filePath = filePath; - } - - void begin() { - createFileInputElement(); - try { - fileInputElement.sendKeys(filePath); - } catch (RuntimeException e) { - end(); - throw e; - } - } - - private void createFileInputElement() { - // The input needs to be visible to Selenium to allow sending keys to it - // in Firefox and IE. - // According to http://stackoverflow.com/questions/6101461/ - // Selenium criteria whether an element is visible or not are the - // following: - // - visibility != hidden - // - display != none (is also checked against every parent element) - // - opacity != 0 - // - height and width are both > 0 - // - for an input, the attribute type != hidden - // So let's make sure its all good! - fileInputElement = (WebElement) driver.executeScript( - "var input = document.createElement('input');" + - "input.type = 'file';" + - "input.style.display = 'block';" + - "input.style.opacity = '1';" + - "input.style.visibility = 'visible';" + - "input.style.height = '1px';" + - "input.style.width = '1px';" + - "if (document.body.childElementCount > 0) { " + - " document.body.insertBefore(input, document.body.childNodes[0]);"+ - "} else { " + - " document.body.appendChild(input);" + - "}" + - "return input;" - ); - } - - void dragOverDocument() { - // According to the HTML5 spec, we need to dispatch the dragenter event - // once, and then the dragover event continuously, every 350+-200ms: - // http://www.w3.org/html/wg/drafts/html/master/editing.html#current- - // drag-operation - // Especially IE implements this spec very tightly, and considers the - // dragging to be over if no dragover event occurs for more than ~1sec. - // We thus need to ensure that we keep dispatching the dragover event. - - // This line used to read `dispatchEvent(..., "document");`. However, - // this doesn't work when adding a photo to a tweet on Twitter. - // Dispatching the event to document.body fixes this, and also works for - // Gmail: - dispatchEvent("dragenter", "document.body"); - dragoverEvent = prepareContinuousEvent("dragover", "document", 300); - dragoverEvent.start(); - } - - private void dispatchEvent(String eventName, String to) { - Tuple scriptArgs = - prepareDispatchEvent(eventName, to); - driver.executeScript(scriptArgs.getFirst(), scriptArgs.getSecond()); - } - private void dispatchEvent(String eventName, WebElementWrapper to) { - Tuple scriptArgs = - prepareDispatchEvent(eventName, to); - driver.executeScript(scriptArgs.getFirst(), scriptArgs.getSecond()); - } - - private JavaScriptInterval prepareContinuousEvent( - String eventName, String to, long intervalMsecs - ) { - Tuple scriptArgs = - prepareDispatchEvent(eventName, to); - return new JavaScriptInterval( - driver, scriptArgs.getFirst(), scriptArgs.getSecond(), - intervalMsecs - ); - } - - private Tuple prepareDispatchEvent( - String eventName, String to - ) { - String script = DISPATCH_EVENT_SCRIPT.replace("arguments[2]", to); - return new Tuple( - script, new Object[] {fileInputElement, eventName} - ); - } - - private final String DISPATCH_EVENT_SCRIPT = - "var files = arguments[0].files;" + - "var items = [];" + - "var types = [];" + - "for (var i = 0; i < files.length; i++) {" + - " items[i] = {kind: 'file', type: files[i].type};" + - " types[i] = 'Files';" + - "}" + - "var event = document.createEvent('CustomEvent');" + - "event.initCustomEvent(arguments[1], true, true, 0);" + - "event.dataTransfer = {" + - " files: files," + - " items: items," + - " types: types" + - "};" + - "arguments[2].dispatchEvent(event);"; - - private Tuple prepareDispatchEvent( - String eventName, WebElementWrapper to - ) { - return new Tuple( - DISPATCH_EVENT_SCRIPT, - new Object[] {fileInputElement, eventName, to.unwrap()} - ); - } - - void dropOn(WebElementWrapper element) { - dragoverEvent.stop(); - dispatchEvent("drop", element); - } - - void end() { - if (fileInputElement != null) - driver.executeScript( - "arguments[0].parentNode.removeChild(arguments[0]);", - fileInputElement - ); - fileInputElement = null; - } - - private class JavaScriptInterval { - - private WebDriverWrapper driver; - private String script; - private Object[] args; - private long intervalMsecs; - private long intervalId; - - private JavaScriptInterval( - WebDriverWrapper driver, String script, Object[] args, - long intervalMsecs - ) { - this.driver = driver; - this.script = script; - this.args = args; - this.intervalMsecs = intervalMsecs; - } - - private void start() { - String setintervalScript = String.format( - "var originalArguments = arguments;" + - "return setInterval(function() {" + - " arguments = originalArguments;" + - " %s" + - "}, %d);", script, intervalMsecs - ); - intervalId = (Long) driver.executeScript(setintervalScript, args); - } - - private void stop() { - driver.executeScript("clearInterval(arguments[0]);", intervalId); - intervalId = 0L; - } - - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/DragHelper.java b/helium-java/src/main/java/com/heliumhq/api_impl/DragHelper.java deleted file mode 100644 index 69fc488..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/DragHelper.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebElementWrapper; - -class DragHelper { - - private final APIImpl apiImpl; - private boolean isHtml5Drag; - - DragHelper(APIImpl apiImpl) { - this.apiImpl = apiImpl; - this.isHtml5Drag = false; - } - - void begin() { - executeScript( - "window.helium = {};" + - "window.helium.dragHelper = {" + - " createEvent: function(type) {" + - " var event = document.createEvent('CustomEvent');" + - " event.initCustomEvent(type, true, true, null);" + - " event.dataTransfer = {" + - " data: {}," + - " setData: function(type, val) {" + - " this.data[type] = val;" + - " }," + - " getData: function(type) {" + - " return this.data[type];" + - " }" + - " };" + - " return event;" + - " }" + - "};" - ); - } - - void startDragging(WebElementWrapper element) { - if (attemptHtml5Drag(element)) - isHtml5Drag = true; - else - apiImpl.pressMouseOn(element); - } - - void dropOnTarget(WebElementWrapper target) { - if (isHtml5Drag) - completeHtml5Drag(target); - else - apiImpl.releaseMouseOver(target); - } - - void end() { - executeScript("delete window.helium;"); - } - - private boolean attemptHtml5Drag(WebElementWrapper elementToDrag) { - return (Boolean) executeScript( - "var source = arguments[0];" + - "function getDraggableParent(element) {" + - " var previousParent = null;" + - " while (element != null && element != previousParent) {" + - " previousParent = element;" + - " if ('draggable' in element) {" + - " var draggable = element.draggable;" + - " if (draggable === true)" + - " return element;" + - " if (typeof draggable == 'string' " + - " || draggable instanceof String)" + - " if (draggable.toLowerCase() == 'true')" + - " return element;" + - " }" + - " element = element.parentNode;" + - " }" + - " return null;" + - "}" + - "var draggableParent = getDraggableParent(source);" + - "if (draggableParent == null)" + - " return false;" + - "window.helium.dragHelper.draggedElement = draggableParent;" + - "var dragStart = " + - "window.helium.dragHelper.createEvent('dragstart');" + - "source.dispatchEvent(dragStart);" + - "window.helium.dragHelper.dataTransfer = dragStart.dataTransfer;" + - "return true;", - elementToDrag.unwrap() - ); - } - - private void completeHtml5Drag(WebElementWrapper on) { - executeScript( - "var target = arguments[0];" + - "var drop = window.helium.dragHelper.createEvent('drop');" + - "drop.dataTransfer = window.helium.dragHelper.dataTransfer;" + - "target.dispatchEvent(drop);" + - "var dragEnd = window.helium.dragHelper.createEvent('dragend');" + - "dragEnd.dataTransfer = window.helium.dragHelper.dataTransfer;" + - "window.helium.dragHelper.draggedElement.dispatchEvent(dragEnd);", - on.unwrap() - ); - } - - private Object executeScript(String script, Object... args) { - return apiImpl.requireDriver().executeScript(script, args); - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/DriverServiceDestroyer.java b/helium-java/src/main/java/com/heliumhq/api_impl/DriverServiceDestroyer.java deleted file mode 100644 index 16e75fa..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/DriverServiceDestroyer.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.heliumhq.api_impl; - -import org.openqa.selenium.os.CommandLine; -import org.openqa.selenium.remote.service.DriverService; - -import java.lang.reflect.Field; -import java.util.concurrent.locks.ReentrantLock; - -class DriverServiceDestroyer extends Thread { - - private final DriverService driverService; - - DriverServiceDestroyer(DriverService driverService) { - this.driverService = driverService; - } - - public void run() { - try { - ReentrantLock lock = (ReentrantLock) getField("lock"); - try { - lock.lock(); - CommandLine process = (CommandLine) getField("process"); - if (process == null) - return; - process.destroy(); - setField("process", null); - } finally { - lock.unlock(); - } - } catch (Exception e) { - throw new RuntimeException( - "Unable to shutdown " + driverService + ".", e - ); - } - } - - private Object getField(String fieldName) throws - NoSuchFieldException, IllegalAccessException { - return getFieldDefinition(fieldName).get(driverService); - } - private Field getFieldDefinition(String fieldName) throws - NoSuchFieldException { - Field field = DriverService.class.getDeclaredField(fieldName); - field.setAccessible(true); - return field; - } - private void setField(String fieldName, Object value) throws - IllegalAccessException, NoSuchFieldException { - getFieldDefinition(fieldName).set(driverService, value); - } -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/FileInput.java b/helium-java/src/main/java/com/heliumhq/api_impl/FileInput.java deleted file mode 100644 index ab5dc4e..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/FileInput.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; - -class FileInput extends LabelledElement { - - FileInput(WebDriverWrapper driver, SearchRegion... searchRegions) { - super(driver, searchRegions); - } - - FileInput( - WebDriverWrapper driver, String label, SearchRegion... searchRegions - ) { - super(driver, label, searchRegions); - } - - @Override - protected String getXPath() { - return "//input[@type='file']"; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/FreeText.java b/helium-java/src/main/java/com/heliumhq/api_impl/FreeText.java deleted file mode 100644 index a17964d..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/FreeText.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; - -public class FreeText extends HTMLElementContainingText { - public FreeText( - WebDriverWrapper driver, String text, SearchRegion... searchRegions - ) { - super(driver, text, searchRegions); - } - - @Override - protected String getXPathNodeSelector() { - return "text()"; - } - - @Override - protected String getXPath() { - return super.getXPath() + "/.."; - } -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/GUIElementImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/GUIElementImpl.java deleted file mode 100644 index e68f926..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/GUIElementImpl.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import com.heliumhq.util.Generator; -import org.openqa.selenium.ElementNotVisibleException; -import org.openqa.selenium.NoSuchElementException; -import org.openqa.selenium.WebDriverException; -import org.openqa.selenium.interactions.MoveTargetOutOfBoundsException; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import static com.heliumhq.API.Config; -import static com.heliumhq.util.StringUtils.escape; -import static com.heliumhq.util.StringUtils.join; -import static java.lang.System.currentTimeMillis; -import static java.util.Arrays.asList; - -public abstract class GUIElementImpl implements Cloneable { - - protected final WebDriverWrapper driver; - private T boundOccurrence; - - protected GUIElementImpl(WebDriverWrapper driver) { - this.driver = driver; - } - - public boolean exists() { - return findAll().iterator().hasNext(); - } - - public Iterable> findAll() { - if (isBound()) - return asList(this); - final Iterator allOccurrences = findAllOccurrences().iterator(); - return new Generator>() { - @Override - protected GUIElementImpl generateNext() { - return boundToOccurrence(allOccurrences.next()); - } - }; - } - - @Override - public String toString() { - return toString(getClass().getSimpleName()); - } - - public String toString(String className) { - return String.format( - "%s(%s)", className, reprConstuctorArgs() - ); - } - - protected String reprConstuctorArgs() { - Object[] constructorArgs = getConstructorArgs(); - List constructorArgsReprs = new ArrayList(); - for (Object arg : constructorArgs) { - if (arg instanceof String) - constructorArgsReprs.add(escape((String) arg)); - else if (arg != null) - constructorArgsReprs.add(arg.toString()); - } - return join(", ", constructorArgsReprs); - } - - protected abstract Object[] getConstructorArgs(); - - protected boolean isBound() { - return boundOccurrence != null; - } - - protected abstract Iterable findAllOccurrences(); - - GUIElementImpl boundToOccurrence(T occurrence) { - GUIElementImpl result; - try { - result = (GUIElementImpl) clone(); - } catch (CloneNotSupportedException e) { - throw new RuntimeException(e); - } - result.boundOccurrence = occurrence; - return result; - } - - protected T getFirstOccurrence() { - if (! isBound()) - bindToFirstOccurrence(); - return boundOccurrence; - } - - protected void bindToFirstOccurrence() { - perform(new NoOpAction()); - // performNoWait(...) below now sets boundOccurrence. - } - - T perform(Action action) { - long endTime = currentTimeMillis() + - (long) (Config.getImplicitWaitSecs() * 1000); - // Try to perform `action` at least once: - T result = performNoWait(action); - while (result == null && currentTimeMillis() < endTime) - result = performNoWait(action); - if (result != null) - return result; - throw new NoSuchElementException("Cannot find element " + this + "."); - } - - private T performNoWait(Action action) { - for (GUIElementImpl boundGUIElementImpl : findAll()) { - T occurrence = boundGUIElementImpl.getFirstOccurrence(); - try { - action.performOn(occurrence); - } catch (RuntimeException e) { - if (shouldIgnoreException(e)) - continue; - else - throw e; - } - boundOccurrence = occurrence; - return occurrence; - } - return null; - } - - private boolean shouldIgnoreException(RuntimeException e) { - if (e instanceof ElementNotVisibleException) - return true; - if (e instanceof MoveTargetOutOfBoundsException) - return true; - if (e instanceof WebDriverException) { - String msg = e.getMessage(); - if (msg != null && msg.contains("Element is not clickable at point") - && msg.contains("Other element would receive the click") - ) - return true; - } - return false; - } - - private class NoOpAction extends Action { - @Override - public void performOn(T element) {} - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/HTMLElementContainingText.java b/helium-java/src/main/java/com/heliumhq/api_impl/HTMLElementContainingText.java deleted file mode 100644 index 62516b3..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/HTMLElementContainingText.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; - -import static com.heliumhq.util.XPath.predicate; - -abstract class HTMLElementContainingText extends HTMLElementIdentifiedByXPath { - - protected final String searchText; - - public HTMLElementContainingText( - WebDriverWrapper driver, SearchRegion... searchRegions - ) { - this(driver, null, searchRegions); - } - - public HTMLElementContainingText( - WebDriverWrapper driver, String text, SearchRegion... searchRegions - ) { - super(driver, searchRegions); - this.searchText = text; - } - - @Override - protected String getXPath() { - String xpathBase = "//" + getXPathNodeSelector() + - predicate(matches.xpath(".", searchText)); - return String.format( - "%s[not(self::script)][not(.%s)]", xpathBase, xpathBase - ); - } - - protected String getXPathNodeSelector() { - return "*"; - } - - @Override - protected Object[] getConstructorArgsBeforeSearchRegions() { - return new Object[] {searchText}; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/HTMLElementIdentifiedByXPath.java b/helium-java/src/main/java/com/heliumhq/api_impl/HTMLElementIdentifiedByXPath.java deleted file mode 100644 index 5b185d8..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/HTMLElementIdentifiedByXPath.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import com.heliumhq.selenium_wrappers.WebElementWrapper; -import org.openqa.selenium.By; -import org.openqa.selenium.StaleElementReferenceException; - -import java.util.ArrayList; -import java.util.List; - -abstract class HTMLElementIdentifiedByXPath extends HTMLElementImpl { - - HTMLElementIdentifiedByXPath( - WebDriverWrapper driver, SearchRegion... searchRegions - ) { - super(driver, searchRegions); - } - - @Override - protected List findAllInCurrFrame() { - String xpath = getXPath(); - List result = new ArrayList(); - for (org.openqa.selenium.WebElement element : - driver.findElements(By.xpath(xpath))) - result.add(new WebElementWrapper(driver, element)); - return sortSearchResult(result); - } - - private List sortSearchResult( - List result - ) { - List> resultScores = - new ArrayList>(); - for (WebElementWrapper element : result) { - try { - double score = getSortIndex(element); - resultScores.add( - new ResultScore(element, score) - ); - } catch (StaleElementReferenceException e) { - // Simply ignore the element. - } - } - return ResultScore.getSortedResults(resultScores); - } - - protected abstract String getXPath(); - - protected double getSortIndex(WebElementWrapper webElement) { - return driver.getDistanceToLastManipulated(webElement) + 1; - } -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/HTMLElementImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/HTMLElementImpl.java deleted file mode 100644 index e4808d7..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/HTMLElementImpl.java +++ /dev/null @@ -1,193 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.FrameIterator; -import com.heliumhq.selenium_wrappers.FramesChangedWhileIterating; -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import com.heliumhq.selenium_wrappers.WebElementWrapper; -import com.heliumhq.util.Generator; -import org.openqa.selenium.NoSuchWindowException; -import org.openqa.selenium.WebElement; - -import java.util.*; - -import static com.google.common.collect.ObjectArrays.concat; -import static com.heliumhq.API.Point; -import static com.heliumhq.util.HtmlUtils.getEasilyReadableSnippet; - -public abstract class HTMLElementImpl extends - GUIElementImpl { - - protected final SearchRegion[] searchRegions; - protected final MatchType matches; - - HTMLElementImpl( - WebDriverWrapper driver, SearchRegion... searchRegions - ) { - super(driver); - this.searchRegions = searchRegions; - matches = MatchType.PREFIX_IGNORE_CASE; - } - - public int getWidth() { - return getFirstOccurrence().getLocation().getWidth(); - } - - public int getHeight() { - return getFirstOccurrence().getLocation().getHeight(); - } - - public int getX() { - return getFirstOccurrence().getLocation().getLeft(); - } - - public int getY() { - return getFirstOccurrence().getLocation().getTop(); - } - - public Point getTopLeft() { - return Point(getX(), getY()); - } - - public WebElement getWebElement() { - return getFirstOccurrence().unwrap(); - } - - @Override - protected Object[] getConstructorArgs() { - Object[] normalConstrArgs = getConstructorArgsBeforeSearchRegions(); - return concat(normalConstrArgs, searchRegions, Object.class); - } - - protected abstract Object[] getConstructorArgsBeforeSearchRegions(); - - @Override - public String toString(String className) { - if (isBound()) { - String elementHtml = getWebElement().getAttribute("outerHTML"); - return getEasilyReadableSnippet(elementHtml); - } else - return super.toString(className); - } - - @Override - protected Iterable findAllOccurrences() { - return new Generator() { - - private boolean firstCall = true; - private Iterator frameIndices; - private int[] frameIndex; - List searchRegions; - Iterator occurrences; - - @Override - protected WebElementWrapper generateNext() { - if (firstCall) { - firstCall = false; - handleClosedWindow(); - driver.switchTo().defaultContent(); - } - if (frameIndices == null) - frameIndices = new FrameIterator(driver).iterator(); - while (true) { - if (frameIndex == null) - try { - frameIndex = frameIndices.next(); - } catch (FramesChangedWhileIterating e) { - // Abort this search: - throw new NoSuchElementException(); - } - if (searchRegions == null) - searchRegions = getSearchRegionsInCurrFrame(); - if (occurrences == null) - occurrences = findAllInCurrFrame().iterator(); - while (occurrences.hasNext()) { - WebElementWrapper occ = occurrences.next(); - if (shouldYield(occ, searchRegions)) { - occ.setFrameIndex(frameIndex); - return occ; - } - } - frameIndex = null; - searchRegions = null; - occurrences = null; - } - } - - private void handleClosedWindow() { - boolean windowHasBeenClosed; - Set windowHandles = driver.getWindowHandles(); - try { - windowHasBeenClosed = - ! windowHandles.contains(driver.getWindowHandle()); - } catch (NoSuchWindowException e) { - windowHasBeenClosed = true; - } - if (windowHasBeenClosed) - driver.switchTo().window(windowHandles.iterator().next()); - } - - }; - } - - private List getSearchRegionsInCurrFrame() { - List result = - new ArrayList(); - for (SearchRegion searchRegion : searchRegions) - result.addAll(searchRegion.getOccurrencesInCurrFrame()); - return result; - } - - private boolean shouldYield( - WebElementWrapper occurrence, - List searchRegions - ) { - return occurrence.isDisplayed() && - isInAnySearchRegion(occurrence, searchRegions); - } - - private boolean isInAnySearchRegion( - WebElementWrapper element, List searchRegions - ) { - // group by SearchDirection - Map> directionToRegion - = new HashMap>(); - for (SearchRegion.Occurrence searchRegion : searchRegions) { - SearchDirection direction = searchRegion.getSearchDirection(); - if (!directionToRegion.containsKey(direction)) { - directionToRegion.put( - direction, - new ArrayList() - ); - } - directionToRegion.get(direction).add(searchRegion); - } - - for (SearchDirection direction : SearchDirection.values()) { - if (directionToRegion.containsKey(direction)) { - boolean found = false; - for (SearchRegion.Occurrence searchRegion : - directionToRegion.get(direction)) { - if (searchRegion.contains(element)) { - found = true; - break; - } - } - if (!found) { - return false; - } - } - } - - return true; - } - - protected abstract Iterable findAllInCurrFrame(); - - /** - * Useful for subclasses. - */ - protected boolean isEnabled() { - return getFirstOccurrence().getAttribute("disabled") == null; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/ImageImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/ImageImpl.java deleted file mode 100644 index 40e7a46..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/ImageImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; - -import static com.heliumhq.util.XPath.predicate; - -public class ImageImpl extends HTMLElementIdentifiedByXPath { - - private final String alt; - - public ImageImpl(WebDriverWrapper driver, SearchRegion... searchRegions) { - this(driver, null, searchRegions); - } - - public ImageImpl( - WebDriverWrapper driver, String alt, SearchRegion... searchRegions - ) { - super(driver, searchRegions); - this.alt = alt; - } - - @Override - protected Object[] getConstructorArgsBeforeSearchRegions() { - return new Object[] {alt}; - } - - @Override - protected String getXPath() { - return "//img" + predicate(matches.xpath("@alt", alt)); - } - -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/LabelledElement.java b/helium-java/src/main/java/com/heliumhq/api_impl/LabelledElement.java deleted file mode 100644 index 692840b..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/LabelledElement.java +++ /dev/null @@ -1,243 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import com.heliumhq.selenium_wrappers.WebElementWrapper; -import com.heliumhq.util.Tuple; -import com.heliumhq.util.geom.Rectangle; -import org.openqa.selenium.By; -import org.openqa.selenium.WebElement; - -import java.util.*; - -import static com.heliumhq.util.Collections.inverse; -import static com.heliumhq.util.XPath.predicate; -import static com.heliumhq.util.StringUtils.isEmpty; - -abstract class LabelledElement extends HTMLElementImpl { - - private final static double SECONDARY_SEARCH_DIMENSION_PENALTY_FACTOR = 1.5; - - private final String label; - - LabelledElement(WebDriverWrapper driver, SearchRegion... searchRegions) { - this(driver, null, searchRegions); - } - - LabelledElement( - WebDriverWrapper driver, String label, SearchRegion... searchRegions - ) { - super(driver, searchRegions); - this.label = label; - } - - @Override - protected Object[] getConstructorArgsBeforeSearchRegions() { - return new Object[] {label}; - } - - @Override - protected List findAllInCurrFrame() { - List result; - if (isEmpty(label)) - result = findElts(); - else { - List labels = - new TextImpl(driver, label, false).findAllInCurrFrame(); - if (! labels.isEmpty()) - result = filterEltsBelongingToLabels(findElts(), labels); - else - result = findEltsByFreeText(); - } - Collections.sort(result, new Comparator() { - @Override - public int compare(WebElementWrapper e1, WebElementWrapper e2) { - double s1 = driver.getDistanceToLastManipulated(e1); - double s2 = driver.getDistanceToLastManipulated(e2); - return (int) Math.round(s1 - s2); - } - }); - return result; - } - - private List findElts() { - return findElts(null); - } - - private List findElts(String xpath) { - if (xpath == null) - xpath = getXPath(); - List result = new ArrayList(); - for (WebElement element : driver.findElements(By.xpath(xpath))) - result.add(new WebElementWrapper(driver, element)); - return result; - } - - private List findEltsByFreeText() { - List eltTypes = new ArrayList(); - for (String xpath : getXPath().split(("\\|"))) - eltTypes.add(xpath.trim().replaceAll("^/+", "")); - String labels = "//text()" + predicate(matches.xpath(".", label)); - StringBuilder xpath = new StringBuilder(); - boolean isFirst = true; - for (String eltType : eltTypes) { - if (! isFirst) - xpath.append(" | "); - xpath.append(labels); - String axis; - if (eltType.contains("checkbox") || eltType.contains("radio")) { - axis = "preceding-sibling"; - } else { - axis = "following"; - } - xpath.append(String.format("/%s::", axis)); - xpath.append(eltType); - xpath.append("[1]"); - isFirst = false; - } - return findElts(xpath.toString()); - } - - protected abstract String getXPath(); - - protected SearchDirection getPrimarySearchDirection() { - return SearchDirection.TO_RIGHT_OF; - } - - protected SearchDirection getSecondarySearchDirection() { - return SearchDirection.BELOW; - } - - private List filterEltsBelongingToLabels( - List allElts, List labels - ) { - List result = new ArrayList(); - for (Tuple tpl : - getLabelsWithExplicitElts(allElts, labels)) { - WebElementWrapper label = tpl.getFirst(); - WebElementWrapper elt = tpl.getSecond(); - result.add(elt); - labels.remove(label); - allElts.remove(elt); - } - Map> labelsToElts = - getRelatedElts(allElts, labels); - labelsToElts = ensureAtMostOneLabelPerElt(labelsToElts); - retainClosest(labelsToElts); - for (Set eltsForLabel : labelsToElts.values()) { - assert eltsForLabel.size() <= 1; - if (eltsForLabel.size() > 0) - result.add(eltsForLabel.iterator().next()); - } - return result; - } - - private List> - getLabelsWithExplicitElts( - List allElts, List labels - ) { - List> result = - new ArrayList>(); - for (WebElementWrapper label : labels) - if ("label".equals(label.getTagName())) { - String labelTarget = label.getAttribute("for"); - if (!isEmpty(labelTarget)) - for (WebElementWrapper elt : allElts) { - String eltId = elt.getAttribute("id"); - if (labelTarget.equalsIgnoreCase(eltId)) - result.add( - new Tuple< - WebElementWrapper, WebElementWrapper - >(label, elt) - ); - } - } - return result; - } - - private Map> - getRelatedElts( - List allElts, List labels - ) { - Map> result = - new HashMap>(); - for (WebElementWrapper label : labels) - for (WebElementWrapper elt : allElts) - if (areRelated(elt, label)) { - if (!result.containsKey(label)) - result.put(label, new HashSet()); - result.get(label).add(elt); - } - return result; - } - - private boolean areRelated( - WebElementWrapper elt, WebElementWrapper label - ) { - Rectangle eltLoc = elt.getLocation(); - Rectangle labelLoc = label.getLocation(); - if (eltLoc.intersects(labelLoc)) - return true; - SearchDirection primSearchDir = getPrimarySearchDirection(); - SearchDirection secSearchDir = getSecondarySearchDirection(); - return labelLoc.getDistanceTo(eltLoc) <= 150 && ( - primSearchDir.isInDirection(eltLoc, labelLoc) || - secSearchDir.isInDirection(eltLoc, labelLoc) - ); - } - - private Map> - ensureAtMostOneLabelPerElt( - Map> labelsToElts - ) { - Map> eltsToLabels = - inverse(labelsToElts); - retainClosest(eltsToLabels); - return inverse(eltsToLabels); - } - - private void retainClosest( - Map> pivotsToElts - ) { - for (WebElementWrapper pivot : pivotsToElts.keySet()) { - Set elts = pivotsToElts.get(pivot); - if (! elts.isEmpty()) - pivotsToElts.put( - pivot, - new HashSet( - Arrays.asList(findClosest(pivot, elts)) - ) - ); - } - } - - private WebElementWrapper findClosest( - WebElementWrapper toPivot, Set amongElts - ) { - Iterator remainingElts = amongElts.iterator(); - WebElementWrapper result = remainingElts.next(); - double resultDistance = computeDistance(result, toPivot); - while (remainingElts.hasNext()) { - WebElementWrapper element = remainingElts.next(); - double elementDistance = computeDistance(element, toPivot); - if (elementDistance < resultDistance) { - result = element; - resultDistance = elementDistance; - } - } - return result; - } - - private double computeDistance( - WebElementWrapper elt1, WebElementWrapper elt2 - ) { - Rectangle loc1 = elt1.getLocation(); - Rectangle loc2 = elt2.getLocation(); - double factor; - if (getSecondarySearchDirection().isInDirection(loc1, loc2)) - factor = SECONDARY_SEARCH_DIMENSION_PENALTY_FACTOR; - else - factor = 1; - return factor * loc1.getDistanceTo(loc2); - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/LinkImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/LinkImpl.java deleted file mode 100644 index e7e37bf..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/LinkImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.heliumhq.util.XPath.predicate; - -public class LinkImpl extends HTMLElementContainingText { - - public LinkImpl(WebDriverWrapper driver, SearchRegion... searchRegions) { - super(driver, searchRegions); - } - - public LinkImpl( - WebDriverWrapper driver, String text, SearchRegion... searchRegions - ) { - super(driver, text, searchRegions); - } - - public String getHref() { - return this.getWebElement().getAttribute("href"); - } - - @Override - protected String getXPathNodeSelector() { - return "a"; - } - - @Override - protected String getXPath() { - return super.getXPath() + " | " + "//a" + - predicate(matches.xpath("@title", searchText)) + " | " + - "//*[@role='link']" + predicate(matches.xpath(".", searchText)); - } -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/ListItemImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/ListItemImpl.java deleted file mode 100644 index 5b596d5..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/ListItemImpl.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; - -public class ListItemImpl extends HTMLElementContainingText { - - public ListItemImpl( - WebDriverWrapper driver, SearchRegion... searchRegions - ) { - super(driver, searchRegions); - } - - public ListItemImpl( - WebDriverWrapper driver, String text, SearchRegion... searchRegions - ) { - super(driver, text, searchRegions); - } - - @Override - protected String getXPathNodeSelector() { - return "li"; - } - -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/MatchType.java b/helium-java/src/main/java/com/heliumhq/api_impl/MatchType.java deleted file mode 100644 index 371d2b7..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/MatchType.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.heliumhq.api_impl; - -import static com.heliumhq.util.XPath.lower; -import static com.heliumhq.util.XPath.replaceNbsp; -import static com.heliumhq.util.StringUtils.isEmpty; -import static com.heliumhq.util.StringUtils.join; - -enum MatchType { - PREFIX_IGNORE_CASE() { - @Override - public String xpath(String value, String text) { - if (isEmpty(text)) - return ""; - // Asterisks '*' are sometimes used to mark required fields. Eg.: - // - // The starts-with filter below would be too strict to include such - // matches. To get around this, we ignore asterisks unless the - // searched text itself contains one. - String stripAsterisks; - if (text.contains("*")) { - stripAsterisks = value; - } else { - stripAsterisks = String.format("translate(%s, '*', '')", value); - } - // if text contains apostrophes (single quotes) then they need to be - // treated with care - if (text.contains("'")) { - text = String.format( - "concat('%s')", join("',\"'\",'", text.split("'")) - ); - } else { - text = String.format("'%s'", text); - } - - return String.format( - "starts-with(normalize-space(%s), %s)", - lower(replaceNbsp(stripAsterisks)), text.toLowerCase() - ); - } - @Override - public boolean text(String value, String text) { - if (isEmpty(text)) - return true; - return value.toLowerCase().trim().startsWith(text.toLowerCase()); - } - }; - public abstract String xpath(String value, String text); - public abstract boolean text(String value, String text); -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/RadioButtonImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/RadioButtonImpl.java deleted file mode 100644 index 04defad..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/RadioButtonImpl.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; - -public class RadioButtonImpl extends LabelledElement { - - public RadioButtonImpl( - WebDriverWrapper driver, SearchRegion... searchRegions - ) { - super(driver, searchRegions); - } - - public RadioButtonImpl( - WebDriverWrapper driver, String label, SearchRegion... searchRegions - ) { - super(driver, label, searchRegions); - } - - public boolean isSelected() { - return getFirstOccurrence().getAttribute("checked") != null; - } - - @Override - protected String getXPath() { - return "//input[@type='radio']"; - } - - @Override - protected SearchDirection getPrimarySearchDirection() { - return SearchDirection.TO_LEFT_OF; - } - - @Override - protected SearchDirection getSecondarySearchDirection() { - return SearchDirection.TO_RIGHT_OF; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/ResultScore.java b/helium-java/src/main/java/com/heliumhq/api_impl/ResultScore.java deleted file mode 100644 index 0a50fd9..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/ResultScore.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.heliumhq.api_impl; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -class ResultScore implements Comparable> { - public static List getSortedResults( - Collection> resultScores - ) { - List> sortedResultScores = - new ArrayList>(); - sortedResultScores.addAll(resultScores); - Collections.sort(sortedResultScores); - List result = new ArrayList(); - for (ResultScore resultScore : sortedResultScores) - result.add(resultScore.result); - return result; - } - final T result; - double score; - ResultScore(T result) { - this(result, 0); - } - ResultScore(T result, double score) { - this.result = result; - this.score = score; - } - @Override - public int compareTo(ResultScore other) { - return (int) Math.round(score - other.score); - } -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/SearchDirection.java b/helium-java/src/main/java/com/heliumhq/api_impl/SearchDirection.java deleted file mode 100644 index 5b165b2..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/SearchDirection.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.util.geom.Rectangle; - -public enum SearchDirection { - - TO_LEFT_OF { - @Override - public boolean isInDirection(Rectangle r1, Rectangle r2) { - return r1.isToLeftOf(r2); - } - }, - TO_RIGHT_OF { - @Override - public boolean isInDirection(Rectangle r1, Rectangle r2) { - return r1.isToRightOf(r2); - } - }, - ABOVE { - @Override - public boolean isInDirection(Rectangle r1, Rectangle r2) { - return r1.isAbove(r2); - } - }, - BELOW { - @Override - public boolean isInDirection(Rectangle r1, Rectangle r2) { - return r1.isBelow(r2); - } - }; - - public abstract boolean isInDirection(Rectangle r1, Rectangle r2); - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/SearchRegion.java b/helium-java/src/main/java/com/heliumhq/api_impl/SearchRegion.java deleted file mode 100644 index 628fb3a..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/SearchRegion.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebElementWrapper; -import com.heliumhq.util.geom.Rectangle; - -import java.util.ArrayList; -import java.util.List; - -public class SearchRegion { - - private final SearchDirection searchDirection; - private final HTMLElementImpl pivotElement; - - public SearchRegion( - SearchDirection searchDirection, HTMLElementImpl element - ) { - this.searchDirection = searchDirection; - this.pivotElement = element; - } - - List getOccurrencesInCurrFrame() { - List result = new ArrayList(); - for (WebElementWrapper occurrence : pivotElement.findAllInCurrFrame()) - result.add( - new Occurrence(searchDirection, occurrence.getLocation()) - ); - return result; - } - - class Occurrence { - private final SearchDirection searchDirection; - private final Rectangle location; - private Occurrence( - SearchDirection searchDirection, Rectangle location - ) { - this.searchDirection = searchDirection; - this.location = location; - } - boolean contains(WebElementWrapper element) { - return searchDirection.isInDirection( - element.getLocation(), location - ); - } - public SearchDirection getSearchDirection() { - return this.searchDirection; - } - } - - public String toString() { - String pivotElementRepr; - if (pivotElement instanceof TextImpl) - // Strip surrounding 'Text('...')': - pivotElementRepr = pivotElement.reprConstuctorArgs(); - else - pivotElementRepr = pivotElement.toString(); - return String.format( - "%s(%s)", makeCamelCase(searchDirection.name()), pivotElementRepr - ); - } - - // "ABOVE" -> "above", "TO_LEFT_OF" -> "toLeftOf", etc. - private String makeCamelCase(String enumName) { - String[] components = enumName.split("_"); - StringBuilder result = new StringBuilder(components[0].toLowerCase()); - for (int i = 1; i < components.length; i++) { - String component = components[i]; - result.append(component.charAt(0)); - result.append(component.toLowerCase().substring(1)); - } - return result.toString(); - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/TextFieldImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/TextFieldImpl.java deleted file mode 100644 index cb82d33..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/TextFieldImpl.java +++ /dev/null @@ -1,175 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; - -import static com.heliumhq.util.XPath.lower; -import static com.heliumhq.util.XPath.predicate; - -public class TextFieldImpl extends CompositeElement { - - private final String label; - - public TextFieldImpl( - WebDriverWrapper driver, SearchRegion... searchRegions - ) { - this(driver, null, searchRegions); - } - - public TextFieldImpl( - WebDriverWrapper driver, String label, SearchRegion... searchRegions - ) { - super(driver, searchRegions); - this.label = label; - } - - @Override - protected Object[] getConstructorArgsBeforeSearchRegions() { - return new Object[] {label}; - } - - public String getValue() { - return ((TextFieldType) getFirstElement()).getValue(); - } - - public boolean isEnabled() { - return ((TextFieldType) getFirstElement()).isEnabled(); - } - - public boolean isEditable() { - return ((TextFieldType) getFirstElement()).isEditable(); - } - - @Override - protected HTMLElementImpl[] getElements() { - return new HTMLElementImpl[] { - new StandardTextFieldWithPlaceHolder( - driver, label, searchRegions - ), - new StandardTextFieldWithLabel(driver, label, searchRegions), - new AriaTextFieldWithLabel(driver, label, searchRegions) - }; - } - - private interface TextFieldType { - String getValue(); - boolean isEnabled(); - boolean isEditable(); - } - - private class StandardTextFieldWithLabel extends LabelledElement - implements TextFieldType { - - StandardTextFieldWithLabel( - WebDriverWrapper driver, String label, - SearchRegion... searchRegions - ) { - super(driver, label, searchRegions); - } - - @Override - public String getValue() { - String result = getFirstOccurrence().getAttribute("value"); - if (result == null) - return ""; - return result; - } - - @Override - public boolean isEnabled() { - return super.isEnabled(); - } - - @Override - public boolean isEditable() { - return getFirstOccurrence().getAttribute("readOnly") == null; - } - - @Override - protected String getXPath() { - return String.format( - "//input[%s='text' or %s='email' or %s='password'" + - " or %s='number' or %s='tel' or string-length(@type)=0]", - lower("@type"), lower("@type"), lower("@type"), lower("@type"), - lower("@type") - ) + " | //textarea | //*[@contenteditable='true']"; - } - } - - private class AriaTextFieldWithLabel extends LabelledElement - implements TextFieldType { - - AriaTextFieldWithLabel( - WebDriverWrapper driver, String label, - SearchRegion... searchRegions - ) { - super(driver, label, searchRegions); - } - - @Override - public String getValue() { - return getFirstOccurrence().getText(); - } - - @Override - public boolean isEnabled() { - return super.isEnabled(); - } - - @Override - public boolean isEditable() { - return getFirstOccurrence().getAttribute("readOnly") == null; - } - - @Override - protected String getXPath() { - return "//*[@role='textbox']"; - } - } - - private class StandardTextFieldWithPlaceHolder extends - HTMLElementIdentifiedByXPath implements TextFieldType { - - private final String label; - - StandardTextFieldWithPlaceHolder( - WebDriverWrapper driver, String label, - SearchRegion... searchRegions - ) { - super(driver, searchRegions); - this.label = label; - } - - @Override - public String getValue() { - String result = getFirstOccurrence().getAttribute("value"); - if (result == null) - return ""; - return result; - } - - @Override - public boolean isEnabled() { - return super.isEnabled(); - } - - @Override - public boolean isEditable() { - return getFirstOccurrence().getAttribute("readOnly") == null; - } - - @Override - protected Object[] getConstructorArgsBeforeSearchRegions() { - return new Object[] {label}; - } - - @Override - protected String getXPath() { - return String.format( - "(%s)%s", - new StandardTextFieldWithLabel(driver, label).getXPath(), - predicate(matches.xpath("@placeholder", label)) - ); - } - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/TextImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/TextImpl.java deleted file mode 100644 index fa7e9da..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/TextImpl.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; - -import static com.heliumhq.util.StringUtils.isEmpty; - -public class TextImpl extends HTMLElementContainingText { - - private final boolean includeFreeTexts; - - public TextImpl(WebDriverWrapper driver, SearchRegion... searchRegions) { - super(driver, searchRegions); - this.includeFreeTexts = true; - } - - public TextImpl( - WebDriverWrapper driver, String text, SearchRegion... searchRegions - ) { - super(driver, text, searchRegions); - this.includeFreeTexts = true; - } - - public TextImpl( - WebDriverWrapper driver, String label, boolean includeFreeTexts - ) { - super(driver, label); - this.includeFreeTexts = includeFreeTexts; - } - - public String getValue() { - return getFirstOccurrence().getText(); - } - - @Override - protected String getXPath() { - ButtonImpl buttonImpl = new ButtonImpl(driver, searchText); - LinkImpl linkImpl = new LinkImpl(driver, searchText); - String result = getSearchTextXPath(); - result += " | " + buttonImpl.getInputButtonXPath(); - result += " | " + linkImpl.getXPath(); - if (! isEmpty(searchText) && includeFreeTexts) - result += " | " + new FreeText(driver, searchText).getXPath(); - return result; - } - - String getSearchTextXPath() { - String result; - if (! isEmpty(searchText)) - result = super.getXPath(); - else { - String noDescendantWithSameText = - "not(.//*[normalize-space(.)=normalize-space(self::*)])"; - result = - String.format("//*[text() and %s]", noDescendantWithSameText); - } - return result + "[not(self::option)]" - + (this.includeFreeTexts ? "" : "[count(*) <= 1]"); - } - -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/WindowImpl.java b/helium-java/src/main/java/com/heliumhq/api_impl/WindowImpl.java deleted file mode 100644 index c2f5a73..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/WindowImpl.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.heliumhq.api_impl; - -import com.heliumhq.selenium_wrappers.WebDriverWrapper; -import org.openqa.selenium.NoSuchWindowException; -import org.openqa.selenium.WebDriver; - -import java.util.ArrayList; -import java.util.List; - -public class WindowImpl extends GUIElementImpl { - - private final String searchTitle; - - public WindowImpl(WebDriverWrapper driver) { - this(driver, null); - } - - public WindowImpl(WebDriverWrapper driver, String title) { - super(driver); - searchTitle = title; - } - - @Override - protected Iterable findAllOccurrences() { - List> resultScores = - new ArrayList>(); - for (String handle : driver.unwrap().getWindowHandles()) { - SeleniumWindow window = new SeleniumWindow(driver.unwrap(), handle); - if (searchTitle == null) - resultScores.add(new ResultScore(window)); - else { - String title = window.getTitle(); - if (title.startsWith(searchTitle)) { - int score = title.length() - searchTitle.length(); - resultScores.add( - new ResultScore(window, score) - ); - } - } - } - return ResultScore.getSortedResults(resultScores); - } - - public String getTitle() { - return getFirstOccurrence().getTitle(); - } - - public String getHandle() { - return getFirstOccurrence().getHandle(); - } - - @Override - protected Object[] getConstructorArgs() { - String title = isBound() ? getTitle() : searchTitle; - return new Object[] {title}; - } - - static class SeleniumWindow { - private final WebDriver driver; - private final String handle; - private String windowHandleBefore; - - public SeleniumWindow(WebDriver driver, String handle) { - this.driver = driver; - this.handle = handle; - } - - public String getHandle() { - return handle; - } - - public String getTitle() { - activateTemporarily(); - try { - return driver.getTitle(); - } finally { - restorePreviousWindow(); - } - } - - private void activateTemporarily() { - boolean doSwitch; - try { - windowHandleBefore = driver.getWindowHandle(); - doSwitch = ! windowHandleBefore.equals(handle); - } catch (NoSuchWindowException windowClosed) { - doSwitch = true; - } - if (doSwitch) - driver.switchTo().window(handle); - } - - private void restorePreviousWindow() { - if ( - windowHandleBefore != null && - !driver.getWindowHandle().equals(windowHandleBefore) - ) - driver.switchTo().window(windowHandleBefore); - } - } - -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/application_context/APIConfig.java b/helium-java/src/main/java/com/heliumhq/api_impl/application_context/APIConfig.java deleted file mode 100644 index 8a9200d..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/application_context/APIConfig.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.heliumhq.api_impl.application_context; - -import com.heliumhq.environment.ResourceLocator; -import com.heliumhq.api_impl.APIImpl; - -import java.util.logging.Level; -import java.util.logging.Logger; - -public abstract class APIConfig { - - private APIImpl apiImpl; - - public APIConfig() { - initializeLogging(); - } - - protected abstract void initializeLogging(); - - public APIImpl getAPIImpl() { - if (apiImpl == null) - apiImpl = new APIImpl(getResourceLocator()); - return apiImpl; - } - - public abstract ResourceLocator getResourceLocator(); - - protected void suppressSeleniumLoggers() { - Logger.getLogger("org.openqa.selenium").setLevel(Level.WARNING); - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/application_context/ApplicationContext.java b/helium-java/src/main/java/com/heliumhq/api_impl/application_context/ApplicationContext.java deleted file mode 100644 index ef7d677..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/application_context/ApplicationContext.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.heliumhq.api_impl.application_context; - -public class ApplicationContext { - - private static APIConfig APPLICATION_CONTEXT; - - public static APIConfig getApplicationContext() { - if (APPLICATION_CONTEXT == null) { - if (isDevelopment()) - APPLICATION_CONTEXT = new DevelopmentAPIConfig(); - else - APPLICATION_CONTEXT = new StandaloneAPIConfig(); - } - return APPLICATION_CONTEXT; - } - - private static boolean isDevelopment() { - return ! isRunningFromJar(); - } - - private static boolean isRunningFromJar() { - String className = ApplicationContext.class.getName().replace('.', '/'); - String classFileLocation = ApplicationContext.class.getResource( - "/" + className + ".class" - ).toString(); - return classFileLocation.startsWith("jar:"); - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/application_context/DevelopmentAPIConfig.java b/helium-java/src/main/java/com/heliumhq/api_impl/application_context/DevelopmentAPIConfig.java deleted file mode 100644 index e523a4c..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/application_context/DevelopmentAPIConfig.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.heliumhq.api_impl.application_context; - -import com.heliumhq.environment.ResourceLocator; - -import java.io.File; -import java.util.Arrays; - -import static com.heliumhq.util.System.*; - -public class DevelopmentAPIConfig extends APIConfig { - - private ResourceLocator resourceLocator; - - public static String getHeliumFile(String relPath) { - File result = getHeliumDir(); - for (String relPathComponent : relPath.split("/")) - result = new File(result, relPathComponent); - return result.getAbsolutePath(); - } - - public static File getHeliumDir() { - File result = new File(".").getAbsoluteFile(); - while (! Arrays.asList(result.list()).contains("pom.xml") || - ! result.getName().equalsIgnoreCase("helium")) - result = result.getParentFile(); - return result; - } - - @Override - protected void initializeLogging() { - suppressSeleniumLoggers(); - } - - @Override - public ResourceLocator getResourceLocator() { - if (resourceLocator == null) { - String platfDir; - if (isWindows()) - platfDir = "win"; - else if (isLinux()) - platfDir = "linux"; - else { - assert isOSX(); - platfDir = "macosx"; - } - resourceLocator = new ResourceLocator( - getHeliumFile("src/main/resources/" + platfDir), - getHeliumFile("target") - ); - } - return resourceLocator; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/application_context/StandaloneAPIConfig.java b/helium-java/src/main/java/com/heliumhq/api_impl/application_context/StandaloneAPIConfig.java deleted file mode 100644 index a9dd674..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/application_context/StandaloneAPIConfig.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.heliumhq.api_impl.application_context; - -import com.heliumhq.environment.ResourceLocator; -import com.heliumhq.util.FileUtil; - -import java.io.*; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.*; - -import static com.heliumhq.util.Date.createDate; -import static java.util.logging.Level.WARNING; - -public class StandaloneAPIConfig extends APIConfig { - - private ResourceLocator resourceLocator; - - @Override - protected void initializeLogging() { - suppressApacheHttpLogsOnStderr(); - suppressSeleniumLoggers(); - } - - /** - * When starting IEDriverServer, the Java implementation of Selenium polls - * the server by sending HTTP requests to it until it has initialized. Each - * failed poll attempt before that prints some log output on stderr: - * - * org.apache.http.impl.client.DefaultHttpClient tryExecute - * INFO: I/O exception (java.net.SocketException) caught when processing - * request: Software caused connection abort: recv failed - * org.apache.http.impl.client.DefaultHttpClient tryExecute - * INFO: Retrying request - * - * suppressApacheHttpLogsOnStderr() prevents this log message from - * appearing in most (but not all) cases. - * - * For further information on the issue, see http://jimevansmusic.blogspot. - * com/2012/12/seeing-info-messages-in-log-does-not.html or https://groups. - * google.com/forum/#!topic/selenium-users/iZKKXkhfV2k. - */ - private void suppressApacheHttpLogsOnStderr() { - Logger.getLogger("org.apache.http.impl").setLevel(Level.WARNING); - } - - @Override - public ResourceLocator getResourceLocator() { - if (resourceLocator == null) { - File containingJar = urlToFile( - StandaloneAPIConfig.class.getProtectionDomain().getCodeSource(). - getLocation() - ); - String heliumRoot = containingJar.getParentFile(). - getParentFile().getAbsolutePath(); - resourceLocator = new ResourceLocator(heliumRoot); - } - return resourceLocator; - } - - /** - * A file:// URL may contain special escape characters such as %20 in - * file:///c:/Documents%20and%20Settings/... This method converts file URLs - * to File objects while making a best effort to handle such cases (ie. - * return File("c:/Documents and Settings/...")). Unfortunately, the current - * implementation of this still isn't 100% bullet proof, see: - * https://weblogs.java.net/blog/kohsuke/archive/2007/04/how_to_convert.html - */ - private File urlToFile(URL fileURL) { - try { - return new File(fileURL.toURI()); - } catch (URISyntaxException e) { - return new File(fileURL.getPath()); - } - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/api_impl/application_context/StartupError.java b/helium-java/src/main/java/com/heliumhq/api_impl/application_context/StartupError.java deleted file mode 100644 index 18fd006..0000000 --- a/helium-java/src/main/java/com/heliumhq/api_impl/application_context/StartupError.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.heliumhq.api_impl.application_context; - -import com.heliumhq.errors.HeliumError; - -public class StartupError extends HeliumError { - public StartupError(String message) { - super(message); - } -} diff --git a/helium-java/src/main/java/com/heliumhq/environment/ResourceLocator.java b/helium-java/src/main/java/com/heliumhq/environment/ResourceLocator.java deleted file mode 100644 index e8808a4..0000000 --- a/helium-java/src/main/java/com/heliumhq/environment/ResourceLocator.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.heliumhq.environment; - -import java.io.File; - -public class ResourceLocator { - - String[] rootDirs; - - public ResourceLocator(String... rootDirs) { - this.rootDirs = rootDirs; - } - - public String locate(String... relPathComponents) { - for (String rootDir : rootDirs) { - String location = constructPath(rootDir, relPathComponents); - if (new File(location).exists()) - return location; - } - return constructPath(rootDirs[0], relPathComponents); - } - - private String constructPath(String root, String... relPathComponents) { - File result = new File(root); - for (String relPathComponent : relPathComponents) - result = new File(result, relPathComponent); - return result.getAbsolutePath(); - } - -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/errors/HeliumError.java b/helium-java/src/main/java/com/heliumhq/errors/HeliumError.java deleted file mode 100644 index 6591433..0000000 --- a/helium-java/src/main/java/com/heliumhq/errors/HeliumError.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.heliumhq.errors; - -import java.io.PrintStream; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.List; - -public class HeliumError extends Error { - - public HeliumError(String message) { - super(message); - } - - public HeliumError(Throwable cause) { - super(cause); - } - - public String toString() { - return "- " + getMessage(); - } - - public void printStackTrace() { - truncateStackTrace(); - super.printStackTrace(); - } - - private void truncateStackTrace() { - StackTraceElement[] stackTrace = getStackTrace(); - List newStackTrace = - new ArrayList(); - for (int i = stackTrace.length - 1; i >= 0; i--) { - newStackTrace.add(0, stackTrace[i]); - if (stackTrace[i].getClassName().startsWith("com.heliumhq.API")) - break; - } - setStackTrace(newStackTrace.toArray( - new StackTraceElement[newStackTrace.size()] - )); - } - - @Override - public void printStackTrace(PrintStream s) { - truncateStackTrace(); - super.printStackTrace(s); - } - - @Override - public void printStackTrace(PrintWriter s) { - truncateStackTrace(); - super.printStackTrace(s); - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/selenium_wrappers/FrameIterator.java b/helium-java/src/main/java/com/heliumhq/selenium_wrappers/FrameIterator.java deleted file mode 100644 index e7892ed..0000000 --- a/helium-java/src/main/java/com/heliumhq/selenium_wrappers/FrameIterator.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.heliumhq.selenium_wrappers; - -import com.heliumhq.util.Generator; -import org.openqa.selenium.NoSuchFrameException; -import org.openqa.selenium.WebDriverException; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -public class FrameIterator implements Iterable { - - private final WebDriverWrapper driver; - private final int[] startFrame; - - public FrameIterator(WebDriverWrapper driver) { - this(driver, new int[0]); - } - - public FrameIterator(WebDriverWrapper driver, int[] startFrame) { - this.driver = driver; - this.startFrame = startFrame; - } - - @Override - public Iterator iterator() { - return (new Generator() { - - boolean firstCall = true; - int newFrame = 0; - boolean newFrameChanged = true; - Iterator results; - - protected int[] generateNext() { - if (firstCall) { - firstCall = false; - return new int[0]; - } - while (true) { - if (newFrameChanged) { - newFrameChanged = false; - try { - driver.switchTo().frame(newFrame); - } catch (WebDriverException e) { - throw new NoSuchElementException(); - } - int[] newStartFrame = - concat(startFrame, new int[]{newFrame}); - results = - new FrameIterator(driver, newStartFrame).iterator(); - } - if (results.hasNext()) - return concat(new int[]{newFrame}, results.next()); - try { - switchToFrame(startFrame); - } catch (NoSuchFrameException e) { - throw new FramesChangedWhileIterating(); - } - newFrame++; - newFrameChanged = true; - } - } - - }).iterator(); - } - - public void switchToFrame(int[] frameIndexPath) { - driver.switchTo().defaultContent(); - for (int frameIndex : frameIndexPath) - driver.switchTo().frame(frameIndex); - } - - int[] concat(int[] a, int[] b) { - int aLen = a.length; - int bLen = b.length; - int[] result = new int[aLen + bLen]; - System.arraycopy(a, 0, result, 0, aLen); - System.arraycopy(b, 0, result, aLen, bLen); - return result; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/selenium_wrappers/FramesChangedWhileIterating.java b/helium-java/src/main/java/com/heliumhq/selenium_wrappers/FramesChangedWhileIterating.java deleted file mode 100644 index dd4922d..0000000 --- a/helium-java/src/main/java/com/heliumhq/selenium_wrappers/FramesChangedWhileIterating.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.heliumhq.selenium_wrappers; - -public class FramesChangedWhileIterating extends RuntimeException { -} diff --git a/helium-java/src/main/java/com/heliumhq/selenium_wrappers/WebDriverWrapper.java b/helium-java/src/main/java/com/heliumhq/selenium_wrappers/WebDriverWrapper.java deleted file mode 100644 index f800d30..0000000 --- a/helium-java/src/main/java/com/heliumhq/selenium_wrappers/WebDriverWrapper.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.heliumhq.selenium_wrappers; - -import com.heliumhq.util.geom.Rectangle; -import org.openqa.selenium.*; -import org.openqa.selenium.interactions.Actions; -import org.openqa.selenium.remote.RemoteWebDriver; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -public class WebDriverWrapper extends Wrapper { - - private WebElementWrapper lastManipulatedElement; - - public WebDriverWrapper(WebDriver target) { - super(target); - } - - public double getDistanceToLastManipulated(WebElementWrapper element) { - if (lastManipulatedElement == null) - return 0; - Rectangle lastManipulatedLocation; - try { - lastManipulatedLocation = lastManipulatedElement.getLocation(); - } catch (StaleElementReferenceException e) { - return 0; - } - return element.getLocation().getDistanceTo(lastManipulatedLocation); - } - - public void setLastManipulatedElement(WebElementWrapper value) { - lastManipulatedElement = value; - } - - public Actions action() { - return new Actions(target); - } - - public List findElements(By by) { - List result = target.findElements(by); - // The Python implementation sometimes returns None instead of [] for - // find_elements_by_xpath(...). Just in case this also occurs in - // Selenium's Java bindings, we add the null-check here too: - if (result == null) - result = new ArrayList(); - return result; - } - - public void get(String url) { - target.get(url); - } - - public Object executeScript(String script, Object... args) { - return ((JavascriptExecutor) target).executeScript(script, args); - } - - public String getBrowserName() { - return ((RemoteWebDriver) target).getCapabilities().getBrowserName(); - } - - public boolean isFirefox() { - return "firefox".equals(getBrowserName()); - } - - public boolean isIE() { - return "internet explorer".equals(getBrowserName()); - } - - public WebDriver.TargetLocator switchTo() { - return target.switchTo(); - } - - public String getWindowHandle() { - return target.getWindowHandle(); - } - - public Set getWindowHandles() { - return target.getWindowHandles(); - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/selenium_wrappers/WebElementWrapper.java b/helium-java/src/main/java/com/heliumhq/selenium_wrappers/WebElementWrapper.java deleted file mode 100644 index fd5dad6..0000000 --- a/helium-java/src/main/java/com/heliumhq/selenium_wrappers/WebElementWrapper.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.heliumhq.selenium_wrappers; - -import com.heliumhq.util.geom.Rectangle; -import org.openqa.selenium.*; - -public class WebElementWrapper extends Wrapper { - - private WebDriverWrapper driver; - - private Rectangle cachedLocation; - - private int[] frameIndex; - - public WebElementWrapper(WebDriverWrapper driver, WebElement target) { - super(target); - this.driver = driver; - } - - public void setFrameIndex(int[] frameIndex) { - this.frameIndex = frameIndex; - } - - public Rectangle getLocation() { - if (cachedLocation == null) - cacheLocation(); - return cachedLocation; - } - - private void cacheLocation() { - if (frameIndex == null) - cacheLocationWithoutHandlingErrors(); - else { - try { - cacheLocationWithoutHandlingErrors(); - } catch (StaleElementReferenceException originalExc) { - try { - new FrameIterator(driver).switchToFrame(frameIndex); - cacheLocationWithoutHandlingErrors(); - } catch (NoSuchFrameException e2) { - throw originalExc; - } - } - } - } - - // In the Python implementation of Selenium, when the browser is closed and - // a WebElement's .location is accessed, an ugly socket.error is raised: - // "No connection could be made because the target machine actively refused - // it". The Python implementation of Helium catches this exception and - // raises a more meaningful StaleElementReferenceException in this case (see - // _translate_url_errors_caused_by_server_shutdown). - // The Java implementation of Selenium does not have the problem described - // above (it throws a descriptive error in the aforementioned situation). - // Hence we don't need to do anything special here. - private void cacheLocationWithoutHandlingErrors() { - Point location = target.getLocation(); - Dimension size = target.getSize(); - cachedLocation = new Rectangle( - location.getX(), location.getY(), - size.getWidth(), size.getHeight() - ); - } - - public boolean isDisplayed() { - try { - return target.isDisplayed() && getLocation().intersects( - new Rectangle(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE) - ); - } catch (StaleElementReferenceException e) { - return false; - } - } - - public String getAttribute(String name) { - if (frameIndex == null) - return target.getAttribute(name); - try { - return target.getAttribute(name); - } catch (StaleElementReferenceException originalExc) { - try { - new FrameIterator(driver).switchToFrame(frameIndex); - return target.getAttribute(name); - } catch (NoSuchFrameException e) { - throw originalExc; - } - } - } - - public String getText() { - if (frameIndex == null) - return target.getText(); - try { - return target.getText(); - } catch (StaleElementReferenceException originalExc) { - try { - new FrameIterator(driver).switchToFrame(frameIndex); - return target.getText(); - } catch (NoSuchFrameException e) { - throw originalExc; - } - } - } - - public String getTagName() { - if (frameIndex == null) - return target.getTagName(); - try { - return target.getTagName(); - } catch (StaleElementReferenceException originalExc) { - try { - new FrameIterator(driver).switchToFrame(frameIndex); - return target.getTagName(); - } catch (NoSuchFrameException e) { - throw originalExc; - } - } - } - - public String toString() { - return String.format( - "<%s>%s", getTagName(), getText(), getTagName() - ); - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/selenium_wrappers/Wrapper.java b/helium-java/src/main/java/com/heliumhq/selenium_wrappers/Wrapper.java deleted file mode 100644 index 6f43016..0000000 --- a/helium-java/src/main/java/com/heliumhq/selenium_wrappers/Wrapper.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.heliumhq.selenium_wrappers; - -public class Wrapper { - - protected final T target; - - protected Wrapper(T target) { - this.target = target; - } - - public T unwrap() { - return target; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/util/Collections.java b/helium-java/src/main/java/com/heliumhq/util/Collections.java deleted file mode 100644 index 41a2a4e..0000000 --- a/helium-java/src/main/java/com/heliumhq/util/Collections.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.heliumhq.util; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -public class Collections { - public static Map> inverse(Map> map) { - Map> result = new HashMap>(); - for (Map.Entry> entry : map.entrySet()) - for (V value : entry.getValue()) { - if (! result.containsKey(value)) - result.put(value, new HashSet()); - result.get(value).add(entry.getKey()); - } - return result; - } -} diff --git a/helium-java/src/main/java/com/heliumhq/util/Date.java b/helium-java/src/main/java/com/heliumhq/util/Date.java deleted file mode 100644 index 8b2bfaf..0000000 --- a/helium-java/src/main/java/com/heliumhq/util/Date.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.heliumhq.util; - -import java.util.GregorianCalendar; - -public class Date { - - public static GregorianCalendar createDate() { - return new GregorianCalendar(); - } - - public static GregorianCalendar createDate(int year, int month, int day) { - return new GregorianCalendar(year, month - 1, day); - } - - public static GregorianCalendar createDate(long date) { - GregorianCalendar result = new GregorianCalendar(); - result.setTimeInMillis(date); - return result; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/util/FileUtil.java b/helium-java/src/main/java/com/heliumhq/util/FileUtil.java deleted file mode 100644 index 9e0a949..0000000 --- a/helium-java/src/main/java/com/heliumhq/util/FileUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.heliumhq.util; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.channels.FileChannel; - -public class FileUtil { - - public static void copyFile(File sourceFile, File destFile) throws - IOException { - // make sure the destination directory exists - File outDirectory = getDirectory(destFile); - if (!outDirectory.exists()) { - outDirectory.mkdirs(); - } - - if (!destFile.exists()) { - destFile.createNewFile(); - } - FileChannel source = null; - FileChannel destination = null; - try { - source = new FileInputStream(sourceFile).getChannel(); - destination = new FileOutputStream(destFile).getChannel(); - destination.transferFrom(source, 0, source.size()); - } finally { - if (source != null) { - source.close(); - } - if (destination != null) { - destination.close(); - } - } - } - - public static File getDirectory(File file) { - int sep = file.getAbsolutePath().lastIndexOf(File.separator); - File outDirectory = new File(file.getAbsolutePath().substring(0, sep)); - return outDirectory; - } -} diff --git a/helium-java/src/main/java/com/heliumhq/util/Generator.java b/helium-java/src/main/java/com/heliumhq/util/Generator.java deleted file mode 100644 index 92f0b09..0000000 --- a/helium-java/src/main/java/com/heliumhq/util/Generator.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.heliumhq.util; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -public abstract class Generator implements Iterable { - - private boolean needToGenerate = true; - private T next; - private boolean exhausted = false; - - protected abstract T generateNext(); - - @Override - public Iterator iterator() { - return new Iterator() { - @Override - public boolean hasNext() { - if (exhausted) - return false; - if (needToGenerate) { - try { - next = generateNext(); - } catch (NoSuchElementException e) { - exhausted = true; - return false; - } - needToGenerate = false; - } - return true; - } - - @Override - public T next() { - if (!hasNext()) - throw new NoSuchElementException(); - // Calling next() 'consumes' the item: - needToGenerate = true; - return next; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/util/HtmlUtils.java b/helium-java/src/main/java/com/heliumhq/util/HtmlUtils.java deleted file mode 100644 index b8fb7c2..0000000 --- a/helium-java/src/main/java/com/heliumhq/util/HtmlUtils.java +++ /dev/null @@ -1,109 +0,0 @@ -// Copied from https://github.com/lyncode/jtwig/blob/d540f2160467146a7dde0bdf9ac -// 979687f78f194/jtwig-functions/src/main/java/com/lyncode/jtwig/functions/util/ -// HtmlUtils.java -/** - * Copyright 2012 Lyncode - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copyFile of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.heliumhq.util; - -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static java.util.Arrays.asList; -import static java.util.regex.Pattern.*; - -public class HtmlUtils { - - private static final String START_COMMENT = ""; - - public static String stripTags(String input, String allowedTags) { - return removeUnknownTags(removeHtmlComments(input), allowedTags); - } - - public static String stripTags(String input) { - return removeUnknownTags(removeHtmlComments(input), ""); - } - - private static String removeUnknownTags(String input, String knownTags) { - List knownTagList = asList( - knownTags.replaceAll("^<", "").replaceAll(">$", "").split("><") - ); - return removeTags(input, knownTagList); - } - - private static String removeTags(String input, List knownTagList) { - Pattern tag = compile("]*)\\s*[^>]*>", CASE_INSENSITIVE); - Matcher matches = tag.matcher(input); - while (matches.find()) { - if (!knownTagList.contains(matches.group(1))) { - input = input.replaceAll(quote(matches.group()), ""); - } - } - return input; - } - - private static String removeTags( - String input, String startTag, String endTag - ) { - while (input.contains(startTag)) { - int start = input.indexOf(startTag); - int end = - input.substring(start + startTag.length()).indexOf(endTag); - if (end == -1) input = input.substring(0, start); - else - input = - input.substring(0, start) + - input.substring(start + startTag.length() + - end + endTag.length()); - } - return input; - } - - private static String removeHtmlComments(String input) { - return removeTags(input, START_COMMENT, END_COMMENT); - } - - public static String getEasilyReadableSnippet(String html) { - html = normalizeWhitespace(html); - int innerStart = html.indexOf('>') + 1; - int innerEnd = html.substring(innerStart).lastIndexOf('<'); - if (innerStart == -1 || innerEnd == -1) - return html; - // We computed innerEnd inside `html.substring(innerStart)`. To get the - // index inside just `html`, we thus need to add the length of the - // string which we skipped (`innerStart`): - innerEnd += innerStart; - String openingTag = html.substring(0, innerStart); - String closingTag = html.substring(innerEnd); - String inner = html.substring(innerStart, innerEnd); - if (inner.contains("<") || inner.length() > 60) - return String.format("%s...%s", openingTag, closingTag); - else - return html; - } - - public static String normalizeWhitespace(String html) { - String result = html.trim(); - // Remove multiple spaces: - result = result.replaceAll("\\s+", " "); - // Remove spaces after opening or before closing tags: - result = result.replaceAll("> ", ">").replaceAll(" <", "<"); - return result; - } - -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/util/Number.java b/helium-java/src/main/java/com/heliumhq/util/Number.java deleted file mode 100644 index cd8acdc..0000000 --- a/helium-java/src/main/java/com/heliumhq/util/Number.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.heliumhq.util; - -public class Number { - - public static String int2base(int x, String base) { - if (x == 0) - return String.valueOf(base.charAt(0)); - StringBuilder digits = new StringBuilder(); - while (x != 0) { - digits.append(base.charAt((int) (x % base.length()))); - x /= base.length(); - } - return digits.reverse().toString(); - } - - public static int base2int(String x, String base) { - int result = 0; - int exponent = 0; - for (int i = x.length() - 1; i >= 0; i--) { - char digit = x.charAt(i); - int digitVal = base.indexOf(digit); - result += digitVal * Math.pow(base.length(), exponent); - exponent++; - } - return result; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/util/StringUtils.java b/helium-java/src/main/java/com/heliumhq/util/StringUtils.java deleted file mode 100644 index dcd9c78..0000000 --- a/helium-java/src/main/java/com/heliumhq/util/StringUtils.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.heliumhq.util; - -import java.util.Arrays; - -public class StringUtils { - public static String join(String delimiter, Object[] elements) { - return join(delimiter, Arrays.asList(elements)); - } - public static String join(String delimiter, Iterable elements) { - StringBuilder result = new StringBuilder(); - boolean isFirst = true; - for (Object element : elements) { - if (!isFirst) - result.append(delimiter); - result.append(element.toString()); - isFirst = false; - } - return result.toString(); - } - public static boolean isEmpty(String s) { - return s == null || s.equals(""); - } - public static String escape(String s) { - if (s == null) - return ""; - return "\"" + s + "\""; - } -} diff --git a/helium-java/src/main/java/com/heliumhq/util/System.java b/helium-java/src/main/java/com/heliumhq/util/System.java deleted file mode 100644 index 7c82a1c..0000000 --- a/helium-java/src/main/java/com/heliumhq/util/System.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.heliumhq.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class System { - - // isWindows, isLinux, isOSX inspired by org.apache.commons.lang.SystemUtils - public static boolean isWindows() { - return osNameMatches("Windows"); - } - public static boolean isLinux() { - - return osNameMatches("Linux") || osNameMatches("LINUX"); - } - public static boolean isOSX() { - return osNameMatches("Mac OS X") || osNameMatches("Darwin"); - } - private static boolean osNameMatches(String expected) { - String actual = java.lang.System.getProperty("os.name"); - return actual != null && actual.startsWith(expected); - } - - /** - * Determines whether the current OS is 32- or 64 bit. Note that this may be - * different from the bitness of the Java runtime or the CPU. Eg. is32bit() - * returns true on a 32 bit Windows running on a 64 bit processor. - */ - public static boolean is32bit() { - if (isWindows()) - return java.lang.System.getenv("PROGRAMFILES(X86)") == null; - assert isLinux() || isOSX(); - String unameM = unameM(); - return "i386".equals(unameM) || "i686".equals(unameM); - } - - private static String unameM() { - try { - Process uname = Runtime.getRuntime().exec("uname -m"); - uname.waitFor(); - BufferedReader reader = new BufferedReader( - new InputStreamReader(uname.getInputStream()) - ); - return reader.readLine().trim(); - } catch (IOException e) { - return null; - } catch (InterruptedException e) { - return null; - } - } - - public static boolean is64bit() { - if (isWindows()) - return java.lang.System.getenv("PROGRAMFILES(X86)") != null; - assert isLinux() || isOSX(); - String unameM = unameM(); - return "x86_64".equals(unameM) || "ia64".equals(unameM) || - "amd64".equals(unameM); - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/util/Tuple.java b/helium-java/src/main/java/com/heliumhq/util/Tuple.java deleted file mode 100644 index 227a61f..0000000 --- a/helium-java/src/main/java/com/heliumhq/util/Tuple.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.heliumhq.util; - -public class Tuple { - - private final F first; - private final S second; - - public Tuple(F first, S second) { - this.first = first; - this.second = second; - } - - public F getFirst() { - return first; - } - - public S getSecond() { - return second; - } - -} diff --git a/helium-java/src/main/java/com/heliumhq/util/XPath.java b/helium-java/src/main/java/com/heliumhq/util/XPath.java deleted file mode 100644 index cf3a521..0000000 --- a/helium-java/src/main/java/com/heliumhq/util/XPath.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.heliumhq.util; - -import static com.heliumhq.util.StringUtils.isEmpty; -import static java.lang.String.format; - -public class XPath { - public static String lower(String text) { - String alphabet = - "ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝ"; - return format( - "translate(%s, '%s', '%s')", text, alphabet, alphabet.toLowerCase() - ); - } - public static String replaceNbsp(String text) { - return replaceNbsp(text, " "); - } - public static String replaceNbsp(String text, String by) { - return format("translate(%s, '\u00a0', '%s')", text, by); - } - public static String predicate(String condition) { - if (isEmpty(condition)) - return ""; - else - return format("[%s]", condition); - } - public static String predicateOr(String... conditions) { - String resultCondition = ""; - for (String condition : conditions) { - if (!isEmpty(condition)) { - if (!isEmpty(resultCondition)) - resultCondition += " or "; - resultCondition += condition; - } - } - return predicate(resultCondition); - } -} \ No newline at end of file diff --git a/helium-java/src/main/java/com/heliumhq/util/geom/Rectangle.java b/helium-java/src/main/java/com/heliumhq/util/geom/Rectangle.java deleted file mode 100644 index 23b6b9f..0000000 --- a/helium-java/src/main/java/com/heliumhq/util/geom/Rectangle.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.heliumhq.util.geom; - -public class Rectangle { - - private int left, top, width, height; - - public Rectangle(int left, int top, int width, int height) { - this.left = left; - this.top = top; - this.width = width; - this.height = height; - } - - public int getLeft() { - return left; - } - - public int getRight() { - return left + width; - } - - public int getTop() { - return top; - } - - public int getBottom() { - return top + height; - } - - public int getWidth() { - return width; - } - - public int getHeight() { - return height; - } - - public double getDistanceTo(Rectangle other) { - Rectangle leftmost = left < other.left ? this : other; - Rectangle rightmost = leftmost == other ? this : other; - int distanceX = Math.max(0, rightmost.left - leftmost.getRight()); - Rectangle topmost = top < other.top ? this : other; - Rectangle bottommost = topmost == other ? this : other; - int distanceY = Math.max(0, bottommost.top - topmost.getBottom()); - return Math.sqrt(distanceX * distanceX + distanceY * distanceY); - } - - public boolean intersects(Rectangle other) { - int left = Math.max(this.left, other.left); - int top = Math.max(this.top, other.top); - int right = Math.min(getRight(), other.getRight()); - int bottom = Math.min(getBottom(), other.getBottom()); - return left < right && top < bottom; - } - - public boolean isAbove(Rectangle other) { - boolean startsAboveOther = top < other.top; - boolean overlapsOtherLeft = - left <= other.left && other.left < getRight(); - boolean otherOverlapsLeft = - other.left <= left && left < other.getRight(); - return startsAboveOther && (overlapsOtherLeft || otherOverlapsLeft); - } - - public boolean isBelow(Rectangle other) { - return other.isAbove(this); - } - - public boolean isToRightOf(Rectangle other) { - return other.isToLeftOf(this); - } - - public boolean isToLeftOf(Rectangle other) { - boolean thisStartsToLeftOfOther = left < other.left; - boolean thisOverlapsOtherTop = - top <= other.top && other.top < getBottom(); - boolean otherOverlapsThisTop = - other.top <= top && top < other.getBottom(); - return thisStartsToLeftOfOther && ( - thisOverlapsOtherTop || otherOverlapsThisTop - ); - } - - public boolean equals(Object other) { - if (other == null) - return false; - if (! (other instanceof Rectangle)) - return false; - Rectangle otherRect = (Rectangle) other; - return left == otherRect.left && top == otherRect.top && - width == otherRect.width && height == otherRect.height; - } - - @Override - public int hashCode() { - return left + 7 * top + 11 * width + 13 * height; - } -} diff --git a/helium-java/src/site/java/com/heliumhq/site/AdvancedEnumerationHelper.java b/helium-java/src/site/java/com/heliumhq/site/AdvancedEnumerationHelper.java deleted file mode 100644 index 80b9384..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/AdvancedEnumerationHelper.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.heliumhq.site; - -import java.util.Iterator; - -public class AdvancedEnumerationHelper implements Iterable { - - private final Iterator source; - private final String lastDelimiter; - private final String delimiter; - private int numTimesNextCalled; - private boolean isLast; - - public AdvancedEnumerationHelper( - Iterable source, String delimiter, String lastDelimiter - ) { - this.source = source.iterator(); - this.delimiter = delimiter; - this.lastDelimiter = lastDelimiter; - numTimesNextCalled = 0; - isLast = false; - } - - public String getDelimiter() { - if (numTimesNextCalled < 2) - return ""; - if (isLast) - return lastDelimiter; - return delimiter; - } - - @Override - public Iterator iterator() { - return new Iterator() { - @Override - public boolean hasNext() { - return source.hasNext(); - } - - @Override - public T next() { - T result = source.next(); - isLast = ! hasNext(); - numTimesNextCalled++; - return result; - } - - @Override - public void remove() { - source.remove(); - } - }; - } - -} diff --git a/helium-java/src/site/java/com/heliumhq/site/DocUtils.java b/helium-java/src/site/java/com/heliumhq/site/DocUtils.java deleted file mode 100644 index 05c3e4b..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/DocUtils.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.heliumhq.site; - -import com.sun.javadoc.MethodDoc; -import com.sun.javadoc.Parameter; - -import java.util.ArrayList; -import java.util.List; - -import static com.heliumhq.util.StringUtils.join; - -public class DocUtils { - public static String getShortSignature(MethodDoc impl) { - String result = impl.name() + "("; - List paramNames = new ArrayList(); - for (Parameter parameter : impl.parameters()) - paramNames.add(parameter.name()); - result += join(", ", paramNames); - if (impl.isVarArgs()) - result += "..."; - result += ")"; - return result; - } - public static String getSimpleName(String qualifiedClassName) { - String[] nameComponents = qualifiedClassName.split("\\."); - return nameComponents[nameComponents.length - 1]; - } -} diff --git a/helium-java/src/site/java/com/heliumhq/site/EnumerationHelper.java b/helium-java/src/site/java/com/heliumhq/site/EnumerationHelper.java deleted file mode 100644 index d792b4c..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/EnumerationHelper.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.heliumhq.site; - -public class EnumerationHelper { - private final String delimiter; - private boolean isFirst = true; - public EnumerationHelper() { - this(", "); - } - public EnumerationHelper(String delimiter) { - this.delimiter = delimiter; - } - public String next() { - if (isFirst) { - isFirst = false; - return ""; - } - return delimiter; - } -} \ No newline at end of file diff --git a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIClassDoc.java b/helium-java/src/site/java/com/heliumhq/site/HeliumAPIClassDoc.java deleted file mode 100644 index 7ac8eb5..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIClassDoc.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.heliumhq.site; - -import com.sun.javadoc.ClassDoc; -import com.sun.javadoc.MethodDoc; - -public class HeliumAPIClassDoc implements HeliumAPIDocElement { - private final ClassDoc classDoc; - - public HeliumAPIClassDoc(ClassDoc classDoc) { - this.classDoc = classDoc; - } - - public void writeTo(HeliumAPIDocWriter writer) { - writer.writeClassHeaderPrefix(classDoc); - writer.writeMemberPostfix(); - writer.write(classDoc.inlineTags()); - for (MethodDoc methodDoc : classDoc.methods()) - new HeliumAPIMethodDoc(methodDoc).writeTo(writer); - writer.writePostamble(); - } -} diff --git a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDoc.java b/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDoc.java deleted file mode 100644 index abf2d56..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDoc.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.heliumhq.site; - -import com.sun.javadoc.ClassDoc; -import com.sun.javadoc.MethodDoc; -import com.sun.javadoc.RootDoc; - -import java.util.LinkedHashMap; -import java.util.Map; - -import static com.heliumhq.util.StringUtils.isEmpty; - -public class HeliumAPIDoc implements HeliumAPIDocElement { - - private final RootDoc rootDoc; - private final ClassDoc apiclassDoc; - private final Map methods; - - public HeliumAPIDoc(RootDoc rootDoc, String apiclass) { - this.rootDoc = rootDoc; - apiclassDoc = rootDoc.classNamed(apiclass); - methods = new LinkedHashMap(); - fillMethods(); - } - - private void fillMethods() { - for (MethodDoc method : apiclassDoc.methods()) { - String name = method.name(); - ClassDoc classDoc = getClassNamed(name); - if (! methods.containsKey(name)) - methods.put(name, new HeliumAPIMethodDoc(name, classDoc)); - methods.get(name).addImpl(method); - } - } - - public void writeTo(HeliumAPIDocWriter writer) { - writer.writePreamblePrefix(); - writer.write(apiclassDoc.inlineTags()); - writer.writePreamblePostfix(); - for (HeliumAPIMethodDoc methodDoc : methods.values()) - methodDoc.writeTo(writer); - for (ClassDoc innerClass : apiclassDoc.innerClasses()) - if (! isEmpty(innerClass.commentText())) - new HeliumAPIClassDoc(innerClass).writeTo(writer); - } - - private ClassDoc getClassNamed(String simpleName) { - for (ClassDoc classDoc : rootDoc.classes()) - if (classDoc.simpleTypeName().equals(simpleName)) - return classDoc; - return null; - } - -} diff --git a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDocElement.java b/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDocElement.java deleted file mode 100644 index 65023dd..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDocElement.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.heliumhq.site; - -public interface HeliumAPIDocElement { - public void writeTo(HeliumAPIDocWriter writer); -} diff --git a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDocHTMLWriter.java b/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDocHTMLWriter.java deleted file mode 100644 index 156d2d7..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDocHTMLWriter.java +++ /dev/null @@ -1,363 +0,0 @@ -package com.heliumhq.site; - -import com.sun.javadoc.*; - -import java.io.PrintStream; -import java.util.*; - -import static com.heliumhq.site.DocUtils.getSimpleName; -import static com.heliumhq.util.StringUtils.join; -import static com.heliumhq.site.StringUtils.stripFirstWhitespaceOfEachLine; -import static com.heliumhq.util.StringUtils.isEmpty; - -public class HeliumAPIDocHTMLWriter implements HeliumAPIDocWriter { - - private final static String PRETTY_PRINT_CLASS = "prettyprint lang-java"; - - private final PrintStream out; - - public HeliumAPIDocHTMLWriter(PrintStream out) { - this.out = out; - } - - private HeliumAPIDocHTMLWriter write(String text) { - out.print(text); - return this; - } - - @Override - public HeliumAPIDocHTMLWriter writePreamblePrefix() { - write("

"); - return this; - } - - @Override - public HeliumAPIDocHTMLWriter writePreamblePostfix() { - return write("

"); - } - - @Override - public HeliumAPIDocHTMLWriter writeFunctionHeaderPrefix( - MethodDoc methodDoc - ) { - return writeMemberPrefix(methodDoc, "function"); - } - - private HeliumAPIDocHTMLWriter writeMemberPrefix( - MemberDoc memberDoc, String dlClassName - ) { - String memberId = - memberDoc.containingClass().qualifiedName() + - "." + memberDoc.name(); - write("
\n"); - write("
\n"); - write(""); - return this; - } - - @Override - public HeliumAPIDocWriter writePredicateHeaderPrefix(MethodDoc methodDoc) { - return writeMemberPrefix(methodDoc, "class"); - } - - @Override - public HeliumAPIDocWriter writeMethodHeaderPrefix(MethodDoc methodDoc) { - return writeMemberPrefix(methodDoc, "method"); - } - - @Override - public HeliumAPIDocWriter writeFieldHeaderPrefix(FieldDoc fieldDoc) { - return writeMemberPrefix(fieldDoc, "attribute").write(fieldDoc.name()); - } - - @Override - public HeliumAPIDocWriter writeClassHeaderPrefix(ClassDoc classDoc) { - write("
\n"); - write("
\n"); - write("class "); - write(""); - write(classDoc.simpleTypeName()); - return this; - } - - @Override - public HeliumAPIDocHTMLWriter writeFunctionSignature( - String name, List paramCombinations - ) { - write(name); - write("("); - EnumerationHelper paramCombEnum = - new EnumerationHelper(" or "); - for (ParamCombination paramCombination : paramCombinations) { - write(paramCombEnum.next()); - EnumerationHelper paramEnum = new EnumerationHelper(); - EnumerationHelper optionalEnum = new EnumerationHelper(" "); - int optionalsDepth = 0; - for (List paramAlternatives : paramCombination) { - EnumerationHelper paramAltsEnum = new EnumerationHelper(" or "); - Param firstAlternative = paramAlternatives.get(0); - if (firstAlternative.isVarargs()) - for (; optionalsDepth > 0; optionalsDepth--) - write("]"); - if (firstAlternative.isOptional()) { - write(optionalEnum.next()); - write("["); - optionalsDepth++; - } else - optionalEnum.next(); - write(paramEnum.next()); - for (Param paramAlternative : paramAlternatives) { - write(paramAltsEnum.next()); - write(paramAlternative.getName()); - if (paramAlternative.isVarargs()) - write("..."); - } - } - for (; optionalsDepth > 0; optionalsDepth--) - write("]"); - } - write(")"); - return this; - } - - @Override - public HeliumAPIDocHTMLWriter writeMemberPostfix() { - return write("
\n
"); - } - - @Override - public HeliumAPIDocHTMLWriter writeFunctionDescriptionPrefix() { - return write("

"); - } - - @Override - public HeliumAPIDocHTMLWriter writeFunctionDescriptionPostfix() { - return write("

"); - } - - @Override - public HeliumAPIDocHTMLWriter write(Tag[] inlineTags) { - for (Tag inlineTag : inlineTags) { - if (inlineTag.name().equals("@link")) - writeLink((SeeTag) inlineTag); - else { - String text = stripFirstWhitespaceOfEachLine(inlineTag.text()); - if (inlineTag.name().equals("@code")) - writeCode(text); - else - write(text - .replace("

", "

\n

") - .replace( - "", - "" - ) - ); - } - } - return this; - } - - private HeliumAPIDocHTMLWriter writeCode(String code) { - write("

\n"); - write("
");
-		write(code);
-		write("
\n"); - write("

"); - return this; - } - - private HeliumAPIDocHTMLWriter writeLink(SeeTag linkTag) { - return write(" ").writeLink( - linkTag.referencedClassName(), linkTag.referencedMemberName() - ); - } - - private HeliumAPIDocHTMLWriter writeLink(String className) { - return writeLink(className, ""); - } - - private HeliumAPIDocHTMLWriter writeLink(String typeName, String member) { - return write(getAPIDocLink(typeName, member)); - } - - private String getAPIDocLink(String typeName, String member) { - String nameToDisplay = getNameToDisplay(typeName, member); - if (typeName.startsWith("org.openqa.selenium")) { - String url = getExternalLinkURL( - typeName, member, - "http://selenium.googlecode.com/svn/trunk/docs/api/java/" - ); - return "" + nameToDisplay + ""; - } else if ( - typeName.startsWith("com.heliumhq") && - ! typeName.startsWith("com.heliumhq.api_impl") - ) { - String reference = getInternalLinkReference(typeName, member); - return "" + nameToDisplay + - ""; - } - return nameToDisplay; - } - - private String getExternalLinkURL( - String typeName, String member, String linkBase - ) { - String result = - linkBase + stripGenerics(typeName).replace('.', '/') + ".html"; - if (! isEmpty(member)) - result += "#" + member; - return result; - } - - private String getInternalLinkReference(String typeName, String member) { - if (isEmpty(member)) { - // We want to convert a link to com.heliumhq.Point to - // com.heliumhq.API.Point, but not com.heliumhq.Point.withOffset - // to com.heliumhq.API.Point.withOffset. That's why we only - // perform a change if 'member' is empty (see if-stmt above). - List pathParts = new ArrayList( - Arrays.asList(typeName.split("\\.")) - ); - if (! pathParts.contains("API")) - pathParts.add(pathParts.size() - 1, "API"); - typeName = join(".", pathParts); - } - String result = typeName; - if (! isEmpty(member)) - result += "." + stripParentheses(member); - return result; - } - - private String getNameToDisplay(String className, String referencedMember) { - String classNameWithGenerics; - if (className.startsWith("java.lang.")) - classNameWithGenerics = className.substring("java.lang.".length()); - else if (className.equals("com.heliumhq.API")) - classNameWithGenerics = ""; - else - classNameWithGenerics = className; - String result = getSimpleName(stripGenerics(classNameWithGenerics)); - if (! isEmpty(referencedMember)) { - if (! isEmpty(classNameWithGenerics)) - result += "#"; - result += stripParentheses(referencedMember) + "(...)"; - } - return result; - } - - private String stripGenerics(String typeName) { - if (typeName.contains("<")) - return typeName.substring(0, typeName.indexOf('<')).trim(); - return typeName; - } - - private String stripParentheses(String memberName) { - if (memberName.contains("(")) - return memberName.substring(0, memberName.indexOf('(')).trim(); - return memberName; - } - - - @Override - public HeliumAPIDocHTMLWriter writeParamDescriptionsPrefix() { - return writeParamDescriptionsPrefix("Parameters:"); - } - - public HeliumAPIDocHTMLWriter writeParamDescriptionsPrefix(String title) { - write( - "\n" - ); - write("\n"); - write("\n"); - write("\n"); - write( - "\n\n\n
" + title + - "
    " - ); - return this; - } - - @Override - public HeliumAPIDocHTMLWriter writeParamDescription( - ParamTag paramTag, boolean isOptional, Set paramTypes - ) { - write("
  • "); - write(paramTag.parameterName()); - write(""); - if (isOptional) - write(" (optional)"); - write(" - "); - AdvancedEnumerationHelper enumHelper = - new AdvancedEnumerationHelper(paramTypes, ", ", " or "); - for (String paramType : enumHelper) { - write(enumHelper.getDelimiter()); - writeLink(paramType); - } - write(""); - if (paramTag != null) { - write(": "); - write(paramTag.inlineTags()); - } else - write("."); - write("
  • "); - return this; - } - - @Override - public HeliumAPIDocHTMLWriter writeParamDescriptionsPostfix() { - write("\n
\n
\n"); - return this; - } - - @Override - public HeliumAPIDocHTMLWriter writeReturnTag(Tag returnTag) { - if (returnTag != null) { - write("Returns: "); - write(returnTag.inlineTags()); - } - return this; - } - - @Override - public HeliumAPIDocHTMLWriter writeThrowsTagsPrefix() { - return writeParamDescriptionsPrefix("Throws:"); - } - - @Override - public HeliumAPIDocHTMLWriter writeThrowsTag(ThrowsTag throwsTag) { - write("

  • "); - writeLink(throwsTag.exceptionName()); - write(""); - write(" - "); - write(throwsTag.inlineTags()); - write("
  • "); - return this; - } - - - @Override - public HeliumAPIDocHTMLWriter writeThrowsTagsPostfix() { - return writeParamDescriptionsPostfix(); - } - - @Override - public HeliumAPIDocWriter writeMembersPrefix(ClassDoc classDoc) { - write("Returns: "); - write("an object of class "); - write(""); - write(classDoc.qualifiedName()); - write(""); - write(", with the following properties:

    "); - writeParamDescriptionsPostfix(); - return this; - } - - @Override - public HeliumAPIDocWriter writePostamble() { - write("
    \n\n"); - return this; - } - -} \ No newline at end of file diff --git a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDocWriter.java b/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDocWriter.java deleted file mode 100644 index 85bbd65..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDocWriter.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.heliumhq.site; - -import com.sun.javadoc.*; - -import java.util.List; -import java.util.Set; - -public interface HeliumAPIDocWriter { - public HeliumAPIDocWriter writePreamblePrefix(); - public HeliumAPIDocWriter writePreamblePostfix(); - public HeliumAPIDocWriter writeFunctionHeaderPrefix(MethodDoc methodDoc); - public HeliumAPIDocWriter writePredicateHeaderPrefix(MethodDoc methodDoc); - public HeliumAPIDocWriter writeMethodHeaderPrefix(MethodDoc methodDoc); - public HeliumAPIDocWriter writeFieldHeaderPrefix(FieldDoc fieldDoc); - public HeliumAPIDocWriter writeClassHeaderPrefix(ClassDoc classDoc); - public HeliumAPIDocWriter writeFunctionSignature( - String name, List paramCombinations - ); - public HeliumAPIDocWriter writeMemberPostfix(); - public HeliumAPIDocWriter writeFunctionDescriptionPrefix(); - public HeliumAPIDocWriter writeFunctionDescriptionPostfix(); - public HeliumAPIDocWriter write(Tag[] inlineTags); - public HeliumAPIDocWriter writeParamDescriptionsPrefix(); - public HeliumAPIDocWriter writeParamDescription( - ParamTag paramTag, boolean isOptional, Set paramTypes - ); - public HeliumAPIDocWriter writeParamDescriptionsPostfix(); - public HeliumAPIDocWriter writeReturnTag(Tag returnTag); - public HeliumAPIDocWriter writeThrowsTagsPrefix(); - public HeliumAPIDocWriter writeThrowsTag(ThrowsTag throwsTag); - public HeliumAPIDocWriter writeThrowsTagsPostfix(); - public HeliumAPIDocWriter writeMembersPrefix(ClassDoc classDoc); - public HeliumAPIDocWriter writePostamble(); -} diff --git a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDoclet.java b/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDoclet.java deleted file mode 100644 index c03154d..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIDoclet.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.heliumhq.site; - -import com.sun.javadoc.*; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.PrintStream; - -public class HeliumAPIDoclet { - - /** - * We need to implement this method to tell the Doclet API about our custom - * options. - */ - public static int optionLength(String option) { - if ("-apiclass".equals(option) || "-d".equals(option) || - "-f".equals(option)) - return 2; - return 0; - } - - /** - * Another method of the Doclet API which we can implement to verify that - * any required options are set properly. - */ - public static boolean validOptions( - String[][] options, DocErrorReporter errorReporter - ) { - return requireOption("d", options, errorReporter) && - requireOption("apiclass", options, errorReporter); - } - - private static boolean requireOption( - String option, String[][] options, DocErrorReporter errorReporter - ) { - String[] optionValue = readOption(options, option); - if (optionValue == null) { - errorReporter.printError("Option '-" + option + "' is required."); - return false; - } - if (optionValue.length != 2) { - errorReporter.printError( - "Option '-" + option + "' requires exactly one argument." - ); - return false; - } - return true; - } - - public static boolean start(RootDoc rootDoc) throws FileNotFoundException { - String apiclass = readOption(rootDoc.options(), "apiclass")[1]; - HeliumAPIDoc apiDoc = new HeliumAPIDoc(rootDoc, apiclass); - String outputDir = readOption(rootDoc.options(), "d")[1]; - String fileName = "index.html"; - try { - fileName = readOption(rootDoc.options(), "f")[1]; - } catch (ArrayIndexOutOfBoundsException e) { - } catch (NullPointerException e) {} - PrintStream out = new PrintStream(new File(outputDir, fileName)); - apiDoc.writeTo(new HeliumAPIDocHTMLWriter(out)); - return true; - } - - private static String[] readOption(String[][] options, String option) { - for (String[] candidateOption : options) - if (("-" + option).equals(candidateOption[0])) - return candidateOption; - return null; - } - - /** - * This is required to make 'MethodDoc#isVarArgs()' work. - */ - public static LanguageVersion languageVersion() { - return LanguageVersion.JAVA_1_5; - } - -} diff --git a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIFieldDoc.java b/helium-java/src/site/java/com/heliumhq/site/HeliumAPIFieldDoc.java deleted file mode 100644 index 57edbb1..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIFieldDoc.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.heliumhq.site; - -import com.sun.javadoc.FieldDoc; - -public class HeliumAPIFieldDoc implements HeliumAPIDocElement { - private final FieldDoc fieldDoc; - public HeliumAPIFieldDoc(FieldDoc fieldDoc) { - this.fieldDoc = fieldDoc; - } - public void writeTo(HeliumAPIDocWriter writer) { - writer.writeFieldHeaderPrefix(fieldDoc); - writer.writeMemberPostfix(); - writer.write(fieldDoc.inlineTags()); - writer.writePostamble(); - } -} diff --git a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIMethodDoc.java b/helium-java/src/site/java/com/heliumhq/site/HeliumAPIMethodDoc.java deleted file mode 100644 index 69289f5..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/HeliumAPIMethodDoc.java +++ /dev/null @@ -1,251 +0,0 @@ -package com.heliumhq.site; - -import com.heliumhq.util.Tuple; -import com.sun.javadoc.*; - -import java.util.*; - -import static com.heliumhq.util.StringUtils.isEmpty; - -public class HeliumAPIMethodDoc implements HeliumAPIDocElement { - private final String name; - private final List impls; - private final ClassDoc classDoc; - private final boolean isFunction, isPredicate, isMethod; - public HeliumAPIMethodDoc(String name, ClassDoc classDoc) { - this(name, classDoc, classDoc == null, classDoc != null, false); - } - public HeliumAPIMethodDoc(MethodDoc methodDoc) { - this(methodDoc.name(), null, false, false, true); - addImpl(methodDoc); - } - private HeliumAPIMethodDoc( - String name, ClassDoc classDoc, boolean isFunction, boolean isPredicate, - boolean isMethod - ) { - this.name = name; - this.classDoc = classDoc; - this.impls = new ArrayList(); - this.isFunction = isFunction; - this.isPredicate = isPredicate; - this.isMethod = isMethod; - } - public void addImpl(MethodDoc methodDoc) { - assert methodDoc.name().equals(name); - impls.add(methodDoc); - } - public void writeTo(HeliumAPIDocWriter writer) { - writeHeaderTo(writer); - writer.writeMemberPostfix(); - writeDescriptionTo(writer); - writeParamDescriptionsTo(writer); - writer.writeReturnTag(getReturnTag()); - writeThrowsDescriptionsTo(writer); - writeMembersTo(writer); - writer.writePostamble(); - } - - private void writeHeaderTo(HeliumAPIDocWriter writer) { - MethodDoc firstImpl = impls.iterator().next(); - if (isFunction) - writer.writeFunctionHeaderPrefix(firstImpl); - else if (isPredicate) - writer.writePredicateHeaderPrefix(firstImpl); - else { - assert isMethod; - writer.writeMethodHeaderPrefix(firstImpl); - } - writer.writeFunctionSignature(name, getParamCombinations()); - } - - private List getParamCombinations() { - List result = new ArrayList(); - List params = getParams(); - for (MethodDoc impl : impls) { - ParamCombination current = new ParamCombination(); - for (Parameter parameter : impl.parameters()) { - Param param = null; - for (Param maybeParameter : params) - if (maybeParameter.getName().equals(parameter.name())) { - param = maybeParameter; - break; - } - current.add(param); - } - Iterator resultIter = result.iterator(); - boolean shouldBeAdded = true; - while (resultIter.hasNext()) { - ParamCombination existing = resultIter.next(); - if (existing.join(current)) { - shouldBeAdded = false; - break; - } - if (current.join(existing)) - resultIter.remove(); - } - if (shouldBeAdded) - result.add(current); - } - return result; - } - - private void writeDescriptionTo(HeliumAPIDocWriter writer) { - writer.writeFunctionDescriptionPrefix(); - for (MethodDoc impl : impls) - writer.write(impl.inlineTags()); - writer.writeFunctionDescriptionPostfix(); - } - - private void writeParamDescriptionsTo(HeliumAPIDocWriter writer) { - List params = getParams(); - if (! params.isEmpty()) - writer.writeParamDescriptionsPrefix(); - for (Param param : params) { - ParamTag paramTag = getParamTag(param.getName()); - if (paramTag != null) - writer.writeParamDescription( - paramTag, param.isOptional(), param.getTypes() - ); - } - if (! params.isEmpty()) - writer.writeParamDescriptionsPostfix(); - } - - private List getParams() { - Map, Boolean>> pTypes = - new LinkedHashMap, Boolean>>(); - for (MethodDoc impl : impls) { - for (int i = 0; i < impl.parameters().length; i++) { - Parameter param = impl.parameters()[i]; - String paramName = param.name(); - String paramType = param.type().qualifiedTypeName(); - boolean isLastParam = i == impl.parameters().length - 1; - boolean isVarArgs = impl.isVarArgs() && isLastParam; - if (! pTypes.containsKey(paramName)) - pTypes.put(paramName, new Tuple, Boolean>( - new LinkedHashSet(), isVarArgs - )); - pTypes.get(paramName).getFirst().add(paramType); - } - } - List result = new ArrayList(); - for (Map.Entry, Boolean>> e : - pTypes.entrySet()) { - String paramName = e.getKey(); - Set paramTypes = e.getValue().getFirst(); - boolean isOptional = isOptional(paramName); - boolean isVarArgs = e.getValue().getSecond(); - result.add(new Param(paramName, paramTypes, isOptional, isVarArgs)); - } - return result; - } - private boolean isOptional(String parameter) { - MethodDoc implWithParam = getImplWithParameter(parameter); - List otherParameters = new ArrayList(); - for (Parameter param : implWithParam.parameters()) - if (! param.name().equals(parameter)) - otherParameters.add(param.name()); - return getImplWithParameters(otherParameters) != null; - } - private MethodDoc getImplWithParameter(String parameter) { - List implsWithParameter = getImplsWithParameter(parameter); - if (implsWithParameter.isEmpty()) - return null; - return implsWithParameter.get(0); - } - private List getImplsWithParameter(String parameter) { - List result = new ArrayList(); - for (MethodDoc impl : impls) - for (Parameter param : impl.parameters()) - if (param.name().equals(parameter)) - result.add(impl); - return result; - } - private MethodDoc getImplWithParameters(List parameters) { - for (MethodDoc impl : impls) { - if (impl.parameters().length != parameters.size()) - continue; - boolean found = true; - for (int i = 0; i < parameters.size(); i++) - if (! impl.parameters()[i].name().equals(parameters.get(i))) { - found = false; - break; - } - if (found) - return impl; - } - return null; - } - private ParamTag getParamTag(String parameterName) { - for (MethodDoc implWithParam : getImplsWithParameter(parameterName)) - for (ParamTag paramTag : implWithParam.paramTags()) - if (paramTag.parameterName().equals(parameterName)) - return paramTag; - return null; - } - private Tag getReturnTag() { - for (MethodDoc impl : impls) { - Tag[] returnTags = impl.tags("return"); - if (returnTags.length > 0) - return returnTags[0]; - } - return null; - } - private void writeThrowsDescriptionsTo(HeliumAPIDocWriter writer) { - List throwsTags = getThrowsTags(); - if (! throwsTags.isEmpty()) { - writer.writeThrowsTagsPrefix(); - for (ThrowsTag throwsTag : throwsTags) - writer.writeThrowsTag(throwsTag); - writer.writeThrowsTagsPostfix(); - } - } - private List getThrowsTags() { - List result = new ArrayList(); - for (MethodDoc impl : impls) { - Tag[] throwsTags = impl.tags("throws"); - if (throwsTags.length > 0) - for (Tag tag : throwsTags) { - result.add((ThrowsTag) tag); - } - } - return result; - } - private void writeMembersTo(HeliumAPIDocWriter writer) { - if (classDoc != null) - writer.writeMembersPrefix(classDoc); - List members = getMembersSortedByName(); - for (HeliumAPIDocElement member : members) - member.writeTo(writer); - } - private List getMembersSortedByName() { - // We're using a Map to sort by name, but it can happen that there are - // two members with the same name (eg. Text(...).exists and - // Text(...).exists()). We thus append a unique id to the keys used for - // the map: - int uniqueId = 0; - Map result = - new TreeMap(); - ClassDoc superclassDoc = classDoc; - while (superclassDoc != null) { - for (MethodDoc methodDoc : superclassDoc.methods()) { - String commentText = methodDoc.commentText(); - if (isEmpty(commentText)) - continue; - String uniqueName = methodDoc.name() + uniqueId; - uniqueId ++; - result.put(uniqueName, new HeliumAPIMethodDoc(methodDoc)); - } - for (FieldDoc fieldDoc : superclassDoc.fields()) { - String commentText = fieldDoc.commentText(); - if (isEmpty(commentText)) - continue; - String uniqueName = fieldDoc.name() + uniqueId; - uniqueId ++; - result.put(uniqueName, new HeliumAPIFieldDoc(fieldDoc)); - } - superclassDoc = superclassDoc.superclass(); - } - return new ArrayList(result.values()); - } -} \ No newline at end of file diff --git a/helium-java/src/site/java/com/heliumhq/site/Param.java b/helium-java/src/site/java/com/heliumhq/site/Param.java deleted file mode 100644 index 5a8ad75..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/Param.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.heliumhq.site; - -import java.util.Set; - -public class Param { - private final String name; - private final Set types; - private final boolean isOptional; - private final boolean isVarargs; - public Param( - String name, Set types, boolean isOptional, boolean isVarargs - ) { - this.name = name; - this.types = types; - this.isOptional = isOptional; - this.isVarargs = isVarargs; - } - - public String getName() { - return name; - } - - public Set getTypes() { - return types; - } - - public boolean isOptional() { - return isOptional; - } - - public boolean isVarargs() { - return isVarargs; - } -} \ No newline at end of file diff --git a/helium-java/src/site/java/com/heliumhq/site/ParamCombination.java b/helium-java/src/site/java/com/heliumhq/site/ParamCombination.java deleted file mode 100644 index cf36566..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/ParamCombination.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.heliumhq.site; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import static java.lang.Math.min; -import static java.util.Arrays.asList; - -public class ParamCombination implements Iterable> { - private final List> params; - public ParamCombination() { - this.params = new ArrayList>(); - } - - public void add(Param param) { - params.add(new ArrayList(asList(param))); - } - - public boolean join(ParamCombination other) { - int commonSuffixLength = getCommonSuffixLength(other); - int thisRemaining = params.size() - commonSuffixLength; - int otherRemaining = other.params.size() - commonSuffixLength; - if (thisRemaining < otherRemaining) - return false; - for (int i = otherRemaining - 1; i >= 0; i--) { - List thisParams = params.get(i); - List otherParams = other.params.get(i); - if (allAreEqual(thisParams, otherParams)) - return true; - if (! allAreOptional(thisParams) || ! allAreOptional(otherParams)) - return false; - } - for (int i = otherRemaining - 1; i >= 0; i--) { - List thisParams = params.get(i); - List otherParams = other.params.get(i); - thisParams.addAll(otherParams); - } - return true; - } - - private int getCommonSuffixLength(ParamCombination other) { - int result = 0; - final int thisSize = params.size(); - final int otherSize = other.params.size(); - while (result < min(thisSize, otherSize)) { - List thisParams = params.get(thisSize - result - 1); - List otherParams = other.params.get(otherSize - result - 1); - if (thisParams.size() != 1 || otherParams.size() != 1) - break; - Param thisParam = thisParams.get(0); - Param otherParam = otherParams.get(0); - if (! thisParam.getName().equals(otherParam.getName())) - break; - result ++; - } - return result; - } - - private boolean allAreOptional(List params) { - for (Param param : params) - if (! param.isOptional()) - return false; - return true; - } - - private boolean allAreEqual(List first, List second) { - if (first.size() != second.size()) - return false; - for (int i = 0; i < first.size(); i++) - if (! first.get(i).equals(second.get(i))) - return false; - return true; - } - - @Override - public Iterator> iterator() { - return params.iterator(); - } - - @Override - public String toString() { - StringBuilder result = new StringBuilder("ParamCombination{"); - EnumerationHelper paramHelper = new EnumerationHelper(); - for (List paramAlternatives : params) { - result.append(paramHelper.next()); - EnumerationHelper paramAltHelper = new EnumerationHelper(); - result.append("["); - for (Param param : paramAlternatives) { - result.append(paramAltHelper.next()); - result.append(param.getName()); - } - result.append("]"); - } - result.append('}'); - return result.toString(); - } -} diff --git a/helium-java/src/site/java/com/heliumhq/site/ParamCombinationTest.java b/helium-java/src/site/java/com/heliumhq/site/ParamCombinationTest.java deleted file mode 100644 index b92b23d..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/ParamCombinationTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.heliumhq.site; - -// Contents of this class uncommented because it is not possible (easily) to add -// JUnit to the class path of the site Java sources in Maven. We should really -// switch to another build tool... - -//import org.junit.Test; -// -//import java.util.HashSet; -//import java.util.Iterator; -//import java.util.List; -// -//import static java.util.Arrays.asList; -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertTrue; - -public class ParamCombinationTest { -// @Test -// public void testJoinSelf() { -// ParamCombination paramCombination = new ParamCombination(); -// Assert.assertTrue(paramCombination.join(paramCombination)); -// } -// @Test -// public void testJoinEmpty() { -// ParamCombination paramCombination = new ParamCombination(); -// Param param = new Param( -// "element", new HashSet(asList("String")), true, false -// ); -// paramCombination.add(param); -// ParamCombination empty = new ParamCombination(); -// Assert.assertTrue(paramCombination.join(empty)); -// } -// @Test -// public void testJoinSimpleSuffix() { -// Param searchRegion = new Param( -// "searchRegion", new HashSet(asList("SearchRegion")), false, -// true -// ); -// Param text = new Param( -// "text", new HashSet(asList("String")), true, false -// ); -// // Text([text], searchRegion...) -// ParamCombination thisCombination = new ParamCombination(); -// thisCombination.add(text); -// thisCombination.add(searchRegion); -// // Text(searchRegion...) -// ParamCombination otherCombination = new ParamCombination(); -// otherCombination.add(searchRegion); -// -// Assert.assertTrue(thisCombination.join(otherCombination)); -// } -// @Test -// public void testJoinCommonSuffix() { -// Param searchRegion = new Param( -// "searchRegion", new HashSet(asList("SearchRegion")), false, -// true -// ); -// Param text = new Param( -// "text", new HashSet(asList("String")), true, false -// ); -// Param locator = new Param( -// "locator", new HashSet(asList("By")), true, false -// ); -// // Text([text], searchRegion...) -// ParamCombination thisCombination = new ParamCombination(); -// thisCombination.add(text); -// thisCombination.add(searchRegion); -// // Text([locator], searchRegion...) -// ParamCombination otherCombination = new ParamCombination(); -// otherCombination.add(locator); -// otherCombination.add(searchRegion); -// -// Assert.assertTrue(thisCombination.join(otherCombination)); -// // Expect thisCombination to have become -// // Text([text or locator], searchRegion...) -// Iterator> iter = thisCombination.iterator(); -// Assert.assertEquals(asList(text, locator), iter.next()); -// Assert.assertEquals(asList(searchRegion), iter.next()); -// } -// @Test -// public void testJoinOptionalPrefix() { -// Param text = new Param( -// "text", new HashSet(asList("String")), false, false -// ); -// Param into = new Param( -// "into", new HashSet(asList("String")), true, false -// ); -// // write(text [, into]) -// ParamCombination thisCombination = new ParamCombination(); -// thisCombination.add(text); -// thisCombination.add(into); -// // write(text) -// ParamCombination otherCombination = new ParamCombination(); -// otherCombination.add(text); -// -// Assert.assertTrue(thisCombination.join(otherCombination)); -// } -} diff --git a/helium-java/src/site/java/com/heliumhq/site/StringUtils.java b/helium-java/src/site/java/com/heliumhq/site/StringUtils.java deleted file mode 100644 index 815d98b..0000000 --- a/helium-java/src/site/java/com/heliumhq/site/StringUtils.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.heliumhq.site; - -import static com.heliumhq.util.StringUtils.*; - -public class StringUtils { - - public static String stripFirstWhitespaceOfEachLine(String input) { - return join("\n", input.split("\n ?")); - } - -} diff --git a/helium-java/src/unittest/java/com/heliumhq/selenium_wrappers/FrameIteratorTest.java b/helium-java/src/unittest/java/com/heliumhq/selenium_wrappers/FrameIteratorTest.java deleted file mode 100644 index 693818d..0000000 --- a/helium-java/src/unittest/java/com/heliumhq/selenium_wrappers/FrameIteratorTest.java +++ /dev/null @@ -1,235 +0,0 @@ -package com.heliumhq.selenium_wrappers; - -import org.junit.Assert; -import org.junit.Test; -import org.openqa.selenium.*; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import static java.util.Arrays.asList; -import static org.junit.Assert.assertArrayEquals; - - -public class FrameIteratorTest { - - @Test - public void testOnlyMainFrame() { - WebDriverWrapper driver = new WebDriverWrapper(new StubWebDriver()); - assertEquals(asList(new int[0]), list(new FrameIterator(driver))); - } - - @Test - public void testOneFrame() { - WebDriverWrapper driver = - new WebDriverWrapper(new StubWebDriver(new Frame())); - assertEquals( - asList(new int[0], new int[] {0}), list(new FrameIterator(driver)) - ); - } - - @Test - public void testTwoFrames() { - WebDriverWrapper driver = - new WebDriverWrapper(new StubWebDriver(new Frame(), new Frame())); - assertEquals( - asList(new int[0], new int[] {0}, new int[] {1}), - list(new FrameIterator(driver)) - ); - } - - @Test - public void testNestedFrame() { - WebDriverWrapper driver = - new WebDriverWrapper(new StubWebDriver(new Frame(new Frame()))); - assertEquals( - asList(new int[0], new int[] {0}, new int[] {0, 0}), - list(new FrameIterator(driver)) - ); - } - - @Test - public void testComplex() { - WebDriverWrapper driver = new WebDriverWrapper( - new StubWebDriver(new Frame(new Frame()), new Frame()) - ); - assertEquals( - asList(new int[0], new int[] {0}, new int[] {0, 0}, new int[] {1}), - list(new FrameIterator(driver)) - ); - } - - @Test(expected=FramesChangedWhileIterating.class) - public void testDisappearingFrame() { - Frame childFrame = new Frame(); - Frame firstFrame = new Frame(childFrame); - StubWebDriver driver = new StubWebDriver(firstFrame); - // We allow precisely 2 frame switches: One to firstFrame and one to - // childFrame. After this, FrameIterator tries to switch back to - // firstFrame, to see whether it has other children besides childFrame. - // This is where we raise a NoSuchFrameException (by limiting the num. - // of frame switches to 2). This simulates a situation where firstFrame - // disappears during iteration. - driver.switchTo = - new TargetLocatorFailingAfterNFrameSwitches(driver, 2); - list(new FrameIterator(new WebDriverWrapper(driver))); - } - - private class StubWebDriver implements WebDriver { - private final Frame[] frames; - private StubTargetLocator switchTo; - private Frame currentFrame; - private StubWebDriver(Frame... frames) { - this.frames = frames; - switchTo = new StubTargetLocator(this); - currentFrame = null; - } - @Override - public TargetLocator switchTo() { - return switchTo; - } - @Override - public void get(String url) { - throw new UnsupportedOperationException(); - } - @Override - public String getCurrentUrl() { - throw new UnsupportedOperationException(); - } - @Override - public String getTitle() { - throw new UnsupportedOperationException(); - } - @Override - public List findElements(By by) { - throw new UnsupportedOperationException(); - } - @Override - public WebElement findElement(By by) { - throw new UnsupportedOperationException(); - } - @Override - public String getPageSource() { - throw new UnsupportedOperationException(); - } - @Override - public void close() { - throw new UnsupportedOperationException(); - } - @Override - public void quit() { - throw new UnsupportedOperationException(); - } - @Override - public Set getWindowHandles() { - throw new UnsupportedOperationException(); - } - @Override - public String getWindowHandle() { - throw new UnsupportedOperationException(); - } - @Override - public Navigation navigate() { - throw new UnsupportedOperationException(); - } - @Override - public Options manage() { - throw new UnsupportedOperationException(); - } - } - - private class StubTargetLocator implements WebDriver.TargetLocator { - private final StubWebDriver driver; - protected StubTargetLocator(StubWebDriver driver) { - this.driver = driver; - } - @Override - public WebDriver defaultContent() { - driver.currentFrame = null; - return driver; - } - @Override - public WebDriver frame(int index) { - Frame[] children; - if (driver.currentFrame == null) - children = driver.frames; - else - children = driver.currentFrame.children; - Frame newFrame; - try { - newFrame = children[index]; - } catch (ArrayIndexOutOfBoundsException e) { - throw new NoSuchFrameException("Frame doesn't exist."); - } - driver.currentFrame = newFrame; - return driver; - } - - @Override - public WebDriver frame(String nameOrId) { - throw new UnsupportedOperationException(); - } - @Override - public WebDriver frame(WebElement frameElement) { - throw new UnsupportedOperationException(); - } - @Override - public WebDriver parentFrame() { - throw new UnsupportedOperationException(); - } - @Override - public WebDriver window(String nameOrHandle) { - throw new UnsupportedOperationException(); - } - @Override - public WebElement activeElement() { - throw new UnsupportedOperationException(); - } - @Override - public Alert alert() { - throw new UnsupportedOperationException(); - } - } - - private class Frame { - private final Frame[] children; - private Frame(Frame... children) { - this.children = children; - } - } - - private class TargetLocatorFailingAfterNFrameSwitches extends - StubTargetLocator { - private int numAllowedFrameSwitches; - private TargetLocatorFailingAfterNFrameSwitches( - StubWebDriver driver, int numAllowedFrameSwitches - ) { - super(driver); - this.numAllowedFrameSwitches = numAllowedFrameSwitches; - } - - @Override - public WebDriver frame(int index) { - if (numAllowedFrameSwitches > 0) { - numAllowedFrameSwitches--; - return super.frame(index); - } - throw new NoSuchFrameException("Frame no longer available."); - } - } - - private List list(Iterable iterable) { - List result = new ArrayList(); - for (T item : iterable) - result.add(item); - return result; - } - - private void assertEquals(List expected, List actual) { - Assert.assertEquals(expected.size(), actual.size()); - for (int i = 0; i < expected.size(); i++) - assertArrayEquals(expected.get(i), actual.get(i)); - } - -} diff --git a/helium-java/src/unittest/java/com/heliumhq/util/Base2intTest.java b/helium-java/src/unittest/java/com/heliumhq/util/Base2intTest.java deleted file mode 100644 index 91ce503..0000000 --- a/helium-java/src/unittest/java/com/heliumhq/util/Base2intTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.heliumhq.util; - -import org.junit.Test; - -import static com.heliumhq.util.Number.base2int; -import static org.junit.Assert.assertEquals; - -public class Base2intTest { - - @Test - public void testZero() { - assertEquals(0, base2int("0", "01")); - } - - @Test - public void testOne() { - assertEquals(1, base2int("1", "01")); - } - - @Test - public void testTwoDigits() { - assertEquals(3, base2int("11", "01")); - } - - @Test - public void testHex() { - assertEquals(255, base2int("FF", "0123456789ABCDEF")); - } - -} \ No newline at end of file diff --git a/helium-java/src/unittest/java/com/heliumhq/util/CollectionsTest.java b/helium-java/src/unittest/java/com/heliumhq/util/CollectionsTest.java deleted file mode 100644 index 52e1275..0000000 --- a/helium-java/src/unittest/java/com/heliumhq/util/CollectionsTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.heliumhq.util; - -import org.junit.Test; - -import java.util.*; - -import static com.heliumhq.util.Collections.inverse; -import static org.junit.Assert.assertEquals; - -public class CollectionsTest { - @Test - public void testInverseEmpty() { - Map> intToStr = - new HashMap>(); - Map> strToInt = - new HashMap>(); - assertEquals(strToInt, inverse(intToStr)); - } - @Test - public void testInverse() { - Map> namesForInts = - new HashMap>(); - Set namesForZero = new HashSet(); - namesForZero.add("zero"); - namesForZero.add("naught"); - Set namesForOne = new HashSet(); - namesForOne.add("one"); - namesForInts.put(0, namesForZero); - namesForInts.put(1, namesForOne); - - Map> intsForNames = - new HashMap>(); - intsForNames.put("zero", new HashSet(Arrays.asList(0))); - intsForNames.put("naught", new HashSet(Arrays.asList(0))); - intsForNames.put("one", new HashSet(Arrays.asList(1))); - assertEquals(intsForNames, inverse(namesForInts)); - } -} diff --git a/helium-java/src/unittest/java/com/heliumhq/util/FileUtilTest.java b/helium-java/src/unittest/java/com/heliumhq/util/FileUtilTest.java deleted file mode 100644 index 53b7a62..0000000 --- a/helium-java/src/unittest/java/com/heliumhq/util/FileUtilTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.heliumhq.util; - -import org.junit.Test; - -import java.io.File; -import java.io.IOException; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class FileUtilTest { - @Test - public void testTextFileCopy() throws IOException { - File source = File.createTempFile("src", ".txt"); - File destination = File.createTempFile("dest", ".txt"); - assertTrue(destination.exists()); - destination.delete(); - assertFalse(destination.exists()); - FileUtil.copyFile(source, destination); - assertTrue(destination.exists()); - destination.delete(); - assertFalse(destination.exists()); - source.deleteOnExit(); - } - - @Test - public void testTextFileCopyNonExistentDir() throws IOException { - File source = File.createTempFile("src", ".txt"); - File destination = new File(new File(java.lang.System.getProperty("java.io.tmpdir", null), "helium-tempdir"), source.getName()); - File destDir = FileUtil.getDirectory(destination); - assertFalse(destDir.exists()); - assertFalse(destination.exists()); - FileUtil.copyFile(source, destination); - assertTrue(destDir.exists()); - assertTrue(destination.exists()); - source.deleteOnExit(); - destination.delete(); - destDir.delete(); - } -} diff --git a/helium-java/src/unittest/java/com/heliumhq/util/GeneratorTest.java b/helium-java/src/unittest/java/com/heliumhq/util/GeneratorTest.java deleted file mode 100644 index 648ea18..0000000 --- a/helium-java/src/unittest/java/com/heliumhq/util/GeneratorTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.heliumhq.util; - -import junit.framework.AssertionFailedError; -import org.junit.Test; - -import java.util.*; -import java.util.Collections; - -import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class GeneratorTest { - - @Test - public void testEmpty() { - assertIterableEquals(Collections.EMPTY_LIST, generate()); - } - - @Test - public void testOneItem() { - assertIterableEquals(asList(1), generate(1)); - } - - @Test - public void testTwoItems() { - assertIterableEquals(asList(5, 3), generate(5, 3)); - } - - @Test - public void testInfinite() { - Generator infinite = new Generator() { - @Override - protected Integer generateNext() { - return 1; - } - }; - Iterator iterator = infinite.iterator(); - for (int i=0; i < 1000; i++) { - assertTrue(iterator.hasNext()); - assertEquals(1, (int) iterator.next()); - } - } - - @Test - public void testGenerateNextNotCalledAfterExhausted() { - Generator generator = new Generator() { - - boolean firstCall = true; - - @Override - protected Integer generateNext() { - if (firstCall) { - firstCall = false; - throw new NoSuchElementException(); - } - throw new AssertionFailedError(); - } - - }; - Iterator iterator = generator.iterator(); - assertFalse(iterator.hasNext()); - // This is the crucial second call that tests that generateNext is not - // called again: - assertFalse(iterator.hasNext()); - } - - private Generator generate(T... items) { - final Iterator iterator = asList(items).iterator(); - return new Generator() { - @Override - protected T generateNext() { - return iterator.next(); - } - }; - } - - private void assertIterableEquals( - Iterable expected, Iterable actual - ) { - List expectedList = new ArrayList(); - for (E item : expected) - expectedList.add(item); - List actualList = new ArrayList(); - for (E item : actual) - actualList.add(item); - assertEquals(expectedList, actualList); - } - -} \ No newline at end of file diff --git a/helium-java/src/unittest/java/com/heliumhq/util/GetEasilyReadableSnippetTest.java b/helium-java/src/unittest/java/com/heliumhq/util/GetEasilyReadableSnippetTest.java deleted file mode 100644 index 20e05fd..0000000 --- a/helium-java/src/unittest/java/com/heliumhq/util/GetEasilyReadableSnippetTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.heliumhq.util; - -import org.junit.Test; - -import static com.google.common.base.Strings.repeat; -import static com.heliumhq.util.HtmlUtils.getEasilyReadableSnippet; -import static org.junit.Assert.assertEquals; - -public class GetEasilyReadableSnippetTest { - - @Test - public void testNoTag() { - assertEquals( - "Hello World!", getEasilyReadableSnippet("Hello World!") - ); - } - - @Test - public void testCompletelyEmptyTag() { - assertEquals("<>", getEasilyReadableSnippet("<>")); - } - - @Test - public void testEmptyTagWithAttributes() { - String emptyTagWithAttrs = - ""; - assertEquals( - emptyTagWithAttrs, - getEasilyReadableSnippet(emptyTagWithAttrs) - ); - } - - @Test - public void testTagWithNestedTags() { - assertEquals( - "...", - getEasilyReadableSnippet("

    Hello World!

    ") - ); - } - - @Test - public void testTagWithLongContent() { - String tagWithLongContent = String.format( - "%s", repeat("x", 100) - ); - assertEquals( - "...", - getEasilyReadableSnippet(tagWithLongContent) - ); - } - -} \ No newline at end of file diff --git a/helium-java/src/unittest/java/com/heliumhq/util/Int2baseTest.java b/helium-java/src/unittest/java/com/heliumhq/util/Int2baseTest.java deleted file mode 100644 index e7705ff..0000000 --- a/helium-java/src/unittest/java/com/heliumhq/util/Int2baseTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.heliumhq.util; - -import org.junit.Test; - -import static com.heliumhq.util.Number.int2base; -import static junit.framework.Assert.assertEquals; - -public class Int2baseTest { - - @Test - public void testZero() { - assertEquals("0", int2base(0, "01")); - } - - @Test - public void testOne() { - assertEquals("1", int2base(1, "01")); - } - - @Test - public void testTwoDigits() { - assertEquals("11", int2base(3, "01")); - } - - @Test - public void testHex() { - assertEquals("FF", int2base(255, "0123456789ABCDEF")); - } - - @Test - public void testHexEightytwo() { - assertEquals("52", int2base(82, "0123456789ABCDEF")); - } - -} \ No newline at end of file diff --git a/helium-java/src/unittest/java/com/heliumhq/util/NormalizeWhitespaceTest.java b/helium-java/src/unittest/java/com/heliumhq/util/NormalizeWhitespaceTest.java deleted file mode 100644 index ee05f3b..0000000 --- a/helium-java/src/unittest/java/com/heliumhq/util/NormalizeWhitespaceTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.heliumhq.util; - -import org.junit.Test; - -import static com.heliumhq.util.HtmlUtils.normalizeWhitespace; -import static org.junit.Assert.assertEquals; - -public class NormalizeWhitespaceTest { - - @Test - public void testStringWithoutWhitespace() { - assertEquals("Foo", normalizeWhitespace("Foo")); - } - - @Test - public void testStringOneWhitespace() { - assertEquals("Hello World!", normalizeWhitespace("Hello World!")); - } - - @Test - public void testStringLeadingWhitespace() { - assertEquals("Hello World!", normalizeWhitespace(" Hello World!")); - } - - @Test - public void testStringComplexWhitespace() { - assertEquals( - "Hello World!", normalizeWhitespace("\n\t Hello\t\t World! \n") - ); - } - - @Test - public void testTagWithSpacesAroundInnerHtml() { - assertEquals( - "Hi there!", - normalizeWhitespace(" Hi there! ") - ); - } - -} diff --git a/helium-java/src/unittest/java/com/heliumhq/util/XPathTest.java b/helium-java/src/unittest/java/com/heliumhq/util/XPathTest.java deleted file mode 100644 index 844e55a..0000000 --- a/helium-java/src/unittest/java/com/heliumhq/util/XPathTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.heliumhq.util; - -import org.junit.Test; - -import static com.heliumhq.util.XPath.predicateOr; -import static org.junit.Assert.assertEquals; - -public class XPathTest { - @Test - public void testPredicateOrNoArgs() { - assertEquals("", predicateOr()); - } - @Test - public void testPredicateOrOneArg() { - assertEquals("[a=b]", predicateOr("a=b")); - } - @Test - public void testPredicateOrTwoArgs() { - assertEquals("[a=b or c=d]", predicateOr("a=b", "c=d")); - } - @Test - public void testPredicateOrOneEmptyArg() { - assertEquals("", predicateOr("")); - } - @Test - public void testPredicateOrEmptyArgAmongNormalArgs() { - assertEquals("[a=b or c=d]", predicateOr("a=b", "", "c=d")); - } -} diff --git a/helium-java/src/unittest/java/com/heliumhq/util/geom/RectangleTest.java b/helium-java/src/unittest/java/com/heliumhq/util/geom/RectangleTest.java deleted file mode 100644 index 491932d..0000000 --- a/helium-java/src/unittest/java/com/heliumhq/util/geom/RectangleTest.java +++ /dev/null @@ -1,191 +0,0 @@ -package com.heliumhq.util.geom; - -import org.junit.Test; - -import static org.junit.Assert.*; - -public class RectangleTest { - @Test - public void testDistanceToOverlappingHorizontally() { - Rectangle top = new Rectangle(989, 14, 47, 15); - Rectangle bottom = new Rectangle(803, 194, 194, 41); - assertEquals(165.0, top.getDistanceTo(bottom), 0.01); - } - @Test - public void testDistanceToOverlappingVertically() { - Rectangle left = new Rectangle(14, 989, 15, 47); - Rectangle right = new Rectangle(194, 803, 41, 194); - assertEquals(165.0, left.getDistanceTo(right), 0.01); - } - @Test - public void testDistanceToNotOverlapping() { - Rectangle topLeft = new Rectangle(0, 0, 1, 1); - Rectangle bottomRight = new Rectangle(2, 2, 1, 1); - assertEquals(Math.sqrt(2), topLeft.getDistanceTo(bottomRight), 0.01); - } - @Test - public void testDistanceFullyOverlappingVertically() { - Rectangle top = new Rectangle(989, 14, 1000, 15); - Rectangle bottom = new Rectangle(803, 194, 194, 41); - assertEquals(165.0, top.getDistanceTo(bottom), 0.01); - } - @Test - public void testIntersectsSelf() { - Rectangle rect = new Rectangle(1, 2, 3, 4); - assertTrue(rect.intersects(rect)); - } - @Test - public void testIntersectsNonIntersecting() { - Rectangle rect_1 = new Rectangle(1, 2, 3, 4); - Rectangle rect_2 = new Rectangle(10, 20, 30, 40); - assertFalse(rect_1.intersects(rect_2)); - } - @Test - public void testIntersectsContaining() { - Rectangle rect_1 = new Rectangle(1, 2, 3, 4); - Rectangle rect_2 = new Rectangle(2, 3, 1, 1); - assertTrue(rect_2.intersects(rect_1)); - } - @Test - public void testIntersectsOverlapping() { - Rectangle rect_1 = new Rectangle(0, 0, 3, 3); - Rectangle rect_2 = new Rectangle(1, 2, 3, 4); - assertTrue(rect_1.intersects(rect_2)); - } - @Test - public void testIsToLeftOf() { - /** - * 0 10 20 30 40 50 60 - * 01234567890123456789012345678901234567890123456789012345678901 - * ____ ____ - * 0 |_r0_| ____ | r1 | - * 1 ___ | r2 | ____ ____ |____| - * 2 | | |____| | r3 | | | ____ - * 3 | r | |____| | r4 | |_r5_| ____ - * 4 |___| |____| | r6 | ____ - * 5 |____| | r7 | ____ - * 6 |____| |_r8_| - */ - Rectangle rectangle = new Rectangle(0, 2, 4, 3); - Rectangle r0 = new Rectangle(7, 0, 5, 1); - Rectangle r1 = new Rectangle(35, 0, 5, 2); - Rectangle r2 = new Rectangle(14, 1, 5, 2); - Rectangle r3 = new Rectangle(21, 2, 5, 2); - Rectangle r4 = new Rectangle(28, 2, 5, 3); - Rectangle r5 = new Rectangle(35, 3, 5, 1); - Rectangle r6 = new Rectangle(42, 4, 5, 2); - Rectangle r7 = new Rectangle(49, 5, 5, 2); - Rectangle r8 = new Rectangle(56, 6, 5, 1); - assertFalse(rectangle.isToLeftOf(r0)); - assertFalse(rectangle.isToLeftOf(r1)); - assertTrue(rectangle.isToLeftOf(r2)); - assertTrue(rectangle.isToLeftOf(r3)); - assertTrue(rectangle.isToLeftOf(r4)); - assertTrue(rectangle.isToLeftOf(r5)); - assertTrue(rectangle.isToLeftOf(r6)); - assertFalse(rectangle.isToLeftOf(r7)); - assertFalse(rectangle.isToLeftOf(r8)); - } - @Test - public void testIsToRightOf() { - /** - * 0 10 20 30 40 50 60 - * 01234567890123456789012345678901234567890123456789012345678901 - * ____ ____ - * 0 |_r0_| ____ | r1 | - * 1 ___ | r2 | ____ ____ |____| - * 2 | | |____| | r3 | | | ____ - * 3 | r | |____| | r4 | |_r5_| ____ - * 4 |___| |____| | r6 | ____ - * 5 |____| | r7 | ____ - * 6 |____| |_r8_| - */ - Rectangle rectangle = new Rectangle(0, 2, 4, 3); - Rectangle r0 = new Rectangle(7, 0, 5, 1); - Rectangle r1 = new Rectangle(35, 0, 5, 2); - Rectangle r2 = new Rectangle(14, 1, 5, 2); - Rectangle r3 = new Rectangle(21, 2, 5, 2); - Rectangle r4 = new Rectangle(28, 2, 5, 3); - Rectangle r8 = new Rectangle(56, 6, 5, 1); - assertFalse(r8.isToRightOf(r1)); - assertTrue(r4.isToRightOf(r3)); - assertTrue(r4.isToRightOf(r2)); - assertFalse(r4.isToRightOf(r0)); - assertTrue(r4.isToRightOf(rectangle)); - } - @Test - public void testIsAbove() { - /** - * 0 10 20 - * 0123456789012345678901 - * _____ - * 0 |__r__| - * 1 ____ ____ ____ - * 2 |_r0_| |_r3_| |_r8_| - * 3 ____ __ ____ - * 4 |_r1_| |r5||_r7_| - * 5 ____ ____ - * 6 |_r2_| |_r6_| - * 7 _____ - * 8 |_r4__| - */ - Rectangle rectangle = new Rectangle(7, 0, 6, 1); - Rectangle r0 = new Rectangle(0, 2, 5, 1); - Rectangle r1 = new Rectangle(2, 4, 5, 1); - Rectangle r2 = new Rectangle(5, 6, 5, 1); - Rectangle r3 = new Rectangle(7, 2, 5, 1); - Rectangle r4 = new Rectangle(7, 8, 6, 1); - Rectangle r5 = new Rectangle(9, 4, 3, 1); - Rectangle r6 = new Rectangle(12, 6, 5, 1); - Rectangle r7 = new Rectangle(13, 4, 5, 1); - Rectangle r8 = new Rectangle(15, 2, 5, 1); - assertFalse(rectangle.isAbove(r0)); - assertFalse(rectangle.isAbove(r1)); - assertTrue(rectangle.isAbove(r2)); - assertTrue(rectangle.isAbove(r3)); - assertTrue(rectangle.isAbove(r4)); - assertTrue(rectangle.isAbove(r5)); - assertTrue(rectangle.isAbove(r6)); - assertFalse(rectangle.isAbove(r7)); - assertFalse(rectangle.isAbove(r8)); - } - @Test - public void testEqualsNull() { - Rectangle rectangle = new Rectangle(1, 2, 3, 4); - assertFalse(rectangle.equals(null)); - } - @Test - public void testEqualsNonRectangle() { - Rectangle rectangle = new Rectangle(1, 2, 3, 4); - assertFalse(rectangle.equals("hi there")); - } - @Test - public void testEqualsSelf() { - Rectangle rectangle = new Rectangle(1, 2, 3, 4); - assertTrue(rectangle.equals(rectangle)); - } - @Test - public void testEqualsEqual() { - Rectangle r1 = new Rectangle(1, 2, 3, 4); - Rectangle r2 = new Rectangle(1, 2, 3, 4); - assertTrue(r1.equals(r2)); - } - @Test - public void testEqualsDifferent() { - Rectangle r1 = new Rectangle(1, 2, 3, 4); - Rectangle r2 = new Rectangle(4, 5, 6, 7); - assertFalse(r1.equals(r2)); - } - @Test - public void testHashcodeDifferentForDifferentRectangles() { - Rectangle r1 = new Rectangle(1, 2, 3, 4); - Rectangle r2 = new Rectangle(6, 3, 3, 4); - assertNotEquals(r1.hashCode(), r2.hashCode()); - } - @Test - public void testHashcodeSameForEqualRectangles() { - Rectangle r1 = new Rectangle(1, 2, 3, 4); - Rectangle r2 = new Rectangle(1, 2, 3, 4); - assertEquals(r1.hashCode(), r2.hashCode()); - } -} diff --git a/helium-python/.gitignore b/helium-python/.gitignore deleted file mode 100644 index 8bab856..0000000 --- a/helium-python/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -*.pyc -target/ -*.poic \ No newline at end of file diff --git a/helium-python/build.py b/helium-python/build.py deleted file mode 100644 index 56a506f..0000000 --- a/helium-python/build.py +++ /dev/null @@ -1,115 +0,0 @@ -from helium.util import system -from helium.util.path import ensure_exists -from build_environment import get_target_path, get_proj_path -from build_impl import copy_package_sources, rmtree_safe, Platform, \ - copy_with_filtering, unzip_replacing_top_lvl_dir, pip_install -from distutils.dir_util import copy_tree -from glob import glob -from os.path import exists, join -from setuptools import find_packages - -import helium -import selenium -import sys - -PLATFORMS = [ - Platform('linux', 'Operating System :: POSIX :: Linux'), - Platform('macosx', 'Operating System :: MacOS :: MacOS X'), - Platform('win', 'Operating System :: Microsoft :: Windows') -] - -_SOURCES_DIR = get_target_path('sources') -_PIP_DIST_DIR = get_target_path('pip-dist') - -def initialize(selenium_version, psutil_version): - pip_install('selenium==' + selenium_version) - pip_install('psutil==' + psutil_version) - -def generate_sources(project_version, selenium_version, psutil_version): - if exists(_SOURCES_DIR): - rmtree_safe(_SOURCES_DIR) - copy_package_sources(helium, to=_SOURCES_DIR) - helium__init__ = join(_SOURCES_DIR, 'helium', '__init__.py') - _add__version__(helium__init__, project_version) - for platform in PLATFORMS: - _generate_setup_py( - platform.dist_dir, [platform], project_version, selenium_version, - psutil_version - ) - _generate_setup_py( - _PIP_DIST_DIR, PLATFORMS, project_version, selenium_version, - psutil_version - ) - -def _add__version__(helium__init__, project_version): - with open(helium__init__, 'r') as f: - existing_contents = f.read() - with open(helium__init__, 'w') as f: - f.write("__version__ = %r\n\n%s" % (project_version, existing_contents)) - -def _generate_setup_py( - dest_dir, platforms, project_version, selenium_version, psutil_version -): - template = get_proj_path('src/main/resources/base/setup.py') - classifiers = _DEFAULT_CLASSIFIERS[:] - classifiers.extend([platform.classifier for platform in platforms]) - format_items = lambda items: "\n\t\t%s\n\t" % ",\n\t\t".join(items) - classifiers_str = '[%s]' % format_items(list(map(repr, classifiers))) - packages = find_packages(_get_sources_dir_to_distribute()) - packages_str = '[%s]' % format_items(list(map(repr, packages))) - package_data = dict([(pkg, ['*.py3']) for pkg in packages]) - package_data['helium'].append('data/*.*') - for platform in platforms: - package_data['helium'].append('data/%s/webdrivers/*' % platform.name) - package_data_items = \ - ['%r: %r' % item for item in list(package_data.items())] - package_data_str = '{%s}' % format_items(package_data_items) - ensure_exists(dest_dir) - copy_with_filtering( - template, dest_dir, - { - 'project.version': project_version, - 'classifiers': classifiers_str, - 'packages': packages_str, - 'package_data': package_data_str, - 'selenium.version': selenium_version, - 'psutil.version': psutil_version - } - ) - -_DEFAULT_CLASSIFIERS = [ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'License :: Other/Proprietary License', - 'Topic :: Software Development :: Testing', - 'Topic :: Software Development :: Libraries', - 'Programming Language :: Python', - 'Programming Language :: Python :: 2.6', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3.2', - 'Programming Language :: Python :: 3.3' -] - -def _get_sources_dir_to_distribute(): - return _SOURCES_DIR - -def process_resources(selenium_version): - dependencies_dir = get_target_path('dependencies') - assert selenium.__version__ == selenium_version, \ - 'Please ensure you have Selenium version %s installed or notify ' \ - 'the team if you want to update.' % selenium_version - copy_package_sources(selenium, to=dependencies_dir) - -def prepare_package(): - heliumlib_base = get_target_path('dist-base/heliumlib') - copy_tree(_get_sources_dir_to_distribute(), heliumlib_base) - copy_tree(get_target_path('dependencies'), heliumlib_base) - -def pre_integration_test(project_version): - test_dist_dir = get_target_path('test-dist') - platform = system.get_canonical_os_name() - helium_zip_path, = glob(get_target_path('helium-*.*.*-%s.zip' % platform)) - unzip_replacing_top_lvl_dir(helium_zip_path, test_dist_dir) - -if __name__ == '__main__': - globals()[sys.argv[1]](*sys.argv[2:]) \ No newline at end of file diff --git a/helium-python/build_environment.py b/helium-python/build_environment.py deleted file mode 100644 index eb7880e..0000000 --- a/helium-python/build_environment.py +++ /dev/null @@ -1,8 +0,0 @@ -from os.path import dirname, join - -def get_proj_path(*rel_path): - rel_path = '/'.join(rel_path) - return join(dirname(__file__), *rel_path.split('/')) - -def get_target_path(*rel_path): - return get_proj_path('target/' + '/'.join(rel_path)) \ No newline at end of file diff --git a/helium-python/build_impl.py b/helium-python/build_impl.py deleted file mode 100644 index 0af71f1..0000000 --- a/helium-python/build_impl.py +++ /dev/null @@ -1,72 +0,0 @@ -from build_environment import get_target_path, get_proj_path -from helium.util.path import ensure_exists, get_components -from os import walk, chmod, unlink, path -from os.path import abspath, join, dirname, splitext, pardir, basename -from shutil import copyfile, rmtree -from subprocess import check_call -from zipfile import ZipFile - -import stat -import sys - -class Platform(object): - def __init__(self, name, classifier): - self.name = name - self.classifier = classifier - @property - def dist_dir(self): - return get_target_path('dist-' + self.name) - -def rmtree_safe(dir_path): - def handle_rm_error(func, file_path, exc_info): - # This gets called when rmtree cannot remove file with path file_path. - # Assume the cause of the problem is that the file is readonly and - # unlink it: - chmod(file_path, stat.S_IWRITE) - unlink(file_path) - rmtree(dir_path, onerror=handle_rm_error) - -def copy_package_sources( - package, to, file_endings=('.py', '.so', '.json', '.xpi', '.js') -): - copy_over(package.__path__[0], join(to, package.__name__), file_endings) - -def copy_over(src_dir, dest_dir, file_endings=None): - src_dir = abspath(src_dir) - dest_dir = abspath(dest_dir) - src_dir_parts = get_components(src_dir) - for root, dirs, files in walk(src_dir): - for file_name in files: - if file_endings is None or splitext(file_name)[1] in file_endings: - src_file_path = join(root, file_name) - src_file_path_parts = get_components(src_file_path) - dest_file_parts = src_file_path_parts[len(src_dir_parts):] - dest_file_path = join(dest_dir, *dest_file_parts) - ensure_exists(dirname(dest_file_path)) - copyfile(src_file_path, dest_file_path) - -def abs_path(*rel_path): - return abspath(join(__file__, pardir, *rel_path)) - -def copy_with_filtering(src_file, dest_dir, dict_, place_holder='${%s}'): - ensure_exists(dest_dir) - dest_file = join(dest_dir, basename(src_file)) - with open(src_file, 'r') as open_src_file: - with open(dest_file, 'w') as open_dest_file: - for line in open_src_file: - new_line = line - for key, value in dict_.items(): - new_line = new_line.replace(place_holder % key, value) - open_dest_file.write(new_line) - -def unzip_replacing_top_lvl_dir(zip_file_path, dest_dir): - zip_file = ZipFile(zip_file_path, 'r') - target_dir, _ = path.split(dest_dir) - zip_file.extractall(target_dir) - top_lvl_dir = sorted(zip_file.namelist(), key=lambda name: len(name))[0] - unzipped_dir = join(target_dir, top_lvl_dir) - copy_over(unzipped_dir, dest_dir) - rmtree_safe(unzipped_dir) - -def pip_install(dependency): - check_call([sys.executable, '-m', 'pip', 'install', '-U', dependency, '-q']) \ No newline at end of file diff --git a/helium-python/pom.xml b/helium-python/pom.xml deleted file mode 100644 index aa9f479..0000000 --- a/helium-python/pom.xml +++ /dev/null @@ -1,604 +0,0 @@ - - 4.0.0 - - com.heliumhq - helium - 2.0.4-SNAPSHOT - - helium-python - pom - - 3.141.0 - inttest_.* - apitest_.* - systest_.* - ${basedir}/.. - - - - integrationtests - - true - - performRelease - true - - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - - perform-integrationtests - integration-test - - exec - - - nosetests - - ${basedir} - - - - --where=${basedir}/src/integrationtest/python - - - --include=${inttestIncludes} - - --verbose - --nocapture - - - - --no-path-adjustment - - - - --stop - - - --nologcapture - - - - ${heliumPythonInttestPythonpath} - - - - - - - - - - - chrome - - true - - performRelease - true - - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - - perform-api-integrationtests-chrome - integration-test - - exec - - - nosetests - - ${basedir} - - - - --where=${basedir}/src/integrationtest/python - - - --include=${apitestIncludes} - - --verbose - --nocapture - - - - --no-path-adjustment - - - - --stop - - - --nologcapture - - - - ${heliumPythonApitestPythonpath} - - - - - - - - - - - firefox - - - performRelease - true - - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - - perform-api-integrationtests-firefox - integration-test - - exec - - - nosetests - - ${basedir} - - - - --where=${basedir}/src/integrationtest/python - - - --include=${apitestIncludes} - - --verbose - --nocapture - - - - --no-path-adjustment - - - - --stop - - - --nologcapture - - - - ${heliumPythonApitestPythonpath} - - firefox - - - - - - - - - - ie - - - performRelease - true - - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - - perform-api-integrationtests-ie - integration-test - - exec - - - nosetests - - ${basedir} - - - - --where=${basedir}/src/integrationtest/python - - - --include=${apitestIncludes} - - --verbose - --nocapture - - - - --no-path-adjustment - - - - --stop - - - --nologcapture - - - - ${heliumPythonApitestPythonpath} - - ie - - - - - - - - - - - ${project.artifactId}-${project.version} - ${project.build.directory}/dist-base - - ${project.build.directory}/test-dist - - - - maven-clean-plugin - 2.5 - - - - ${basedir} - - target/ - **/*.log - **/*.pyo - **/*.pyc - - false - - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - - initialize - initialize - - exec - - - python - ${basedir} - - build.py - initialize - ${selenium.version} - ${psutil.version} - - - ${buildPythonpath} - - - - - perform-unittests - test - - exec - - - nosetests - ${basedir} - - - --where=src/unittest/python - - --verbose - --nocapture - - - --stop - - - --nologcapture - - - - ${heliumPythonUnittestPythonpath} - - - - - - perform-systemtests - integration-test - - exec - - - nosetests - ${basedir} - - - --where=src/systemtest/python - - - --include=${systestIncludes} - - --verbose - --nocapture - - - --no-path-adjustment - - - --stop - - - --nologcapture - - - ${heliumPythonSystestPythonpath} - - - - - generate-sources - generate-sources - - exec - - - python - ${basedir} - - build.py - generate_sources - ${project.version} - ${selenium.version} - ${psutil.version} - - - - ${buildPythonpath} - - - - - - process-resources - process-resources - - exec - - - python - ${basedir} - - build.py - process_resources - ${selenium.version} - - - - ${buildPythonpath} - - - - - - prepare-package - prepare-package - - exec - - - python - ${basedir} - - build.py - prepare_package - - - - ${buildPythonpath} - - - - - - pre-integration-test - pre-integration-test - - exec - - - python - ${basedir} - - build.py - pre_integration_test - ${project.version} - - - - ${buildPythonpath} - - - - - - install-site-dependencies - pre-site - - exec - - - pip - ${basedir} - - install - sphinx==1.3.1 - -q - - - - - generate-sources-for-site - pre-site - - exec - - - python - ${basedir} - - build.py - generate_sources - ${project.version} - ${selenium.version} - ${psutil.version} - - - - ${buildPythonpath} - - - - - - generate-api-docs - site - - exec - - - make - - ${basedir}/src/site/docs - - - html - - - - ${heliumPythonMainPythonpath} - - - - - - - - maven-resources-plugin - 2.6 - - - ${*} - - false - - ${project.build.outputDirectory} - - - - - ${basedir}/src/main/resources/base - - - setup.py - **/*.pyc - - false - - - - - - default-resources - process-resources - - copy-resources - - - - - - maven-assembly-plugin - 2.4 - - - package-individual-platforms - package - - single - - - - - ${basedir}/src/main/assembly/win.xml - - - ${basedir}/src/main/assembly/macosx.xml - - - ${basedir}/src/main/assembly/linux.xml - - - - ${project.build.directory} - - true - - - - prepare-pip-dist-for-upload-to-pypi - install - - single - - - - - ${basedir}/src/main/assembly/pip.xml - - - - ${project.build.directory} - - false - false - pip-dist - - - - - - - diff --git a/helium-python/src/integrationtest/python/helium_integrationtest/__init__.py b/helium-python/src/integrationtest/python/helium_integrationtest/__init__.py deleted file mode 100644 index b3db43d..0000000 --- a/helium-python/src/integrationtest/python/helium_integrationtest/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from helium_integrationtest.environment import get_integrationtest_resource, \ - path_to_file_url \ No newline at end of file diff --git a/helium-python/src/integrationtest/python/helium_integrationtest/environment.py b/helium-python/src/integrationtest/python/helium_integrationtest/environment.py deleted file mode 100644 index e00abe8..0000000 --- a/helium-python/src/integrationtest/python/helium_integrationtest/environment.py +++ /dev/null @@ -1,20 +0,0 @@ -from os import path -from os.path import abspath, pardir - -def get_integrationtest_resource(*rel_path_compontents): - return abspath(path.join( - __file__, pardir, pardir, pardir, pardir, pardir, pardir, - 'src', 'integrationtest', 'resources', *rel_path_compontents - )) - -def get_helium_package_source(*rel_path_compontents): - return abspath(path.join( - __file__, pardir, pardir, pardir, pardir, pardir, - 'src', 'main', 'python', *rel_path_compontents - )) - -def path_to_file_url(path): - return 'file:///' + path.replace('\\', '/') - -def get_it_file_url(page): - return path_to_file_url(get_integrationtest_resource(page)) \ No newline at end of file diff --git a/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/apitest_ie_ssl.py b/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/apitest_ie_ssl.py deleted file mode 100644 index 373fa96..0000000 --- a/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/apitest_ie_ssl.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -from helium.api import click, Text -from helium_integrationtest.environment import get_integrationtest_resource -from helium_integrationtest.inttest_api import test_browser_name, BrowserAT -from http.server import HTTPServer -from locale import getdefaultlocale -from os.path import abspath -from http.server import SimpleHTTPRequestHandler -from threading import Thread -from unittest.case import skipIf -import ssl -import sys - -@skipIf( - test_browser_name() != 'ie', - "This test only makes sense to be run on IE as other browsers don't display" - " the warning page 'Invalid SSL certificate' when driven via Selenium." -) -class IESSLIT(BrowserAT): - SSL_SERVER_PORT = 4443 - def setUp(self): - self.ssl_server = SSLServer(self.SSL_SERVER_PORT, get_ssl_cert_file()) - self.ssl_server.start() - super(IESSLIT, self).setUp() - def get_url(self): - return 'https://localhost:%d' % self.SSL_SERVER_PORT - def test_continue(self): - def_locale = getdefaultlocale()[0] - if def_locale.startswith("pl"): - click( - 'Kontynuuj przeglądanie tej witryny sieci Web (niezalecane).' - ) - else: - click("Continue to this website (not recommended).") - self.assertTrue(Text("Directory listing").exists()) - def tearDown(self): - super(IESSLIT, self).tearDown() - self.ssl_server.stop() - -class SSLServer(object): - def __init__(self, port, cert_file_path): - self.cert_file_path = cert_file_path - self.server = HTTPServer(('localhost', port), SimpleHTTPRequestHandler) - self.server.socket = ssl.wrap_socket( - self.server.socket, certfile=abspath(self.cert_file_path), - server_side=True - ) - self.server_thread = None - def start(self): - self.server_thread = Thread(target=self.server.serve_forever) - self.server_thread.start() - def stop(self): - self.server.shutdown() - self.server_thread.join() - -def get_ssl_cert_file(): - return get_integrationtest_resource('inttest_ie_ssl', 'ssl_certificate.pem') - -if __name__ == '__main__': - ssl_server = SSLServer(IESSLIT.SSL_SERVER_PORT, get_ssl_cert_file()) - ssl_server.start() - sys.stdout.write( - 'SSL server started on port %r.\n' % IESSLIT.SSL_SERVER_PORT - ) - sys.stdout.flush() \ No newline at end of file diff --git a/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/apitest_kill_service_at_exit_ie.py b/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/apitest_kill_service_at_exit_ie.py deleted file mode 100644 index b2c6f18..0000000 --- a/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/apitest_kill_service_at_exit_ie.py +++ /dev/null @@ -1,27 +0,0 @@ -from helium_integrationtest.util import InSubProcess -from helium.api import start_ie -from helium_integrationtest.inttest_api import test_browser_name -from helium_integrationtest.inttest_api.apitest_kill_service_at_exit import \ - KillServiceAtExitAT -from unittest import skipIf, TestCase - -@skipIf( - test_browser_name() != 'ie', "Only run this test for TEST_BROWSER ie." -) -class KillServiceAtExitIEIT(KillServiceAtExitAT, TestCase): - def get_service_process_names(self): - return ["IEDriverServer.exe"] - def get_browser_process_name(self): - return "iexplore.exe" - def start_browser_in_sub_process(self): - with IeInSubProcess(): - pass - -class IeInSubProcess(InSubProcess): - @classmethod - def main(cls): - start_ie() - cls.synchronize_with_parent_process() - -if __name__ == '__main__': - IeInSubProcess.main() \ No newline at end of file diff --git a/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/apitest_press.py b/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/apitest_press.py deleted file mode 100644 index 70a4484..0000000 --- a/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/apitest_press.py +++ /dev/null @@ -1,29 +0,0 @@ -from helium.api import press, write, CONTROL, TAB, TextField, SHIFT -from helium_integrationtest.inttest_api import BrowserAT -from unittest import skip - -class PressIT(BrowserAT): - def get_page(self): - return 'inttest_write.html' - def test_press_single_character(self): - press('a') - self.assertEqual('a', TextField('Autofocus text field').value) - def test_press_upper_case_character(self): - press('A') - self.assertEqual('A', TextField('Autofocus text field').value) - def test_press_shift_plus_lower_case_character(self): - press(SHIFT + 'a') - self.assertEqual('A', TextField('Autofocus text field').value) - @skip - def test_copy_paste(self): - # it is not possible to copy paste on OSX - # OSX does not support native key events - # https://code.google.com/p/selenium/issues/detail?id=3101 - write('One Two Three') - press(CONTROL + 'a') - press(CONTROL + 'c') - press(TAB) - press(CONTROL + 'v') - self.assertEqual( - 'One Two Three', TextField("Normal text field").value - ) \ No newline at end of file diff --git a/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/apitest_window.py b/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/apitest_window.py deleted file mode 100644 index 55a0020..0000000 --- a/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/apitest_window.py +++ /dev/null @@ -1,43 +0,0 @@ -from helium.api import Window, click, go_to, get_driver, wait_until -from helium_integrationtest.environment import get_it_file_url -from helium_integrationtest.inttest_api import BrowserAT, should_run - -class WindowIT(BrowserAT): - def get_page(self): - return 'inttest_window/inttest_window.html' - def test_window_exists(self): - self.assertTrue(Window('inttest_window').exists()) - def test_window_not_exists(self): - self.assertFalse(Window('non-existent').exists()) - def test_no_arg_window_exists(self): - self.assertTrue(Window().exists()) - def test_handle(self): - self.assertTrue(Window('inttest_window').handle) - def test_title(self): - self.assertEqual('inttest_window', Window('inttest_window').title) - -class MultipleWindowIT(WindowIT): - """ - The purpose of this IT is to run the same tests as WindowIT, but with an - additional pop up window open. - """ - @classmethod - def setUpClass(cls): - super(MultipleWindowIT, cls).setUpClass() - if should_run(): - go_to(get_it_file_url('inttest_window/inttest_window.html')) - click("Click here to open a popup.") - wait_until(Window('inttest_window - popup').exists) - def test_popup_window_exists(self): - self.assertTrue(Window('inttest_window - popup').exists()) - def setUp(self): - # Don't let super go_to(...): - pass - @classmethod - def tearDownClass(cls): - popup_window_handle = Window("inttest_window - popup").handle - main_window_handle = Window("inttest_window").handle - get_driver().switch_to_window(popup_window_handle) - get_driver().close() - get_driver().switch_to_window(main_window_handle) - super(MultipleWindowIT, cls).tearDownClass() \ No newline at end of file diff --git a/helium-python/src/integrationtest/python/helium_integrationtest/inttest_environment.py b/helium-python/src/integrationtest/python/helium_integrationtest/inttest_environment.py deleted file mode 100644 index cee5ecb..0000000 --- a/helium-python/src/integrationtest/python/helium_integrationtest/inttest_environment.py +++ /dev/null @@ -1,30 +0,0 @@ -from helium_integrationtest.util import ResourceLocator -from helium_integrationtest.environment import get_integrationtest_resource -from os import path -from unittest import TestCase - -class ResourceLocatorIT(TestCase): - def setUp(self): - self.root_dir = get_integrationtest_resource('inttest_environment') - def test_locate_file(self): - resource_locator = ResourceLocator(self.root_dir) - result = resource_locator.locate('file.txt') - self.assertIsNotNone(result) - self.assertTrue(path.exists(result)) - def test_locate_file_in_dir(self): - resource_locator = ResourceLocator(self.root_dir) - result = resource_locator.locate('dir', 'file_in_dir.txt') - self.assertIsNotNone(result) - self.assertTrue(path.exists(result)) - def test_locate_non_existent_file(self): - resource_locator = ResourceLocator(self.root_dir) - result = resource_locator.locate('non-existent file') - self.assertIsNotNone(result) - def test_multiple_root_directories(self): - resource_locator = ResourceLocator( - self.root_dir, - get_integrationtest_resource('inttest_environment', 'dir') - ) - result = resource_locator.locate('file_in_dir.txt') - self.assertIsNotNone(result) - self.assertTrue(path.exists(result)) \ No newline at end of file diff --git a/helium-python/src/main/assembly/linux.xml b/helium-python/src/main/assembly/linux.xml deleted file mode 100644 index b800803..0000000 --- a/helium-python/src/main/assembly/linux.xml +++ /dev/null @@ -1,27 +0,0 @@ - - linux - - zip - - ${project.artifactId}-${project.version} - - - ${project.build.outputDirectory} - . - - - - ${parentBasedir}/src/main/resources/linux/webdrivers - - - heliumlib/helium/data/linux/webdrivers - - 0755 - 0755 - - - \ No newline at end of file diff --git a/helium-python/src/main/assembly/macosx.xml b/helium-python/src/main/assembly/macosx.xml deleted file mode 100644 index eca78d2..0000000 --- a/helium-python/src/main/assembly/macosx.xml +++ /dev/null @@ -1,27 +0,0 @@ - - macosx - - zip - - ${project.artifactId}-${project.version} - - - ${project.build.outputDirectory} - . - - - - ${parentBasedir}/src/main/resources/macosx/webdrivers - - - heliumlib/helium/data/macosx/webdrivers - - 0755 - 0755 - - - \ No newline at end of file diff --git a/helium-python/src/main/assembly/pip.xml b/helium-python/src/main/assembly/pip.xml deleted file mode 100644 index 3813e8a..0000000 --- a/helium-python/src/main/assembly/pip.xml +++ /dev/null @@ -1,31 +0,0 @@ - - pip - - dir - - false - - - ${project.build.outputDirectory} - . - - heliumlib/helium/** - heliumlib/bfs/** - - - - ${parentBasedir}/src/main/resources - - linux/webdrivers/* - macosx/webdrivers/* - win/webdrivers/* - - heliumlib/helium/data - 0755 - - - \ No newline at end of file diff --git a/helium-python/src/main/assembly/win.xml b/helium-python/src/main/assembly/win.xml deleted file mode 100644 index 8540e57..0000000 --- a/helium-python/src/main/assembly/win.xml +++ /dev/null @@ -1,35 +0,0 @@ - - win - - zip - - ${project.artifactId}-${project.version} - - - ${project.build.outputDirectory} - . - - - ${project.build.directory}/dist-win - . - - - ${basedir}/src/main/resources/win - . - - - - ${parentBasedir}/src/main/resources/win/webdrivers - - - heliumlib/helium/data/win/webdrivers - - 0755 - 0755 - - - \ No newline at end of file diff --git a/helium-python/src/main/python/helium/api_impl/application_context.py b/helium-python/src/main/python/helium/api_impl/application_context.py deleted file mode 100644 index 6d74fc2..0000000 --- a/helium-python/src/main/python/helium/api_impl/application_context.py +++ /dev/null @@ -1,57 +0,0 @@ -from helium.api_impl import APIImpl -from helium.environment import ResourceLocator, is_development -from helium.util.system import get_canonical_os_name -from os.path import pardir, join, exists, dirname, normpath - -import helium - -def get_application_context(): - global _APPLICATION_CONTEXT - if _APPLICATION_CONTEXT is None: - if is_development(): - _APPLICATION_CONTEXT = DevelopmentAPIConfig() - else: - _APPLICATION_CONTEXT = StandaloneAPIConfig() - return _APPLICATION_CONTEXT -_APPLICATION_CONTEXT = None - -class APIConfig(object): - def __init__(self): - self.api_impl = None - def APIImpl(self): - if self.api_impl is None: - self.api_impl = APIImpl(self.ResourceLocator()) - return self.api_impl - def ResourceLocator(self): - raise NotImplementedError() - -class DevelopmentAPIConfig(APIConfig): - def __init__(self): - super(DevelopmentAPIConfig, self).__init__() - self.resource_locator = None - def ResourceLocator(self): - if self.resource_locator is None: - proj_dir = \ - join(dirname(__file__), pardir, pardir, pardir, pardir, pardir) - def proj_file(rel_path): - return normpath(join(proj_dir, *rel_path.split('/'))) - return ResourceLocator( - proj_file('../src/main/resources/base'), - proj_file('../src/main/resources/' + get_canonical_os_name()), - proj_file('../target') - ) - return self.resource_locator - -class StandaloneAPIConfig(APIConfig): - def __init__(self): - self.resource_locator = None - super(StandaloneAPIConfig, self).__init__() - def ResourceLocator(self): - if self.resource_locator is None: - helium_pkg_dir = dirname(helium.__file__) - data_dir = join(helium_pkg_dir, 'data') - helium_home = data_dir if exists(data_dir) else helium_pkg_dir - self.resource_locator = ResourceLocator( - helium_home, join(helium_home, get_canonical_os_name()) - ) - return self.resource_locator \ No newline at end of file diff --git a/helium-python/src/main/resources/base/setup.py b/helium-python/src/main/resources/base/setup.py deleted file mode 100644 index 3998fcf..0000000 --- a/helium-python/src/main/resources/base/setup.py +++ /dev/null @@ -1,19 +0,0 @@ -from setuptools import setup - -setup( - name = 'helium', - version = '${project.version}', - author = 'Michael Herrmann', - author_email = 'michael+removethisifyouarehuman@herrmann.io', - description = 'Simple web automation based on Selenium.', - keywords = 'selenium web automation', - url = 'http://heliumhq.com', - classifiers = ${classifiers}, - packages = ${packages}, - package_dir = {'helium': 'heliumlib/helium'}, - install_requires = [ - 'selenium==${selenium.version}', 'psutil>=${psutil.version}' - ], - package_data = ${package_data}, - zip_safe = False -) \ No newline at end of file diff --git a/helium-python/src/site/docs/.gitignore b/helium-python/src/site/docs/.gitignore deleted file mode 100644 index 69fa449..0000000 --- a/helium-python/src/site/docs/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_build/ diff --git a/helium-python/src/site/docs/Makefile b/helium-python/src/site/docs/Makefile deleted file mode 100644 index a5eea9b..0000000 --- a/helium-python/src/site/docs/Makefile +++ /dev/null @@ -1,187 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = ../../../target/docs - -ifeq ($(shell $(SPHINXBUILD) 2> /dev/null; echo $$?), 127) -define MSG - - -The 'sphinx-build' command was not found. Make sure you have Sphinx -installed, then set the SPHINXBUILD environment variable to point -to the full path of the 'sphinx-build' executable. Alternatively you -may add the Sphinx directory to PATH. - -If you don't have Sphinx installed, grab it from -http://sphinx-doc.org/ -endef -$(error $(MSG)) -endif - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . -# the i18n builder cannot share the environment and doctrees with the others -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext - -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " texinfo to make Texinfo files" - @echo " info to make Texinfo files and run them through makeinfo" - @echo " gettext to make PO message catalogs" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " xml to make Docutils-native XML files" - @echo " pseudoxml to make pseudoxml-XML files for display purposes" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - -clean: - rm -rf $(BUILDDIR)/* - -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Automa.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Automa.qhc" - -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/Automa" - @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Automa" - @echo "# devhelp" - -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make' in that directory to run these through (pdf)latex" \ - "(use \`make latexpdf' here to do that automatically)." - -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through pdflatex..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -latexpdfja: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through platex and dvipdfmx..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text - @echo - @echo "Build finished. The text files are in $(BUILDDIR)/text." - -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man - @echo - @echo "Build finished. The manual pages are in $(BUILDDIR)/man." - -texinfo: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo - @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." - @echo "Run \`make' in that directory to run these through makeinfo" \ - "(use \`make info' here to do that automatically)." - -info: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo "Running Texinfo files through makeinfo..." - make -C $(BUILDDIR)/texinfo info - @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." - -gettext: - $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale - @echo - @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." - -xml: - $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml - @echo - @echo "Build finished. The XML files are in $(BUILDDIR)/xml." - -pseudoxml: - $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml - @echo - @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/helium-python/src/site/docs/_templates/helium/domainindex.html b/helium-python/src/site/docs/_templates/helium/domainindex.html deleted file mode 100644 index 7f99da6..0000000 --- a/helium-python/src/site/docs/_templates/helium/domainindex.html +++ /dev/null @@ -1,56 +0,0 @@ -{# - basic/domainindex.html - ~~~~~~~~~~~~~~~~~~~~~~ - - Template for domain indices (module index, ...). - - :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -#} -{%- extends "layout.html" %} -{% set title = indextitle %} -{% block extrahead %} -{{ super() }} -{% if not embedded and collapse_index %} - -{% endif %} -{% endblock %} -{% block body %} - - {%- set groupid = idgen() %} - -

    {{ indextitle }}

    - -
    - {%- for (letter, entries) in content %} - {{ letter }} - {%- if not loop.last %} | {% endif %} - {%- endfor %} -
    - - - {%- for letter, entries in content %} - - - {%- for (name, grouptype, page, anchor, extra, qualifier, description) - in entries %} - - - - {%- endfor %} - {%- endfor %} -
     
    - {{ letter }}
    {% if grouptype == 1 -%} - - {%- endif %}{% if grouptype == 2 %}   {% endif %} - {% if page %}{% endif -%} - {{ name|e }} - {%- if page %}{% endif %} - {%- if extra %} ({{ extra|e }}){% endif -%} - {% if qualifier %}{{ qualifier|e }}:{% endif %} - {{ description|e }}
    - -{% endblock %} diff --git a/helium-python/src/site/docs/_templates/helium/genindex.html b/helium-python/src/site/docs/_templates/helium/genindex.html deleted file mode 100644 index dd2c96d..0000000 --- a/helium-python/src/site/docs/_templates/helium/genindex.html +++ /dev/null @@ -1,77 +0,0 @@ -{# - basic/genindex.html - ~~~~~~~~~~~~~~~~~~~ - - Template for an "all-in-one" index. - - :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -#} -{% macro indexentries(firstname, links) %} -
    - {%- if links -%} - - {%- if links[0][0] %}{% endif -%} - {{ firstname|e }} - {%- if links[0][0] %}{% endif -%} - - - {%- for ismain, link in links[1:] -%} - , {% if ismain %}{% endif -%} - [{{ loop.index }}] - {%- if ismain %}{% endif -%} - - {%- endfor %} - {%- else %} - {{ firstname|e }} - {%- endif %} -
    -{% endmacro %} - -{%- extends "layout.html" %} -{% set title = _('Index') %} -{% block body %} - -

    {{ _('Index') }}

    - -
    - {% for key, dummy in genindexentries -%} - {{ key }} - {% if not loop.last %}| {% endif %} - {%- endfor %} -
    - -{%- for key, entries in genindexentries %} -

    {{ key }}

    - - {%- for column in entries|slice(2) if column %} - - {%- endfor %} -
    - {%- for entryname, (links, subitems) in column %} - {{ indexentries(entryname, links) }} - {%- if subitems %} -
    - {%- for subentryname, subentrylinks in subitems %} - {{ indexentries(subentryname, subentrylinks) }} - {%- endfor %} -
    - {%- endif -%} - {%- endfor %} -
    -{% endfor %} - -{% endblock %} - -{% block sidebarrel %} -{% if split_index %} -

    {{ _('Index') }}

    -

    {% for key, dummy in genindexentries -%} - {{ key }} - {% if not loop.last %}| {% endif %} - {%- endfor %}

    - -

    {{ _('Full index on one page') }}

    -{% endif %} - {{ super() }} -{% endblock %} diff --git a/helium-python/src/site/docs/_templates/helium/layout.html b/helium-python/src/site/docs/_templates/helium/layout.html deleted file mode 100644 index a7b68ec..0000000 --- a/helium-python/src/site/docs/_templates/helium/layout.html +++ /dev/null @@ -1,2 +0,0 @@ - - {% block body %} {% endblock %} diff --git a/helium-python/src/site/docs/_templates/helium/page.html b/helium-python/src/site/docs/_templates/helium/page.html deleted file mode 100644 index 185c6c8..0000000 --- a/helium-python/src/site/docs/_templates/helium/page.html +++ /dev/null @@ -1,13 +0,0 @@ -{# - basic/page.html - ~~~~~~~~~~~~~~~ - - Master template for simple pages. - - :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -#} -{%- extends "layout.html" %} -{% block body %} - {{ body }} -{% endblock %} diff --git a/helium-python/src/site/docs/_templates/helium/search.html b/helium-python/src/site/docs/_templates/helium/search.html deleted file mode 100644 index 011c239..0000000 --- a/helium-python/src/site/docs/_templates/helium/search.html +++ /dev/null @@ -1,56 +0,0 @@ -{# - basic/search.html - ~~~~~~~~~~~~~~~~~ - - Template for the search page. - - :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -#} -{%- extends "layout.html" %} -{% set title = _('Search') %} -{% set script_files = script_files + ['_static/searchtools.js'] %} -{% block extrahead %} - - {{ super() }} -{% endblock %} -{% block body %} -

    {{ _('Search') }}

    -
    - -

    - {% trans %}Please activate JavaScript to enable the search - functionality.{% endtrans %} -

    -
    -

    - {% trans %}From here you can search these documents. Enter your search - words into the box below and click "search". Note that the search - function will automatically search for all of the words. Pages - containing fewer words won't appear in the result list.{% endtrans %} -

    -
    - - - -
    - {% if search_performed %} -

    {{ _('Search Results') }}

    - {% if not search_results %} -

    {{ _('Your search did not match any results.') }}

    - {% endif %} - {% endif %} -
    - {% if search_results %} -
      - {% for href, caption, context in search_results %} -
    • {{ caption }} -
      {{ context|e }}
      -
    • - {% endfor %} -
    - {% endif %} -
    -{% endblock %} diff --git a/helium-python/src/site/docs/_templates/helium/theme.conf b/helium-python/src/site/docs/_templates/helium/theme.conf deleted file mode 100644 index f728373..0000000 --- a/helium-python/src/site/docs/_templates/helium/theme.conf +++ /dev/null @@ -1,8 +0,0 @@ -[theme] -inherit = none -stylesheet = basic.css -pygments_style = none - -[options] -nosidebar = false -sidebarwidth = 230 \ No newline at end of file diff --git a/helium-python/src/site/docs/conf.py b/helium-python/src/site/docs/conf.py deleted file mode 100644 index 48528e1..0000000 --- a/helium-python/src/site/docs/conf.py +++ /dev/null @@ -1,277 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Helium documentation build configuration file, created by -# sphinx-quickstart on Thu Mar 21 21:55:11 2013. -# -# This file is execfile()d with the current directory set to its containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -from os import getcwd, path -from datetime import date - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -proj_root = path.join(getcwd(), path.pardir, path.pardir, path.pardir) -#sys.path.insert(0, path.abspath(path.join(proj_root, 'src', 'main', 'python'))) -sys.path.insert(0, path.abspath( - path.join(proj_root, 'target', 'sources')) -) - -# -- General configuration ----------------------------------------------------- - -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc'] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -#source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = 'Helium' -copyright = str(date.today().year) + ', Michael Herrmann' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = '1' -# The full version, including alpha/beta/rc tags. -release = '1' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -language = 'en' - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -today_fmt = '%d/%m/%Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ['_build'] - -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -add_module_names = False - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -#keep_warnings = False - - -# -- Options for HTML output --------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = 'helium' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -#html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -html_theme_path = ["./_templates"] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None -html_add_permalinks = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = 'Heliumdoc' - - -# -- Options for LaTeX output -------------------------------------------------- - -latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', -'papersize': 'a4paper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', -'preamble': r'''\usepackage{lastpage} -\usepackage{fancyhdr} -\pagenumbering{arabic} -\cfoot{\textbf{\thepage\ of \pageref*{LastPage}}} -\pagestyle{fancy} -\fancyhead[L]{\textbf{Helium Python API Documentation}} -\fancyhead[R]{ -} -''', -'classoptions': ',oneside', -'babel': '\\usepackage[english]{babel}', -'releasename': '', -'tableofcontents': '', -'printindex': '\\printindex', -'fncychap': '\\usepackage[Bjarne]{fncychap}' -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass [howto/manual]). -latex_documents = [ - ('index', 'HeliumAPIDocumentation.tex', 'Helium Python API Documentation', - 'Michael Herrmann', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -latex_logo = 'helium.png' - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = True - -# If true, show page references after internal links. -latex_show_pagerefs = True - -#latex_docclass = 'manual' - -# If true, show URL addresses after external links. -#latex_show_urls = False - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -latex_domain_indices = False - -#latex_use_modindex = False - -latex_additional_files = [] - - -# -- Options for manual page output -------------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'helium', 'Helium Python API Documentation', - ['Michael Herrmann'], 1) -] - -# If true, show URL addresses after external links. -#man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------------ - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ('index', 'Helium', 'Helium Documentation', - 'Michael Herrmann', 'Helium', 'One line description of project.', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -#texinfo_appendices = [] - -# If false, no module index is generated. -#texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -#texinfo_no_detailmenu = False diff --git a/helium-python/src/site/docs/helium.png b/helium-python/src/site/docs/helium.png deleted file mode 100644 index 3dca141..0000000 Binary files a/helium-python/src/site/docs/helium.png and /dev/null differ diff --git a/helium-python/src/site/docs/index.rst b/helium-python/src/site/docs/index.rst deleted file mode 100644 index ed425cb..0000000 --- a/helium-python/src/site/docs/index.rst +++ /dev/null @@ -1,13 +0,0 @@ -.. Helium documentation master file, created by - sphinx-quickstart on Thu Mar 21 21:55:11 2013. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - -.. automodule:: helium.api - :show-inheritance: - :inherited-members: - :exclude-members: Point - :member-order: bysource - -.. autoclass:: Point - :members: x, y \ No newline at end of file diff --git a/helium-python/src/site/docs/make.bat b/helium-python/src/site/docs/make.bat deleted file mode 100644 index a24f454..0000000 --- a/helium-python/src/site/docs/make.bat +++ /dev/null @@ -1,246 +0,0 @@ -@ECHO OFF - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set BUILDDIR=../../../target/site/docs -set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . -set I18NSPHINXOPTS=%SPHINXOPTS% . -if NOT "%PAPER%" == "" ( - set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% - set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% -) - -if "%1" == "" goto help - -if "%1" == "help" ( - :help - echo.Please use `make ^` where ^ is one of - echo. html to make standalone HTML files - echo. dirhtml to make HTML files named index.html in directories - echo. singlehtml to make a single large HTML file - echo. pickle to make pickle files - echo. json to make JSON files - echo. htmlhelp to make HTML files and a HTML help project - echo. qthelp to make HTML files and a qthelp project - echo. devhelp to make HTML files and a Devhelp project - echo. epub to make an epub - echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter - echo. text to make text files - echo. man to make manual pages - echo. texinfo to make Texinfo files - echo. gettext to make PO message catalogs - echo. changes to make an overview over all changed/added/deprecated items - echo. xml to make Docutils-native XML files - echo. pseudoxml to make pseudoxml-XML files for display purposes - echo. linkcheck to check all external links for integrity - echo. doctest to run all doctests embedded in the documentation if enabled - goto end -) - -if "%1" == "clean" ( - for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i - del /q /s %BUILDDIR%\* - goto end -) - - -%SPHINXBUILD% 2> nul -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.http://sphinx-doc.org/ - exit /b 1 -) - -if "%1" == "html" ( - %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/html. - goto end -) - -if "%1" == "dirhtml" ( - %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. - goto end -) - -if "%1" == "singlehtml" ( - %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. - goto end -) - -if "%1" == "pickle" ( - %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the pickle files. - goto end -) - -if "%1" == "json" ( - %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the JSON files. - goto end -) - -if "%1" == "htmlhelp" ( - %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run HTML Help Workshop with the ^ -.hhp project file in %BUILDDIR%/htmlhelp. - goto end -) - -if "%1" == "qthelp" ( - %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run "qcollectiongenerator" with the ^ -.qhcp project file in %BUILDDIR%/qthelp, like this: - echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Automa.qhcp - echo.To view the help file: - echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Automa.ghc - goto end -) - -if "%1" == "devhelp" ( - %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. - goto end -) - -if "%1" == "epub" ( - %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The epub file is in %BUILDDIR%/epub. - goto end -) - -if "%1" == "latex" ( - if "%2" == "" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - ) else ( - %SPHINXBUILD% -b latex %2 %3=%4 %ALLSPHINXOPTS% %BUILDDIR%/latex - ) - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "latexpdf" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - cd %BUILDDIR%/latex - make all-pdf - cd %BUILDDIR%/.. - echo. - echo.Build finished; the PDF files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "latexpdfja" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - cd %BUILDDIR%/latex - make all-pdf-ja - cd %BUILDDIR%/.. - echo. - echo.Build finished; the PDF files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "text" ( - %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The text files are in %BUILDDIR%/text. - goto end -) - -if "%1" == "man" ( - %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The manual pages are in %BUILDDIR%/man. - goto end -) - -if "%1" == "texinfo" ( - %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. - goto end -) - -if "%1" == "gettext" ( - %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The message catalogs are in %BUILDDIR%/locale. - goto end -) - -if "%1" == "changes" ( - %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes - if errorlevel 1 exit /b 1 - echo. - echo.The overview file is in %BUILDDIR%/changes. - goto end -) - -if "%1" == "linkcheck" ( - %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck - if errorlevel 1 exit /b 1 - echo. - echo.Link check complete; look for any errors in the above output ^ -or in %BUILDDIR%/linkcheck/output.txt. - goto end -) - -if "%1" == "doctest" ( - %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest - if errorlevel 1 exit /b 1 - echo. - echo.Testing of doctests in the sources finished, look at the ^ -results in %BUILDDIR%/doctest/output.txt. - goto end -) - -if "%1" == "xml" ( - %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The XML files are in %BUILDDIR%/xml. - goto end -) - -if "%1" == "pseudoxml" ( - %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. - goto end -) - -:end diff --git a/helium-python/src/systemtest/python/helium_systemtest/__init__.py b/helium-python/src/systemtest/python/helium_systemtest/__init__.py deleted file mode 100644 index 74448aa..0000000 --- a/helium-python/src/systemtest/python/helium_systemtest/__init__.py +++ /dev/null @@ -1,47 +0,0 @@ -from helium_systemtest.environment import get_test_library -from subprocess import Popen, STDOUT -from tempfile import TemporaryFile -from unittest import TestCase - -import os - -def run_commands_in_python(commands, python_binary="python"): - return run_python_with_helium_library( - ['-c', ';'.join(commands)], python_binary=python_binary - ) - -def run_python_with_helium_library(args, python_binary="python", cwd=None): - return run_python( - args, python_binary=python_binary, cwd=cwd, - env={'PYTHONPATH': get_test_library()} - ) - -def run_python(args, python_binary="python", cwd=None, env=None): - """ - We would like to be able to use ApplicationConsoleTester or Popen with - stdout=PIPE here, however if we do that, we never receive any output. - This may be a Python bug. - To avoid this problem, we redirect stdout and stderr to a normal file. - """ - if env is None: - env = {} - with TemporaryFile('r+') as open_stdout_file: - full_env = os.environ.copy() - for key in env: - set_item_ignore_case(full_env, key, env[key]) - python = Popen( - [python_binary] + list(args), - stdout=open_stdout_file, stderr=STDOUT, cwd=cwd, env=full_env - ) - return_code = python.wait() - open_stdout_file.seek(0) - output = open_stdout_file.read() - return return_code, output - -def set_item_ignore_case(dictionary, key, value): - for actual_key in dictionary: - if actual_key.lower() == key.lower(): - dictionary[actual_key] = value - -class HeliumST(TestCase): - pass \ No newline at end of file diff --git a/helium-python/src/systemtest/python/helium_systemtest/environment.py b/helium-python/src/systemtest/python/helium_systemtest/environment.py deleted file mode 100644 index e851239..0000000 --- a/helium-python/src/systemtest/python/helium_systemtest/environment.py +++ /dev/null @@ -1,11 +0,0 @@ -from build_environment import get_target_path, get_proj_path -from os.path import pardir - -def get_test_library(): - return get_target_path('test-dist/heliumlib') - -def get_systemtest_resource(*rel_path): - return get_proj_path(pardir, 'src', 'systemtest', 'resources', *rel_path) - -def get_test_dist_dir(): - return get_target_path('test-dist') \ No newline at end of file diff --git a/helium-python/src/systemtest/python/helium_systemtest/systest_python.py b/helium-python/src/systemtest/python/helium_systemtest/systest_python.py deleted file mode 100644 index 3b4840a..0000000 --- a/helium-python/src/systemtest/python/helium_systemtest/systest_python.py +++ /dev/null @@ -1,10 +0,0 @@ -from helium_systemtest import run_commands_in_python, HeliumST - -class PythonST(HeliumST): - TEST_COMMANDS = [ - 'from helium.api import *', 'start_chrome(headless=True)', - 'kill_browser()', 'exit()' - ] - def test_python(self): - code, output = run_commands_in_python(self.TEST_COMMANDS) - self.assertEqual(0, code, msg=output) \ No newline at end of file diff --git a/helium-python/src/main/python/helium/__init__.py b/helium/__init__.py similarity index 100% rename from helium-python/src/main/python/helium/__init__.py rename to helium/__init__.py diff --git a/helium-python/src/main/python/helium/api.py b/helium/api.py similarity index 98% rename from helium-python/src/main/python/helium/api.py rename to helium/api.py index 49135c8..fd5695c 100644 --- a/helium-python/src/main/python/helium/api.py +++ b/helium/api.py @@ -24,7 +24,7 @@ 'get_driver', 'go_to', 'highlight', 'hover', 'kill_browser', 'press', 'refresh', 'rightclick', 'scroll_down', 'scroll_left', 'scroll_right', 'scroll_up', 'select', 'set_driver', 'start_chrome', 'start_firefox', - 'start_ie', 'switch_to', 'wait_until', 'write', + 'switch_to', 'wait_until', 'write', # Predicates: 'Alert', 'Button', 'CheckBox', 'ComboBox', 'Config', 'Image', 'Link', 'ListItem', 'Point', 'S', 'RadioButton', 'Text', 'TextField', 'Window', @@ -83,26 +83,6 @@ def start_chrome(url=None, headless=False): """ return _get_api_impl().start_chrome_impl(url, headless) -def start_ie(url=None): - """ - :param url: URL to open. - :type url: str - - (Windows only) Starts Internet Explorer, optionally opening the specified - URL. For instance:: - - start_ie() - start_ie("google.com") - - On shutdown of the Python interpreter, Helium cleans up all resources used - for controlling the browser (such as the IEDriverServer process), but does - not close the browser itself. If you want to terminate the browser at the - end of your script, use the following command:: - - kill_browser() - """ - return _get_api_impl().start_ie_impl(url) - def go_to(url): """ :param url: URL to open. @@ -454,7 +434,7 @@ def wait_until(condition_fn, timeout_secs=10, interval_secs=0.5): """ _get_api_impl().wait_until_impl(condition_fn, timeout_secs, interval_secs) -class Config(object): +class Config: """ This class contains Helium's run-time configuration. To modify Helium's behaviour, simply assign to the properties of this class. For instance:: @@ -487,7 +467,7 @@ class Config(object): ``.implicitly_wait(...)`` in conjunction with Helium. """ -class GUIElement(object): +class GUIElement: def __init__(self): self._driver = _get_api_impl().require_driver() self._args = [] diff --git a/helium-python/src/main/python/helium/api_impl/__init__.py b/helium/api_impl/__init__.py similarity index 96% rename from helium-python/src/main/python/helium/api_impl/__init__.py rename to helium/api_impl/__init__.py index 94926b6..017b77b 100644 --- a/helium-python/src/main/python/helium/api_impl/__init__.py +++ b/helium/api_impl/__init__.py @@ -7,7 +7,7 @@ from helium.util.os_ import make_executable from helium.util.system import is_windows from helium.util.xpath import lower, predicate, predicate_or -from inspect import getargspec, ismethod, isfunction +from inspect import getfullargspec, ismethod, isfunction from os import access, X_OK from os.path import exists from selenium.common.exceptions import UnexpectedAlertPresentException, \ @@ -18,8 +18,7 @@ from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support.ui import Select -from selenium.webdriver import Chrome, Ie, DesiredCapabilities, \ - ChromeOptions +from selenium.webdriver import Chrome, ChromeOptions from selenium.webdriver import Firefox from time import sleep, time @@ -69,13 +68,12 @@ def f_decorated(*args, **kwargs): ) return f_decorated -class APIImpl(object): +class APIImpl: DRIVER_REQUIRED_MESSAGE = \ "This operation requires a browser window. Please call one of " \ "the following functions first:\n" \ " * start_chrome()\n" \ " * start_firefox()\n" \ - " * start_ie()\n" \ " * set_driver(...)" def __init__(self, resource_locator): self.resource_locator = resource_locator @@ -121,7 +119,7 @@ def _get_chrome_options(self, headless): return result def _get_chrome_driver_kwargs(self, chrome_options): result = { - 'chrome_options': chrome_options + 'options': chrome_options } driver = self._locate_web_driver('chromedriver') if exists(driver): @@ -131,37 +129,14 @@ def _get_chrome_driver_kwargs(self, chrome_options): def _locate_web_driver(self, driver_name): if is_windows(): driver_name += '.exe' - return self.resource_locator.locate("webdrivers", driver_name) + return self.resource_locator.locate(driver_name) def _kill_service(self, service): - if service and hasattr(service, 'process') and service.process: - try: - service.process.kill() - except OSError as e: - if e.errno not in (NO_SUCH_PROCESS, ACCESS_DENIED): - raise - def start_ie_impl(self, url=None): - ie_driver_path = self._locate_web_driver("IEDriverServer") - capabilities = DesiredCapabilities.INTERNETEXPLORER.copy() - capabilities["ignoreZoomSetting"] = True - kwargs = { - 'capabilities': capabilities - } - if exists(ie_driver_path): - kwargs['executable_path'] = ie_driver_path + old = service.send_remote_shutdown_command + service.send_remote_shutdown_command = lambda: None try: - ie_browser = Ie(**kwargs) - except WebDriverException as e: - exc_to_raise = e - msg = e.msg - if 'Protected Mode settings are not the same for all zones.' in msg: - exc_to_raise = WebDriverException( - 'Error launching IE: Protected Mode settings are not the ' - 'same for all zones. Please follow these steps: ' - 'http://heliumhq.com/docs/internet_explorer#protected_mode' - ) - raise exc_to_raise - atexit.register(self._kill_service, ie_browser.iedriver) - return self._start(ie_browser, url) + service.stop() + finally: + service.send_remote_shutdown_command = old def _start(self, browser, url=None): self.set_driver_impl(browser) if url is not None: @@ -290,7 +265,7 @@ def _point_to_element_and_offset(self, point): )) offset = point - (element.location.left, element.location.top) if offset == (0, 0) and driver.is_firefox(): - # In some CSS settings (eg. inttest_point.html), the (0, 0) point of + # In some CSS settings (eg. test_point.html), the (0, 0) point of # buttons in Firefox is not clickable! The reason for this is that # Firefox styles buttons to not be perfect squares, but have an # indent in the corners. This workaround makes `click(btn.top_left)` @@ -382,12 +357,12 @@ def _refresh_with_alert(self): def wait_until_impl(self, condition_fn, timeout_secs=10, interval_secs=0.5): if ismethod(condition_fn): is_bound = condition_fn.__self__ is not None - args_spec = getargspec(condition_fn).args + args_spec = getfullargspec(condition_fn).args unfilled_args = len(args_spec) - (1 if is_bound else 0) else: if not isfunction(condition_fn): condition_fn = condition_fn.__call__ - args_spec = getargspec(condition_fn).args + args_spec = getfullargspec(condition_fn).args unfilled_args = len(args_spec) condition = \ condition_fn if unfilled_args else lambda driver: condition_fn() @@ -442,7 +417,7 @@ def require_driver(self): raise RuntimeError(self.DRIVER_REQUIRED_MESSAGE) return self.driver -class DragHelper(object): +class DragHelper: def __init__(self, api_impl): self.api_impl = api_impl self.is_html_5_drag = None @@ -523,7 +498,7 @@ def _complete_html_5_drag(self, on): def _execute_script(self, script, *args): return self.api_impl.require_driver().execute_script(script, *args) -class DragAndDropFile(object): +class DragAndDropFile: def __init__(self, driver, file_path): self.driver = driver self.file_path = file_path @@ -621,7 +596,7 @@ def end(self): ) self.file_input_element = None -class JavaScriptInterval(object): +class JavaScriptInterval: def __init__(self, driver, script, args, interval_msecs): self.driver = driver self.script = script @@ -644,7 +619,7 @@ def stop(self): ) self._interval_id = None -class GUIElementImpl(object): +class GUIElementImpl: def __init__(self, driver): self._bound_occurrence = None self._driver = driver @@ -772,7 +747,7 @@ def _handle_closed_window(self): else: window_has_been_closed = curr_window_handle not in window_handles if window_has_been_closed: - self._driver.switch_to_window(window_handles[0]) + self._driver.switch_to.window(window_handles[0]) def _get_search_regions_in_curr_frame(self): result = [] if self.below: @@ -1251,7 +1226,7 @@ def title(self): @property def handle(self): return self.first_occurrence.handle - class SeleniumWindow(object): + class SeleniumWindow: def __init__(self, driver, handle): self.driver = driver self.handle = handle diff --git a/helium/api_impl/application_context.py b/helium/api_impl/application_context.py new file mode 100644 index 0000000..aa1d088 --- /dev/null +++ b/helium/api_impl/application_context.py @@ -0,0 +1,28 @@ +from helium.api_impl import APIImpl +from helium.environment import ResourceLocator +from helium.util.system import get_canonical_os_name +from os.path import join, dirname + +import helium + +def get_application_context(): + global _APPLICATION_CONTEXT + if _APPLICATION_CONTEXT is None: + _APPLICATION_CONTEXT = ApplicationContext() + return _APPLICATION_CONTEXT + +_APPLICATION_CONTEXT = None + +class ApplicationContext: + def __init__(self): + self.api_impl = self.resource_locator = None + def APIImpl(self): + if self.api_impl is None: + self.api_impl = APIImpl(self.ResourceLocator()) + return self.api_impl + def ResourceLocator(self): + if self.resource_locator is None: + helium_pkg_dir = dirname(helium.__file__) + data_dir = join(helium_pkg_dir, 'data', get_canonical_os_name()) + self.resource_locator = ResourceLocator(data_dir) + return self.resource_locator \ No newline at end of file diff --git a/helium-python/src/main/python/helium/api_impl/match_type.py b/helium/api_impl/match_type.py similarity index 97% rename from helium-python/src/main/python/helium/api_impl/match_type.py rename to helium/api_impl/match_type.py index 9430cbb..c39627d 100644 --- a/helium-python/src/main/python/helium/api_impl/match_type.py +++ b/helium/api_impl/match_type.py @@ -1,6 +1,6 @@ from helium.util.xpath import lower, replace_nbsp -class MatchType(object): +class MatchType: def xpath(self, value, text): raise NotImplementedError() def text(self, value, text): diff --git a/src/main/resources/linux/webdrivers/chromedriver b/helium/data/linux/chromedriver similarity index 100% rename from src/main/resources/linux/webdrivers/chromedriver rename to helium/data/linux/chromedriver diff --git a/src/main/resources/linux/webdrivers/geckodriver b/helium/data/linux/geckodriver similarity index 100% rename from src/main/resources/linux/webdrivers/geckodriver rename to helium/data/linux/geckodriver diff --git a/src/main/resources/macosx/webdrivers/chromedriver b/helium/data/macosx/chromedriver similarity index 100% rename from src/main/resources/macosx/webdrivers/chromedriver rename to helium/data/macosx/chromedriver diff --git a/src/main/resources/macosx/webdrivers/geckodriver b/helium/data/macosx/geckodriver similarity index 100% rename from src/main/resources/macosx/webdrivers/geckodriver rename to helium/data/macosx/geckodriver diff --git a/src/main/resources/win/webdrivers/chromedriver.exe b/helium/data/win/chromedriver.exe similarity index 100% rename from src/main/resources/win/webdrivers/chromedriver.exe rename to helium/data/win/chromedriver.exe diff --git a/src/main/resources/win/webdrivers/geckodriver.exe b/helium/data/win/geckodriver.exe similarity index 100% rename from src/main/resources/win/webdrivers/geckodriver.exe rename to helium/data/win/geckodriver.exe diff --git a/helium-python/src/main/python/helium/environment.py b/helium/environment.py similarity index 52% rename from helium-python/src/main/python/helium/environment.py rename to helium/environment.py index 4546929..dd0933a 100644 --- a/helium-python/src/main/python/helium/environment.py +++ b/helium/environment.py @@ -1,13 +1,6 @@ -from base64 import b64decode -from os.path import normpath, exists, join, abspath +from os.path import normpath, exists, join -def is_development(): - source_code_subpath_b64 = \ - 'aGVsaXVtLXB5dGhvbi9zcmMvbWFpbi9weXRob24='.encode('ascii') - source_code_subpath = b64decode(source_code_subpath_b64).decode('ascii') - return normpath(source_code_subpath) in normpath(abspath(__file__)) - -class ResourceLocator(object): +class ResourceLocator: def __init__(self, *root_dirs): self.root_dirs = root_dirs def locate(self, *rel_path_components): diff --git a/helium-python/src/main/python/helium/selenium_wrappers.py b/helium/selenium_wrappers.py similarity index 98% rename from helium-python/src/main/python/helium/selenium_wrappers.py rename to helium/selenium_wrappers.py index f034c59..f98db41 100644 --- a/helium-python/src/main/python/helium/selenium_wrappers.py +++ b/helium/selenium_wrappers.py @@ -5,7 +5,7 @@ from urllib.error import URLError import sys -class Wrapper(object): +class Wrapper: def __init__(self, target): self.target = target def __getattr__(self, item): @@ -92,7 +92,7 @@ def f_decorated(self, *args, **kwargs): return f(self, *args, **kwargs) return f_decorated -class WebElementWrapper(object): +class WebElementWrapper: def __init__(self, target, frame_index=None): self.target = target self.frame_index = frame_index @@ -139,7 +139,7 @@ def unwrap(self): def __repr__(self): return '<%s>%s' % (self.tag_name, self.target.text, self.tag_name) -class FrameIterator(object): +class FrameIterator: def __init__(self, driver, start_frame=None): if start_frame is None: start_frame = [] diff --git a/helium-python/src/main/python/helium/util/__init__.py b/helium/util/__init__.py similarity index 100% rename from helium-python/src/main/python/helium/util/__init__.py rename to helium/util/__init__.py diff --git a/helium-python/src/main/python/helium/util/dictionary.py b/helium/util/dictionary.py similarity index 100% rename from helium-python/src/main/python/helium/util/dictionary.py rename to helium/util/dictionary.py diff --git a/helium-python/src/main/python/helium/util/geom.py b/helium/util/geom.py similarity index 99% rename from helium-python/src/main/python/helium/util/geom.py rename to helium/util/geom.py index 95fec15..68c10a2 100644 --- a/helium-python/src/main/python/helium/util/geom.py +++ b/helium/util/geom.py @@ -2,7 +2,7 @@ from collections import namedtuple from math import sqrt -class Rectangle(object): +class Rectangle: def __init__(self, left=0, top=0, width=0, height=0): self.left = left self.top = top @@ -175,7 +175,7 @@ def __div__(self, scalar): def __bool__(self): return bool(self.x) or bool(self.y) -class Direction(object): +class Direction: def __init__(self, unit_vector): self.unit_vector = unit_vector def iterate_points_starting_at(self, point, offsets): diff --git a/helium-python/src/main/python/helium/util/html.py b/helium/util/html.py similarity index 100% rename from helium-python/src/main/python/helium/util/html.py rename to helium/util/html.py diff --git a/helium-python/src/main/python/helium/util/inspect_.py b/helium/util/inspect_.py similarity index 95% rename from helium-python/src/main/python/helium/util/inspect_.py rename to helium/util/inspect_.py index c8e06dd..7d42c1b 100644 --- a/helium-python/src/main/python/helium/util/inspect_.py +++ b/helium/util/inspect_.py @@ -6,7 +6,7 @@ def repr_args(f, args=None, kwargs=None, repr_fn=repr): args = [] if kwargs is None: kwargs = {} - arg_names, _, _, defaults = inspect.getargspec(f) + arg_names, _, _, defaults = inspect.getfullargspec(f)[:4] if isbound(f): # Skip 'self' parameter: arg_names = arg_names[1:] diff --git a/helium-python/src/main/python/helium/util/lang.py b/helium/util/lang.py similarity index 94% rename from helium-python/src/main/python/helium/util/lang.py rename to helium/util/lang.py index d3d8802..b5be5f2 100644 --- a/helium-python/src/main/python/helium/util/lang.py +++ b/helium/util/lang.py @@ -1,4 +1,4 @@ -class TemporaryAttrValue(object): +class TemporaryAttrValue: def __init__(self, obj, attr, value): self.obj = obj self.attr = attr diff --git a/helium-python/src/main/python/helium/util/os_.py b/helium/util/os_.py similarity index 100% rename from helium-python/src/main/python/helium/util/os_.py rename to helium/util/os_.py diff --git a/helium-python/src/main/python/helium/util/path.py b/helium/util/path.py similarity index 100% rename from helium-python/src/main/python/helium/util/path.py rename to helium/util/path.py diff --git a/helium-python/src/main/python/helium/util/system.py b/helium/util/system.py similarity index 100% rename from helium-python/src/main/python/helium/util/system.py rename to helium/util/system.py diff --git a/helium-python/src/main/python/helium/util/xpath.py b/helium/util/xpath.py similarity index 100% rename from helium-python/src/main/python/helium/util/xpath.py rename to helium/util/xpath.py diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 886f7d8..0000000 --- a/pom.xml +++ /dev/null @@ -1,87 +0,0 @@ - - 4.0.0 - com.heliumhq - helium - 2.0.4-SNAPSHOT - pom - - - scm:git:ssh://git@bitbucket.org/mherrmann_at/helium.git - - https://bitbucket.org/mherrmann_at/helium/src - v1.6.7 - - - helium-java - helium-python - - - UTF-8 - 1.2.1 - 1.7 - 3.141.59 - 2.53.1.0 - 2.34.522940 - 0.6.1 - ${basedir}/../helium-python - ${heliumPythonHome}/src/main/python - ${heliumPythonHome}/src/unittest/python${path.separator}${heliumPythonMainPythonpath} - ${heliumPythonHome}/src/integrationtest/python${path.separator}${heliumPythonUnittestPythonpath} - - ${heliumPythonHome}/target/test-dist/heliumlib${path.separator}${heliumPythonInttestPythonpath} - - - ${heliumPythonHome}${path.separator}${heliumPythonHome}/src/systemtest/python${path.separator}${heliumPythonInttestPythonpath} - - ${basedir}${path.separator}${heliumPythonHome}${path.separator}${heliumPythonMainPythonpath} - ${basedir} - yyyy-MM-dd - - - ${project.artifactId}-${project.version} - - - org.apache.maven.plugins - maven-release-plugin - 2.3.2 - - v@{project.version} - deploy site-deploy - - - - org.apache.maven.scm - maven-scm-provider-gitexe - 1.8.1 - - - - - org.apache.maven.plugins - maven-install-plugin - 2.4 - - true - - - - org.apache.maven.plugins - maven-deploy-plugin - 2.7 - - true - - - - - org.apache.maven.plugins - maven-site-plugin - 3.2 - - true - true - - - - - \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..451593a --- /dev/null +++ b/setup.py @@ -0,0 +1,40 @@ +from setuptools import setup, find_packages + +setup( + name = 'helium', + version = '3.0.0', + author = 'Michael Herrmann', + author_email = 'michael+removethisifyouarehuman@herrmann.io', + description = 'Lighter browser automation based on Selenium.', + keywords = 'helium selenium browser automation', + url = 'https://github.com/mherrmann/helium', + python_requires='>=3', + packages = find_packages(exclude=['tests', 'tests.*']), + install_requires = [ + 'selenium==3.141.0' + ], + package_data = { + 'helium': ['data/**/*'] + }, + zip_safe = False, + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Topic :: Software Development :: Testing', + 'Topic :: Software Development :: Libraries', + 'Programming Language :: Python', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Operating System :: Microsoft :: Windows', + 'Operating System :: POSIX :: Linux', + 'Operating System :: MacOS :: MacOS X' + ], + test_suite='tests', + tests_require=[ + 'psutil==0.6.1', + "pywin32 >= 227;platform_system=='Windows'" + ] +) \ No newline at end of file diff --git a/src/integrationtest/resources/inttest_environment/file.txt b/src/integrationtest/resources/inttest_environment/file.txt deleted file mode 100644 index e69de29..0000000 diff --git a/src/integrationtest/resources/inttest_ie_ssl/ssl_certificate.pem b/src/integrationtest/resources/inttest_ie_ssl/ssl_certificate.pem deleted file mode 100644 index 2af4999..0000000 --- a/src/integrationtest/resources/inttest_ie_ssl/ssl_certificate.pem +++ /dev/null @@ -1,33 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIICXAIBAAKBgQDGsS5U4Gnzo05pIVcOB/7V9ZDyzVJ7EFScC9/yvFlpPQpPRYw+ -e1dSeevH0Oyl+bceCQD10FLRkJsS9jlrV4xj2rafE5UhzgD1ANfk/6zy7xizuxvN -v/nVR2405urRumNpOXZ8kiNGmQjcnEXvUXg9QFdFAho9lJ7zhLOWf5/KfQIDAQAB -AoGBALrp60AFbSa5tgXIS3DzrJPy00zWQoVqs22o7iAXd7U8qvov3uLYfSklcN0k -ebsZ01358mFMfNyQQJHx98o3LeUJaWJ3HDSAiYZPruk0tgV0Cgc0UXl0dWne5hSN -xHMsHeFTxtWeZPo87KbnYTo21yLSsPXTRlUV+E3UsR5HeLqBAkEA5l9EfmMerkvs -stGflV/uIYKI1XZE8N69KOdthf50a+shmlmGwYUSSFnmz2r0AMx/+qI6EQnFBWq/ -0arXXf8uNQJBANzLs/BnIWqOnqoNRs/eykNdnahwNgUbiHJv6Paeh3VuV2S/RxRS -1BbasXxdrJHj43/bggNeAH010FrLA484VCkCQDGaK6ZG81E2GdX62rCQAjcG4y2L -FJcEbphDFEr4mdquuwJ/6kr6uxAHA3J/peASKDAwA+6tOtXKwViEv3CGxE0CQGPw -UCIgjB+PLoIKQGMWlLapSRNUtx7Yt4oU3X3Dg8zDhQs1CRdJ5nXxxyRjwhjG7dKR -qOedRNtn4Ec4XQQWmwECQCwlnFhwVhnlVX5Dvskby4xGPheHaD+Y+SzhWQRqObbt -6K+3qS6iM1l+Zj6cSBMjR3HdrC/VldR8Pi9GatjWTVk= ------END RSA PRIVATE KEY----- ------BEGIN CERTIFICATE----- -MIIC+DCCAmGgAwIBAgIJAL8XD9ZXb3mwMA0GCSqGSIb3DQEBBQUAMIGUMQswCQYD -VQQGEwJQTDETMBEGA1UECAwKU29tZS1TdGF0ZTEPMA0GA1UEBwwGV2Fyc2F3MRkw -FwYDVQQKDBBCdWdGcmVlIFNvZnR3YXJlMRkwFwYDVQQDDBBNaWNoYWVsIEhlcnJt -YW5uMSkwJwYJKoZIhvcNAQkBFhphZG1pbkBidWdmcmVlLXNvZnR3YXJlLmNvbTAe -Fw0xMzEyMjYxMDU3MjNaFw0xNDAxMjUxMDU3MjNaMIGUMQswCQYDVQQGEwJQTDET -MBEGA1UECAwKU29tZS1TdGF0ZTEPMA0GA1UEBwwGV2Fyc2F3MRkwFwYDVQQKDBBC -dWdGcmVlIFNvZnR3YXJlMRkwFwYDVQQDDBBNaWNoYWVsIEhlcnJtYW5uMSkwJwYJ -KoZIhvcNAQkBFhphZG1pbkBidWdmcmVlLXNvZnR3YXJlLmNvbTCBnzANBgkqhkiG -9w0BAQEFAAOBjQAwgYkCgYEAxrEuVOBp86NOaSFXDgf+1fWQ8s1SexBUnAvf8rxZ -aT0KT0WMPntXUnnrx9Dspfm3HgkA9dBS0ZCbEvY5a1eMY9q2nxOVIc4A9QDX5P+s -8u8Ys7sbzb/51UduNObq0bpjaTl2fJIjRpkI3JxF71F4PUBXRQIaPZSe84Szln+f -yn0CAwEAAaNQME4wHQYDVR0OBBYEFK+CGM4B1sYHkkQ/Y8wEZ04w7KE8MB8GA1Ud -IwQYMBaAFK+CGM4B1sYHkkQ/Y8wEZ04w7KE8MAwGA1UdEwQFMAMBAf8wDQYJKoZI -hvcNAQEFBQADgYEASsjpBJAtZ4XxdzL4aHs4a4/Ql/9T0ZAeWPCLdfSNldng7pNS -j+HCODvCYVLPVHfXqLn1lPz5xEsA0Y1UgBefreJyzglNeLe860POOuJWUeRYwfPT -jqMyZbzP/U3hqy2d8gBTQ8PfmCqgWu9hH/Ji1nVbv/ajbIsU9DijLWCWmk8= ------END CERTIFICATE----- diff --git a/src/integrationtest/resources/inttest_shutil/file.txt b/src/integrationtest/resources/inttest_shutil/file.txt deleted file mode 100644 index c57eff5..0000000 --- a/src/integrationtest/resources/inttest_shutil/file.txt +++ /dev/null @@ -1 +0,0 @@ -Hello World! \ No newline at end of file diff --git a/src/integrationtest/resources/inttest_shutil/simple_zip.zip b/src/integrationtest/resources/inttest_shutil/simple_zip.zip deleted file mode 100644 index 7633ad8..0000000 Binary files a/src/integrationtest/resources/inttest_shutil/simple_zip.zip and /dev/null differ diff --git a/src/integrationtest/resources/inttest_shutil/zip_in_zip.zip b/src/integrationtest/resources/inttest_shutil/zip_in_zip.zip deleted file mode 100644 index 04f3b5d..0000000 Binary files a/src/integrationtest/resources/inttest_shutil/zip_in_zip.zip and /dev/null differ diff --git a/src/main/resources/win/webdrivers/IEDriverServer.exe b/src/main/resources/win/webdrivers/IEDriverServer.exe deleted file mode 100644 index 9f66efe..0000000 Binary files a/src/main/resources/win/webdrivers/IEDriverServer.exe and /dev/null differ diff --git a/helium-python/src/unittest/python/helium_unittest/__init__.py b/tests/__init__.py similarity index 100% rename from helium-python/src/unittest/python/helium_unittest/__init__.py rename to tests/__init__.py diff --git a/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/__init__.py b/tests/api/__init__.py similarity index 63% rename from helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/__init__.py rename to tests/api/__init__.py index 232af83..a9c0c07 100644 --- a/helium-python/src/integrationtest/python/helium_integrationtest/inttest_api/__init__.py +++ b/tests/api/__init__.py @@ -1,8 +1,7 @@ -from helium.api import start_chrome, start_firefox, start_ie, go_to, \ - set_driver, kill_browser -from helium_integrationtest.util import is_windows -from helium_integrationtest.environment import get_it_file_url -from unittest import TestCase, skipIf +from helium.api import start_chrome, start_firefox, go_to, set_driver, \ + kill_browser +from unittest import TestCase +from tests.api.util import get_data_file_url from time import time, sleep import os @@ -15,27 +14,20 @@ def test_browser_name(): else: return browser_name -def should_run(): - return is_windows() or not test_browser_name() == 'ie' - -@skipIf(not should_run(), 'IE on Windows only') class BrowserAT(TestCase): @classmethod def setUpClass(cls): - # We still need this check despite the @skipIf above because nose calls - # this method even if @skipIf returns True. - if should_run(): - if _TEST_BROWSER is None: - cls.driver = start_browser() - cls.started_browser = True - else: - cls.driver = _TEST_BROWSER - cls.started_browser = False - set_driver(cls.driver) + if _TEST_BROWSER is None: + cls.driver = start_browser() + cls.started_browser = True + else: + cls.driver = _TEST_BROWSER + cls.started_browser = False + set_driver(cls.driver) def setUp(self): go_to(self.get_url()) def get_url(self): - return get_it_file_url(self.get_page()) + return get_data_file_url(self.get_page()) def get_page(self): raise NotImplementedError() def read_result_from_browser(self, timeout_secs=3): @@ -74,7 +66,6 @@ def start_browser(url=None): return _TEST_BROWSERS[browser_name](url, **kwargs) _TEST_BROWSERS = { - 'ie': start_ie, 'firefox': start_firefox, 'chrome': start_chrome } \ No newline at end of file diff --git a/src/integrationtest/resources/default.css b/tests/api/data/default.css similarity index 100% rename from src/integrationtest/resources/default.css rename to tests/api/data/default.css diff --git a/src/integrationtest/resources/img/dolphin.jpg b/tests/api/data/img/dolphin.jpg similarity index 100% rename from src/integrationtest/resources/img/dolphin.jpg rename to tests/api/data/img/dolphin.jpg diff --git a/src/integrationtest/resources/img/link_with_title.png b/tests/api/data/img/link_with_title.png similarity index 100% rename from src/integrationtest/resources/img/link_with_title.png rename to tests/api/data/img/link_with_title.png diff --git a/src/integrationtest/resources/js/jquery-ui.min.js b/tests/api/data/js/jquery-ui.min.js similarity index 100% rename from src/integrationtest/resources/js/jquery-ui.min.js rename to tests/api/data/js/jquery-ui.min.js diff --git a/src/integrationtest/resources/js/jquery.min.js b/tests/api/data/js/jquery.min.js similarity index 100% rename from src/integrationtest/resources/js/jquery.min.js rename to tests/api/data/js/jquery.min.js diff --git a/src/integrationtest/resources/js/jquery.ui-contextmenu.js b/tests/api/data/js/jquery.ui-contextmenu.js similarity index 100% rename from src/integrationtest/resources/js/jquery.ui-contextmenu.js rename to tests/api/data/js/jquery.ui-contextmenu.js diff --git a/src/integrationtest/resources/js/util.js b/tests/api/data/js/util.js similarity index 100% rename from src/integrationtest/resources/js/util.js rename to tests/api/data/js/util.js diff --git a/src/integrationtest/resources/inttest_alert.html b/tests/api/data/test_alert.html similarity index 96% rename from src/integrationtest/resources/inttest_alert.html rename to tests/api/data/test_alert.html index 21bf431..19f5a52 100644 --- a/src/integrationtest/resources/inttest_alert.html +++ b/tests/api/data/test_alert.html @@ -1,7 +1,7 @@ - inttest_alert + test_alert