Search in sources :

Example 6 with GenericMethod

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

the class EnvironmentTestClusterAugmenter method handleNetwork.

private void handleNetwork(TestCase test) {
    /*
		 * there are several things that are mocked in the network. based on
		 * what the SUT used, we might only need a subset of methods used to
		 * manipulate the mocked network
		 */
    // TODO might need more stuff once we handle assertion generation
    test.getAccessedEnvironment().addLocalListeningPorts(VirtualNetwork.getInstance().getViewOfLocalListeningPorts());
    test.getAccessedEnvironment().addRemoteURLs(VirtualNetwork.getInstance().getViewOfRemoteAccessedFiles());
    test.getAccessedEnvironment().addRemoteContactedPorts(VirtualNetwork.getInstance().getViewOfRemoteContactedPorts());
    if (!hasAddedRemoteURLs && test.getAccessedEnvironment().getViewOfRemoteURLs().size() > 0) {
        hasAddedRemoteURLs = true;
        try {
            TestCluster.getInstance().addEnvironmentTestCall(new GenericMethod(NetworkHandling.class.getMethod("createRemoteTextFile", new Class<?>[] { EvoSuiteURL.class, String.class }), new GenericClass(NetworkHandling.class)));
        } catch (Exception e) {
            logger.error("Error while handling hasAddedRemoteURLs: " + e.getMessage(), e);
        }
    }
    boolean openedTCP = false;
    boolean openedUDP = false;
    for (EndPointInfo info : test.getAccessedEnvironment().getViewOfLocalListeningPorts()) {
        if (info.getType().equals(VirtualNetwork.ConnectionType.TCP)) {
            openedTCP = true;
        } else if (info.getType().equals(VirtualNetwork.ConnectionType.UDP)) {
            openedUDP = true;
        }
        if (openedTCP && openedUDP) {
            break;
        }
    }
    if (!hasAddedUdpSupport && openedUDP) {
        hasAddedUdpSupport = true;
        try {
            TestCluster.getInstance().addEnvironmentTestCall(new GenericMethod(NetworkHandling.class.getMethod("sendUdpPacket", new Class<?>[] { EvoSuiteLocalAddress.class, EvoSuiteRemoteAddress.class, byte[].class }), new GenericClass(NetworkHandling.class)));
            TestCluster.getInstance().addEnvironmentTestCall(new GenericMethod(NetworkHandling.class.getMethod("sendUdpPacket", new Class<?>[] { EvoSuiteLocalAddress.class, byte[].class }), new GenericClass(NetworkHandling.class)));
        } catch (Exception e) {
            logger.error("Error while handling hasAddedUdpSupport: " + e.getMessage(), e);
        }
    }
    if (!hasAddedTcpListeningSupport && openedTCP) {
        hasAddedTcpListeningSupport = true;
        try {
            TestCluster.getInstance().addEnvironmentTestCall(new GenericMethod(NetworkHandling.class.getMethod("sendDataOnTcp", new Class<?>[] { EvoSuiteLocalAddress.class, byte[].class }), new GenericClass(NetworkHandling.class)));
            TestCluster.getInstance().addEnvironmentTestCall(new GenericMethod(NetworkHandling.class.getMethod("sendMessageOnTcp", new Class<?>[] { EvoSuiteLocalAddress.class, String.class }), new GenericClass(NetworkHandling.class)));
        } catch (Exception e) {
            logger.error("Error while handling hasAddedTcpListeningSupport: " + e.getMessage(), e);
        }
    }
    if (!hasAddedTcpRemoteSupport && test.getAccessedEnvironment().getViewOfRemoteContactedPorts().size() > 0) {
        hasAddedTcpRemoteSupport = true;
        try {
            TestCluster.getInstance().addEnvironmentTestCall(new GenericMethod(NetworkHandling.class.getMethod("openRemoteTcpServer", new Class<?>[] { EvoSuiteRemoteAddress.class }), new GenericClass(NetworkHandling.class)));
        } catch (Exception e) {
            logger.error("Error while handling hasAddedTcpRemoteSupport: " + e.getMessage(), e);
        }
    }
}
Also used : GenericClass(org.evosuite.utils.generic.GenericClass) EndPointInfo(org.evosuite.runtime.vnet.EndPointInfo) GenericMethod(org.evosuite.utils.generic.GenericMethod)

Example 7 with GenericMethod

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

the class TestClusterGenerator method handleSpecialCases.

private void handleSpecialCases() {
    if (Properties.P_REFLECTION_ON_PRIVATE > 0 && Properties.REFLECTION_START_PERCENT < 1) {
        // Check if we should add
        // PrivateAccess.callDefaultConstructorOfTheClassUnderTest()
        Class<?> target = Properties.getTargetClassAndDontInitialise();
        Constructor<?> constructor = null;
        try {
            constructor = target.getDeclaredConstructor();
        } catch (NoSuchMethodException e) {
        }
        if (constructor != null && Modifier.isPrivate(constructor.getModifiers()) && target.getDeclaredConstructors().length == 1 && // Not enums
        !target.isEnum()) {
            Method m = null;
            try {
                m = PrivateAccess.class.getDeclaredMethod("callDefaultConstructorOfTheClassUnderTest");
            } catch (NoSuchMethodException e) {
                logger.error("Missing method: " + e.toString());
                return;
            }
            GenericMethod gm = new GenericMethod(m, PrivateAccess.class);
            // It is not really an environment method, but not sure how else
            // to handle it...
            TestCluster.getInstance().addEnvironmentTestCall(gm);
        }
    }
}
Also used : PrivateAccess(org.evosuite.runtime.PrivateAccess) GenericMethod(org.evosuite.utils.generic.GenericMethod) Method(java.lang.reflect.Method) GenericMethod(org.evosuite.utils.generic.GenericMethod)

Example 8 with GenericMethod

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

the class TestFactory method insertRandomCallOnEnvironment.

/**
 * @param test
 * @param lastValidPosition
 * @return the position where the insertion happened, or a negative value otherwise
 */
public int insertRandomCallOnEnvironment(TestCase test, int lastValidPosition) {
    int previousLength = test.size();
    currentRecursion.clear();
    List<GenericAccessibleObject<?>> shuffledOptions = TestCluster.getInstance().getRandomizedCallsToEnvironment();
    if (shuffledOptions == null || shuffledOptions.isEmpty()) {
        return -1;
    }
    // iterate (in random order) over all possible environment methods till we find one that can be inserted
    for (GenericAccessibleObject<?> o : shuffledOptions) {
        try {
            int position = ConstraintVerifier.getAValidPositionForInsertion(o, test, lastValidPosition);
            if (position < 0) {
                // the given method/constructor cannot be added
                continue;
            }
            if (o.isConstructor()) {
                GenericConstructor c = (GenericConstructor) o;
                addConstructor(test, c, position, 0);
                return position;
            } else if (o.isMethod()) {
                GenericMethod m = (GenericMethod) o;
                if (!m.isStatic()) {
                    VariableReference callee = null;
                    Type target = m.getOwnerType();
                    if (!test.hasObject(target, position)) {
                        callee = createObject(test, target, position, 0, null);
                        position += test.size() - previousLength;
                        previousLength = test.size();
                    } else {
                        callee = test.getRandomNonNullObject(target, position);
                    }
                    if (!TestUsageChecker.canUse(m.getMethod(), callee.getVariableClass())) {
                        logger.error("Cannot call method " + m + " with callee of type " + callee.getClassName());
                    }
                    addMethodFor(test, callee, m.copyWithNewOwner(callee.getGenericClass()), position);
                    return position;
                } else {
                    addMethod(test, m, position, 0);
                    return position;
                }
            } else {
                throw new RuntimeException("Unrecognized type for environment: " + o);
            }
        } catch (ConstructionFailedException e) {
            // TODO what to do here?
            AtMostOnceLogger.warn(logger, "Failed environment insertion: " + e);
        }
    }
    return -1;
}
Also used : GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) CaptureType(com.googlecode.gentyref.CaptureType) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericMethod(org.evosuite.utils.generic.GenericMethod) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 9 with GenericMethod

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

the class TestFactory method insertRandomCall.

/**
 * Insert a random call for the UUT at the given position
 *
 * @param test
 * @param position
 */
public boolean insertRandomCall(TestCase test, int position) {
    int previousLength = test.size();
    String name = "";
    currentRecursion.clear();
    logger.debug("Inserting random call at position {}", position);
    try {
        if (reflectionFactory == null) {
            final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();
            reflectionFactory = new ReflectionFactory(targetClass);
        }
        if (reflectionFactory.hasPrivateFieldsOrMethods() && TimeController.getInstance().getPhasePercentage() >= Properties.REFLECTION_START_PERCENT && (Randomness.nextDouble() < Properties.P_REFLECTION_ON_PRIVATE || TestCluster.getInstance().getNumTestCalls() == 0)) {
            logger.debug("Going to insert random reflection call");
            return insertRandomReflectionCall(test, position, 0);
        }
        GenericAccessibleObject<?> o = TestCluster.getInstance().getRandomTestCall(test);
        if (o == null) {
            logger.warn("Have no target methods to test");
            return false;
        } else if (o.isConstructor()) {
            if (InstanceOnlyOnce.canInstantiateOnlyOnce(o.getDeclaringClass()) && ConstraintHelper.countNumberOfNewInstances(test, o.getDeclaringClass()) != 0) {
                return false;
            }
            GenericConstructor c = (GenericConstructor) o;
            logger.debug("Adding constructor call {}", c.getName());
            name = c.getName();
            addConstructor(test, c, position, 0);
        } else if (o.isMethod()) {
            GenericMethod m = (GenericMethod) o;
            logger.debug("Adding method call {}", m.getName());
            name = m.getName();
            if (!m.isStatic()) {
                logger.debug("Getting callee of type {}", m.getOwnerClass().getTypeName());
                VariableReference callee = null;
                Type target = m.getOwnerType();
                if (!test.hasObject(target, position)) {
                    // no FM for SUT
                    callee = createObject(test, target, position, 0, null, false, false, true);
                    position += test.size() - previousLength;
                    previousLength = test.size();
                } else {
                    callee = test.getRandomNonNullObject(target, position);
                // This may also be an inner class, in this case we can't use a SUT instance
                // if (!callee.isAssignableTo(m.getDeclaringClass())) {
                // callee = test.getRandomNonNullObject(m.getDeclaringClass(), position);
                // }
                }
                logger.debug("Got callee of type {}", callee.getGenericClass().getTypeName());
                if (!TestUsageChecker.canUse(m.getMethod(), callee.getVariableClass())) {
                    logger.debug("Cannot call method {} with callee of type {}", m, callee.getClassName());
                    throw new ConstructionFailedException("Cannot apply method to this callee");
                }
                addMethodFor(test, callee, m.copyWithNewOwner(callee.getGenericClass()), position);
            } else {
                // We only use this for static methods to avoid using wrong constructors (?)
                addMethod(test, m, position, 0);
            }
        } else if (o.isField()) {
            GenericField f = (GenericField) o;
            name = f.getName();
            logger.debug("Adding field {}", f.getName());
            if (Randomness.nextBoolean()) {
                addFieldAssignment(test, f, position, 0);
            } else {
                addField(test, f, position, 0);
            }
        } else {
            logger.error("Got type other than method or constructor!");
            return false;
        }
        return true;
    } catch (ConstructionFailedException e) {
        // TODO: Check this! - TestCluster replaced
        // TestCluster.getInstance().checkDependencies(o);
        logger.debug("Inserting statement {} has failed. Removing statements: {}", name, e);
        // TODO: Doesn't work if position != test.size()
        int lengthDifference = test.size() - previousLength;
        for (int i = lengthDifference - 1; i >= 0; i--) {
            // we need to remove them in order, so that the testcase is at all time consistent
            if (logger.isDebugEnabled()) {
                logger.debug("  Removing statement: " + test.getStatement(position + i).getCode());
            }
            test.remove(position + i);
        }
        return false;
    }
}
Also used : CaptureType(com.googlecode.gentyref.CaptureType) ReflectionFactory(org.evosuite.testcase.statements.reflection.ReflectionFactory) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericMethod(org.evosuite.utils.generic.GenericMethod) GenericField(org.evosuite.utils.generic.GenericField) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 10 with GenericMethod

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

the class TestFactory method changeCall.

/**
 * Replace the statement with a new statement using given call
 *
 * @param test
 * @param statement
 * @param call
 * @throws ConstructionFailedException
 */
public void changeCall(TestCase test, Statement statement, GenericAccessibleObject<?> call) throws ConstructionFailedException {
    int position = statement.getReturnValue().getStPosition();
    logger.debug("Changing call {} with {}", test.getStatement(position), call);
    if (call.isMethod()) {
        GenericMethod method = (GenericMethod) call;
        if (method.hasTypeParameters())
            throw new ConstructionFailedException("Cannot handle generic methods properly");
        VariableReference retval = statement.getReturnValue();
        VariableReference callee = null;
        if (!method.isStatic()) {
            callee = getRandomNonNullNonPrimitiveObject(test, method.getOwnerType(), position);
        }
        List<VariableReference> parameters = new ArrayList<>();
        for (Type type : method.getParameterTypes()) {
            parameters.add(test.getRandomObject(type, position));
        }
        MethodStatement m = new MethodStatement(test, method, callee, parameters, retval);
        test.setStatement(m, position);
        logger.debug("Using method {}", m.getCode());
    } else if (call.isConstructor()) {
        GenericConstructor constructor = (GenericConstructor) call;
        VariableReference retval = statement.getReturnValue();
        List<VariableReference> parameters = new ArrayList<>();
        for (Type type : constructor.getParameterTypes()) {
            parameters.add(test.getRandomObject(type, position));
        }
        ConstructorStatement c = new ConstructorStatement(test, constructor, retval, parameters);
        test.setStatement(c, position);
        logger.debug("Using constructor {}", c.getCode());
    } else if (call.isField()) {
        GenericField field = (GenericField) call;
        VariableReference retval = statement.getReturnValue();
        VariableReference source = null;
        if (!field.isStatic())
            source = getRandomNonNullNonPrimitiveObject(test, field.getOwnerType(), position);
        try {
            FieldStatement f = new FieldStatement(test, field, source, retval);
            test.setStatement(f, position);
            logger.debug("Using field {}", f.getCode());
        } catch (Throwable e) {
            logger.error("Error: " + e + " , Field: " + field + " , Test: " + test);
            throw new Error(e);
        }
    }
}
Also used : PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) ArrayList(java.util.ArrayList) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericMethod(org.evosuite.utils.generic.GenericMethod) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException) CaptureType(com.googlecode.gentyref.CaptureType) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) MockList(org.evosuite.runtime.mock.MockList) ArrayList(java.util.ArrayList) List(java.util.List) GenericField(org.evosuite.utils.generic.GenericField)

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