Example usage for org.openqa.selenium.remote SessionId SessionId

List of usage examples for org.openqa.selenium.remote SessionId SessionId

Introduction

In this page you can find the example usage for org.openqa.selenium.remote SessionId SessionId.

Prototype

public SessionId(String opaqueKey) 

Source Link

Usage

From source file:com.machinepublishers.jbrowserdriver.JBrowserDriver.java

License:Apache License

/**
 * Use {@link Settings#builder()} ...build() to create settings to pass to this constructor.
 * //from  w ww.jav a2 s. co  m
 * @param settings
 */
public JBrowserDriver(final Settings settings) {
    initWorkThread();
    synchronized (locks) {
        locks.add(lock);
    }
    File tmpDir = null;
    try {
        tmpDir = Files.createTempDirectory("jbd_tmp_").toFile();
    } catch (Throwable t) {
        Util.handleException(t);
    }
    this.tmpDir = tmpDir;
    this.shutdownHook = new FileRemover(tmpDir);
    Runtime.getRuntime().addShutdownHook(shutdownHook);

    final Job job = new Job(settings, configuredPortGroup);
    synchronized (waiting) {
        waiting.add(job);
        waiting.notifyAll();
    }
    synchronized (job) {
        while (configuredPortGroup.get() == null) {
            try {
                job.wait();
            } catch (InterruptedException e) {
            }
        }
    }
    SessionId sessionIdTmp = null;
    if (!settings.customClasspath()) {
        synchronized (firstLaunch) {
            if (firstLaunch.compareAndSet(true, false)) {
                initClasspath();
                classpathArgs.set(classpathUnpackedArgs);
                sessionIdTmp = new SessionId(launchProcess(settings, configuredPortGroup.get()));
                if (actualPortGroup.get() == null) {
                    classpathArgs.set(classpathSimpleArgs);
                }
            }
        }
    }
    if (actualPortGroup.get() == null) {
        sessionIdTmp = new SessionId(launchProcess(settings, configuredPortGroup.get()));
    }
    sessionId = sessionIdTmp;
    if (actualPortGroup.get() == null) {
        endProcess();
        Util.handleException(new IllegalStateException("Could not launch browser."));
    }
    HeartbeatRemote heartbeatTmp = null;
    JBrowserDriverRemote instanceTmp = null;
    try {
        synchronized (lock.validated()) {
            Registry registry = LocateRegistry.getRegistry(settings.host(), (int) actualPortGroup.get().child,
                    new SocketFactory(settings.host(), actualPortGroup.get(), locks));
            heartbeatTmp = (HeartbeatRemote) registry.lookup("HeartbeatRemote");
            instanceTmp = (JBrowserDriverRemote) registry.lookup("JBrowserDriverRemote");
            instanceTmp.setUp(settings);
        }
    } catch (Throwable t) {
        Util.handleException(t);
    }
    final HeartbeatRemote heartbeat = heartbeatTmp;
    heartbeatThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                if (processEnded.get()) {
                    return;
                }
                try {
                    heartbeat.heartbeat();
                } catch (RemoteException e) {
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
            }
        }
    });
    heartbeatThread.setName("Heartbeat");
    heartbeatThread.start();
    remote = instanceTmp;
    LogsRemote logsRemote = null;
    try {
        synchronized (lock.validated()) {
            logsRemote = remote.logs();
        }
    } catch (Throwable t) {
        Util.handleException(t);
    }
    logs = new Logs(logsRemote, lock);
}

From source file:com.seleniumtests.ut.connectors.selenium.TestSeleniumGridConnector.java

License:Apache License

@BeforeMethod(groups = { "ut" })
private void init() throws ClientProtocolException, IOException {
    PowerMockito.mockStatic(HttpClients.class);
    PowerMockito.mockStatic(TestLogging.class);
    PowerMockito.mockStatic(Unirest.class);

    when(HttpClients.createDefault()).thenReturn(client);
    when(response.getEntity()).thenReturn(entity);
    when(response.getStatusLine()).thenReturn(statusLine);
    when(client.execute((HttpHost) any(HttpHost.class), any(HttpRequest.class))).thenReturn(response);
    when(driver.getCapabilities()).thenReturn(capabilities);
    when(driver.getSessionId()).thenReturn(new SessionId("0"));
}

From source file:com.seleniumtests.ut.core.TestSeleniumTestContext3.java

License:Apache License

/**
 * Test that a grid connection is created when all parameters are correct
 * @param testNGCtx/*from w  ww. j  a v a  2 s. c o m*/
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 * @throws NoSuchFieldException 
 * @throws SecurityException 
 * @throws NoSuchMethodException 
 */
@Test(groups = "ut")
public void testGridConnection(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, "http://localhost:4444/hub/wd");

        ITestResult testResult = GenericTest.generateResult(testNGCtx, getClass());
        initThreadContext(testNGCtx, "myTest", testResult);
        Assert.assertEquals(SeleniumTestsContextManager.getThreadContext().getSeleniumGridConnector(),
                gridConnector);

    } finally {
        System.clearProperty(SeleniumTestsContext.RUN_MODE);
        System.clearProperty(SeleniumTestsContext.WEB_DRIVER_GRID);
    }
}

From source file:com.seleniumtests.ut.core.TestSeleniumTestContext3.java

License:Apache License

/**
 * Local test, no grid connector/*from   w  ww.j  a v  a  2  s  . co m*/
 * @param testNGCtx
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 * @throws NoSuchFieldException 
 * @throws SecurityException 
 * @throws NoSuchMethodException 
 */
@Test(groups = "ut")
public void testNoGridConnection(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, "local");
        System.setProperty(SeleniumTestsContext.WEB_DRIVER_GRID, "http://localhost:4444/hub/wd");

        ITestResult testResult = GenericTest.generateResult(testNGCtx, getClass());
        initThreadContext(testNGCtx, "myTest", testResult);
        Assert.assertNull(SeleniumTestsContextManager.getThreadContext().getSeleniumGridConnector());

    } finally {
        System.clearProperty(SeleniumTestsContext.RUN_MODE);
        System.clearProperty(SeleniumTestsContext.WEB_DRIVER_GRID);
    }
}

From source file:com.seleniumtests.ut.core.TestSeleniumTestContext3.java

License:Apache License

/**
 * grid test but missing url. An error should be raised
 * @param testNGCtx// w ww.j ava 2  s . c  o m
 * @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);
    }
}

From source file:com.seleniumtests.ut.core.TestTestTasks.java

License:Apache License

@Test(groups = { "ut" })
public void testKillProcessGrid(final ITestContext testNGCtx) {
    SeleniumGridConnector gridConnector = spy(new SeleniumRobotGridConnector("http://localhost:4444/hub/wd"));
    doNothing().when(gridConnector).killProcess("some_process");

    // 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 {/*from   w w  w  . j  a  va 2 s  .  c  o m*/
        System.setProperty(SeleniumTestsContext.RUN_MODE, "grid");
        System.setProperty(SeleniumTestsContext.WEB_DRIVER_GRID, "http://localhost:4444/hub/wd");
        initThreadContext(testNGCtx);

        SeleniumTestsContextManager.getThreadContext().getSeleniumGridConnectors();
        TestTasks.killProcess("some_process");

        verify(gridConnector).killProcess("some_process");

    } finally {
        System.clearProperty(SeleniumTestsContext.RUN_MODE);
        System.clearProperty(SeleniumTestsContext.WEB_DRIVER_GRID);
    }
}

From source file:com.seleniumtests.ut.core.TestTestTasks.java

License:Apache License

@Test(groups = { "ut" })
public void testGetProcessListGrid(final ITestContext testNGCtx) {
    SeleniumGridConnector gridConnector = spy(new SeleniumRobotGridConnector("http://localhost:4444/hub/wd"));
    doReturn(Arrays.asList(10, 20)).when(gridConnector).getProcessList("some_process");

    // 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 {//from   ww  w . j a v  a  2  s.  c om
        System.setProperty(SeleniumTestsContext.RUN_MODE, "grid");
        System.setProperty(SeleniumTestsContext.WEB_DRIVER_GRID, "http://localhost:4444/hub/wd");
        initThreadContext(testNGCtx);

        SeleniumTestsContextManager.getThreadContext().getSeleniumGridConnectors();
        TestTasks.getProcessList("some_process");

        verify(gridConnector).getProcessList("some_process");

    } finally {
        System.clearProperty(SeleniumTestsContext.RUN_MODE);
        System.clearProperty(SeleniumTestsContext.WEB_DRIVER_GRID);
    }
}

From source file:com.seleniumtests.ut.driver.TestCustomEventFiringWebDriver.java

License:Apache License

@BeforeMethod(groups = { "ut" })
private void init() throws Exception {

    PowerMockito.spy(CustomEventFiringWebDriver.class);

    // add DriverExceptionListener to reproduce driver behavior
    eventDriver = spy(/*from  ww  w.  j ava 2  s.c  o m*/
            new CustomEventFiringWebDriver(driver, null, browserInfo, true, DriverMode.LOCAL, null, null)
                    .register(new DriverExceptionListener()));

    when(driver.manage()).thenReturn(options);
    when(driver.getSessionId()).thenReturn(new SessionId("1234"));
    when(driver.getPageSource()).thenReturn("<html></html>");
    when(options.window()).thenReturn(window);
    when(window.getSize()).thenReturn(new Dimension(100, 100));

    PowerMockito.mockStatic(OSUtilityFactory.class);
    when(OSUtilityFactory.getInstance()).thenReturn(osUtility);

    PowerMockito.whenNew(Robot.class).withNoArguments().thenReturn(robot);
    PowerMockito.whenNew(VideoRecorder.class).withAnyArguments().thenReturn(videoRecorder);
    PowerMockito.whenNew(Keyboard.class).withNoArguments().thenReturn(keyboard);
    PowerMockito.doReturn(new Rectangle(1900, 1000)).when(CustomEventFiringWebDriver.class,
            "getScreensRectangle");

}

From source file:com.seleniumtests.ut.uipage.htmlelements.TestHtmlElement.java

License:Apache License

@BeforeMethod(groups = { "ut" })
private void init() throws WebDriverException, IOException {
    // mimic sub elements of the HtmlElement
    List<WebElement> subElList = new ArrayList<WebElement>();
    subElList.add(subElement1);//  w w  w  .jav a 2 s.  c  o  m
    subElList.add(subElement2);

    // list of elements correspond
    List<WebElement> elList = new ArrayList<WebElement>();
    elList.add(element);

    // add DriverExceptionListener to reproduce driver behavior
    eventDriver = spy(new CustomEventFiringWebDriver(driver).register(new DriverExceptionListener()));

    PowerMockito.mockStatic(WebUIDriver.class);
    when(WebUIDriver.getWebDriver()).thenReturn(eventDriver);
    when(driver.findElement(By.id("el"))).thenReturn(element);
    when(driver.findElements(By.name("subEl"))).thenReturn(subElList);
    when(driver.findElement(By.name("subEl"))).thenReturn(subElement1);
    when(driver.findElements(By.id("el"))).thenReturn(elList);
    when(driver.getKeyboard()).thenReturn(keyboard);
    when(driver.getMouse()).thenReturn(mouse);
    when(driver.switchTo()).thenReturn(locator);
    when(driver.executeScript(anyString())).thenReturn(Arrays.asList(100, 100));

    when(element.findElement(By.name("subEl"))).thenReturn(subElement1);
    when(element.findElements(By.name("subEl"))).thenReturn(subElList);
    when(element.getAttribute(anyString())).thenReturn("attribute");
    when(element.getSize()).thenReturn(new Dimension(10, 10));
    when(element.getLocation()).thenReturn(new Point(5, 5));
    when(element.getTagName()).thenReturn("h1");
    when(element.getText()).thenReturn("text");
    when(element.isDisplayed()).thenReturn(true);
    when(element.isEnabled()).thenReturn(true);

    when(subElement1.isDisplayed()).thenReturn(true);
    when(subElement2.isDisplayed()).thenReturn(true);
    when(subElement1.getLocation()).thenReturn(new Point(5, 5));
    when(subElement2.getLocation()).thenReturn(new Point(5, 5));

    when(mobileElement.getCenter()).thenReturn(new Point(2, 2));
    when(mobileElement.getLocation()).thenReturn(new Point(1, 1));
    when(mobileElement.isDisplayed()).thenReturn(true);
    when(mobileElement.getId()).thenReturn("12");

    // init for mobile tests
    AppiumCommandExecutor ce = Mockito.mock(AppiumCommandExecutor.class);
    Response response = new Response(new SessionId("1"));
    response.setValue(new HashMap<String, Object>());
    Response findResponse = new Response(new SessionId("1"));
    findResponse.setValue(mobileElement);

    when(ce.execute(any())).thenReturn(response, response, response, findResponse);
    doReturn(response).when(ce)
            .execute(argThat(command -> DriverCommand.NEW_SESSION.equals(command.getName())));
    doReturn(response).when(ce)
            .execute(argThat(command -> DriverCommand.FIND_ELEMENT.equals(command.getName())));
    doReturn(response).when(ce).execute(argThat(command -> "getSession".equals(command.getName())));

    // newSession, getSession, getSession, findElement

    mobileDriver = Mockito.spy(new AppiumDriver<>(ce, new DesiredCapabilities()));

    SeleniumTestsContextManager.getThreadContext().setTestType(TestType.WEB);
    SeleniumTestsContextManager.getThreadContext().setBrowser("htmlunit");
}

From source file:com.thoughtworks.selenium.webdriven.WebDriverBackedSeleniumServlet.java

License:Apache License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String cmd = req.getParameter("cmd");
    SessionId sessionId = new SessionId(req.getParameter("sessionId"));
    String[] args = deserializeArgs(req);

    if (cmd == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from ww  w.j  av  a  2s .c o  m*/
    }

    StringBuilder printableArgs = new StringBuilder("[");
    Joiner.on(", ").appendTo(printableArgs, args);
    printableArgs.append("]");
    getServletContext()
            .log(String.format("Command request: %s%s on session %s", cmd, printableArgs, sessionId));

    if ("getNewBrowserSession".equals(cmd)) {
        // Figure out what to do. If the first arg is "*webdriver", check for a session id and use
        // that existing session if present. Otherwise, start a new session with whatever comes to
        // hand. If, however, the first parameter specifies something else, then create a session
        // using a webdriver-backed instance of that.
        startNewSession(resp, args[0], args[1], args.length == 4 ? args[3] : "");
        return;
    } else if ("testComplete".equals(cmd)) {
        sessionsSupplier.get().deleteSession(sessionId);

        CommandProcessor commandProcessor = SESSIONS.getIfPresent(sessionId);
        if (commandProcessor == null) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        SESSIONS.invalidate(sessionId);
        sendResponse(resp, null);
        return;
    }

    // Common case.
    CommandProcessor commandProcessor = SESSIONS.getIfPresent(sessionId);
    if (commandProcessor == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    try {
        String result = commandProcessor.doCommand(cmd, args);
        sendResponse(resp, result);
    } catch (SeleniumException e) {
        sendError(resp, e.getMessage());
    }
}