Search in sources :

Example 51 with ConfigurationException

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

the class SeleniumRobotServerTestRecorder method generateReport.

@Override
protected void generateReport(Map<ITestContext, Set<ITestResult>> resultSet, String outdir, boolean optimizeReport, boolean finalGeneration) {
    ITestContext testCtx = SeleniumTestsContextManager.getGlobalContext().getTestNGContext();
    if (testCtx == null) {
        logger.error("Looks like your class does not extend from SeleniumTestPlan!");
        return;
    }
    // issue #81: use global context because these parameters are known from there (thread context is too narrow)
    if (!Boolean.TRUE.equals(SeleniumTestsContextManager.getGlobalContext().getSeleniumRobotServerActive()) || !SeleniumTestsContextManager.getGlobalContext().getSeleniumRobotServerRecordResults() && !SeleniumTestsContextManager.getGlobalContext().getSeleniumRobotServerCompareSnapshot()) {
        return;
    }
    // check that seleniumRobot server is alive
    SeleniumRobotSnapshotServerConnector serverConnector = getServerConnector();
    if (!serverConnector.getActive()) {
        logger.info("selenium-robot-server not found or down");
        return;
    } else {
        try {
            // create session only if it has not been before
            for (ITestContext testContext : resultSet.keySet()) {
                recordTestSession(testContext);
            }
        } catch (SeleniumRobotServerException | ConfigurationException e) {
            logger.error("Error contacting selenium robot server", e);
            return;
        }
    }
    try {
        recordResults(serverConnector, resultSet);
    } catch (SeleniumRobotServerException | ConfigurationException e) {
        logger.error("Error recording result on selenium robot server", e);
    }
}
Also used : ConfigurationException(com.seleniumtests.customexception.ConfigurationException) ITestContext(org.testng.ITestContext) SeleniumRobotSnapshotServerConnector(com.seleniumtests.connectors.selenium.SeleniumRobotSnapshotServerConnector) SeleniumRobotServerException(com.seleniumtests.customexception.SeleniumRobotServerException)

Example 52 with ConfigurationException

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

the class WebUIDriver method checkBrowserRunnable.

private void checkBrowserRunnable() {
    if (config.getMode() == DriverMode.LOCAL && !config.getTestType().isMobile()) {
        Map<BrowserType, List<BrowserInfo>> browsers = OSUtility.getInstalledBrowsersWithVersion(config.getBetaBrowser());
        if (!browsers.containsKey(config.getBrowserType()) || browsers.get(config.getBrowserType()).isEmpty()) {
            throw new ConfigurationException(String.format("Browser %s is not available. Available browsers are %s", config.getBrowserType(), browsers));
        }
        boolean browserFound = false;
        for (BrowserInfo browserInfo : browsers.get(config.getBrowserType())) {
            if (config.getBetaBrowser().equals(browserInfo.getBeta())) {
                browserFound = true;
                break;
            }
        }
        if (!browserFound) {
            throw new ConfigurationException(String.format("Browser %s %s is not available. Available browsers are %s", config.getBrowserType(), config.getBetaBrowser() ? "beta" : "", browsers));
        }
    }
}
Also used : ConfigurationException(com.seleniumtests.customexception.ConfigurationException) BrowserInfo(com.seleniumtests.browserfactory.BrowserInfo) List(java.util.List) ArrayList(java.util.ArrayList)

Example 53 with ConfigurationException

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

the class ErrorCauseFinder method searchMatchingInPreviousStep.

/**
 * Search a test step before 'testStep' which is matching the current failed step
 * e.g: we failed on step 3 so we search in 'step 2', then 'step 1' to see if one of them matches our 'step 3' visually
 * @param testStepManager		the TestStepManager
 * @param testStep				the TestStep on which we fail
 * @param stepSnapshotFile		the snapshot taken at the beginning of the step (which will be compared to references
 * @param errorCauses			the list of error causes
 */
private void searchMatchingInPreviousStep(TestStepManager testStepManager, TestStep testStep, File stepSnapshotFile, List<ErrorCause> errorCauses) {
    // read the list in reverse order to find the best matching reference
    List<TestStep> testStepsSubList = testStepManager.getTestSteps().subList(0, testStep.getPosition());
    Collections.reverse(testStepsSubList);
    for (TestStep testStep2 : testStepsSubList) {
        if (testStep2.getStepResultId() != null) {
            try {
                File referenceSnapshot = SeleniumRobotSnapshotServerConnector.getInstance().getReferenceSnapshot(testStep2.getStepResultId());
                if (referenceSnapshot == null) {
                    continue;
                }
                int matching = compareReferenceToStepSnapshot(stepSnapshotFile, referenceSnapshot);
                if (matching > 80) {
                    errorCauses.add(new ErrorCause(ErrorType.SELENIUM_ERROR, String.format("Wrong page found, we are on the page of step '%s'", testStep2.getName()), testStep));
                    return;
                }
            } catch (ConfigurationException | SeleniumRobotServerException e) {
                logger.error(e.getMessage());
            }
        }
    }
    errorCauses.add(new ErrorCause(ErrorType.UNKNOWN_PAGE, null, testStep));
}
Also used : TestStep(com.seleniumtests.reporter.logger.TestStep) ConfigurationException(com.seleniumtests.customexception.ConfigurationException) File(java.io.File) SeleniumRobotServerException(com.seleniumtests.customexception.SeleniumRobotServerException)

Example 54 with ConfigurationException

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

the class ReplayAction method replay.

/**
 * Replay all actions annotated by ReplayOnError if the class is not a subclass of
 * HtmlElement
 * @param joinPoint
 * @throws Throwable
 */
@Around("!execution(public * com.seleniumtests.uipage.htmlelements.HtmlElement+.* (..))" + "&& execution(@com.seleniumtests.uipage.ReplayOnError public * * (..)) && @annotation(replay)")
public Object replay(ProceedingJoinPoint joinPoint, ReplayOnError replay) throws Throwable {
    int replayDelayMs = replay != null ? replay.replayDelayMs() : 100;
    Instant end = systemClock.instant().plusSeconds(SeleniumTestsContextManager.getThreadContext().getReplayTimeout());
    Object reply = null;
    String targetName = joinPoint.getTarget().toString();
    TestAction currentAction = null;
    if (joinPoint.getTarget() instanceof GenericPictureElement) {
        String methodName = joinPoint.getSignature().getName();
        List<String> pwdToReplace = new ArrayList<>();
        String actionName = String.format("%s on %s %s", methodName, targetName, LogAction.buildArgString(joinPoint, pwdToReplace, new HashMap<>()));
        currentAction = new TestAction(actionName, false, pwdToReplace);
        // order of steps is the right one (first called is first displayed)
        if (TestStepManager.getParentTestStep() != null) {
            TestStepManager.getParentTestStep().addAction(currentAction);
        }
    }
    boolean actionFailed = false;
    Throwable currentException = null;
    try {
        while (end.isAfter(systemClock.instant())) {
            // raised if action cannot be performed
            if (((CustomEventFiringWebDriver) WebUIDriver.getWebDriver(false)).getBrowserInfo().getBrowser() == BrowserType.CHROME || ((CustomEventFiringWebDriver) WebUIDriver.getWebDriver(false)).getBrowserInfo().getBrowser() == BrowserType.EDGE) {
                updateScrollFlagForElement(joinPoint, true, null);
            }
            try {
                reply = joinPoint.proceed(joinPoint.getArgs());
                WaitHelper.waitForMilliSeconds(200);
                break;
            // do not replay if error comes from scenario
            } catch (ScenarioException | ConfigurationException | DatasetException e) {
                throw e;
            } catch (MoveTargetOutOfBoundsException | InvalidElementStateException e) {
                updateScrollFlagForElement(joinPoint, null, e);
            } catch (Throwable e) {
                if (end.minusMillis(200).isAfter(systemClock.instant())) {
                    WaitHelper.waitForMilliSeconds(replayDelayMs);
                    continue;
                } else {
                    throw e;
                }
            }
        }
        return reply;
    } catch (Throwable e) {
        actionFailed = true;
        currentException = e;
        throw e;
    } finally {
        if (currentAction != null && TestStepManager.getParentTestStep() != null) {
            currentAction.setFailed(actionFailed);
            scenarioLogger.logActionError(currentException);
            if (joinPoint.getTarget() instanceof GenericPictureElement) {
                currentAction.setDurationToExclude(((GenericPictureElement) joinPoint.getTarget()).getActionDuration());
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) Instant(java.time.Instant) ArrayList(java.util.ArrayList) InvalidElementStateException(org.openqa.selenium.InvalidElementStateException) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint) MoveTargetOutOfBoundsException(org.openqa.selenium.interactions.MoveTargetOutOfBoundsException) TestAction(com.seleniumtests.reporter.logger.TestAction) GenericPictureElement(com.seleniumtests.uipage.htmlelements.GenericPictureElement) DatasetException(com.seleniumtests.customexception.DatasetException) ConfigurationException(com.seleniumtests.customexception.ConfigurationException) ScenarioException(com.seleniumtests.customexception.ScenarioException) Around(org.aspectj.lang.annotation.Around)

Example 55 with ConfigurationException

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

the class AppTestDocumentation method main.

public static void main(String[] args) throws IOException {
    stepsUsedInTests = new HashMap<>();
    steps = new ArrayList<>();
    tests = new ArrayList<>();
    searchedElements = 0;
    File srcDir = Paths.get(args[0].replace(File.separator, "/"), "src", "test", "java").toFile();
    // find the root source path (folder where "tests" and "webpage" can be found
    List<Path> rootFolders;
    try (Stream<Path> files = Files.walk(Paths.get(srcDir.getAbsolutePath()))) {
        rootFolders = files.filter(Files::isDirectory).filter(p -> p.toAbsolutePath().resolve("tests").toFile().exists() && p.toAbsolutePath().resolve("webpage").toFile().exists()).collect(Collectors.toList());
    }
    javadoc = new StringBuilder("Cette page référence l'ensemble des tests et des opération disponible pour l'application\n");
    Path rootFolder = null;
    if (rootFolders.isEmpty()) {
        System.out.println("Cannot find a folder which contains 'tests' and 'webpage' subfolder. The project does not follow conventions");
        javadoc.append("Cannot find a folder which contains 'tests' and 'webpage' subfolder. The project does not follow conventions");
        System.exit(0);
    } else {
        rootFolder = rootFolders.get(0);
    }
    javadoc.append("\n{toc}\n\n");
    javadoc.append("${project.summary}\n");
    javadoc.append("h1. Tests\n");
    try (Stream<Path> files = Files.walk(rootFolder)) {
        List<Path> testsFolders = files.filter(Files::isDirectory).filter(p -> p.getFileName().toString().equals("tests")).collect(Collectors.toList());
        for (Path testsFolder : testsFolders) {
            exploreTests(testsFolder.toFile());
        }
    } catch (IndexOutOfBoundsException e) {
        throw new ConfigurationException("no 'tests' sub-package found");
    }
    javadoc.append("----");
    javadoc.append("h1. Pages\n");
    try (Stream<Path> files = Files.walk(rootFolder)) {
        List<Path> pagesFolders = files.filter(Files::isDirectory).filter(p -> p.getFileName().toString().equals("webpage")).collect(Collectors.toList());
        for (Path pagesFolder : pagesFolders) {
            explorePages(pagesFolder.toFile());
        }
    } catch (IndexOutOfBoundsException e) {
        throw new ConfigurationException("no 'webpage' sub-package found");
    }
    javadoc.append("${project.scmManager}\n\n");
    // store usage data
    javadoc.append("h1. Statistics\n");
    javadoc.append(String.format("Number of tests: %d\n", tests.size()));
    System.out.println(String.format("Number of tests: %d", tests.size()));
    javadoc.append(String.format("Searched elements: %d\n", searchedElements));
    System.out.println(String.format("Searched elements: %d", searchedElements));
    javadoc.append(String.format("Test steps: %d\n", steps.size()));
    System.out.println(String.format("Test steps: %d", steps.size()));
    javadoc.append(String.format("Mean elements/steps: %.1f\n", searchedElements * 1.0 / steps.size()));
    System.out.println(String.format("Mean elements/steps: %.1f\n", searchedElements * 1.0 / steps.size()));
    int usedSteps = 0;
    Map<String, Integer> stepReuse = new HashMap<>();
    for (List<String> stepsFromTest : stepsUsedInTests.values()) {
        for (String step : stepsFromTest) {
            if (steps.contains(step)) {
                stepReuse.put(step, stepReuse.getOrDefault(step, 0) + 1);
                usedSteps++;
            }
        }
    }
    javadoc.append(String.format("Steps reuse percentage: %.1f\n", usedSteps * 1.0 / stepReuse.size()));
    System.out.println(String.format("Steps reuse percentage: %.2f", usedSteps * 1.0 / stepReuse.size()));
    /*for (String step :steps) {
			if (!stepReuse.containsKey(step)) {
				System.out.println(step);
			}
		}
		System.out.println(new JSONObject(stepsUsedInTests).toString(2));*/
    FileUtils.write(Paths.get(args[0], "src/site/confluence/template.confluence").toFile(), javadoc, StandardCharsets.UTF_8);
}
Also used : Path(java.nio.file.Path) VoidVisitorAdapter(com.github.javaparser.ast.visitor.VoidVisitorAdapter) AnnotationExpr(com.github.javaparser.ast.expr.AnnotationExpr) HashMap(java.util.HashMap) Test(org.testng.annotations.Test) ArrayList(java.util.ArrayList) Charset(java.nio.charset.Charset) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) ConfigurationException(com.seleniumtests.customexception.ConfigurationException) Map(java.util.Map) CompilationUnit(com.github.javaparser.ast.CompilationUnit) NoSuchElementException(java.util.NoSuchElementException) Path(java.nio.file.Path) Node(com.github.javaparser.ast.Node) Files(java.nio.file.Files) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) FileInputStream(java.io.FileInputStream) Collectors(java.util.stream.Collectors) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) Modifier(com.github.javaparser.ast.Modifier) List(java.util.List) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) Optional(java.util.Optional) Comment(com.github.javaparser.ast.comments.Comment) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) JavaParser(com.github.javaparser.JavaParser) HashMap(java.util.HashMap) ConfigurationException(com.seleniumtests.customexception.ConfigurationException) Files(java.nio.file.Files) File(java.io.File)

Aggregations

ConfigurationException (com.seleniumtests.customexception.ConfigurationException)66 ArrayList (java.util.ArrayList)19 File (java.io.File)18 IOException (java.io.IOException)14 HashMap (java.util.HashMap)13 Test (org.testng.annotations.Test)13 Matcher (java.util.regex.Matcher)9 List (java.util.List)8 UnirestException (kong.unirest.UnirestException)8 GenericTest (com.seleniumtests.GenericTest)7 SeleniumRobotServerException (com.seleniumtests.customexception.SeleniumRobotServerException)7 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 ScenarioException (com.seleniumtests.customexception.ScenarioException)5 BrowserType (com.seleniumtests.driver.BrowserType)5 Map (java.util.Map)5 Pattern (java.util.regex.Pattern)5 Collectors (java.util.stream.Collectors)5 Win32Exception (com.sun.jna.platform.win32.Win32Exception)4 StandardCharsets (java.nio.charset.StandardCharsets)4 Files (java.nio.file.Files)4