use of org.evosuite.testcase.execution.EvosuiteError in project evosuite by EvoSuite.
the class TestClassInitialization method buildLoadTargetClassTestCase.
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);
return test;
} catch (NoSuchMethodException | SecurityException e) {
throw new EvosuiteError("Unexpected exception while creating Class Initializer Test Case");
}
}
use of org.evosuite.testcase.execution.EvosuiteError in project evosuite by EvoSuite.
the class Z3Str2Solver method solve.
@Override
public SolverResult solve(Collection<Constraint<?>> constraints) throws SolverTimeoutException, IOException, SolverParseException, SolverEmptyQueryException, SolverErrorException {
SmtCheckSatQuery smtCheckSatQuery = buildSmtQuerty(constraints);
if (smtCheckSatQuery.getConstantDeclarations().isEmpty()) {
logger.debug("Z3-str2 input has no variables");
throw new SolverEmptyQueryException("Z3-str2 input has no variables");
}
if (smtCheckSatQuery.getAssertions().isEmpty()) {
Map<String, Object> emptySolution = new HashMap<String, Object>();
SolverResult emptySAT = SolverResult.newSAT(emptySolution);
return emptySAT;
}
Z3Str2QueryPrinter printer = new Z3Str2QueryPrinter();
String smtQueryStr = printer.print(smtCheckSatQuery);
logger.debug("Z3-str2 input:");
logger.debug(smtQueryStr);
int timeout = (int) Properties.DSE_CONSTRAINT_SOLVER_TIMEOUT_MILLIS;
File tempDir = createNewTmpDir();
String z3TempFileName = tempDir.getAbsolutePath() + File.separatorChar + EVOSUITE_Z3_STR_FILENAME;
if (Properties.Z3_STR2_PATH == null) {
String errMsg = "Property Z3_STR_PATH should be setted in order to use the Z3StrSolver!";
logger.error(errMsg);
throw new IllegalStateException(errMsg);
}
try {
FileIOUtils.writeFile(smtQueryStr, z3TempFileName);
String z3Cmd = Properties.Z3_STR2_PATH + " -f " + z3TempFileName;
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
launchNewProcess(z3Cmd, smtQueryStr, timeout, stdout);
String z3str2ResultStr = stdout.toString("UTF-8");
Z3Str2ResultParser parser = new Z3Str2ResultParser();
Set<Variable<?>> variables = getVariables(constraints);
Map<String, Object> initialValues = getConcreteValues(variables);
SolverResult solverResult;
if (addMissingVariables()) {
solverResult = parser.parse(z3str2ResultStr, initialValues);
} else {
solverResult = parser.parse(z3str2ResultStr);
}
if (solverResult.isSAT()) {
// check if solution is correct, otherwise return UNSAT
boolean check = checkSAT(constraints, solverResult);
if (!check) {
logger.debug("Z3-str2 solution does not solve the constraint system!");
SolverResult unsatResult = SolverResult.newUNSAT();
return unsatResult;
}
}
return solverResult;
} catch (UnsupportedEncodingException e) {
throw new EvosuiteError("UTF-8 should not cause this exception!");
} finally {
File tempFile = new File(z3TempFileName);
if (tempFile.exists()) {
tempFile.delete();
}
}
}
use of org.evosuite.testcase.execution.EvosuiteError in project evosuite by EvoSuite.
the class MethodStatement method execute.
/**
* {@inheritDoc}
*/
@Override
public Throwable execute(final Scope scope, PrintStream out) throws InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException {
logger.trace("Executing method " + method.getName());
final Object[] inputs = new Object[parameters.size()];
Throwable exceptionThrown = null;
try {
return super.exceptionHandler(new Executer() {
@Override
public void execute() throws InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException, CodeUnderTestException {
Object callee_object;
try {
java.lang.reflect.Type[] parameterTypes = method.getParameterTypes();
for (int i = 0; i < parameters.size(); i++) {
VariableReference parameterVar = parameters.get(i);
inputs[i] = parameterVar.getObject(scope);
if (inputs[i] == null && method.getMethod().getParameterTypes()[i].isPrimitive()) {
throw new CodeUnderTestException(new NullPointerException());
}
if (inputs[i] != null && !TypeUtils.isAssignable(inputs[i].getClass(), parameterTypes[i])) {
// !parameterVar.isAssignableTo(parameterTypes[i])) {
throw new CodeUnderTestException(new UncompilableCodeException("Cannot assign " + parameterVar.getVariableClass().getName() + " to " + parameterTypes[i]));
}
}
callee_object = method.isStatic() ? null : callee.getObject(scope);
if (!method.isStatic() && callee_object == null) {
throw new CodeUnderTestException(new NullPointerException());
}
} catch (CodeUnderTestException e) {
throw e;
// throw CodeUnderTestException.throwException(e.getCause());
} catch (Throwable e) {
e.printStackTrace();
throw new EvosuiteError(e);
}
Object ret = method.getMethod().invoke(callee_object, inputs);
/*
* TODO: Sometimes we do want to cast an Object to String etc...
*/
if (method.getReturnType() instanceof Class<?>) {
Class<?> returnClass = (Class<?>) method.getReturnType();
if (!returnClass.isPrimitive() && ret != null && !returnClass.isAssignableFrom(ret.getClass())) {
throw new CodeUnderTestException(new ClassCastException("Cannot assign " + method.getReturnType() + " to variable of type " + retval.getType()));
}
}
try {
retval.setObject(scope, ret);
} catch (CodeUnderTestException e) {
throw e;
// throw CodeUnderTestException.throwException(e);
} catch (Throwable e) {
throw new EvosuiteError(e);
}
}
@Override
public Set<Class<? extends Throwable>> throwableExceptions() {
Set<Class<? extends Throwable>> t = new LinkedHashSet<Class<? extends Throwable>>();
t.add(InvocationTargetException.class);
return t;
}
});
} catch (InvocationTargetException e) {
exceptionThrown = e.getCause();
logger.debug("Exception thrown in method {}: {}", method.getName(), exceptionThrown);
}
return exceptionThrown;
}
use of org.evosuite.testcase.execution.EvosuiteError in project evosuite by EvoSuite.
the class MethodDescriptor method executeMatcher.
public Object executeMatcher(int i) throws IllegalArgumentException {
if (i < 0 || i >= getNumberOfInputParameters()) {
throw new IllegalArgumentException("Invalid index: " + i);
}
Type[] types = method.getParameterTypes();
Type type = types[i];
try {
if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
return Mockito.anyInt();
} else if (type.equals(Long.TYPE) || type.equals(Long.class)) {
return Mockito.anyLong();
} else if (type.equals(Boolean.TYPE) || type.equals(Boolean.class)) {
return Mockito.anyBoolean();
} else if (type.equals(Double.TYPE) || type.equals(Double.class)) {
return Mockito.anyDouble();
} else if (type.equals(Float.TYPE) || type.equals(Float.class)) {
return Mockito.anyFloat();
} else if (type.equals(Short.TYPE) || type.equals(Short.class)) {
return Mockito.anyShort();
} else if (type.equals(Character.TYPE) || type.equals(Character.class)) {
return Mockito.anyChar();
} else if (type.equals(String.class)) {
return Mockito.anyString();
} else if (TypeUtils.isAssignable(type, List.class)) {
return Mockito.anyList();
} else if (TypeUtils.isAssignable(type, Set.class)) {
return Mockito.anySet();
} else if (TypeUtils.isAssignable(type, Map.class)) {
return Mockito.anyMap();
} else if (TypeUtils.isAssignable(type, Collection.class)) {
return Mockito.anyCollection();
} else if (TypeUtils.isAssignable(type, Iterable.class)) {
return Mockito.anyIterable();
} else {
GenericClass gc = new GenericClass(type);
return Mockito.nullable(gc.getRawClass());
}
} catch (Exception e) {
logger.error("Failed to executed Mockito matcher n{} of type {} in {}.{}: {}", i, type, className, methodName, e.getMessage());
throw new EvosuiteError(e);
}
}
use of org.evosuite.testcase.execution.EvosuiteError in project evosuite by EvoSuite.
the class FunctionalMockStatement method execute.
@Override
public Throwable execute(Scope scope, PrintStream out) throws InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException {
Throwable exceptionThrown = null;
try {
return super.exceptionHandler(new Executer() {
@Override
public void execute() throws InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException, CodeUnderTestException {
// First create the listener
listener = createInvocationListener();
// then create the mock
Object ret;
try {
logger.debug("Mockito: create mock for {}", targetClass);
ret = mock(targetClass, createMockSettings());
// ret = mockCreator.invoke(null,targetClass,withSettings().invocationListeners(listener));
// execute all "when" statements
int index = 0;
logger.debug("Mockito: going to mock {} different methods", mockedMethods.size());
for (MethodDescriptor md : mockedMethods) {
if (!md.shouldBeMocked()) {
// no need to mock a method that returns void
logger.debug("Mockito: method {} cannot be mocked", md.getMethodName());
continue;
}
// target method, eg foo.aMethod(...)
Method method = md.getMethod();
// this is needed if method is protected: it couldn't be called here, although fine in
// the generated JUnit tests
method.setAccessible(true);
// target inputs
Object[] targetInputs = new Object[md.getNumberOfInputParameters()];
for (int i = 0; i < targetInputs.length; i++) {
logger.debug("Mockito: executing matcher {}/{}", (1 + i), targetInputs.length);
targetInputs[i] = md.executeMatcher(i);
}
logger.debug("Mockito: going to invoke method {} with {} matchers", method.getName(), targetInputs.length);
if (!method.getDeclaringClass().isAssignableFrom(ret.getClass())) {
String msg = "Mismatch between callee's class " + ret.getClass() + " and method's class " + method.getDeclaringClass();
msg += "\nTarget class classloader " + targetClass.getClassLoader() + " vs method's classloader " + method.getDeclaringClass().getClassLoader();
throw new EvosuiteError(msg);
}
// actual call foo.aMethod(...)
Object targetMethodResult;
try {
if (targetInputs.length == 0) {
targetMethodResult = method.invoke(ret);
} else {
targetMethodResult = method.invoke(ret, targetInputs);
}
} catch (InvocationTargetException e) {
logger.error("Invocation of mocked {}.{}() threw an exception. " + "This means the method was not mocked", targetClass.getName(), method.getName());
throw e;
} catch (IllegalArgumentException | IllegalAccessError e) {
// FIXME: Happens for reasons I don't understand. By throwing a CodeUnderTestException EvoSuite
// will just ignore that mocking statement and continue, instead of crashing
logger.error("IAE on <" + method + "> when called with " + Arrays.toString(targetInputs));
throw new CodeUnderTestException(e);
}
// when(...)
logger.debug("Mockito: call 'when'");
OngoingStubbing<Object> retForThen = Mockito.when(targetMethodResult);
// thenReturn(...)
Object[] thenReturnInputs = null;
try {
int size = Math.min(md.getCounter(), Properties.FUNCTIONAL_MOCKING_INPUT_LIMIT);
thenReturnInputs = new Object[size];
for (int i = 0; i < thenReturnInputs.length; i++) {
// the position in flat parameter list
int k = i + index;
if (k >= parameters.size()) {
// throw new RuntimeException("EvoSuite ERROR: index " + k + " out of " + parameters.size());
throw new CodeUnderTestException(new FalsePositiveException("EvoSuite ERROR: index " + k + " out of " + parameters.size()));
}
VariableReference parameterVar = parameters.get(i + index);
thenReturnInputs[i] = parameterVar.getObject(scope);
CodeUnderTestException codeUnderTestException = null;
if (thenReturnInputs[i] == null && method.getReturnType().isPrimitive()) {
codeUnderTestException = new CodeUnderTestException(new NullPointerException());
} else if (thenReturnInputs[i] != null && !TypeUtils.isAssignable(thenReturnInputs[i].getClass(), method.getReturnType())) {
codeUnderTestException = new CodeUnderTestException(new UncompilableCodeException("Cannot assign " + parameterVar.getVariableClass().getName() + " to " + method.getReturnType()));
}
if (codeUnderTestException != null) {
throw codeUnderTestException;
}
thenReturnInputs[i] = fixBoxing(thenReturnInputs[i], method.getReturnType());
}
} catch (Exception e) {
// be sure "then" is always called after a "when", otherwise Mockito might end up in
// a inconsistent state
retForThen.thenThrow(new RuntimeException("Failed to setup mock: " + e.getMessage()));
throw e;
}
// final call when(...).thenReturn(...)
logger.debug("Mockito: executing 'thenReturn'");
if (thenReturnInputs == null || thenReturnInputs.length == 0) {
retForThen.thenThrow(new RuntimeException("No valid return value"));
} else if (thenReturnInputs.length == 1) {
retForThen.thenReturn(thenReturnInputs[0]);
} else {
Object[] values = Arrays.copyOfRange(thenReturnInputs, 1, thenReturnInputs.length);
retForThen.thenReturn(thenReturnInputs[0], values);
}
index += thenReturnInputs == null ? 0 : thenReturnInputs.length;
}
} catch (CodeUnderTestException e) {
throw e;
} catch (java.lang.NoClassDefFoundError e) {
AtMostOnceLogger.error(logger, "Cannot use Mockito on " + targetClass + " due to failed class initialization: " + e.getMessage());
// or should throw an exception?
return;
} catch (MockitoException | IllegalAccessException | IllegalAccessError | IllegalArgumentException e) {
// FIXME: Happens for reasons I don't understand. By throwing a CodeUnderTestException EvoSuite
// will just ignore that mocking statement and continue, instead of crashing
AtMostOnceLogger.error(logger, "Cannot use Mockito on " + targetClass + " due to IAE: " + e.getMessage());
// or should throw an exception?
throw new CodeUnderTestException(e);
} catch (Throwable t) {
AtMostOnceLogger.error(logger, "Failed to use Mockito on " + targetClass + ": " + t.getMessage());
throw new EvosuiteError(t);
}
// finally, activate the listener
listener.activate();
try {
retval.setObject(scope, ret);
} catch (CodeUnderTestException e) {
throw e;
} catch (Throwable e) {
throw new EvosuiteError(e);
}
}
/**
* a "char" can be used for a "int". But problem is that Mockito takes as input
* Object, and so those get boxed. However, a Character cannot be used for a "int",
* so we need to be sure to convert it here
*
* @param value
* @param expectedType
* @return
*/
private Object fixBoxing(Object value, Class<?> expectedType) {
if (!expectedType.isPrimitive()) {
return value;
}
Class<?> valuesClass = value.getClass();
assert !valuesClass.isPrimitive();
if (expectedType.equals(Integer.TYPE)) {
if (valuesClass.equals(Character.class)) {
value = (int) ((Character) value).charValue();
} else if (valuesClass.equals(Byte.class)) {
value = (int) ((Byte) value).intValue();
} else if (valuesClass.equals(Short.class)) {
value = (int) ((Short) value).intValue();
}
}
if (expectedType.equals(Double.TYPE)) {
if (valuesClass.equals(Integer.class)) {
value = (double) ((Integer) value).intValue();
} else if (valuesClass.equals(Byte.class)) {
value = (double) ((Byte) value).intValue();
} else if (valuesClass.equals(Character.class)) {
value = (double) ((Character) value).charValue();
} else if (valuesClass.equals(Short.class)) {
value = (double) ((Short) value).intValue();
} else if (valuesClass.equals(Long.class)) {
value = (double) ((Long) value).longValue();
} else if (valuesClass.equals(Float.class)) {
value = (double) ((Float) value).floatValue();
}
}
if (expectedType.equals(Float.TYPE)) {
if (valuesClass.equals(Integer.class)) {
value = (float) ((Integer) value).intValue();
} else if (valuesClass.equals(Byte.class)) {
value = (float) ((Byte) value).intValue();
} else if (valuesClass.equals(Character.class)) {
value = (float) ((Character) value).charValue();
} else if (valuesClass.equals(Short.class)) {
value = (float) ((Short) value).intValue();
} else if (valuesClass.equals(Long.class)) {
value = (float) ((Long) value).longValue();
}
}
if (expectedType.equals(Long.TYPE)) {
if (valuesClass.equals(Integer.class)) {
value = (long) ((Integer) value).intValue();
} else if (valuesClass.equals(Byte.class)) {
value = (long) ((Byte) value).intValue();
} else if (valuesClass.equals(Character.class)) {
value = (long) ((Character) value).charValue();
} else if (valuesClass.equals(Short.class)) {
value = (long) ((Short) value).intValue();
}
}
if (expectedType.equals(Short.TYPE)) {
if (valuesClass.equals(Integer.class)) {
value = (short) ((Integer) value).intValue();
} else if (valuesClass.equals(Byte.class)) {
value = (short) ((Byte) value).intValue();
} else if (valuesClass.equals(Short.class)) {
value = (short) ((Short) value).intValue();
} else if (valuesClass.equals(Character.class)) {
value = (short) ((Character) value).charValue();
} else if (valuesClass.equals(Long.class)) {
value = (short) ((Long) value).intValue();
}
}
if (expectedType.equals(Byte.TYPE)) {
if (valuesClass.equals(Integer.class)) {
value = (byte) ((Integer) value).intValue();
} else if (valuesClass.equals(Short.class)) {
value = (byte) ((Short) value).intValue();
} else if (valuesClass.equals(Byte.class)) {
value = (byte) ((Byte) value).intValue();
} else if (valuesClass.equals(Character.class)) {
value = (byte) ((Character) value).charValue();
} else if (valuesClass.equals(Long.class)) {
value = (byte) ((Long) value).intValue();
}
}
return value;
}
@Override
public Set<Class<? extends Throwable>> throwableExceptions() {
Set<Class<? extends Throwable>> t = new LinkedHashSet<>();
t.add(InvocationTargetException.class);
return t;
}
});
} catch (InvocationTargetException e) {
exceptionThrown = e.getCause();
}
return exceptionThrown;
}
Aggregations