aboutsummaryrefslogtreecommitdiff
path: root/test/haketilo_test/unit/test_install.py
blob: 29910cf14ea7c8516770cc1d368b046eb6681d46 (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
# SPDX-License-Identifier: CC0-1.0

"""
Haketilo unit tests - item installation dialog
"""

# This file is part of Haketilo
#
# Copyright (C) 2022 Wojtek Kosior <koszko@koszko.org>
#
# 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
import json
from selenium.webdriver.support.ui import WebDriverWait

from ..extension_crafting import ExtraHTML
from ..script_loader import load_script
from .utils import *

def setup_view(driver, execute_in_page):
    execute_in_page(mock_cacher_code)

    execute_in_page(load_script('html/install.js'))
    container_ids, containers_objects = execute_in_page(
        '''
        const cb_calls = [];
        const install_view = new InstallView(0,
                                             () => cb_calls.push("show"),
                                             () => cb_calls.push("hide"));
        document.body.append(install_view.main_div);
        const ets = () => install_view.item_entries;
        const shw = slice => [cb_calls.slice(slice || 0), install_view.shown];
        returnval([container_ids, container_ids.map(cid => install_view[cid])]);
        ''')

    containers = dict(zip(container_ids, containers_objects))

    def assert_container_displayed(container_id):
        for cid, cobj in zip(container_ids, containers_objects):
            assert (cid == container_id) == cobj.is_displayed()

    return containers, assert_container_displayed

install_ext_data = {
    'background_script': broker_js,
    'extra_html': ExtraHTML('html/install.html', {}),
    'navigate_to': 'html/install.html'
}

@pytest.mark.ext_data(install_ext_data)
@pytest.mark.usefixtures('webextension')
@pytest.mark.parametrize('complex_variant', [False, True])
def test_install_normal_usage(driver, execute_in_page, complex_variant):
    """
    Test of the normal package installation procedure with one mapping and,
    depending on parameter, one or many resources.
    """
    containers, assert_container_displayed = setup_view(driver, execute_in_page)

    assert execute_in_page('returnval(shw());') == [[], False]

    if complex_variant:
        # The resource/mapping others depend on.
        root_id = 'abcd-defg-ghij'
        root_resource_id = f'resource-{root_id}'
        root_mapping_id = f'mapping-{root_id}'
        # Those ids are used to check the alphabetical ordering.
        resource_ids = [f'resource-{letters}' for letters in (
            'a', 'abcd', root_id, 'b', 'c',
            'd', 'defg', 'e', 'f',
            'g', 'ghij', 'h', 'i', 'j'
        )]
        files_count = 9
    else:
        root_resource_id = f'resource-a'
        root_mapping_id = f'mapping-a'
        resource_ids = [root_resource_id]
        files_count = 0

    # Preview the installation of a resource, show resource's details, close
    # the details and cancel installation.
    execute_in_page('returnval(install_view.show(...arguments));',
                    'https://hydril.la/', 'resource', root_resource_id)

    assert execute_in_page('returnval(shw());') == [['show'], True]
    assert f'{root_resource_id}-2021.11.11-1'\
        in containers['install_preview'].text
    assert_container_displayed('install_preview')

    entries = execute_in_page('returnval(ets().map(e => e.main_li.innerText));')
    assert len(entries) == len(resource_ids)
    # Verify alphabetical ordering.
    assert all([id in text for id, text in zip(resource_ids, entries)])

    assert not execute_in_page('returnval(ets()[0].old_ver);').is_displayed()
    execute_in_page('returnval(ets()[0].details_but);').click()
    assert 'resource-a' in containers['resource_preview_container'].text
    assert_container_displayed('resource_preview_container')

    execute_in_page('returnval(install_view.resource_back_but);').click()
    assert_container_displayed('install_preview')

    assert execute_in_page('returnval(shw());') == [['show'], True]
    execute_in_page('returnval(install_view.cancel_but);').click()
    assert execute_in_page('returnval(shw());') == [['show', 'hide'], False]

    # Preview the installation of a mapping and a resource, show mapping's
    # details, close the details and commit the installation.
    execute_in_page('returnval(install_view.show(...arguments));',
                    'https://hydril.la/', 'mapping',
                    root_mapping_id, [2022, 5, 10])

    assert execute_in_page('returnval(shw(2));') == [['show'], True]
    assert_container_displayed('install_preview')

    entries = execute_in_page('returnval(ets().map(e => e.main_li.innerText));')
    assert len(entries) == len(resource_ids) + 1
    assert f'{root_mapping_id}-2022.5.10' in entries[0]
    # Verify alphabetical ordering.
    assert all([id in text for id, text in zip(resource_ids, entries[1:])])

    assert not execute_in_page('returnval(ets()[0].old_ver);').is_displayed()
    execute_in_page('returnval(ets()[0].details_but);').click()
    assert root_mapping_id in containers['mapping_preview_container'].text
    assert_container_displayed('mapping_preview_container')

    execute_in_page('returnval(install_view.mapping_back_but);').click()
    assert_container_displayed('install_preview')

    execute_in_page('returnval(install_view.install_but);').click()
    installed = lambda d: 'ly installed!' in containers['dialog_container'].text
    WebDriverWait(driver, 10).until(installed)

    assert execute_in_page('returnval(shw(2));') == [['show'], True]
    execute_in_page('returnval(install_view.dialog_ctx.ok_but);').click()
    assert execute_in_page('returnval(shw(2));') == [['show', 'hide'], False]

    # Verify the install
    db_contents = get_db_contents(execute_in_page)
    for item_type, ids in \
        [('mapping', {root_mapping_id}), ('resource', set(resource_ids))]:
        assert set([it['identifier'] for it in db_contents[item_type]]) == ids

    assert all([len(db_contents[store]) == files_count
                for store in ('file', 'file_uses')])

    # Update the installed mapping to a newer version.
    execute_in_page('returnval(install_view.show(...arguments));',
                    'https://hydril.la/', 'mapping', root_mapping_id)
    assert execute_in_page('returnval(shw(4));') == [['show'], True]
    # resources are already in the newest versions, hence they should not appear
    # in the install preview list.
    assert execute_in_page('returnval(ets().length);') == 1
    # Mapping's version update information should be displayed.
    assert execute_in_page('returnval(ets()[0].old_ver);').is_displayed()
    execute_in_page('returnval(install_view.install_but);').click()

    WebDriverWait(driver, 10).until(installed)

    assert execute_in_page('returnval(shw(4));') == [['show'], True]
    execute_in_page('returnval(install_view.dialog_ctx.ok_but);').click()
    assert execute_in_page('returnval(shw(4));') == [['show', 'hide'], False]

    # Verify the newer version install.
    old_db_contents, db_contents = db_contents, get_db_contents(execute_in_page)
    old_db_contents['mapping'][0]['version'][-1] += 1
    assert db_contents['mapping'] == old_db_contents['mapping']

    # All items are up to date - verify dialog is instead shown in this case.
    execute_in_page('install_view.show(...arguments);',
                    'https://hydril.la/', 'mapping', root_mapping_id)

    fetched = lambda d: 'Fetching ' not in containers['dialog_container'].text
    WebDriverWait(driver, 10).until(fetched)

    assert 'Nothing to do - packages already installed.' \
        in containers['dialog_container'].text
    assert_container_displayed('dialog_container')

    assert execute_in_page('returnval(shw(6));') == [['show'], True]
    execute_in_page('returnval(install_view.dialog_ctx.ok_but);').click()
    assert execute_in_page('returnval(shw(6));') == [['show', 'hide'], False]

@pytest.mark.ext_data(install_ext_data)
@pytest.mark.usefixtures('webextension')
@pytest.mark.parametrize('message', [
    'fetching_data',
    'failure_to_communicate_sendmessage',
    'HTTP_code_item',
    'invalid_JSON',
    'newer_API_version',
    'invalid_response_format',
    'indexeddb_error_item',
    'installing',
    'indexeddb_error_file_uses',
    'failure_to_communicate_fetch',
    'HTTP_code_file',
    'sha256_mismatch',
    'indexeddb_error_write'
])
def test_install_dialogs(driver, execute_in_page, message):
    """
    Test of various error and loading messages used in install view.
    """
    containers, assert_container_displayed = setup_view(driver, execute_in_page)

    def dlg_buts():
        return execute_in_page(
            '''{
            const dlg = install_view.dialog_ctx;
            const ids = ['ask_buts', 'conf_buts'];
            returnval(ids.filter(id => !dlg[id].classList.contains("hide")));
            }''')

    def dialog_txt():
        return execute_in_page(
            'returnval(install_view.dialog_ctx.msg.textContent);'
        )

    def assert_dlg(awaited_buttons, expected_msg, hides_install_view=True,
                   button_to_click='ok_but'):
        WebDriverWait(driver, 10).until(lambda d: dlg_buts() == awaited_buttons)

        assert expected_msg == dialog_txt()

        execute_in_page(
            f'returnval(install_view.dialog_ctx.{button_to_click});'
        ).click()

        if hides_install_view:
            assert execute_in_page('returnval(shw());') == \
                [['show', 'hide'], False]

    if message == 'fetching_data':
        execute_in_page(
            '''
            window.mock_cacher_fetch = () => new Promise(cb => {});
            install_view.show(...arguments);
            ''',
            'https://hydril.la/', 'mapping', 'mapping-a')

        assert dlg_buts() == []
        assert dialog_txt() == 'Fetching data from repository...'
    elif message == 'failure_to_communicate_sendmessage':
        execute_in_page(
            '''
            window.mock_cacher_fetch =
                () => {throw new Error("Something happened :o")};
            install_view.show(...arguments);
            ''',
            'https://hydril.la/', 'mapping', 'mapping-a')

        assert_dlg(['conf_buts'], 'Failure to communicate with repository :(')
    elif message == 'HTTP_code_item':
        execute_in_page(
            '''
            const response = new Response("", {status: 404});
            window.mock_cacher_fetch = () => Promise.resolve(response);
            install_view.show(...arguments);
            ''',
            'https://hydril.la/', 'mapping', 'mapping-a')

        assert_dlg(['conf_buts'], 'Repository sent HTTP code 404 :(')
    elif message == 'invalid_JSON':
        execute_in_page(
            '''
            const response = new Response("sth", {status: 200});
            window.mock_cacher_fetch = () => Promise.resolve(response);
            install_view.show(...arguments);
            ''',
            'https://hydril.la/', 'mapping', 'mapping-a')

        assert_dlg(['conf_buts'], "Repository's response is not valid JSON :(")
    elif message == 'newer_API_version':
        execute_in_page(
            '''
            const newer_schema_url =
                "https://hydrilla.koszko.org/schemas/api_mapping_description-255.1.schema.json";
            const mocked_json_data = JSON.stringify({$schema: newer_schema_url});
            const response = new Response(mocked_json_data, {status: 200});
            window.mock_cacher_fetch = () => Promise.resolve(response);
            install_view.show(...arguments);
            ''',
            'https://hydril.la/', 'mapping', 'mapping-a', [2022, 5, 10])

        assert_dlg(['conf_buts'],
                   'Mapping mapping-a-2022.5.10 was served using unsupported Hydrilla API version. You might need to update Haketilo.')
    elif message == 'invalid_response_format':
        execute_in_page(
            '''
            window.mock_cacher_fetch = async function(...args) {
                const response = await fetch(...args);
                const json = await response.json();

                /* identifier is no longer a string as it should be. */
                json.identifier = 1234567;

                return new Response(JSON.stringify(json), {
                    status:     response.status,
                    statusText: response.statusText,
                    headers:    [...response.headers.entries()]
                });
            }
            install_view.show(...arguments);
            ''',
            'https://hydril.la/', 'resource', 'resource-a')

        assert_dlg(['conf_buts'],
                   'Resource resource-a was served using a nonconforming response format.')
    elif message == 'indexeddb_error_item':
        execute_in_page(
            '''
            haketilodb.idb_get = () => {throw "some error";};
            install_view.show(...arguments);
            ''',
            'https://hydril.la/', 'mapping', 'mapping-a')

        assert_dlg(['conf_buts'],
                   "Error accessing Haketilo's internal database :(")
    elif message == 'installing':
        execute_in_page(
            '''
            haketilodb.save_items = () => new Promise(() => {});
            returnval(install_view.show(...arguments));
            ''',
            'https://hydril.la/', 'mapping', 'mapping-b')

        execute_in_page('returnval(install_view.install_but);').click()

        assert dlg_buts() == []
        assert dialog_txt() == 'Installing...'
    elif message == 'indexeddb_error_file_uses':
        execute_in_page(
            '''
            const old_idb_get = haketilodb.idb_get;
            haketilodb.idb_get = function(transaction, store_name, identifier) {
                if (store_name === "file_uses")
                    throw "some error";
                return old_idb_get(...arguments);
            }
            returnval(install_view.show(...arguments));
            ''',
            'https://hydril.la/', 'mapping', 'mapping-b')

        execute_in_page('returnval(install_view.install_but);').click()

        assert_dlg(['conf_buts'],
                   "Error accessing Haketilo's internal database :(")
    elif message == 'failure_to_communicate_fetch':
        execute_in_page(
            '''
            fetch = () => {throw new Error("some error");};
            returnval(install_view.show(...arguments));
            ''',
            'https://hydril.la/', 'mapping', 'mapping-b')

        execute_in_page('returnval(install_view.install_but);').click()

        assert_dlg(['conf_buts'],
                   'Failure to communicate with repository :(')
    elif message == 'HTTP_code_file':
        execute_in_page(
            '''
            fetch = () => Promise.resolve({ok: false, status: 400});
            returnval(install_view.show(...arguments));
            ''',
            'https://hydril.la/', 'mapping', 'mapping-b')

        execute_in_page('returnval(install_view.install_but);').click()

        assert_dlg(['conf_buts'], 'Repository sent HTTP code 400 :(')
    elif message == 'sha256_mismatch':
        execute_in_page(
            '''
            let old_fetch = fetch, url_used;
            fetch = async function(url) {
                url_used = url;
                const response = await old_fetch(...arguments);
                const text = () => response.text().then(t => t + ":d");
                return {ok: response.ok, status: response.status, text};
            }
            returnval(install_view.show(...arguments));
            ''',
            'https://hydril.la/', 'mapping', 'mapping-b')

        execute_in_page('returnval(install_view.install_but);').click()

        get_url_used = lambda d: execute_in_page('returnval(url_used);')
        url_used = WebDriverWait(driver, 10).until(get_url_used)
        print ((url_used,))

        assert dlg_buts() == ['conf_buts']
        assert dialog_txt() == \
            f'{url_used} served a file with different SHA256 cryptographic sum :('
    elif message == 'indexeddb_error_write':
        execute_in_page(
            '''
            haketilodb.save_items = () => {throw "some error";};
            returnval(install_view.show(...arguments));
            ''',
            'https://hydril.la/', 'mapping', 'mapping-b')

        execute_in_page('returnval(install_view.install_but);').click()

        assert_dlg(['conf_buts'],
                   "Error writing to Haketilo's internal database :(")
    else:
        raise Exception('made a typo in test function params?')