Search in sources :

Example 91 with GenericMethod

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

the class TestCodeVisitor method visitMethodStatement.

/*
	 * (non-Javadoc)
	 * 
	 * @see org.evosuite.testcase.TestVisitor#visitMethodStatement(org.evosuite.testcase.MethodStatement)
	 */
/**
 * {@inheritDoc}
 */
@Override
public void visitMethodStatement(MethodStatement statement) {
    String result = "";
    VariableReference retval = statement.getReturnValue();
    GenericMethod method = statement.getMethod();
    Throwable exception = getException(statement);
    List<VariableReference> parameters = statement.getParameterReferences();
    boolean isGenericMethod = method.hasTypeParameters();
    if (exception != null && !statement.isDeclaredException(exception)) {
        result += "// Undeclared exception!" + NEWLINE;
    }
    boolean lastStatement = statement.getPosition() == statement.getTestCase().size() - 1;
    boolean unused = !Properties.ASSERTIONS ? exception != null : test != null && !test.hasReferences(retval);
    if (!retval.isVoid() && retval.getAdditionalVariableReference() == null && !unused) {
        if (exception != null) {
            if (!lastStatement || statement.hasAssertions())
                result += getClassName(retval) + " " + getVariableName(retval) + " = " + retval.getDefaultValueString() + ";" + NEWLINE;
        } else {
            result += getClassName(retval) + " ";
        }
    }
    if (shouldUseTryCatch(exception, statement.isDeclaredException(exception))) {
        result += "try { " + NEWLINE + "  ";
    }
    String parameter_string = getParameterString(method.getParameterTypes(), parameters, isGenericMethod, method.isOverloaded(parameters), 0);
    String callee_str = "";
    if (!unused && !retval.isAssignableFrom(method.getReturnType()) && !retval.getVariableClass().isAnonymousClass() && // Static generic methods are a special case where we shouldn't add a cast
    !(isGenericMethod && method.getParameterTypes().length == 0 && method.isStatic())) {
        String name = getClassName(retval);
        if (!name.matches(".*\\.\\d+$")) {
            callee_str = "(" + name + ")";
        }
    }
    if (method.isStatic()) {
        callee_str += getClassName(method.getMethod().getDeclaringClass());
    } else {
        VariableReference callee = statement.getCallee();
        if (callee instanceof ConstantValue) {
            callee_str += "((" + getClassName(method.getMethod().getDeclaringClass()) + ")" + getVariableName(callee) + ")";
        } else {
            // If the method is not public and this is a subclass in a different package we need to cast
            if (!method.isPublic() && !method.getDeclaringClass().equals(callee.getVariableClass()) && callee.isAssignableTo(method.getMethod().getDeclaringClass())) {
                String packageName1 = ClassUtils.getPackageName(method.getDeclaringClass());
                String packageName2 = ClassUtils.getPackageName(callee.getVariableClass());
                if (!packageName1.equals(packageName2)) {
                    callee_str += "((" + getClassName(method.getMethod().getDeclaringClass()) + ")" + getVariableName(callee) + ")";
                } else {
                    callee_str += getVariableName(callee);
                }
            } else if (!callee.isAssignableTo(method.getMethod().getDeclaringClass())) {
                try {
                    // If the concrete callee class has that method then it's ok
                    callee.getVariableClass().getDeclaredMethod(method.getName(), method.getRawParameterTypes());
                    callee_str += getVariableName(callee);
                } catch (NoSuchMethodException e) {
                    // If not we need to cast to the subtype
                    callee_str += "((" + getTypeName(method.getMethod().getDeclaringClass()) + ") " + getVariableName(callee) + ")";
                // TODO: Here we could check if this is actually possible
                // ...but what would we do?
                // if(!ClassUtils.getAllSuperclasses(method.getMethod().getDeclaringClass()).contains(callee.getVariableClass())) {
                // }
                }
            } else {
                callee_str += getVariableName(callee);
            }
        }
    }
    if (retval.isVoid()) {
        result += callee_str + "." + method.getName() + "(" + parameter_string + ");";
    } else {
        // if (exception == null || !lastStatement)
        if (!unused)
            result += getVariableName(retval) + " = ";
        // If unused, then we don't want to print anything:
        // else
        // result += getClassName(retval) + " " + getVariableName(retval) + " = ";
        result += callee_str + "." + method.getName() + "(" + parameter_string + ");";
    }
    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 : GenericMethod(org.evosuite.utils.generic.GenericMethod)

Example 92 with GenericMethod

use of org.evosuite.utils.generic.GenericMethod 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 93 with GenericMethod

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

the class TestFactory method addCallFor.

/**
 * Append given call to the test case at given position
 *
 * @param test
 * @param call
 * @param position
 */
private boolean addCallFor(TestCase test, VariableReference callee, GenericAccessibleObject<?> call, int position) {
    logger.trace("addCallFor {}", callee.getName());
    int previousLength = test.size();
    currentRecursion.clear();
    try {
        if (call.isMethod()) {
            GenericMethod method = (GenericMethod) call;
            if (call.isStatic() || !method.getDeclaringClass().isAssignableFrom(callee.getVariableClass())) {
                // Static methods / methods in other classes can be modifiers of the SUT if the SUT depends on static fields
                addMethod(test, method, position, 0);
            } else {
                addMethodFor(test, callee, (GenericMethod) call.copyWithNewOwner(callee.getGenericClass()), position);
            }
        } else if (call.isField()) {
            // A modifier for the SUT could also be a static field in another class
            if (call.isStatic()) {
                addFieldAssignment(test, (GenericField) call, position, 0);
            } else {
                addFieldFor(test, callee, (GenericField) call.copyWithNewOwner(callee.getGenericClass()), position);
            }
        }
        return true;
    } catch (ConstructionFailedException e) {
        // TODO: Check this!
        logger.debug("Inserting call {} has failed: {} Removing statements", call, e);
        // TODO: Doesn't work if position != test.size()
        int lengthDifference = test.size() - previousLength;
        for (int i = lengthDifference - 1; i >= 0; i--) {
            // we need to remove them in order, so that the testcase is at all time consistent
            if (logger.isDebugEnabled()) {
                logger.debug("  Removing statement: " + test.getStatement(position + i).getCode());
            }
            test.remove(position + i);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Test after removal: " + test.toCode());
        }
        return false;
    }
}
Also used : GenericMethod(org.evosuite.utils.generic.GenericMethod) GenericField(org.evosuite.utils.generic.GenericField) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 94 with GenericMethod

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

the class TestFactory method getPossibleCalls.

/**
 * Retrieve all the replacement calls that can be inserted at this position
 * without changing the length
 *
 * @param returnType
 * @param objects
 * @return
 */
private List<GenericAccessibleObject<?>> getPossibleCalls(Type returnType, List<VariableReference> objects) {
    List<GenericAccessibleObject<?>> calls = new ArrayList<GenericAccessibleObject<?>>();
    Set<GenericAccessibleObject<?>> allCalls;
    try {
        allCalls = TestCluster.getInstance().getGenerators(new GenericClass(returnType), true);
    } catch (ConstructionFailedException e) {
        return calls;
    }
    for (GenericAccessibleObject<?> call : allCalls) {
        Set<Type> dependencies = null;
        if (call.isMethod()) {
            GenericMethod method = (GenericMethod) call;
            if (method.hasTypeParameters()) {
                try {
                    call = method.getGenericInstantiation(new GenericClass(returnType));
                } catch (ConstructionFailedException e) {
                    continue;
                }
            }
            if (!((GenericMethod) call).getReturnType().equals(returnType))
                continue;
            dependencies = getDependencies((GenericMethod) call);
        } else if (call.isConstructor()) {
            dependencies = getDependencies((GenericConstructor) call);
        } else if (call.isField()) {
            if (!((GenericField) call).getFieldType().equals(returnType))
                continue;
            dependencies = getDependencies((GenericField) call);
        } else {
            assert (false);
        }
        if (dependenciesSatisfied(dependencies, objects)) {
            calls.add(call);
        }
    }
    return calls;
}
Also used : GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) CaptureType(com.googlecode.gentyref.CaptureType) GenericClass(org.evosuite.utils.generic.GenericClass) ArrayList(java.util.ArrayList) GenericMethod(org.evosuite.utils.generic.GenericMethod) GenericField(org.evosuite.utils.generic.GenericField) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 95 with GenericMethod

use of org.evosuite.utils.generic.GenericMethod 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)

Aggregations

GenericMethod (org.evosuite.utils.generic.GenericMethod)110 Test (org.junit.Test)68 VariableReference (org.evosuite.testcase.variable.VariableReference)64 GenericConstructor (org.evosuite.utils.generic.GenericConstructor)60 Method (java.lang.reflect.Method)57 GenericClass (org.evosuite.utils.generic.GenericClass)40 MethodStatement (org.evosuite.testcase.statements.MethodStatement)29 IntPrimitiveStatement (org.evosuite.testcase.statements.numeric.IntPrimitiveStatement)19 ArrayList (java.util.ArrayList)18 DefaultTestCase (org.evosuite.testcase.DefaultTestCase)17 ConstructorStatement (org.evosuite.testcase.statements.ConstructorStatement)15 TestCase (org.evosuite.testcase.TestCase)12 BranchCoverageSuiteFitness (org.evosuite.coverage.branch.BranchCoverageSuiteFitness)11 Injector (org.evosuite.runtime.javaee.injection.Injector)10 Type (java.lang.reflect.Type)9 ConstructionFailedException (org.evosuite.ga.ConstructionFailedException)8 EvoServletState (org.evosuite.runtime.javaee.javax.servlet.EvoServletState)8 GenericAccessibleObject (org.evosuite.utils.generic.GenericAccessibleObject)8 GenericField (org.evosuite.utils.generic.GenericField)8 TestSuiteChromosome (org.evosuite.testsuite.TestSuiteChromosome)7