Search in sources :

Example 1 with Statement

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

the class TestSuiteGenerator method buildLoadTargetClassTestCase.

/**
 * Creates a single Test Case that only loads the target class.
 * <code>
 * Thread currentThread = Thread.currentThread();
 * ClassLoader classLoader = currentThread.getClassLoader();
 * classLoader.load(className);
 * </code>
 * @param className the class to be loaded
 * @return
 * @throws EvosuiteError if a reflection error happens while creating the test case
 */
private static DefaultTestCase buildLoadTargetClassTestCase(String className) throws EvosuiteError {
    DefaultTestCase test = new DefaultTestCase();
    StringPrimitiveStatement stmt0 = new StringPrimitiveStatement(test, className);
    VariableReference string0 = test.addStatement(stmt0);
    try {
        Method currentThreadMethod = Thread.class.getMethod("currentThread");
        Statement currentThreadStmt = new MethodStatement(test, new GenericMethod(currentThreadMethod, currentThreadMethod.getDeclaringClass()), null, Collections.emptyList());
        VariableReference currentThreadVar = test.addStatement(currentThreadStmt);
        Method getContextClassLoaderMethod = Thread.class.getMethod("getContextClassLoader");
        Statement getContextClassLoaderStmt = new MethodStatement(test, new GenericMethod(getContextClassLoaderMethod, getContextClassLoaderMethod.getDeclaringClass()), currentThreadVar, Collections.emptyList());
        VariableReference contextClassLoaderVar = test.addStatement(getContextClassLoaderStmt);
        // Method loadClassMethod = ClassLoader.class.getMethod("loadClass", String.class);
        // Statement loadClassStmt = new MethodStatement(test,
        // new GenericMethod(loadClassMethod, loadClassMethod.getDeclaringClass()), contextClassLoaderVar,
        // Collections.singletonList(string0));
        // test.addStatement(loadClassStmt);
        BooleanPrimitiveStatement stmt1 = new BooleanPrimitiveStatement(test, true);
        VariableReference boolean0 = test.addStatement(stmt1);
        Method forNameMethod = Class.class.getMethod("forName", String.class, boolean.class, ClassLoader.class);
        Statement forNameStmt = new MethodStatement(test, new GenericMethod(forNameMethod, forNameMethod.getDeclaringClass()), null, Arrays.<VariableReference>asList(string0, boolean0, contextClassLoaderVar));
        test.addStatement(forNameStmt);
        return test;
    } catch (NoSuchMethodException | SecurityException e) {
        throw new EvosuiteError("Unexpected exception while creating Class Initializer Test Case");
    }
}
Also used : StringPrimitiveStatement(org.evosuite.testcase.statements.StringPrimitiveStatement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) EvosuiteError(org.evosuite.testcase.execution.EvosuiteError) BooleanPrimitiveStatement(org.evosuite.testcase.statements.numeric.BooleanPrimitiveStatement) Statement(org.evosuite.testcase.statements.Statement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) StringPrimitiveStatement(org.evosuite.testcase.statements.StringPrimitiveStatement) BooleanPrimitiveStatement(org.evosuite.testcase.statements.numeric.BooleanPrimitiveStatement) DefaultTestCase(org.evosuite.testcase.DefaultTestCase) Method(java.lang.reflect.Method) GenericMethod(org.evosuite.utils.generic.GenericMethod) GenericMethod(org.evosuite.utils.generic.GenericMethod)

Example 2 with Statement

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

the class EqualsSymmetricContract 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 });
        GenericMethod method = new GenericMethod(equalsMethod, a.getGenericClass());
        // Create x = a.equals(b)
        Statement st1 = new MethodStatement(test, method, a, Arrays.asList(new VariableReference[] { b }));
        VariableReference x = test.addStatement(st1, statement.getPosition() + 1);
        // Create y = b.equals(a);
        Statement st2 = new MethodStatement(test, method, b, Arrays.asList(new VariableReference[] { a }));
        VariableReference y = test.addStatement(st2, statement.getPosition() + 2);
        Statement newStatement = test.getStatement(y.getStPosition());
        // Create assertEquals(x, y)
        EqualsAssertion assertion = new EqualsAssertion();
        assertion.setStatement(newStatement);
        assertion.setSource(x);
        assertion.setDest(y);
        assertion.setValue(true);
        newStatement.addAssertion(assertion);
        newStatement.addComment("Violates contract a.equals(b) <-> b.equals(a)");
    } 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) EqualsAssertion(org.evosuite.assertion.EqualsAssertion)

Example 3 with Statement

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

the class InspectorTraceObserver 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) {
    // TODO: Check the variable class is complex?
    // We don't want inspector checks on string constants
    Statement declaringStatement = currentTest.getStatement(var.getStPosition());
    if (declaringStatement instanceof PrimitiveStatement<?>)
        return;
    if (statement.isAssignmentStatement() && statement.getReturnValue().isArrayIndex())
        return;
    if (statement instanceof ConstructorStatement) {
        if (statement.getReturnValue().isWrapperType() || statement.getReturnValue().isAssignableTo(EvoSuiteMock.class))
            return;
    }
    if (var.isPrimitive() || var.isString() || var.isWrapperType())
        return;
    logger.debug("Checking for inspectors of " + var + " at statement " + statement.getPosition());
    List<Inspector> inspectors = InspectorManager.getInstance().getInspectors(var.getVariableClass());
    InspectorTraceEntry entry = new InspectorTraceEntry(var);
    for (Inspector i : inspectors) {
        // No inspectors from java.lang.Object
        if (i.getMethod().getDeclaringClass().equals(Object.class))
            continue;
        try {
            Object target = var.getObject(scope);
            if (target != null) {
                // Don't call inspector methods on mock objects
                if (target.getClass().getCanonicalName().contains("EnhancerByMockito"))
                    return;
                Object value = i.getValue(target);
                logger.debug("Inspector " + i.getMethodCall() + " is: " + value);
                // We need no assertions that include the memory location
                if (value instanceof String) {
                    // String literals may not be longer than 32767
                    if (((String) value).length() >= 32767)
                        continue;
                    // Maximum length of strings we look at
                    if (((String) value).length() > Properties.MAX_STRING)
                        continue;
                    // If we suspect an Object hashCode not use this, as it may lead to flaky tests
                    if (addressPattern.matcher((String) value).find())
                        continue;
                    // The word "hashCode" is also suspicious
                    if (((String) value).toLowerCase().contains("hashcode"))
                        continue;
                    // Avoid asserting anything on values referring to mockito proxy objects
                    if (((String) value).toLowerCase().contains("EnhancerByMockito"))
                        continue;
                    if (((String) value).toLowerCase().contains("$MockitoMock$"))
                        continue;
                    if (target instanceof URL) {
                        // Absolute paths may be different between executions
                        if (((String) value).startsWith("/") || ((String) value).startsWith("file:/"))
                            continue;
                    }
                }
                entry.addValue(i, value);
            }
        } catch (Exception e) {
            if (e instanceof TimeoutException) {
                logger.debug("Timeout during inspector call - deactivating inspector " + i.getMethodCall());
                InspectorManager.getInstance().removeInspector(var.getVariableClass(), i);
            }
            logger.debug("Exception " + e + " / " + e.getCause());
            if (e.getCause() != null && !e.getCause().getClass().equals(NullPointerException.class)) {
                logger.debug("Exception during call to inspector: " + e + " - " + e.getCause());
            }
        }
    }
    logger.debug("Found " + entry.size() + " inspectors for " + var + " at statement " + statement.getPosition());
    trace.addEntry(statement.getPosition(), var, entry);
}
Also used : ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) Statement(org.evosuite.testcase.statements.Statement) ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) URL(java.net.URL) TimeoutException(java.util.concurrent.TimeoutException) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) EvoSuiteMock(org.evosuite.runtime.mock.EvoSuiteMock) TimeoutException(java.util.concurrent.TimeoutException)

Example 4 with Statement

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

the class TestChromosome method mutationChange.

/**
 * Each statement is replaced with probability 1/length
 *
 * @return
 */
private boolean mutationChange() {
    boolean changed = false;
    int lastMutatableStatement = getLastMutatableStatement();
    double pl = 1d / (lastMutatableStatement + 1);
    TestFactory testFactory = TestFactory.getInstance();
    if (Randomness.nextDouble() < Properties.CONCOLIC_MUTATION) {
        try {
            changed = mutationConcolic();
        } catch (Exception exc) {
            logger.warn("Encountered exception when trying to use concolic mutation: {}", exc.getMessage());
            logger.debug("Detailed exception trace: ", exc);
        }
    }
    if (!changed) {
        for (int position = 0; position <= lastMutatableStatement; position++) {
            if (Randomness.nextDouble() <= pl) {
                assert (test.isValid());
                Statement statement = test.getStatement(position);
                if (statement.isReflectionStatement())
                    continue;
                int oldDistance = statement.getReturnValue().getDistance();
                // constraints are handled directly in the statement mutations
                if (statement.mutate(test, testFactory)) {
                    changed = true;
                    mutationHistory.addMutationEntry(new TestMutationHistoryEntry(TestMutationHistoryEntry.TestMutation.CHANGE, statement));
                    assert (test.isValid());
                    assert ConstraintVerifier.verifyTest(test);
                } else if (!statement.isAssignmentStatement() && ConstraintVerifier.canDelete(test, position)) {
                    // if a statement should not be deleted, then it cannot be either replaced by another one
                    int pos = statement.getPosition();
                    if (testFactory.changeRandomCall(test, statement)) {
                        changed = true;
                        mutationHistory.addMutationEntry(new TestMutationHistoryEntry(TestMutationHistoryEntry.TestMutation.CHANGE, test.getStatement(pos)));
                        assert ConstraintVerifier.verifyTest(test);
                    }
                    assert (test.isValid());
                }
                statement.getReturnValue().setDistance(oldDistance);
                // Might have changed due to mutation
                position = statement.getPosition();
            }
        }
    }
    if (changed) {
        assert ConstraintVerifier.verifyTest(test);
    }
    return changed;
}
Also used : FunctionalMockStatement(org.evosuite.testcase.statements.FunctionalMockStatement) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) Statement(org.evosuite.testcase.statements.Statement) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 5 with Statement

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

the class TestChromosome method mutate.

/**
 * {@inheritDoc}
 *
 * Each statement is mutated with probability 1/l
 */
@Override
public void mutate() {
    boolean changed = false;
    mutationHistory.clear();
    if (mockChange()) {
        changed = true;
    }
    if (Properties.CHOP_MAX_LENGTH && size() >= Properties.CHROMOSOME_LENGTH) {
        int lastPosition = getLastMutatableStatement();
        test.chop(lastPosition + 1);
    }
    // Delete
    if (Randomness.nextDouble() <= Properties.P_TEST_DELETE) {
        logger.debug("Mutation: delete");
        if (mutationDelete())
            changed = true;
    }
    // Change
    if (Randomness.nextDouble() <= Properties.P_TEST_CHANGE) {
        logger.debug("Mutation: change");
        if (mutationChange())
            changed = true;
    }
    // Insert
    if (Randomness.nextDouble() <= Properties.P_TEST_INSERT) {
        logger.debug("Mutation: insert");
        if (mutationInsert())
            changed = true;
    }
    if (changed) {
        this.increaseNumberOfMutations();
        setChanged(true);
        test.clearCoveredGoals();
    }
    for (Statement s : test) {
        s.isValid();
    }
    // if it happens, it means a bug in EvoSuite
    assert ConstraintVerifier.verifyTest(test);
    assert !ConstraintVerifier.hasAnyOnlyForAssertionMethod(test);
}
Also used : FunctionalMockStatement(org.evosuite.testcase.statements.FunctionalMockStatement) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) Statement(org.evosuite.testcase.statements.Statement)

Aggregations

Statement (org.evosuite.testcase.statements.Statement)48 MethodStatement (org.evosuite.testcase.statements.MethodStatement)25 VariableReference (org.evosuite.testcase.variable.VariableReference)17 ConstructorStatement (org.evosuite.testcase.statements.ConstructorStatement)16 PrimitiveStatement (org.evosuite.testcase.statements.PrimitiveStatement)11 TestCase (org.evosuite.testcase.TestCase)8 JUnitTestCarvedChromosomeFactory (org.evosuite.testcase.factories.JUnitTestCarvedChromosomeFactory)8 Test (org.junit.Test)8 ArrayList (java.util.ArrayList)7 FieldStatement (org.evosuite.testcase.statements.FieldStatement)7 Method (java.lang.reflect.Method)6 TestChromosome (org.evosuite.testcase.TestChromosome)6 GenericMethod (org.evosuite.utils.generic.GenericMethod)6 FunctionalMockStatement (org.evosuite.testcase.statements.FunctionalMockStatement)5 NullStatement (org.evosuite.testcase.statements.NullStatement)5 StringPrimitiveStatement (org.evosuite.testcase.statements.StringPrimitiveStatement)5 ConstructionFailedException (org.evosuite.ga.ConstructionFailedException)4 ArrayStatement (org.evosuite.testcase.statements.ArrayStatement)4 TestFactory (org.evosuite.testcase.TestFactory)3 TestFitnessFunction (org.evosuite.testcase.TestFitnessFunction)3