Search in sources :

Example 41 with ScenarioException

use of com.seleniumtests.customexception.ScenarioException 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 42 with ScenarioException

use of com.seleniumtests.customexception.ScenarioException 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 43 with ScenarioException

use of com.seleniumtests.customexception.ScenarioException in project seleniumRobot by bhecquet.

the class PerfectoCapabilitiesFactory method createCapabilities.

@Override
public MutableCapabilities createCapabilities() {
    String apiKey = extractApiKey();
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability("enableAppiumBehavior", true);
    capabilities.setCapability("autoLaunch", true);
    capabilities.setCapability("securityToken", apiKey);
    if (ANDROID_PLATFORM.equalsIgnoreCase(webDriverConfig.getPlatform())) {
        Capabilities androidCaps = new AndroidCapabilitiesFactory(webDriverConfig).createCapabilities();
        capabilities.merge(androidCaps);
    } else if (IOS_PLATFORM.equalsIgnoreCase(webDriverConfig.getPlatform())) {
        Capabilities iosCaps = new IOsCapabilitiesFactory(webDriverConfig).createCapabilities();
        capabilities.merge(iosCaps);
    }
    // we need to upload something
    if (capabilities.getCapability(MobileCapabilityType.APP) != null) {
        boolean uploadApp = isUploadApp(capabilities);
        String appName = new File((String) capabilities.getCapability(MobileCapabilityType.APP)).getName();
        String repositoryKey = String.format("PUBLIC:%s", appName);
        String cloudName = extractCloudName();
        if (uploadApp) {
            try {
                uploadFile(cloudName, apiKey, (String) capabilities.getCapability(MobileCapabilityType.APP), repositoryKey);
            } catch (URISyntaxException | IOException e) {
                throw new ScenarioException("Could not upload file", e);
            }
        }
        capabilities.setCapability(MobileCapabilityType.APP, repositoryKey);
    }
    return capabilities;
}
Also used : MutableCapabilities(org.openqa.selenium.MutableCapabilities) Capabilities(org.openqa.selenium.Capabilities) DesiredCapabilities(org.openqa.selenium.remote.DesiredCapabilities) DesiredCapabilities(org.openqa.selenium.remote.DesiredCapabilities) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) File(java.io.File) ScenarioException(com.seleniumtests.customexception.ScenarioException)

Example 44 with ScenarioException

use of com.seleniumtests.customexception.ScenarioException in project seleniumRobot by bhecquet.

the class SeleniumRobotGridConnector method uploadFileToNode.

/**
 * Upload file to node
 * @param filePath			the file to upload
 * @param returnLocalFile	if true, returned path will be the local path on grid node. If false, we get file://upload/file/<uuid>/
 * @return
 */
@Override
public String uploadFileToNode(String filePath, boolean returnLocalFile) {
    if (nodeUrl == null) {
        throw new ScenarioException("You cannot upload file to browser before driver has been created and corresponding node instanciated");
    }
    // zip file
    File zipFile = null;
    try {
        List<File> appFiles = new ArrayList<>();
        appFiles.add(new File(filePath));
        zipFile = FileUtility.createZipArchiveFromFiles(appFiles);
    } catch (IOException e1) {
        throw new SeleniumGridException("Error in uploading file, when zipping: " + e1.getMessage());
    }
    logger.info("uploading file to node: " + zipFile.getName());
    try {
        HttpRequestWithBody req = Unirest.post(String.format("%s%s", nodeUrl, FILE_SERVLET)).header(HttpHeaders.CONTENT_TYPE, MediaType.OCTET_STREAM.toString()).queryString(OUTPUT_FIELD, "file");
        if (returnLocalFile) {
            req = req.queryString("localPath", "true");
        }
        HttpResponse<String> response = req.field("upload", zipFile).asString();
        if (response.getStatus() != 200) {
            throw new SeleniumGridException(String.format("Error uploading file: %s", response.getBody()));
        } else {
            return response.getBody();
        }
    } catch (UnirestException e) {
        throw new SeleniumGridException(String.format("Cannot upload file: %s", e.getMessage()));
    }
}
Also used : SeleniumGridException(com.seleniumtests.customexception.SeleniumGridException) HttpRequestWithBody(kong.unirest.HttpRequestWithBody) ArrayList(java.util.ArrayList) UnirestException(kong.unirest.UnirestException) IOException(java.io.IOException) File(java.io.File) ScenarioException(com.seleniumtests.customexception.ScenarioException)

Example 45 with ScenarioException

use of com.seleniumtests.customexception.ScenarioException in project seleniumRobot by bhecquet.

the class Fixture method getElement.

/**
 * Get element from its name
 * @param name
 * @return	the found element
 * @throws ScenarioException when element is not found
 */
public String getElement(String name) {
    Field elementField = allElements.get(name);
    if (elementField == null) {
        throw new ScenarioException(String.format("Element '%s' cannot be found among all classes. It may not have been defined", name));
    }
    Class<?> pageClass = elementField.getDeclaringClass();
    // create new page if we are not on it
    if (currentPage.get() == null || pageClass != currentPage.get().getClass()) {
        try {
            currentPage.set((PageObject) pageClass.newInstance());
        } catch (InstantiationException | IllegalAccessException e) {
            throw new ScenarioException(String.format("Page '%s' don't have default constructor, add it to avoid this error", pageClass.getSimpleName()));
        }
        logger.info("switching to page " + pageClass.getSimpleName());
    }
    if (name.split("\\.").length == 1) {
        return name;
    } else {
        return name.split("\\.")[1];
    }
}
Also used : Field(java.lang.reflect.Field) ScenarioException(com.seleniumtests.customexception.ScenarioException)

Aggregations

ScenarioException (com.seleniumtests.customexception.ScenarioException)68 ArrayList (java.util.ArrayList)17 WebElement (org.openqa.selenium.WebElement)14 UnirestException (kong.unirest.UnirestException)13 GenericPictureElement (com.seleniumtests.uipage.htmlelements.GenericPictureElement)12 IOException (java.io.IOException)12 JSONObject (kong.unirest.json.JSONObject)12 CheckBoxElement (com.seleniumtests.uipage.htmlelements.CheckBoxElement)11 Element (com.seleniumtests.uipage.htmlelements.Element)11 HtmlElement (com.seleniumtests.uipage.htmlelements.HtmlElement)11 LinkElement (com.seleniumtests.uipage.htmlelements.LinkElement)11 RadioButtonElement (com.seleniumtests.uipage.htmlelements.RadioButtonElement)11 File (java.io.File)10 List (java.util.List)9 HashMap (java.util.HashMap)8 ConfigurationException (com.seleniumtests.customexception.ConfigurationException)7 AWTException (java.awt.AWTException)7 Robot (java.awt.Robot)6 Map (java.util.Map)5 TestStep (com.seleniumtests.reporter.logger.TestStep)4