Search in sources :

Example 96 with GenericClass

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

the class CastClassManager method addAssignableClass.

private boolean addAssignableClass(WildcardType wildcardType, Map<TypeVariable<?>, Type> typeMap) {
    Set<Class<?>> classes = TestCluster.getInstance().getAnalyzedClasses();
    Set<Class<?>> assignableClasses = new LinkedHashSet<Class<?>>();
    for (Class<?> clazz : classes) {
        if (!TestUsageChecker.canUse(clazz))
            continue;
        GenericClass genericClass = new GenericClass(clazz).getWithWildcardTypes();
        if (!genericClass.satisfiesBoundaries(wildcardType, typeMap)) {
            logger.debug("Not assignable: " + clazz);
        } else {
            logger.debug("Assignable");
            assignableClasses.add(clazz);
        }
    }
    for (Type t : typeMap.values()) {
        if (t instanceof WildcardType)
            // TODO: For now.
            continue;
        Class<?> clazz = GenericTypeReflector.erase(t);
        if (!TestUsageChecker.canUse(GenericTypeReflector.erase(clazz)))
            continue;
        GenericClass genericClass = new GenericClass(clazz).getWithWildcardTypes();
        if (!genericClass.satisfiesBoundaries(wildcardType, typeMap)) {
            logger.debug("Not assignable: " + clazz);
        } else {
            logger.debug("Assignable");
            assignableClasses.add(clazz);
        }
    }
    for (Type t : wildcardType.getUpperBounds()) {
        if (typeMap.containsKey(t))
            t = typeMap.get(t);
        Class<?> clazz = GenericTypeReflector.erase(t);
        logger.debug("Checking bound: " + t);
        if (!TestUsageChecker.canUse(clazz))
            continue;
        GenericClass genericClass = new GenericClass(t);
        if (genericClass.hasTypeVariables()) {
            logger.debug("Has type variables: " + genericClass);
            GenericClass wildcardClass = genericClass.getWithWildcardTypes();
            if (!wildcardClass.satisfiesBoundaries(wildcardType, typeMap)) {
                logger.debug("Not assignable: " + clazz);
            } else {
                logger.debug("Assignable");
                assignableClasses.add(clazz);
            }
        } else {
            logger.debug("Adding directly: " + genericClass);
            assignableClasses.add(genericClass.getRawClass());
            classMap.put(genericClass, 10);
        }
    }
    logger.debug("Found assignable classes for wildcardtype " + wildcardType + ": " + assignableClasses.size());
    if (!assignableClasses.isEmpty()) {
        Class<?> clazz = Randomness.choice(assignableClasses);
        GenericClass castClass = new GenericClass(clazz);
        logger.debug("Adding cast class " + castClass);
        classMap.put(castClass, 10);
        return true;
    }
    return false;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) WildcardType(java.lang.reflect.WildcardType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) WildcardType(java.lang.reflect.WildcardType) GenericClass(org.evosuite.utils.generic.GenericClass) GenericClass(org.evosuite.utils.generic.GenericClass)

Example 97 with GenericClass

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

the class ObjectFields method getAllVars.

private static Map<String, Object> getAllVars(Object p, int counter, String prefix) {
    // TODO Auto-generated method stub
    // logger.warn("getting: " + ((p instanceof Field)?((Field)
    // p).getType():p.getClass()) + ", count:" + counter);
    Map<String, Object> values = new HashMap<String, Object>();
    if (p == null)
        return values;
    Collection<Field> fields = getAllFields(p.getClass());
    for (Field field : fields) {
        // String what_happened = "";
        GenericClass gc = new GenericClass(field.getType());
        if (ClassUtils.isPrimitiveOrWrapper(field.getType()) || gc.isString()) {
            // what_happened += ", " + field.getType() + " is primitive,";
            if (field.getName().equals("serialVersionUID"))
                continue;
            values.put(prefix + field.getName(), getObjectValue(getFieldValue(field, p)));
        } else if (field.getType().equals(Object.class) || counter >= MAX_RECURSION) {
            values.put(prefix + field.getName(), (getObjectValue(getFieldValue(field, p)) != null));
        // what_happened += ", " + field.getType() + ",reached end,";
        } else if (field.getType().isArray()) {
            /*
				 * values.put(prefix + field.getName(), Array
				 * .getLength(getObjectValue(getFieldValue(field, p))));
				 */
            // Object[] arr = (Object[]) getFieldValue(field, p);
            /*
				 * for(Object o: arr){ values.putAll(getAllVars(o, counter +
				 * 1,prefix + ((prefix.equals(""))?"":".")+field.getName())); }
				 */
            Object arr = getFieldValue(field, p);
            if (arr == null)
                return values;
            for (int n = 0; n < Array.getLength(arr); n++) {
                // values.putAll(getAllVars(Array.get(arr,n), counter +
                // 1,prefix + ((prefix.isEmpty())?"":".")+field.getName()));
                values.put(prefix + field.getName(), getAllVars(Array.get(arr, n), counter + 1, prefix + ((prefix.isEmpty()) ? "" : ".") + field.getName()));
            }
        } else {
            try {
                field.setAccessible(true);
                // values.putAll(getAllVars(field.get(p), counter + 1,prefix
                // + ((prefix.isEmpty())?"":".")+field.getName()));
                values.put(prefix + field.getName(), getAllVars(field.get(p), counter + 1, prefix + ((prefix.isEmpty()) ? "" : ".") + field.getName()));
            } catch (IllegalArgumentException e) {
                return values;
            } catch (IllegalAccessException e) {
                return values;
            }
        // what_happened += ", " + field.getType() + ",recursed,";
        }
    // logger.warn(prefix + field.getName() + what_happened);
    }
    return values;
}
Also used : Field(java.lang.reflect.Field) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) GenericClass(org.evosuite.utils.generic.GenericClass)

Example 98 with GenericClass

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

the class ObjectPool method getPoolFromTestSuite.

/**
 * Convert a test suite to a pool
 *
 * @param testSuite
 */
public static ObjectPool getPoolFromTestSuite(TestSuiteChromosome testSuite) {
    ObjectPool pool = new ObjectPool();
    for (TestChromosome testChromosome : testSuite.getTestChromosomes()) {
        TestCase test = testChromosome.getTestCase().clone();
        test.removeAssertions();
        /*
			if (testChromosome.hasException()) {
				// No code including or after an exception should be in the pool
				Integer pos = testChromosome.getLastExecutionResult().getFirstPositionOfThrownException();
				if (pos != null) {
					test.chop(pos);
				} else {
					test.chop(test.size() - 1);
				}
			}
			*/
        Class<?> targetClass = Properties.getTargetClassAndDontInitialise();
        if (!testChromosome.hasException() && test.hasObject(targetClass, test.size())) {
            pool.addSequence(new GenericClass(targetClass), test);
        }
    }
    return pool;
}
Also used : TestCase(org.evosuite.testcase.TestCase) GenericClass(org.evosuite.utils.generic.GenericClass) TestChromosome(org.evosuite.testcase.TestChromosome)

Example 99 with GenericClass

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

the class EnvironmentDataSystemTest method testOnSpecificTest.

@Test
public void testOnSpecificTest() throws ClassNotFoundException, ConstructionFailedException, NoSuchMethodException, SecurityException {
    Properties.TARGET_CLASS = DseBar.class.getCanonicalName();
    Class<?> sut = TestGenerationContext.getInstance().getClassLoaderForSUT().loadClass(Properties.TARGET_CLASS);
    Class<?> fooClass = TestGenerationContext.getInstance().getClassLoaderForSUT().loadClass(DseFoo.class.getCanonicalName());
    GenericClass clazz = new GenericClass(sut);
    DefaultTestCase test = new DefaultTestCase();
    // String string0 = "baz5";
    VariableReference stringVar = test.addStatement(new StringPrimitiveStatement(test, "baz5"));
    // DseFoo dseFoo0 = new DseFoo();
    GenericConstructor fooConstructor = new GenericConstructor(fooClass.getConstructors()[0], fooClass);
    ConstructorStatement fooConstructorStatement = new ConstructorStatement(test, fooConstructor, Arrays.asList(new VariableReference[] {}));
    VariableReference fooVar = test.addStatement(fooConstructorStatement);
    // String fileName = new String("/home/galeotti/README.txt")
    String path = "/home/galeotti/README.txt";
    EvoSuiteFile evosuiteFile = new EvoSuiteFile(path);
    FileNamePrimitiveStatement fileNameStmt = new FileNamePrimitiveStatement(test, evosuiteFile);
    test.addStatement(fileNameStmt);
    Method fooIncMethod = fooClass.getMethod("inc", new Class<?>[] {});
    GenericMethod incMethod = new GenericMethod(fooIncMethod, fooClass);
    test.addStatement(new MethodStatement(test, incMethod, fooVar, Arrays.asList(new VariableReference[] {})));
    test.addStatement(new MethodStatement(test, incMethod, fooVar, Arrays.asList(new VariableReference[] {})));
    test.addStatement(new MethodStatement(test, incMethod, fooVar, Arrays.asList(new VariableReference[] {})));
    test.addStatement(new MethodStatement(test, incMethod, fooVar, Arrays.asList(new VariableReference[] {})));
    test.addStatement(new MethodStatement(test, incMethod, fooVar, Arrays.asList(new VariableReference[] {})));
    // DseBar dseBar0 = new DseBar(string0);
    GenericConstructor gc = new GenericConstructor(clazz.getRawClass().getConstructors()[0], clazz);
    ConstructorStatement constructorStatement = new ConstructorStatement(test, gc, Arrays.asList(new VariableReference[] { stringVar }));
    VariableReference callee = test.addStatement(constructorStatement);
    // dseBar0.coverMe(dseFoo0);
    Method m = clazz.getRawClass().getMethod("coverMe", new Class<?>[] { fooClass });
    GenericMethod method = new GenericMethod(m, sut);
    MethodStatement ms = new MethodStatement(test, method, callee, Arrays.asList(new VariableReference[] { fooVar }));
    test.addStatement(ms);
    System.out.println(test);
    TestSuiteChromosome suite = new TestSuiteChromosome();
    BranchCoverageSuiteFitness fitness = new BranchCoverageSuiteFitness();
    BranchCoverageMap.getInstance().searchStarted(null);
    assertEquals(4.0, fitness.getFitness(suite), 0.1F);
    suite.addTest(test);
    assertEquals(1.0, fitness.getFitness(suite), 0.1F);
    System.out.println("Test suite: " + suite);
    Properties.CONCOLIC_TIMEOUT = Integer.MAX_VALUE;
    TestSuiteLocalSearch localSearch = TestSuiteLocalSearch.selectTestSuiteLocalSearch();
    LocalSearchObjective<TestSuiteChromosome> localObjective = new DefaultLocalSearchObjective<TestSuiteChromosome>();
    localObjective.addFitnessFunction(fitness);
    localSearch.doSearch(suite, localObjective);
    System.out.println("Fitness: " + fitness.getFitness(suite));
    System.out.println("Test suite: " + suite);
    assertEquals("Local search failed to cover class", 0.0, fitness.getFitness(suite), 0.1F);
    BranchCoverageMap.getInstance().searchFinished(null);
}
Also used : ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) StringPrimitiveStatement(org.evosuite.testcase.statements.StringPrimitiveStatement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) BranchCoverageSuiteFitness(org.evosuite.coverage.branch.BranchCoverageSuiteFitness) FileNamePrimitiveStatement(org.evosuite.testcase.statements.environment.FileNamePrimitiveStatement) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) DefaultTestCase(org.evosuite.testcase.DefaultTestCase) GenericMethod(org.evosuite.utils.generic.GenericMethod) Method(java.lang.reflect.Method) GenericMethod(org.evosuite.utils.generic.GenericMethod) DseBar(com.examples.with.different.packagename.localsearch.DseBar) TestSuiteLocalSearch(org.evosuite.testsuite.localsearch.TestSuiteLocalSearch) DefaultLocalSearchObjective(org.evosuite.ga.localsearch.DefaultLocalSearchObjective) GenericClass(org.evosuite.utils.generic.GenericClass) EvoSuiteFile(org.evosuite.runtime.testdata.EvoSuiteFile) TestSuiteChromosome(org.evosuite.testsuite.TestSuiteChromosome) DseFoo(com.examples.with.different.packagename.localsearch.DseFoo) Test(org.junit.Test)

Example 100 with GenericClass

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

the class TestTestSuiteMinimizer method minimizeSuiteFullCoverageWithTwoFitnessFunctionsMinimizeTestsEnabled.

@Test
public void minimizeSuiteFullCoverageWithTwoFitnessFunctionsMinimizeTestsEnabled() throws ClassNotFoundException, NoSuchFieldException, SecurityException, ConstructionFailedException, NoSuchMethodException {
    Properties.TARGET_CLASS = FlagExample1.class.getCanonicalName();
    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();
    testFactory.addConstructor(test, gc, 0, 0);
    List<VariableReference> parameters = new ArrayList<VariableReference>();
    for (int i = 0; i < 10; i++) {
        IntPrimitiveStatement ips = new IntPrimitiveStatement(test, 28234 + i);
        VariableReference vr = test.addStatement(ips, i + 1);
    }
    ConstructorStatement ct = new ConstructorStatement(test, gc, parameters);
    Method m = clazz.getRawClass().getMethod("testMe", new Class<?>[] { int.class });
    GenericMethod method = new GenericMethod(m, sut);
    testFactory.addMethod(test, method, 11, 0);
    parameters = new ArrayList<VariableReference>();
    for (int i = 12; i < 15; i++) {
        IntPrimitiveStatement ips = new IntPrimitiveStatement(test, i);
        VariableReference vr = test.addStatement(ips, i);
    }
    ct = new ConstructorStatement(test, gc, parameters);
    testFactory.addMethod(test, method, 15, 0);
    assertEquals(16, test.size());
    TestSuiteChromosome tsc = new TestSuiteChromosome();
    tsc.addTest(test);
    TestSuiteFitnessFunction branch = new BranchCoverageSuiteFitness();
    double previous_branch_fitness = branch.getFitness(tsc);
    tsc.setFitness(branch, previous_branch_fitness);
    assertEquals(previous_branch_fitness, 0.0, 0.0);
    TestSuiteFitnessFunction defuse = new DefUseCoverageSuiteFitness();
    double previous_defuse_fitness = defuse.getFitness(tsc);
    tsc.setFitness(defuse, previous_defuse_fitness);
    assertEquals(previous_defuse_fitness, 0.0, 0.0);
    List<TestFitnessFactory<? extends TestFitnessFunction>> factories = new ArrayList<TestFitnessFactory<? extends TestFitnessFunction>>();
    factories.add(new BranchCoverageFactory());
    factories.add(new DefUseCoverageFactory());
    TestSuiteMinimizer minimizer = new TestSuiteMinimizer(factories);
    minimizer.minimize(tsc, true);
    assertEquals(2, tsc.getTests().size());
    assertEquals(3, tsc.getTests().get(0).size());
    assertEquals(3, tsc.getTests().get(1).size());
    // assertTrue(tsc.getTests().get(0).toCode().equals("FlagExample1 flagExample1_0 = new FlagExample1();\nint int0 = 28234;\nflagExample1_0.testMe(int0);\n"));
    // assertTrue(tsc.getTests().get(1).toCode().equals("FlagExample1 flagExample1_0 = new FlagExample1();\nint int0 = 28241;\nflagExample1_0.testMe(int0);\n"));
    double branch_fitness = branch.getFitness(tsc);
    assertEquals(previous_branch_fitness, branch_fitness, 0.0);
    double defuse_fitness = defuse.getFitness(tsc);
    assertEquals(previous_defuse_fitness, defuse_fitness, 0.0);
}
Also used : DefUseCoverageSuiteFitness(org.evosuite.coverage.dataflow.DefUseCoverageSuiteFitness) ArrayList(java.util.ArrayList) GenericMethod(org.evosuite.utils.generic.GenericMethod) BranchCoverageFactory(org.evosuite.coverage.branch.BranchCoverageFactory) GenericClass(org.evosuite.utils.generic.GenericClass) ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) BranchCoverageSuiteFitness(org.evosuite.coverage.branch.BranchCoverageSuiteFitness) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) TestFitnessFactory(org.evosuite.coverage.TestFitnessFactory) DefUseCoverageFactory(org.evosuite.coverage.dataflow.DefUseCoverageFactory) GenericMethod(org.evosuite.utils.generic.GenericMethod) Method(java.lang.reflect.Method) IntPrimitiveStatement(org.evosuite.testcase.statements.numeric.IntPrimitiveStatement) FlagExample1(com.examples.with.different.packagename.FlagExample1) Test(org.junit.Test)

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