Example usage for org.openqa.selenium Platform ANY

List of usage examples for org.openqa.selenium Platform ANY

Introduction

In this page you can find the example usage for org.openqa.selenium Platform ANY.

Prototype

Platform ANY

To view the source code for org.openqa.selenium Platform ANY.

Click Source Link

Document

Never returned, but can be used to request a browser running on any operating system.

Usage

From source file:com.rmn.qa.aws.VmManagerTest.java

License:Open Source License

@Test
// Test if multiple security groups can be passed when launching a node
public void testLaunchNodesMultipleSecurityGroups() throws NodesCouldNotBeStartedException {
    MockAmazonEc2Client client = new MockAmazonEc2Client(null);
    RunInstancesResult runInstancesResult = new RunInstancesResult();
    Reservation reservation = new Reservation();
    reservation.setInstances(Arrays.asList(new Instance()));
    runInstancesResult.setReservation(reservation);
    client.setRunInstances(runInstancesResult);
    Properties properties = new Properties();
    String region = "east", uuid = "uuid", browser = "chrome";
    Platform os = Platform.ANY;
    Integer threadCount = 5, maxSessions = 5;
    MockManageVm manageEC2 = new MockManageVm(client, properties, region);
    String userData = "userData";
    String securityGroup = "securityGroup1,securityGroup2,securityGroup3", subnetId = "subnetId",
            keyName = "keyName", linuxImage = "linuxImage";
    String[] splitSecurityGroupdIds = securityGroup.split(",");
    List securityGroupIdsAryLst = new ArrayList();

    if (securityGroup != null) {
        for (int i = 0; i < splitSecurityGroupdIds.length; i++) {
            securityGroupIdsAryLst.add(splitSecurityGroupdIds[i]);
        }/*from w w  w .j a v  a2s.  c  o  m*/
    }
    properties.setProperty(region + "_security_group", securityGroup);
    properties.setProperty(region + "_subnet_id", subnetId);
    properties.setProperty(region + "_key_name", keyName);
    properties.setProperty(region + "_linux_node_ami", linuxImage);
    manageEC2.setUserData(userData);
    manageEC2.launchNodes(uuid, os, browser, null, threadCount, maxSessions);
    RunInstancesRequest request = client.getRunInstancesRequest();
    request.setSecurityGroupIds(securityGroupIdsAryLst);
    List<String> securityGroups = request.getSecurityGroupIds();
    List<String> expectedSecurityGroups = Arrays
            .asList("securityGroup1,securityGroup2,securityGroup3".split(","));
    Assert.assertTrue("Security groups should match all given security groups",
            securityGroups.containsAll(expectedSecurityGroups));

    List<String> invalidSecurityGroups = Arrays
            .asList("securityGroup1,securityGroup2,securityGroup7".split(","));
    Assert.assertFalse("Security groups should match only the set security groups",
            securityGroups.containsAll(invalidSecurityGroups));

    Assert.assertFalse("Security group should not be empty", request.getSecurityGroupIds().isEmpty());
    Assert.assertEquals("More than 1 security group should be set", 3, securityGroups.size());
}

From source file:com.rmn.qa.servlet.AutomationTestRunServlet.java

License:Open Source License

/**
 * Attempts to register a new run request with the server.
 * Returns a 201 if the request can be fulfilled but AMIs must be started
 * Returns a 202 if the request can be fulfilled
 * Returns a 400 if the required parameters are not passed in.
 * Returns a 409 if the server is at full node capacity
 *///from   w w  w  .  j  a va2s.  co m
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");

    String browserRequested = request.getParameter("browser");
    String browserVersion = request.getParameter("browserVersion");
    String osRequested = request.getParameter("os");
    String threadCount = request.getParameter("threadCount");
    String uuid = request.getParameter(AutomationConstants.UUID);
    BrowserPlatformPair browserPlatformPairRequest;
    Platform requestedPlatform;

    // Return a 400 if any of the required parameters are not passed in
    // Check for uuid first as this is the most important variable
    if (uuid == null) {
        String msg = "Parameter 'uuid' must be passed in as a query string parameter";
        log.error(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
    if (browserRequested == null) {
        String msg = "Parameter 'browser' must be passed in as a query string parameter";
        log.error(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
    if (threadCount == null) {
        String msg = "Parameter 'threadCount' must be passed in as a query string parameter";
        log.error(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
    if (StringUtils.isEmpty(osRequested)) {
        requestedPlatform = Platform.ANY;
    } else {
        requestedPlatform = AutomationUtils.getPlatformFromObject(osRequested);
        if (requestedPlatform == null) {
            String msg = "Parameter 'os' does not have a valid Selenium Platform equivalent: " + osRequested;
            log.error(msg);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            return;
        }
    }

    Integer threadCountRequested = Integer.valueOf(threadCount);

    AutomationRunRequest runRequest = new AutomationRunRequest(uuid, threadCountRequested, browserRequested,
            browserVersion, requestedPlatform);
    browserPlatformPairRequest = new BrowserPlatformPair(browserRequested, requestedPlatform);

    log.info(String.format("Server request [%s] received.", runRequest));
    boolean amisNeeded;
    int amiThreadsToStart = 0;
    int currentlyAvailableNodes;
    // Synchronize this block until we've added the run to our context for other potential threads to see
    synchronized (AutomationTestRunServlet.class) {
        int remainingNodesAvailable = AutomationContext.getContext().getTotalThreadsAvailable(getProxySet());
        // If the number of nodes this grid hub can actually run is less than the number requested, this hub can not fulfill this run at this time
        if (remainingNodesAvailable < runRequest.getThreadCount()) {
            log.error(String.format(
                    "Requested node count of [%d] could not be fulfilled due to hub limit. [%d] nodes available - Request UUID [%s]",
                    threadCountRequested, remainingNodesAvailable, uuid));
            response.sendError(HttpServletResponse.SC_CONFLICT,
                    "Server cannot fulfill request due to configured node limit being reached.");
            return;
        }
        // Get the number of matching, free nodes to determine if we need to start up AMIs or not
        currentlyAvailableNodes = requestMatcher.getNumFreeThreadsForParameters(getProxySet(), runRequest);
        // If the number of available nodes is less than the total number requested, we will have to spin up AMIs in order to fulfill the request
        amisNeeded = currentlyAvailableNodes < threadCountRequested;
        if (amisNeeded) {
            // Get the difference which will be the number of additional nodes we need to spin up to supplement existing nodes
            amiThreadsToStart = threadCountRequested - currentlyAvailableNodes;
        }
        // If the browser requested is not supported by AMIs, we need to not unnecessarily spin up AMIs
        if (amisNeeded && !AutomationUtils.browserAndPlatformSupported(browserPlatformPairRequest)) {
            response.sendError(HttpServletResponse.SC_GONE,
                    "Request cannot be fulfilled and browser and platform is not supported by AMIs");
            return;
        }
        // Add the run to our context so we can track it
        AutomationRunRequest newRunRequest = new AutomationRunRequest(uuid, threadCountRequested,
                browserRequested, browserVersion, requestedPlatform);
        boolean addSuccessful = AutomationContext.getContext().addRun(newRunRequest);
        if (!addSuccessful) {
            log.warn(String.format("Test run already exists for the same UUID [%s]", uuid));
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Test run already exists with the same UUID.");
            return;
        }
    }
    if (amisNeeded) {
        // Start up AMIs as that will be required
        log.warn(String.format(
                "Insufficient nodes to fulfill request. New AMIs will be queued up. Requested [%s] - Available [%s] - Request UUID [%s]",
                threadCountRequested, currentlyAvailableNodes, uuid));
        try {
            AutomationTestRunServlet.startNodes(ec2, uuid, amiThreadsToStart, browserRequested,
                    requestedPlatform);
        } catch (NodesCouldNotBeStartedException e) {
            // Make sure and de-register the run if the AMI startup was not successful
            AutomationContext.getContext().deleteRun(uuid);
            String throwableMessage = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
            String msg = "Nodes could not be started: " + throwableMessage;
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
            return;
        }
        // Return a 201 to let the caller know AMIs will be started
        response.setStatus(HttpServletResponse.SC_CREATED);
        return;
    } else {
        // Otherwise just return a 202 letting the caller know the requested resources are available
        response.setStatus(HttpServletResponse.SC_ACCEPTED);
        return;
    }
}

From source file:com.rmn.qa.servlet.AutomationTestRunServletTest.java

License:Open Source License

@Test
// Tests if a hub has maxed out its configurable thread count that the hub will not attempt
// to fulfill the request
public void testHubThreadCountMaxedOut() throws IOException, ServletException {
    MockAutomationTestRunServlet servlet = new MockAutomationTestRunServlet(null, false, new MockVmManager(),
            new MockRequestMatcher());
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("uuid", "testUuid");
    request.setParameter("browser", "firefox");
    request.setParameter("os", Platform.ANY.toString());
    request.setParameter("threadCount", "50");
    AutomationContext.getContext().addRun(new AutomationRunRequest("runUUid", 50, "firefox"));
    AutomationContext.getContext().setTotalNodeCount(50);
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.doGet(request, response);//from   w ww.  j  av  a  2s.c o m
    Assert.assertEquals("Response code should be an error since the max thread count was reached",
            HttpServletResponse.SC_CONFLICT, response.getErrorCode());

    Assert.assertEquals("Response code should be an error since the max thread count was reached",
            "Server cannot fulfill request due to configured node limit being reached.",
            response.getErrorMessage());
}

From source file:com.rmn.qa.servlet.AutomationTestRunServletTest.java

License:Open Source License

@Test
// Tests that the configurable maximum thread count works with multiple nodes
public void testHubThreadCountMaxedOutMultipleRuns() throws IOException, ServletException {
    MockAutomationTestRunServlet servlet = new MockAutomationTestRunServlet(null, false, new MockVmManager(),
            new MockRequestMatcher());
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("uuid", "testUuid");
    request.setParameter("browser", "firefox");
    request.setParameter("os", Platform.ANY.toString());
    request.setParameter("threadCount", "50");
    AutomationContext.getContext().addRun(new AutomationRunRequest("runUUid", 25, "firefox"));
    AutomationContext.getContext().addRun(new AutomationRunRequest("runUUid", 25, "firefox"));
    AutomationContext.getContext().setTotalNodeCount(50);
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.doGet(request, response);/*w  w w .  j av a2  s .  c  o m*/
    Assert.assertEquals("Response code should be an error since the max thread count was reached",
            HttpServletResponse.SC_CONFLICT, response.getErrorCode());

    Assert.assertEquals("Response code should be an error since the max thread count was reached",
            "Server cannot fulfill request due to configured node limit being reached.",
            response.getErrorMessage());
}

From source file:com.rmn.qa.servlet.AutomationTestRunServletTest.java

License:Open Source License

@Test
// Tests the happy path that a hub says a request can be fulfilled when it can be
public void testRequestCanFulfill() throws IOException, ServletException {
    MockVmManager manageEc2 = new MockVmManager();
    MockRequestMatcher matcher = new MockRequestMatcher();
    matcher.setThreadsToReturn(10);//w  w w  .  j  av a 2 s .c  o  m
    MockAutomationTestRunServlet servlet = new MockAutomationTestRunServlet(null, false, manageEc2, matcher);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("uuid", "testUuid");
    request.setParameter("browser", "firefox");
    request.setParameter("os", Platform.ANY.toString());
    request.setParameter("threadCount", "10");
    String nodeId = "nodeId";
    // Add a node that is not running to make sure its not included in the available calculation
    AutomationDynamicNode node = new AutomationDynamicNode("testUuid", nodeId, null, null, new Date(), 50);
    AutomationContext.getContext().addNode(node);
    ProxySet proxySet = new ProxySet(false);
    MockRemoteProxy proxy = new MockRemoteProxy();
    proxy.setMaxNumberOfConcurrentTestSessions(50);
    proxy.setCapabilityMatcher(new AutomationCapabilityMatcher());
    Map<String, Object> config = new HashMap<String, Object>();
    config.put(AutomationConstants.INSTANCE_ID, nodeId);
    proxy.setConfig(config);
    Map<String, Object> capabilities = new HashMap<String, Object>();
    capabilities.put(CapabilityType.BROWSER_NAME, "firefox");
    TestSlot testSlot = new TestSlot(proxy, SeleniumProtocol.WebDriver, null, capabilities);
    proxy.setMultipleTestSlots(testSlot, 10);
    proxySet.add(proxy);
    servlet.setProxySet(proxySet);
    AutomationContext.getContext().setTotalNodeCount(50);
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.doGet(request, response);
    Assert.assertEquals("Hub should be able to fulfill request", HttpServletResponse.SC_ACCEPTED,
            response.getStatusCode());
}

From source file:com.rmn.qa.servlet.AutomationTestRunServletTest.java

License:Open Source License

@Test
// Tests that a run request with a duplicate uuid of another run is rejected
public void testDuplicateUuids() throws IOException, ServletException {
    MockVmManager manageEc2 = new MockVmManager();
    MockRequestMatcher matcher = new MockRequestMatcher();
    matcher.setThreadsToReturn(10);/*from   w ww.  j av a2  s . c  o m*/
    MockAutomationTestRunServlet servlet = new MockAutomationTestRunServlet(null, false, manageEc2, matcher);
    MockHttpServletRequest request = new MockHttpServletRequest();
    String uuid = "testUUid";
    request.setParameter("uuid", uuid);
    request.setParameter("browser", "firefox");
    request.setParameter("os", Platform.ANY.toString());
    request.setParameter("threadCount", "10");
    String nodeId = "nodeId";
    // Add a node that is not running to make sure its not included in the available calculation
    AutomationDynamicNode node = new AutomationDynamicNode("testUuid", nodeId, null, null, new Date(), 50);
    AutomationContext.getContext().addNode(node);
    ProxySet proxySet = new ProxySet(false);
    MockRemoteProxy proxy = new MockRemoteProxy();
    proxy.setMaxNumberOfConcurrentTestSessions(50);
    proxy.setCapabilityMatcher(new AutomationCapabilityMatcher());
    Map<String, Object> config = new HashMap<String, Object>();
    config.put(AutomationConstants.INSTANCE_ID, nodeId);
    proxy.setConfig(config);
    Map<String, Object> capabilities = new HashMap<String, Object>();
    capabilities.put(CapabilityType.BROWSER_NAME, "firefox");
    TestSlot testSlot = new TestSlot(proxy, SeleniumProtocol.WebDriver, null, capabilities);
    proxy.setMultipleTestSlots(testSlot, 10);
    proxySet.add(proxy);
    servlet.setProxySet(proxySet);
    AutomationContext.getContext().setTotalNodeCount(50);
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.doGet(request, response);
    // Submit a 2nd request with the same UUID
    MockHttpServletResponse response2 = new MockHttpServletResponse();
    servlet.doGet(request, response2);
    Assert.assertEquals("Hub should not able to fulfill request due to duplicate uuid",
            HttpServletResponse.SC_BAD_REQUEST, response2.getErrorCode());
    Assert.assertEquals("Hub should not able to fulfill request due to duplicate uuid",
            "Test run already exists with the same UUID.", response2.getErrorMessage());
}

From source file:com.rmn.qa.servlet.AutomationTestRunServletTest.java

License:Open Source License

@Test
// Tests a request can be fulfilled when nodes have to be spun up
public void testRequestCanFulfillSpinUpNodes() throws IOException, ServletException {
    MockVmManager manageEc2 = new MockVmManager();
    MockRequestMatcher matcher = new MockRequestMatcher();
    matcher.setThreadsToReturn(0);//from   w w w. j  a va2  s  .  c o m
    MockAutomationTestRunServlet servlet = new MockAutomationTestRunServlet(null, false, manageEc2, matcher);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("uuid", "testUuid");
    request.setParameter("browser", "firefox");
    request.setParameter("os", Platform.ANY.toString());
    request.setParameter("threadCount", "6");
    String nodeId = "nodeId";
    // Add a node that is not running to make sure its not included in the available calculation
    AutomationDynamicNode node = new AutomationDynamicNode("testUuid", nodeId, null, null, new Date(), 50);
    AutomationContext.getContext().addNode(node);
    ProxySet proxySet = new ProxySet(false);
    MockRemoteProxy proxy = new MockRemoteProxy();
    proxy.setMaxNumberOfConcurrentTestSessions(50);
    proxy.setCapabilityMatcher(new AutomationCapabilityMatcher());
    Map<String, Object> config = new HashMap<String, Object>();
    config.put(AutomationConstants.INSTANCE_ID, nodeId);
    proxy.setConfig(config);
    Map<String, Object> capabilities = new HashMap<String, Object>();
    capabilities.put(CapabilityType.BROWSER_NAME, "firefox");
    TestSlot testSlot = new TestSlot(proxy, SeleniumProtocol.WebDriver, null, capabilities);
    proxy.setMultipleTestSlots(testSlot, 10);
    proxySet.add(proxy);
    servlet.setProxySet(proxySet);
    AutomationContext.getContext().setTotalNodeCount(50);
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.doGet(request, response);
    Assert.assertEquals("Hub should be able to fulfill request", HttpServletResponse.SC_CREATED,
            response.getStatusCode());
}

From source file:com.rmn.qa.task.AutomationScaleNodeTask.java

License:Open Source License

@Override
public void doWork() {
    log.warn("Doing node scale work");
    // Iterate over all queued requests and track browser/platform combinations that are eligible to scale capacity for
    Iterator<DesiredCapabilities> pendingCapabilities = getDesiredCapabilities().iterator();
    if (pendingCapabilities.hasNext()) {
        log.info("Analyzing currently queued requests");
        while (pendingCapabilities.hasNext()) {
            DesiredCapabilities capabilities = pendingCapabilities.next();
            String browser = (String) capabilities.getCapability(CapabilityType.BROWSER_NAME);
            Object platformObject = capabilities.getCapability(CapabilityType.PLATFORM);
            Platform platform = AutomationUtils.getPlatformFromObject(platformObject);
            // If a valid platform wasn't able to be parsed from the queued test request, go ahead and default to Platform.ANY,
            // as Platform is not required for this plugin
            if (platform == null) {
                // Default to ANY here and let AwsVmManager dictate what ANY translates to
                platform = Platform.ANY;
            }/*from   w  w w  .ja va 2s.  co  m*/
            // Group all platforms by their underlying family
            platform = AutomationUtils.getUnderlyingFamily(platform);
            BrowserPlatformPair desiredPair = new BrowserPlatformPair(browser, platform);

            // Don't attempt to calculate load for browsers & platform families we cannot start
            if (!isEligibleToScale(desiredPair)) {
                log.warn("Unsupported browser and platform pair, browser:  " + browser + " platform family: "
                        + platform.family());
                continue;
            }

            // Handle requests for specific browser platforms.
            queuedBrowsersPlatforms.computeIfAbsent(new BrowserPlatformPair(browser, platform),
                    s -> new Date());
        }
    }
    // Now, iterate over eligible browser/platform combinations that we're tracking and attempt to scale up
    Iterator<BrowserPlatformPair> queuedBrowsersIterator = queuedBrowsersPlatforms.keySet().iterator();
    while (queuedBrowsersIterator.hasNext()) {
        BrowserPlatformPair originalBrowserPlatformRequest = queuedBrowsersIterator.next();
        Date currentTime = new Date();
        Date timeBrowserPlatformQueued = queuedBrowsersPlatforms.get(originalBrowserPlatformRequest);
        if (haveTestRequestsBeenQueuedForLongEnough(currentTime, timeBrowserPlatformQueued)) { // If we've had pending queued requests for this browser for at least 5 seconds
            pendingCapabilities = getDesiredCapabilities().iterator();
            if (pendingCapabilities.hasNext()) {
                int browsersToStart = 0;
                while (pendingCapabilities.hasNext()) {
                    DesiredCapabilities currentlyQueuedCapabilities = pendingCapabilities.next();
                    String currentlyQueuedBrowser = (String) currentlyQueuedCapabilities
                            .getCapability(CapabilityType.BROWSER_NAME);
                    Object platformObject = currentlyQueuedCapabilities.getCapability(CapabilityType.PLATFORM);
                    Platform currentlyQueuedPlatform = AutomationUtils.getPlatformFromObject(platformObject);
                    // If a valid platform wasn't able to be parsed from the queued test request, go ahead and default to Platform.ANY,
                    // as Platform is not required for this plugin
                    if (currentlyQueuedPlatform == null) {
                        currentlyQueuedPlatform = Platform.ANY;
                    }
                    // Group all platforms by their underlying family
                    currentlyQueuedPlatform = AutomationUtils.getUnderlyingFamily(currentlyQueuedPlatform);
                    if (originalBrowserPlatformRequest
                            .equals(new BrowserPlatformPair(currentlyQueuedBrowser, currentlyQueuedPlatform))) {
                        browsersToStart++;
                    }
                }
                this.startNodesForBrowserPlatform(originalBrowserPlatformRequest, browsersToStart);
            }
            // Regardless of if we spun up browsers or not, clear this count out
            queuedBrowsersIterator.remove();
        }
    }
}

From source file:com.seleniumtests.core.SeleniumTestsContext.java

License:Apache License

/**
 * From platform name, in case of Desktop platform, do nothing and in case of mobile, extract OS version from name
 * as platformName will be 'Android 5.0' for example
 *
 * @throws ConfigurationException    in mobile, if version is not present
 *///  w w w  .  ja va2  s.c om
private void updatePlatformVersion() {
    try {
        Platform currentPlatform = Platform.fromString(getPlatform());
        if (currentPlatform.is(Platform.WINDOWS) || currentPlatform.is(Platform.MAC)
                || currentPlatform.is(Platform.UNIX)
                || currentPlatform.is(Platform.ANY) && getRunMode() == DriverMode.GRID) {
            return;

        } else {
            throw new WebDriverException("");
        }
    } catch (WebDriverException e) {
        if (getPlatform().toLowerCase().startsWith("android")
                || getPlatform().toLowerCase().startsWith("ios")) {
            String[] pfVersion = getPlatform().split(" ", 2);
            try {
                setPlatform(pfVersion[0]);
                setMobilePlatformVersion(pfVersion[1]);
                return;
            } catch (IndexOutOfBoundsException x) {
                setMobilePlatformVersion(null);
                logger.warn(
                        "For mobile platform, platform name should contain version. Ex: 'Android 5.0' or 'iOS 9.1'. Else, first found device is used");
            }

        } else {
            throw new ConfigurationException(
                    String.format("Platform %s has not been recognized as a valid platform", getPlatform()));
        }
    }
}

From source file:com.seleniumtests.core.SeleniumTestsContext.java

License:Apache License

/**
 * Set platform on which we request to execute the test
 * In mobile, platform parameter will be given (iOS xx or Android yy)
 * In desktop, if we run the test locally, we should get the current platform, else, let user decide on which platform
 * test will be run. It may be any if underlying OS does not matter (for grid)
 * @param platform//from   www . ja  v  a 2s.  c o m
 */
public void setPlatform(String platform) {
    if (platform != null) {
        setAttribute(PLATFORM, platform);
    } else {
        if (getRunMode() == DriverMode.LOCAL) {
            setAttribute(PLATFORM, OSUtility.getCurrentPlatorm().toString());
        } else {
            setAttribute(PLATFORM, Platform.ANY.toString());
        }
    }
}