summaryrefslogtreecommitdiff
path: root/src/main/java/au/id/zancanaro/PropertyTestRunner.java
blob: 8df9b2afd105624cd208d289a0138ad30184b5e1 (about) (plain)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package au.id.zancanaro;

import au.id.zancanaro.annotations.Property;
import au.id.zancanaro.annotations.Seed;
import org.junit.AssumptionViolatedException;
import org.junit.Ignore;
import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.ParentRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.*;

public class PropertyTestRunner extends ParentRunner<FrameworkMethod> {

    private final Class<?> classUnderTest;

    public PropertyTestRunner(Class<?> classUnderTest) throws InitializationError{
        super(classUnderTest);
        this.classUnderTest = classUnderTest;
    }

    @Override
    protected boolean isIgnored(FrameworkMethod child) {
        return child.getAnnotation(Ignore.class) != null;
    }

    @Override
    protected List<FrameworkMethod> getChildren() {
        List<FrameworkMethod> result = new ArrayList<>();
        for (Method method : classUnderTest.getDeclaredMethods()) {
            if (method.isAnnotationPresent(Property.class)
                    && !method.isAnnotationPresent(Ignore.class)) {
                result.add(new FrameworkMethod(method));
            }
        }
        return result;
    }

    @Override
    protected Description describeChild(FrameworkMethod child) {
        return Description.createTestDescription(classUnderTest, child.getName());
    }

    @Override
    protected void runChild(FrameworkMethod child, RunNotifier notifier) {
        try {
            Property details = child.getAnnotation(Property.class);
            Description description = Description.createTestDescription(classUnderTest, child.getName());
            boolean failed = false;
            int assumptionsFailed = 0;

            long seed = getSeed(child.getMethod());
            Random random = new Random(seed);
            int numRuns = details.runs();
            for (int i = 0; i < numRuns && !failed; ++i) {
                int size = details.size();
                notifier.fireTestStarted(description);
                Object obj;
                try {
                    obj = classUnderTest.getConstructor().newInstance();
                } catch (Throwable ex) { // HACKY
                    System.out.println(ex);
                    return;
                }
                RoseTree<Object[]> generated = generateArgs(random, size,
                        child.getMethod().getGenericParameterTypes(),
                        child.getMethod().getParameterAnnotations());
                try {
                    child.getMethod().invoke(obj, generated.getValue());
                } catch (InvocationTargetException ex) {
                    if (ex.getTargetException() instanceof AssumptionViolatedException) {
                        assumptionsFailed++;
                        i--;
                    } else {
                        System.out.println("Test failed with seed: " + seed);
                        System.out.println("Failing arguments: " + Arrays.asList(generated.getValue()));
                        Object[] shrinkResult = shrink(child.getMethod(), obj, generated);
                        if (shrinkResult == null) {
                            System.out.println("Arguments could not be shrunk any further");
                        } else {
                            System.out.println("Arguments shrunk to: " + Arrays.asList(shrinkResult));
                        }
                        notifier.fireTestFailure(new Failure(description, ex.getTargetException()));
                        failed = true;
                    }
                } catch (IllegalAccessException ex) {
                    notifier.fireTestFailure(new Failure(description, ex));
                    failed = true;
                }
            }

            if (assumptionsFailed > 0) {
                System.out.println("Failed " + assumptionsFailed + " assumptions");
            }
            notifier.fireTestFinished(description);
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }

    private long getSeed(Method method) {
        Seed seed = method.getAnnotation(Seed.class);
        if (seed == null) {
            return System.currentTimeMillis();
        } else {
            return seed.value();
        }
    }

    private Object[] shrink(Method method, Object obj, RoseTree<Object[]> failed) {
        Object[] smallest = failed.getValue();
        Iterator<RoseTree<Object[]>> trees = failed.getChildren();
        while (trees.hasNext()) {
            RoseTree<Object[]> tree = trees.next();
            try {
                method.invoke(obj, tree.getValue());
            } catch (InvocationTargetException ex) {
                if (!(ex.getTargetException() instanceof AssumptionViolatedException)) {
                    smallest = tree.getValue();
                    Iterator<RoseTree<Object[]>> children = tree.getChildren();
                    if (children.hasNext()) {
                        trees = children;
                    } else {
                        break;
                    }
                }
            } catch (IllegalAccessException ex) {
                System.out.println(ex);
            }
        }
        return smallest;
    }

    private <T> String printShrinkTree(RoseTree<T[]> generated) {
        StringBuilder builder = new StringBuilder();
        builder.append('(');
        builder.append(Arrays.toString(generated.getValue()));
        generated.getChildren().forEachRemaining((child) -> {
            builder.append(' ');
            builder.append(printShrinkTree(child));
        });
        builder.append(')');
        return builder.toString();
    }


    private RoseTree<Object[]> generateArgs(Random random, int size, Type[] types, Annotation[][] annotations) {
        Generator<?>[] generators = new Generator[types.length];
        for (int i = 0; i < types.length; ++i) {
//            generators[i] = getGeneratorFromAnnotations(annotations[i]);
//            if (generators[i] == null) {
                generators[i] = getGeneratorFromType(types[i]);
//            }
        }
        @SuppressWarnings("unchecked")
        Generator<Object>[] argsGenerators = (Generator<Object>[]) generators;
        return Generator.tuple(argsGenerators).generate(random, size);
    }

    private Generator<?> getGeneratorFromType(Type type) {
        if (type instanceof Class) {
            Class<?> clazz = (Class<?>) type;
            if (clazz.isPrimitive() && clazz == Integer.TYPE) {
                return Generators.integer();
            } else {
                throw new RuntimeException("Unknown type for generator (atm only int is supported)");
            }
        } else {
            throw new RuntimeException("Unknown type for generator (atm only int is supported)");
        }
    }
}