use of org.evosuite.utils.generic.GenericMethod in project evosuite by EvoSuite.
the class TestCodeVisitor method visitMethodStatement.
/*
* (non-Javadoc)
*
* @see org.evosuite.testcase.TestVisitor#visitMethodStatement(org.evosuite.testcase.MethodStatement)
*/
/**
* {@inheritDoc}
*/
@Override
public void visitMethodStatement(MethodStatement statement) {
String result = "";
VariableReference retval = statement.getReturnValue();
GenericMethod method = statement.getMethod();
Throwable exception = getException(statement);
List<VariableReference> parameters = statement.getParameterReferences();
boolean isGenericMethod = method.hasTypeParameters();
if (exception != null && !statement.isDeclaredException(exception)) {
result += "// Undeclared exception!" + NEWLINE;
}
boolean lastStatement = statement.getPosition() == statement.getTestCase().size() - 1;
boolean unused = !Properties.ASSERTIONS ? exception != null : test != null && !test.hasReferences(retval);
if (!retval.isVoid() && retval.getAdditionalVariableReference() == null && !unused) {
if (exception != null) {
if (!lastStatement || statement.hasAssertions())
result += getClassName(retval) + " " + getVariableName(retval) + " = " + retval.getDefaultValueString() + ";" + NEWLINE;
} else {
result += getClassName(retval) + " ";
}
}
if (shouldUseTryCatch(exception, statement.isDeclaredException(exception))) {
result += "try { " + NEWLINE + " ";
}
String parameter_string = getParameterString(method.getParameterTypes(), parameters, isGenericMethod, method.isOverloaded(parameters), 0);
String callee_str = "";
if (!unused && !retval.isAssignableFrom(method.getReturnType()) && !retval.getVariableClass().isAnonymousClass() && // Static generic methods are a special case where we shouldn't add a cast
!(isGenericMethod && method.getParameterTypes().length == 0 && method.isStatic())) {
String name = getClassName(retval);
if (!name.matches(".*\\.\\d+$")) {
callee_str = "(" + name + ")";
}
}
if (method.isStatic()) {
callee_str += getClassName(method.getMethod().getDeclaringClass());
} else {
VariableReference callee = statement.getCallee();
if (callee instanceof ConstantValue) {
callee_str += "((" + getClassName(method.getMethod().getDeclaringClass()) + ")" + getVariableName(callee) + ")";
} else {
// If the method is not public and this is a subclass in a different package we need to cast
if (!method.isPublic() && !method.getDeclaringClass().equals(callee.getVariableClass()) && callee.isAssignableTo(method.getMethod().getDeclaringClass())) {
String packageName1 = ClassUtils.getPackageName(method.getDeclaringClass());
String packageName2 = ClassUtils.getPackageName(callee.getVariableClass());
if (!packageName1.equals(packageName2)) {
callee_str += "((" + getClassName(method.getMethod().getDeclaringClass()) + ")" + getVariableName(callee) + ")";
} else {
callee_str += getVariableName(callee);
}
} else if (!callee.isAssignableTo(method.getMethod().getDeclaringClass())) {
try {
// If the concrete callee class has that method then it's ok
callee.getVariableClass().getDeclaredMethod(method.getName(), method.getRawParameterTypes());
callee_str += getVariableName(callee);
} catch (NoSuchMethodException e) {
// If not we need to cast to the subtype
callee_str += "((" + getTypeName(method.getMethod().getDeclaringClass()) + ") " + getVariableName(callee) + ")";
// TODO: Here we could check if this is actually possible
// ...but what would we do?
// if(!ClassUtils.getAllSuperclasses(method.getMethod().getDeclaringClass()).contains(callee.getVariableClass())) {
// }
}
} else {
callee_str += getVariableName(callee);
}
}
}
if (retval.isVoid()) {
result += callee_str + "." + method.getName() + "(" + parameter_string + ");";
} else {
// if (exception == null || !lastStatement)
if (!unused)
result += getVariableName(retval) + " = ";
// If unused, then we don't want to print anything:
// else
// result += getClassName(retval) + " " + getVariableName(retval) + " = ";
result += callee_str + "." + method.getName() + "(" + parameter_string + ");";
}
if (shouldUseTryCatch(exception, statement.isDeclaredException(exception))) {
if (Properties.ASSERTIONS) {
result += generateFailAssertion(statement, exception);
}
// end try block
result += NEWLINE + "}";
result += generateCatchBlock(statement, exception);
}
testCode += result + NEWLINE;
addAssertions(statement);
}
use of org.evosuite.utils.generic.GenericMethod in project evosuite by EvoSuite.
the class TestFactory method attemptObjectGeneration.
/**
* Try to generate an object suitable for Object.class
*
* @param test
* @param position
* @param recursionDepth
* @param allowNull
* @return
* @throws ConstructionFailedException
*/
protected VariableReference attemptObjectGeneration(TestCase test, int position, int recursionDepth, boolean allowNull) throws ConstructionFailedException {
if (allowNull && Randomness.nextDouble() <= Properties.NULL_PROBABILITY) {
logger.debug("Using a null reference to satisfy the type: {}", Object.class);
return createNull(test, Object.class, position, recursionDepth);
}
Set<GenericClass> castClasses = new LinkedHashSet<>(CastClassManager.getInstance().getCastClasses());
// needed a copy because hasGenerator(c) does modify that set...
List<GenericClass> classes = castClasses.stream().filter(c -> TestCluster.getInstance().hasGenerator(c) || c.isString()).collect(Collectors.toList());
classes.add(new GenericClass(Object.class));
// TODO if classes is empty, should we use FM here?
GenericClass choice = Randomness.choice(classes);
logger.debug("Chosen class for Object: {}", choice);
if (choice.isString()) {
return createOrReuseVariable(test, String.class, position, recursionDepth, null, allowNull, false, false);
}
GenericAccessibleObject<?> o = TestCluster.getInstance().getRandomGenerator(choice);
currentRecursion.add(o);
if (o == null) {
if (!TestCluster.getInstance().hasGenerator(Object.class)) {
logger.debug("We have no generator for Object.class ");
}
throw new ConstructionFailedException("Generator is null");
} else if (o.isField()) {
logger.debug("Attempting generating of Object.class via field of type Object.class");
VariableReference ret = addField(test, (GenericField) o, position, recursionDepth + 1);
ret.setDistance(recursionDepth + 1);
logger.debug("Success in generating type Object.class");
return ret;
} else if (o.isMethod()) {
logger.debug("Attempting generating of Object.class via method {} of type Object.class", o);
VariableReference ret = addMethod(test, (GenericMethod) o, position, recursionDepth + 1);
logger.debug("Success in generating type Object.class");
ret.setDistance(recursionDepth + 1);
return ret;
} else if (o.isConstructor()) {
logger.debug("Attempting generating of Object.class via constructor {} of type Object.class", o);
VariableReference ret = addConstructor(test, (GenericConstructor) o, position, recursionDepth + 1);
logger.debug("Success in generating Object.class");
ret.setDistance(recursionDepth + 1);
return ret;
} else {
logger.debug("No generators found for Object.class");
throw new ConstructionFailedException("No generator found for Object.class");
}
}
use of org.evosuite.utils.generic.GenericMethod in project evosuite by EvoSuite.
the class TestFactory method addCallFor.
/**
* Append given call to the test case at given position
*
* @param test
* @param call
* @param position
*/
private boolean addCallFor(TestCase test, VariableReference callee, GenericAccessibleObject<?> call, int position) {
logger.trace("addCallFor {}", callee.getName());
int previousLength = test.size();
currentRecursion.clear();
try {
if (call.isMethod()) {
GenericMethod method = (GenericMethod) call;
if (call.isStatic() || !method.getDeclaringClass().isAssignableFrom(callee.getVariableClass())) {
// Static methods / methods in other classes can be modifiers of the SUT if the SUT depends on static fields
addMethod(test, method, position, 0);
} else {
addMethodFor(test, callee, (GenericMethod) call.copyWithNewOwner(callee.getGenericClass()), position);
}
} else if (call.isField()) {
// A modifier for the SUT could also be a static field in another class
if (call.isStatic()) {
addFieldAssignment(test, (GenericField) call, position, 0);
} else {
addFieldFor(test, callee, (GenericField) call.copyWithNewOwner(callee.getGenericClass()), position);
}
}
return true;
} catch (ConstructionFailedException e) {
// TODO: Check this!
logger.debug("Inserting call {} has failed: {} Removing statements", call, 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);
}
if (logger.isDebugEnabled()) {
logger.debug("Test after removal: " + test.toCode());
}
return false;
}
}
use of org.evosuite.utils.generic.GenericMethod in project evosuite by EvoSuite.
the class TestFactory method getPossibleCalls.
/**
* Retrieve all the replacement calls that can be inserted at this position
* without changing the length
*
* @param returnType
* @param objects
* @return
*/
private List<GenericAccessibleObject<?>> getPossibleCalls(Type returnType, List<VariableReference> objects) {
List<GenericAccessibleObject<?>> calls = new ArrayList<GenericAccessibleObject<?>>();
Set<GenericAccessibleObject<?>> allCalls;
try {
allCalls = TestCluster.getInstance().getGenerators(new GenericClass(returnType), true);
} catch (ConstructionFailedException e) {
return calls;
}
for (GenericAccessibleObject<?> call : allCalls) {
Set<Type> dependencies = null;
if (call.isMethod()) {
GenericMethod method = (GenericMethod) call;
if (method.hasTypeParameters()) {
try {
call = method.getGenericInstantiation(new GenericClass(returnType));
} catch (ConstructionFailedException e) {
continue;
}
}
if (!((GenericMethod) call).getReturnType().equals(returnType))
continue;
dependencies = getDependencies((GenericMethod) call);
} else if (call.isConstructor()) {
dependencies = getDependencies((GenericConstructor) call);
} else if (call.isField()) {
if (!((GenericField) call).getFieldType().equals(returnType))
continue;
dependencies = getDependencies((GenericField) call);
} else {
assert (false);
}
if (dependenciesSatisfied(dependencies, objects)) {
calls.add(call);
}
}
return calls;
}
use of org.evosuite.utils.generic.GenericMethod in project evosuite by EvoSuite.
the class EvoTestCaseCodeGenerator method createCollectionInitStmt.
@Override
public void createCollectionInitStmt(final CaptureLog log, final int logRecNo) {
try {
final int oid = log.objectIds.get(logRecNo);
final Object[] params = log.params.get(logRecNo);
String collTypeName = log.getTypeName(oid);
Class<?> collType = getClassForName(collTypeName);
// -- determine if an alternative collection must be used for code generation
final boolean isPublic = java.lang.reflect.Modifier.isPublic(collType.getModifiers());
if (!isPublic || !hasDefaultConstructor(collType)) {
if (Set.class.isAssignableFrom(collType)) {
collTypeName = HashSet.class.getName();
collType = HashSet.class;
} else if (List.class.isAssignableFrom(collType)) {
collTypeName = ArrayList.class.getName();
collType = ArrayList.class;
} else if (Queue.class.isAssignableFrom(collType)) {
collTypeName = ArrayDeque.class.getName();
collType = ArrayDeque.class;
} else {
CodeGeneratorException.propagateError("[logRecNo = %s] - collection %s is not supported", logRecNo, collType);
}
}
// -- create code for instantiating collection
final List<VariableReference> noParams = Collections.emptyList();
final ConstructorStatement constrStmt = new ConstructorStatement(testCase, new GenericConstructor(collType.getConstructor(new Class<?>[0]), collType), noParams);
final VariableReference collRef = testCase.addStatement(constrStmt);
this.oidToVarRefMap.put(oid, collRef);
// --- fill collection
MethodStatement methodStmt;
// is either an oid or null
Integer argOID;
ArrayList<VariableReference> paramList;
Method method;
for (int i = 0; i < params.length; i++) {
paramList = new ArrayList<VariableReference>(1);
argOID = (Integer) params[i];
if (argOID == null || !this.oidToVarRefMap.containsKey(argOID)) {
VariableReference var = testCase.addStatement(new NullStatement(testCase, Object.class));
paramList.add(var);
} else {
VariableReference var = this.oidToVarRefMap.get(argOID);
paramList.add(var);
}
method = collType.getMethod("add", Object.class);
methodStmt = new MethodStatement(testCase, new GenericMethod(method, collType), collRef, paramList);
testCase.addStatement(methodStmt);
}
} catch (final Exception e) {
CodeGeneratorException.propagateError("[logRecNo = %s] - an unexpected error occurred while creating collection init stmt", logRecNo, e);
}
}
Aggregations