aboutsummaryrefslogtreecommitdiff
path: root/test/unit/utils.py
blob: 255f89def7fa885722bfa54cc176162258ae4a17 (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
# 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 <koszko@koszko.org>
#
# 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 <https://www.gnu.org/licenses/>.
#
# 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

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('<!-- dummy report -->'),
    '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 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 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());
        }''')