use of org.evosuite.utils.generic.GenericMethod in project evosuite by EvoSuite.
the class EvoTestCaseCodeGenerator method createMethodCallStmt.
@Override
public void createMethodCallStmt(final CaptureLog log, final int logRecNo) {
if (log == null)
throw new IllegalArgumentException("captured log must not be null");
if (logRecNo <= -1)
throw new IllegalArgumentException("log record number is invalid: " + logRecNo);
if (isMaximumLengthReached())
return;
// assumption: all necessary statements are created and there is one variable for each referenced object
final int oid = log.objectIds.get(logRecNo);
final Object[] methodArgs = log.params.get(logRecNo);
final String methodName = log.methodNames.get(logRecNo);
Class<?> type;
try {
final String typeName = log.getTypeName(oid);
type = getClassForName(typeName);
logger.debug("Creating method call statement for call to method {}.{}", typeName, methodName);
final Class<?>[] methodParamTypeClasses = getMethodParamTypeClasses(log, logRecNo);
final ArrayList<VariableReference> args = getArguments(methodArgs, methodParamTypeClasses);
if (CaptureLog.OBSERVED_INIT.equals(methodName)) {
// Person var0 = new Person();
final ConstructorStatement constStmt = new ConstructorStatement(testCase, new GenericConstructor(type.getDeclaredConstructor(methodParamTypeClasses), type), args);
this.oidToVarRefMap.put(oid, testCase.addStatement(constStmt));
} else {
// ------------------ handling for ordinary method calls e.g. var1 = var0.doSth();
final Object returnValue = log.returnValues.get(logRecNo);
if (CaptureLog.RETURN_TYPE_VOID.equals(returnValue)) {
GenericMethod genericMethod = new GenericMethod(this.getDeclaredMethod(type, methodName, methodParamTypeClasses), type);
MethodStatement m = new MethodStatement(testCase, genericMethod, this.oidToVarRefMap.get(oid), args);
testCase.addStatement(m);
} else {
// final org.objectweb.asm.Type returnType = org.objectweb.asm.Type.getReturnType(methodDesc);
logger.debug("Callee: {} ({})", this.oidToVarRefMap.get(oid), this.oidToVarRefMap.keySet());
// Person var0 = var.getPerson();
final MethodStatement m = new MethodStatement(testCase, new GenericMethod(this.getDeclaredMethod(type, methodName, methodParamTypeClasses), type), this.oidToVarRefMap.get(oid), args);
final Integer returnValueOID = (Integer) returnValue;
this.oidToVarRefMap.put(returnValueOID, testCase.addStatement(m));
}
}
} catch (NoSuchMethodException e) {
logger.info("Method not found; this may happen e.g. if an exception is thrown in the constructor");
return;
} catch (final Exception e) {
logger.info("Error at log record number {}: {}", logRecNo, e.toString());
logger.info("Test case so far: " + testCase.toCode());
logger.info(log.toString());
CodeGeneratorException.propagateError(e, "[logRecNo = %s] - an unexpected error occurred while creating method call stmt for %s.", logRecNo, methodName);
}
}
use of org.evosuite.utils.generic.GenericMethod in project evosuite by EvoSuite.
the class EvoTestCaseCodeGenerator method createMapInitStmt.
@Override
public void createMapInitStmt(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)) {
collType = HashMap.class;
}
// -- 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 = new ArrayList<VariableReference>();
for (int i = 0; i < params.length; i++) {
argOID = (Integer) params[i];
if (argOID == null) {
paramList.add(testCase.addStatement(new NullStatement(testCase, Object.class)));
} else {
paramList.add(this.oidToVarRefMap.get(argOID));
}
if (i % 2 == 1) {
final Method method = collType.getMethod("put", Object.class, Object.class);
replaceNullWithNullReferences(paramList, Object.class, Object.class);
methodStmt = new MethodStatement(testCase, new GenericMethod(method, collType), collRef, paramList);
testCase.addStatement(methodStmt);
paramList = new ArrayList<VariableReference>(2);
}
}
} catch (final Exception e) {
CodeGeneratorException.propagateError(e, "[logRecNo = %s] - an unexpected error occurred while creating map init stmt", logRecNo);
}
}
use of org.evosuite.utils.generic.GenericMethod in project evosuite by EvoSuite.
the class TestFactory method createObject.
/**
* Create a new non-null, non-primitive object and return reference
*
* @param test
* @param type
* @param position
* @param recursionDepth
* @return
* @throws ConstructionFailedException
*/
public VariableReference createObject(TestCase test, Type type, int position, int recursionDepth, VariableReference generatorRefToExclude, boolean allowNull, boolean canUseFunctionalMocks, boolean canReuseVariables) throws ConstructionFailedException {
GenericClass clazz = new GenericClass(type);
logger.debug("Going to create object for type {}", type);
VariableReference ret = null;
if (canUseFunctionalMocks && TimeController.getInstance().getPhasePercentage() >= Properties.FUNCTIONAL_MOCKING_PERCENT && Randomness.nextDouble() < Properties.P_FUNCTIONAL_MOCKING && FunctionalMockStatement.canBeFunctionalMocked(type)) {
// mock creation
logger.debug("Creating functional mock for {}", type);
ret = addFunctionalMock(test, type, position, recursionDepth + 1);
} else {
// regular creation
GenericAccessibleObject<?> o = TestCluster.getInstance().getRandomGenerator(clazz, currentRecursion, test, position, generatorRefToExclude, recursionDepth);
currentRecursion.add(o);
if (o == null) {
if (canReuseVariables) {
/*
It could happen that there is no current valid generator for 'position', but valid
generators were usable before. This is for example the case when the only generator
has an "atMostOnce" constraint, and so can only be used once.
In such case, we should just re-use an existing variable if it exists, as long as
it is not a functional mock (which can be used only once)
*/
for (int i = position - 1; i >= 0; i--) {
Statement statement = test.getStatement(i);
VariableReference var = statement.getReturnValue();
if (!allowNull && ConstraintHelper.isNull(var, test)) {
continue;
}
if (var.isAssignableTo(type) && !(statement instanceof FunctionalMockStatement)) {
logger.debug("Reusing variable at position {}", var.getStPosition());
return var;
}
}
}
if (canUseFunctionalMocks && (Properties.MOCK_IF_NO_GENERATOR || Properties.P_FUNCTIONAL_MOCKING > 0)) {
/*
Even if mocking is not active yet in this phase, if we have
no generator for a type, we use mocking directly
*/
if (FunctionalMockStatement.canBeFunctionalMocked(type)) {
logger.debug("Using mock for type {}", type);
ret = addFunctionalMock(test, type, position, recursionDepth + 1);
} else if (clazz.isAbstract() && FunctionalMockStatement.canBeFunctionalMockedIncludingSUT(type)) {
{
logger.debug("Using mock for abstract type {}", type);
ret = addFunctionalMockForAbstractClass(test, type, position, recursionDepth + 1);
}
}
}
if (ret == null) {
logger.debug("No mock solution found: {}, {}, {}, {}", canUseFunctionalMocks, Properties.MOCK_IF_NO_GENERATOR, FunctionalMockStatement.canBeFunctionalMocked(type), FunctionalMockStatement.canBeFunctionalMockedIncludingSUT(type));
if (!TestCluster.getInstance().hasGenerator(type)) {
logger.debug("No generators found for {}, attempting to resolve dependencies", type);
TestClusterGenerator clusterGenerator = TestGenerationContext.getInstance().getTestClusterGenerator();
Class<?> mock = MockList.getMockClass(clazz.getRawClass().getCanonicalName());
if (mock != null) {
clusterGenerator.addNewDependencies(Arrays.asList(mock));
} else {
clusterGenerator.addNewDependencies(Arrays.asList(clazz.getRawClass()));
}
if (TestCluster.getInstance().hasGenerator(type)) {
logger.debug("Found new generators for {}", type);
return createObject(test, type, position, recursionDepth + 1, generatorRefToExclude, allowNull, canUseFunctionalMocks, canReuseVariables);
} else {
logger.debug("Found no new generators for {}", type);
}
}
throw new ConstructionFailedException("Have no generator for " + type + " canUseFunctionalMocks=" + canUseFunctionalMocks + ", canBeMocked: " + FunctionalMockStatement.canBeFunctionalMocked(type));
}
} else if (o.isField()) {
logger.debug("Attempting generating of {} via field of type {}", type, type);
ret = addField(test, (GenericField) o, position, recursionDepth + 1);
} else if (o.isMethod()) {
logger.debug("Attempting generating of " + type + " via method " + (o) + " of type " + type);
ret = addMethod(test, (GenericMethod) o, position, recursionDepth + 1);
// TODO: Why are we doing this??
// if (o.isStatic()) {
// ret.setType(type);
// }
logger.debug("Success in generating type {} using method \"{}\"", type, o);
} else if (o.isConstructor()) {
if (logger.isDebugEnabled()) {
logger.debug("Attempting generating of " + type + " via constructor " + (o) + " of type " + type + ", with constructor type " + o.getOwnerType() + ", at position " + position);
}
ret = addConstructor(test, (GenericConstructor) o, type, position, recursionDepth + 1);
} else {
logger.debug("No generators found for type {}", type);
throw new ConstructionFailedException("No generator found for type " + type);
}
}
ret.setDistance(recursionDepth + 1);
logger.debug("Success in generation of type {} at position {}", type, position);
return ret;
}
use of org.evosuite.utils.generic.GenericMethod in project evosuite by EvoSuite.
the class TestCoverageGoalNameGeneration method testMultipleMethods.
@Test
public void testMultipleMethods() throws NoSuchMethodException {
TestCase test = new DefaultTestCase();
GenericConstructor gc = new GenericConstructor(Object.class.getConstructor(), Object.class);
VariableReference callee = test.addStatement(new ConstructorStatement(test, gc, new ArrayList<VariableReference>()));
GenericMethod gm = new GenericMethod(Object.class.getMethod("toString"), Object.class);
test.addStatement(new MethodStatement(test, gm, callee, new ArrayList<VariableReference>()));
MethodCoverageTestFitness goal1 = new MethodCoverageTestFitness("FooClass", "toString()Ljava/lang/String;");
test.addCoveredGoal(goal1);
MethodCoverageTestFitness goal2 = new MethodCoverageTestFitness("FooClass", "foo()Ljava/lang/String;");
test.addCoveredGoal(goal2);
MethodCoverageTestFitness goal3 = new MethodCoverageTestFitness("FooClass", "bar()Ljava/lang/String;");
test.addCoveredGoal(goal3);
List<TestCase> tests = new ArrayList<>();
tests.add(test);
CoverageGoalTestNameGenerationStrategy naming = new CoverageGoalTestNameGenerationStrategy(tests);
String generatedName = naming.getName(test);
assertEquals("testToString", generatedName);
// TODO: What should be the name now? Need some heuristic, currently sorted alphabetically
// Better heuristic would consider other things, like e.g. which method has more goals covered
// or which one is the last one called?
}
use of org.evosuite.utils.generic.GenericMethod in project evosuite by EvoSuite.
the class TestClassInitialization method buildLoadTargetClassTestCase.
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);
return test;
} catch (NoSuchMethodException | SecurityException e) {
throw new EvosuiteError("Unexpected exception while creating Class Initializer Test Case");
}
}
Aggregations