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