Search in sources :

Example 66 with GenericConstructor

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);
}
Also used : GenericArrayType(java.lang.reflect.GenericArrayType) WildcardType(java.lang.reflect.WildcardType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) CaptureType(com.googlecode.gentyref.CaptureType) GenericConstructor(org.evosuite.utils.generic.GenericConstructor)

Example 67 with GenericConstructor

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");
    }
}
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)

Example 68 with GenericConstructor

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);
    }
}
Also used : ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) ArrayList(java.util.ArrayList) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericMethod(org.evosuite.utils.generic.GenericMethod) Method(java.lang.reflect.Method) GenericMethod(org.evosuite.utils.generic.GenericMethod) ArrayDeque(java.util.ArrayDeque) NullStatement(org.evosuite.testcase.statements.NullStatement) ArrayList(java.util.ArrayList) List(java.util.List) ResourceList(org.evosuite.classpath.ResourceList) HashSet(java.util.HashSet)

Example 69 with GenericConstructor

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;
}
Also used : DefaultTestCase(org.evosuite.testcase.DefaultTestCase) TestCase(org.evosuite.testcase.TestCase) TestFactory(org.evosuite.testcase.TestFactory) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 70 with GenericConstructor

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;
}
Also used : MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) GenericClass(org.evosuite.utils.generic.GenericClass) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericMethod(org.evosuite.utils.generic.GenericMethod) Method(java.lang.reflect.Method) GenericMethod(org.evosuite.utils.generic.GenericMethod) IntPrimitiveStatement(org.evosuite.testcase.statements.numeric.IntPrimitiveStatement)

Aggregations

GenericConstructor (org.evosuite.utils.generic.GenericConstructor)76 GenericMethod (org.evosuite.utils.generic.GenericMethod)61 VariableReference (org.evosuite.testcase.variable.VariableReference)56 Test (org.junit.Test)47 Method (java.lang.reflect.Method)30 GenericClass (org.evosuite.utils.generic.GenericClass)25 MethodStatement (org.evosuite.testcase.statements.MethodStatement)22 ConstructorStatement (org.evosuite.testcase.statements.ConstructorStatement)19 ArrayList (java.util.ArrayList)17 IntPrimitiveStatement (org.evosuite.testcase.statements.numeric.IntPrimitiveStatement)17 DefaultTestCase (org.evosuite.testcase.DefaultTestCase)11 Injector (org.evosuite.runtime.javaee.injection.Injector)9 GenericAccessibleObject (org.evosuite.utils.generic.GenericAccessibleObject)8 GenericField (org.evosuite.utils.generic.GenericField)8 AbstractEnumInInnerClass (com.examples.with.different.packagename.AbstractEnumInInnerClass)7 BranchCoverageSuiteFitness (org.evosuite.coverage.branch.BranchCoverageSuiteFitness)7 ConstructionFailedException (org.evosuite.ga.ConstructionFailedException)7 EnumInInnerClass (com.examples.with.different.packagename.EnumInInnerClass)6 FactoryExample (com.examples.with.different.packagename.FactoryExample)6 Type (java.lang.reflect.Type)6