aboutsummaryrefslogtreecommitdiff
path: root/test/unit/test_patterns_query_tree.py
blob: 9fbc0c38f8259704e386e915613d7065207bba61 (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
# SPDX-License-Identifier: CC0-1.0

"""
Haketilo unit tests - URL patterns
"""

# This file is part of Haketilo
#
# Copyright (C) 2021, Wojtek Kosior
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the CC0 1.0 Universal License as published by
# the Creative Commons Corporation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# CC0 1.0 Universal License for more details.

import pytest

from ..script_loader import load_script

@pytest.fixture(scope="session")
def patterns_tree_code():
    yield load_script('common/patterns_query_tree.js', ['common'])

def test_modify_branch(execute_in_page, patterns_tree_code):
    """
    patterns_query_tree.js contains Patterns Tree data structure that allows
    arrays of string labels to be mapped to items.
    Verify operations modifying a single branch of such tree work properly.
    """
    execute_in_page(patterns_tree_code, page='https://gotmyowndoma.in')
    execute_in_page(
        '''
        let items_added;
        let items_removed;

        function _item_adder(item, array)
        {
            items_added++;
            return [...(array || []), item];
        }

        function item_adder(item)
        {
            items_added = 0;
            return array => _item_adder(item, array);
        }

        function _item_remover(array)
        {
            if (array !== null) {
                items_removed++;
                array.pop();
            }
            return (array && array.length > 0) ? array : null;
        }

        function item_remover()
        {
            items_removed = 0;
            return _item_remover;
        }''')

    # Let's construct some tree branch while checking that each addition gives
    # the right result.
    branch = execute_in_page(
        '''{
        const branch = make_tree_node();
        modify_sequence(branch, ['com', 'example'], item_adder('some_item'));
        returnval(branch);
        }''')
    assert branch == {
        'literal_match': None,
        'wildcard_matches': [None, None, None],
        'children': {
            'com': {
                'literal_match': None,
                'wildcard_matches': [None, None, None],
                'children': {
                    'example': {
                        'literal_match': ['some_item'],
                        'wildcard_matches': [None, None, None],
                        'children': {
                        }
                    }
                }
            }
        }
    }

    branch, items_added = execute_in_page(
        '''{
        const branch = arguments[0];
        modify_sequence(branch, ['com', 'example'], item_adder('other_item'));
        returnval([branch, items_added]);
        }''', branch)
    assert items_added == 1
    assert branch['children']['com']['children']['example']['literal_match'] \
            == ['some_item', 'other_item']

    for i in range(3):
        for expected_array in [['third_item'], ['third_item', '4th_item']]:
            wildcard = '*' * (i + 1)
            branch, items_added = execute_in_page(
                '''{
                const branch = arguments[0];
                modify_sequence(branch, ['com', 'sample', arguments[1]],
                                item_adder(arguments[2]));
                returnval([branch, items_added]);
                }''',
                branch, wildcard, expected_array[-1])
            assert items_added == 2
            sample = branch['children']['com']['children']['sample']
            assert sample['wildcard_matches'][i] == expected_array
            assert sample['children'][wildcard]['literal_match'] \
                == expected_array

    branch, items_added = execute_in_page(
        '''{
        const branch = arguments[0];
        modify_sequence(branch, ['org', 'koszko', '***', '123'],
                        item_adder('5th_item'));
        returnval([branch, items_added]);
        }''',
        branch)
    assert items_added == 1
    assert branch['children']['org']['children']['koszko']['children']['***']\
        ['children']['123']['literal_match'] == ['5th_item']

    # Let's verify that removing a nonexistent element doesn't modify the tree.
    branch2, items_removed = execute_in_page(
        '''{
        const branch = arguments[0];
        modify_sequence(branch, ['com', 'not', 'registered', '*'],
                        item_remover());
        returnval([branch, items_removed]);
        }''',
        branch)
    assert branch == branch2
    assert items_removed == 0

    # Let's remove all elements in the tree branch while checking that each
    # removal gives the right result.
    branch, items_removed = execute_in_page(
        '''{
        const branch = arguments[0];
        modify_sequence(branch, ['org', 'koszko', '***', '123'],
                        item_remover());
        returnval([branch, items_removed]);
        }''',
        branch)
    assert items_removed == 1
    assert 'org' not in branch['children']

    for i in range(3):
        for expected_array in [['third_item'], None]:
            wildcard = '*' * (i + 1)
            branch, items_removed = execute_in_page(
                '''{
                const branch = arguments[0];
                modify_sequence(branch, ['com', 'sample', arguments[1]],
                                item_remover());
                returnval([branch, items_removed]);
                }''',
                branch, wildcard)
            assert items_removed == 2
            if i == 2 and expected_array == []:
                break
            sample = branch['children']['com']['children'].get('sample', {})
            assert sample.get('wildcard_matches', [None, None, None])[i] \
                == expected_array
            assert sample.get('children', {}).get(wildcard, {})\
                .get('literal_match') == expected_array

    for i in range(2):
        branch, items_removed = execute_in_page(
            '''{
            const branch = arguments[0];
            modify_sequence(branch, ['com', 'example'], item_remover());
            returnval([branch, items_removed]);
            }''',
            branch)
        assert items_removed == 1
        if i == 0:
            assert branch['children']['com']['children']['example']\
                ['literal_match'] == ['some_item']
        else:
            assert branch == {
                'literal_match': None,
                'wildcard_matches': [None, None, None],
                'children': {
                }
            }

def test_search_branch(execute_in_page, patterns_tree_code):
    """
    patterns_query_tree.js contains Patterns Tree data structure that allows
    arrays of string labels to be mapped to items.
    Verify searching a single branch of such tree work properly.
    """
    execute_in_page(patterns_tree_code, page='https://gotmyowndoma.in')
    execute_in_page(
        '''
        const item_adder = item => (array => [...(array || []), item]);
        ''')

    # Let's construct some tree branch to test on.
    execute_in_page(
        '''
        var branch = make_tree_node();

        for (const [item, sequence] of [
            ['(root)', []],
            ['***',    ['***']],
            ['**',     ['**']],
            ['*',      ['*']],

            ['a',      ['a']],
            ['A',      ['a']],
            ['b',      ['b']],

            ['a/***',  ['a', '***']],
            ['A/***',  ['a', '***']],
            ['a/**',   ['a', '**']],
            ['A/**',   ['a', '**']],
            ['a/*',    ['a', '*']],
            ['A/*',    ['a', '*']],
            ['a/sth',  ['a', 'sth']],
            ['A/sth',  ['a', 'sth']],

            ['b/***',  ['b', '***']],
            ['b/**',   ['b', '**']],
            ['b/*',    ['b', '*']],
            ['b/sth',  ['b', 'sth']],
        ])
            modify_sequence(branch, sequence, item_adder(item));
        ''')

    # Let's make the actual searches on our testing branch.
    for sequence, expected in [
            ([],      [{'(root)'},                            {'***'}]),
            (['a'],   [{'a', 'A'}, {'a/***', 'A/***'}, {'*'}, {'***'}]),
            (['b'],   [{'b'},      {'b/***'},          {'*'}, {'***'}]),
            (['c'],   [                                {'*'}, {'***'}]),
            (['***'], [{'***'},                        {'*'}         ]),
            (['**'],  [{'**'},                         {'*'}, {'***'}]),
            (['**'],  [{'**'},                         {'*'}, {'***'}]),
            (['*'],   [{'*'},                                 {'***'}]),

            (['a', 'sth'], [{'a/sth', 'A/sth'}, {'a/*', 'A/*'}, {'a/***', 'A/***'}, {'**'}, {'***'}]),
            (['b', 'sth'], [{'b/sth'},          {'b/*'},        {'b/***'},          {'**'}, {'***'}]),
            (['a', 'hts'], [                    {'a/*', 'A/*'}, {'a/***', 'A/***'}, {'**'}, {'***'}]),
            (['b', 'hts'], [                    {'b/*'},        {'b/***'},          {'**'}, {'***'}]),
            (['a', '***'], [{'a/***', 'A/***'}, {'a/*', 'A/*'},                     {'**'}, {'***'}]),
            (['b', '***'], [{'b/***'},          {'b/*'},                            {'**'}, {'***'}]),
            (['a', '**'],  [{'a/**', 'A/**'},   {'a/*', 'A/*'}, {'a/***', 'A/***'}, {'**'}, {'***'}]),
            (['b', '**'],  [{'b/**'},           {'b/*'},        {'b/***'},          {'**'}, {'***'}]),
            (['a', '*'],   [{'a/*', 'A/*'},                     {'a/***', 'A/***'}, {'**'}, {'***'}]),
            (['b', '*'],   [{'b/*'},                            {'b/***'},          {'**'}, {'***'}]),

            (['a', 'c', 'd'], [{'a/**', 'A/**'}, {'a/***', 'A/***'}, {'**'}, {'***'}]),
            (['b', 'c', 'd'], [{'b/**'},         {'b/***'},          {'**'}, {'***'}])
    ]:
        result = execute_in_page(
            '''
            returnval([...search_sequence(branch, arguments[0])]);
            ''',
            sequence)

        try:
            assert len(result) == len(expected)

            for expected_set, result_array in zip(expected, result):
                assert len(expected_set) == len(result_array)
                assert expected_set      == set(result_array)
        except Exception as e:
            import sys
            print('sequence:', sequence, '\nexpected:', expected,
                  '\nresult:', result, file=sys.stderr)
            raise e from None