File: test_segments.py

package info (click to toggle)
dpath-python 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 256 kB
  • sloc: python: 1,671; makefile: 3
file content (331 lines) | stat: -rw-r--r-- 10,458 bytes parent folder | download
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import os
from unittest import TestCase

import hypothesis.strategies as st
from hypothesis import given, assume, settings, HealthCheck

import dpath.segments as api
from dpath import options

settings.register_profile("default", suppress_health_check=(HealthCheck.too_slow,))
settings.load_profile(os.getenv(u'HYPOTHESIS_PROFILE', 'default'))

random_key_int = st.integers(0, 1000)
random_key_str = st.binary() | st.text()
random_key = random_key_str | random_key_int
random_segments = st.lists(random_key)
random_leaf = st.integers() | st.floats() | st.booleans() | st.binary() | st.text() | st.none()

random_thing = st.recursive(
    random_leaf,
    lambda children: st.lists(children) | st.tuples(children) | st.dictionaries(st.binary() | st.text(), children),
    max_leaves=100
)
random_node = random_thing.filter(lambda thing: isinstance(thing, (list, tuple, dict)))

random_mutable_thing = st.recursive(
    random_leaf,
    lambda children: st.lists(children) | st.dictionaries(st.binary() | st.text(), children)
)
random_mutable_node = random_mutable_thing.filter(lambda thing: isinstance(thing, (list, dict)))


@st.composite
def mutate(draw, segment):
    # Convert number segments.
    segment = api.int_str(segment)

    # Infer the type constructor for the result.
    kind = type(segment)

    # Produce a valid kind conversion for our wildcards.
    if isinstance(segment, bytes):
        def to_kind(v):
            try:
                return bytes(v, 'utf-8')
            except:
                return kind(v)
    else:
        def to_kind(v):
            return kind(v)

    # Convert to an list of single values.
    converted = []
    for i in range(len(segment)):
        # This carefully constructed nonsense to get a single value
        # is necessary to work around limitations in the bytes type
        # iteration returning integers instead of byte strings of
        # length 1.
        c = segment[i:i + 1]

        # Check for values that need to be escaped.
        if c in tuple(map(to_kind, ('*', '?', '[', ']'))):
            c = to_kind('[') + c + to_kind(']')

        converted.append(c)

    # Start with a non-mutated result.
    result = converted

    # 50/50 chance we will attempt any mutation.
    change = draw(st.sampled_from((True, False)))
    if change:
        result = []

        # For every value in segment maybe mutate, maybe not.
        for c in converted:
            # If the length isn't 1 then, we know this value is already
            # an escaped special character. We will not mutate these.
            if len(c) != 1:
                result.append(c)
            else:
                result.append(draw(st.sampled_from((c, to_kind('?'), to_kind('*')))))

    combined = kind().join(result)

    # If we by chance produce the star-star result, then just revert
    # back to the original converted segment. This is not the mutation
    # you are looking for.
    if combined == to_kind('**'):
        combined = kind().join(converted)

    return combined


@st.composite
def random_segments_with_glob(draw):
    segments = draw(random_segments)
    glob = list(map(lambda x: draw(mutate(x)), segments))

    # 50/50 chance we will attempt to add a star-star to the glob.
    use_ss = draw(st.sampled_from((True, False)))
    if use_ss:
        # Decide if we are inserting a new segment or replacing a range.
        insert_ss = draw(st.sampled_from((True, False)))
        if insert_ss:
            index = draw(st.integers(0, len(glob)))
            glob.insert(index, '**')
        else:
            start = draw(st.integers(0, len(glob)))
            stop = draw(st.integers(start, len(glob)))
            glob[start:stop] = ['**']

    return segments, glob


@st.composite
def random_segments_with_nonmatching_glob(draw):
    (segments, glob) = draw(random_segments_with_glob())

    # Generate a segment that is not in segments.
    invalid = draw(random_key.filter(lambda x: x not in segments and x not in ('*', '**')))

    # Do we just have a star-star glob? It matches everything, so we
    # need to replace it entirely.
    if len(glob) == 1 and glob[0] == '**':
        glob = [invalid]
    # Do we have a star glob and only one segment? It matches anything
    # in the segment, so we need to replace it entirely.
    elif len(glob) == 1 and glob[0] == '*' and len(segments) == 1:
        glob = [invalid]
    # Otherwise we can add something we know isn't in the segments to
    # the glob.
    else:
        index = draw(st.integers(0, len(glob)))
        glob.insert(index, invalid)

    return (segments, glob)


@st.composite
def random_walk(draw):
    node = draw(random_mutable_node)
    found = tuple(api.walk(node))
    assume(len(found) > 0)
    return (node, draw(st.sampled_from(found)))


@st.composite
def random_leaves(draw):
    node = draw(random_mutable_node)
    found = tuple(api.leaves(node))
    assume(len(found) > 0)
    return (node, draw(st.sampled_from(found)))


class TestSegments(TestCase):
    @classmethod
    def setUpClass(cls):
        # Allow empty strings in segments.
        options.ALLOW_EMPTY_STRING_KEYS = True

    @classmethod
    def tearDownClass(cls):
        # Revert back to default.
        options.ALLOW_EMPTY_STRING_KEYS = False

    @given(random_node)
    def test_kvs(self, node):
        '''
        Given a node, kvs should produce a key that when used to extract
        from the node renders the exact same value given.
        '''
        for k, v in api.make_walkable(node):
            assert node[k] is v

    @given(random_leaf)
    def test_leaf_with_leaf(self, leaf):
        '''
        Given a leaf, leaf should return True.
        '''
        assert api.leaf(leaf) is True

    @given(random_node)
    def test_leaf_with_node(self, node):
        '''
        Given a node, leaf should return False.
        '''
        assert api.leaf(node) is False

    @given(random_thing)
    def test_walk(self, thing):
        '''
        Given a thing to walk, walk should yield key, value pairs where key
        is a tuple of non-zero length.
        '''
        for k, v in api.walk(thing):
            assert isinstance(k, tuple)
            assert len(k) > 0

    @given(random_node)
    def test_get(self, node):
        '''
        Given a node, get should return the exact value given a key for all
        key, value pairs in the node.
        '''
        for k, v in api.walk(node):
            assert api.get(node, k) is v

    @given(random_node)
    def test_has(self, node):
        '''
        Given a node, has should return True for all paths, False otherwise.
        '''
        for k, v in api.walk(node):
            assert api.has(node, k) is True

            # If we are at a leaf, then we can create a value that isn't
            # present easily.
            if api.leaf(v):
                assert api.has(node, k + (0,)) is False

    @given(random_segments)
    def test_expand(self, segments):
        '''
        Given segments expand should produce as many results are there were
        segments and the last result should equal the given segments.
        '''
        count = len(segments)
        result = list(api.expand(segments))

        assert count == len(result)

        if count > 0:
            assert segments == result[-1]

    @given(random_node)
    def test_types(self, node):
        '''
        Given a node, types should yield a tuple of key, type pairs and the
        type indicated should equal the type of the value.
        '''
        for k, v in api.walk(node):
            ts = api.types(node, k)
            ta = ()
            for tk, tt in ts:
                ta += (tk,)
                assert type(api.get(node, ta)) is tt

    @given(random_node)
    def test_leaves(self, node):
        '''
        Given a node, leaves should yield only leaf key, value pairs.
        '''
        for k, v in api.leaves(node):
            assert api.leafy(v)

    @given(random_segments_with_glob())
    def test_match(self, pair):
        '''
        Given segments and a known good glob, match should be True.
        '''
        (segments, glob) = pair
        assert api.match(segments, glob) is True

    @given(random_segments_with_nonmatching_glob())
    def test_match_nonmatching(self, pair):
        '''
        Given segments and a known bad glob, match should be False.
        '''
        (segments, glob) = pair
        assert api.match(segments, glob) is False

    @given(walkable=random_walk(), value=random_thing)
    def test_set_walkable(self, walkable, value):
        '''
        Given a walkable location, set should be able to update any value.
        '''
        (node, (segments, found)) = walkable
        api.set(node, segments, value)
        assert api.get(node, segments) is value

    @given(walkable=random_leaves(),
           kstr=random_key_str,
           kint=random_key_int,
           value=random_thing,
           extension=random_segments)
    def test_set_create_missing(self, walkable, kstr, kint, value, extension):
        '''
        Given a walkable non-leaf, set should be able to create missing
        nodes and set a new value.
        '''
        (node, (segments, found)) = walkable
        assume(api.leaf(found))

        parent_segments = segments[:-1]
        parent = api.get(node, parent_segments)

        if isinstance(parent, list):
            assume(len(parent) < kint)
            destination = parent_segments + (kint,) + tuple(extension)
        elif isinstance(parent, dict):
            assume(kstr not in parent)
            destination = parent_segments + (kstr,) + tuple(extension)
        else:
            raise Exception('mad mad world')

        api.set(node, destination, value)
        assert api.get(node, destination) is value

    @given(thing=random_thing)
    def test_fold(self, thing):
        '''
        Given a thing, count paths with fold.
        '''

        def f(o, p, a):
            a[0] += 1

        [count] = api.fold(thing, f, [0])
        assert count == len(tuple(api.walk(thing)))

    @given(walkable=random_walk())
    def test_view(self, walkable):
        '''
        Given a walkable location, view that location.
        '''
        (node, (segments, found)) = walkable
        assume(found == found)  # Hello, nan! We don't want you here.

        view = api.view(node, segments)
        assert api.get(view, segments) == api.get(node, segments)