I have some code that works with intervals, which are really just python dicts with the following structure:
JavaScript
x
7
1
{
2
"name": "some utf8 string",
3
"start": 0.0, # 0.0 <= start < 1.0
4
"end": 1.0, # start < end <= 1.0
5
"size": 1.0, # size == end - start
6
}
7
Writing a strategy for a single interval is relatively straightforward. I’d like to write a strategy to generate interval sets. An interval set is a list of intervals, such that:
- The list contains an arbitrary number of intervals.
- The interval names are unique.
- The intervals do not overlap.
- All intervals are contained within the range
(0.0, 1.0)
. - Each interval’s
size
is correct. - The intervals do not have to be contiguous and the entire range doesn’t need to be covered.
How would you write this strategy?
Advertisement
Answer
I managed to get this working with the following strategies. This is almost certainly sub-optimal but does produce the desired object state.
JavaScript
1
41
41
1
import math
2
import sys
3
4
from hypothesis import strategies as st
5
6
@composite
7
def range_strategy(draw):
8
"""Produces start-end pairs within the 0.0–1.0 interval"""
9
start = 0.0
10
end = 1.0
11
ranges = []
12
13
while draw(st.booleans()):
14
range_start = draw(st.floats(min_value=start, max_value=end, exclude_max=True)
15
range_end = draw(st.floats(min_value=range_start, max_value=end, exclude_min=True)
16
ranges.append((range_start, range_end))
17
18
if math.isclose(range_end, end, abs_tol=sys.float_info.epsilon):
19
# We hit the ceiling so we're done
20
break
21
start = math.nextafter(range_end, float("inf"))
22
return ranges
23
24
25
@composite
26
def interval_set_strategy(draw):
27
ranges = draw(range_strategy())
28
intervals = st.just(
29
map(
30
lambda range: {
31
"name": draw(st.text()),
32
"start": range[0],
33
"end": range[1],
34
"size": range[1] - range[0],
35
}
36
),
37
ranges
38
)
39
40
return draw(st.builds(list, intervals))
41