Search in sources :

Example 6 with GenericConstructor

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

the class TestFactory method changeCall.

/**
 * Replace the statement with a new statement using given call
 *
 * @param test
 * @param statement
 * @param call
 * @throws ConstructionFailedException
 */
public void changeCall(TestCase test, Statement statement, GenericAccessibleObject<?> call) throws ConstructionFailedException {
    int position = statement.getReturnValue().getStPosition();
    logger.debug("Changing call {} with {}", test.getStatement(position), call);
    if (call.isMethod()) {
        GenericMethod method = (GenericMethod) call;
        if (method.hasTypeParameters())
            throw new ConstructionFailedException("Cannot handle generic methods properly");
        VariableReference retval = statement.getReturnValue();
        VariableReference callee = null;
        if (!method.isStatic()) {
            callee = getRandomNonNullNonPrimitiveObject(test, method.getOwnerType(), position);
        }
        List<VariableReference> parameters = new ArrayList<>();
        for (Type type : method.getParameterTypes()) {
            parameters.add(test.getRandomObject(type, position));
        }
        MethodStatement m = new MethodStatement(test, method, callee, parameters, retval);
        test.setStatement(m, position);
        logger.debug("Using method {}", m.getCode());
    } else if (call.isConstructor()) {
        GenericConstructor constructor = (GenericConstructor) call;
        VariableReference retval = statement.getReturnValue();
        List<VariableReference> parameters = new ArrayList<>();
        for (Type type : constructor.getParameterTypes()) {
            parameters.add(test.getRandomObject(type, position));
        }
        ConstructorStatement c = new ConstructorStatement(test, constructor, retval, parameters);
        test.setStatement(c, position);
        logger.debug("Using constructor {}", c.getCode());
    } else if (call.isField()) {
        GenericField field = (GenericField) call;
        VariableReference retval = statement.getReturnValue();
        VariableReference source = null;
        if (!field.isStatic())
            source = getRandomNonNullNonPrimitiveObject(test, field.getOwnerType(), position);
        try {
            FieldStatement f = new FieldStatement(test, field, source, retval);
            test.setStatement(f, position);
            logger.debug("Using field {}", f.getCode());
        } catch (Throwable e) {
            logger.error("Error: " + e + " , Field: " + field + " , Test: " + test);
            throw new Error(e);
        }
    }
}
Also used : PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) ArrayList(java.util.ArrayList) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericMethod(org.evosuite.utils.generic.GenericMethod) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException) CaptureType(com.googlecode.gentyref.CaptureType) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) MockList(org.evosuite.runtime.mock.MockList) ArrayList(java.util.ArrayList) List(java.util.List) GenericField(org.evosuite.utils.generic.GenericField)

Example 7 with GenericConstructor

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

the class EvoTestCaseCodeGenerator method createMethodCallStmt.

@Override
public void createMethodCallStmt(final CaptureLog log, final int logRecNo) {
    if (log == null)
        throw new IllegalArgumentException("captured log must not be null");
    if (logRecNo <= -1)
        throw new IllegalArgumentException("log record number is invalid: " + logRecNo);
    if (isMaximumLengthReached())
        return;
    // assumption: all necessary statements are created and there is one variable for each referenced object
    final int oid = log.objectIds.get(logRecNo);
    final Object[] methodArgs = log.params.get(logRecNo);
    final String methodName = log.methodNames.get(logRecNo);
    Class<?> type;
    try {
        final String typeName = log.getTypeName(oid);
        type = getClassForName(typeName);
        logger.debug("Creating method call statement for call to method {}.{}", typeName, methodName);
        final Class<?>[] methodParamTypeClasses = getMethodParamTypeClasses(log, logRecNo);
        final ArrayList<VariableReference> args = getArguments(methodArgs, methodParamTypeClasses);
        if (CaptureLog.OBSERVED_INIT.equals(methodName)) {
            // Person var0 = new Person();
            final ConstructorStatement constStmt = new ConstructorStatement(testCase, new GenericConstructor(type.getDeclaredConstructor(methodParamTypeClasses), type), args);
            this.oidToVarRefMap.put(oid, testCase.addStatement(constStmt));
        } else {
            // ------------------ handling for ordinary method calls e.g. var1 = var0.doSth();
            final Object returnValue = log.returnValues.get(logRecNo);
            if (CaptureLog.RETURN_TYPE_VOID.equals(returnValue)) {
                GenericMethod genericMethod = new GenericMethod(this.getDeclaredMethod(type, methodName, methodParamTypeClasses), type);
                MethodStatement m = new MethodStatement(testCase, genericMethod, this.oidToVarRefMap.get(oid), args);
                testCase.addStatement(m);
            } else {
                // final org.objectweb.asm.Type returnType = org.objectweb.asm.Type.getReturnType(methodDesc);
                logger.debug("Callee: {} ({})", this.oidToVarRefMap.get(oid), this.oidToVarRefMap.keySet());
                // Person var0 = var.getPerson();
                final MethodStatement m = new MethodStatement(testCase, new GenericMethod(this.getDeclaredMethod(type, methodName, methodParamTypeClasses), type), this.oidToVarRefMap.get(oid), args);
                final Integer returnValueOID = (Integer) returnValue;
                this.oidToVarRefMap.put(returnValueOID, testCase.addStatement(m));
            }
        }
    } catch (NoSuchMethodException e) {
        logger.info("Method not found; this may happen e.g. if an exception is thrown in the constructor");
        return;
    } catch (final Exception e) {
        logger.info("Error at log record number {}: {}", logRecNo, e.toString());
        logger.info("Test case so far: " + testCase.toCode());
        logger.info(log.toString());
        CodeGeneratorException.propagateError(e, "[logRecNo = %s] - an unexpected error occurred while creating method call stmt for %s.", logRecNo, methodName);
    }
}
Also used : ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericMethod(org.evosuite.utils.generic.GenericMethod)

Example 8 with GenericConstructor

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

the class EvoTestCaseCodeGenerator method createMapInitStmt.

@Override
public void createMapInitStmt(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)) {
            collType = HashMap.class;
        }
        // -- 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 = new ArrayList<VariableReference>();
        for (int i = 0; i < params.length; i++) {
            argOID = (Integer) params[i];
            if (argOID == null) {
                paramList.add(testCase.addStatement(new NullStatement(testCase, Object.class)));
            } else {
                paramList.add(this.oidToVarRefMap.get(argOID));
            }
            if (i % 2 == 1) {
                final Method method = collType.getMethod("put", Object.class, Object.class);
                replaceNullWithNullReferences(paramList, Object.class, Object.class);
                methodStmt = new MethodStatement(testCase, new GenericMethod(method, collType), collRef, paramList);
                testCase.addStatement(methodStmt);
                paramList = new ArrayList<VariableReference>(2);
            }
        }
    } catch (final Exception e) {
        CodeGeneratorException.propagateError(e, "[logRecNo = %s] - an unexpected error occurred while creating map init stmt", logRecNo);
    }
}
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) NullStatement(org.evosuite.testcase.statements.NullStatement)

Example 9 with GenericConstructor

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

the class TestCoverageGoalNameGeneration method testMultipleMethods.

@Test
public void testMultipleMethods() throws NoSuchMethodException {
    TestCase test = new DefaultTestCase();
    GenericConstructor gc = new GenericConstructor(Object.class.getConstructor(), Object.class);
    VariableReference callee = test.addStatement(new ConstructorStatement(test, gc, new ArrayList<VariableReference>()));
    GenericMethod gm = new GenericMethod(Object.class.getMethod("toString"), Object.class);
    test.addStatement(new MethodStatement(test, gm, callee, new ArrayList<VariableReference>()));
    MethodCoverageTestFitness goal1 = new MethodCoverageTestFitness("FooClass", "toString()Ljava/lang/String;");
    test.addCoveredGoal(goal1);
    MethodCoverageTestFitness goal2 = new MethodCoverageTestFitness("FooClass", "foo()Ljava/lang/String;");
    test.addCoveredGoal(goal2);
    MethodCoverageTestFitness goal3 = new MethodCoverageTestFitness("FooClass", "bar()Ljava/lang/String;");
    test.addCoveredGoal(goal3);
    List<TestCase> tests = new ArrayList<>();
    tests.add(test);
    CoverageGoalTestNameGenerationStrategy naming = new CoverageGoalTestNameGenerationStrategy(tests);
    String generatedName = naming.getName(test);
    assertEquals("testToString", generatedName);
// TODO: What should be the name now? Need some heuristic, currently sorted alphabetically
// Better heuristic would consider other things, like e.g. which method has more goals covered
// or which one is the last one called?
}
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) DefaultTestCase(org.evosuite.testcase.DefaultTestCase) GenericMethod(org.evosuite.utils.generic.GenericMethod) TestCase(org.evosuite.testcase.TestCase) DefaultTestCase(org.evosuite.testcase.DefaultTestCase) MethodCoverageTestFitness(org.evosuite.coverage.method.MethodCoverageTestFitness) CoverageGoalTestNameGenerationStrategy(org.evosuite.junit.naming.methods.CoverageGoalTestNameGenerationStrategy) Test(org.junit.Test)

Example 10 with GenericConstructor

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

the class TestSimilarity method testBasicSimilarityDifferentTypes.

@Test
public void testBasicSimilarityDifferentTypes() {
    TestCase test1 = new DefaultTestCase();
    TestCase test2 = new DefaultTestCase();
    PrimitiveStatement<?> aInt = new IntPrimitiveStatement(test1, 42);
    test1.addStatement(aInt);
    PrimitiveStatement<?> aInt2 = new IntPrimitiveStatement(test1, 42);
    test1.addStatement(aInt2);
    PrimitiveStatement<?> bInt = new IntPrimitiveStatement(test2, 42);
    test2.addStatement(bInt);
    Constructor<?> c = Object.class.getConstructors()[0];
    ConstructorStatement cs = new ConstructorStatement(test2, new GenericConstructor(c, Object.class), new ArrayList<VariableReference>());
    test2.addStatement(cs);
    double score = DiversityObserver.getNeedlemanWunschScore(test1, test2);
    Assert.assertTrue(score <= 0);
}
Also used : ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) IntPrimitiveStatement(org.evosuite.testcase.statements.numeric.IntPrimitiveStatement) Test(org.junit.Test)

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