org.testcontainers.containers.BrowserWebDriverContainer Java Examples

The following examples show how to use org.testcontainers.containers.BrowserWebDriverContainer. 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: ScreenshotOnFailureExtension.java    From blog-tutorials with MIT License 6 votes vote down vote up
@Override
public void afterEach(ExtensionContext extensionContext) throws Exception {
  if (extensionContext.getExecutionException().isPresent()) {
    Object testInstance = extensionContext.getRequiredTestInstance();
    Field containerField = testInstance.getClass().getDeclaredField("container");
    containerField.setAccessible(true);
    BrowserWebDriverContainer browserContainer = (BrowserWebDriverContainer) containerField.get(testInstance);
    byte[] screenshot = browserContainer.getWebDriver().getScreenshotAs(OutputType.BYTES);

    try {
      Path path = Paths
        .get("target/selenium-screenshots")
        .resolve(String.format("%s-%s-%s.png",
          LocalDateTime.now(),
          extensionContext.getRequiredTestClass().getName(),
          extensionContext.getRequiredTestMethod().getName()));

      Files.createDirectories(path.getParent());
      Files.write(path, screenshot);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
 
Example #2
Source File: ChromeRecordingWebDriverContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void recordingTestThatShouldBeRecordedButNotPersisted() {
    try (
        // withRecordingFileFactory {
        BrowserWebDriverContainer chrome = new BrowserWebDriverContainer()
            // }
            .withCapabilities(new ChromeOptions())
            // withRecordingFileFactory {
            .withRecordingFileFactory(new CustomRecordingFileFactory())
        // }
    ) {
        chrome.start();

        doSimpleExplore(chrome);
    }
}
 
Example #3
Source File: BaseWebDriverContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
protected void doSimpleWebdriverTest(BrowserWebDriverContainer rule) {
    RemoteWebDriver driver = setupDriverFromRule(rule);
    System.out.println("Selenium remote URL is: " + rule.getSeleniumAddress());
    System.out.println("VNC URL is: " + rule.getVncAddress());

    driver.get("http://www.google.com");
    WebElement search = driver.findElement(By.name("q"));
    search.sendKeys("testcontainers");
    search.submit();

    List<WebElement> results = new WebDriverWait(driver, 15)
        .until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("#search h3")));

    assertTrue("the word 'testcontainers' appears in search results",
        results.stream()
            .anyMatch(el -> el.getText().contains("testcontainers")));
}
 
Example #4
Source File: BrowserWebDriverContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void createContainerWithoutShmVolume() {
    try (
        BrowserWebDriverContainer webDriverContainer = new BrowserWebDriverContainer<>()
            .withSharedMemorySize(512 * FileUtils.ONE_MB)
            .withCapabilities(new FirefoxOptions())
    ) {
        webDriverContainer.start();

        assertEquals("Shared memory size is configured",
            512 * FileUtils.ONE_MB,
            webDriverContainer.getShmSize());

        assertEquals("No shm mounts present", emptyList(), shmVolumes(webDriverContainer));
    }
}
 
Example #5
Source File: BrowserWebDriverContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void honorPresetNoProxyEnvironment() {
    try (
        BrowserWebDriverContainer chromeWithNoProxySet = (BrowserWebDriverContainer) new BrowserWebDriverContainer()
            .withCapabilities(new ChromeOptions())
            .withEnv(NO_PROXY_KEY, NO_PROXY_VALUE)
    ) {
        chromeWithNoProxySet.start();

        Object noProxy = chromeWithNoProxySet.getEnvMap().get(NO_PROXY_KEY);
        assertEquals("no_proxy should be preserved by the container rule", NO_PROXY_VALUE, noProxy);
    }
}
 
Example #6
Source File: BrowserWebDriverContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void provideDefaultNoProxyEnvironmentIfNotSet() {
    try (
        BrowserWebDriverContainer chromeWithoutNoProxySet = new BrowserWebDriverContainer()
            .withCapabilities(new ChromeOptions())

    ) {
        chromeWithoutNoProxySet.start();

        Object noProxy = chromeWithoutNoProxySet.getEnvMap().get(NO_PROXY_KEY);
        assertEquals("no_proxy should be set to default if not already present", "localhost", noProxy);
    }
}
 
Example #7
Source File: BrowserWebDriverContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void createContainerWithShmVolume() {
    try (
        BrowserWebDriverContainer webDriverContainer = new BrowserWebDriverContainer()
            .withCapabilities(new FirefoxOptions())
    ) {
        webDriverContainer.start();

        final List<InspectContainerResponse.Mount> shmVolumes = shmVolumes(webDriverContainer);

        assertEquals("Only one shm mount present", 1, shmVolumes.size());
        assertEquals("Shm mount source is correct", "/dev/shm", shmVolumes.get(0).getSource());
        assertEquals("Shm mount mode is correct", "rw", shmVolumes.get(0).getMode());
    }
}
 
Example #8
Source File: BrowserWebDriverContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private List<InspectContainerResponse.Mount> shmVolumes(final BrowserWebDriverContainer container) {
    return container.getContainerInfo().getMounts()
        .stream()
        // destination path is always /dev/shm
        .filter(m -> m.getDestination().getPath().equals("/dev/shm"))
        .collect(toList());
}
 
Example #9
Source File: BytecoderUnitTestRunner.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private static synchronized BrowserWebDriverContainer initializeSeleniumContainer() {

        if (SELENIUMCONTAINER == null) {
            java.util.logging.Logger.getLogger("org.openqa.selenium").setLevel(Level.OFF);

            final ChromeOptions theOptions = new ChromeOptions().setHeadless(true);
            theOptions.addArguments("--js-flags=experimental-wasm-eh");
            theOptions.addArguments("--enable-experimental-wasm-eh");
            theOptions.addArguments("disable-infobars"); // disabling infobars
            theOptions.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
            theOptions.addArguments("--no-sandbox"); // Bypass OS security model
            theOptions.setExperimentalOption("useAutomationExtension", false);
            final LoggingPreferences theLoggingPreferences = new LoggingPreferences();
            theLoggingPreferences.enable(LogType.BROWSER, Level.ALL);
            theOptions.setCapability(CapabilityType.LOGGING_PREFS, theLoggingPreferences);
            theOptions.setCapability("goog:loggingPrefs", theLoggingPreferences);

            Testcontainers.exposeHostPorts(getTestWebServerPort());

            SELENIUMCONTAINER = new BrowserWebDriverContainer()
                    .withCapabilities(theOptions)
                    .withRecordingMode(BrowserWebDriverContainer.VncRecordingMode.SKIP, new File("."));
            SELENIUMCONTAINER.start();

            Runtime.getRuntime().addShutdownHook(new Thread(() -> SELENIUMCONTAINER.stop()));
        }
        return SELENIUMCONTAINER;
    }
 
Example #10
Source File: BaseWebDriverContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
protected static void doSimpleExplore(BrowserWebDriverContainer rule) {
    RemoteWebDriver driver = setupDriverFromRule(rule);
    driver.get("http://en.wikipedia.org/wiki/Randomness");

    // Oh! The irony!
    assertTrue("Randomness' description has the word 'pattern'", driver.findElementByPartialLinkText("pattern").isDisplayed());
}
 
Example #11
Source File: Selenium3xTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void testAdditionalStartupString() {
    try (BrowserWebDriverContainer chrome = new BrowserWebDriverContainer("selenium/standalone-chrome-debug:" + tag)
            .withCapabilities(new ChromeOptions())) {
        chrome.start();
    }
}
 
Example #12
Source File: ChromeRecordingWebDriverContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void recordingTestThatShouldBeRecordedAndRetained() {
    File target = vncRecordingDirectory.getRoot();
    try (
        // recordAll {
        // To do this, simply add extra parameters to the rule constructor:
        BrowserWebDriverContainer chrome = new BrowserWebDriverContainer()
            .withCapabilities(new ChromeOptions())
            .withRecordingMode(RECORD_ALL, target)
            // }
            .withRecordingFileFactory(new DefaultRecordingFileFactory())
    ) {
        chrome.start();

        doSimpleExplore(chrome);
        chrome.afterTest(new TestDescription() {
            @Override
            public String getTestId() {
                return getFilesystemFriendlyName();
            }

            @Override
            public String getFilesystemFriendlyName() {
                return "ChromeThatRecordsAllTests-recordingTestThatShouldBeRecordedAndRetained";
            }
        }, Optional.empty());

        String[] files = vncRecordingDirectory.getRoot().list(new PatternFilenameFilter("PASSED-.*\\.flv"));
        assertEquals("Recorded file not found", 1, files.length);
    }
}
 
Example #13
Source File: SeleniumChromeExtension.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
private void deployChrome() {
    LOGGER.info("Deploying chrome browser");
    if (!TestUtils.isExternalRegistry()) {
        Testcontainers.exposeHostPorts(TestUtils.getRegistryPort());
    }
    chrome = new BrowserWebDriverContainer()
            .withCapabilities(new ChromeOptions());
    chrome.start();
    SeleniumProvider.getInstance().setupDriver(chrome.getWebDriver());
    SeleniumProvider.getInstance().setUiUrl(TestUtils.getRegistryUIUrl().replace("localhost", "host.testcontainers.internal"));
    deployed = true;
}
 
Example #14
Source File: ChromeRecordingWebDriverContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void recordingTestThatShouldBeRecordedAndRetained() {
    File target = vncRecordingDirectory.getRoot();
    try (
        // recordFailing {
        // or if you only want videos for test failures:
        BrowserWebDriverContainer chrome = new BrowserWebDriverContainer()
            .withCapabilities(new ChromeOptions())
            .withRecordingMode(RECORD_FAILING, target)
            // }
            .withRecordingFileFactory(new DefaultRecordingFileFactory())
    ) {
        chrome.start();

        doSimpleExplore(chrome);
        chrome.afterTest(new TestDescription() {
            @Override
            public String getTestId() {
                return getFilesystemFriendlyName();
            }

            @Override
            public String getFilesystemFriendlyName() {
                return "ChromeThatRecordsFailingTests-recordingTestThatShouldBeRecordedAndRetained";
            }
        }, Optional.of(new RuntimeException("Force writing of video file.")));

        String[] files = vncRecordingDirectory.getRoot().list(new PatternFilenameFilter("FAILED-.*\\.flv"));
        assertEquals("Recorded file not found", 1, files.length);
    }

}
 
Example #15
Source File: FlakyContainerCreationTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test @Ignore
public void testCreationOfManyContainers() {
    for (int i = 0; i < 50; i++) {
        BrowserWebDriverContainer container = new BrowserWebDriverContainer()
                .withCapabilities(new ChromeOptions())
                .withRecordingMode(BrowserWebDriverContainer.VncRecordingMode.RECORD_FAILING, new File("build"));

        container.start();
        RemoteWebDriver driver = container.getWebDriver();

        driver.get("http://www.google.com");

        container.stop();
    }
}
 
Example #16
Source File: BytecoderUnitTestRunner.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
private void testJSBackendFrameworkMethod(final FrameworkMethod aFrameworkMethod, final RunNotifier aRunNotifier, final TestOption aTestOption) {
    if ("".equals(System.getProperty("BYTECODER_DISABLE_JSTESTS", ""))) {
        final TestClass testClass = getTestClass();
        final Description theDescription = Description.createTestDescription(testClass.getJavaClass(), aFrameworkMethod.getName() + " " + aTestOption.toDescription());
        aRunNotifier.fireTestStarted(theDescription);

        try {
            final CompileTarget theCompileTarget = new CompileTarget(testClass.getJavaClass().getClassLoader(), CompileTarget.BackendType.js);

            final BytecodeMethodSignature theSignature = theCompileTarget.toMethodSignature(aFrameworkMethod.getMethod());

            final BytecodeObjectTypeRef theTestClass = new BytecodeObjectTypeRef(testClass.getName());
            final BytecodeMethodSignature theTestClassConstructorSignature = new BytecodeMethodSignature(BytecodePrimitiveTypeRef.VOID, new BytecodeTypeRef[0]);

            final StringWriter theStrWriter = new StringWriter();
            final PrintWriter theCodeWriter = new PrintWriter(theStrWriter);

            final CompileOptions theOptions = new CompileOptions(LOGGER, true, KnownOptimizer.ALL, aTestOption.isExceptionsEnabled(), "bytecoder", 512, 512, aTestOption.isMinify(), aTestOption.isPreferStackifier(), Allocator.linear, additionalClassesToLink, additionalResources, null, aTestOption.isEscapeAnalysisEnabled());
            final JSCompileResult result = (JSCompileResult) theCompileTarget.compile(theOptions, testClass.getJavaClass(), aFrameworkMethod.getName(), theSignature);
            final CompileResult.StringContent content = (CompileResult.StringContent) result.getContent()[0];

            theCodeWriter.println(content.asString());

            final String theFilename = result.getMinifier().toClassName(theTestClass) + "." + result.getMinifier().toMethodName(aFrameworkMethod.getName(), theSignature) + "_" + aTestOption.toFilePrefix() + ".html";

            theCodeWriter.println();

            theCodeWriter.println("console.log(\"Starting test\");");
            theCodeWriter.println("bytecoder.bootstrap();");
            theCodeWriter.println("var theTestInstance = " + result.getMinifier().toClassName(theTestClass) + "." +  result.getMinifier().toSymbol("__runtimeclass") + "." + result.getMinifier().toMethodName("$newInstance", theTestClassConstructorSignature) + "();");
            theCodeWriter.println("try {");
            theCodeWriter.println("     theTestInstance." + result.getMinifier().toMethodName(aFrameworkMethod.getName(), theSignature) + "();");
            theCodeWriter.println("     console.log(\"Test finished OK\");");
            theCodeWriter.println("} catch (e) {");
            theCodeWriter.println("     if (e.exception) {");
            theCodeWriter.println("         console.log(\"Test finished with exception. Message = \" + bytecoder.toJSString(e.exception.message));");
            theCodeWriter.println("     } else {");
            theCodeWriter.println("         console.log(\"Test finished with exception.\");");
            theCodeWriter.println("     }");
            theCodeWriter.println("     console.log(e.stack);");
            theCodeWriter.println("}");

            theCodeWriter.flush();

            final File theWorkingDirectory = new File(".");

            initializeTestWebServer();

            final BrowserWebDriverContainer theContainer = initializeSeleniumContainer();

            final File theMavenTargetDir = new File(theWorkingDirectory, "target");
            final File theGeneratedFilesDir = new File(theMavenTargetDir, "bytecoderjs");
            theGeneratedFilesDir.mkdirs();

            // Copy additional resources
            for (final CompileResult.Content c : result.getContent()) {
                if (c instanceof CompileResult.URLContent) {
                    try (final FileOutputStream fos = new FileOutputStream(new File(theGeneratedFilesDir, c.getFileName()))) {
                        c.writeTo(fos);
                    }
                }
            }

            final File theGeneratedFile = new File(theGeneratedFilesDir, theFilename);
            final PrintWriter theWriter = new PrintWriter(theGeneratedFile);
            theWriter.println("<html><body><script>");
            theWriter.println(theStrWriter.toString());
            theWriter.println("</script></body></html>");
            theWriter.flush();
            theWriter.close();

            initializeWebRoot(theGeneratedFile.getParentFile());

            final URL theTestURL = getTestFileUrl(theGeneratedFile);
            final WebDriver theDriver = theContainer.getWebDriver();
            theDriver.get(theTestURL.toString());

            final List<LogEntry> theAll = theDriver.manage().logs().get(LogType.BROWSER).getAll();
            if (1 > theAll.size()) {
                aRunNotifier.fireTestFailure(new Failure(theDescription, new RuntimeException("No console output from browser")));
            }
            for (final LogEntry theEntry : theAll) {
                LOGGER.info(theEntry.getMessage());
            }
            final LogEntry theLast = theAll.get(theAll.size() - 1);

            if (!theLast.getMessage().contains("Test finished OK")) {
                aRunNotifier.fireTestFailure(new Failure(theDescription, new RuntimeException("Test did not succeed! Got : " + theLast.getMessage())));
            }
        } catch (final Exception e) {
            aRunNotifier.fireTestFailure(new Failure(theDescription, e));
        } finally {
            aRunNotifier.fireTestFinished(theDescription);
        }
    }
}
 
Example #17
Source File: BaseWebDriverContainerTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
protected void assertBrowserNameIs(BrowserWebDriverContainer rule, String expectedName) {
    RemoteWebDriver driver = setupDriverFromRule(rule);
    String actual = driver.getCapabilities().getBrowserName();
    assertTrue(format("actual browser name is %s", actual),
        actual.equals(expectedName));
}
 
Example #18
Source File: BaseWebDriverContainerTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
@NotNull
private static RemoteWebDriver setupDriverFromRule(BrowserWebDriverContainer rule) {
    RemoteWebDriver driver = rule.getWebDriver();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    return driver;
}