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
|
package au.id.zancanaro.javacheck;
import au.id.zancanaro.javacheck.annotations.DataSource;
import au.id.zancanaro.javacheck.annotations.Property;
import au.id.zancanaro.javacheck.junit.Properties;
import org.junit.runner.RunWith;
import java.util.Optional;
import java.util.function.Function;
import static au.id.zancanaro.javacheck.Generator.pure;
import static au.id.zancanaro.javacheck.Generators.integer;
import static au.id.zancanaro.javacheck.Generators.oneOf;
import static org.junit.Assert.assertEquals;
@RunWith(Properties.class)
public class OptionalFunctorRulesTest {
private final static int runs = 1000;
private final static int maxSize = 1000;
@DataSource
public static Generator<Optional<Integer>> listOfIntegers = oneOf(
pure(Optional.empty()),
integer().map(Optional::of));
@DataSource
public static Generator<Function<Integer, Integer>> integerFunction =
oneOf(
integer().map(OptionalFunctorRulesTest::plusI),
integer().map(OptionalFunctorRulesTest::timesI),
integer().map(OptionalFunctorRulesTest::constantlyI));
@Property(maxSize = maxSize, runs = runs)
public void mappingCompositionsWithStreams(
Optional<Integer> optional,
Function<Integer, Integer> f,
Function<Integer, Integer> g) {
Optional<Integer> left = optional
.map(g)
.map(f);
Optional<Integer> right = optional
.map(x -> f.apply(g.apply(x)));
assertEquals(left, right);
}
@Property(maxSize = maxSize, runs = runs)
public void mappingCompositionsWithIntermediateList(
Optional<Integer> optional,
Function<Integer, Integer> f,
Function<Integer, Integer> g) {
Optional<Integer> intermediate = optional.map(g);
Optional<Integer> left = intermediate.map(f);
Optional<Integer> right = optional
.map(x -> f.apply(g.apply(x)));
assertEquals(left, right);
}
@Property(maxSize = maxSize, runs = runs)
public void mapIdentityIsIdentity(Optional<Integer> optional) {
Optional<Integer> mapped = optional.map(x -> x);
assertEquals(optional, mapped);
}
private static Function<Integer,Integer> plusI(final int i) {
return new Function<Integer, Integer>() {
@Override
public Integer apply(Integer integer) {
return i + integer;
}
@Override
public String toString() {
return "x -> x + " + i;
}
};
}
private static Function<Integer,Integer> timesI(final int i) {
return new Function<Integer, Integer>() {
@Override
public Integer apply(Integer integer) {
return i * integer;
}
@Override
public String toString() {
return "x -> x * " + i;
}
};
}
private static Function<Integer,Integer> constantlyI(final int i) {
return new Function<Integer, Integer>() {
@Override
public Integer apply(Integer integer) {
return i;
}
@Override
public String toString() {
return "x -> " + i;
}
};
}
}
|