Search in sources :

Example 21 with GenericClass

use of org.evosuite.utils.generic.GenericClass in project evosuite by EvoSuite.

the class TestFactory method assignArray.

/**
 * Assign a value to an array index
 *
 * @param test
 * @param array
 * @param arrayIndex
 * @param position
 * @throws ConstructionFailedException
 */
public void assignArray(TestCase test, VariableReference array, int arrayIndex, int position) throws ConstructionFailedException {
    List<VariableReference> objects = test.getObjects(array.getComponentType(), position);
    Iterator<VariableReference> iterator = objects.iterator();
    GenericClass componentClass = new GenericClass(array.getComponentType());
    // Remove assignments from the same array
    while (iterator.hasNext()) {
        VariableReference var = iterator.next();
        if (var instanceof ArrayIndex) {
            if (((ArrayIndex) var).getArray().equals(array))
                iterator.remove();
            else // This may e.g. happen if we have Object[], we could otherwise assign Object[] as values
            if (((ArrayIndex) var).getArray().getType().equals(array.getType()))
                iterator.remove();
        }
        if (componentClass.isWrapperType()) {
            Class<?> rawClass = ClassUtils.wrapperToPrimitive(componentClass.getRawClass());
            if (!var.getVariableClass().equals(rawClass) && !var.getVariableClass().equals(componentClass.getRawClass())) {
                iterator.remove();
            }
        }
    }
    logger.debug("Reusable objects: " + objects);
    assignArray(test, array, arrayIndex, position, objects);
}
Also used : GenericClass(org.evosuite.utils.generic.GenericClass)

Example 22 with GenericClass

use of org.evosuite.utils.generic.GenericClass in project evosuite by EvoSuite.

the class TestFactory method createPrimitive.

/**
 * Create and return a new primitive variable
 *
 * @param test
 * @param position
 * @param recursionDepth
 * @return
 * @throws ConstructionFailedException
 */
private VariableReference createPrimitive(TestCase test, GenericClass clazz, int position, int recursionDepth) throws ConstructionFailedException {
    // Special case: we cannot instantiate Class<Class<?>>
    if (clazz.isClass()) {
        if (clazz.hasWildcardOrTypeVariables()) {
            logger.debug("Getting generic instantiation of class");
            clazz = clazz.getGenericInstantiation();
            logger.debug("Chosen: " + clazz);
        }
        Type parameterType = clazz.getParameterTypes().get(0);
        if (!(parameterType instanceof WildcardType) && GenericTypeReflector.erase(parameterType).equals(Class.class)) {
            throw new ConstructionFailedException("Cannot instantiate a class with a class");
        }
    }
    Statement st = PrimitiveStatement.getRandomStatement(test, clazz, position);
    VariableReference ret = test.addStatement(st, position);
    ret.setDistance(recursionDepth);
    return ret;
}
Also used : CaptureType(com.googlecode.gentyref.CaptureType) PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) GenericClass(org.evosuite.utils.generic.GenericClass) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 23 with GenericClass

use of org.evosuite.utils.generic.GenericClass 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;
}
Also used : GenericClass(org.evosuite.utils.generic.GenericClass) PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) GenericMethod(org.evosuite.utils.generic.GenericMethod) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 24 with GenericClass

use of org.evosuite.utils.generic.GenericClass in project evosuite by EvoSuite.

the class TestGenericClass method testWildcardIntegerBoundaries.

@Test
public void testWildcardIntegerBoundaries() {
    WildcardType objectType = new WildcardTypeImpl(new Type[] { Integer.class }, new Type[] {});
    GenericClass integerClass = new GenericClass(Integer.class);
    GenericClass comparableClass = new GenericClass(Comparable.class);
    GenericClass dateClass = new GenericClass(java.util.Date.class);
    GenericClass sqlDateClass = new GenericClass(java.sql.Date.class);
    Assert.assertTrue(integerClass.satisfiesBoundaries(objectType));
    Assert.assertFalse(comparableClass.satisfiesBoundaries(objectType));
    Assert.assertFalse(dateClass.satisfiesBoundaries(objectType));
    Assert.assertFalse(sqlDateClass.satisfiesBoundaries(objectType));
}
Also used : WildcardType(java.lang.reflect.WildcardType) WildcardTypeImpl(org.evosuite.utils.generic.WildcardTypeImpl) GenericClass(org.evosuite.utils.generic.GenericClass) Test(org.junit.Test)

Example 25 with GenericClass

use of org.evosuite.utils.generic.GenericClass in project evosuite by EvoSuite.

the class TestGenericClass method testTypeVariableBoundariesRefined.

@Test
public void testTypeVariableBoundariesRefined() {
    TypeVariable<?> dateTypeVariable = RefinedComparableBoundary.class.getTypeParameters()[0];
    TypeVariable<?> comparableTypeVariable = ComparableBoundary.class.getTypeParameters()[0];
    GenericClass listOfIntegerClass = new GenericClass(Integer.class);
    GenericClass listOfComparableClass = new GenericClass(Comparable.class);
    GenericClass listOfDateClass = new GenericClass(java.util.Date.class);
    GenericClass listOfSqlDateClass = new GenericClass(java.sql.Date.class);
    Assert.assertFalse(listOfIntegerClass.satisfiesBoundaries(dateTypeVariable));
    Assert.assertFalse(listOfComparableClass.satisfiesBoundaries(dateTypeVariable));
    Assert.assertTrue(listOfDateClass.satisfiesBoundaries(dateTypeVariable));
    Assert.assertTrue(listOfSqlDateClass.satisfiesBoundaries(dateTypeVariable));
    Assert.assertTrue(listOfIntegerClass.satisfiesBoundaries(comparableTypeVariable));
    // Assert.assertTrue(listOfComparableClass.satisfiesBoundaries(comparableTypeVariable));
    Assert.assertTrue(listOfDateClass.satisfiesBoundaries(comparableTypeVariable));
// Assert.assertTrue(listOfSqlDateClass.satisfiesBoundaries(comparableTypeVariable));
}
Also used : GenericClass(org.evosuite.utils.generic.GenericClass) Test(org.junit.Test)

Aggregations

GenericClass (org.evosuite.utils.generic.GenericClass)144 Test (org.junit.Test)64 GenericMethod (org.evosuite.utils.generic.GenericMethod)40 Method (java.lang.reflect.Method)36 VariableReference (org.evosuite.testcase.variable.VariableReference)25 GenericConstructor (org.evosuite.utils.generic.GenericConstructor)24 WildcardType (java.lang.reflect.WildcardType)22 TypeToken (com.googlecode.gentyref.TypeToken)20 ConstructionFailedException (org.evosuite.ga.ConstructionFailedException)17 Type (java.lang.reflect.Type)16 ArrayList (java.util.ArrayList)16 GenericAccessibleObject (org.evosuite.utils.generic.GenericAccessibleObject)16 MethodStatement (org.evosuite.testcase.statements.MethodStatement)15 IntPrimitiveStatement (org.evosuite.testcase.statements.numeric.IntPrimitiveStatement)15 ParameterizedType (java.lang.reflect.ParameterizedType)14 WildcardTypeImpl (org.evosuite.utils.generic.WildcardTypeImpl)10 ConstructorStatement (org.evosuite.testcase.statements.ConstructorStatement)9 AnnotatedType (java.lang.reflect.AnnotatedType)8 LinkedList (java.util.LinkedList)8 List (java.util.List)7