Search in sources :

Example 1 with GenericMethod

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

the class TestSuiteGenerator method buildLoadTargetClassTestCase.

/**
 * Creates a single Test Case that only loads the target class.
 * <code>
 * Thread currentThread = Thread.currentThread();
 * ClassLoader classLoader = currentThread.getClassLoader();
 * classLoader.load(className);
 * </code>
 * @param className the class to be loaded
 * @return
 * @throws EvosuiteError if a reflection error happens while creating the test case
 */
private static DefaultTestCase buildLoadTargetClassTestCase(String className) throws EvosuiteError {
    DefaultTestCase test = new DefaultTestCase();
    StringPrimitiveStatement stmt0 = new StringPrimitiveStatement(test, className);
    VariableReference string0 = test.addStatement(stmt0);
    try {
        Method currentThreadMethod = Thread.class.getMethod("currentThread");
        Statement currentThreadStmt = new MethodStatement(test, new GenericMethod(currentThreadMethod, currentThreadMethod.getDeclaringClass()), null, Collections.emptyList());
        VariableReference currentThreadVar = test.addStatement(currentThreadStmt);
        Method getContextClassLoaderMethod = Thread.class.getMethod("getContextClassLoader");
        Statement getContextClassLoaderStmt = new MethodStatement(test, new GenericMethod(getContextClassLoaderMethod, getContextClassLoaderMethod.getDeclaringClass()), currentThreadVar, Collections.emptyList());
        VariableReference contextClassLoaderVar = test.addStatement(getContextClassLoaderStmt);
        // Method loadClassMethod = ClassLoader.class.getMethod("loadClass", String.class);
        // Statement loadClassStmt = new MethodStatement(test,
        // new GenericMethod(loadClassMethod, loadClassMethod.getDeclaringClass()), contextClassLoaderVar,
        // Collections.singletonList(string0));
        // test.addStatement(loadClassStmt);
        BooleanPrimitiveStatement stmt1 = new BooleanPrimitiveStatement(test, true);
        VariableReference boolean0 = test.addStatement(stmt1);
        Method forNameMethod = Class.class.getMethod("forName", String.class, boolean.class, ClassLoader.class);
        Statement forNameStmt = new MethodStatement(test, new GenericMethod(forNameMethod, forNameMethod.getDeclaringClass()), null, Arrays.<VariableReference>asList(string0, boolean0, contextClassLoaderVar));
        test.addStatement(forNameStmt);
        return test;
    } catch (NoSuchMethodException | SecurityException e) {
        throw new EvosuiteError("Unexpected exception while creating Class Initializer Test Case");
    }
}
Also used : StringPrimitiveStatement(org.evosuite.testcase.statements.StringPrimitiveStatement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) EvosuiteError(org.evosuite.testcase.execution.EvosuiteError) BooleanPrimitiveStatement(org.evosuite.testcase.statements.numeric.BooleanPrimitiveStatement) Statement(org.evosuite.testcase.statements.Statement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) StringPrimitiveStatement(org.evosuite.testcase.statements.StringPrimitiveStatement) BooleanPrimitiveStatement(org.evosuite.testcase.statements.numeric.BooleanPrimitiveStatement) DefaultTestCase(org.evosuite.testcase.DefaultTestCase) Method(java.lang.reflect.Method) GenericMethod(org.evosuite.utils.generic.GenericMethod) GenericMethod(org.evosuite.utils.generic.GenericMethod)

Example 2 with GenericMethod

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

the class EqualsSymmetricContract method addAssertionAndComments.

@Override
public void addAssertionAndComments(Statement statement, List<VariableReference> variables, Throwable exception) {
    TestCase test = statement.getTestCase();
    VariableReference a = variables.get(0);
    VariableReference b = variables.get(1);
    try {
        Method equalsMethod = a.getGenericClass().getRawClass().getMethod("equals", new Class<?>[] { Object.class });
        GenericMethod method = new GenericMethod(equalsMethod, a.getGenericClass());
        // Create x = a.equals(b)
        Statement st1 = new MethodStatement(test, method, a, Arrays.asList(new VariableReference[] { b }));
        VariableReference x = test.addStatement(st1, statement.getPosition() + 1);
        // Create y = b.equals(a);
        Statement st2 = new MethodStatement(test, method, b, Arrays.asList(new VariableReference[] { a }));
        VariableReference y = test.addStatement(st2, statement.getPosition() + 2);
        Statement newStatement = test.getStatement(y.getStPosition());
        // Create assertEquals(x, y)
        EqualsAssertion assertion = new EqualsAssertion();
        assertion.setStatement(newStatement);
        assertion.setSource(x);
        assertion.setDest(y);
        assertion.setValue(true);
        newStatement.addAssertion(assertion);
        newStatement.addComment("Violates contract a.equals(b) <-> b.equals(a)");
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) TestCase(org.evosuite.testcase.TestCase) Statement(org.evosuite.testcase.statements.Statement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) GenericMethod(org.evosuite.utils.generic.GenericMethod) Method(java.lang.reflect.Method) GenericMethod(org.evosuite.utils.generic.GenericMethod) EqualsAssertion(org.evosuite.assertion.EqualsAssertion)

Example 3 with GenericMethod

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

the class TestCluster method sortCalls.

/**
 * Sort by remaining uncovered goals to bias search towards most rewarding methods
 *
 * @param testMethods
 * @return
 */
private List<GenericAccessibleObject<?>> sortCalls(List<GenericAccessibleObject<?>> testMethods) {
    // TODO: This can be done more efficiently, but we're just trying to see if this makes a difference at all
    Map<GenericAccessibleObject<?>, String> mapCallToName = new LinkedHashMap<>();
    for (GenericAccessibleObject<?> call : testMethods) {
        String name = call.getDeclaringClass().getCanonicalName();
        if (call.isMethod()) {
            GenericMethod method = (GenericMethod) call;
            name += method.getNameWithDescriptor();
        } else if (call.isConstructor()) {
            GenericConstructor constructor = (GenericConstructor) call;
            name += constructor.getNameWithDescriptor();
        } else {
            throw new RuntimeException("Coverage goals must be methods or constructors");
        }
        mapCallToName.put(call, name);
    }
    Map<String, Integer> mapMethodToGoals = new LinkedHashMap<>();
    for (String methodName : mapCallToName.values()) {
        // MethodKey is class+method+desc
        mapMethodToGoals.put(methodName, Archive.getArchiveInstance().getNumOfRemainingTargets(methodName));
    }
    return testMethods.stream().sorted(Comparator.comparingInt(item -> mapMethodToGoals.get(mapCallToName.get(item))).reversed()).collect(Collectors.toList());
}
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) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericMethod(org.evosuite.utils.generic.GenericMethod)

Example 4 with GenericMethod

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

the class EnvironmentTestClusterAugmenter method handleGUI.

private void handleGUI() {
    if (!hasAddedJOptionPaneInputsForStrings && JOptionPaneInputs.getInstance().hasDialog(GUIAction.STRING_INPUT)) {
        hasAddedJOptionPaneInputsForStrings = true;
        try {
            final Class<?> clazz = JOptionPaneInputs.class;
            final String ENQUEUE_INPUT_STRING = "enqueueInputString";
            final Method method_to_call = clazz.getMethod(ENQUEUE_INPUT_STRING, new Class<?>[] { String.class });
            final GenericClass genericClass = new GenericClass(clazz);
            final GenericMethod genericMethod = new GenericMethod(method_to_call, genericClass);
            // adds JOptionPaneInputs.enqueueString() to the palette of
            // methods that can be used
            TestCluster.getInstance().addEnvironmentTestCall(genericMethod);
        } catch (SecurityException e) {
            logger.error("Error while handling Random: " + e.getMessage(), e);
        } catch (NoSuchMethodException e) {
            logger.error("Error while handling Random: " + e.getMessage(), e);
        }
    }
    if (!hasAddedJOptionPaneYesNoCancelSelection && JOptionPaneInputs.getInstance().hasDialog(GUIAction.YES_NO_CANCEL_SELECTION)) {
        hasAddedJOptionPaneYesNoCancelSelection = true;
        try {
            final Class<?> clazz = JOptionPaneInputs.class;
            final String ENQUEUE_YES_NO_CANCEL_SELECTION = "enqueueYesNoCancelSelection";
            final Method method_to_call = clazz.getMethod(ENQUEUE_YES_NO_CANCEL_SELECTION, new Class<?>[] { int.class });
            final GenericClass genericClass = new GenericClass(clazz);
            final GenericMethod genericMethod = new GenericMethod(method_to_call, genericClass);
            // adds JOptionPaneInputs.enqueueString() to the palette of
            // methods that can be used
            TestCluster.getInstance().addEnvironmentTestCall(genericMethod);
        } catch (SecurityException e) {
            logger.error("Error while handling Random: " + e.getMessage(), e);
        } catch (NoSuchMethodException e) {
            logger.error("Error while handling Random: " + e.getMessage(), e);
        }
    }
    if (!hasAddedJOptionPaneYesNoSelection && JOptionPaneInputs.getInstance().hasDialog(GUIAction.YES_NO_SELECTION)) {
        hasAddedJOptionPaneYesNoSelection = true;
        try {
            final Class<?> clazz = JOptionPaneInputs.class;
            final String ENQUEUE_YES_NO_SELECTION = "enqueueYesNoSelection";
            final Method method_to_call = clazz.getMethod(ENQUEUE_YES_NO_SELECTION, new Class<?>[] { int.class });
            final GenericClass genericClass = new GenericClass(clazz);
            final GenericMethod genericMethod = new GenericMethod(method_to_call, genericClass);
            // adds JOptionPaneInputs.enqueueString() to the palette of
            // methods that can be used
            TestCluster.getInstance().addEnvironmentTestCall(genericMethod);
        } catch (SecurityException e) {
            logger.error("Error while handling Random: " + e.getMessage(), e);
        } catch (NoSuchMethodException e) {
            logger.error("Error while handling Random: " + e.getMessage(), e);
        }
    }
    if (!hasAddedJOptionPaneOkCancelSelection && JOptionPaneInputs.getInstance().hasDialog(GUIAction.OK_CANCEL_SELECTION)) {
        hasAddedJOptionPaneOkCancelSelection = true;
        try {
            final Class<?> clazz = JOptionPaneInputs.class;
            final String ENQUEUE_OK_CANCEL_SELECTION = "enqueueOkCancelSelection";
            final Method method_to_call = clazz.getMethod(ENQUEUE_OK_CANCEL_SELECTION, new Class<?>[] { int.class });
            final GenericClass genericClass = new GenericClass(clazz);
            final GenericMethod genericMethod = new GenericMethod(method_to_call, genericClass);
            // adds JOptionPaneInputs.enqueueString() to the palette of
            // methods that can be used
            TestCluster.getInstance().addEnvironmentTestCall(genericMethod);
        } catch (SecurityException e) {
            logger.error("Error while handling Random: " + e.getMessage(), e);
        } catch (NoSuchMethodException e) {
            logger.error("Error while handling Random: " + e.getMessage(), e);
        }
    }
    if (!hasAddedJOptionPaneOptionSelection && JOptionPaneInputs.getInstance().hasDialog(GUIAction.OPTION_SELECTION)) {
        hasAddedJOptionPaneOptionSelection = true;
        try {
            final Class<?> clazz = JOptionPaneInputs.class;
            final String ENQUEUE_OPTION_SELECTION = "enqueueOptionSelection";
            final Method method_to_call = clazz.getMethod(ENQUEUE_OPTION_SELECTION, new Class<?>[] { int.class });
            final GenericClass genericClass = new GenericClass(clazz);
            final GenericMethod genericMethod = new GenericMethod(method_to_call, genericClass);
            // adds JOptionPaneInputs.enqueueString() to the palette of
            // methods that can be used
            TestCluster.getInstance().addEnvironmentTestCall(genericMethod);
        } catch (SecurityException e) {
            logger.error("Error while handling Random: " + e.getMessage(), e);
        } catch (NoSuchMethodException e) {
            logger.error("Error while handling Random: " + e.getMessage(), e);
        }
    }
}
Also used : JOptionPaneInputs(org.evosuite.runtime.util.JOptionPaneInputs) GenericClass(org.evosuite.utils.generic.GenericClass) GenericMethod(org.evosuite.utils.generic.GenericMethod) Method(java.lang.reflect.Method) GenericMethod(org.evosuite.utils.generic.GenericMethod)

Example 5 with GenericMethod

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

the class EnvironmentTestClusterAugmenter method addEnvironmentClassToCluster.

/**
 * Add the given klass to the test cluster. Also recursively add (as
 * modifiers) all the other EvoSuite classes for which the given class is a
 * generator
 *
 * @param klass
 */
private boolean addEnvironmentClassToCluster(Class<?> klass) {
    if (handledClasses.contains(klass.getCanonicalName()) || !TestClusterUtils.isEvoSuiteClass(klass)) {
        // already handled, or not valid
        return false;
    }
    handledClasses.add(klass.getCanonicalName());
    boolean excludeClass = klass.getAnnotation(EvoSuiteClassExclude.class) != null;
    for (Constructor c : klass.getConstructors()) {
        // first check if it should be skipped
        if (shouldSkip(excludeClass, c)) {
            continue;
        }
        GenericAccessibleObject gc = new GenericConstructor(c, klass);
        TestCluster.getInstance().addEnvironmentTestCall(gc);
        GenericClass genclass = new GenericClass(klass);
        TestCluster.getInstance().invalidateGeneratorCache(genclass);
        TestCluster.getInstance().addGenerator(genclass, gc);
        testClusterGenerator.addNewDependencies(Arrays.asList(c.getParameterTypes()));
    }
    for (Method m : klass.getMethods()) {
        if (shouldSkip(excludeClass, m)) {
            continue;
        }
        GenericAccessibleObject gm = new GenericMethod(m, klass);
        TestCluster.getInstance().addEnvironmentTestCall(gm);
        testClusterGenerator.addNewDependencies(Arrays.asList(m.getParameterTypes()));
        Class<?> returnType = m.getReturnType();
        if (!returnType.equals(Void.TYPE)) {
            GenericClass genclass = new GenericClass(returnType);
            TestCluster.getInstance().invalidateGeneratorCache(genclass);
            TestCluster.getInstance().addGenerator(genclass, gm);
            addEnvironmentDependency(returnType);
        }
    }
    return true;
}
Also used : GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) GenericClass(org.evosuite.utils.generic.GenericClass) Constructor(java.lang.reflect.Constructor) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericMethod(org.evosuite.utils.generic.GenericMethod) Method(java.lang.reflect.Method) GenericMethod(org.evosuite.utils.generic.GenericMethod)

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