Search in sources :

Example 36 with MethodStatement

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

the class ContractViolation method resultsFromMethod.

public boolean resultsFromMethod(String methodName) {
    if (statement instanceof MethodStatement) {
        MethodStatement ms = (MethodStatement) statement;
        String target = ms.getMethodName() + ms.getDescriptor();
        return target.equals(methodName);
    } else if (statement instanceof ConstructorStatement) {
        return methodName.startsWith("<init>");
    } else {
        return false;
    }
}
Also used : ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) MethodStatement(org.evosuite.testcase.statements.MethodStatement)

Example 37 with MethodStatement

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

the class ContractViolation method same.

/**
 * Determine if we have already seen an instance of this violation
 *
 * @param other
 *            a {@link org.evosuite.contracts.ContractViolation} object.
 * @return a boolean.
 */
public boolean same(ContractViolation other) {
    // Same contract?
    if (!contract.getClass().equals(other.contract.getClass()))
        return false;
    // Same type of statement?
    if (!statement.getClass().equals(other.statement.getClass()))
        return false;
    // Same exception type?
    if (exception != null && other.exception != null) {
        if (!exception.getClass().equals(other.exception.getClass()))
            return false;
    }
    // Same method call / constructor?
    if (statement instanceof MethodStatement) {
        MethodStatement ms1 = (MethodStatement) statement;
        MethodStatement ms2 = (MethodStatement) other.statement;
        if (ms1.getMethod().getMethod().equals(ms2.getMethod().getMethod())) {
            return true;
        }
    } else if (statement instanceof ConstructorStatement) {
        ConstructorStatement ms1 = (ConstructorStatement) statement;
        ConstructorStatement ms2 = (ConstructorStatement) other.statement;
        if (ms1.getConstructor().getConstructor().equals(ms2.getConstructor().getConstructor())) {
            return true;
        }
    } else if (statement instanceof AssignmentStatement) {
        VariableReference var1 = statement.getReturnValue();
        VariableReference var2 = other.statement.getReturnValue();
        if (var1 instanceof FieldReference && var2 instanceof FieldReference) {
            if (((FieldReference) var1).getField().getField().equals(((FieldReference) var2).getField().getField()))
                return true;
        }
    }
    return false;
}
Also used : ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) FieldReference(org.evosuite.testcase.variable.FieldReference) VariableReference(org.evosuite.testcase.variable.VariableReference) AssignmentStatement(org.evosuite.testcase.statements.AssignmentStatement)

Example 38 with MethodStatement

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

the class EqualsHashcodeContract method addAssertionAndComments.

@Override
public void addAssertionAndComments(Statement statement, List<VariableReference> variables, Throwable exception) {
    TestCase test = statement.getTestCase();
    VariableReference a = variables.get(0);
    VariableReference b = variables.get(1);
    try {
        Method equalsMethod = a.getGenericClass().getRawClass().getMethod("equals", new Class<?>[] { Object.class });
        Method hashCodeMethod = a.getGenericClass().getRawClass().getMethod("hashCode", new Class<?>[] {});
        GenericMethod genericEqualsMethod = new GenericMethod(equalsMethod, a.getGenericClass());
        GenericMethod genericHashCodeMethod = new GenericMethod(hashCodeMethod, a.getGenericClass());
        // Create x = a.equals(b)
        Statement st1 = new MethodStatement(test, genericEqualsMethod, a, Arrays.asList(new VariableReference[] { b }));
        VariableReference x = test.addStatement(st1, statement.getPosition() + 1);
        // Create y = a.hashCode();
        Statement st2 = new MethodStatement(test, genericHashCodeMethod, a, Arrays.asList(new VariableReference[] {}));
        VariableReference y = test.addStatement(st2, statement.getPosition() + 2);
        // Create z = b.hashCode();
        Statement st3 = new MethodStatement(test, genericHashCodeMethod, b, Arrays.asList(new VariableReference[] {}));
        VariableReference z = test.addStatement(st3, statement.getPosition() + 3);
        // Create w = z == z
        VariableReference w = new VariableReferenceImpl(test, boolean.class);
        PrimitiveExpression exp = new PrimitiveExpression(test, w, y, Operator.EQUALS, z);
        w = test.addStatement(exp, statement.getPosition() + 4);
        Statement newStatement = test.getStatement(w.getStPosition());
        // Create assertEquals(x, w)
        EqualsAssertion assertion = new EqualsAssertion();
        assertion.setStatement(newStatement);
        assertion.setSource(x);
        assertion.setDest(w);
        assertion.setValue(true);
        newStatement.addAssertion(assertion);
        newStatement.addComment("Violates contract equals - hashcode");
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) TestCase(org.evosuite.testcase.TestCase) Statement(org.evosuite.testcase.statements.Statement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReferenceImpl(org.evosuite.testcase.variable.VariableReferenceImpl) GenericMethod(org.evosuite.utils.generic.GenericMethod) Method(java.lang.reflect.Method) GenericMethod(org.evosuite.utils.generic.GenericMethod) PrimitiveExpression(org.evosuite.testcase.statements.PrimitiveExpression) EqualsAssertion(org.evosuite.assertion.EqualsAssertion)

Example 39 with MethodStatement

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

the class ToStringReturnsNormallyContract method addAssertionAndComments.

@Override
public void addAssertionAndComments(Statement statement, List<VariableReference> variables, Throwable exception) {
    TestCase test = statement.getTestCase();
    int position = statement.getPosition();
    VariableReference a = variables.get(0);
    try {
        Method hashCodeMethod = a.getGenericClass().getRawClass().getMethod("toString", new Class<?>[] {});
        GenericMethod method = new GenericMethod(hashCodeMethod, a.getGenericClass());
        Statement st1 = new MethodStatement(test, method, a, Arrays.asList(new VariableReference[] {}));
        test.addStatement(st1, position + 1);
        st1.addComment("Throws exception: " + exception.getMessage());
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) TestCase(org.evosuite.testcase.TestCase) Statement(org.evosuite.testcase.statements.Statement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) GenericMethod(org.evosuite.utils.generic.GenericMethod) Method(java.lang.reflect.Method) GenericMethod(org.evosuite.utils.generic.GenericMethod)

Example 40 with MethodStatement

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

the class SimpleMutationAssertionGenerator method addAssertions.

/**
 * Add assertions to current test set for given set of mutants
 *
 * @param test
 *            a {@link org.evosuite.testcase.TestCase} object.
 * @param killed
 *            a {@link java.util.Set} object.
 * @param mutants
 *            a {@link java.util.Map} object.
 */
private void addAssertions(TestCase test, Set<Integer> killed, Map<Integer, Mutation> mutants) {
    if (test.isEmpty())
        return;
    logger.debug("Generating assertions");
    int s1 = killed.size();
    logger.debug("Running on original");
    ExecutionResult origResult = runTest(test);
    if (origResult.hasTimeout() || origResult.hasTestException()) {
        logger.debug("Skipping test, as it has timeouts or exceptions");
        return;
    }
    Map<Mutation, List<OutputTrace<?>>> mutationTraces = new HashMap<Mutation, List<OutputTrace<?>>>();
    List<Mutation> executedMutants = new ArrayList<Mutation>();
    for (Integer mutationId : origResult.getTrace().getTouchedMutants()) {
        if (!mutants.containsKey(mutationId)) {
        // logger.warn("Mutation ID unknown: " + mutationId);
        // logger.warn(mutants.keySet().toString());
        } else
            executedMutants.add(mutants.get(mutationId));
    }
    Randomness.shuffle(executedMutants);
    logger.debug("Executed mutants: " + origResult.getTrace().getTouchedMutants());
    int numExecutedMutants = 0;
    for (Mutation m : executedMutants) {
        numExecutedMutants++;
        if (!TimeController.getInstance().isThereStillTimeInThisPhase()) {
            logger.info("Reached maximum time to generate assertions!");
            break;
        }
        assert (m != null);
        if (MutationTimeoutStoppingCondition.isDisabled(m)) {
            killed.add(m.getId());
            continue;
        }
        if (timedOutMutations.containsKey(m)) {
            if (timedOutMutations.get(m) >= Properties.MUTATION_TIMEOUTS) {
                logger.debug("Skipping timed out mutant");
                killed.add(m.getId());
                continue;
            }
        }
        if (exceptionMutations.containsKey(m)) {
            if (exceptionMutations.get(m) >= Properties.MUTATION_TIMEOUTS) {
                logger.debug("Skipping mutant with exceptions");
                killed.add(m.getId());
                continue;
            }
        }
        if (Properties.MAX_MUTANTS_PER_TEST > 0 && numExecutedMutants > Properties.MAX_MUTANTS_PER_TEST)
            break;
        /*
			if (killed.contains(m.getId())) {
				logger.info("Skipping dead mutant");
				continue;
			}
			*/
        logger.debug("Running test on mutation {}", m.getMutationName());
        ExecutionResult mutantResult = runTest(test, m);
        int numKilled = 0;
        for (Class<?> observerClass : observerClasses) {
            if (mutantResult.getTrace(observerClass) == null || origResult.getTrace(observerClass) == null)
                continue;
            numKilled += origResult.getTrace(observerClass).getAssertions(test, mutantResult.getTrace(observerClass));
        }
        List<OutputTrace<?>> traces = new ArrayList<OutputTrace<?>>(mutantResult.getTraces());
        mutationTraces.put(m, traces);
        if (mutantResult.hasTimeout()) {
            logger.debug("Increasing timeout count!");
            if (!timedOutMutations.containsKey(m)) {
                timedOutMutations.put(m, 1);
            } else {
                timedOutMutations.put(m, timedOutMutations.get(m) + 1);
            }
            MutationTimeoutStoppingCondition.timeOut(m);
        } else if (!mutantResult.noThrownExceptions() && origResult.noThrownExceptions()) {
            logger.debug("Increasing exception count.");
            if (!exceptionMutations.containsKey(m)) {
                exceptionMutations.put(m, 1);
            } else {
                exceptionMutations.put(m, exceptionMutations.get(m) + 1);
            }
            MutationTimeoutStoppingCondition.raisedException(m);
        }
        if (numKilled > 0 || mutantResult.hasTimeout() || (!mutantResult.noThrownExceptions() && origResult.noThrownExceptions())) {
            killed.add(m.getId());
        }
    }
    List<Assertion> assertions = test.getAssertions();
    logger.info("Got " + assertions.size() + " assertions");
    Map<Integer, Set<Integer>> killMap = new HashMap<Integer, Set<Integer>>();
    int num = 0;
    for (Assertion assertion : assertions) {
        Set<Integer> killedMutations = new HashSet<Integer>();
        for (Mutation m : executedMutants) {
            boolean isKilled = false;
            if (mutationTraces.containsKey(m)) {
                for (OutputTrace<?> trace : mutationTraces.get(m)) {
                    if (trace.isDetectedBy(assertion)) {
                        isKilled = true;
                        break;
                    }
                }
            }
            if (isKilled) {
                killedMutations.add(m.getId());
                assertion.addKilledMutation(m);
            }
        }
        killMap.put(num, killedMutations);
        // logger.info("Assertion " + num + " kills mutants " + killedMutations);
        num++;
    }
    int killedBefore = getNumKilledMutants(test, mutationTraces, executedMutants);
    logger.debug("Need to kill mutants: " + killedBefore);
    logger.debug(killMap.toString());
    minimize(test, executedMutants, assertions, killMap);
    int killedAfter = getNumKilledMutants(test, mutationTraces, executedMutants);
    int s2 = killed.size() - s1;
    assert (killedBefore == killedAfter) : "Mutants killed before / after / should be: " + killedBefore + "/" + killedAfter + "/" + s2 + ": " + test.toCode();
    logger.info("Mutants killed before / after / should be: " + killedBefore + "/" + killedAfter + "/" + s2);
    logger.info("Assertions in this test: " + test.getAssertions().size());
    if (primitiveWithoutAssertion(test.getStatement(test.size() - 1))) {
        logger.info("Last statement has primitive return value but no assertions: " + test.toCode());
        for (Assertion assertion : assertions) {
            if (assertion instanceof PrimitiveAssertion) {
                if (assertion.getStatement().equals(test.getStatement(test.size() - 1))) {
                    logger.debug("Adding a primitive assertion " + assertion);
                    test.getStatement(test.size() - 1).addAssertion(assertion);
                    break;
                }
            }
        }
        filterInspectorPrimitiveDuplication(test.getStatement(test.size() - 1));
    }
    // IF there are no mutant killing assertions on the last statement, still assert something
    if (test.getStatement(test.size() - 1).getAssertions().isEmpty() || justNullAssertion(test.getStatement(test.size() - 1))) {
        logger.info("Last statement has no assertions: " + test.toCode());
        logger.info("Assertions to choose from: " + assertions.size());
        if (test.getStatement(test.size() - 1).getAssertions().isEmpty()) {
            logger.debug("Last statement: " + test.getStatement(test.size() - 1).getCode());
        }
        if (origResult.isThereAnExceptionAtPosition(test.size() - 1))
            logger.debug("Exception on last statement!");
        if (justNullAssertion(test.getStatement(test.size() - 1)))
            logger.debug("Just null assertions on last statement: " + test.toCode());
        boolean haveAssertion = false;
        for (Assertion assertion : assertions) {
            if (assertion instanceof PrimitiveAssertion) {
                if (assertion.getStatement().equals(test.getStatement(test.size() - 1))) {
                    logger.debug("Adding a primitive assertion " + assertion);
                    test.getStatement(test.size() - 1).addAssertion(assertion);
                    haveAssertion = true;
                    break;
                }
            }
        }
        if (!haveAssertion) {
            logger.info("Could not find a primitive assertion, continuing search");
            for (Assertion assertion : assertions) {
                if (assertion instanceof NullAssertion)
                    continue;
                if (assertion.getStatement().equals(test.getStatement(test.size() - 1))) {
                    logger.info("Adding an assertion: " + assertion);
                    test.getStatement(test.size() - 1).addAssertion(assertion);
                    haveAssertion = true;
                    break;
                }
            }
        }
        // if (!test.hasAssertions()) {
        if (!haveAssertion) {
            logger.info("After second round we still have no assertion");
            Method inspectorMethod = null;
            if (test.getStatement(test.size() - 1) instanceof MethodStatement) {
                MethodStatement methodStatement = (MethodStatement) test.getStatement(test.size() - 1);
                Method method = methodStatement.getMethod().getMethod();
                if (method.getParameterTypes().length == 0) {
                    if (method.getReturnType().isPrimitive() && !method.getReturnType().equals(void.class)) {
                        inspectorMethod = method;
                    }
                }
            }
            for (OutputTrace<?> trace : origResult.getTraces()) {
                trace.getAllAssertions(test);
            }
            Set<Assertion> target = new HashSet<Assertion>(test.getStatement(test.size() - 1).getAssertions());
            logger.debug("Found assertions: " + target.size());
            test.removeAssertions();
            // test.addAssertions(clone);
            VariableReference targetVar = test.getStatement(test.size() - 1).getReturnValue();
            if (!targetVar.isVoid()) {
                logger.debug("Return value is non void: " + targetVar.getClassName());
                int maxAssertions = 1;
                int numAssertions = 0;
                for (Assertion ass : target) {
                    if (ass.getReferencedVariables().contains(targetVar) && !(ass instanceof NullAssertion)) {
                        if (ass instanceof InspectorAssertion) {
                            if (((InspectorAssertion) ass).inspector.getMethod().equals(inspectorMethod)) {
                                continue;
                            }
                        }
                        test.getStatement(test.size() - 1).addAssertion(ass);
                        logger.debug("Adding assertion " + ass.getCode());
                        if (++numAssertions >= maxAssertions)
                            break;
                    } else {
                        logger.debug("Assertion does not contain target: " + ass.getCode());
                    }
                }
                if (numAssertions == 0) {
                    for (Assertion ass : target) {
                        if (ass.getReferencedVariables().contains(targetVar)) {
                            test.getStatement(test.size() - 1).addAssertion(ass);
                            logger.debug("Adding assertion " + ass.getCode());
                            if (++numAssertions >= maxAssertions)
                                break;
                        } else {
                            logger.debug("Assertion does not contain target: " + ass.getCode());
                        }
                    }
                }
            } else {
                logger.debug("Return value is void");
                Set<VariableReference> targetVars = test.getStatement(test.size() - 1).getVariableReferences();
                int maxAssertions = 1;
                int numAssertions = 0;
                for (Assertion ass : target) {
                    Set<VariableReference> vars = ass.getReferencedVariables();
                    vars.retainAll(targetVars);
                    if (!vars.isEmpty()) {
                        test.getStatement(test.size() - 1).addAssertion(ass);
                        if (++numAssertions >= maxAssertions)
                            break;
                    }
                }
            }
            logger.info("1. Done with assertions");
        }
        logger.info("2. Done with assertions");
        filterInspectorPrimitiveDuplication(test.getStatement(test.size() - 1));
    }
    if (!origResult.noThrownExceptions()) {
        if (!test.getStatement(test.size() - 1).getAssertions().isEmpty()) {
            logger.debug("Removing assertions after exception");
            test.getStatement(test.size() - 1).removeAssertions();
        }
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) ExecutionResult(org.evosuite.testcase.execution.ExecutionResult) Method(java.lang.reflect.Method) Mutation(org.evosuite.coverage.mutation.Mutation)

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