-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathRandomResolver.java
82 lines (65 loc) · 2.49 KB
/
RandomResolver.java
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
package org.codefx.demo.junit5;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
public class RandomResolver implements ParameterResolver, TestExecutionExceptionHandler {
private static final Namespace NAMESPACE = Namespace.create("org", "codefx", "RandomResolver");
@Override
public boolean supportsParameter(
ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
// don't blindly support a common type like `Random`
// instead it should be annotated with `@Randomized` or something
Class<?> targetType = parameterContext.getParameter().getType();
return targetType == Random.class || targetType == SeededRandom.class;
}
@Override
public Object resolveParameter(
ParameterContext parameterContext, ExtensionContext context)
throws ParameterResolutionException {
return randomByUniqueId(context)
.computeIfAbsent(context.getUniqueId(), SeededRandom::create);
}
@SuppressWarnings("unchecked")
private static Map<String, SeededRandom> randomByUniqueId(ExtensionContext context) {
return context
.getStore(NAMESPACE)
.getOrComputeIfAbsent("Map<Unique ID, SeededRandom>", key -> new ConcurrentHashMap<>(), Map.class);
}
@Override
public void handleTestExecutionException(
ExtensionContext context, Throwable throwable) throws Throwable {
String seed = Optional.ofNullable(randomByUniqueId(context).get(context.getUniqueId()))
.map(SeededRandom::seed)
.map(s -> "seed " + s)
.orElse("unknown seed");
System.out.println("Exception occurred in test based on " + seed);
throw throwable;
}
public static class SeededRandom extends Random {
private static Random seeder = new Random();
private final String testId;
private final long seed;
private SeededRandom(String testId, long seed) {
super(seed);
this.testId = testId;
this.seed = seed;
}
static SeededRandom create(String testId) {
return new SeededRandom(testId, seeder.nextLong());
}
public String testId() {
return testId;
}
public long seed() {
return seed;
}
}
}