summaryrefslogtreecommitdiff
path: root/tests/test_pattern_tree.py
blob: df2ba159c80a0d5c96422d7c319e725c34acbb48 (about) (plain)
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# SPDX-License-Identifier: CC0-1.0

# Copyright (C) 2022 Wojtek Kosior <koszko@koszko.org>
#
# Available under the terms of Creative Commons Zero v1.0 Universal.

import pytest
import re
import dataclasses as dc

from immutables import Map

from hydrilla import pattern_tree

from .url_patterns_common import *

@pytest.mark.parametrize('_in, out', [
    (Map(),                                                  True),
    ({'children': Map(non_empty='non_emtpy')},               False),
    ({'literal_match': 'non-None'},                          False),
    ({'children': Map(non_empty='non_emtpy')},               False),
    ({'literal_match': 'non-None', 'children': 'non-empty'}, False)
])
def test_pattern_tree_node_is_empty(_in, out):
    """...."""
    assert pattern_tree.PatternTreeNode(**_in).is_empty() == out

def test_pattern_tree_node_update_literal_match():
    """...."""
    node1 = pattern_tree.PatternTreeNode()
    node2 = node1.update_literal_match('dummy match item')

    assert node1.literal_match is None
    assert node2.literal_match == 'dummy match item'

def test_pattern_tree_node_get_child():
    """...."""
    node = pattern_tree.PatternTreeNode(children=Map(dummy_key='dummy_val'))

    assert node.get_child('dummy_key') == 'dummy_val'
    assert node.get_child('other_key') is None

def test_pattern_tree_node_remove_child():
    """...."""
    node1 = pattern_tree.PatternTreeNode(children=Map(dummy_key='dummy_val'))
    node2 = node1.remove_child('dummy_key')

    assert node1.children == Map(dummy_key='dummy_val')
    assert node2.children == Map()

def test_pattern_tree_node_set_child():
    """...."""
    node1 = pattern_tree.PatternTreeNode(children=Map(dummy_key='dummy_val'))
    node2 = node1.set_child('other_key', 'other_val')

    assert node1.children == Map(dummy_key='dummy_val')
    assert node2.children == Map(dummy_key='dummy_val', other_key='other_val')

@pytest.mark.parametrize('root_empty', [True, False])
def test_pattern_tree_branch_is_empty(root_empty):
    """...."""
    class DummyEmptyRoot:
        """...."""
        is_empty = lambda: root_empty

    branch = pattern_tree.PatternTreeBranch(root_node=DummyEmptyRoot)
    assert branch.is_empty() == root_empty

# def test_pattern_tree_branch_copy():
#     """...."""
#     class DummyRoot:
#         """...."""
#         pass

#     branch1 = pattern_tree.PatternTreeBranch(root_node=DummyRoot)
#     branch2 = branch1.copy()

#     assert branch1 is not branch2
#     for val_b1, val_b2 in zip(dc.astuple(branch1), dc.astuple(branch2)):
#         assert val_b1 is val_b2

@pytest.fixture
def empty_branch():
    """...."""
    return pattern_tree.PatternTreeBranch(
        root_node = pattern_tree.PatternTreeNode()
    )

@pytest.fixture
def branch_with_a_b():
    """...."""
    return pattern_tree.PatternTreeBranch(
        root_node = pattern_tree.PatternTreeNode(
            children = Map(
                a = pattern_tree.PatternTreeNode(
                    children = Map(
                        b = pattern_tree.PatternTreeNode(
                            literal_match = frozenset({'myitem'})
                        )
                    )
                )
            )
        )
    )

def test_pattern_tree_branch_update_add_first(empty_branch, branch_with_a_b):
    """...."""
    updated_branch = empty_branch.update(
        ['a', 'b'],
        lambda s: frozenset({*(s or []), 'myitem'})
    )

    assert updated_branch                  == branch_with_a_b
    assert empty_branch.root_node.children == Map()

def test_pattern_tree_branch_update_add_second(branch_with_a_b):
    """...."""
    updated_branch = branch_with_a_b.update(
        ['a', 'b'],
        lambda s: frozenset({*(s or []), 'myotheritem'})
    )

    leaf_node = updated_branch.root_node.children['a'].children['b']
    assert leaf_node.literal_match == frozenset({'myitem', 'myotheritem'})

def test_pattern_tree_branch_update_add_different_path(branch_with_a_b):
    """...."""
    updated_branch = branch_with_a_b.update(
        ['a', 'not_b'],
        lambda s: frozenset({*(s or []), 'myotheritem'})
    )

    for segment, item in [('b', 'myitem'), ('not_b', 'myotheritem')]:
        leaf_node = updated_branch.root_node.children['a'].children[segment]
        assert leaf_node.literal_match == frozenset({item})

# def test_pattern_tree_branch_update_is_value_copied(branch_with_a_b):
#     """...."""
#     updated_branch = branch_with_a_b.update(['a', 'b'], lambda s: s)

#     leaf_node_orig = updated_branch.root_node.children['a'].children['b']
#     leaf_node_new  = branch_with_a_b.root_node.children['a'].children['b']

#     assert leaf_node_orig.literal_match == leaf_node_new.literal_match
#     assert leaf_node_orig.literal_match is not leaf_node_new.literal_match

def test_pattern_tree_branch_remove(branch_with_a_b, empty_branch):
    """...."""
    updated_branch = branch_with_a_b.update(['a', 'b'], lambda s: None)

    assert updated_branch == empty_branch

def test_pattern_tree_branch_search_empty(empty_branch):
    """...."""
    assert [*empty_branch.search(['a', 'b'])] == []

@pytest.fixture
def branch_with_wildcards():
    """...."""
    return pattern_tree.PatternTreeBranch(
        root_node = pattern_tree.PatternTreeNode(
            children = Map(
                a = pattern_tree.PatternTreeNode(
                    children = Map(
                        b = pattern_tree.PatternTreeNode(
                            children = Map({
                                'c': pattern_tree.PatternTreeNode(
                                    literal_match = 'dummy/c'
                                ),
                                '*': pattern_tree.PatternTreeNode(
                                    literal_match = 'dummy/*'
                                ),
                                '**': pattern_tree.PatternTreeNode(
                                    literal_match = 'dummy/**'
                                ),
                                '***': pattern_tree.PatternTreeNode(
                                    literal_match = 'dummy/***'
                                )
                            })
                        )
                    )
                )
            )
        )
    )

@pytest.mark.parametrize('_in, out', [
    (['a'],                       []),
    (['a', 'x', 'y', 'z'],        []),
    (['a', 'b'],                  ['dummy/***']),
    (['a', 'b', 'c'],             ['dummy/c', 'dummy/*', 'dummy/***']),
    (['a', 'b', 'u'],             ['dummy/*', 'dummy/***']),
    (['a', 'b', '*'],             ['dummy/*', 'dummy/***']),
    (['a', 'b', '**'],            ['dummy/**', 'dummy/*', 'dummy/***']),
    (['a', 'b', '***'],           ['dummy/***', 'dummy/*']),
    (['a', 'b', 'u', 'l'],        ['dummy/**', 'dummy/***']),
    (['a', 'b', 'u', 'l', 'y'],   ['dummy/**', 'dummy/***'])
])
def test_pattern_tree_branch_search_wildcards(_in, out, branch_with_wildcards):
    """...."""
    assert [*branch_with_wildcards.search(_in)] == out

def test_filter_by_trailing_slash(sample_url_parsed):
    """...."""
    sample_url_parsed2 = dc.replace(sample_url_parsed, has_trailing_slash=True)
    item1 = pattern_tree.StoredTreeItem('dummy_it1', sample_url_parsed)
    item2 = pattern_tree.StoredTreeItem('dummy_it2', sample_url_parsed2)

    assert pattern_tree.filter_by_trailing_slash((item1, item2), False) == \
        frozenset({item1})

    assert pattern_tree.filter_by_trailing_slash((item1, item2), True) == \
        frozenset({item2})

@pytest.mark.parametrize('register_mode',  [True, False])
@pytest.mark.parametrize('empty_at_start', [True, False])
@pytest.mark.parametrize('empty_at_end',   [True, False])
def test_pattern_tree_privatemethod_register(
        register_mode,
        empty_at_start,
        empty_at_end,
        monkeypatch,
        sample_url_parsed
):
    """...."""
    dummy_it       = pattern_tree.StoredTreeItem('dummy_it', sample_url_parsed)
    other_dummy_it = pattern_tree.StoredTreeItem(
        item    = 'other_dummy_it',
        pattern = sample_url_parsed
    )

    class MockedTreeBranch:
        """...."""
        def is_empty(self):
            """...."""
            return empty_at_end

        def update(self, segments, item_updater):
            """...."""
            if segments == ('com', 'example'):
                return self._update_as_domain_branch(item_updater)
            else:
                assert segments == ('aa', 'bb')
                return self._update_as_path_branch(item_updater)

        def _update_as_domain_branch(self, item_updater):
            """...."""
            for updater_input in (None, MockedTreeBranch()):
                updated = item_updater(updater_input)
                if empty_at_end:
                    assert updated is None
                else:
                    assert type(updated) is MockedTreeBranch

            return MockedTreeBranch()

        def _update_as_path_branch(self, item_updater):
            """...."""
            set_with_1_item  = frozenset()
            set_with_2_items = frozenset({dummy_it, other_dummy_it})
            for updater_input in (None, set_with_1_item, set_with_2_items):
                updated = item_updater(updater_input)
                if register_mode:
                    assert dummy_it in updated
                elif updater_input is set_with_2_items:
                    assert dummy_it not in updated
                else:
                    assert updated is None

            return MockedTreeBranch()

    monkeypatch.setattr(pattern_tree, 'PatternTreeBranch', MockedTreeBranch)

    initial_root = Map() if empty_at_start else \
        Map({('http', 80): MockedTreeBranch()})

    tree = pattern_tree.PatternTree(_by_scheme_and_port=initial_root)

    new_tree = tree._register(
        sample_url_parsed,
        'dummy_it',
        register=register_mode
    )

    assert new_tree is not tree

    if empty_at_end:
        assert new_tree._by_scheme_and_port == Map()
    else:
        assert len(new_tree._by_scheme_and_port) == 1
        assert type(new_tree._by_scheme_and_port[('http', 80)]) is \
            MockedTreeBranch

# @pytest.mark.parametrize('register_mode', [True, False])
# def test_pattern_tree_privatemethod_register(
#         register_mode,
#         monkeypatch,
#         sample_url_parsed
# ):
#     """...."""
#     registered_count = 0

#     def mocked_parse_pattern(url_pattern):
#         """...."""
#         assert url_pattern == 'dummy_pattern'

#         for _ in range(2):
#             yield sample_url_parsed

#     monkeypatch.setattr(pattern_tree, 'parse_pattern', mocked_parse_pattern)

#     def mocked_reconstruct_url(self):
#         """...."""
#         return 'dummy_reconstructed_pattern'

#     monkeypatch.setattr(pattern_tree.ParsedUrl, 'reconstruct_url',
#                         mocked_reconstruct_url)

#     def mocked_register_with_parsed_pattern(
#             self,
#             parsed_pat,
#             wrapped_item,
#             register=True
#     ):
#         """...."""
#         nonlocal registered_count

#         assert parsed_pat is sample_url_parsed
#         assert wrapped_item.pattern == 'dummy_reconstructed_pattern'
#         assert register == register_mode

#         registered_count += 1

#         return 'dummy_new_tree' if registered_count == 2 else dc.replace(self)

#     monkeypatch.setattr(
#         pattern_tree.PatternTree,
#         '_register_with_parsed_pattern',
#         mocked_register_with_parsed_pattern
#     )

#     pattern_tree = pattern_tree.PatternTree()

#     new_tree = pattern_tree._register(
#         'dummy_pattern',
#         'dummy_item',
#         register_mode
#     )

#     assert new_tree == 'dummy_new_tree'

@pytest.mark.parametrize('method_name, register_mode', [
    ('register',   True),
    ('deregister', False)
])
def test_pattern_tree_register(method_name, register_mode, monkeypatch):
    """...."""
    def mocked_privatemethod_register(self, parsed_pat, item, register=True):
        """...."""
        assert (parsed_pat, item, register) == \
            ('dummy_pattern', 'dummy_url', register_mode)

        return 'dummy_new_tree'

    monkeypatch.setattr(
        pattern_tree.PatternTree,
        '_register',
        mocked_privatemethod_register
    )

    method = getattr(pattern_tree.PatternTree(), method_name)
    assert method('dummy_pattern', 'dummy_url') == 'dummy_new_tree'

@pytest.fixture
def mock_parse_url(monkeypatch, sample_url_parsed):
    """...."""
    def mocked_parse_url(url):
        """...."""
        assert url == 'dummy_url'
        return dc.replace(
            sample_url_parsed,
            **getattr(mocked_parse_url, 'url_mod', {})
        )

    monkeypatch.setattr(pattern_tree, 'parse_url', mocked_parse_url)

    return mocked_parse_url

@pytest.mark.usefixtures('mock_parse_url')
def test_pattern_tree_search_empty(sample_url_parsed):
    """...."""
    for url in ('dummy_url', sample_url_parsed):
        assert [*pattern_tree.PatternTree().search(url)] == []

@pytest.mark.parametrize('url_mod, out', [
    ({},
     ['dummy_set_A', 'dummy_set_B', 'dummy_set_C']),

    ({'has_trailing_slash': True},
     ['dummy_set_A_with_slash', 'dummy_set_A',
      'dummy_set_B_with_slash', 'dummy_set_B',
      'dummy_set_C_with_slash', 'dummy_set_C'])
])
def test_pattern_tree_search(
        url_mod,
        out,
        monkeypatch,
        sample_url_parsed,
        mock_parse_url,
):
    """...."""
    mock_parse_url.url_mod = url_mod

    dummy_tree_contents = [
        ['dummy_set_A', 'dummy_set_B'],
        [],
        ['dummy_empty_set'] * 3,
        ['dummy_set_C']
    ]

    def mocked_filter_by_trailing_slash(items, with_slash):
        """...."""
        if items == 'dummy_empty_set':
            return frozenset()

        return items + ('_with_slash' if with_slash else '')

    monkeypatch.setattr(pattern_tree, 'filter_by_trailing_slash',
                        mocked_filter_by_trailing_slash)

    class MockedDomainBranch:
        """...."""
        def search(self, labels):
            """...."""
            assert labels == sample_url_parsed.domain_labels

            for item_sets in dummy_tree_contents:
                class MockedPathBranch:
                    """...."""
                    def search(self, segments, item_sets=item_sets):
                        """...."""
                        assert segments == sample_url_parsed.path_segments

                        for dummy_items_set in item_sets:
                            yield dummy_items_set

                yield MockedPathBranch()

    tree = pattern_tree.PatternTree(
        _by_scheme_and_port = {('http', 80): MockedDomainBranch()}
    )

    for url in ('dummy_url', mock_parse_url('dummy_url')):
        assert [*tree.search(url)] == out