com.codeborne.selenide.WebDriverRunner Java Examples

The following examples show how to use com.codeborne.selenide.WebDriverRunner. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TableImpl.java    From masquerade with Apache License 2.0 7 votes vote down vote up
@Override
public ElementsCollection selectRows(By rowBy) {
    this.shouldBe(VISIBLE)
            .shouldBe(LOADED)
            .shouldBe(ENABLED);

    ElementsCollection rows = getRows(rowBy);

    WebDriver webDriver = WebDriverRunner.getWebDriver();
    Actions action = new Actions(webDriver);

    for (SelenideElement row : rows) {
        row.shouldNotHave(selectedClass);

        Keys controlKey = getControlKey();

        action.keyDown(controlKey)
                .click(row.getWrappedElement())
                .keyUp(controlKey)
                .build()
                .perform();
    }

    return rows;
}
 
Example #2
Source File: TableImpl.java    From masquerade with Apache License 2.0 6 votes vote down vote up
@Override
public SelenideElement deselectRow(By rowBy) {
    this.shouldBe(VISIBLE)
            .shouldBe(ENABLED);

    SelenideElement row = getRow(rowBy)
            .shouldBe(visible)
            .shouldHave(selectedClass);

    WebDriver webDriver = WebDriverRunner.getWebDriver();
    Actions action = new Actions(webDriver);

    Keys controlKey = getControlKey();

    action.keyDown(controlKey)
            .click(row.getWrappedElement())
            .keyUp(controlKey)
            .build()
            .perform();

    return row;
}
 
Example #3
Source File: JustTestLahConfiguration.java    From justtestlah with Apache License 2.0 6 votes vote down vote up
/** Set the correct {@link org.openqa.selenium.WebDriver}. */
public synchronized void initWebDriver() {
  // for web and local testing the Selenide default behavior is sufficient
  System.setProperty("browser", browser);
  // not thread-safe!
  Configuration.headless = headless;
  Platform platform = getPlatform();
  if (platform.equals(Platform.ANDROID)) {
    WebDriverRunner.setWebDriver(webDriverBuilder.getAndroidDriver());
  } else if (platform.equals(Platform.IOS)) {
    WebDriverRunner.setWebDriver(webDriverBuilder.getIOsDriver());
  } else if (platform.equals(Platform.WEB)) {
    if (cloudProvider.equals("browserstack")) {
      WebDriverRunner.setWebDriver(webDriverBuilder.getWebDriver());
      open(baseUrl);
    } else {
      open(baseUrl);
      WebDriverRunner.setWebDriver(webDriverBuilder.getWebDriver());
    }
  }
  WebDriver driver = WebDriverRunner.getWebDriver();
  if (driver instanceof TakesScreenshot) {
    ocr.setDriver(driver);
  }
}
 
Example #4
Source File: DataGridImpl.java    From masquerade with Apache License 2.0 6 votes vote down vote up
/**
 * @return control key depending on operating system
 */
protected Keys getControlKey() {
    Keys controlKey = Keys.CONTROL;

    WebDriver webDriver = WebDriverRunner.getWebDriver();
    if (webDriver instanceof JavascriptExecutor) {
        // check if working on MacOS
        Object result = ((JavascriptExecutor) webDriver)
                .executeScript("return window.navigator.platform");

        if (result instanceof String) {
            String platform = (String) result;

            if (MAC_OS_PLATFORM.equals(platform)) {
                controlKey = Keys.COMMAND;
            }
        }
    }

    return controlKey;
}
 
Example #5
Source File: BasePage.java    From justtestlah with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the given image within the current screen.
 *
 * @param imageName image to check for
 * @param threshold matching threshold
 * @return {@link Match}
 */
public Match findImage(String imageName, double threshold) {
  WebDriver driver = WebDriverRunner.getWebDriver();
  if (driver instanceof TakesScreenshot) {
    File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    if (templateMatcher instanceof AppiumTemplateMatcher) {
      if (driver instanceof HasSettings) {
        LOG.info("Setting image matching threshold to {}", threshold);
        HasSettings settingsDriver = ((HasSettings) driver);
        settingsDriver.setSetting(Setting.IMAGE_MATCH_THRESHOLD, threshold);
      }
      ((AppiumTemplateMatcher) templateMatcher).setDriver(WebDriverRunner.getWebDriver());
    }
    return templateMatcher.match(
        screenshotFile.getAbsolutePath(), ImageUtils.getFullPath(imageName), threshold);
  } else {
    throw new UnsupportedOperationException(
        "This operation is not supported for the current WebDriver: "
            + driver.getClass().getSimpleName()
            + ".");
  }
}
 
Example #6
Source File: DataGridImpl.java    From masquerade with Apache License 2.0 6 votes vote down vote up
@Override
public ElementsCollection selectRows(By rowBy) {
    this.shouldBe(VISIBLE)
            .shouldBe(LOADED)
            .shouldBe(ENABLED);

    ElementsCollection rows = getRows(rowBy);

    WebDriver webDriver = WebDriverRunner.getWebDriver();
    Actions action = new Actions(webDriver);

    for (SelenideElement row : rows) {
        row.shouldNotHave(selectedClass);

        Keys controlKey = getControlKey();

        action.keyDown(controlKey)
                .click(row.getWrappedElement())
                .keyUp(controlKey)
                .build()
                .perform();
    }

    return rows;
}
 
Example #7
Source File: DataGridImpl.java    From masquerade with Apache License 2.0 6 votes vote down vote up
@Override
public SelenideElement deselectRow(By rowBy) {
    this.shouldBe(VISIBLE)
            .shouldBe(ENABLED);

    SelenideElement row = getRow(rowBy)
            .shouldBe(visible)
            .shouldHave(selectedClass);

    WebDriver webDriver = WebDriverRunner.getWebDriver();
    Actions action = new Actions(webDriver);

    Keys controlKey = getControlKey();

    action.keyDown(controlKey)
            .click(row.getWrappedElement())
            .keyUp(controlKey)
            .build()
            .perform();

    return row;
}
 
Example #8
Source File: TableImpl.java    From masquerade with Apache License 2.0 6 votes vote down vote up
/**
 * @return control key depending on operating system
 */
protected Keys getControlKey() {
    Keys controlKey = Keys.CONTROL;

    WebDriver webDriver = WebDriverRunner.getWebDriver();
    if (webDriver instanceof JavascriptExecutor) {
        // check if working on MacOS
        Object result = ((JavascriptExecutor) webDriver)
                .executeScript("return window.navigator.platform");

        if (result instanceof String) {
            String platform = (String) result;

            if (MAC_OS_PLATFORM.equals(platform)) {
                controlKey = Keys.COMMAND;
            }
        }
    }

    return controlKey;
}
 
Example #9
Source File: LambdaBaseTest.java    From lambda-selenium with MIT License 5 votes vote down vote up
@BeforeClass
public static void baseTestBeforeClass() {
    Configuration.browser = "chrome";
    Configuration.reopenBrowserOnFail = false;

    if (EnvironmentDetector.inLambda()) {
        WebDriverRunner.webdriverContainer = new LambdaWebDriverThreadLocalContainer();
    }
}
 
Example #10
Source File: ManageBrowserStepsTest.java    From akita with Apache License 2.0 5 votes vote down vote up
@Test
@Disabled
void setWindowSizeSimple() {
    Dimension expectedDimension = new Dimension(800, 600);
    dmbs.setBrowserWindowSize(800, 600);
    Dimension actualDimension = WebDriverRunner.getWebDriver().manage().window().getSize();
    assertThat(expectedDimension, equalTo(actualDimension));
}
 
Example #11
Source File: ApplitoolsHooks.java    From justtestlah with Apache License 2.0 5 votes vote down vote up
/**
 * Initialise Applitools.
 *
 * @param scenario Cucumber scenario
 */
@Override
public void before(Scenario scenario) {
  if (configuration.isEyesEnabled()) {
    LOG.info("Initializing Eyes");
    eyes.open(
        WebDriverRunner.getAndCheckWebDriver(),
        configuration.getApplicationName(),
        configuration.getPlatform().name());
  }
}
 
Example #12
Source File: Galen.java    From justtestlah with Apache License 2.0 5 votes vote down vote up
public void checkLayout(String spec, LocatorMap locators) {
  LOG.info("Checking layout {}", spec);
  URL specURL = this.getClass().getClassLoader().getResource(spec);
  if (specURL == null) {
    LOG.warn(
        String.format("Missing Galen specification %s. Skipping checks for this page.", specURL));
    return;
  }
  String specPath = specURL.getPath();
  if (injectLocators) {
    specPath = uiLocatorInjector.injectUILocators(specPath, locators);
  }
  String title = "Check layout " + specPath;
  LayoutReport layoutReport;
  try {
    layoutReport =
        com.galenframework.api.Galen.checkLayout(
            WebDriverRunner.getWebDriver(),
            specPath,
            Collections.singletonList(configuration.getPlatform().name()));
    GalenTestInfo test = GalenTestInfo.fromString(this.getClass().getSimpleName());
    test.getReport().layout(layoutReport, title);
    galenTests.add(test);
  } catch (IOException exception) {
    LOG.warn("Error checking layout", exception);
  }
}
 
Example #13
Source File: AllureSelenide.java    From allure-java with Apache License 2.0 5 votes vote down vote up
private static Optional<byte[]> getPageSourceBytes() {
    try {
        return WebDriverRunner.hasWebDriverStarted()
            ? Optional.of(WebDriverRunner.getWebDriver().getPageSource().getBytes(UTF_8))
            : Optional.empty();
    } catch (WebDriverException e) {
        LOGGER.warn("Could not get page source", e);
        return Optional.empty();
    }
}
 
Example #14
Source File: LambdaBaseTest.java    From lambda-selenium with MIT License 5 votes vote down vote up
protected void screenshot(String description) {
    if (EnvironmentDetector.inLambda()) {
        LambdaTestHandler.addAttachment(description + ".png",
                ((TakesScreenshot) WebDriverRunner.getWebDriver())
                        .getScreenshotAs(OutputType.BYTES));
    } else {
        Selenide.screenshot(description);
    }
}
 
Example #15
Source File: AllureSelenide.java    From allure-java with Apache License 2.0 5 votes vote down vote up
private static Optional<byte[]> getScreenshotBytes() {
    try {
        return WebDriverRunner.hasWebDriverStarted()
            ? Optional.of(((TakesScreenshot) WebDriverRunner.getWebDriver()).getScreenshotAs(OutputType.BYTES))
            : Optional.empty();
    } catch (WebDriverException e) {
        LOGGER.warn("Could not get screen shot", e);
        return Optional.empty();
    }
}
 
Example #16
Source File: AllureSelenideTest.java    From allure-java with Apache License 2.0 5 votes vote down vote up
@AllureFeatures.Attachments
@Test
void shouldSaveScreenshotsOnFail() {
    final ChromeDriver wdMock = mock(ChromeDriver.class);
    WebDriverRunner.setWebDriver(wdMock);
    doReturn("hello".getBytes(StandardCharsets.UTF_8))
            .when(wdMock).getScreenshotAs(OutputType.BYTES);

    final AllureResults results = runWithinTestContext(() -> {
        final AllureSelenide selenide = new AllureSelenide()
                .savePageSource(false)
                .screenshots(true);
        SelenideLogger.addListener(UUID.randomUUID().toString(), selenide);
        final SelenideLog log = SelenideLogger.beginStep(
                "dummy source",
                "dummyMethod()",
                "param1",
                "param2"
        );
        SelenideLogger.commitStep(log, new Exception("something went wrong"));
    });

    final StepResult selenideStep = extractStepFromResults(results);
    assertThat(selenideStep.getAttachments())
            .hasSize(1);

    final Attachment attachment = selenideStep.getAttachments().iterator().next();
    assertThat(results.getAttachments())
            .containsKey(attachment.getSource());

    final String attachmentContent = new String(
            results.getAttachments().get(attachment.getSource()),
            StandardCharsets.UTF_8
    );

    assertThat(attachmentContent)
            .isEqualTo("hello");
}
 
Example #17
Source File: BaseTest.java    From vaadin-app-layout with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void init() {
    Optional<String> version = WebDriverManager.chromedriver().getVersions().stream().max(String::compareTo);
    if (version.isPresent()) {
        WebDriverManager.chromedriver().version(version.get()).setup();
        driver = new ChromeDriver();
        WebDriverRunner.setWebDriver(driver);
    } else {
        throw new IllegalStateException("No Chromedriver found!");
    }
}
 
Example #18
Source File: AllureSelenideTest.java    From allure-java with Apache License 2.0 5 votes vote down vote up
@AllureFeatures.Attachments
@Test
void shouldSavePageSourceOnFail() {
    final ChromeDriver wdMock = mock(ChromeDriver.class);
    WebDriverRunner.setWebDriver(wdMock);
    doReturn("dummy-page-source")
            .when(wdMock).getPageSource();

    final AllureResults results = runWithinTestContext(() -> {
        final AllureSelenide selenide = new AllureSelenide()
                .screenshots(false)
                .savePageSource(true);
        SelenideLogger.addListener(UUID.randomUUID().toString(), selenide);
        final SelenideLog log = SelenideLogger.beginStep(
                "dummy source",
                "dummyMethod()",
                "param1",
                "param2"
        );
        SelenideLogger.commitStep(log, new Exception("something went wrong"));
    });

    final StepResult selenideStep = extractStepFromResults(results);
    assertThat(selenideStep.getAttachments())
            .hasSize(1);

    final Attachment attachment = selenideStep.getAttachments().iterator().next();
    assertThat(results.getAttachments())
            .containsKey(attachment.getSource());

    final String attachmentContent = new String(
            results.getAttachments().get(attachment.getSource()),
            StandardCharsets.UTF_8
    );

    assertThat(attachmentContent)
            .isEqualTo("dummy-page-source");
}
 
Example #19
Source File: ElementStepsTest.java    From akita with Apache License 2.0 5 votes vote down vote up
@Test
void findElementPositive() {
    elis.findElement("LINK");
    sleep(500);
    assertThat(WebDriverRunner.getWebDriver().getCurrentUrl(),
            equalTo(akitaScenario.getVar("RedirectionPage")));
}
 
Example #20
Source File: SelenideAddons.java    From neodymium-library with MIT License 5 votes vote down vote up
/**
 * Returns an supplier that will return all results if any. It will return elements that are found by parentSelector
 * and have a result for subElementSelector. It does NOT return the subelements, it is meant to be a workaround for
 * poor CSS where the parent is only recognizable by looking at its children, but we don't need the children.
 * Important, this is meant to be lazy so don't call get() when you setup a field or so, only when you really need
 * the element. It reselects all the time!
 *
 * @param parentSelector
 *            The selector that is used to find subElementSelector
 * @param subElementSelector
 *            The selector that is shall have the element selected by parentSelector
 * @return an supplier that will return the result later
 */
public static Supplier<ElementsCollection> parentsBySubElement(final By parentSelector, final By subElementSelector)
{
    return new Supplier<ElementsCollection>()
    {
        @Override
        public ElementsCollection get()
        {
            List<SelenideElement> list = $$(parentSelector).stream().filter(e -> {
                return e.$(subElementSelector).exists();
            }).collect(Collectors.toList());
            return new ElementsCollection(new WebElementsCollectionWrapper(WebDriverRunner.driver(), list));
        };
    };
}
 
Example #21
Source File: SelenideAddons.java    From neodymium-library with MIT License 5 votes vote down vote up
/**
 * Returns an supplier that will return all results if any. It will return elements that are found by parentSelector
 * and have a no result for subElementSelector. It does NOT return the subelements, it is meant to be a workaround
 * for poor CSS where the parent is only recognizable by looking at its children, but we don't need the children.
 * Important, this is meant to be lazy so don't call get() when you setup a field or so, only when you really need
 * the element. It reselects all the time!
 *
 * @param parentSelector
 *            The selector that is used to find subElementSelector
 * @param subElementSelector
 *            The selector that shall not be contained by the parentSelector
 * @return an supplier that will return the result later
 */
public static Supplier<ElementsCollection> parentsWithoutSubElement(final By parentSelector, final By subElementSelector)
{
    return new Supplier<ElementsCollection>()
    {
        @Override
        public ElementsCollection get()
        {
            List<SelenideElement> list = $$(parentSelector).stream().filter(e -> {
                return !e.$(subElementSelector).exists();
            }).collect(Collectors.toList());
            return new ElementsCollection(new WebElementsCollectionWrapper(WebDriverRunner.driver(), list));
        };
    };
}
 
Example #22
Source File: SelenideAddons.java    From neodymium-library with MIT License 5 votes vote down vote up
/**
 * The missing wrapper to generate screenshots and save the html source code if a jUnit assertion fails.<br>
 * <br>
 * <p>
 * Sample: Assert that page title is correct and dump the page source and a screenshot in case of a mismatch
 * <code> wrapAssertionError(()-&gt;{Assert.assertEquals("MyPageTitle", Selenide.title());});</code>
 * </p>
 * 
 * @param runnable
 *            The lambda containing an assertion
 */
public static void wrapAssertionError(final Runnable runnable)
{
    try
    {
        runnable.run();
    }
    catch (AssertionError e)
    {
        Driver driver = WebDriverRunner.driver();
        String message = "No error message provided by the Assertion.";
        if (StringUtils.isNotBlank(e.getMessage()))
        {
            message = e.getMessage();
        }
        else
        {
            AssertionError wrapper = new AssertionError(message, e.getCause());
            wrapper.setStackTrace(e.getStackTrace());
            e = wrapper;
        }
        SelenideLogger.commitStep(new SelenideLog("Assertion error", message), e);
        if (!driver.config().assertionMode().equals(AssertionMode.SOFT))
        {
            throw UIAssertionError.wrap(driver, e, 0);
        }
    }
}
 
Example #23
Source File: AbstractTest.java    From selenium-grid-extensions with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
    readGridHostPort();

    DesiredCapabilities desiredCapabilities = firefoxWithSikuli();
    URL url = new URL(String.format("http://%s:%d/wd/hub", host, port));

    RemoteWebDriver remoteWebDriver = new RemoteWebDriver(url, desiredCapabilities);
    WebDriverRunner.setWebDriver(remoteWebDriver);
}
 
Example #24
Source File: InitialSetupHooks.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * По завершению теста удаляет все куки и закрывает веб-браузер
 */

@After(order = 10)
public void closeWebDriver() {
    if (hasWebDriverStarted()) {
        getWebDriver().manage().deleteAllCookies();
        WebDriverRunner.closeWebDriver();
    }
}
 
Example #25
Source File: DownloadTestWithDockerAndProxy.java    From testcontainers with MIT License 5 votes vote down vote up
@Before
public void setUp() {
    Configuration.proxyHost = "host.testcontainers.internal";
    Configuration.proxyPort = proxyPort;
    Configuration.proxyEnabled = true;
    Configuration.fileDownload = PROXY;

    proxyServer = new SelenideProxyServer(new StaticConfig(), null);
    proxyServer.start();

    RemoteWebDriver driver = chrome.getWebDriver();
    WebDriverRunner.setWebDriver(driver, proxyServer);
}
 
Example #26
Source File: DownloadTestWithDockerAndProxy.java    From testcontainers with MIT License 5 votes vote down vote up
@After
public void tearDown() {
    proxyServer.shutdown();
    WebDriverRunner.closeWebDriver();
    Configuration.fileDownload = HTTPGET;
    Configuration.proxyEnabled = false;
    Configuration.proxyHost = null;
    Configuration.proxyPort = 0;
}
 
Example #27
Source File: ManageBrowserCookieStepsTest.java    From akita with Apache License 2.0 5 votes vote down vote up
@BeforeAll
static void setup() {
    dmbs = new ManageBrowserSteps();
    akitaScenario = AkitaScenario.getInstance();
    Scenario scenario = new StubScenario();
    akitaScenario.setEnvironment(new AkitaEnvironment(scenario));
    wpis = new WebPageInteractionSteps();
    webDriver = mock(WebDriver.class);
    WebDriverRunner.setWebDriver(webDriver);
    when(webDriver.manage()).thenReturn(mock(WebDriver.Options.class));
}
 
Example #28
Source File: ElementStepsTest.java    From akita with Apache License 2.0 5 votes vote down vote up
@Test
void findElementMixedLanguagePartialEnPositive() {
    elis.findElement("EnGliSh");
    sleep(500);
    assertThat(WebDriverRunner.getWebDriver().findElement(By.name("mixedButton"))
            .isEnabled(), is(false));
}
 
Example #29
Source File: ElementStepsTest.java    From akita with Apache License 2.0 5 votes vote down vote up
@Test
void findElementMixedLanguagePartialRuPositive() {
    elis.findElement("РуСсКий.");
    sleep(500);
    assertThat(WebDriverRunner.getWebDriver().findElement(By.name("mixedButton"))
            .isEnabled(), is(false));
}
 
Example #30
Source File: ElementStepsTest.java    From akita with Apache License 2.0 5 votes vote down vote up
@Test
void findElementMixedLanguagePositive() {
    elis.findElement("EnGliSh? РуСсКий.");
    sleep(500);
    assertThat(WebDriverRunner.getWebDriver().findElement(By.name("mixedButton"))
            .isEnabled(), is(false));
}