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");
}
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;
}
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
}
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;
}
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;
}
Aggregations