use of org.evosuite.utils.generic.GenericField in project evosuite by EvoSuite.
the class TestFactory method insertRandomCall.
/**
* Insert a random call for the UUT at the given position
*
* @param test
* @param position
*/
public boolean insertRandomCall(TestCase test, int position) {
int previousLength = test.size();
String name = "";
currentRecursion.clear();
logger.debug("Inserting random call at position {}", position);
try {
if (reflectionFactory == null) {
final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();
reflectionFactory = new ReflectionFactory(targetClass);
}
if (reflectionFactory.hasPrivateFieldsOrMethods() && TimeController.getInstance().getPhasePercentage() >= Properties.REFLECTION_START_PERCENT && (Randomness.nextDouble() < Properties.P_REFLECTION_ON_PRIVATE || TestCluster.getInstance().getNumTestCalls() == 0)) {
logger.debug("Going to insert random reflection call");
return insertRandomReflectionCall(test, position, 0);
}
GenericAccessibleObject<?> o = TestCluster.getInstance().getRandomTestCall(test);
if (o == null) {
logger.warn("Have no target methods to test");
return false;
} else if (o.isConstructor()) {
if (InstanceOnlyOnce.canInstantiateOnlyOnce(o.getDeclaringClass()) && ConstraintHelper.countNumberOfNewInstances(test, o.getDeclaringClass()) != 0) {
return false;
}
GenericConstructor c = (GenericConstructor) o;
logger.debug("Adding constructor call {}", c.getName());
name = c.getName();
addConstructor(test, c, position, 0);
} else if (o.isMethod()) {
GenericMethod m = (GenericMethod) o;
logger.debug("Adding method call {}", m.getName());
name = m.getName();
if (!m.isStatic()) {
logger.debug("Getting callee of type {}", m.getOwnerClass().getTypeName());
VariableReference callee = null;
Type target = m.getOwnerType();
if (!test.hasObject(target, position)) {
// no FM for SUT
callee = createObject(test, target, position, 0, null, false, false, true);
position += test.size() - previousLength;
previousLength = test.size();
} else {
callee = test.getRandomNonNullObject(target, position);
// This may also be an inner class, in this case we can't use a SUT instance
// if (!callee.isAssignableTo(m.getDeclaringClass())) {
// callee = test.getRandomNonNullObject(m.getDeclaringClass(), position);
// }
}
logger.debug("Got callee of type {}", callee.getGenericClass().getTypeName());
if (!TestUsageChecker.canUse(m.getMethod(), callee.getVariableClass())) {
logger.debug("Cannot call method {} with callee of type {}", m, callee.getClassName());
throw new ConstructionFailedException("Cannot apply method to this callee");
}
addMethodFor(test, callee, m.copyWithNewOwner(callee.getGenericClass()), position);
} else {
// We only use this for static methods to avoid using wrong constructors (?)
addMethod(test, m, position, 0);
}
} else if (o.isField()) {
GenericField f = (GenericField) o;
name = f.getName();
logger.debug("Adding field {}", f.getName());
if (Randomness.nextBoolean()) {
addFieldAssignment(test, f, position, 0);
} else {
addField(test, f, position, 0);
}
} else {
logger.error("Got type other than method or constructor!");
return false;
}
return true;
} catch (ConstructionFailedException e) {
// TODO: Check this! - TestCluster replaced
// TestCluster.getInstance().checkDependencies(o);
logger.debug("Inserting statement {} has failed. Removing statements: {}", name, e);
// TODO: Doesn't work if position != test.size()
int lengthDifference = test.size() - previousLength;
for (int i = lengthDifference - 1; i >= 0; i--) {
// we need to remove them in order, so that the testcase is at all time consistent
if (logger.isDebugEnabled()) {
logger.debug(" Removing statement: " + test.getStatement(position + i).getCode());
}
test.remove(position + i);
}
return false;
}
}
use of org.evosuite.utils.generic.GenericField in project evosuite by EvoSuite.
the class TestFactory method changeCall.
/**
* Replace the statement with a new statement using given call
*
* @param test
* @param statement
* @param call
* @throws ConstructionFailedException
*/
public void changeCall(TestCase test, Statement statement, GenericAccessibleObject<?> call) throws ConstructionFailedException {
int position = statement.getReturnValue().getStPosition();
logger.debug("Changing call {} with {}", test.getStatement(position), call);
if (call.isMethod()) {
GenericMethod method = (GenericMethod) call;
if (method.hasTypeParameters())
throw new ConstructionFailedException("Cannot handle generic methods properly");
VariableReference retval = statement.getReturnValue();
VariableReference callee = null;
if (!method.isStatic()) {
callee = getRandomNonNullNonPrimitiveObject(test, method.getOwnerType(), position);
}
List<VariableReference> parameters = new ArrayList<>();
for (Type type : method.getParameterTypes()) {
parameters.add(test.getRandomObject(type, position));
}
MethodStatement m = new MethodStatement(test, method, callee, parameters, retval);
test.setStatement(m, position);
logger.debug("Using method {}", m.getCode());
} else if (call.isConstructor()) {
GenericConstructor constructor = (GenericConstructor) call;
VariableReference retval = statement.getReturnValue();
List<VariableReference> parameters = new ArrayList<>();
for (Type type : constructor.getParameterTypes()) {
parameters.add(test.getRandomObject(type, position));
}
ConstructorStatement c = new ConstructorStatement(test, constructor, retval, parameters);
test.setStatement(c, position);
logger.debug("Using constructor {}", c.getCode());
} else if (call.isField()) {
GenericField field = (GenericField) call;
VariableReference retval = statement.getReturnValue();
VariableReference source = null;
if (!field.isStatic())
source = getRandomNonNullNonPrimitiveObject(test, field.getOwnerType(), position);
try {
FieldStatement f = new FieldStatement(test, field, source, retval);
test.setStatement(f, position);
logger.debug("Using field {}", f.getCode());
} catch (Throwable e) {
logger.error("Error: " + e + " , Field: " + field + " , Test: " + test);
throw new Error(e);
}
}
}
use of org.evosuite.utils.generic.GenericField in project evosuite by EvoSuite.
the class EvoTestCaseCodeGenerator method createFieldWriteAccessStmt.
@Override
public void createFieldWriteAccessStmt(CaptureLog log, int logRecNo) {
// assumption: all necessary statements are created and there is one variable for each referenced object
final Object[] methodArgs = log.params.get(logRecNo);
final int oid = log.objectIds.get(logRecNo);
final int captureId = log.captureIds.get(logRecNo);
final String fieldName = log.getNameOfAccessedFields(captureId);
final String typeName = log.getTypeName(oid);
try {
final Class<?> type = getClassForName(typeName);
final String fieldDesc = log.descList.get(logRecNo);
final Class<?> fieldType = CaptureUtil.getClassFromDesc(fieldDesc);
final FieldReference targetFieldRef = new FieldReference(testCase, new GenericField(this.getDeclaredField(type, fieldName), type), this.oidToVarRefMap.get(oid));
final AssignmentStatement assignment;
final Integer arg = (Integer) methodArgs[0];
if (arg == null) {
final NullStatement nullStmt = new NullStatement(testCase, fieldType);
final VariableReference nullReference = testCase.addStatement(nullStmt);
assignment = new AssignmentStatement(testCase, targetFieldRef, nullReference);
} else {
assignment = new AssignmentStatement(testCase, targetFieldRef, this.oidToVarRefMap.get(arg));
}
final VariableReference varRef = testCase.addStatement(assignment);
logger.debug("Adding assignment statement: " + assignment.getCode());
if (arg != null) {
this.oidToVarRefMap.put(arg, varRef);
}
} catch (final Exception e) {
CodeGeneratorException.propagateError(e, "[logRecNo = %s] - an unexpected error occurred while creating field write access stmt. Log: %s", logRecNo, log);
}
}
use of org.evosuite.utils.generic.GenericField in project evosuite by EvoSuite.
the class TestCarvingExecutionObserver method afterStatement.
/**
* own comment..
*/
@Override
public void afterStatement(final Statement statement, final Scope scope, final Throwable exception) {
if (statement instanceof AssignmentStatement) {
final AssignmentStatement assign = (AssignmentStatement) statement;
final VariableReference left = assign.getReturnValue();
if (left instanceof FieldReference) {
final FieldReference fieldRef = (FieldReference) left;
final GenericField field = fieldRef.getField();
FieldRegistry.notifyModification(field.isStatic() ? null : scope.getObject(fieldRef.getSource()), this.captureId, Type.getInternalName(field.getDeclaringClass()), field.getName(), Type.getDescriptor(field.getField().getType()));
// PUTFIELDRegistry creates PUTXXX as well as corresponding GETXXX statements
this.captureId -= 2;
}
}
}
use of org.evosuite.utils.generic.GenericField in project evosuite by EvoSuite.
the class DowncastTest method testFieldReferenceNeedsDowncast.
@Test
public void testFieldReferenceNeedsDowncast() throws NoSuchMethodException, NoSuchFieldException {
TestCaseBuilder builder = new TestCaseBuilder();
VariableReference var = builder.appendConstructor(DowncastExample.class.getConstructor());
VariableReference num0 = builder.appendMethod(var, DowncastExample.class.getMethod("getAbstractFoo"));
// This would be set during execution
num0.setType(ConcreteSubclass.class);
VariableReference bool0 = builder.appendBooleanPrimitive(true);
DefaultTestCase test = builder.getDefaultTestCase();
FieldReference fr = new FieldReference(test, new GenericField(ConcreteSubclass.class.getField("fieldInConcreteClass"), ConcreteSubclass.class), num0);
AssignmentStatement statement = new AssignmentStatement(test, fr, bool0);
test.addStatement(statement);
test.removeDownCasts();
System.out.println(test);
FieldReference fr2 = (FieldReference) test.getStatement(3).getReturnValue();
assertEquals(ConcreteSubclass.class, fr2.getSource().getVariableClass());
}
Aggregations