Search in sources :

Example 1 with TestSuiteChromosome

use of org.evosuite.testsuite.TestSuiteChromosome in project evosuite by EvoSuite.

the class AllDefsCoverageSuiteFitness method getFitness.

/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.evosuite.ga.FitnessFunction#getFitness(org.
	 * evosuite.ga.Chromosome)
	 */
/**
 * {@inheritDoc}
 */
@Override
public double getFitness(AbstractTestSuiteChromosome<? extends ExecutableChromosome> individual) {
    logger.trace("Calculating defuse fitness");
    TestSuiteChromosome suite = (TestSuiteChromosome) individual;
    List<ExecutionResult> results = runTestSuite(suite);
    double fitness = 0.0;
    Set<TestFitnessFunction> coveredGoals = new HashSet<TestFitnessFunction>();
    for (TestFitnessFunction goal : goals) {
        if (coveredGoals.contains(goal))
            continue;
        double goalFitness = 2.0;
        for (ExecutionResult result : results) {
            TestChromosome tc = new TestChromosome();
            tc.setTestCase(result.test);
            double resultFitness = goal.getFitness(tc, result);
            if (resultFitness < goalFitness)
                goalFitness = resultFitness;
            if (goalFitness == 0.0) {
                result.test.addCoveredGoal(goal);
                // System.out.println(goal.toString());
                // System.out.println(result.test.toCode());
                // System.out.println(resultFitness);
                coveredGoals.add(goal);
                break;
            }
        }
        fitness += goalFitness;
    }
    updateIndividual(this, individual, fitness);
    setSuiteCoverage(suite, coveredGoals);
    return fitness;
}
Also used : TestFitnessFunction(org.evosuite.testcase.TestFitnessFunction) AbstractTestSuiteChromosome(org.evosuite.testsuite.AbstractTestSuiteChromosome) TestSuiteChromosome(org.evosuite.testsuite.TestSuiteChromosome) ExecutionResult(org.evosuite.testcase.execution.ExecutionResult) TestChromosome(org.evosuite.testcase.TestChromosome) HashSet(java.util.HashSet)

Example 2 with TestSuiteChromosome

use of org.evosuite.testsuite.TestSuiteChromosome in project evosuite by EvoSuite.

the class WeakMutationSuiteFitness method getFitness.

/* (non-Javadoc)
	 * @see org.evosuite.ga.FitnessFunction#getFitness(org.evosuite.ga.Chromosome)
	 */
/**
 * {@inheritDoc}
 */
@Override
public double getFitness(AbstractTestSuiteChromosome<? extends ExecutableChromosome> individual) {
    /**
     * e.g. classes with only static constructors
     */
    if (this.numMutants == 0) {
        updateIndividual(this, individual, 0.0);
        ((TestSuiteChromosome) individual).setCoverage(this, 1.0);
        ((TestSuiteChromosome) individual).setNumOfCoveredGoals(this, 0);
        return 0.0;
    }
    List<ExecutionResult> results = runTestSuite(individual);
    // First objective: achieve branch coverage
    logger.debug("Calculating branch fitness: ");
    /*
		 * Note: results are cached, so the test suite is not executed again when we
		 * calculated the branch fitness
		 */
    double fitness = branchFitness.getFitness(individual);
    Map<Integer, Double> mutant_distance = new LinkedHashMap<Integer, Double>();
    Set<Integer> touchedMutants = new LinkedHashSet<Integer>();
    for (ExecutionResult result : results) {
        // use reflection for basic criteria, not for mutation
        if (result.hasTimeout() || result.hasTestException() || result.calledReflection()) {
            continue;
        }
        touchedMutants.addAll(result.getTrace().getTouchedMutants());
        Map<Integer, Double> touchedMutantsDistances = result.getTrace().getMutationDistances();
        if (touchedMutantsDistances.isEmpty()) {
            // if 'result' does not touch any mutant, no need to continue
            continue;
        }
        TestChromosome test = new TestChromosome();
        test.setTestCase(result.test);
        test.setLastExecutionResult(result);
        test.setChanged(false);
        Iterator<Entry<Integer, MutationTestFitness>> it = this.mutantMap.entrySet().iterator();
        while (it.hasNext()) {
            Entry<Integer, MutationTestFitness> entry = it.next();
            int mutantID = entry.getKey();
            TestFitnessFunction goal = entry.getValue();
            double fit = 0.0;
            if (touchedMutantsDistances.containsKey(mutantID)) {
                fit = touchedMutantsDistances.get(mutantID);
                if (!mutant_distance.containsKey(mutantID)) {
                    mutant_distance.put(mutantID, fit);
                } else {
                    mutant_distance.put(mutantID, Math.min(mutant_distance.get(mutantID), fit));
                }
            } else {
                // archive is updated by the TestFitnessFunction class
                fit = goal.getFitness(test, result);
            }
            if (fit == 0.0) {
                // update list of covered goals
                test.getTestCase().addCoveredGoal(goal);
                // goal to not be considered by the next iteration of the evolutionary algorithm
                this.toRemoveMutants.add(mutantID);
            }
            if (Properties.TEST_ARCHIVE) {
                Archive.getArchiveInstance().updateArchive(goal, test, fit);
            }
        }
    }
    // Second objective: touch all mutants?
    fitness += MutationPool.getMutantCounter() - touchedMutants.size();
    int covered = removedMutants.size();
    for (Double distance : mutant_distance.values()) {
        if (distance < 0) {
            logger.warn("Distance is " + distance + " / " + Integer.MAX_VALUE + " / " + Integer.MIN_VALUE);
            // FIXXME
            distance = 0.0;
        }
        fitness += normalize(distance);
        if (distance == 0.0) {
            covered++;
        }
    }
    updateIndividual(this, individual, fitness);
    ((TestSuiteChromosome) individual).setCoverage(this, (double) covered / (double) this.numMutants);
    ((TestSuiteChromosome) individual).setNumOfCoveredGoals(this, covered);
    return fitness;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) TestFitnessFunction(org.evosuite.testcase.TestFitnessFunction) ExecutionResult(org.evosuite.testcase.execution.ExecutionResult) LinkedHashMap(java.util.LinkedHashMap) Entry(java.util.Map.Entry) AbstractTestSuiteChromosome(org.evosuite.testsuite.AbstractTestSuiteChromosome) TestSuiteChromosome(org.evosuite.testsuite.TestSuiteChromosome) TestChromosome(org.evosuite.testcase.TestChromosome)

Example 3 with TestSuiteChromosome

use of org.evosuite.testsuite.TestSuiteChromosome in project evosuite by EvoSuite.

the class StrongMutationSuiteFitness method getFitness.

/* (non-Javadoc)
	 * @see org.evosuite.ga.FitnessFunction#getFitness(org.evosuite.ga.Chromosome)
	 */
/**
 * {@inheritDoc}
 */
@Override
public double getFitness(AbstractTestSuiteChromosome<? extends ExecutableChromosome> individual) {
    runTestSuite(individual);
    // Set<MutationTestFitness> uncoveredMutants = MutationTestPool.getUncoveredFitnessFunctions();
    TestSuiteChromosome suite = (TestSuiteChromosome) individual;
    for (TestChromosome test : suite.getTestChromosomes()) {
        ExecutionResult result = test.getLastExecutionResult();
        if (result.hasTimeout() || result.hasTestException()) {
            logger.debug("Skipping test with timeout");
            double fitness = branchFitness.totalGoals * 2 + branchFitness.totalMethods + 3 * this.numMutants;
            updateIndividual(this, individual, fitness);
            suite.setCoverage(this, 0.0);
            logger.info("Test case has timed out, setting fitness to max value " + fitness);
            return fitness;
        }
    }
    // First objective: achieve branch coverage
    logger.debug("Calculating branch fitness: ");
    double fitness = branchFitness.getFitness(individual);
    Set<Integer> touchedMutants = new LinkedHashSet<Integer>();
    Map<Mutation, Double> minMutantFitness = new LinkedHashMap<Mutation, Double>();
    // 0..1 -> propagation distance
    for (Integer mutantId : this.mutantMap.keySet()) {
        MutationTestFitness mutantFitness = mutantMap.get(mutantId);
        minMutantFitness.put(mutantFitness.getMutation(), 3.0);
    }
    int mutantsChecked = 0;
    int numKilled = removedMutants.size();
    Set<Integer> newKilled = new LinkedHashSet<Integer>();
    // Quicker tests first
    List<TestChromosome> executionOrder = prioritizeTests(suite);
    for (TestChromosome test : executionOrder) {
        ExecutionResult result = test.getLastExecutionResult();
        // use reflection for basic criteria, not for mutation
        if (result.calledReflection())
            continue;
        ExecutionTrace trace = result.getTrace();
        touchedMutants.addAll(trace.getTouchedMutants());
        logger.debug("Tests touched " + touchedMutants.size() + " mutants");
        Map<Integer, Double> touchedMutantsDistances = trace.getMutationDistances();
        if (touchedMutantsDistances.isEmpty()) {
            // if 'result' does not touch any mutant, no need to continue
            continue;
        }
        Iterator<Entry<Integer, MutationTestFitness>> it = this.mutantMap.entrySet().iterator();
        while (it.hasNext()) {
            Entry<Integer, MutationTestFitness> entry = it.next();
            int mutantID = entry.getKey();
            if (newKilled.contains(mutantID)) {
                continue;
            }
            MutationTestFitness goal = entry.getValue();
            if (MutationTimeoutStoppingCondition.isDisabled(goal.getMutation())) {
                logger.debug("Skipping timed out mutation " + goal.getMutation().getId());
                continue;
            }
            mutantsChecked++;
            double mutantInfectionDistance = 3.0;
            boolean hasBeenTouched = touchedMutantsDistances.containsKey(mutantID);
            if (hasBeenTouched) {
                // Infection happened, so we need to check propagation
                if (touchedMutantsDistances.get(mutantID) == 0.0) {
                    logger.debug("Executing test against mutant " + goal.getMutation());
                    // archive is updated by the TestFitnessFunction class
                    mutantInfectionDistance = goal.getFitness(test, result);
                } else {
                    // We can skip calling the test fitness function since we already know
                    // fitness is 1.0 (for propagation) + infection distance
                    mutantInfectionDistance = 1.0 + normalize(touchedMutantsDistances.get(mutantID));
                }
            } else {
                // archive is updated by the TestFitnessFunction class
                mutantInfectionDistance = goal.getFitness(test, result);
            }
            if (mutantInfectionDistance == 0.0) {
                numKilled++;
                newKilled.add(mutantID);
                // update list of covered goals
                result.test.addCoveredGoal(goal);
                // goal to not be considered by the next iteration of the evolutionary algorithm
                this.toRemoveMutants.add(mutantID);
            } else {
                minMutantFitness.put(goal.getMutation(), Math.min(mutantInfectionDistance, minMutantFitness.get(goal.getMutation())));
            }
        }
    }
    // logger.info("Fitness values for " + minMutantFitness.size() + " mutants");
    for (Double fit : minMutantFitness.values()) {
        fitness += fit;
    }
    logger.debug("Mutants killed: {}, Checked: {}, Goals: {})", numKilled, mutantsChecked, this.numMutants);
    updateIndividual(this, individual, fitness);
    assert numKilled == newKilled.size() + removedMutants.size();
    assert numKilled <= this.numMutants;
    double coverage = (double) numKilled / (double) this.numMutants;
    assert coverage >= 0.0 && coverage <= 1.0;
    suite.setCoverage(this, coverage);
    suite.setNumOfCoveredGoals(this, numKilled);
    return fitness;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ExecutionTrace(org.evosuite.testcase.execution.ExecutionTrace) ExecutionResult(org.evosuite.testcase.execution.ExecutionResult) LinkedHashMap(java.util.LinkedHashMap) Entry(java.util.Map.Entry) AbstractTestSuiteChromosome(org.evosuite.testsuite.AbstractTestSuiteChromosome) TestSuiteChromosome(org.evosuite.testsuite.TestSuiteChromosome) TestChromosome(org.evosuite.testcase.TestChromosome)

Example 4 with TestSuiteChromosome

use of org.evosuite.testsuite.TestSuiteChromosome in project evosuite by EvoSuite.

the class DSEStrategy method generateTests.

@Override
public TestSuiteChromosome generateTests() {
    LoggingUtils.getEvoLogger().info("* Setting up DSE test suite generation");
    long startTime = System.currentTimeMillis() / 1000;
    Properties.CRITERION = new Criterion[] { Properties.Criterion.BRANCH };
    // What's the search target
    List<TestSuiteFitnessFunction> fitnessFunctions = getFitnessFunctions();
    List<TestFitnessFunction> goals = getGoals(true);
    if (!canGenerateTestsForSUT()) {
        LoggingUtils.getEvoLogger().info("* Found no testable methods in the target class " + Properties.TARGET_CLASS);
        ClientServices.getInstance().getClientNode().trackOutputVariable(RuntimeVariable.Total_Goals, goals.size());
        return new TestSuiteChromosome();
    }
    /*
		 * Proceed with search if CRITERION=EXCEPTION, even if goals is empty
		 */
    TestSuiteChromosome testSuite = null;
    if (!(Properties.STOP_ZERO && goals.isEmpty()) || ArrayUtil.contains(Properties.CRITERION, Criterion.EXCEPTION)) {
        // Perform search
        LoggingUtils.getEvoLogger().info("* Using seed {}", Randomness.getSeed());
        LoggingUtils.getEvoLogger().info("* Starting evolution");
        ClientServices.getInstance().getClientNode().changeState(ClientState.SEARCH);
        testSuite = generateSuite();
    } else {
        zeroFitness.setFinished();
        testSuite = new TestSuiteChromosome();
        for (FitnessFunction<?> ff : fitnessFunctions) {
            testSuite.setCoverage(ff, 1.0);
        }
    }
    long endTime = System.currentTimeMillis() / 1000;
    // recalculated now after the search, eg to
    goals = getGoals(false);
    // handle exception fitness
    ClientServices.getInstance().getClientNode().trackOutputVariable(RuntimeVariable.Total_Goals, goals.size());
    // Newline after progress bar
    if (Properties.SHOW_PROGRESS)
        LoggingUtils.getEvoLogger().info("");
    if (!Properties.IS_RUNNING_A_SYSTEM_TEST) {
        // avoid printing time
        // related info in system
        // tests due to lack of
        // determinism
        LoggingUtils.getEvoLogger().info("* Search finished after " + (endTime - startTime) + "s and " + MaxStatementsStoppingCondition.getNumExecutedStatements() + " statements, best individual has fitness: " + testSuite.getFitness());
    }
    // Search is finished, send statistics
    sendExecutionStatistics();
    return testSuite;
}
Also used : TestFitnessFunction(org.evosuite.testcase.TestFitnessFunction) TestSuiteFitnessFunction(org.evosuite.testsuite.TestSuiteFitnessFunction) TestSuiteChromosome(org.evosuite.testsuite.TestSuiteChromosome)

Example 5 with TestSuiteChromosome

use of org.evosuite.testsuite.TestSuiteChromosome in project evosuite by EvoSuite.

the class RegressionSuiteStrategy method generateTests.

@Override
public TestSuiteChromosome generateTests() {
    track(RuntimeVariable.Total_Goals, 0);
    track(RuntimeVariable.Generated_Assertions, 0);
    track(RuntimeVariable.Coverage_Old, 0);
    track(RuntimeVariable.Coverage_New, 0);
    track(RuntimeVariable.Exception_Difference, 0);
    track(RuntimeVariable.State_Distance, 0);
    track(RuntimeVariable.Testsuite_Diversity, 0);
    // Disable test archive
    Properties.TEST_ARCHIVE = false;
    // Disable functional mocking stuff (due to incompatibilities)
    Properties.P_FUNCTIONAL_MOCKING = 0;
    Properties.FUNCTIONAL_MOCKING_INPUT_LIMIT = 0;
    Properties.FUNCTIONAL_MOCKING_PERCENT = 0;
    // Regression random strategy switch.
    if (Properties.REGRESSION_FITNESS == RegressionMeasure.RANDOM) {
        return generateRandomRegressionTests();
    }
    LoggingUtils.getEvoLogger().info("* Setting up search algorithm for REGRESSION suite generation");
    PropertiesSuiteGAFactory algorithmFactory = new PropertiesSuiteGAFactory();
    GeneticAlgorithm<?> algorithm = algorithmFactory.getSearchAlgorithm();
    if (Properties.SERIALIZE_GA || Properties.CLIENT_ON_THREAD) {
        TestGenerationResultBuilder.getInstance().setGeneticAlgorithm(algorithm);
    }
    long startTime = System.currentTimeMillis() / 1000;
    Properties.CRITERION = new Criterion[] { Criterion.REGRESSION };
    // What's the search target
    List<TestSuiteFitnessFunction> fitnessFunctions = getFitnessFunctions();
    // TODO: Argh, generics.
    algorithm.addFitnessFunctions((List) fitnessFunctions);
    if (ArrayUtil.contains(Properties.CRITERION, Criterion.DEFUSE) || ArrayUtil.contains(Properties.CRITERION, Criterion.ALLDEFS) || ArrayUtil.contains(Properties.CRITERION, Criterion.STATEMENT) || ArrayUtil.contains(Properties.CRITERION, Criterion.RHO) || ArrayUtil.contains(Properties.CRITERION, Criterion.AMBIGUITY)) {
        ExecutionTracer.enableTraceCalls();
    }
    // TODO: why it was only if "analyzing"???
    // if (analyzing)
    algorithm.resetStoppingConditions();
    List<TestFitnessFunction> goals = getGoals(true);
    // List<TestSuiteChromosome> bestSuites = new
    // ArrayList<TestSuiteChromosome>();
    TestSuiteChromosome bestSuites = new TestSuiteChromosome();
    RegressionTestSuiteChromosome best = null;
    if (!Properties.STOP_ZERO || !goals.isEmpty()) {
        // logger.warn("performing search ... ############################################################");
        // Perform search
        LoggingUtils.getEvoLogger().info("* Using seed {}", Randomness.getSeed());
        LoggingUtils.getEvoLogger().info("* Starting evolution");
        ClientServices.getInstance().getClientNode().changeState(ClientState.SEARCH);
        algorithm.generateSolution();
        best = (RegressionTestSuiteChromosome) algorithm.getBestIndividual();
        // ArrayList<TestSuiteChromosome>();
        for (TestCase t : best.getTests()) {
            bestSuites.addTest(t);
        }
        // bestSuites = (List<TestSuiteChromosome>) ga.getBestIndividuals();
        if (bestSuites.size() == 0) {
            LoggingUtils.getEvoLogger().warn("Could not find any suiteable chromosome");
            return bestSuites;
        }
    } else {
        zeroFitness.setFinished();
        bestSuites = new TestSuiteChromosome();
        for (FitnessFunction<?> ff : bestSuites.getFitnessValues().keySet()) {
            bestSuites.setCoverage(ff, 1.0);
        }
    }
    long end_time = System.currentTimeMillis() / 1000;
    // recalculated now after the search, eg to handle exception fitness
    goals = getGoals(false);
    track(RuntimeVariable.Total_Goals, goals.size());
    // Newline after progress bar
    if (Properties.SHOW_PROGRESS) {
        LoggingUtils.getEvoLogger().info("");
    }
    String text = " statements, best individual has fitness: ";
    if (bestSuites.size() > 1) {
        text = " statements, best individuals have fitness: ";
    }
    LoggingUtils.getEvoLogger().info("* Search finished after " + (end_time - startTime) + "s and " + algorithm.getAge() + " generations, " + MaxStatementsStoppingCondition.getNumExecutedStatements() + text + ((best != null) ? best.getFitness() : ""));
    if (Properties.COVERAGE) {
        for (Properties.Criterion pc : Properties.CRITERION) {
            // FIXME: can
            CoverageCriteriaAnalyzer.analyzeCoverage(bestSuites, pc);
        }
    // we send
    // all
    // bestSuites?
    }
    // progressMonitor.updateStatus(99);
    int number_of_test_cases = 0;
    int totalLengthOfTestCases = 0;
    double coverage = 0.0;
    // for (TestSuiteChromosome tsc : bestSuites) {
    number_of_test_cases += bestSuites.size();
    totalLengthOfTestCases += bestSuites.totalLengthOfTestCases();
    coverage += bestSuites.getCoverage();
    if (ArrayUtil.contains(Properties.CRITERION, Criterion.MUTATION) || ArrayUtil.contains(Properties.CRITERION, Criterion.STRONGMUTATION)) {
    // SearchStatistics.getInstance().mutationScore(coverage);
    }
    // StatisticsSender.executedAndThenSendIndividualToMaster(bestSuites);
    // // FIXME: can we send all bestSuites?
    // statistics.iteration(ga);
    // statistics.minimized(bestSuites.get(0)); // FIXME: can we send all
    // bestSuites?
    LoggingUtils.getEvoLogger().info("* Generated " + number_of_test_cases + " tests with total length " + totalLengthOfTestCases);
    // TODO: In the end we will only need one analysis technique
    if (!Properties.ANALYSIS_CRITERIA.isEmpty()) {
        // SearchStatistics.getInstance().addCoverage(Properties.CRITERION.toString(),
        // coverage);
        CoverageCriteriaAnalyzer.analyzeCriteria(bestSuites, Properties.ANALYSIS_CRITERIA);
    // FIXME: can we send all bestSuites?
    }
    LoggingUtils.getEvoLogger().info("* Resulting test suite's coverage: " + NumberFormat.getPercentInstance().format(coverage));
    algorithm.printBudget();
    return bestSuites;
}
Also used : TestFitnessFunction(org.evosuite.testcase.TestFitnessFunction) RegressionTestSuiteChromosome(org.evosuite.regression.RegressionTestSuiteChromosome) TestSuiteFitnessFunction(org.evosuite.testsuite.TestSuiteFitnessFunction) Properties(org.evosuite.Properties) TestCase(org.evosuite.testcase.TestCase) RegressionTestSuiteChromosome(org.evosuite.regression.RegressionTestSuiteChromosome) TestSuiteChromosome(org.evosuite.testsuite.TestSuiteChromosome) Criterion(org.evosuite.Properties.Criterion)

Aggregations

TestSuiteChromosome (org.evosuite.testsuite.TestSuiteChromosome)536 Test (org.junit.Test)430 EvoSuite (org.evosuite.EvoSuite)392 Properties (org.evosuite.Properties)78 OutputVariable (org.evosuite.statistics.OutputVariable)50 GenericSUTString (com.examples.with.different.packagename.generic.GenericSUTString)49 TestChromosome (org.evosuite.testcase.TestChromosome)47 BranchCoverageSuiteFitness (org.evosuite.coverage.branch.BranchCoverageSuiteFitness)44 TestCase (org.evosuite.testcase.TestCase)43 TestFitnessFunction (org.evosuite.testcase.TestFitnessFunction)30 DefaultTestCase (org.evosuite.testcase.DefaultTestCase)22 Ignore (org.junit.Ignore)19 ArrayList (java.util.ArrayList)17 DefaultLocalSearchObjective (org.evosuite.ga.localsearch.DefaultLocalSearchObjective)17 TestSuiteFitnessFunction (org.evosuite.testsuite.TestSuiteFitnessFunction)14 CheapPurityAnalyzer (org.evosuite.assertion.CheapPurityAnalyzer)13 LineCoverageSuiteFitness (org.evosuite.coverage.line.LineCoverageSuiteFitness)13 InstrumentingClassLoader (org.evosuite.instrumentation.InstrumentingClassLoader)13 ExecutionResult (org.evosuite.testcase.execution.ExecutionResult)10 Method (java.lang.reflect.Method)9