All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.codacy.scoobydoo.Retry Maven / Gradle / Ivy

package com.codacy.scoobydoo;

import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;

import java.lang.annotation.Annotation;
import java.util.Optional;


public class Retry implements IRetryAnalyzer {

    private final int analysisMaxTries;
    private final int maxTries;
    private int count = 0;

    public Retry() {
        analysisMaxTries = getRetryNumber("ANALYSIS_RETRY_NUMBER")
                .orElse(0);
        maxTries = getRetryNumber("RETRY_NUMBER")
                .orElse(0);
    }

    @Override
    public boolean retry(ITestResult result) {

        if(result.isSuccess()) {
            result.setStatus(ITestResult.SUCCESS);
            return false;

        } else if (hasShouldNotBeRetriedAnnotation(result)) {
            return false;

        } else {

            int targetMaxTries = hasWaitForAnalysisAnnotation(result) ? analysisMaxTries : maxTries;

            if (count < targetMaxTries) {
                count++;
                return true;
            } else {
                return false;
            }
        }
    }

    private Optional getRetryNumber(String envVarName) {

        String envValue = System.getenv(envVarName);
        if (envValue != null && !envValue.isBlank()) {
            try {
                return Optional.of(Integer.parseInt(envValue));

            } catch (NumberFormatException e) {
                final String errorMessage =
                        "Value [" + envValue + "] for key '" + envVarName + "' is not valid. It as to be an integer.";
                LoggingHelper.error(errorMessage, e);
                throw e;
            }

        } else {
            return Optional.empty();
        }
    }

    private boolean hasShouldNotBeRetriedAnnotation(ITestResult result) {
        return hasAnnotation(result, ShouldNotBeRetried.class);
    }

    private boolean hasWaitForAnalysisAnnotation(ITestResult result) {
        return hasAnnotation(result, WaitForAnalysis.class);
    }

    private boolean hasAnnotation(ITestResult result, Class annotation) {
        return result.getMethod().getConstructorOrMethod().getMethod().isAnnotationPresent(annotation);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy