| 1 |
# vim:fileencoding=utf-8 |
| 2 |
# License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> |
| 3 |
from __python__ import bound_methods, hash_literals |
| 4 |
|
| 5 |
from dom import clear |
| 6 |
|
| 7 |
|
| 8 |
def raise_fail(preamble, msg, call_site): |
| 9 |
if msg: |
| 10 |
msg = '. ' + msg |
| 11 |
else: |
| 12 |
msg = '' |
| 13 |
if call_site?.module_name: |
| 14 |
msg += f' [in module {call_site.module_name}:{call_site.line}:{call_site.col}]' |
| 15 |
raise AssertionError(preamble + msg) |
| 16 |
|
| 17 |
|
| 18 |
def repr_of(a): |
| 19 |
if not a: |
| 20 |
return a |
| 21 |
q = a.outerHTML |
| 22 |
if q: |
| 23 |
return q.split('>')[0] + '>' |
| 24 |
if a.nodeType is Node.TEXT_NODE: |
| 25 |
return repr(a.nodeValue) |
| 26 |
return str(a) |
| 27 |
|
| 28 |
|
| 29 |
def assert_equal(a, b, msg, call_site=None): |
| 30 |
def fail(): |
| 31 |
ra = repr_of(a) |
| 32 |
rb = repr_of(b) |
| 33 |
p = f'{ra} != {rb}' |
| 34 |
raise_fail(p, msg, call_site) |
| 35 |
|
| 36 |
atype = jstype(a) |
| 37 |
btype = jstype(b) |
| 38 |
base_types = {'number': True, 'boolean': True, 'string': True, 'undefined': True} |
| 39 |
if base_types[atype] or base_types[btype] or a is None or b is None: |
| 40 |
if a is not b: |
| 41 |
fail() |
| 42 |
return |
| 43 |
if a.__eq__: |
| 44 |
if not a.__eq__(b): |
| 45 |
fail() |
| 46 |
return |
| 47 |
if a.isSameNode: |
| 48 |
if not a.isSameNode(b): |
| 49 |
fail() |
| 50 |
return |
| 51 |
if b.__eq__: |
| 52 |
if not b.__eq__(a): |
| 53 |
fail() |
| 54 |
return |
| 55 |
if b.isSameNode: |
| 56 |
if not b.isSameNode(a): |
| 57 |
fail() |
| 58 |
return |
| 59 |
if a.length? or b.length?: |
| 60 |
if a.length is not b.length: |
| 61 |
fail() |
| 62 |
for i in range(a.length): |
| 63 |
assert_equal(a[i], b[i]) |
| 64 |
return |
| 65 |
if atype is 'object': |
| 66 |
for key in Object.keys(a): |
| 67 |
assert_equal(a[key], b[key]) |
| 68 |
if btype is 'object': |
| 69 |
for key in Object.keys(b): |
| 70 |
assert_equal(a[key], b[key]) |
| 71 |
|
| 72 |
if atype is not 'object' and btype is not 'object': |
| 73 |
fail() |
| 74 |
|
| 75 |
|
| 76 |
def assert_true(x, msg, call_site=None): |
| 77 |
if not x: |
| 78 |
raise_fail(f'{x} is not truthy', msg, call_site) |
| 79 |
|
| 80 |
|
| 81 |
def assert_false(x, msg, call_site=None): |
| 82 |
if x: |
| 83 |
raise_fail(f'{x} is truthy', msg, call_site) |
| 84 |
|
| 85 |
|
| 86 |
def reset_dom(): |
| 87 |
html = document.documentElement |
| 88 |
clear(html) |
| 89 |
head = document.createElement('head') |
| 90 |
body = document.createElement('body') |
| 91 |
html.appendChild(head) |
| 92 |
html.appendChild(body) |
| 93 |
|
| 94 |
|
| 95 |
registered_tests = {} |
| 96 |
|
| 97 |
|
| 98 |
def test(f): |
| 99 |
mod = f.__module__ or 'unknown_test_module' |
| 100 |
f.test_name = mod + '.' + f.name |
| 101 |
registered_tests[f.test_name] = f |
| 102 |
return f |