Search in sources :

Example 6 with MethodStatement

use of org.evosuite.testcase.statements.MethodStatement in project evosuite by EvoSuite.

the class OutputObserver method afterStatement.

/* (non-Javadoc)
     * @see org.evosuite.testcase.ExecutionObserver#afterStatement(org.evosuite.testcase.StatementInterface, org.evosuite.testcase.Scope, java.lang.Throwable)
     */
@Override
public void afterStatement(Statement statement, Scope scope, Throwable exception) {
    if (statement instanceof MethodStatement) {
        MethodStatement methodStmt = (MethodStatement) statement;
        VariableReference varRef = methodStmt.getReturnValue();
        try {
            Object returnObject = varRef.getObject(scope);
            if (exception == null && !methodStmt.getReturnType().equals(Void.TYPE)) {
                // we don't save anything if there was an exception
                // we are only interested in methods whose return type != void
                String className = methodStmt.getDeclaringClassName();
                String methodDesc = methodStmt.getDescriptor();
                String methodName = methodStmt.getMethodName();
                outputCoverage.put(statement.getPosition(), OutputCoverageGoal.createGoalsFromObject(className, methodName, methodDesc, returnObject));
            }
        } catch (CodeUnderTestException e) {
        // ignore?
        }
    }
}
Also used : MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException)

Example 7 with MethodStatement

use of org.evosuite.testcase.statements.MethodStatement 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 MethodStatement

use of org.evosuite.testcase.statements.MethodStatement 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 MethodStatement

use of org.evosuite.testcase.statements.MethodStatement in project evosuite by EvoSuite.

the class ConstantInliner method afterStatement.

/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.evosuite.testcase.ExecutionObserver#statement(org.evosuite.testcase.
	 * StatementInterface, org.evosuite.testcase.Scope, java.lang.Throwable)
	 */
/**
 * {@inheritDoc}
 */
@Override
public void afterStatement(Statement statement, Scope scope, Throwable exception) {
    try {
        for (VariableReference var : statement.getVariableReferences()) {
            if (var.equals(statement.getReturnValue()) || var.equals(statement.getReturnValue().getAdditionalVariableReference()))
                continue;
            Object object = var.getObject(scope);
            if (var.isPrimitive()) {
                ConstantValue value = new ConstantValue(test, var.getGenericClass());
                value.setValue(object);
                // logger.info("Statement before inlining: " +
                // statement.getCode());
                statement.replace(var, value);
            // logger.info("Statement after inlining: " +
            // statement.getCode());
            } else if (var.isString() && object != null) {
                ConstantValue value = new ConstantValue(test, var.getGenericClass());
                try {
                    String val = StringEscapeUtils.unescapeJava(new String(object.toString()));
                    if (val.length() < Properties.MAX_STRING) {
                        value.setValue(val);
                        statement.replace(var, value);
                    }
                } catch (IllegalArgumentException e) {
                    // Exceptions may happen if strings are not valid
                    // unicode
                    logger.info("Cannot escape invalid string: " + object);
                }
            // logger.info("Statement after inlining: " +
            // statement.getCode());
            } else if (var.isArrayIndex()) {
                // then replace the array index with that object
                for (VariableReference otherVar : scope.getElements(var.getType())) {
                    Object otherObject = otherVar.getObject(scope);
                    if (otherObject == object && !otherVar.isArrayIndex() && otherVar.getStPosition() < statement.getPosition()) {
                        statement.replace(var, otherVar);
                        break;
                    }
                }
            } else {
                // the assertion for now
                if (object == null) {
                    if (statement instanceof MethodStatement) {
                        MethodStatement ms = (MethodStatement) statement;
                        if (var.equals(ms.getCallee())) {
                            // Don't put null in callee's, the compiler will not accept it
                            continue;
                        }
                    } else if (statement instanceof FieldStatement) {
                        FieldStatement fs = (FieldStatement) statement;
                        if (var.equals(fs.getSource())) {
                            // Don't put null in source, the compiler will not accept it
                            continue;
                        }
                    }
                    ConstantValue value = new ConstantValue(test, var.getGenericClass());
                    value.setValue(null);
                    // logger.info("Statement before inlining: " +
                    // statement.getCode());
                    statement.replace(var, value);
                // logger.info("Statement after inlining: " +
                // statement.getCode());
                }
            }
        }
    } catch (CodeUnderTestException e) {
        logger.warn("Not inlining test: " + e.getCause());
    // throw new AssertionError("This case isn't handled yet: " +
    // e.getCause()
    // + ", " + Arrays.asList(e.getStackTrace()));
    }
}
Also used : MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) FieldStatement(org.evosuite.testcase.statements.FieldStatement) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException) ConstantValue(org.evosuite.testcase.variable.ConstantValue)

Example 10 with MethodStatement

use of org.evosuite.testcase.statements.MethodStatement 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)

Aggregations

MethodStatement (org.evosuite.testcase.statements.MethodStatement)54 VariableReference (org.evosuite.testcase.variable.VariableReference)40 GenericMethod (org.evosuite.utils.generic.GenericMethod)29 Method (java.lang.reflect.Method)25 ConstructorStatement (org.evosuite.testcase.statements.ConstructorStatement)22 GenericConstructor (org.evosuite.utils.generic.GenericConstructor)22 Statement (org.evosuite.testcase.statements.Statement)19 GenericClass (org.evosuite.utils.generic.GenericClass)15 DefaultTestCase (org.evosuite.testcase.DefaultTestCase)11 IntPrimitiveStatement (org.evosuite.testcase.statements.numeric.IntPrimitiveStatement)10 ArrayList (java.util.ArrayList)9 Test (org.junit.Test)8 TestCase (org.evosuite.testcase.TestCase)7 CodeUnderTestException (org.evosuite.testcase.execution.CodeUnderTestException)5 FieldStatement (org.evosuite.testcase.statements.FieldStatement)5 StringPrimitiveStatement (org.evosuite.testcase.statements.StringPrimitiveStatement)5 HashSet (java.util.HashSet)4 TestFactory (org.evosuite.testcase.TestFactory)4 AssignmentStatement (org.evosuite.testcase.statements.AssignmentStatement)4 PrimitiveStatement (org.evosuite.testcase.statements.PrimitiveStatement)4