Search in sources :

Example 96 with CtClass

use of javassist.CtClass in project powermock by powermock.

the class MethodsMockTransformerTest method prepareClassesForTest.

private CtClass prepareClassesForTest(ClassPool classPool, String bodyOfSyntheticMethod) throws NotFoundException, CannotCompileException {
    CtClass ctClass = classPool.getCtClass(SuperClassWithObjectMethod.class.getName());
    addSyntheticMethod(classPool, ctClass, bodyOfSyntheticMethod);
    return ctClass;
}
Also used : CtClass(javassist.CtClass) SuperClassWithObjectMethod(powermock.test.support.MainMockTransformerTestSupport.SuperClassWithObjectMethod)

Example 97 with CtClass

use of javassist.CtClass in project powermock by powermock.

the class PowerMockExpressionEditor method edit.

@Override
public void edit(MethodCall m) throws CannotCompileException {
    try {
        final CtMethod method = m.getMethod();
        final CtClass declaringClass = method.getDeclaringClass();
        if (declaringClass != null) {
            if (TransformerHelper.shouldTreatAsSystemClassCall(declaringClass)) {
                StringBuilder code = new StringBuilder();
                code.append("{Object classOrInstance = null; if($0!=null){classOrInstance = $0;} else { classOrInstance = $class;}");
                code.append("Object value =  ").append(MockGateway.class.getName()).append(".methodCall(").append("classOrInstance,\"").append(m.getMethodName()).append("\",$args, $sig,\"").append(getReturnTypeAsString(method)).append("\");");
                code.append("if(value == ").append(MockGateway.class.getName()).append(".PROCEED) {");
                code.append("	$_ = $proceed($$);");
                code.append("} else {");
                final String correctReturnValueType = getCorrectReturnValueType(method.getReturnType());
                if (!VOID.equals(correctReturnValueType)) {
                    code.append("	$_ = ").append(correctReturnValueType).append(";");
                }
                code.append("}}");
                m.replace(code.toString());
            }
        }
    } catch (NotFoundException e) {
    /*
                 * If multiple java agents are active (in INST_REDEFINE mode), the types implicitly loaded by javassist from disk
                 * might differ from the types available in memory. Thus, this error might occur.
                 *
                 * It may also happen if PowerMock is modifying an SPI where the SPI require some classes to be available in the classpath
                 * at runtime but they are not! This is valid in some cases such as slf4j.
                 */
    }
}
Also used : CtClass(javassist.CtClass) MockGateway(org.powermock.core.MockGateway) NotFoundException(javassist.NotFoundException) TransformerHelper.getReturnTypeAsString(org.powermock.core.transformers.javassist.support.TransformerHelper.getReturnTypeAsString) CtMethod(javassist.CtMethod)

Example 98 with CtClass

use of javassist.CtClass in project powermock by powermock.

the class ClassReplicaCreator method createInstanceReplica.

/**
 * Create a class that is a replica of type {@code T}. To allow for
 * partial mocking all calls to non-mocked methods will be delegated to the
 * {@code delegator}.
 *
 * @param <T>       The type of the replica class to be created.
 * @param delegator The delegator object that will be invoked to allow for partial
 *                  mocking.
 * @return A replica class that can be used to duck-type an instance.
 */
@SuppressWarnings("unchecked")
public <T> Class<T> createInstanceReplica(T delegator) {
    if (delegator == null) {
        throw new IllegalArgumentException("delegator cannot be null");
    }
    final Class<T> clazz = (Class<T>) delegator.getClass();
    ClassPool classpool = ClassPool.getDefault();
    final String originalClassName = clazz.getName();
    CtClass originalClassAsCtClass;
    final CtClass newClass = classpool.makeClass(generateReplicaClassName(clazz));
    try {
        originalClassAsCtClass = classpool.get(originalClassName);
        copyFields(originalClassAsCtClass, newClass);
        addDelegatorField(delegator, newClass);
        CtMethod[] declaredMethods = originalClassAsCtClass.getDeclaredMethods();
        for (CtMethod ctMethod : declaredMethods) {
            @SuppressWarnings("unused") final String code = getReplicaMethodDelegationCode(delegator.getClass(), ctMethod, POWERMOCK_INSTANCE_DELEGATOR_FIELD_NAME);
            CtMethod make2 = CtNewMethod.copy(ctMethod, newClass, null);
            newClass.addMethod(make2);
        }
        CtConstructor[] declaredConstructors = originalClassAsCtClass.getDeclaredConstructors();
        for (CtConstructor ctConstructor : declaredConstructors) {
            CtConstructor copy = CtNewConstructor.copy(ctConstructor, newClass, null);
            newClass.addConstructor(copy);
        }
        return (Class<T>) newClass.toClass(this.getClass().getClassLoader(), this.getClass().getProtectionDomain());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : ClassPool(javassist.ClassPool) CannotCompileException(javassist.CannotCompileException) NotFoundException(javassist.NotFoundException) CtConstructor(javassist.CtConstructor) CtClass(javassist.CtClass) CtClass(javassist.CtClass) CtMethod(javassist.CtMethod)

Example 99 with CtClass

use of javassist.CtClass in project powermock by powermock.

the class MethodMockTransformer method modifyMethod.

void modifyMethod(final CtMethod method) throws NotFoundException, CannotCompileException {
    if (!shouldSkipMethod(method)) {
        // Lookup the method return type
        final CtClass returnTypeAsCtClass = method.getReturnType();
        final String returnTypeAsString = getReturnTypeAsString(method);
        if (Modifier.isNative(method.getModifiers())) {
            modifyNativeMethod(method, returnTypeAsCtClass, returnTypeAsString);
        } else {
            modifyMethod(method, returnTypeAsCtClass, returnTypeAsString);
        }
    }
}
Also used : CtClass(javassist.CtClass) TransformerHelper.getReturnTypeAsString(org.powermock.core.transformers.javassist.support.TransformerHelper.getReturnTypeAsString)

Example 100 with CtClass

use of javassist.CtClass in project powermock by powermock.

the class JavassistMockClassLoader method defineAndTransformClass.

protected byte[] defineAndTransformClass(String name, ProtectionDomain protectionDomain) {
    final byte[] clazz;
    ClassPool.doPruning = false;
    try {
        CtClass type = classPool.get(name);
        ClassWrapper<CtClass> wrappedType = classWrapperFactory.wrap(type);
        wrappedType = transformClass(wrappedType);
        type = wrappedType.unwrap();
        /*
             * ClassPool may cause huge memory consumption if the number of CtClass
             * objects becomes amazingly large (this rarely happens since Javassist
             * tries to reduce memory consumption in various ways). To avoid this
             * problem, you can explicitly remove an unnecessary CtClass object from
             * the ClassPool. If you call detach() on a CtClass object, then that
             * CtClass object is removed from the ClassPool.
             */
        type.detach();
        clazz = type.toBytecode();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to transform class with name " + name + ". Reason: " + e.getMessage(), e);
    }
    return clazz;
}
Also used : CtClass(javassist.CtClass) NotFoundException(javassist.NotFoundException)

Aggregations

CtClass (javassist.CtClass)271 CtMethod (javassist.CtMethod)96 ClassPool (javassist.ClassPool)93 NotFoundException (javassist.NotFoundException)85 Test (org.junit.Test)63 CannotCompileException (javassist.CannotCompileException)62 CtField (javassist.CtField)53 IOException (java.io.IOException)35 CtConstructor (javassist.CtConstructor)26 Method (java.lang.reflect.Method)17 LoaderClassPath (javassist.LoaderClassPath)16 ClassFile (javassist.bytecode.ClassFile)14 ArrayList (java.util.ArrayList)13 ByteArrayInputStream (java.io.ByteArrayInputStream)12 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)11 ConstPool (javassist.bytecode.ConstPool)11 File (java.io.File)8 FileNotFoundException (java.io.FileNotFoundException)8 Collectors (java.util.stream.Collectors)8 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)7