Search in sources :

Example 11 with Statement

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

the class Scaffolding method generateMockInitialization.

/**
 * This is needed  because the first time we do initialize a mock object, that can take
 * some seconds (successive calls would be based on cached data), and so tests might
 * timeout. So here we force the mock initialization in a @BeforeClass
 *
 * @param bd
 * @param results
 */
private void generateMockInitialization(String testClassName, StringBuilder bd, List<ExecutionResult> results) {
    if (!TestSuiteWriterUtils.doesUseMocks(results)) {
        return;
    }
    // In order to make sure this is called *after* initializeClasses this method is now called directly from initEvoSuiteFramework
    // bd.append(METHOD_SPACE);
    // bd.append("@BeforeClass \n");
    bd.append(METHOD_SPACE);
    bd.append("private static void initMocksToAvoidTimeoutsInTheTests() throws ClassNotFoundException { \n");
    Set<String> mockStatements = new LinkedHashSet<>();
    for (ExecutionResult er : results) {
        for (Statement st : er.test) {
            if (st instanceof FunctionalMockStatement) {
                FunctionalMockStatement fms = (FunctionalMockStatement) st;
                String name = new GenericClass(fms.getReturnType()).getRawClass().getTypeName();
                mockStatements.add("mock(Class.forName(\"" + name + "\", false, " + testClassName + ".class.getClassLoader()));");
            }
        }
    }
    mockStatements.stream().sorted().forEach(m -> {
        bd.append(BLOCK_SPACE);
        bd.append(m);
        bd.append("\n");
    });
    bd.append(METHOD_SPACE);
    bd.append("}\n");
}
Also used : GenericClass(org.evosuite.utils.generic.GenericClass) FunctionalMockStatement(org.evosuite.testcase.statements.FunctionalMockStatement) Statement(org.evosuite.testcase.statements.Statement) ExecutionResult(org.evosuite.testcase.execution.ExecutionResult) FunctionalMockStatement(org.evosuite.testcase.statements.FunctionalMockStatement)

Example 12 with Statement

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

the class ArrayLocalSearch method stripAssignments.

private int stripAssignments(ArrayStatement statement, TestChromosome test, LocalSearchObjective<TestChromosome> objective) {
    int difference = 0;
    ArrayReference arrRef = (ArrayReference) statement.getReturnValue();
    TestFactory factory = TestFactory.getInstance();
    for (int position = test.size() - 1; position > statement.getPosition(); position--) {
        logger.debug("Current delete position: " + position);
        if (test.getTestCase().getStatement(position) instanceof AssignmentStatement) {
            logger.debug("Is assignment statement");
            AssignmentStatement assignment = (AssignmentStatement) test.getTestCase().getStatement(position);
            Statement valueStatement = test.getTestCase().getStatement(assignment.getValue().getStPosition());
            if (assignment.getReturnValue().getAdditionalVariableReference() == arrRef) {
                int currentDelta = 0;
                int differenceDelta = 0;
                logger.debug("Assigns to target array. Checking if we can remove it without worsening fitness");
                backup(test);
                try {
                    factory.deleteStatement(test.getTestCase(), position);
                    if (valueStatement instanceof PrimitiveStatement || valueStatement instanceof NullStatement) {
                        if (!test.getTestCase().hasReferences(valueStatement.getReturnValue())) {
                            if (valueStatement.getPosition() < statement.getPosition())
                                differenceDelta = 1;
                            currentDelta = 1;
                            logger.debug("Deleting primitive statement assigned to this array at " + valueStatement.getPosition());
                            factory.deleteStatement(test.getTestCase(), valueStatement.getPosition());
                        }
                    }
                    if (!objective.hasNotWorsened(test)) {
                        logger.debug("Fitness has decreased, so restoring test");
                        restore(test);
                        currentDelta = 0;
                        differenceDelta = 0;
                    }
                } catch (ConstructionFailedException e) {
                    currentDelta = 0;
                    differenceDelta = 0;
                    restore(test);
                }
                position -= currentDelta;
                difference += differenceDelta;
            }
        }
    }
    return difference;
}
Also used : ArrayReference(org.evosuite.testcase.variable.ArrayReference) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) NullStatement(org.evosuite.testcase.statements.NullStatement) AssignmentStatement(org.evosuite.testcase.statements.AssignmentStatement) TestFactory(org.evosuite.testcase.TestFactory) Statement(org.evosuite.testcase.statements.Statement) AssignmentStatement(org.evosuite.testcase.statements.AssignmentStatement) NullStatement(org.evosuite.testcase.statements.NullStatement) ArrayStatement(org.evosuite.testcase.statements.ArrayStatement) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 13 with Statement

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

the class TestRunnable method executeStatements.

/**
 * Iterate over all statements in the test case, and execute them one at a time
 *
 * @param result
 * @param out
 * @param num
 * @throws TimeoutException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws VMError
 * @throws EvosuiteError
 */
private void executeStatements(ExecutionResult result, PrintStream out, AtomicInteger num) throws TimeoutException, InvocationTargetException, IllegalAccessException, InstantiationException, VMError, EvosuiteError {
    for (Statement s : test) {
        if (Thread.currentThread().isInterrupted() || Thread.interrupted()) {
            logger.info("Thread interrupted at statement " + num + ": " + s.getCode());
            throw new TimeoutException();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Executing statement " + s.getCode());
        }
        ExecutionTracer.statementExecuted();
        informObservers_before(s);
        /*
			 * Here actually execute a statement of the SUT
			 */
        Throwable exceptionThrown = s.execute(scope, out);
        if (exceptionThrown != null) {
            // -------------------------------------------------------
            if (exceptionThrown instanceof VMError) {
                throw (VMError) exceptionThrown;
            }
            if (exceptionThrown instanceof EvosuiteError) {
                throw (EvosuiteError) exceptionThrown;
            }
            /*
				 * This is implemented in this way due to ExecutionResult.hasTimeout()
				 */
            if (exceptionThrown instanceof TestCaseExecutor.TimeoutExceeded) {
                logger.debug("Test timed out!");
                exceptionsThrown.put(test.size(), exceptionThrown);
                result.setThrownExceptions(exceptionsThrown);
                result.reportNewThrownException(test.size(), exceptionThrown);
                result.setTrace(ExecutionTracer.getExecutionTracer().getTrace());
                break;
            }
            // keep track if the exception and where it was thrown
            exceptionsThrown.put(num.get(), exceptionThrown);
            // --------------------------------------------------------
            if (ExecutionTracer.getExecutionTracer().getLastException() == exceptionThrown) {
                result.explicitExceptions.put(num.get(), true);
            } else {
                result.explicitExceptions.put(num.get(), false);
            }
            // --------------------------------------------------------
            printDebugInfo(s, exceptionThrown);
            /*
				 * If an exception is thrown, we stop the execution of the test case, because the internal state could be corrupted, and not
				 * possible to verify the behavior of any following function call. Predicate should be true by default
				 */
            if (Properties.BREAK_ON_EXCEPTION || exceptionThrown instanceof SystemExitException) {
                informObservers_after(s, exceptionThrown);
                break;
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Done statement " + s.getCode());
        }
        informObservers_after(s, exceptionThrown);
        num.incrementAndGet();
    }
    // end of loop
    informObservers_finished(result);
// TODO
}
Also used : Statement(org.evosuite.testcase.statements.Statement) SystemExitException(org.evosuite.runtime.System.SystemExitException) TimeoutException(java.util.concurrent.TimeoutException) VMError(org.evosuite.dse.VMError)

Example 14 with Statement

use of org.evosuite.testcase.statements.Statement 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 15 with Statement

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

the class ReferenceLocalSearch method replace.

/**
 * Replace the call with a completely different call
 *
 * @param test
 * @param statement
 * @return
 */
private boolean replace(TestChromosome test, int statement) {
    logger.debug("Replacing call");
    TestFactory factory = TestFactory.getInstance();
    Statement theStatement = test.getTestCase().getStatement(statement);
    VariableReference var = theStatement.getReturnValue();
    int oldLength = test.size();
    try {
        VariableReference replacement = null;
        if (Randomness.nextDouble() < Properties.NULL_PROBABILITY) {
            NullStatement nullStatement = new NullStatement(test.getTestCase(), var.getType());
            replacement = test.getTestCase().addStatement(nullStatement, statement);
        } else if (!var.isPrimitive()) {
            // Test cluster does not keep track of generators for primitives
            replacement = factory.createObject(test.getTestCase(), var.getType(), statement, 0, null);
        }
        if (replacement != null) {
            int oldStatement = statement + (test.size() - oldLength);
            for (int i = oldStatement + 1; i < test.size(); i++) {
                test.getTestCase().getStatement(i).replace(var, replacement);
            }
            factory.deleteStatement(test.getTestCase(), oldStatement);
            test.setChanged(true);
        }
    } catch (ConstructionFailedException e) {
        if (test.size() < oldLength) {
            restore(test);
        }
        test.setChanged(test.size() != oldLength);
    }
    return false;
}
Also used : VariableReference(org.evosuite.testcase.variable.VariableReference) NullStatement(org.evosuite.testcase.statements.NullStatement) TestFactory(org.evosuite.testcase.TestFactory) Statement(org.evosuite.testcase.statements.Statement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) NullStatement(org.evosuite.testcase.statements.NullStatement) FieldStatement(org.evosuite.testcase.statements.FieldStatement) ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

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