use of org.evosuite.utils.generic.GenericConstructor in project evosuite by EvoSuite.
the class TestCodeVisitor method visitConstructorStatement.
/*
* (non-Javadoc)
*
* @see org.evosuite.testcase.TestVisitor#visitConstructorStatement(org.evosuite.testcase.ConstructorStatement)
*/
/**
* {@inheritDoc}
*/
@Override
public void visitConstructorStatement(ConstructorStatement statement) {
String result = "";
GenericConstructor constructor = statement.getConstructor();
VariableReference retval = statement.getReturnValue();
Throwable exception = getException(statement);
boolean isGenericConstructor = constructor.hasTypeParameters();
boolean isNonStaticMemberClass = constructor.getConstructor().getDeclaringClass().isMemberClass() && !constructor.isStatic() && !Modifier.isStatic(constructor.getConstructor().getDeclaringClass().getModifiers());
List<VariableReference> parameters = statement.getParameterReferences();
int startPos = 0;
if (isNonStaticMemberClass) {
startPos = 1;
}
Type[] parameterTypes = constructor.getParameterTypes();
String parameterString = getParameterString(parameterTypes, parameters, isGenericConstructor, constructor.isOverloaded(parameters), startPos);
if (shouldUseTryCatch(exception, statement.isDeclaredException(exception))) {
String className = getClassName(retval);
// But really, this can't really add any coverage, so we shouldn't be printing this in the first place!
if (retval.isPrimitive()) {
className = retval.getGenericClass().getUnboxedType().getSimpleName();
}
result = className + " " + getVariableName(retval) + " = null;" + NEWLINE;
result += "try {" + NEWLINE + " ";
} else {
result += getClassName(retval) + " ";
}
if (isNonStaticMemberClass) {
result += getVariableName(retval) + " = " + getVariableName(parameters.get(0)) + ".new " + getSimpleTypeName(constructor.getOwnerType()) + "(" + parameterString + ");";
} else {
result += getVariableName(retval) + " = new " + getTypeName(constructor.getOwnerType()) + "(" + parameterString + ");";
}
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.GenericConstructor 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.GenericConstructor 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);
}
}
use of org.evosuite.utils.generic.GenericConstructor in project evosuite by EvoSuite.
the class AllMethodsTestChromosomeFactory method getRandomTestCase.
/**
* Create a random individual
*
* @param size
*/
private TestCase getRandomTestCase(int size) {
boolean tracerEnabled = ExecutionTracer.isEnabled();
if (tracerEnabled)
ExecutionTracer.disable();
TestCase test = getNewTestCase();
int num = 0;
// Choose a random length in 0 - size
int length = Randomness.nextInt(size);
while (length == 0) length = Randomness.nextInt(size);
// Then add random stuff
while (test.size() < length && num < Properties.MAX_ATTEMPTS) {
if (remainingMethods.size() == 0) {
reset();
}
GenericAccessibleObject<?> call = Randomness.choice(remainingMethods);
attemptedMethods.add(call);
remainingMethods.remove(call);
try {
TestFactory testFactory = TestFactory.getInstance();
if (call.isMethod()) {
testFactory.addMethod(test, (GenericMethod) call, test.size(), 0);
} else if (call.isConstructor()) {
testFactory.addConstructor(test, (GenericConstructor) call, test.size(), 0);
} else {
assert (false) : "Found test call that is neither method nor constructor";
}
} catch (ConstructionFailedException e) {
}
num++;
}
if (logger.isDebugEnabled())
logger.debug("Randomized test case:" + test.toCode());
if (tracerEnabled)
ExecutionTracer.enable();
return test;
}
use of org.evosuite.utils.generic.GenericConstructor in project evosuite by EvoSuite.
the class ChangeMutationSystemTest method getIntTest.
private TestCase getIntTest(int x) throws NoSuchMethodException, SecurityException, ConstructionFailedException, ClassNotFoundException {
Class<?> sut = TestGenerationContext.getInstance().getClassLoaderForSUT().loadClass(Properties.TARGET_CLASS);
GenericClass clazz = new GenericClass(sut);
DefaultTestCase test = new DefaultTestCase();
GenericConstructor gc = new GenericConstructor(clazz.getRawClass().getConstructors()[0], clazz);
TestFactory testFactory = TestFactory.getInstance();
VariableReference callee = testFactory.addConstructor(test, gc, 0, 0);
VariableReference intVar = test.addStatement(new IntPrimitiveStatement(test, x));
Method m = clazz.getRawClass().getMethod("testMe", new Class<?>[] { int.class });
GenericMethod method = new GenericMethod(m, sut);
MethodStatement ms = new MethodStatement(test, method, callee, Arrays.asList(new VariableReference[] { intVar }));
test.addStatement(ms);
return test;
}
Aggregations