Search in sources :

Example 16 with MethodStatement

use of org.evosuite.testcase.statements.MethodStatement in project evosuite by EvoSuite.

the class RegressionSuiteMinimizer method removeDuplicateAssertions.

private void removeDuplicateAssertions(RegressionTestSuiteChromosome suite) {
    Iterator<TestChromosome> it = suite.getTestChromosomes().iterator();
    Map<String, List<String>> uniqueAssertions = new HashMap<String, List<String>>();
    // int i = -1;
    while (it.hasNext()) {
        // i++;
        RegressionTestChromosome test = (RegressionTestChromosome) it.next();
        boolean changed = false;
        boolean hadAssertion = false;
        // keep track of new unique assertions, and if not unique, remove the assertion
        for (Assertion a : test.getTheTest().getTestCase().getAssertions()) {
            String aClass = a.getClass().getSimpleName();
            List<String> aTypes = uniqueAssertions.get(aClass);
            if (aTypes == null) {
                aTypes = new ArrayList<String>();
            }
            String aType = "";
            if (a instanceof InspectorAssertion) {
                InspectorAssertion ia = (InspectorAssertion) a;
                try {
                    aType = ia.getInspector().getMethod().getName();
                } catch (NullPointerException e) {
                    // technically this should not happen
                    Statement s = ia.getStatement();
                    if (s instanceof MethodStatement) {
                        aType = ((MethodStatement) s).getMethod().getName();
                    }
                }
            }
            if (aTypes.contains(aType)) {
                // logger.warn("removing non-unique assertion: {}-{}", aClass, aType);
                changed = true;
                a.getStatement().getPosition();
                test.getTheTest().getTestCase().removeAssertion(a);
                continue;
            }
            aTypes.add(aType);
            uniqueAssertions.put(aClass, aTypes);
            hadAssertion = true;
        }
        if (changed) {
            test.updateClassloader();
        }
    }
    if (uniqueAssertions.size() > 0) {
        logger.warn("unique assertions: {}", uniqueAssertions);
    }
}
Also used : MethodStatement(org.evosuite.testcase.statements.MethodStatement) InspectorAssertion(org.evosuite.assertion.InspectorAssertion) HashMap(java.util.HashMap) Statement(org.evosuite.testcase.statements.Statement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) Assertion(org.evosuite.assertion.Assertion) InspectorAssertion(org.evosuite.assertion.InspectorAssertion) ArrayList(java.util.ArrayList) List(java.util.List) TestChromosome(org.evosuite.testcase.TestChromosome)

Example 17 with MethodStatement

use of org.evosuite.testcase.statements.MethodStatement in project evosuite by EvoSuite.

the class ClassReInitializer method getMoreClassesToReset.

/*
	 * TODO: I think this would be nicer if each type of statement registered
	 * the classes to reset as part of their execute() method
	 */
private static HashSet<String> getMoreClassesToReset(TestCase tc, ExecutionResult result) {
    HashSet<String> moreClassesForStaticReset = new HashSet<String>();
    for (int position = 0; position < result.getExecutedStatements(); position++) {
        Statement statement = tc.getStatement(position);
        // If we reset also after reads, get all fields
        if (Properties.RESET_STATIC_FIELD_GETS) {
            for (VariableReference var : statement.getVariableReferences()) {
                if (var.isFieldReference()) {
                    FieldReference fieldReference = (FieldReference) var;
                    moreClassesForStaticReset.add(fieldReference.getField().getOwnerClass().getClassName());
                }
            }
        }
        // Check for explicit assignments to static fields
        if (statement.isAssignmentStatement()) {
            if (statement.getReturnValue() instanceof FieldReference) {
                FieldReference fieldReference = (FieldReference) statement.getReturnValue();
                if (fieldReference.getField().isStatic()) {
                    moreClassesForStaticReset.add(fieldReference.getField().getOwnerClass().getClassName());
                }
            }
        } else if (statement instanceof FieldStatement) {
            // Check if we are invoking a non-pure method on a static field
            // variable
            FieldStatement fieldStatement = (FieldStatement) statement;
            if (fieldStatement.getField().isStatic()) {
                VariableReference fieldReference = fieldStatement.getReturnValue();
                if (Properties.RESET_STATIC_FIELD_GETS) {
                    moreClassesForStaticReset.add(fieldStatement.getField().getOwnerClass().getClassName());
                } else {
                    // Check if the field was passed to a non-pure method
                    for (int i = fieldStatement.getPosition() + 1; i < result.getExecutedStatements(); i++) {
                        Statement invokedStatement = tc.getStatement(i);
                        if (invokedStatement.references(fieldReference)) {
                            if (invokedStatement instanceof MethodStatement) {
                                if (fieldReference.equals(((MethodStatement) invokedStatement).getCallee())) {
                                    if (!CheapPurityAnalyzer.getInstance().isPure(((MethodStatement) invokedStatement).getMethod().getMethod())) {
                                        moreClassesForStaticReset.add(fieldStatement.getField().getOwnerClass().getClassName());
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else if (statement instanceof PrivateFieldStatement) {
            PrivateFieldStatement fieldStatement = (PrivateFieldStatement) statement;
            if (fieldStatement.isStaticField()) {
                moreClassesForStaticReset.add(fieldStatement.getOwnerClassName());
            }
        }
    }
    return moreClassesForStaticReset;
}
Also used : MethodStatement(org.evosuite.testcase.statements.MethodStatement) FieldReference(org.evosuite.testcase.variable.FieldReference) VariableReference(org.evosuite.testcase.variable.VariableReference) Statement(org.evosuite.testcase.statements.Statement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) FieldStatement(org.evosuite.testcase.statements.FieldStatement) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) FieldStatement(org.evosuite.testcase.statements.FieldStatement) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) HashSet(java.util.HashSet)

Example 18 with MethodStatement

use of org.evosuite.testcase.statements.MethodStatement in project evosuite by EvoSuite.

the class Issre13SystemTest method testOnSpecificTest.

@Test
public void testOnSpecificTest() throws ClassNotFoundException, ConstructionFailedException, NoSuchMethodException, SecurityException {
    Properties.TARGET_CLASS = DseBar.class.getCanonicalName();
    // force using DSE
    Properties.DSE_PROBABILITY = 1.0;
    Class<?> sut = TestGenerationContext.getInstance().getClassLoaderForSUT().loadClass(Properties.TARGET_CLASS);
    Class<?> fooClass = TestGenerationContext.getInstance().getClassLoaderForSUT().loadClass(DseFoo.class.getCanonicalName());
    GenericClass clazz = new GenericClass(sut);
    DefaultTestCase test = new DefaultTestCase();
    // String string0 = "baz5";
    VariableReference stringVar = test.addStatement(new StringPrimitiveStatement(test, "baz5"));
    // DseFoo dseFoo0 = new DseFoo();
    GenericConstructor fooConstructor = new GenericConstructor(fooClass.getConstructors()[0], fooClass);
    ConstructorStatement fooConstructorStatement = new ConstructorStatement(test, fooConstructor, Arrays.asList(new VariableReference[] {}));
    VariableReference fooVar = test.addStatement(fooConstructorStatement);
    Method fooIncMethod = fooClass.getMethod("inc", new Class<?>[] {});
    GenericMethod incMethod = new GenericMethod(fooIncMethod, fooClass);
    test.addStatement(new MethodStatement(test, incMethod, fooVar, Arrays.asList(new VariableReference[] {})));
    test.addStatement(new MethodStatement(test, incMethod, fooVar, Arrays.asList(new VariableReference[] {})));
    test.addStatement(new MethodStatement(test, incMethod, fooVar, Arrays.asList(new VariableReference[] {})));
    test.addStatement(new MethodStatement(test, incMethod, fooVar, Arrays.asList(new VariableReference[] {})));
    test.addStatement(new MethodStatement(test, incMethod, fooVar, Arrays.asList(new VariableReference[] {})));
    // DseBar dseBar0 = new DseBar(string0);
    GenericConstructor gc = new GenericConstructor(clazz.getRawClass().getConstructors()[0], clazz);
    ConstructorStatement constructorStatement = new ConstructorStatement(test, gc, Arrays.asList(new VariableReference[] { stringVar }));
    VariableReference callee = test.addStatement(constructorStatement);
    // dseBar0.coverMe(dseFoo0);
    Method m = clazz.getRawClass().getMethod("coverMe", new Class<?>[] { fooClass });
    GenericMethod method = new GenericMethod(m, sut);
    MethodStatement ms = new MethodStatement(test, method, callee, Arrays.asList(new VariableReference[] { fooVar }));
    test.addStatement(ms);
    System.out.println(test);
    TestSuiteChromosome suite = new TestSuiteChromosome();
    BranchCoverageSuiteFitness fitness = new BranchCoverageSuiteFitness();
    BranchCoverageMap.getInstance().searchStarted(null);
    assertEquals(4.0, fitness.getFitness(suite), 0.1F);
    suite.addTest(test);
    assertEquals(1.0, fitness.getFitness(suite), 0.1F);
    System.out.println("Test suite: " + suite);
    TestSuiteLocalSearch localSearch = TestSuiteLocalSearch.selectTestSuiteLocalSearch();
    LocalSearchObjective<TestSuiteChromosome> localObjective = new DefaultLocalSearchObjective<TestSuiteChromosome>();
    localObjective.addFitnessFunction(fitness);
    localSearch.doSearch(suite, localObjective);
    System.out.println("Fitness: " + fitness.getFitness(suite));
    System.out.println("Test suite: " + suite);
    assertEquals(0.0, fitness.getFitness(suite), 0.1F);
    BranchCoverageMap.getInstance().searchFinished(null);
}
Also used : ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) StringPrimitiveStatement(org.evosuite.testcase.statements.StringPrimitiveStatement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) BranchCoverageSuiteFitness(org.evosuite.coverage.branch.BranchCoverageSuiteFitness) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) DefaultTestCase(org.evosuite.testcase.DefaultTestCase) GenericMethod(org.evosuite.utils.generic.GenericMethod) Method(java.lang.reflect.Method) GenericMethod(org.evosuite.utils.generic.GenericMethod) DseBar(com.examples.with.different.packagename.localsearch.DseBar) TestSuiteLocalSearch(org.evosuite.testsuite.localsearch.TestSuiteLocalSearch) DefaultLocalSearchObjective(org.evosuite.ga.localsearch.DefaultLocalSearchObjective) GenericClass(org.evosuite.utils.generic.GenericClass) TestSuiteChromosome(org.evosuite.testsuite.TestSuiteChromosome) DseFoo(com.examples.with.different.packagename.localsearch.DseFoo) Test(org.junit.Test)

Example 19 with MethodStatement

use of org.evosuite.testcase.statements.MethodStatement in project evosuite by EvoSuite.

the class ComparisonTraceObserver method visit.

/* (non-Javadoc)
	 * @see org.evosuite.assertion.AssertionTraceObserver#visit(org.evosuite.testcase.StatementInterface, org.evosuite.testcase.Scope, org.evosuite.testcase.VariableReference)
	 */
/**
 * {@inheritDoc}
 */
@Override
protected void visit(Statement statement, Scope scope, VariableReference var) {
    try {
        Object object = var.getObject(scope);
        if (object == null)
            return;
        if (statement instanceof AssignmentStatement)
            return;
        if (statement instanceof PrimitiveStatement<?>)
            return;
        ComparisonTraceEntry entry = new ComparisonTraceEntry(var);
        int position = statement.getPosition();
        for (VariableReference other : scope.getElements(var.getType())) {
            Object otherObject = other.getObject(scope);
            // TODO: Create a matrix of object comparisons?
            if (otherObject == null)
                // TODO: Don't do this?
                continue;
            if (object == otherObject)
                // Don't compare with self?
                continue;
            int otherPos = other.getStPosition();
            if (otherPos >= position)
                // Don't compare with variables that are not defined - may happen with primitives?
                continue;
            Statement otherStatement = currentTest.getStatement(otherPos);
            if (statement instanceof PrimitiveStatement && otherStatement instanceof PrimitiveStatement)
                // Don't compare two primitives
                continue;
            if (otherStatement instanceof MethodStatement) {
                if (((MethodStatement) otherStatement).getMethodName().equals("hashCode"))
                    // No comparison against hashCode, as the hashCode return value will not be in the test
                    continue;
            }
            if (Properties.PURE_EQUALS) {
                String className = object.getClass().getCanonicalName();
                String methodName = "equals";
                String descriptor = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class));
                CheapPurityAnalyzer cheapPurityAnalyzer = CheapPurityAnalyzer.getInstance();
                if (!cheapPurityAnalyzer.isPure(className, methodName, descriptor))
                    // Don't compare using impure equals(Object) methods
                    continue;
            }
            try {
                logger.debug("Comparison of " + var + " with " + other + " is: " + object.equals(otherObject));
                entry.addEntry(other, ComparisonTraceEntry.equals(object, otherObject));
            } catch (Throwable t) {
                logger.debug("Exception during equals: " + t);
            // ignore?
            }
            if (object instanceof Comparable<?>) {
            // TODO
            }
        }
        trace.addEntry(statement.getPosition(), var, entry);
    } catch (CodeUnderTestException e) {
        logger.debug("", e);
    }
}
Also used : MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) Statement(org.evosuite.testcase.statements.Statement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) AssignmentStatement(org.evosuite.testcase.statements.AssignmentStatement) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) AssignmentStatement(org.evosuite.testcase.statements.AssignmentStatement)

Example 20 with MethodStatement

use of org.evosuite.testcase.statements.MethodStatement in project evosuite by EvoSuite.

the class ContainsTraceObserver method visit.

/* (non-Javadoc)
	 * @see org.evosuite.assertion.AssertionTraceObserver#visit(org.evosuite.testcase.StatementInterface, org.evosuite.testcase.Scope, org.evosuite.testcase.VariableReference)
	 */
/**
 * {@inheritDoc}
 */
@Override
protected void visit(Statement statement, Scope scope, VariableReference var) {
    try {
        Object object = var.getObject(scope);
        if (object == null)
            return;
        if (statement instanceof AssignmentStatement)
            return;
        if (statement instanceof PrimitiveStatement<?>)
            return;
        // Only relevant for Collections
        if (!(object instanceof Collection))
            return;
        Collection collectionObject = (Collection) object;
        List<GenericClass> parameterClasses = var.getGenericClass().getParameterClasses();
        // Need to know exact type
        if (parameterClasses.size() != 1)
            return;
        java.lang.reflect.Type parameterType = parameterClasses.get(0).getType();
        ContainsTraceEntry entry = new ContainsTraceEntry(var);
        int position = statement.getPosition();
        Set<VariableReference> otherVariables = new LinkedHashSet<>();
        otherVariables.addAll(scope.getElements(parameterType));
        for (int i = 0; i <= statement.getPosition(); i++) {
            for (VariableReference candidateVar : currentTest.getStatement(i).getVariableReferences()) {
                if (candidateVar instanceof ConstantValue && candidateVar.isAssignableTo(parameterType)) {
                    otherVariables.add(candidateVar);
                }
            }
        }
        for (VariableReference other : otherVariables) {
            Object otherObject;
            if (other instanceof ConstantValue)
                otherObject = ((ConstantValue) other).getValue();
            else
                otherObject = other.getObject(scope);
            if (otherObject == null)
                // TODO: Don't do this?
                continue;
            int otherPos = other.getStPosition();
            if (otherPos > position)
                // Don't compare with variables that are not defined - may happen with primitives?
                continue;
            Statement otherStatement = currentTest.getStatement(otherPos);
            if (otherStatement instanceof MethodStatement) {
                if (((MethodStatement) otherStatement).getMethodName().equals("hashCode"))
                    // No comparison against hashCode, as the hashCode return value will not be in the test
                    continue;
            }
            try {
                logger.debug("Checking whether {} contains {} is: {}", var, other, collectionObject.contains(otherObject));
                entry.addEntry(other, collectionObject.contains(otherObject));
            } catch (Throwable t) {
                logger.debug("Exception during equals: " + t);
            // ignore?
            }
            if (object instanceof Comparable<?>) {
            // TODO
            }
        }
        trace.addEntry(statement.getPosition(), var, entry);
    } catch (CodeUnderTestException e) {
        logger.debug("", e);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) Statement(org.evosuite.testcase.statements.Statement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) AssignmentStatement(org.evosuite.testcase.statements.AssignmentStatement) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) AssignmentStatement(org.evosuite.testcase.statements.AssignmentStatement) GenericClass(org.evosuite.utils.generic.GenericClass) Collection(java.util.Collection) ConstantValue(org.evosuite.testcase.variable.ConstantValue)

Aggregations

MethodStatement (org.evosuite.testcase.statements.MethodStatement)54 VariableReference (org.evosuite.testcase.variable.VariableReference)40 GenericMethod (org.evosuite.utils.generic.GenericMethod)29 Method (java.lang.reflect.Method)25 ConstructorStatement (org.evosuite.testcase.statements.ConstructorStatement)22 GenericConstructor (org.evosuite.utils.generic.GenericConstructor)22 Statement (org.evosuite.testcase.statements.Statement)19 GenericClass (org.evosuite.utils.generic.GenericClass)15 DefaultTestCase (org.evosuite.testcase.DefaultTestCase)11 IntPrimitiveStatement (org.evosuite.testcase.statements.numeric.IntPrimitiveStatement)10 ArrayList (java.util.ArrayList)9 Test (org.junit.Test)8 TestCase (org.evosuite.testcase.TestCase)7 CodeUnderTestException (org.evosuite.testcase.execution.CodeUnderTestException)5 FieldStatement (org.evosuite.testcase.statements.FieldStatement)5 StringPrimitiveStatement (org.evosuite.testcase.statements.StringPrimitiveStatement)5 HashSet (java.util.HashSet)4 TestFactory (org.evosuite.testcase.TestFactory)4 AssignmentStatement (org.evosuite.testcase.statements.AssignmentStatement)4 PrimitiveStatement (org.evosuite.testcase.statements.PrimitiveStatement)4