Search in sources :

Example 96 with TestCase

use of org.evosuite.testcase.TestCase in project evosuite by EvoSuite.

the class TestTestCaseExpander method testOneAssignments.

@Test
public void testOneAssignments() {
    Properties.PROJECT_PREFIX = "org.evosuite.testsuite";
    JUnitTestReader reader = new JUnitTestReader(null, new String[] { SRCDIR });
    TestCase testCase = reader.readJUnitTestCase(ArrayTestExample1.class.getName() + "#test4");
    testCase.clone();
    String code = testCase.toCode();
    TestCaseExpander expander = new TestCaseExpander();
    TestCase expandedTest = expander.expandTestCase(testCase);
    String expandedCode = expandedTest.toCode();
    Assert.assertEquals("Wrong length of test: " + expandedCode + ", original test: " + code, testCase.size() + 2, expandedTest.size());
    Assert.assertFalse(code.equals(expandedCode));
}
Also used : TestCase(org.evosuite.testcase.TestCase) JUnitTestReader(org.evosuite.junit.JUnitTestReader) Test(org.junit.Test)

Example 97 with TestCase

use of org.evosuite.testcase.TestCase in project evosuite by EvoSuite.

the class SequenceExtractor method extractSequences.

/**
 * Extracts execution sequences from JUnit tests which are located in the given package with respect to the given target classes.
 *
 * @param packageToBeConsidered  package to be scanned for JUnit tests
 * @param targetClasses          classes for which sequences shall be extracted
 *
 * @return carved sequences (TestCase)
 */
public static List<TestCase> extractSequences(final String packageToBeConsidered, final Class<?>... targetClasses) {
    if (packageToBeConsidered == null) {
        throw new NullPointerException("Name of the package to be considered must not be null");
    }
    if (targetClasses == null || targetClasses.length == 0) {
        throw new IllegalArgumentException("No targets for sequence extraction specified");
    }
    final Collection<String> classes = getPossibleCandidates(packageToBeConsidered);
    final ArrayList<TestCase> carvedSequences = new ArrayList<TestCase>();
    CarvingTestRunner testRunner;
    Class<?> clazz;
    TestCase carvedSequence;
    for (final String className : classes) {
        try {
            clazz = Class.forName(Utils.getClassNameFromResourcePath(className));
            if (isJUnitTestClass(clazz)) {
                try {
                    testRunner = new CarvingTestRunner(clazz, targetClasses);
                    // TODO is test result interesting?
                    testRunner.run(new RunNotifier());
                    carvedSequence = testRunner.getCarvedTest();
                    if (carvedSequence == null) {
                        logger.warn("For some reason, no carving took place for test class " + className);
                    } else {
                        carvedSequences.add(carvedSequence);
                    }
                } catch (final InitializationError e) {
                    logger.error("An error occurred while initializing CarvingTestRunner for test class " + className, e);
                }
            }
        } catch (final Throwable e) {
            logger.error("Couldn't get class instance of class " + className, e);
        }
    }
    return carvedSequences;
}
Also used : RunNotifier(org.junit.runner.notification.RunNotifier) TestCase(org.evosuite.testcase.TestCase) InitializationError(org.junit.runners.model.InitializationError) ArrayList(java.util.ArrayList)

Example 98 with TestCase

use of org.evosuite.testcase.TestCase in project evosuite by EvoSuite.

the class TestCaseCodeGenerator method generateCode.

// FIXME specifying classes here might not be needed anymore, if we only instrument observed classes...
public TestCase generateCode(final Class<?>... observedClasses) {
    if (observedClasses == null || observedClasses.length == 0) {
        throw new IllegalArgumentException("No observed classes specified");
    }
    // --- 1. step: extract class names
    final HashSet<String> observedClassNames = new HashSet<String>();
    for (int i = 0; i < observedClasses.length; i++) {
        observedClassNames.add(observedClasses[i].getName());
    }
    // --- 2. step: get all oids of the instances of the observed classes
    // NOTE: They are implicitly sorted by INIT_REC_NO because of the natural object creation order captured by the
    // instrumentation
    final TIntArrayList targetOIDs = new TIntArrayList();
    final int numInfoRecs = this.log.oidClassNames.size();
    for (int i = 0; i < numInfoRecs; i++) {
        if (observedClassNames.contains(this.log.oidClassNames.get(i))) {
            targetOIDs.add(this.log.oids.getQuick(i));
        }
    }
    // --- 3. step: init compilation unit
    final TestCase testCase = new DefaultTestCase();
    // no invocations on objects of observed classes -> return empty but compilable CompilationUnit
    if (targetOIDs.isEmpty()) {
        return testCase;
    }
    // --- 4. step: generating code starting with OID with lowest log rec no.
    final int numLogRecords = this.log.objectIds.size();
    int currentOID = targetOIDs.getQuick(0);
    int captureId = -1;
    // TODO knowing last logRecNo for termination criterion belonging to an observed instance would prevent processing unnecessary statements
    for (int currentRecord = this.log.oidRecMapping.get(currentOID); currentRecord < numLogRecords; currentRecord++) {
        currentOID = this.log.objectIds.getQuick(currentRecord);
        if (targetOIDs.contains(currentOID)) {
            this.restorceCodeFromLastPosTo(currentOID, currentRecord, testCase);
            // forward to end of method call sequence
            captureId = this.log.captureIds.getQuick(currentRecord);
            while (!(this.log.objectIds.getQuick(currentRecord) == currentOID && this.log.captureIds.getQuick(currentRecord) == captureId && this.log.methodNames.get(currentRecord).equals(CaptureLog.END_CAPTURE_PSEUDO_METHOD))) {
                currentRecord++;
            }
            // each method call is considered as object state modification -> so save last object modification
            log.updateWhereObjectWasInitializedFirst(currentOID, currentRecord);
        }
    }
    return testCase;
}
Also used : DefaultTestCase(org.evosuite.testcase.DefaultTestCase) TestCase(org.evosuite.testcase.TestCase) DefaultTestCase(org.evosuite.testcase.DefaultTestCase) TIntArrayList(gnu.trove.list.array.TIntArrayList) HashSet(java.util.HashSet)

Example 99 with TestCase

use of org.evosuite.testcase.TestCase in project evosuite by EvoSuite.

the class ReportGenerator method writeRunPage.

/**
 * Write a file for a particular run
 *
 * @param run
 *            a {@link org.evosuite.utils.ReportGenerator.StatisticEntry}
 *            object.
 * @return a {@link java.lang.String} object.
 */
protected String writeRunPage(StatisticEntry run) {
    StringBuffer sb = new StringBuffer();
    writeHTMLHeader(sb, run.className);
    sb.append("<div id=\"header\"><div id=\"logo\">");
    sb.append("<h2>");
    sb.append(run.className);
    sb.append(": ");
    sb.append(String.format("%.2f", 100.0 * run.covered_goals / run.total_goals));
    sb.append("%");
    sb.append("</h2></div></div>\n");
    sb.append("<p><a href=\"../report-generation.html\">Overview</a></p>\n");
    writeResultTable(sb, run);
    // writeMutationTable(sb);
    sb.append("<div id=\"page\"><div id=\"page-bgtop\"><div id=\"page-bgbtm\"><div id=\"content\">");
    sb.append("<div id=\"post\">");
    // Resulting test case
    sb.append("<h2 class=title>Test suite</h2>\n");
    if (run.tests != null) {
        int num = 0;
        for (TestCase test : run.tests) {
            sb.append("<h3>Test case ");
            sb.append(++num);
            sb.append("</h3>\n");
            /*
				 * if(test.exceptionThrown != null) { sb.append("<p>Raises:");
				 * sb.append(test.exceptionThrown); sb.append("</p>"); }
				 */
            sb.append("<pre class=\"prettyprint\" style=\"border: 1px solid #888;padding: 2px\">\n");
            int linecount = 1;
            String code = null;
            if (run.results.containsKey(test))
                code = test.toCode(run.results.get(test));
            else
                code = test.toCode();
            for (String line : code.split("\n")) {
                sb.append(String.format("<span class=\"nocode\"><a name=\"%d\">%3d: </a></span>", linecount, linecount));
                /*
					 * if(test.exceptionsThrown != null &&
					 * test.exception_statement == test_line)
					 * sb.append("<span style=\"background: #FF0000\">");
					 */
                sb.append(StringEscapeUtils.escapeHtml4(line));
                /*
					 * if(test.exceptionThrown != null &&
					 * test.exception_statement == test_line)
					 * sb.append("</span>");
					 */
                linecount++;
                sb.append("\n");
            }
            sb.append("</pre>\n");
        }
    } else {
        sb.append("No test cases generated");
    }
    sb.append("</div>");
    sb.append("<div id=\"post\">");
    // Chart of fitness
    if (Properties.PLOT) {
        if (run.fitness_history.isEmpty()) {
            sb.append("<h2>No fitness history</h2>\n");
        } else {
            String filename = writeDoubleChart(run.fitness_history, run.className + "-" + run.id, "Fitness");
            sb.append("<h2>Fitness</h2>\n");
            sb.append("<p>");
            sb.append("<img src=\"../img/");
            sb.append(filename);
            sb.append("\">");
            sb.append("</p>\n");
        }
        // Chart of size
        if (run.size_history.isEmpty()) {
            sb.append("<h2>No size history</h2>\n");
        } else {
            String filename = writeIntegerChart(run.size_history, run.className + "-" + run.id, "Size");
            sb.append("<h2>Size</h2>\n");
            sb.append("<p>");
            sb.append("<img src=\"../img/");
            sb.append(filename);
            sb.append("\">");
            sb.append("</p>\n");
        }
        // Chart of length
        if (run.length_history.isEmpty()) {
            sb.append("<h2>No length history</h2>\n");
        } else {
            String filename = writeIntegerChart(run.length_history, run.className + "-" + run.id, "Length");
            sb.append("<h2>Length</h2>\n");
            sb.append("<p>");
            sb.append("<img src=\"../img/");
            sb.append(filename);
            sb.append("\">");
            sb.append("</p>\n");
        }
        // Chart of average length
        if (run.average_length_history.isEmpty()) {
            sb.append("<h2>No average length history</h2>\n");
        } else {
            String filename = writeDoubleChart(run.average_length_history, run.className + "-" + run.id, "Length");
            sb.append("<h2>Average Length</h2>\n");
            sb.append("<p>");
            sb.append("<img src=\"../img/");
            sb.append(filename);
            sb.append("\">");
            sb.append("</p>\n");
        }
    }
    sb.append("</div>");
    sb.append("<div id=\"post\">");
    // Source code
    try {
        Iterable<String> source = html_analyzer.getClassContent(run.className);
        sb.append("<h2 class=title>Source Code</h2>\n");
        sb.append("<p>");
        sb.append("<pre class=\"prettyprint\" style=\"border: 1px solid #888;padding: 2px\">");
        int linecount = 1;
        for (String line : source) {
            sb.append(String.format("<span class=\"nocode\"><a name=\"%d\">%3d: </a></span>", linecount, linecount));
            if (run.coverage.contains(linecount)) {
                sb.append("<span style=\"background-color: #ffffcc\">");
                sb.append(StringEscapeUtils.escapeHtml4(line));
                sb.append("</span>");
            } else
                sb.append(StringEscapeUtils.escapeHtml4(line));
            sb.append("\n");
            linecount++;
        }
        sb.append("</pre>\n");
        sb.append("</p>\n");
    } catch (Exception e) {
    // Don't display source if there is an error
    }
    sb.append("</div>");
    sb.append("<div id=\"post\">");
    writeParameterTable(sb, run);
    sb.append("</div>");
    writeHTMLFooter(sb);
    String filename = "report-" + run.className + "-" + run.id + ".html";
    File file = new File(getReportDir().getAbsolutePath() + "/html/" + filename);
    Utils.writeFile(sb.toString(), file);
    // return file.getAbsolutePath();
    return filename;
}
Also used : TestCase(org.evosuite.testcase.TestCase) File(java.io.File) NoSuchParameterException(org.evosuite.Properties.NoSuchParameterException) IOException(java.io.IOException)

Example 100 with TestCase

use of org.evosuite.testcase.TestCase in project evosuite by EvoSuite.

the class TestCoverageGoalNameGeneration method testTwoOutputGoals.

@Test
public void testTwoOutputGoals() {
    TestCase test = new DefaultTestCase();
    OutputCoverageGoal outputGoal1 = new OutputCoverageGoal("FooClass", "toString", stringType(), STRING_EMPTY);
    OutputCoverageTestFitness goal1 = new OutputCoverageTestFitness(outputGoal1);
    OutputCoverageGoal outputGoal2 = new OutputCoverageGoal("FooClass", "bar", objectType(), REF_NONNULL);
    OutputCoverageTestFitness goal2 = new OutputCoverageTestFitness(outputGoal2);
    test.addCoveredGoal(goal1);
    test.addCoveredGoal(goal2);
    List<TestCase> tests = new ArrayList<>();
    tests.add(test);
    CoverageGoalTestNameGenerationStrategy naming = new CoverageGoalTestNameGenerationStrategy(tests);
    String generatedName = naming.getName(test);
    assertEquals("testBarReturningNonNullAndToStringReturningEmptyString", generatedName);
}
Also used : TestCase(org.evosuite.testcase.TestCase) DefaultTestCase(org.evosuite.testcase.DefaultTestCase) CoverageGoalTestNameGenerationStrategy(org.evosuite.junit.naming.methods.CoverageGoalTestNameGenerationStrategy) ArrayList(java.util.ArrayList) DefaultTestCase(org.evosuite.testcase.DefaultTestCase) OutputCoverageTestFitness(org.evosuite.coverage.io.output.OutputCoverageTestFitness) OutputCoverageGoal(org.evosuite.coverage.io.output.OutputCoverageGoal) Test(org.junit.Test)

Aggregations

TestCase (org.evosuite.testcase.TestCase)192 Test (org.junit.Test)119 DefaultTestCase (org.evosuite.testcase.DefaultTestCase)90 ArrayList (java.util.ArrayList)67 CoverageGoalTestNameGenerationStrategy (org.evosuite.junit.naming.methods.CoverageGoalTestNameGenerationStrategy)47 MethodCoverageTestFitness (org.evosuite.coverage.method.MethodCoverageTestFitness)45 TestSuiteChromosome (org.evosuite.testsuite.TestSuiteChromosome)43 IntPrimitiveStatement (org.evosuite.testcase.statements.numeric.IntPrimitiveStatement)39 VariableReference (org.evosuite.testcase.variable.VariableReference)26 OutputCoverageGoal (org.evosuite.coverage.io.output.OutputCoverageGoal)25 OutputCoverageTestFitness (org.evosuite.coverage.io.output.OutputCoverageTestFitness)25 TestFitnessFunction (org.evosuite.testcase.TestFitnessFunction)24 BranchCoverageSuiteFitness (org.evosuite.coverage.branch.BranchCoverageSuiteFitness)17 TestChromosome (org.evosuite.testcase.TestChromosome)17 InstrumentingClassLoader (org.evosuite.instrumentation.InstrumentingClassLoader)15 Ignore (org.junit.Ignore)15 VariableReferenceImpl (org.evosuite.testcase.variable.VariableReferenceImpl)14 GenericMethod (org.evosuite.utils.generic.GenericMethod)12 ExceptionCoverageTestFitness (org.evosuite.coverage.exception.ExceptionCoverageTestFitness)11 InputCoverageGoal (org.evosuite.coverage.io.input.InputCoverageGoal)10