use of org.evosuite.utils.generic.GenericField in project evosuite by EvoSuite.
the class TestCaseBuilder method appendAssignment.
public void appendAssignment(VariableReference receiver, Field field, VariableReference value) {
FieldReference fieldReference;
if (receiver == null) {
fieldReference = new FieldReference(tc, new GenericField(field, field.getDeclaringClass()));
} else {
fieldReference = new FieldReference(tc, new GenericField(field, receiver.getType()), receiver);
}
AssignmentStatement stmt = new AssignmentStatement(tc, fieldReference, value);
tc.addStatement(stmt);
}
use of org.evosuite.utils.generic.GenericField in project evosuite by EvoSuite.
the class DowncastTest method testFieldReferenceDoesNotNeedDowncast.
@Test
public void testFieldReferenceDoesNotNeedDowncast() 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(AbstractSuperclass.class.getField("fieldInAbstractClass"), AbstractSuperclass.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(AbstractSuperclass.class, fr2.getSource().getVariableClass());
}
use of org.evosuite.utils.generic.GenericField in project evosuite by EvoSuite.
the class TestCodeVisitor method getVariableName.
/**
* <p>
* getVariableName
* </p>
*
* @param var
* a {@link org.evosuite.testcase.variable.VariableReference} object.
* @return a {@link java.lang.String} object.
*/
public String getVariableName(VariableReference var) {
if (var instanceof ConstantValue) {
ConstantValue cval = (ConstantValue) var;
if (cval.getValue() != null && cval.getVariableClass().equals(Class.class)) {
return getClassName((Class<?>) cval.getValue()) + ".class";
}
return var.getName();
} else if (var instanceof InputVariable) {
return var.getName();
} else if (var instanceof FieldReference) {
VariableReference source = ((FieldReference) var).getSource();
GenericField field = ((FieldReference) var).getField();
if (source != null) {
String ret = "";
// If the method is not public and this is a subclass in a different package we need to cast
if (!field.isPublic() && !field.getDeclaringClass().equals(source.getVariableClass()) && source.isAssignableTo(field.getDeclaringClass())) {
String packageName1 = ClassUtils.getPackageName(field.getDeclaringClass());
String packageName2 = ClassUtils.getPackageName(source.getVariableClass());
if (!packageName1.equals(packageName2)) {
ret += "((" + getClassName(field.getDeclaringClass()) + ")" + getVariableName(source) + ")";
} else {
ret += getVariableName(source);
}
} else if (!source.isAssignableTo(field.getField().getDeclaringClass())) {
try {
// If the concrete source class has that field then it's ok
source.getVariableClass().getDeclaredField(field.getName());
ret = getVariableName(source);
} catch (NoSuchFieldException e) {
// If not we need to cast to the subtype
ret = "((" + getTypeName(field.getField().getDeclaringClass()) + ") " + getVariableName(source) + ")";
}
} else {
ret += getVariableName(source);
}
return ret + "." + field.getName();
} else
return getClassName(field.getField().getDeclaringClass()) + "." + field.getName();
} else if (var instanceof ArrayIndex) {
VariableReference array = ((ArrayIndex) var).getArray();
List<Integer> indices = ((ArrayIndex) var).getArrayIndices();
String result = getVariableName(array);
for (Integer index : indices) {
result += "[" + index + "]";
}
return result;
} else if (var instanceof ArrayReference) {
String className = var.getSimpleClassName();
// int num = 0;
// for (VariableReference otherVar : variableNames.keySet()) {
// if (!otherVar.equals(var)
// && otherVar.getVariableClass().equals(var.getVariableClass()))
// num++;
// }
String variableName = className.substring(0, 1).toLowerCase() + className.substring(1) + "Array";
variableName = variableName.replace('.', '_').replace("[]", "");
if (!variableNames.containsKey(var)) {
if (!nextIndices.containsKey(variableName)) {
nextIndices.put(variableName, 0);
}
int index = nextIndices.get(variableName);
nextIndices.put(variableName, index + 1);
variableName += index;
variableNames.put(var, variableName);
}
} else if (!variableNames.containsKey(var)) {
String className = var.getSimpleClassName();
// int num = 0;
// for (VariableReference otherVar : variableNames.keySet()) {
// if (otherVar.getVariableClass().equals(var.getVariableClass()))
// num++;
// }
String variableName = className.substring(0, 1).toLowerCase() + className.substring(1);
if (variableName.contains("[]")) {
variableName = variableName.replace("[]", "Array");
}
variableName = variableName.replace(".", "_");
// if (numObjectsOfType > 1 || className.equals(variableName)) {
if (CharUtils.isAsciiNumeric(variableName.charAt(variableName.length() - 1)))
variableName += "_";
if (!nextIndices.containsKey(variableName)) {
nextIndices.put(variableName, 0);
}
int index = nextIndices.get(variableName);
nextIndices.put(variableName, index + 1);
variableName += index;
// }
variableNames.put(var, variableName);
}
return variableNames.get(var);
}
use of org.evosuite.utils.generic.GenericField in project evosuite by EvoSuite.
the class TestCodeVisitor method visitFieldStatement.
/*
* (non-Javadoc)
*
* @see org.evosuite.testcase.TestVisitor#visitFieldStatement(org.evosuite.testcase.FieldStatement)
*/
/**
* {@inheritDoc}
*/
@Override
public void visitFieldStatement(FieldStatement statement) {
Throwable exception = getException(statement);
String cast_str = "";
StringBuilder builder = new StringBuilder();
VariableReference retval = statement.getReturnValue();
GenericField field = statement.getField();
if (!retval.isAssignableFrom(field.getFieldType())) {
cast_str += "(" + getClassName(retval) + ")";
}
if (exception != null) {
builder.append(getClassName(retval));
builder.append(" ");
builder.append(getVariableName(retval));
builder.append(" = null;");
builder.append(NEWLINE);
builder.append("try { ");
builder.append(NEWLINE);
} else {
builder.append(getClassName(retval));
builder.append(" ");
}
if (!field.isStatic()) {
VariableReference source = statement.getSource();
builder.append(getVariableName(retval));
builder.append(" = ");
builder.append(cast_str);
builder.append(getVariableName(source));
builder.append(".");
builder.append(field.getName());
builder.append(";");
} else {
builder.append(getVariableName(retval));
builder.append(" = ");
builder.append(cast_str);
builder.append(getClassName(field.getField().getDeclaringClass()));
builder.append(".");
builder.append(field.getName());
builder.append(";");
}
if (exception != null) {
Class<?> ex = exception.getClass();
while (!Modifier.isPublic(ex.getModifiers())) ex = ex.getSuperclass();
builder.append(NEWLINE);
builder.append("} catch(");
builder.append(getClassName(ex));
builder.append(" e) {}");
}
builder.append(NEWLINE);
testCode += builder.toString();
addAssertions(statement);
}
use of org.evosuite.utils.generic.GenericField 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");
}
}
Aggregations