summaryrefslogtreecommitdiff
path: root/test/unit
diff options
context:
space:
mode:
authorWojtek Kosior <koszko@koszko.org>2022-01-22 13:49:40 +0100
committerWojtek Kosior <koszko@koszko.org>2022-01-22 13:49:40 +0100
commit7218849ae2f43aee6b3462a30e07caf5bac3d22b (patch)
tree3de3b31c07e532edf7373faf4a267f313dc2ed25 /test/unit
parent046b8a7b3e7259bf451926732e6221076b1d4153 (diff)
downloadbrowser-extension-7218849ae2f43aee6b3462a30e07caf5bac3d22b.tar.gz
browser-extension-7218849ae2f43aee6b3462a30e07caf5bac3d22b.zip
add a mapping/resources installation dialog
Diffstat (limited to 'test/unit')
-rw-r--r--test/unit/test_CORS_bypass_server.py2
-rw-r--r--test/unit/test_indexeddb.py38
-rw-r--r--test/unit/test_install.py429
-rw-r--r--test/unit/test_patterns_query_manager.py4
-rw-r--r--test/unit/test_payload_create.py12
-rw-r--r--test/unit/test_repo_query_cacher.py33
-rw-r--r--test/unit/utils.py42
7 files changed, 503 insertions, 57 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