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
#![cfg_attr(feature="cargo-clippy",
allow(type_complexity, expl_impl_clone_on_copy))]
use std::fmt;
use std::marker::PhantomData;
use strategy::*;
use test_runner::*;
mapfn! {
[] fn WrapSome[<T : fmt::Debug>](t: T) -> Option<T> {
Some(t)
}
}
struct NoneStrategy<T>(PhantomData<T>);
impl<T> Clone for NoneStrategy<T> {
fn clone(&self) -> Self { *self }
}
impl<T> Copy for NoneStrategy<T> { }
impl<T> fmt::Debug for NoneStrategy<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "NoneStrategy")
}
}
impl<T : fmt::Debug> Strategy for NoneStrategy<T> {
type Value = Self;
fn new_value(&self, _: &mut TestRunner) -> NewTree<Self> {
Ok(*self)
}
}
impl<T : fmt::Debug> ValueTree for NoneStrategy<T> {
type Value = Option<T>;
fn current(&self) -> Option<T> { None }
fn simplify(&mut self) -> bool { false }
fn complicate(&mut self) -> bool { false }
}
opaque_strategy_wrapper! {
#[derive(Clone)]
pub struct OptionStrategy[<T>][where T : Strategy]
(TupleUnion<(W<NoneStrategy<ValueFor<T>>>,
W<statics::Map<T, WrapSome>>)>)
-> OptionValueTree<T::Value>;
#[derive(Clone, Debug)]
pub struct OptionValueTree[<T>][where T : ValueTree]
(TupleUnionValueTree<(NoneStrategy<T::Value>,
Option<statics::Map<T, WrapSome>>)>)
-> Option<T::Value>;
}
impl<T : Strategy + fmt::Debug> fmt::Debug for OptionStrategy<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "OptionStrategy({:?})", self.0)
}
}
pub fn of<T : Strategy>(t: T) -> OptionStrategy<T> {
weighted(0.5, t)
}
pub fn weighted<T : Strategy>(probability_of_some: f64, t: T)
-> OptionStrategy<T> {
let (weight_some, weight_none) = float_to_weight(probability_of_some);
OptionStrategy(TupleUnion::new((
(weight_none, NoneStrategy(PhantomData)),
(weight_some, statics::Map::new(t, WrapSome)),
)))
}
#[cfg(test)]
mod test {
use super::*;
fn count_some_of_1000(s: OptionStrategy<Just<i32>>) -> u32 {
let mut runner = TestRunner::default();
let mut count = 0;
for _ in 0..1000 {
count += s.new_value(&mut runner).unwrap()
.current().is_some() as u32;
}
count
}
#[test]
fn probability_defaults_to_0p5() {
let count = count_some_of_1000(of(Just(42i32)));
assert!(count > 450 && count < 550);
}
#[test]
fn probability_handled_correctly() {
let count = count_some_of_1000(weighted(0.9, Just(42i32)));
assert!(count > 800 && count < 950);
let count = count_some_of_1000(weighted(0.1, Just(42i32)));
assert!(count > 50 && count < 150);
}
#[test]
fn test_sanity() {
check_strategy_sanity(of(0i32..1000i32), None);
}
}