Search in sources :

Example 56 with GenericClass

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

the class DeleteMutationSystemTest method getTwoIntTest.

private TestCase getTwoIntTest(int x, int y, int x1, int y1) throws NoSuchMethodException, SecurityException, ConstructionFailedException, ClassNotFoundException {
    Class<?> sut = TestGenerationContext.getInstance().getClassLoaderForSUT().loadClass(Properties.TARGET_CLASS);
    GenericClass clazz = new GenericClass(sut);
    DefaultTestCase test = new DefaultTestCase();
    GenericConstructor gc = new GenericConstructor(clazz.getRawClass().getConstructors()[0], clazz);
    TestFactory testFactory = TestFactory.getInstance();
    VariableReference callee = testFactory.addConstructor(test, gc, 0, 0);
    test.addStatement(new IntPrimitiveStatement(test, x));
    test.addStatement(new IntPrimitiveStatement(test, y));
    VariableReference wrongIntVar1 = test.addStatement(new IntPrimitiveStatement(test, x1));
    VariableReference wrongIntVar2 = test.addStatement(new IntPrimitiveStatement(test, y1));
    Method m = clazz.getRawClass().getMethod("testMe", new Class<?>[] { int.class, int.class });
    GenericMethod method = new GenericMethod(m, sut);
    MethodStatement ms = new MethodStatement(test, method, callee, Arrays.asList(new VariableReference[] { wrongIntVar1, wrongIntVar2 }));
    test.addStatement(ms);
    return test;
}
Also used : MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) GenericClass(org.evosuite.utils.generic.GenericClass) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericMethod(org.evosuite.utils.generic.GenericMethod) Method(java.lang.reflect.Method) GenericMethod(org.evosuite.utils.generic.GenericMethod) IntPrimitiveStatement(org.evosuite.testcase.statements.numeric.IntPrimitiveStatement)

Example 57 with GenericClass

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

the class PoolSystemTest method testPoolWithException.

@Test
public void testPoolWithException() throws IOException, NoSuchMethodException, SecurityException {
    File f = File.createTempFile("EvoSuiteTestPool", null, FileUtils.getTempDirectory());
    String filename = f.getAbsolutePath();
    f.delete();
    System.out.println(filename);
    EvoSuite evosuite = new EvoSuite();
    String targetClass = DependencyClassWithException.class.getCanonicalName();
    Properties.TARGET_CLASS = targetClass;
    Properties.getTargetClassAndDontInitialise();
    TestCase test = new DefaultTestCase();
    VariableReference instance = test.addStatement(new ConstructorStatement(test, new GenericConstructor(DependencyClassWithException.class.getConstructors()[0], DependencyClassWithException.class), new ArrayList<VariableReference>()));
    VariableReference int42 = test.addStatement(new IntPrimitiveStatement(test, 42));
    GenericMethod foo = new GenericMethod(DependencyClassWithException.class.getMethod("foo", int.class), DependencyClassWithException.class);
    test.addStatement(new MethodStatement(test, foo, instance, Arrays.asList(new VariableReference[] { int42 })));
    test.addStatement(new MethodStatement(test, foo, instance, Arrays.asList(new VariableReference[] { int42 })));
    test.addStatement(new MethodStatement(test, foo, instance, Arrays.asList(new VariableReference[] { int42 })));
    test.addStatement(new MethodStatement(test, foo, instance, Arrays.asList(new VariableReference[] { int42 })));
    test.addStatement(new MethodStatement(test, foo, instance, Arrays.asList(new VariableReference[] { int42 })));
    String[] command = new String[] { "-generateSuite", "-class", targetClass };
    TestSuiteChromosome best = new TestSuiteChromosome();
    best.addTest(test);
    ObjectPool pool = new ObjectPool();
    pool.addSequence(new GenericClass(DependencyClassWithException.class), test);
    pool.writePool(filename);
    System.out.println("EvolvedTestSuite:\n" + best);
    resetStaticVariables();
    setDefaultPropertiesForTestCases();
    targetClass = ClassDependingOnExceptionClass.class.getCanonicalName();
    Properties.TARGET_CLASS = targetClass;
    Properties.P_OBJECT_POOL = 0.8;
    Properties.OBJECT_POOLS = filename;
    ObjectPoolManager.getInstance().initialisePool();
    // Properties.SEARCH_BUDGET = 50000;
    command = new String[] { "-generateSuite", "-class", targetClass };
    Object result = evosuite.parseCommandLine(command);
    GeneticAlgorithm<?> ga = getGAFromResult(result);
    best = (TestSuiteChromosome) ga.getBestIndividual();
    System.out.println("EvolvedTestSuite:\n" + best);
    Assert.assertEquals("Non-optimal coverage: ", 1d, best.getCoverage(), 0.001);
    f = new File(filename);
    f.delete();
}
Also used : ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) ArrayList(java.util.ArrayList) DependencyClassWithException(com.examples.with.different.packagename.pool.DependencyClassWithException) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericMethod(org.evosuite.utils.generic.GenericMethod) IntPrimitiveStatement(org.evosuite.testcase.statements.numeric.IntPrimitiveStatement) GenericClass(org.evosuite.utils.generic.GenericClass) EvoSuite(org.evosuite.EvoSuite) TestSuiteChromosome(org.evosuite.testsuite.TestSuiteChromosome) File(java.io.File) ObjectPool(org.evosuite.seeding.ObjectPool) ClassDependingOnExceptionClass(com.examples.with.different.packagename.pool.ClassDependingOnExceptionClass) Test(org.junit.Test)

Example 58 with GenericClass

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

the class Scaffolding method generateMockInitialization.

/**
 * This is needed  because the first time we do initialize a mock object, that can take
 * some seconds (successive calls would be based on cached data), and so tests might
 * timeout. So here we force the mock initialization in a @BeforeClass
 *
 * @param bd
 * @param results
 */
private void generateMockInitialization(String testClassName, StringBuilder bd, List<ExecutionResult> results) {
    if (!TestSuiteWriterUtils.doesUseMocks(results)) {
        return;
    }
    // In order to make sure this is called *after* initializeClasses this method is now called directly from initEvoSuiteFramework
    // bd.append(METHOD_SPACE);
    // bd.append("@BeforeClass \n");
    bd.append(METHOD_SPACE);
    bd.append("private static void initMocksToAvoidTimeoutsInTheTests() throws ClassNotFoundException { \n");
    Set<String> mockStatements = new LinkedHashSet<>();
    for (ExecutionResult er : results) {
        for (Statement st : er.test) {
            if (st instanceof FunctionalMockStatement) {
                FunctionalMockStatement fms = (FunctionalMockStatement) st;
                String name = new GenericClass(fms.getReturnType()).getRawClass().getTypeName();
                mockStatements.add("mock(Class.forName(\"" + name + "\", false, " + testClassName + ".class.getClassLoader()));");
            }
        }
    }
    mockStatements.stream().sorted().forEach(m -> {
        bd.append(BLOCK_SPACE);
        bd.append(m);
        bd.append("\n");
    });
    bd.append(METHOD_SPACE);
    bd.append("}\n");
}
Also used : GenericClass(org.evosuite.utils.generic.GenericClass) FunctionalMockStatement(org.evosuite.testcase.statements.FunctionalMockStatement) Statement(org.evosuite.testcase.statements.Statement) ExecutionResult(org.evosuite.testcase.execution.ExecutionResult) FunctionalMockStatement(org.evosuite.testcase.statements.FunctionalMockStatement)

Example 59 with GenericClass

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

the class ClassPrimitiveStatement method changeClassLoader.

@Override
public void changeClassLoader(ClassLoader loader) {
    super.changeClassLoader(loader);
    GenericClass genericClass = new GenericClass(value);
    genericClass.changeClassLoader(loader);
    value = genericClass.getRawClass();
}
Also used : GenericClass(org.evosuite.utils.generic.GenericClass)

Example 60 with GenericClass

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

the class FunctionalMockStatement method canBeFunctionalMockedIncludingSUT.

public static boolean canBeFunctionalMockedIncludingSUT(Type type) {
    Class<?> rawClass = new GenericClass(type).getRawClass();
    if (EvoSuiteMock.class.isAssignableFrom(rawClass) || MockList.isAMockClass(rawClass.getName()) || rawClass.equals(Class.class) || rawClass.isArray() || rawClass.isPrimitive() || rawClass.isAnonymousClass() || rawClass.isEnum() || // note: Mockito can handle package-level classes, but we get all kinds of weird exceptions with instrumentation :(
    !Modifier.isPublic(rawClass.getModifiers())) {
        return false;
    }
    if (!InstrumentedClass.class.isAssignableFrom(rawClass) && Modifier.isFinal(rawClass.getModifiers())) {
        /*
                if a class has not been instrumented (eg because belonging to javax.*),
                then if it is final we cannot mock it :(
                recall that instrumentation does remove the final modifiers
             */
        return false;
    }
    if (InetSocketAddress.class.equals(rawClass)) {
        /*
             InetSocketAddress declares hashCode as final and thus cannot be mocked:
             https://github.com/mockito/mockito/issues/310
             */
        return false;
    }
    try {
        // If dependencies are missing, this may throw a NoClassDefFoundException
        rawClass.getDeclaredMethods();
    } catch (NoClassDefFoundError e) {
        AtMostOnceLogger.warn(logger, "Problem with class " + rawClass.getName() + ": " + e.toString());
        return false;
    }
    // avoid cases of infinite recursions
    boolean onlySelfReturns = true;
    for (Method m : rawClass.getDeclaredMethods()) {
        if (!rawClass.equals(m.getReturnType())) {
            onlySelfReturns = false;
            break;
        }
    }
    if (onlySelfReturns && rawClass.getDeclaredMethods().length > 0) {
        // avoid weird cases like java.lang.Appendable
        return false;
    }
    // ad-hoc list of classes we should not really mock
    List<Class<?>> avoid = Arrays.asList();
    if (avoid.contains(rawClass)) {
        return false;
    }
    return true;
}
Also used : GenericClass(org.evosuite.utils.generic.GenericClass) EvoSuiteMock(org.evosuite.runtime.mock.EvoSuiteMock) GenericClass(org.evosuite.utils.generic.GenericClass) InstrumentedClass(org.evosuite.runtime.instrumentation.InstrumentedClass) Method(java.lang.reflect.Method)

Aggregations

GenericClass (org.evosuite.utils.generic.GenericClass)144 Test (org.junit.Test)64 GenericMethod (org.evosuite.utils.generic.GenericMethod)40 Method (java.lang.reflect.Method)36 VariableReference (org.evosuite.testcase.variable.VariableReference)25 GenericConstructor (org.evosuite.utils.generic.GenericConstructor)24 WildcardType (java.lang.reflect.WildcardType)22 TypeToken (com.googlecode.gentyref.TypeToken)20 ConstructionFailedException (org.evosuite.ga.ConstructionFailedException)17 Type (java.lang.reflect.Type)16 ArrayList (java.util.ArrayList)16 GenericAccessibleObject (org.evosuite.utils.generic.GenericAccessibleObject)16 MethodStatement (org.evosuite.testcase.statements.MethodStatement)15 IntPrimitiveStatement (org.evosuite.testcase.statements.numeric.IntPrimitiveStatement)15 ParameterizedType (java.lang.reflect.ParameterizedType)14 WildcardTypeImpl (org.evosuite.utils.generic.WildcardTypeImpl)10 ConstructorStatement (org.evosuite.testcase.statements.ConstructorStatement)9 AnnotatedType (java.lang.reflect.AnnotatedType)8 LinkedList (java.util.LinkedList)8 List (java.util.List)7