Search in sources :

Example 16 with SeleniumGridConnector

use of com.seleniumtests.connectors.selenium.SeleniumGridConnector in project seleniumRobot by bhecquet.

the class TestSeleniumRobotGridConnector method testIsGridActiveWithGridInError.

@Test(groups = { "ut" })
public void testIsGridActiveWithGridInError() throws ClientProtocolException, IOException {
    SeleniumGridConnector connector = new SeleniumRobotGridConnector(SERVER_URL);
    createServerMock("GET", SeleniumGridConnector.CONSOLE_SERVLET, 500, "some text");
    Assert.assertFalse(connector.isGridActive());
}
Also used : SeleniumRobotGridConnector(com.seleniumtests.connectors.selenium.SeleniumRobotGridConnector) SeleniumGridConnector(com.seleniumtests.connectors.selenium.SeleniumGridConnector) Test(org.testng.annotations.Test) ConnectorsTest(com.seleniumtests.ConnectorsTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 17 with SeleniumGridConnector

use of com.seleniumtests.connectors.selenium.SeleniumGridConnector in project seleniumRobot by bhecquet.

the class TestSeleniumTestContext3 method testGridConnectionWithoutUrl.

/**
 * grid test but missing url. An error should be raised
 *
 * @param testNGCtx
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws NoSuchFieldException
 * @throws SecurityException
 * @throws NoSuchMethodException
 */
@Test(groups = "ut", expectedExceptions = ConfigurationException.class)
public void testGridConnectionWithoutUrl(final ITestContext testNGCtx) throws NoSuchMethodException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    SeleniumGridConnector gridConnector = spy(new SeleniumGridConnector("http://localhost:4444/hub/wd"));
    // grid connector is in use only if session Id exists
    doReturn(new SessionId("1234")).when(gridConnector).getSessionId();
    PowerMockito.mockStatic(SeleniumGridConnectorFactory.class);
    PowerMockito.when(SeleniumGridConnectorFactory.getInstances(Arrays.asList("http://localhost:4444/hub/wd"))).thenReturn(Arrays.asList(gridConnector));
    try {
        System.setProperty(SeleniumTestsContext.RUN_MODE, "grid");
        System.setProperty(SeleniumTestsContext.WEB_DRIVER_GRID, "");
        ITestResult testResult = GenericTest.generateResult(testNGCtx, getClass());
        initThreadContext(testNGCtx, "myTest", testResult);
    } finally {
        System.clearProperty(SeleniumTestsContext.RUN_MODE);
        System.clearProperty(SeleniumTestsContext.WEB_DRIVER_GRID);
    }
}
Also used : ITestResult(org.testng.ITestResult) SeleniumGridConnector(com.seleniumtests.connectors.selenium.SeleniumGridConnector) SessionId(org.openqa.selenium.remote.SessionId) Test(org.testng.annotations.Test) ConnectorsTest(com.seleniumtests.ConnectorsTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) XmlTest(org.testng.xml.XmlTest) GenericTest(com.seleniumtests.GenericTest)

Example 18 with SeleniumGridConnector

use of com.seleniumtests.connectors.selenium.SeleniumGridConnector in project seleniumRobot by bhecquet.

the class Uft method prepareArguments.

/**
 * Prepare list of arguments
 *
 * @param load    if true, add '/load'
 * @param execute if true, add '/execute'
 * @return
 */
public List<String> prepareArguments(boolean load, boolean execute) {
    // copy uft.vbs to disk
    String vbsPath;
    try {
        File tempFile = Files.createTempDirectory("uft").resolve(SCRIPT_NAME).toFile();
        tempFile.deleteOnExit();
        FileUtils.copyInputStreamToFile(Thread.currentThread().getContextClassLoader().getResourceAsStream("uft/" + SCRIPT_NAME), tempFile);
        vbsPath = tempFile.getAbsolutePath();
    } catch (IOException e) {
        throw new ScenarioException("Error sending UFT script to grid node: " + e.getMessage());
    }
    if (SeleniumTestsContextManager.getThreadContext().getRunMode() == DriverMode.GRID) {
        SeleniumGridConnector gridConnector = SeleniumTestsContextManager.getThreadContext().getSeleniumGridConnector();
        if (gridConnector != null) {
            vbsPath = Paths.get(gridConnector.uploadFileToNode(vbsPath, true), SCRIPT_NAME).toString();
        } else {
            throw new ScenarioException("No grid connector present, executing UFT script needs a browser to be initialized");
        }
    }
    List<String> args = new ArrayList<>();
    args.add(vbsPath);
    args.add(scriptPath);
    if (execute) {
        args.add("/execute");
        parameters.forEach((key, value) -> args.add(String.format("\"%s=%s\"", key, value)));
    }
    if (load) {
        if (almServer != null && almUser != null && almPassword != null && almDomain != null && almProject != null) {
            args.add("/server:" + almServer);
            args.add("/user:" + almUser);
            args.add("/password:" + almPassword);
            args.add("/domain:" + almDomain);
            args.add("/project:" + almProject);
        } else if (almServer != null || almUser != null || almPassword != null || almDomain != null || almProject != null) {
            throw new ConfigurationException("All valuers pour ALM connection must be provided: server, user, password, domain and project");
        }
        args.add("/load");
        if (killUftOnStartup) {
            args.add("/clean");
        }
    }
    return args;
}
Also used : ConfigurationException(com.seleniumtests.customexception.ConfigurationException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) File(java.io.File) SeleniumGridConnector(com.seleniumtests.connectors.selenium.SeleniumGridConnector) ScenarioException(com.seleniumtests.customexception.ScenarioException)

Example 19 with SeleniumGridConnector

use of com.seleniumtests.connectors.selenium.SeleniumGridConnector in project seleniumRobot by bhecquet.

the class SeleniumGridDriverFactory method getDriver.

/**
 * Connect to grid using RemoteWebDriver
 * As we may have several grid available, takes the first one where driver is created
 *
 * Several waits are defined
 * By default, we wait 30 mins for a node to be found. For this, we loop through all available hubs
 * In case we do not find any node after 30 mins, we fail and increment a fail counter
 * This fail counter is reset every time we find a node
 * If this counter reaches 3, then we don't even try to get a driver
 *
 * @param url
 * @param capability
 * @return
 */
private WebDriver getDriver(MutableCapabilities capability) {
    driver = null;
    Clock clock = Clock.systemUTC();
    Instant end = clock.instant().plusSeconds(instanceRetryTimeout);
    Exception currentException = null;
    if (webDriverConfig.getRunOnSameNode() != null && webDriverConfig.getSeleniumGridConnector() == null) {
        throw new ScenarioException("Cannot create a driver on the same node as an other driver if no previous driver has been created through grid");
    }
    // issue #311: stop after 3 consecutive failure getting nodes
    int noDriverCount = counter.get();
    if (noDriverCount > 2) {
        throw new SkipException("Skipping as the 3 previous tests could not get any matching node. Check your test configuration and grid setup");
    }
    while (end.isAfter(clock.instant())) {
        for (SeleniumGridConnector gridConnector : gridConnectors) {
            // if grid is not active, try the next one
            if (!gridConnector.isGridActive()) {
                logger.warn(String.format("grid %s is not active, looking for the next one", gridConnector.getHubUrl().toString()));
                continue;
            }
            // if we are launching a second driver for the same test, do it on the same hub
            if (webDriverConfig.getRunOnSameNode() != null && webDriverConfig.getSeleniumGridConnector() != gridConnector) {
                continue;
            }
            try {
                driver = new RemoteWebDriver(gridConnector.getHubUrl(), capability);
                activeGridConnector = gridConnector;
                break;
            } catch (WebDriverException e) {
                logger.warn(String.format("Error creating driver on hub %s: %s", gridConnector.getHubUrl().toString(), e.getMessage()));
                currentException = e;
            }
        }
        // do not wait more
        if (driver != null) {
            break;
        }
        if (currentException != null) {
            WaitHelper.waitForSeconds(5);
        } else {
            // we are here if no grid connector is available
            logger.warn("No grid available, wait 30 secs and retry");
            // for test only, reduce wiat
            if (instanceRetryTimeout > 30) {
                WaitHelper.waitForSeconds(30);
            } else {
                WaitHelper.waitForSeconds(1);
            }
        }
    }
    if (driver == null) {
        noDriverCount = counter.getAndIncrement();
        throw new SeleniumGridNodeNotAvailable(String.format("Cannot create driver on grid, it may be fully used [%d times]", noDriverCount), currentException);
    } else {
        // reset counter as we got a driver
        counter.set(0);
    }
    return driver;
}
Also used : RemoteWebDriver(org.openqa.selenium.remote.RemoteWebDriver) Instant(java.time.Instant) SkipException(org.testng.SkipException) Clock(java.time.Clock) SeleniumGridNodeNotAvailable(com.seleniumtests.customexception.SeleniumGridNodeNotAvailable) SeleniumGridConnector(com.seleniumtests.connectors.selenium.SeleniumGridConnector) SkipException(org.testng.SkipException) WebDriverException(org.openqa.selenium.WebDriverException) ConfigurationException(com.seleniumtests.customexception.ConfigurationException) SessionNotCreatedException(org.openqa.selenium.SessionNotCreatedException) ScenarioException(com.seleniumtests.customexception.ScenarioException) ScenarioException(com.seleniumtests.customexception.ScenarioException) WebDriverException(org.openqa.selenium.WebDriverException)

Example 20 with SeleniumGridConnector

use of com.seleniumtests.connectors.selenium.SeleniumGridConnector in project seleniumRobot by bhecquet.

the class TestSeleniumGridConnector method testGetSessionInformationFromGrid.

@Test(groups = { "ut" })
public void testGetSessionInformationFromGrid() throws UnsupportedOperationException, IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, UnirestException {
    createServerMock("GET", "/grid/api/testsession/", 200, "{'proxyId': 'http://localhost:43210'}");
    // prepare app file
    ((DesiredCapabilities) capabilities).setCapability(CapabilityType.BROWSER_NAME, "firefox");
    ((DesiredCapabilities) capabilities).setCapability(CapabilityType.BROWSER_VERSION, "50.0");
    // prepare response
    InputStream is = new StringInputStream("{'proxyId':'proxy//node:0'}");
    when(entity.getContent()).thenReturn(is);
    SeleniumGridConnector connector = spy(new SeleniumGridConnector(SERVER_URL));
    Logger logger = spy(SeleniumRobotLogger.getLogger(SeleniumGridConnector.class));
    Field loggerField = SeleniumGridConnector.class.getDeclaredField("logger");
    loggerField.setAccessible(true);
    loggerField.set(connector, logger);
    connector.getSessionInformationFromGrid(driver);
    verify(logger).info("Brower firefox (50.0) created in 0.0 secs on node localhost [http://localhost:4321] with session 0");
    // check sessionId is set when test is started
    verify(connector).setSessionId(any(SessionId.class));
    Assert.assertEquals(connector.getNodeUrl(), "http://localhost:43210");
}
Also used : Field(java.lang.reflect.Field) StringInputStream(org.apache.tools.ant.filters.StringInputStream) StringInputStream(org.apache.tools.ant.filters.StringInputStream) InputStream(java.io.InputStream) DesiredCapabilities(org.openqa.selenium.remote.DesiredCapabilities) Logger(org.apache.log4j.Logger) SeleniumRobotLogger(com.seleniumtests.util.logging.SeleniumRobotLogger) SeleniumGridConnector(com.seleniumtests.connectors.selenium.SeleniumGridConnector) SessionId(org.openqa.selenium.remote.SessionId) Test(org.testng.annotations.Test) ConnectorsTest(com.seleniumtests.ConnectorsTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

SeleniumGridConnector (com.seleniumtests.connectors.selenium.SeleniumGridConnector)32 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)28 Test (org.testng.annotations.Test)28 SeleniumRobotGridConnector (com.seleniumtests.connectors.selenium.SeleniumRobotGridConnector)19 ConnectorsTest (com.seleniumtests.ConnectorsTest)18 GenericTest (com.seleniumtests.GenericTest)13 XmlTest (org.testng.xml.XmlTest)13 MockitoTest (com.seleniumtests.MockitoTest)10 SessionId (org.openqa.selenium.remote.SessionId)10 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)7 ScenarioException (com.seleniumtests.customexception.ScenarioException)3 DesiredCapabilities (org.openqa.selenium.remote.DesiredCapabilities)3 ITestResult (org.testng.ITestResult)3 ConfigurationException (com.seleniumtests.customexception.ConfigurationException)2 InputStream (java.io.InputStream)2 StringInputStream (org.apache.tools.ant.filters.StringInputStream)2 SessionNotCreatedException (org.openqa.selenium.SessionNotCreatedException)2 RemoteWebDriver (org.openqa.selenium.remote.RemoteWebDriver)2 SeleniumGridNodeNotAvailable (com.seleniumtests.customexception.SeleniumGridNodeNotAvailable)1 SeleniumRobotLogger (com.seleniumtests.util.logging.SeleniumRobotLogger)1