Search in sources :

Example 26 with VariableReference

use of org.evosuite.testcase.variable.VariableReference in project evosuite by EvoSuite.

the class SymbolicObserver method after.

private void after(IntPrimitiveStatement statement, Scope scope) {
    int valueOf = statement.getValue();
    VariableReference varRef = statement.getReturnValue();
    String varRefName = varRef.getName();
    IntegerVariable integerVariable = buildIntegerVariable(varRefName, valueOf, Integer.MIN_VALUE, Integer.MAX_VALUE);
    symb_expressions.put(varRefName, integerVariable);
    Integer integer_instance;
    try {
        integer_instance = (Integer) varRef.getObject(scope);
    } catch (CodeUnderTestException e) {
        throw new EvosuiteError(e);
    }
    ReferenceConstant integerRef = newIntegerReference(integer_instance, integerVariable);
    symb_references.put(varRefName, integerRef);
}
Also used : ReferenceConstant(org.evosuite.symbolic.expr.ref.ReferenceConstant) IntegerVariable(org.evosuite.symbolic.expr.bv.IntegerVariable) VariableReference(org.evosuite.testcase.variable.VariableReference) EvosuiteError(org.evosuite.testcase.execution.EvosuiteError) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException)

Example 27 with VariableReference

use of org.evosuite.testcase.variable.VariableReference in project evosuite by EvoSuite.

the class SymbolicObserver method after.

private void after(MethodStatement statement, Scope scope) {
    String owner = statement.getMethod().getDeclaringClass().getName().replace('.', '/');
    String name = statement.getMethod().getName();
    String desc = Type.getMethodDescriptor(statement.getMethod().getMethod());
    Type returnType = Type.getReturnType(statement.getMethod().getMethod());
    VariableReference varRef = statement.getReturnValue();
    String varName = varRef.getName();
    try {
        if (varRef.getType().equals(void.class)) {
            VM.CALL_RESULT(owner, name, desc);
        } else if (returnType.equals(Type.INT_TYPE)) {
            Integer res = (Integer) varRef.getObject(scope);
            VM.CALL_RESULT(res.intValue(), owner, name, desc);
            IntegerValue intExpr = env.topFrame().operandStack.popBv32();
            ReferenceConstant newIntegerRef = newIntegerReference(res, intExpr);
            symb_references.put(varName, newIntegerRef);
            symb_expressions.put(varName, intExpr);
        } else if (returnType.equals(Type.BOOLEAN_TYPE)) {
            Boolean res = (Boolean) varRef.getObject(scope);
            VM.CALL_RESULT(res.booleanValue(), owner, name, desc);
            IntegerValue intExpr = env.topFrame().operandStack.popBv32();
            ReferenceConstant newBooleanRef = newBooleanReference(res, intExpr);
            symb_references.put(varName, newBooleanRef);
            symb_expressions.put(varName, intExpr);
        } else if (returnType.equals(Type.DOUBLE_TYPE)) {
            Double res = (Double) varRef.getObject(scope);
            VM.CALL_RESULT(res.doubleValue(), owner, name, desc);
            RealValue realExpr = env.topFrame().operandStack.popFp64();
            ReferenceConstant newDoubleRef = newDoubleReference(res, realExpr);
            symb_references.put(varName, newDoubleRef);
            symb_expressions.put(varName, realExpr);
        } else if (returnType.equals(Type.FLOAT_TYPE)) {
            Float res = (Float) varRef.getObject(scope);
            VM.CALL_RESULT(res.floatValue(), owner, name, desc);
            RealValue realExpr = env.topFrame().operandStack.popFp32();
            ReferenceConstant newFloatRef = newFloatReference(res, realExpr);
            symb_references.put(varName, newFloatRef);
            symb_expressions.put(varName, realExpr);
        } else if (returnType.equals(Type.LONG_TYPE)) {
            Long res = (Long) varRef.getObject(scope);
            VM.CALL_RESULT(res.longValue(), owner, name, desc);
            IntegerValue intExpr = env.topFrame().operandStack.popBv64();
            ReferenceConstant newBooleanRef = newLongReference(res, intExpr);
            symb_references.put(varName, newBooleanRef);
            symb_expressions.put(varName, intExpr);
        } else if (returnType.equals(Type.SHORT_TYPE)) {
            Short res = (Short) varRef.getObject(scope);
            VM.CALL_RESULT(res.shortValue(), owner, name, desc);
            IntegerValue intExpr = env.topFrame().operandStack.popBv32();
            ReferenceConstant newShortRef = newShortReference(res, intExpr);
            symb_references.put(varName, newShortRef);
            symb_expressions.put(varName, intExpr);
        } else if (returnType.equals(Type.BYTE_TYPE)) {
            Byte res = (Byte) varRef.getObject(scope);
            VM.CALL_RESULT(res.byteValue(), owner, name, desc);
            IntegerValue intExpr = env.topFrame().operandStack.popBv32();
            ReferenceConstant newByteRef = newByteReference(res, intExpr);
            symb_references.put(varName, newByteRef);
            symb_expressions.put(varName, intExpr);
        } else if (returnType.equals(Type.CHAR_TYPE)) {
            Character res = (Character) varRef.getObject(scope);
            VM.CALL_RESULT(res.charValue(), owner, name, desc);
            IntegerValue intExpr = env.topFrame().operandStack.popBv32();
            ReferenceConstant newCharacterRef = newCharacterReference(res, intExpr);
            symb_references.put(varName, newCharacterRef);
            symb_expressions.put(varName, intExpr);
        } else {
            Object res = varRef.getObject(scope);
            VM.CALL_RESULT(res, owner, name, desc);
            ReferenceExpression ref = env.topFrame().operandStack.peekRef();
            if (res != null && res instanceof String) {
                String string = (String) res;
                ReferenceConstant newStringRef = (ReferenceConstant) env.heap.getReference(string);
                StringValue str_expr = env.heap.getField(Types.JAVA_LANG_STRING, SymbolicHeap.$STRING_VALUE, string, newStringRef, string);
                symb_references.put(varName, newStringRef);
                symb_expressions.put(varName, str_expr);
            } else {
                symb_references.put(varName, ref);
                if (res != null && isWrapper(res)) {
                    ReferenceConstant nonNullRef = (ReferenceConstant) ref;
                    Expression<?> expr = findOrCreate(res, nonNullRef);
                    symb_expressions.put(varName, expr);
                }
            }
        }
    } catch (CodeUnderTestException e) {
        throw new RuntimeException(e);
    }
    // dispose all other arguments
    env.topFrame().operandStack.clearOperands();
}
Also used : RealValue(org.evosuite.symbolic.expr.fp.RealValue) VariableReference(org.evosuite.testcase.variable.VariableReference) IntegerValue(org.evosuite.symbolic.expr.bv.IntegerValue) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException) ReferenceConstant(org.evosuite.symbolic.expr.ref.ReferenceConstant) Type(org.objectweb.asm.Type) ReferenceExpression(org.evosuite.symbolic.expr.ref.ReferenceExpression) StringValue(org.evosuite.symbolic.expr.str.StringValue)

Example 28 with VariableReference

use of org.evosuite.testcase.variable.VariableReference in project evosuite by EvoSuite.

the class TestCluster method getRandomGenerator.

/**
 * Randomly select one generator
 *
 * @param clazz
 * @param excluded
 * @param test
 * @return {@code null} if there is no valid generator
 * @throws ConstructionFailedException
 */
public GenericAccessibleObject<?> getRandomGenerator(GenericClass clazz, Set<GenericAccessibleObject<?>> excluded, TestCase test, int position, VariableReference generatorRefToExclude, int recursionDepth) throws ConstructionFailedException {
    logger.debug("Getting random generator for " + clazz);
    // Instantiate generics
    if (clazz.hasWildcardOrTypeVariables()) {
        logger.debug("Target class is generic: " + clazz);
        GenericClass concreteClass = clazz.getGenericInstantiation();
        if (!concreteClass.equals(clazz)) {
            logger.debug("Target class is generic: " + clazz + ", getting instantiation " + concreteClass);
            return getRandomGenerator(concreteClass, excluded, test, position, generatorRefToExclude, recursionDepth);
        }
    }
    GenericAccessibleObject<?> generator = null;
    // Collection, Map, Number
    if (isSpecialCase(clazz)) {
        generator = Randomness.choice(getGeneratorsForSpecialCase(clazz));
        if (generator == null) {
            logger.warn("No generator for special case class: " + clazz);
            throw new ConstructionFailedException("Have no generators for special case: " + clazz);
        }
    } else {
        cacheGenerators(clazz);
        Set<GenericAccessibleObject<?>> candidates = new LinkedHashSet<>(generatorCache.get(clazz));
        candidates.removeAll(excluded);
        if (Properties.JEE) {
            Iterator<GenericAccessibleObject<?>> iter = candidates.iterator();
            while (iter.hasNext()) {
                GenericAccessibleObject<?> gao = iter.next();
                if (gao instanceof GenericConstructor) {
                    Class<?> klass = gao.getDeclaringClass();
                    if (InstanceOnlyOnce.canInstantiateOnlyOnce(klass) && ConstraintHelper.countNumberOfNewInstances(test, klass) != 0) {
                        iter.remove();
                    }
                }
                if (!ConstraintVerifier.isValidPositionForInsertion(gao, test, position)) {
                    iter.remove();
                }
            }
        }
        if (generatorRefToExclude != null) {
            Iterator<GenericAccessibleObject<?>> iter = candidates.iterator();
            while (iter.hasNext()) {
                GenericAccessibleObject<?> gao = iter.next();
                // if current generator could be called from excluded ref, then we cannot use it
                if (generatorRefToExclude.isAssignableTo(gao.getOwnerType())) {
                    iter.remove();
                }
            }
        }
        logger.debug("Candidate generators for " + clazz + ": " + candidates.size());
        if (candidates.isEmpty()) {
            return null;
        }
        if (recursionDepth >= Properties.MAX_RECURSION / 2) {
            /*
					if going long into the recursion, then do prefer direct constructors or static methods,
					as non-static methods would require to get a caller which, if it is missing, would need
					to be created, and that could lead to further calls if its generators need input parameters
				 */
            Set<GenericAccessibleObject<?>> set = candidates.stream().filter(p -> p.isStatic() || p.isConstructor()).collect(Collectors.toCollection(() -> new LinkedHashSet<GenericAccessibleObject<?>>()));
            if (!set.isEmpty()) {
                candidates = set;
            }
        }
        generator = Randomness.choice(candidates);
        logger.debug("Chosen generator: " + generator);
    }
    if (generator.getOwnerClass().hasWildcardOrTypeVariables()) {
        logger.debug("Owner class has a wildcard: " + clazz.getTypeName());
        generator = generator.copyWithNewOwner(generator.getOwnerClass().getGenericInstantiation());
    }
    if (generator.hasTypeParameters()) {
        logger.debug("Generator has a type parameter: " + generator);
        generator = generator.getGenericInstantiationFromReturnValue(clazz);
        if (!generator.getGeneratedClass().isAssignableTo(clazz)) {
            throw new ConstructionFailedException("Generics error");
        }
    }
    return generator;
}
Also used : GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) GenericClass(org.evosuite.utils.generic.GenericClass) java.util(java.util) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException) InstanceOnlyOnce(org.evosuite.testcase.jee.InstanceOnlyOnce) LoggerFactory(org.slf4j.LoggerFactory) Archive(org.evosuite.ga.archive.Archive) Constructor(java.lang.reflect.Constructor) GenericMethod(org.evosuite.utils.generic.GenericMethod) ConstraintHelper(org.evosuite.testcase.ConstraintHelper) TestCase(org.evosuite.testcase.TestCase) CoverageAnalysis(org.evosuite.junit.CoverageAnalysis) AtMostOnceLogger(org.evosuite.runtime.util.AtMostOnceLogger) Properties(org.evosuite.Properties) Logger(org.slf4j.Logger) VariableReference(org.evosuite.testcase.variable.VariableReference) Inputs(org.evosuite.runtime.util.Inputs) GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) CastClassManager(org.evosuite.seeding.CastClassManager) Collectors(java.util.stream.Collectors) Randomness(org.evosuite.utils.Randomness) TestGenerationContext(org.evosuite.TestGenerationContext) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) ListUtil(org.evosuite.utils.ListUtil) Type(java.lang.reflect.Type) Entry(java.util.Map.Entry) ConstraintVerifier(org.evosuite.testcase.ConstraintVerifier) GenericClass(org.evosuite.utils.generic.GenericClass) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 29 with VariableReference

use of org.evosuite.testcase.variable.VariableReference in project evosuite by EvoSuite.

the class TestChromosome method mockChange.

private boolean mockChange() {
    /*
			Be sure to update the mocked values if there has been any change in
			behavior in the last execution.

			Note: mock "expansion" cannot be done after a test has been mutated and executed,
			as the expansion itself might have side effects. Therefore, it has to be done
			before a test is evaluated.
		 */
    boolean changed = false;
    for (int i = 0; i < test.size(); i++) {
        Statement st = test.getStatement(i);
        if (!(st instanceof FunctionalMockStatement)) {
            continue;
        }
        FunctionalMockStatement fms = (FunctionalMockStatement) st;
        if (!fms.doesNeedToUpdateInputs()) {
            continue;
        }
        int preLength = test.size();
        try {
            List<Type> missing = fms.updateMockedMethods();
            int pos = st.getPosition();
            logger.debug("Generating parameters for mock call");
            // Added 'null' as additional parameter - fix for @NotNull annotations issue on evo mailing list
            List<VariableReference> refs = TestFactory.getInstance().satisfyParameters(test, null, missing, null, pos, 0, true, false, true);
            fms.addMissingInputs(refs);
        } catch (Exception e) {
            // shouldn't really happen because, in the worst case, we could create mocks for missing parameters
            String msg = "Functional mock problem: " + e.toString();
            AtMostOnceLogger.warn(logger, msg);
            fms.fillWithNullRefs();
            return changed;
        }
        changed = true;
        int increase = test.size() - preLength;
        i += increase;
    }
    return changed;
}
Also used : Type(java.lang.reflect.Type) VariableReference(org.evosuite.testcase.variable.VariableReference) FunctionalMockStatement(org.evosuite.testcase.statements.FunctionalMockStatement) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) Statement(org.evosuite.testcase.statements.Statement) FunctionalMockStatement(org.evosuite.testcase.statements.FunctionalMockStatement) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 30 with VariableReference

use of org.evosuite.testcase.variable.VariableReference in project evosuite by EvoSuite.

the class EvoTestCaseCodeGenerator method getArguments.

private ArrayList<VariableReference> getArguments(final Object[] methodArgs, final Class<?>[] methodParamTypeClasses) throws IllegalArgumentException {
    ArrayList<VariableReference> args = new ArrayList<VariableReference>();
    // is either an oid or null
    Integer argOID;
    for (int i = 0; i < methodArgs.length; i++) {
        argOID = (Integer) methodArgs[i];
        if (argOID == null) {
            args.add(testCase.addStatement(new NullStatement(testCase, methodParamTypeClasses[i])));
        } else {
            VariableReference ref = this.oidToVarRefMap.get(argOID);
            if (ref == null) {
                throw new RuntimeException("VariableReference is null for argOID " + argOID + "; have oids: " + this.oidToVarRefMap.keySet());
            } else {
                args.add(ref);
            }
        }
    }
    return args;
}
Also used : VariableReference(org.evosuite.testcase.variable.VariableReference) NullStatement(org.evosuite.testcase.statements.NullStatement) ArrayList(java.util.ArrayList)

Aggregations

VariableReference (org.evosuite.testcase.variable.VariableReference)472 Method (java.lang.reflect.Method)289 TestCaseBuilder (org.evosuite.symbolic.TestCaseBuilder)143 Test (org.junit.Test)73 GenericMethod (org.evosuite.utils.generic.GenericMethod)68 GenericConstructor (org.evosuite.utils.generic.GenericConstructor)55 MethodStatement (org.evosuite.testcase.statements.MethodStatement)44 DefaultTestCase (org.evosuite.testcase.DefaultTestCase)38 ArrayList (java.util.ArrayList)31 GenericClass (org.evosuite.utils.generic.GenericClass)27 TestCase (org.evosuite.testcase.TestCase)26 CodeUnderTestException (org.evosuite.testcase.execution.CodeUnderTestException)26 ConstructorStatement (org.evosuite.testcase.statements.ConstructorStatement)25 IntPrimitiveStatement (org.evosuite.testcase.statements.numeric.IntPrimitiveStatement)19 Type (java.lang.reflect.Type)17 Statement (org.evosuite.testcase.statements.Statement)17 EvosuiteError (org.evosuite.testcase.execution.EvosuiteError)15 ArrayReference (org.evosuite.testcase.variable.ArrayReference)15 VariableReferenceImpl (org.evosuite.testcase.variable.VariableReferenceImpl)15 ReferenceConstant (org.evosuite.symbolic.expr.ref.ReferenceConstant)14