1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package org.slf4j.helpers;
26
27 import static org.junit.Assert.assertTrue;
28 import static org.junit.Assert.fail;
29
30 import java.lang.reflect.InvocationHandler;
31 import java.lang.reflect.InvocationTargetException;
32 import java.lang.reflect.Method;
33 import java.lang.reflect.Proxy;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.HashSet;
37 import java.util.List;
38 import java.util.Set;
39
40 import org.junit.Test;
41 import org.slf4j.Logger;
42 import org.slf4j.event.EventRecodingLogger;
43 import org.slf4j.helpers.SubstituteLogger;
44
45
46
47
48 public class SubstitutableLoggerTest {
49 private static final Set<String> EXCLUDED_METHODS = new HashSet<String>(Arrays.asList("getName"));
50
51 @Test
52 public void testDelegate() throws Exception {
53 SubstituteLogger log = new SubstituteLogger("foo", null, false);
54 assertTrue(log.delegate() instanceof EventRecodingLogger);
55
56 Set<String> expectedMethodSignatures = determineMethodSignatures(Logger.class);
57 LoggerInvocationHandler ih = new LoggerInvocationHandler();
58 Logger proxyLogger = (Logger) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Logger.class }, ih);
59 log.setDelegate(proxyLogger);
60
61 invokeMethods(log);
62
63
64 expectedMethodSignatures.removeAll(ih.getInvokedMethodSignatures());
65 if (!expectedMethodSignatures.isEmpty()) {
66 fail("Following methods are not delegated " + expectedMethodSignatures.toString());
67 }
68 }
69
70 private void invokeMethods(Logger proxyLogger) throws InvocationTargetException, IllegalAccessException {
71 for (Method m : Logger.class.getDeclaredMethods()) {
72 if (!EXCLUDED_METHODS.contains(m.getName())) {
73 m.invoke(proxyLogger, new Object[m.getParameterTypes().length]);
74 }
75 }
76 }
77
78 private class LoggerInvocationHandler implements InvocationHandler {
79 private final Set<String> invokedMethodSignatures = new HashSet<String>();
80
81 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
82 invokedMethodSignatures.add(getMethodSignature(method));
83 if (method.getName().startsWith("is")) {
84 return true;
85 }
86 return null;
87 }
88
89 public Set<String> getInvokedMethodSignatures() {
90 return invokedMethodSignatures;
91 }
92 }
93
94 private static Set<String> determineMethodSignatures(Class<Logger> loggerClass) {
95 Set<String> methodSignatures = new HashSet<String>();
96 for (Method m : loggerClass.getDeclaredMethods()) {
97 if (!EXCLUDED_METHODS.contains(m.getName())) {
98 methodSignatures.add(getMethodSignature(m));
99 }
100 }
101 return methodSignatures;
102 }
103
104 private static String getMethodSignature(Method m) {
105 List<String> result = new ArrayList<String>();
106 result.add(m.getName());
107 for (Class<?> clazz : m.getParameterTypes()) {
108 result.add(clazz.getSimpleName());
109 }
110 return result.toString();
111 }
112 }