# SPDX-License-Identifier: GPL-3.0-or-later """ Various functions and objects that can be reused between unit tests """ # This file is part of Haketilo. # # Copyright (C) 2021,2022 Wojtek Kosior # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # I, Wojtek Kosior, thereby promise not to sue for violation of this file's # license. Although I request that you do not make use of this code in a # 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 patterns_doc_url = \ 'https://hydrillabugs.koszko.org/projects/haketilo/wiki/URL_patterns' def make_hash_key(file_contents): return f'sha256-{sha256(file_contents.encode()).digest().hex()}' def sample_file(contents): return { 'hash_key': make_hash_key(contents), 'contents': contents } sample_files = { 'report.spdx': sample_file(''), 'LICENSES/somelicense.txt': sample_file('Permission is granted...'), 'LICENSES/CC0-1.0.txt': sample_file('Dummy Commons...'), 'hello.js': sample_file('console.log("uńićódę hello!");\n'), 'bye.js': sample_file('console.log("bye!");\n'), 'combined.js': sample_file('console.log("hello!\\nbye!");\n'), 'README.md': sample_file('# Python Frobnicator\n...') } sample_files_by_hash = dict([[file['hash_key'], file['contents']] for file in sample_files.values()]) def sample_file_ref(file_name): return {'file': file_name, 'hash_key': sample_files[file_name]['hash_key']} def make_sample_mapping(): return { 'source_name': 'example-org-fixes-new', 'source_copyright': [ sample_file_ref('report.spdx'), sample_file_ref('LICENSES/CC0-1.0.txt') ], 'type': 'mapping', 'identifier': 'example-org-minimal', 'long_name': 'Example.org Minimal', 'uuid': '54d23bba-472e-42f5-9194-eaa24c0e3ee7', 'version': [2022, 5, 10], 'description': 'suckless something something', 'payloads': { 'https://example.org/a/*': { 'identifier': 'some-KISS-resource' }, 'https://example.org/t/*': { 'identifier': 'another-KISS-resource' } } } def make_sample_resource(): return { 'source_name': 'hello', 'source_copyright': [ sample_file_ref('report.spdx'), sample_file_ref('LICENSES/CC0-1.0.txt') ], 'type': 'resource', 'identifier': 'helloapple', 'long_name': 'Hello Apple', 'uuid': 'a6754dcb-58d8-4b7a-a245-24fd7ad4cd68', 'version': [2021, 11, 10], 'revision': 1, 'description': 'greets an apple', 'dependencies': ['hello-message'], 'scripts': [ sample_file_ref('hello.js'), sample_file_ref('bye.js') ] } def item_version_string(definition, include_revision=False): """ Given a resource or mapping definition, read its "version" property (and also "revision" if applicable) and produce a corresponding version string. """ ver = '.'.join([str(num) for num in definition['version']]) revision = definition.get('revision') if include_revision else None return f'{ver}-{revision}' if revision is not None else ver def sample_data_dict(items): """ Some indexeddb functions expect saved items to be provided in a nested dict that makes them queryable by identifier by version. This function converts items list to such dict. """ return dict([(it['identifier'], {item_version_string(it): it}) for it in items]) def make_complete_sample_data(): """ Craft a JSON data item with 1 sample resource and 1 sample mapping that can be used to populate IndexedDB. """ return { 'resources': sample_data_dict([make_sample_resource()]), 'mappings': sample_data_dict([make_sample_mapping()]), 'files': sample_files_by_hash } def clear_indexeddb(execute_in_page): """ Remove Haketilo data from IndexedDB. If variables from common/indexeddb.js are in the global scope, this function will handle closing the opened database instance (if any). Otherwise, the caller is responsible for making sure the database being deleted is not opened anywhere. """ execute_in_page( '''{ async function delete_db() { if (typeof db !== "undefined" && db) { db.close(); db = null; } let resolve, reject; const result = new Promise((...cbs) => [resolve, reject] = cbs); const request = indexedDB.deleteDatabase("haketilo"); [request.onsuccess, request.onerror] = [resolve, reject]; await result; } returnval(delete_db()); }''' ) def get_db_contents(execute_in_page): """ Retrieve all IndexedDB contents. It is expected that either variables from common/indexeddb.js are in the global scope or common/indexeddb.js is imported as haketilodb. """ return execute_in_page( '''{ async function get_database_contents() { const db_getter = typeof haketilodb === "undefined" ? get_db : haketilodb.get; const db = await db_getter(); const transaction = db.transaction(db.objectStoreNames); const result = {}; for (const store_name of db.objectStoreNames) { const req = transaction.objectStore(store_name).getAll(); await new Promise(cb => req.onsuccess = cb); result[store_name] = req.result; } return result; } returnval(get_database_contents()); }''') def is_prime(n): return n > 1 and all([n % i != 0 for i in range(2, n)]) broker_js = lambda: load_script('background/broadcast_broker.js') + ';start();' def are_scripts_allowed(driver, nonce=None): return driver.execute_script( ''' document.haketilo_scripts_allowed = false; const script = document.createElement("script"); script.innerHTML = "document.haketilo_scripts_allowed = true;"; if (arguments[0]) script.setAttribute("nonce", arguments[0]); document.head.append(script); 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