Search in sources :

Example 1 with ConstructorStatement

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

the class NullPointerExceptionContract method check.

/* (non-Javadoc)
	 * @see org.evosuite.contracts.Contract#check(org.evosuite.testcase.TestCase, org.evosuite.testcase.Statement, org.evosuite.testcase.Scope, java.lang.Throwable)
	 */
/**
 * {@inheritDoc}
 */
@Override
public ContractViolation check(Statement statement, Scope scope, Throwable exception) {
    if (!isTargetStatement(statement))
        return null;
    try {
        if (exception != null) {
            // method throws no NullPointerException if no input parameter was null
            if (exception instanceof NullPointerException) {
                StackTraceElement element = exception.getStackTrace()[0];
                // If the exception was thrown in the test directly, it is also not interesting
                if (element.getClassName().startsWith(PackageInfo.getEvoSuitePackage() + ".testcase")) {
                    return null;
                }
                List<VariableReference> parameters = new ArrayList<VariableReference>();
                if (statement instanceof MethodStatement) {
                    MethodStatement ms = (MethodStatement) statement;
                    parameters.addAll(ms.getParameterReferences());
                } else if (statement instanceof ConstructorStatement) {
                    ConstructorStatement cs = (ConstructorStatement) statement;
                    parameters.addAll(cs.getParameterReferences());
                } else {
                    return null;
                }
                boolean hasNull = false;
                for (VariableReference var : parameters) {
                    if (var.getObject(scope) == null) {
                        hasNull = true;
                        break;
                    }
                }
                if (!hasNull) {
                    return new ContractViolation(this, statement, exception);
                }
            }
        }
        return null;
    } catch (CodeUnderTestException e) {
        throw new UnsupportedOperationException();
    }
}
Also used : ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) ArrayList(java.util.ArrayList) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException)

Example 2 with ConstructorStatement

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

the class InspectorTraceObserver method visit.

/* (non-Javadoc)
	 * @see org.evosuite.assertion.AssertionTraceObserver#visit(org.evosuite.testcase.StatementInterface, org.evosuite.testcase.Scope, org.evosuite.testcase.VariableReference)
	 */
/**
 * {@inheritDoc}
 */
@Override
protected void visit(Statement statement, Scope scope, VariableReference var) {
    // TODO: Check the variable class is complex?
    // We don't want inspector checks on string constants
    Statement declaringStatement = currentTest.getStatement(var.getStPosition());
    if (declaringStatement instanceof PrimitiveStatement<?>)
        return;
    if (statement.isAssignmentStatement() && statement.getReturnValue().isArrayIndex())
        return;
    if (statement instanceof ConstructorStatement) {
        if (statement.getReturnValue().isWrapperType() || statement.getReturnValue().isAssignableTo(EvoSuiteMock.class))
            return;
    }
    if (var.isPrimitive() || var.isString() || var.isWrapperType())
        return;
    logger.debug("Checking for inspectors of " + var + " at statement " + statement.getPosition());
    List<Inspector> inspectors = InspectorManager.getInstance().getInspectors(var.getVariableClass());
    InspectorTraceEntry entry = new InspectorTraceEntry(var);
    for (Inspector i : inspectors) {
        // No inspectors from java.lang.Object
        if (i.getMethod().getDeclaringClass().equals(Object.class))
            continue;
        try {
            Object target = var.getObject(scope);
            if (target != null) {
                // Don't call inspector methods on mock objects
                if (target.getClass().getCanonicalName().contains("EnhancerByMockito"))
                    return;
                Object value = i.getValue(target);
                logger.debug("Inspector " + i.getMethodCall() + " is: " + value);
                // We need no assertions that include the memory location
                if (value instanceof String) {
                    // String literals may not be longer than 32767
                    if (((String) value).length() >= 32767)
                        continue;
                    // Maximum length of strings we look at
                    if (((String) value).length() > Properties.MAX_STRING)
                        continue;
                    // If we suspect an Object hashCode not use this, as it may lead to flaky tests
                    if (addressPattern.matcher((String) value).find())
                        continue;
                    // The word "hashCode" is also suspicious
                    if (((String) value).toLowerCase().contains("hashcode"))
                        continue;
                    // Avoid asserting anything on values referring to mockito proxy objects
                    if (((String) value).toLowerCase().contains("EnhancerByMockito"))
                        continue;
                    if (((String) value).toLowerCase().contains("$MockitoMock$"))
                        continue;
                    if (target instanceof URL) {
                        // Absolute paths may be different between executions
                        if (((String) value).startsWith("/") || ((String) value).startsWith("file:/"))
                            continue;
                    }
                }
                entry.addValue(i, value);
            }
        } catch (Exception e) {
            if (e instanceof TimeoutException) {
                logger.debug("Timeout during inspector call - deactivating inspector " + i.getMethodCall());
                InspectorManager.getInstance().removeInspector(var.getVariableClass(), i);
            }
            logger.debug("Exception " + e + " / " + e.getCause());
            if (e.getCause() != null && !e.getCause().getClass().equals(NullPointerException.class)) {
                logger.debug("Exception during call to inspector: " + e + " - " + e.getCause());
            }
        }
    }
    logger.debug("Found " + entry.size() + " inspectors for " + var + " at statement " + statement.getPosition());
    trace.addEntry(statement.getPosition(), var, entry);
}
Also used : ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) Statement(org.evosuite.testcase.statements.Statement) ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) URL(java.net.URL) TimeoutException(java.util.concurrent.TimeoutException) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) EvoSuiteMock(org.evosuite.runtime.mock.EvoSuiteMock) TimeoutException(java.util.concurrent.TimeoutException)

Example 3 with ConstructorStatement

use of org.evosuite.testcase.statements.ConstructorStatement 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 4 with ConstructorStatement

use of org.evosuite.testcase.statements.ConstructorStatement 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 5 with ConstructorStatement

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

ConstructorStatement (org.evosuite.testcase.statements.ConstructorStatement)36 MethodStatement (org.evosuite.testcase.statements.MethodStatement)22 VariableReference (org.evosuite.testcase.variable.VariableReference)22 GenericConstructor (org.evosuite.utils.generic.GenericConstructor)19 GenericMethod (org.evosuite.utils.generic.GenericMethod)15 Method (java.lang.reflect.Method)14 Test (org.junit.Test)14 ArrayList (java.util.ArrayList)13 Statement (org.evosuite.testcase.statements.Statement)10 IntPrimitiveStatement (org.evosuite.testcase.statements.numeric.IntPrimitiveStatement)9 GenericClass (org.evosuite.utils.generic.GenericClass)9 BranchCoverageSuiteFitness (org.evosuite.coverage.branch.BranchCoverageSuiteFitness)7 DefaultTestCase (org.evosuite.testcase.DefaultTestCase)6 FlagExample1 (com.examples.with.different.packagename.FlagExample1)5 BranchCoverageFactory (org.evosuite.coverage.branch.BranchCoverageFactory)5 TestCase (org.evosuite.testcase.TestCase)4 TestFitnessFunction (org.evosuite.testcase.TestFitnessFunction)4 TestFitnessFactory (org.evosuite.coverage.TestFitnessFactory)3 DefUseCoverageFactory (org.evosuite.coverage.dataflow.DefUseCoverageFactory)3 DefUseCoverageSuiteFitness (org.evosuite.coverage.dataflow.DefUseCoverageSuiteFitness)3