diff options
Diffstat (limited to 'test')
-rw-r--r-- | test/unit/test_CORS_bypass_server.py | 2 | ||||
-rw-r--r-- | test/unit/test_indexeddb.py | 38 | ||||
-rw-r--r-- | test/unit/test_install.py | 429 | ||||
-rw-r--r-- | test/unit/test_patterns_query_manager.py | 4 | ||||
-rw-r--r-- | test/unit/test_payload_create.py | 12 | ||||
-rw-r--r-- | test/unit/test_repo_query_cacher.py | 33 | ||||
-rw-r--r-- | test/unit/utils.py | 42 | ||||
-rw-r--r-- | test/world_wide_library.py | 91 |
8 files changed, 593 insertions, 58 deletions
diff --git a/test/unit/test_CORS_bypass_server.py b/test/unit/test_CORS_bypass_server.py index 8b845b9..45e4ebb 100644 --- a/test/unit/test_CORS_bypass_server.py +++ b/test/unit/test_CORS_bypass_server.py @@ -97,7 +97,7 @@ def test_CORS_bypass_server(driver, execute_in_page): assert set(results['invalid'].keys()) == {'error'} assert set(results['nonexistent'].keys()) == \ - {'ok', 'status', 'text', 'error-json'} + {'ok', 'status', 'text', 'error_json'} assert results['nonexistent']['ok'] == False assert results['nonexistent']['status'] == 404 assert results['nonexistent']['text'] == 'Handler for this URL not found.' diff --git a/test/unit/test_indexeddb.py b/test/unit/test_indexeddb.py index 07b620c..aea633b 100644 --- a/test/unit/test_indexeddb.py +++ b/test/unit/test_indexeddb.py @@ -78,7 +78,7 @@ def test_haketilodb_item_modifications(driver, execute_in_page): execute_in_page( '''{ - const promise = start_items_transaction(["resources"], arguments[1]) + const promise = start_items_transaction(["resource"], arguments[1]) .then(ctx => save_item(arguments[0], ctx).then(() => ctx)) .then(finalize_transaction); returnval(promise); @@ -97,8 +97,8 @@ def test_haketilodb_item_modifications(driver, execute_in_page): assert set([uses['hash_key'] for uses in database_contents['file_uses']]) \ == set([file['hash_key'] for file in database_contents['files']]) - assert database_contents['mappings'] == [] - assert database_contents['resources'] == [sample_item] + assert database_contents['mapping'] == [] + assert database_contents['resource'] == [sample_item] # See if trying to add an item without providing all its files ends in an # exception and aborts the transaction as it should. @@ -111,7 +111,7 @@ def test_haketilodb_item_modifications(driver, execute_in_page): async function try_add_item() { const context = - await start_items_transaction(["resources"], args[1]); + await start_items_transaction(["resource"], args[1]); try { await save_item(args[0], context); await finalize_transaction(context); @@ -137,7 +137,7 @@ def test_haketilodb_item_modifications(driver, execute_in_page): sample_item = make_sample_mapping() database_contents = execute_in_page( '''{ - const promise = start_items_transaction(["mappings"], arguments[1]) + const promise = start_items_transaction(["mapping"], arguments[1]) .then(ctx => save_item(arguments[0], ctx).then(() => ctx)) .then(finalize_transaction); returnval(promise); @@ -161,9 +161,9 @@ def test_haketilodb_item_modifications(driver, execute_in_page): assert files == dict([(file['hash_key'], file['contents']) for file in sample_files_list]) - del database_contents['resources'][0]['source_copyright'][0]['extra_prop'] - assert database_contents['resources'] == [make_sample_resource()] - assert database_contents['mappings'] == [sample_item] + del database_contents['resource'][0]['source_copyright'][0]['extra_prop'] + assert database_contents['resource'] == [make_sample_resource()] + assert database_contents['mapping'] == [sample_item] # Try removing the items to get an empty database again. results = [None, None] @@ -172,7 +172,7 @@ def test_haketilodb_item_modifications(driver, execute_in_page): f'''{{ const remover = remove_{item_type}; const promise = - start_items_transaction(["{item_type}s"], {{}}) + start_items_transaction(["{item_type}"], {{}}) .then(ctx => remover('helloapple', ctx).then(() => ctx)) .then(finalize_transaction); returnval(promise); @@ -193,8 +193,8 @@ def test_haketilodb_item_modifications(driver, execute_in_page): assert files == dict([(file['hash_key'], file['contents']) for file in sample_files_list]) - assert results[0]['resources'] == [] - assert results[0]['mappings'] == [sample_item] + assert results[0]['resource'] == [] + assert results[0]['mapping'] == [sample_item] assert results[1] == dict([(key, []) for key in results[0].keys()]) @@ -223,8 +223,8 @@ def test_haketilodb_item_modifications(driver, execute_in_page): execute_in_page('initial_data = arguments[0];', initial_data) database_contents = get_db_contents(execute_in_page) - assert database_contents['resources'] == [sample_resource] - assert database_contents['mappings'] == [sample_mapping] + assert database_contents['resource'] == [sample_resource] + assert database_contents['mapping'] == [sample_mapping] @pytest.mark.get_page('https://gotmyowndoma.in') def test_haketilodb_settings(driver, execute_in_page): @@ -407,8 +407,8 @@ def test_haketilodb_track(driver, execute_in_page, wait_elem_text): }''') assert item_counts == [1 for _ in item_counts] for elem_id, json_value in [ - ('resources_helloapple', sample_resource), - ('mappings_helloapple', sample_mapping), + ('resource_helloapple', sample_resource), + ('mapping_helloapple', sample_mapping), ('settings_option15', {'name': 'option15', 'value': '123'}), ('repos_https://hydril.la', {'url': 'https://hydril.la'}), ('blocking_file:///*', {'pattern': 'file:///*', 'allow': False}) @@ -442,8 +442,8 @@ def test_haketilodb_track(driver, execute_in_page, wait_elem_text): driver.switch_to.window(windows[0]) driver.implicitly_wait(10) for elem_id, json_value in [ - ('resources_helloapple-copy', sample_resource2), - ('mappings_helloapple-copy', sample_mapping2), + ('resource_helloapple-copy', sample_resource2), + ('mapping_helloapple-copy', sample_mapping2), ('settings_option22', {'name': 'option22', 'value': 'abc'}), ('repos_https://hydril2.la', {'url': 'https://hydril2.la'}), ('blocking_ftp://a.bc/', {'pattern': 'ftp://a.bc/', 'allow': True}) @@ -457,7 +457,7 @@ def test_haketilodb_track(driver, execute_in_page, wait_elem_text): '''{ async function change_remove_items() { - const store_names = ["resources", "mappings"]; + const store_names = ["resource", "mapping"]; const ctx = await start_items_transaction(store_names, {}); await remove_resource("helloapple", ctx); await remove_mapping("helloapple-copy", ctx); @@ -470,7 +470,7 @@ def test_haketilodb_track(driver, execute_in_page, wait_elem_text): returnval(change_remove_items()); }''') - removed_ids = ['mappings_helloapple-copy', 'resources_helloapple', + removed_ids = ['mapping_helloapple-copy', 'resource_helloapple', 'repos_https://hydril.la', 'blocking_file:///*'] def condition_items_absent_and_changed(driver): for id in removed_ids: diff --git a/test/unit/test_install.py b/test/unit/test_install.py new file mode 100644 index 0000000..cb8fe36 --- /dev/null +++ b/test/unit/test_install.py @@ -0,0 +1,429 @@ +# 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 content_script(): + script = load_script('content/repo_query_cacher.js') + return f'{script}; {tab_id_asker}; start();' + +def background_script(): + script = load_script('background/broadcast_broker.js', + '#IMPORT background/CORS_bypass_server.js') + return f'{script}; {tab_id_responder}; start(); CORS_bypass_server.start();' + +def setup_view(driver, execute_in_page): + tab_id = run_content_script_in_new_window(driver, 'https://gotmyowndoma.in') + + execute_in_page(load_script('html/install.js')) + container_ids, containers_objects = execute_in_page( + ''' + const cb_calls = []; + const install_view = new InstallView(arguments[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])]); + ''', + tab_id) + + 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 = { + 'content_script': content_script, + 'background_script': background_script, + '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, 10000).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 ('files', '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) + assert execute_in_page('returnval(shw(6));') == [['show'], True] + assert_container_displayed('dialog_container') + assert 'Nothing to do - packages already installed.' \ + in containers['dialog_container'].text + 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_API_version', + 'indexeddb_error_item', + 'installing', + 'indexeddb_error_file_uses', + 'failure_to_communicate_fetch', + 'HTTP_code_file', + 'not_valid_text', + '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( + ''' + browser.tabs.sendMessage = () => 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( + ''' + browser.tabs.sendMessage = () => Promise.resolve({error: "sth"}); + 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 = {ok: false, status: 404}; + browser.tabs.sendMessage = () => 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 = {ok: true, status: 200, error_json: "sth"}; + browser.tabs.sendMessage = () => 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 response = { + ok: true, + status: 200, + json: {api_schema_version: [99, 99]} + }; + browser.tabs.sendMessage = () => Promise.resolve(response); + install_view.show(...arguments); + ''', + 'https://hydril.la/', 'mapping', 'somemapping', [2, 1]) + + assert_dlg(['conf_buts'], + 'Mapping somemapping-2.1 was served using unsupported Hydrilla API version (99.99). You might need to update Haketilo.') + elif message == 'invalid_API_version': + execute_in_page( + ''' + const response = { + ok: true, + status: 200, + /* API version here is not an array as it should be. */ + json: {api_schema_version: 123} + }; + browser.tabs.sendMessage = () => Promise.resolve(response); + install_view.show(...arguments); + ''', + 'https://hydril.la/', 'resource', 'someresource') + + assert_dlg(['conf_buts'], + 'Resource someresource was served using unsupported Hydrilla API version. You might need to update Haketilo.') + 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 "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 == 'not_valid_text': + execute_in_page( + ''' + const err = () => {throw "some error";}; + fetch = () => Promise.resolve({ok: true, status: 200, text: err}); + 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's response is not valid text :(") + 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?') diff --git a/test/unit/test_patterns_query_manager.py b/test/unit/test_patterns_query_manager.py index 35047f5..4e6d1bf 100644 --- a/test/unit/test_patterns_query_manager.py +++ b/test/unit/test_patterns_query_manager.py @@ -89,7 +89,7 @@ def test_pqm_tree_building(driver, execute_in_page): const [initial_mappings, initial_blocking] = arguments.slice(0, 2); let mappingchange, blockingchange; - haketilodb.track.mappings = function (cb) { + haketilodb.track.mapping = function (cb) { mappingchange = cb; return [{}, initial_mappings]; @@ -253,7 +253,7 @@ def test_pqm_script_injection(driver, execute_in_page): const identifiers = arguments[0]; async function remove_items() { - const ctx = await start_items_transaction(["mappings"], {}); + const ctx = await start_items_transaction(["mapping"], {}); for (const id of identifiers) await remove_mapping(id, ctx); await finalize_transaction(ctx); diff --git a/test/unit/test_payload_create.py b/test/unit/test_payload_create.py index 6a6cf2c..cee3a9b 100644 --- a/test/unit/test_payload_create.py +++ b/test/unit/test_payload_create.py @@ -118,19 +118,19 @@ def test_payload_create_normal_usage(driver, execute_in_page): def assert_db_contents(): db_contents = get_db_contents(execute_in_page) - assert uuidv4_re.match(db_contents['resources'][0]['uuid']) + assert uuidv4_re.match(db_contents['resource'][0]['uuid']) localid = f'local-{form_data["identifier"]}' long_name = form_data['long_name'] or form_data['identifier'] payloads = dict([(pat, {'identifier': localid}) for pat in form_data['patterns'].split('\n') if pat]) - assert db_contents['resources'] == [{ + assert db_contents['resource'] == [{ 'source_name': localid, 'source_copyright': [], 'type': 'resource', 'identifier': localid, - 'uuid': db_contents['resources'][0]['uuid'], + 'uuid': db_contents['resource'][0]['uuid'], 'version': [1], 'description': form_data['description'], 'dependencies': [], @@ -141,13 +141,13 @@ def test_payload_create_normal_usage(driver, execute_in_page): }] }] - assert uuidv4_re.match(db_contents['mappings'][0]['uuid']) - assert db_contents['mappings'] == [{ + assert uuidv4_re.match(db_contents['mapping'][0]['uuid']) + assert db_contents['mapping'] == [{ 'source_name': localid, 'source_copyright': [], 'type': 'mapping', 'identifier': localid, - 'uuid': db_contents['mappings'][0]['uuid'], + 'uuid': db_contents['mapping'][0]['uuid'], 'version': [1], 'description': form_data['description'], 'long_name': long_name, diff --git a/test/unit/test_repo_query_cacher.py b/test/unit/test_repo_query_cacher.py index d5c7396..ee9f0fd 100644 --- a/test/unit/test_repo_query_cacher.py +++ b/test/unit/test_repo_query_cacher.py @@ -22,40 +22,15 @@ import json from selenium.webdriver.support.ui import WebDriverWait from ..script_loader import load_script - -tab_id_responder = ''' -function tell_tab_id(msg, sender, respond_cb) { - if (msg[0] === "learn_tab_id") - respond_cb(sender.tab.id); -} -browser.runtime.onMessage.addListener(tell_tab_id); -''' +from .utils import * def content_script(): - return load_script('content/repo_query_cacher.js') + '''; - start(); - browser.runtime.sendMessage(["learn_tab_id"]) - .then(tid => window.wrappedJSObject.haketilo_tab = tid); - ''' + script = load_script('content/repo_query_cacher.js') + return f'{script}; {tab_id_asker}; start();' def bypass_js(): return load_script('background/CORS_bypass_server.js') + '; start();' -def run_content_script_in_new_window(driver, url): - initial_handle = driver.current_window_handle - handles = driver.window_handles - driver.execute_script('window.open(arguments[0], "_blank");', url) - WebDriverWait(driver, 10).until(lambda d: d.window_handles is not handles) - new_handle = [h for h in driver.window_handles if h not in handles][0] - - driver.switch_to.window(new_handle) - - get_tab_id = lambda d: d.execute_script('return window.haketilo_tab;') - tab_id = WebDriverWait(driver, 10).until(get_tab_id) - - driver.switch_to.window(initial_handle) - return tab_id - def fetch_through_cache(driver, tab_id, url): return driver.execute_script( ''' @@ -90,7 +65,7 @@ def test_repo_query_cacher_normal_use(driver, execute_in_page): for i in range(2): result = fetch_through_cache(driver, tab_id, 'https://nxdoma.in/') - assert set(result.keys()) == {'ok', 'status', 'error-json'} + assert set(result.keys()) == {'ok', 'status', 'error_json'} assert result['ok'] == False assert result['status'] == 404 diff --git a/test/unit/utils.py b/test/unit/utils.py index 4d8766e..90a2ab7 100644 --- a/test/unit/utils.py +++ b/test/unit/utils.py @@ -26,6 +26,7 @@ Various functions and objects that can be reused between unit tests # proprietary program, I am not going to enforce this in court. from hashlib import sha256 +from selenium.webdriver.support.ui import WebDriverWait from ..script_loader import load_script @@ -200,3 +201,44 @@ def are_scripts_allowed(driver, nonce=None): return document.haketilo_scripts_allowed; ''', nonce) + +""" +tab_id_responder is meant to be appended to background script of a test +extension. +""" +tab_id_responder = ''' +function tell_tab_id(msg, sender, respond_cb) { + if (msg[0] === "learn_tab_id") + respond_cb(sender.tab.id); +} +browser.runtime.onMessage.addListener(tell_tab_id); +''' + +""" +tab_id_asker is meant to be appended to content script of a test extension. +""" +tab_id_asker = ''' +browser.runtime.sendMessage(["learn_tab_id"]) + .then(tid => window.wrappedJSObject.haketilo_tab = tid); +''' + +def run_content_script_in_new_window(driver, url): + """ + Expect an extension to be loaded which had tab_id_responder and tab_id_asker + appended to its background and content scripts, respectively. + Open the provided url in a new tab, find its tab id and return it, with + current window changed back to the initial one. + """ + initial_handle = driver.current_window_handle + handles = driver.window_handles + driver.execute_script('window.open(arguments[0], "_blank");', url) + WebDriverWait(driver, 10).until(lambda d: d.window_handles is not handles) + new_handle = [h for h in driver.window_handles if h not in handles][0] + + driver.switch_to.window(new_handle) + + get_tab_id = lambda d: d.execute_script('return window.haketilo_tab;') + tab_id = WebDriverWait(driver, 10).until(get_tab_id) + + driver.switch_to.window(initial_handle) + return tab_id diff --git a/test/world_wide_library.py b/test/world_wide_library.py index 14e3d2f..31864fb 100644 --- a/test/world_wide_library.py +++ b/test/world_wide_library.py @@ -31,9 +31,14 @@ from hashlib import sha256 from pathlib import Path from shutil import rmtree from threading import Lock +from uuid import uuid4 import json from .misc_constants import here +from .unit.utils import * # sample repo data + +# TODO: instead of having the entire catalog defined here, make it possible to +# add catalog items from within individual test files. served_scripts = {} served_scripts_lock = Lock() @@ -100,6 +105,86 @@ def serve_counter(command, get_params, post_params): json.dumps({'counter': request_counter}) ) +# Mock a Hydrilla repository. + +# Mock files in the repository. +sample_contents = [f'Mi povas manĝi vitron, ĝi ne damaĝas min {i}' + for i in range(9)] +sample_hashes = [sha256(c.encode()).digest().hex() for c in sample_contents] + +file_url = lambda hashed: f'https://hydril.la/file/sha256-{hashed}' +file_handler = lambda contents: lambda c, g, p: (200, {}, contents) + +sample_files_catalog = dict([(file_url(h), file_handler(c)) + for h, c in zip(sample_hashes, sample_contents)]) + +# Mock resources and mappings in the repository. +sample_resource_templates = [] + +for deps in [(0, 1, 2, 3), (3, 4, 5, 6), (6, 7, 8, 9)]: + letters = [chr(ord('a') + i) for i in deps] + sample_resource_templates.append({ + 'id_suffix': ''.join(letters), + 'files_count': deps[0], + 'dependencies': [f'resource_{l}' for l in letters] + }) + +suffixes = [srt['id_suffix'] for srt in sample_resource_templates] +sample_resource_templates.append({ + 'id_suffix': '-'.join(suffixes), + 'files_count': 2, + 'dependencies': [f'resource_{suffix}' for suffix in suffixes] +}) + +for i in range(10): + sample_resource_templates.append({ + 'id_suffix': chr(ord('a') + i), + 'files_count': i, + 'dependencies': [] + }) + +sample_resources_catalog = {} +sample_mappings_catalog = {} + +for srt in sample_resource_templates: + resource = make_sample_resource() + resource['api_schema_version'] = [1] + resource['api_schema_revision'] = 1 + resource['identifier'] = f'resource_{srt["id_suffix"]}' + resource['long_name'] = resource['identifier'].upper() + resource['uuid'] = str(uuid4()) + resource['dependencies'] = srt['dependencies'] + resource['source_copyright'] = [] + resource['scripts'] = [] + for i in range(srt['files_count']): + file_ref = {'file': f'file_{i}', 'sha256': sample_hashes[i]} + resource[('source_copyright', 'scripts')[i & 1]].append(file_ref) + + # Keeping it simple - just make one corresponding mapping for each resource. + payloads = {'https://example.com/*': {'identifier': resource['identifier']}} + + mapping = make_sample_mapping() + mapping['api_schema_version'] = [1] + mapping['api_schema_revision'] = 1 + mapping['identifier'] = f'mapping_{srt["id_suffix"]}' + mapping['long_name'] = mapping['identifier'].upper() + mapping['uuid'] = str(uuid4()) + mapping['source_copyright'] = resource['source_copyright'] + mapping['payloads'] = payloads + + make_handler = lambda txt: lambda c, g, p: (200, {}, txt) + + for item, catalog in [ + (resource, sample_resources_catalog), + (mapping, sample_mappings_catalog) + ]: + fmt = f'https://hydril.la/{item["type"]}/{item["identifier"]}%s.json' + # Make 2 versions of each item so that we can test updates. + for i in range(2): + for fmt_arg in ('', '/' + item_version_string(item)): + catalog[fmt % fmt_arg] = make_handler(json.dumps(item)) + item['version'][-1] += 1 + catalog = { 'http://gotmyowndoma.in': (302, {'location': 'http://gotmyowndoma.in/index.html'}, None), @@ -144,5 +229,9 @@ catalog = { 'https://site.with.paylo.ad/': (302, {'location': 'https://site.with.paylo.ad/index.html'}, None), 'https://site.with.paylo.ad/index.html': - (200, {}, here / 'data' / 'pages' / 'gotmyowndomain_https.html') + (200, {}, here / 'data' / 'pages' / 'gotmyowndomain_https.html'), + + **sample_files_catalog, + **sample_resources_catalog, + **sample_mappings_catalog } |