Search in sources :

Example 16 with GenericField

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);
}
Also used : FieldReference(org.evosuite.testcase.variable.FieldReference) AssignmentStatement(org.evosuite.testcase.statements.AssignmentStatement) GenericField(org.evosuite.utils.generic.GenericField)

Example 17 with GenericField

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());
}
Also used : DowncastExample(com.examples.with.different.packagename.test.DowncastExample) AbstractSuperclass(com.examples.with.different.packagename.test.AbstractSuperclass) TestCaseBuilder(org.evosuite.symbolic.TestCaseBuilder) FieldReference(org.evosuite.testcase.variable.FieldReference) VariableReference(org.evosuite.testcase.variable.VariableReference) AssignmentStatement(org.evosuite.testcase.statements.AssignmentStatement) GenericField(org.evosuite.utils.generic.GenericField) Test(org.junit.Test)

Example 18 with GenericField

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);
}
Also used : InputVariable(org.evosuite.parameterize.InputVariable) GenericClass(org.evosuite.utils.generic.GenericClass) List(java.util.List) ResourceList(org.evosuite.classpath.ResourceList) GenericField(org.evosuite.utils.generic.GenericField)

Example 19 with GenericField

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);
}
Also used : GenericField(org.evosuite.utils.generic.GenericField)

Example 20 with GenericField

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");
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) GenericClass(org.evosuite.utils.generic.GenericClass) Arrays(java.util.Arrays) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException) org.evosuite.testcase.statements(org.evosuite.testcase.statements) TimeController(org.evosuite.TimeController) EnvironmentStatements(org.evosuite.testcase.statements.environment.EnvironmentStatements) PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) InstanceOnlyOnce(org.evosuite.testcase.jee.InstanceOnlyOnce) LoggerFactory(org.slf4j.LoggerFactory) MockList(org.evosuite.runtime.mock.MockList) ArrayList(java.util.ArrayList) EvoServletState(org.evosuite.runtime.javaee.javax.servlet.EvoServletState) ClassUtils(org.apache.commons.lang3.ClassUtils) GenericMethod(org.evosuite.utils.generic.GenericMethod) org.evosuite.testcase.variable(org.evosuite.testcase.variable) Constraints(org.evosuite.runtime.annotation.Constraints) org.evosuite.setup(org.evosuite.setup) LinkedHashSet(java.util.LinkedHashSet) InjectionSupport(org.evosuite.testcase.jee.InjectionSupport) java.lang.reflect(java.lang.reflect) AtMostOnceLogger(org.evosuite.runtime.util.AtMostOnceLogger) Properties(org.evosuite.Properties) Logger(org.slf4j.Logger) GenericTypeReflector(com.googlecode.gentyref.GenericTypeReflector) Iterator(java.util.Iterator) HttpServlet(javax.servlet.http.HttpServlet) Collection(java.util.Collection) Inputs(org.evosuite.runtime.util.Inputs) ObjectPoolManager(org.evosuite.seeding.ObjectPoolManager) GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) Set(java.util.Set) CastClassManager(org.evosuite.seeding.CastClassManager) RandomInsertion(org.evosuite.testcase.mutation.RandomInsertion) GenericField(org.evosuite.utils.generic.GenericField) ReflectionFactory(org.evosuite.testcase.statements.reflection.ReflectionFactory) Collectors(java.util.stream.Collectors) Randomness(org.evosuite.utils.Randomness) TestGenerationContext(org.evosuite.TestGenerationContext) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) List(java.util.List) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) Injector(org.evosuite.runtime.javaee.injection.Injector) GenericUtils(org.evosuite.utils.generic.GenericUtils) CaptureType(com.googlecode.gentyref.CaptureType) Collections(java.util.Collections) ServletSupport(org.evosuite.testcase.jee.ServletSupport) GenericClass(org.evosuite.utils.generic.GenericClass) GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericField(org.evosuite.utils.generic.GenericField) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Aggregations

GenericField (org.evosuite.utils.generic.GenericField)27 Test (org.junit.Test)11 FactoryExample (com.examples.with.different.packagename.FactoryExample)8 VariableReference (org.evosuite.testcase.variable.VariableReference)8 GenericConstructor (org.evosuite.utils.generic.GenericConstructor)8 GenericMethod (org.evosuite.utils.generic.GenericMethod)8 AssignmentStatement (org.evosuite.testcase.statements.AssignmentStatement)6 FieldReference (org.evosuite.testcase.variable.FieldReference)6 ConstructionFailedException (org.evosuite.ga.ConstructionFailedException)5 GenericClass (org.evosuite.utils.generic.GenericClass)5 CaptureType (com.googlecode.gentyref.CaptureType)4 Field (java.lang.reflect.Field)3 Method (java.lang.reflect.Method)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 FieldStatement (org.evosuite.testcase.statements.FieldStatement)3 GenericAccessibleObject (org.evosuite.utils.generic.GenericAccessibleObject)3 DowncastExample (com.examples.with.different.packagename.test.DowncastExample)2 Collection (java.util.Collection)2 LinkedHashSet (java.util.LinkedHashSet)2