| 1 |
#!/usr/bin/env python3 |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright 2015-2026 Mike Fährmann |
| 5 |
# |
| 6 |
# This program is free software; you can redistribute it and/or modify |
| 7 |
# it under the terms of the GNU General Public License version 2 as |
| 8 |
# published by the Free Software Foundation. |
| 9 |
|
| 10 |
import os |
| 11 |
import sys |
| 12 |
import unittest |
| 13 |
|
| 14 |
import re |
| 15 |
import json |
| 16 |
import hashlib |
| 17 |
import datetime |
| 18 |
import collections |
| 19 |
|
| 20 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 21 |
from gallery_dl import \ |
| 22 |
extractor, util, job, config, exception, formatter # noqa E402 |
| 23 |
|
| 24 |
|
| 25 |
RESULTS = os.environ.get("GDL_TEST_RESULTS") |
| 26 |
if RESULTS: |
| 27 |
results = util.import_file(RESULTS) |
| 28 |
else: |
| 29 |
from test import results |
| 30 |
|
| 31 |
|
| 32 |
# temporary issues, etc. |
| 33 |
BROKEN = { |
| 34 |
} |
| 35 |
|
| 36 |
CONFIG = { |
| 37 |
"cache": { |
| 38 |
"file": None, |
| 39 |
}, |
| 40 |
"downloader": { |
| 41 |
"adjust-extensions": False, |
| 42 |
"part": False, |
| 43 |
}, |
| 44 |
} |
| 45 |
|
| 46 |
|
| 47 |
AUTH_REQUIRED = { |
| 48 |
"pixiv", |
| 49 |
"nijie", |
| 50 |
"horne", |
| 51 |
"reddit", |
| 52 |
"seiga", |
| 53 |
"fantia", |
| 54 |
"instagram", |
| 55 |
"twitter", |
| 56 |
"poipiku", |
| 57 |
} |
| 58 |
|
| 59 |
AUTH_KEYS = { |
| 60 |
"username", |
| 61 |
"cookies", |
| 62 |
"api-key", |
| 63 |
"client-id", |
| 64 |
"access-token", |
| 65 |
"refresh-token", |
| 66 |
} |
| 67 |
|
| 68 |
|
| 69 |
class TestExtractorResults(unittest.TestCase): |
| 70 |
|
| 71 |
def setUp(self): |
| 72 |
setup_test_config() |
| 73 |
|
| 74 |
def tearDown(self): |
| 75 |
config.clear() |
| 76 |
|
| 77 |
@classmethod |
| 78 |
def setUpClass(cls): |
| 79 |
cls._skipped = [] |
| 80 |
|
| 81 |
@classmethod |
| 82 |
def tearDownClass(cls): |
| 83 |
if cls._skipped: |
| 84 |
sys.stdout.write("\n\nSkipped tests:\n") |
| 85 |
for url, reason in cls._skipped: |
| 86 |
sys.stdout.write(f'- {url} ("{reason}")\n') |
| 87 |
|
| 88 |
def assertRange(self, value, range, msg=None): |
| 89 |
if range.step > 1: |
| 90 |
self.assertIn(value, range, msg=msg) |
| 91 |
else: |
| 92 |
self.assertLessEqual(value, range.stop, msg=msg) |
| 93 |
self.assertGreaterEqual(value, range.start, msg=msg) |
| 94 |
|
| 95 |
def assertLogEqual(self, exp, out): |
| 96 |
level, name, message = out.split(":", 2) |
| 97 |
|
| 98 |
if isinstance(exp, str): |
| 99 |
return self.assertEqual(exp, message, "#log") |
| 100 |
|
| 101 |
self.assertEqual(exp[0].lower(), level.lower(), "#log/level") |
| 102 |
if len(exp) < 3: |
| 103 |
self.assertEqual(exp[1], message, "#log/message") |
| 104 |
else: |
| 105 |
self.assertEqual(exp[1], name , "#log/name") |
| 106 |
self.assertEqual(exp[2], message, "#log/message") |
| 107 |
|
| 108 |
def assertLogsEqual(self, expected, output): |
| 109 |
if isinstance(expected, str): |
| 110 |
expected = {expected[1:]} if expected[0] == "~" else (expected,) |
| 111 |
|
| 112 |
if isinstance(expected, set): |
| 113 |
self.assertLessEqual(len(expected), len(output), "#log/count") |
| 114 |
for exp in expected: |
| 115 |
for out in output: |
| 116 |
try: |
| 117 |
self.assertLogEqual(exp, out) |
| 118 |
break |
| 119 |
except AssertionError: |
| 120 |
pass |
| 121 |
else: |
| 122 |
self.fail(f'#log/Unmatched "{exp}"') |
| 123 |
else: |
| 124 |
self.assertEqual(len(output), len(expected), "#log/count") |
| 125 |
for exp, out in zip(expected, output): |
| 126 |
self.assertLogEqual(exp, out) |
| 127 |
|
| 128 |
def _run_test(self, result): |
| 129 |
if result.get("#fail"): |
| 130 |
del result["#fail"] |
| 131 |
try: |
| 132 |
self._run_test(result) |
| 133 |
except AssertionError: |
| 134 |
return |
| 135 |
else: |
| 136 |
self.fail("Test did not fail") |
| 137 |
|
| 138 |
base, cat, sub = result_categories(result) |
| 139 |
result.pop("#comment", None) |
| 140 |
result.pop("#category", None) |
| 141 |
auth = result.pop("#auth", None) |
| 142 |
|
| 143 |
cls = result["#class"] |
| 144 |
if cls.__module__.startswith("gallery_dl.extractor."): |
| 145 |
extr_url = extractor.find(result["#url"]) |
| 146 |
else: |
| 147 |
extr_url = extractor_find_external(result) |
| 148 |
self.assertIs(extr_url.__class__, cls, "extractor by URL/find") |
| 149 |
extr_cls = extr = cls.from_url(result["#url"]) |
| 150 |
self.assertIs(extr_cls.__class__, cls, "extractor by cls.from_url()") |
| 151 |
self.assertIs(extr_cls.__class__, extr_url.__class__) |
| 152 |
|
| 153 |
if len(result) <= 2: |
| 154 |
return # only matching |
| 155 |
|
| 156 |
skip = result.pop("#skip", False) |
| 157 |
if skip: |
| 158 |
return self._skipped.append((result["#url"], skip)) |
| 159 |
|
| 160 |
if auth is None: |
| 161 |
auth = (cat in AUTH_REQUIRED) |
| 162 |
elif not auth: |
| 163 |
# auth explicitly disabled |
| 164 |
for key in AUTH_KEYS: |
| 165 |
config.set((), key, None) |
| 166 |
|
| 167 |
if auth and not self._has_auth(extr, auth): |
| 168 |
self._skipped.append((result["#url"], "no auth")) |
| 169 |
self.skipTest("no auth") |
| 170 |
|
| 171 |
if "#options" in result: |
| 172 |
for key, value in result["#options"].items(): |
| 173 |
key = key.split(".") |
| 174 |
config.set(key[:-1], key[-1], value) |
| 175 |
if "#range" in result: |
| 176 |
config.set((), "file-range" , result["#range"]) |
| 177 |
config.set((), "child-range", result["#range"]) |
| 178 |
|
| 179 |
tjob = ResultJob(extr, |
| 180 |
content=("#sha1_content" in result), |
| 181 |
format=(result.get("#metadata") != "post")) |
| 182 |
|
| 183 |
if "#exception" in result: |
| 184 |
exc = result["#exception"] |
| 185 |
if isinstance(exc, str): |
| 186 |
exc, _, msg = exc.partition(":") |
| 187 |
exc = getattr(exception, exc, None) |
| 188 |
elif isinstance(exc, tuple): |
| 189 |
exc, msg = exc |
| 190 |
else: |
| 191 |
msg = "" |
| 192 |
with self.assertRaises(exc, msg="#exception") as cm, \ |
| 193 |
self.assertLogs() as log_info: |
| 194 |
tjob.run() |
| 195 |
if msg: |
| 196 |
self.assertEqual(str(cm.exception), msg, msg="#exception/msg") |
| 197 |
if "#log" in result: |
| 198 |
self.assertLogsEqual(result["#log"], log_info.output) |
| 199 |
return |
| 200 |
|
| 201 |
try: |
| 202 |
if "#log" in result: |
| 203 |
with self.assertLogs() as log_info: |
| 204 |
tjob.run() |
| 205 |
else: |
| 206 |
tjob.run() |
| 207 |
except exception.StopExtraction: |
| 208 |
pass |
| 209 |
except exception.HttpError as exc: |
| 210 |
exc = str(exc) |
| 211 |
if re.match(r"'5\d\d ", exc) or \ |
| 212 |
re.search(r"\bRead timed out\b", exc): |
| 213 |
self._skipped.append((result["#url"], exc)) |
| 214 |
self.skipTest(exc) |
| 215 |
raise |
| 216 |
|
| 217 |
if "#log" in result: |
| 218 |
self.assertLogsEqual(result["#log"], log_info.output) |
| 219 |
|
| 220 |
if result.get("#archive", True): |
| 221 |
self.assertEqual( |
| 222 |
len(set(tjob.archive_list)), |
| 223 |
len(tjob.archive_list), |
| 224 |
msg="archive-id uniqueness") |
| 225 |
|
| 226 |
if tjob.queue: |
| 227 |
# test '_extractor' entries |
| 228 |
for url, kwdict in zip(tjob.url_list, tjob.kwdict_list): |
| 229 |
if "_extractor" in kwdict: |
| 230 |
extr = kwdict["_extractor"].from_url(url) |
| 231 |
if extr is None and not result.get("#extractor", True): |
| 232 |
continue |
| 233 |
self.assertIsInstance(extr, kwdict["_extractor"], msg=url) |
| 234 |
self.assertEqual(extr.url, url) |
| 235 |
else: |
| 236 |
# test 'extension' entries |
| 237 |
for kwdict in tjob.kwdict_list: |
| 238 |
self.assertIn("extension", kwdict, msg="#extension") |
| 239 |
|
| 240 |
# test extraction results |
| 241 |
if "#sha1_url" in result: |
| 242 |
self.assertEqual( |
| 243 |
result["#sha1_url"], |
| 244 |
tjob.url_hash.hexdigest(), |
| 245 |
msg="#sha1_url") |
| 246 |
|
| 247 |
if "#sha1_content" in result: |
| 248 |
expected = result["#sha1_content"] |
| 249 |
digest = tjob.content_hash.hexdigest() |
| 250 |
if isinstance(expected, str): |
| 251 |
self.assertEqual(expected, digest, msg="#sha1_content") |
| 252 |
else: # iterable |
| 253 |
self.assertIn(digest, expected, msg="#sha1_content") |
| 254 |
|
| 255 |
if "#sha1_metadata" in result: |
| 256 |
self.assertEqual( |
| 257 |
result["#sha1_metadata"], |
| 258 |
tjob.kwdict_hash.hexdigest(), |
| 259 |
"#sha1_metadata") |
| 260 |
|
| 261 |
if "#count" in result: |
| 262 |
count = result["#count"] |
| 263 |
len_urls = len(tjob.url_list) |
| 264 |
if isinstance(count, str): |
| 265 |
self.assertRegex( |
| 266 |
count, r"^ *(==|!=|<|<=|>|>=) *\d+ *$", msg="#count") |
| 267 |
expr = f"{len_urls} {count}" |
| 268 |
self.assertTrue(eval(expr), msg=expr) |
| 269 |
elif isinstance(count, range): |
| 270 |
self.assertRange(len_urls, count, msg="#count") |
| 271 |
else: # assume integer |
| 272 |
self.assertEqual(len_urls, count, msg="#count") |
| 273 |
|
| 274 |
if "#pattern" in result: |
| 275 |
self.assertGreater(len(tjob.url_list), 0, msg="#pattern") |
| 276 |
pattern = result["#pattern"] |
| 277 |
if isinstance(pattern, str): |
| 278 |
for url in tjob.url_list: |
| 279 |
self.assertRegex(url, pattern, msg="#pattern") |
| 280 |
else: |
| 281 |
self.assertEqual( |
| 282 |
len(tjob.url_list), len(pattern), msg="#pattern/count") |
| 283 |
for url, pat in zip(tjob.url_list, pattern): |
| 284 |
self.assertRegex(url, pat, msg="#pattern") |
| 285 |
|
| 286 |
if "#results" in result: |
| 287 |
expected = result["#results"] |
| 288 |
if isinstance(expected, str): |
| 289 |
self.assertTrue(tjob.url_list, msg="#results") |
| 290 |
self.assertEqual( |
| 291 |
tjob.url_list[0], expected, msg="#results") |
| 292 |
else: |
| 293 |
self.assertSequenceEqual( |
| 294 |
tjob.url_list, expected, msg="#results") |
| 295 |
|
| 296 |
metadata = {k: v for k, v in result.items() if k[0] != "#"} |
| 297 |
if metadata: |
| 298 |
if result.get("#metadata") == "post": |
| 299 |
kwdicts = tjob.kwdict_post |
| 300 |
else: |
| 301 |
kwdicts = tjob.kwdict_list |
| 302 |
for kwdict in kwdicts: |
| 303 |
self._test_kwdict(kwdict, metadata) |
| 304 |
|
| 305 |
def _has_auth(self, extr, auth): |
| 306 |
if auth is True: |
| 307 |
auth = AUTH_KEYS |
| 308 |
|
| 309 |
if isinstance(auth, str): |
| 310 |
return extr.config(auth) |
| 311 |
if isinstance(auth, set): |
| 312 |
return any(self._has_auth(extr, a) for a in auth) |
| 313 |
if isinstance(auth, (tuple, list)): |
| 314 |
return all(self._has_auth(extr, k) for k in auth) |
| 315 |
|
| 316 |
self.fail(f"Invalid '#auth' value: {auth!r}") |
| 317 |
|
| 318 |
def _test_kwdict(self, kwdict, tests, parent=None): |
| 319 |
for key, test in tests.items(): |
| 320 |
|
| 321 |
if key.startswith("?"): |
| 322 |
key = key[1:] |
| 323 |
if key not in kwdict: |
| 324 |
continue |
| 325 |
|
| 326 |
if key.endswith("[*]"): |
| 327 |
key = key[:-3] |
| 328 |
subtest = True |
| 329 |
else: |
| 330 |
subtest = False |
| 331 |
|
| 332 |
path = f"{parent}.{key}" if parent else key |
| 333 |
|
| 334 |
if key.startswith("!"): |
| 335 |
self.assertNotIn(key[1:], kwdict, msg=path) |
| 336 |
continue |
| 337 |
|
| 338 |
self.assertIn(key, kwdict, msg=path) |
| 339 |
value = kwdict[key] |
| 340 |
|
| 341 |
if subtest: |
| 342 |
self.assertNotIsInstance(value, str, msg=path) |
| 343 |
for idx, item in enumerate(value): |
| 344 |
subpath = f"{path}[{idx}]" |
| 345 |
self._test_kwdict_value(item, test, subpath) |
| 346 |
else: |
| 347 |
self._test_kwdict_value(value, test, path) |
| 348 |
|
| 349 |
def _test_kwdict_value(self, value, test, path): |
| 350 |
if isinstance(test, dict): |
| 351 |
self._test_kwdict(value, test, path) |
| 352 |
elif isinstance(test, type): |
| 353 |
self.assertIsInstance(value, test, msg=path) |
| 354 |
elif isinstance(test, range): |
| 355 |
self.assertRange(value, test, msg=path) |
| 356 |
elif isinstance(test, set): |
| 357 |
if isinstance(value, list): |
| 358 |
value = tuple(value) |
| 359 |
for item in test: |
| 360 |
if isinstance(item, type) and isinstance(value, item) or \ |
| 361 |
value == item: |
| 362 |
break |
| 363 |
else: |
| 364 |
v = type(value) if len(str(value)) > 64 else value |
| 365 |
self.fail(f"{v!r} not in {test}: {path}") |
| 366 |
elif isinstance(test, list): |
| 367 |
subtest = False |
| 368 |
for idx, item in enumerate(test): |
| 369 |
if isinstance(item, dict): |
| 370 |
subtest = True |
| 371 |
subpath = f"{path}[{idx}]" |
| 372 |
try: |
| 373 |
obj = value[idx] |
| 374 |
except Exception as exc: |
| 375 |
self.fail(f"'{exc.__class__.__name__}: {exc}' " |
| 376 |
f"when accessing {subpath}") |
| 377 |
self._test_kwdict(obj, item, subpath) |
| 378 |
if not subtest: |
| 379 |
self.assertEqual(test, value, msg=path) |
| 380 |
elif isinstance(test, str): |
| 381 |
if test.startswith("re:"): |
| 382 |
self.assertIsInstance(value, str, msg=path) |
| 383 |
self.assertRegex(value, test[3:], msg=path) |
| 384 |
elif test.startswith("dt:"): |
| 385 |
self.assertIsInstance(value, datetime.datetime, msg=path) |
| 386 |
self.assertEqual(test[3:], str(value), msg=path) |
| 387 |
elif test.startswith("type:"): |
| 388 |
self.assertEqual(test[5:], type(value).__name__, msg=path) |
| 389 |
elif test.startswith("len:"): |
| 390 |
cls, _, length = test[4:].rpartition(":") |
| 391 |
if cls: |
| 392 |
self.assertEqual( |
| 393 |
cls, type(value).__name__, msg=f"{path}/type") |
| 394 |
try: |
| 395 |
len_value = len(value) |
| 396 |
except Exception: |
| 397 |
len_value = 0 |
| 398 |
for _ in value: |
| 399 |
len_value += 1 |
| 400 |
self.assertEqual(int(length), len_value, msg=path) |
| 401 |
elif test.startswith("hash:"): |
| 402 |
digest = test[5:].lower() |
| 403 |
msg = f"{path} / {digest}" |
| 404 |
if digest == "md5": |
| 405 |
self.assertRegex(value, r"^[0-9a-fA-F]{32}$", msg) |
| 406 |
elif digest == "sha1": |
| 407 |
self.assertRegex(value, r"^[0-9a-fA-F]{40}$", msg) |
| 408 |
elif digest == "sha256": |
| 409 |
self.assertRegex(value, r"^[0-9a-fA-F]{64}$", msg) |
| 410 |
elif digest == "sha512": |
| 411 |
self.assertRegex(value, r"^[0-9a-fA-F]{128}$", msg) |
| 412 |
elif test.startswith("iso:"): |
| 413 |
iso = test[4:] |
| 414 |
if iso in ("dt", "datetime", "8601"): |
| 415 |
msg = f"{path} / ISO 8601" |
| 416 |
try: |
| 417 |
dt = datetime.datetime.fromisoformat(value) |
| 418 |
except Exception as exc: |
| 419 |
self.fail(f"Invalid datetime '{value}': {exc} {msg}") |
| 420 |
self.assertIsInstance(dt, datetime.datetime, msg=msg) |
| 421 |
elif iso in ("lang", "639", "639-1"): |
| 422 |
msg = f"{path} / ISO 639-1" |
| 423 |
self.assertIsInstance(value, str, msg=msg) |
| 424 |
self.assertRegex(value, r"^[a-z]{2}(-\w+)?$", msg=msg) |
| 425 |
elif iso in ("uuid", "11578", "11578:1996", "4122"): |
| 426 |
msg = f"{path} / ISO 11578:1996" |
| 427 |
pat = (r"(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-" |
| 428 |
r"[0-9a-f]{4}-[0-9a-f]{12}") |
| 429 |
self.assertIsInstance(value, str, msg=msg) |
| 430 |
self.assertRegex(value, pat, msg=msg) |
| 431 |
else: |
| 432 |
self.fail(f"Unsupported ISO test '{test}'") |
| 433 |
else: |
| 434 |
self.assertEqual(test, value, msg=path) |
| 435 |
else: |
| 436 |
self.assertEqual(test, value, msg=path) |
| 437 |
|
| 438 |
|
| 439 |
class ResultJob(job.DownloadJob): |
| 440 |
"""Generate test-results for extractor runs""" |
| 441 |
|
| 442 |
def __init__(self, url, parent=None, content=False, format=True): |
| 443 |
job.DownloadJob.__init__(self, url, parent) |
| 444 |
self.queue = False |
| 445 |
self.content = content |
| 446 |
|
| 447 |
self.format = format |
| 448 |
self.url_list = [] |
| 449 |
self.url_hash = hashlib.sha1() |
| 450 |
self.kwdict_list = [] |
| 451 |
self.kwdict_post = [] |
| 452 |
self.kwdict_hash = hashlib.sha1() |
| 453 |
self.archive_list = [] |
| 454 |
self.archive_hash = hashlib.sha1() |
| 455 |
self.content_hash = hashlib.sha1() |
| 456 |
|
| 457 |
if content: |
| 458 |
self.fileobj = TestPathfmt(self.content_hash) |
| 459 |
else: |
| 460 |
self._update_content = lambda url, kwdict: None |
| 461 |
|
| 462 |
def run(self): |
| 463 |
self._init() |
| 464 |
self.dispatch(self.extractor) |
| 465 |
|
| 466 |
def handle_url(self, url, kwdict, fallback=None): |
| 467 |
self._update_url(url) |
| 468 |
self._update_kwdict(kwdict) |
| 469 |
self._update_archive(kwdict) |
| 470 |
self._update_content(url, kwdict) |
| 471 |
self.format_filename(kwdict) |
| 472 |
|
| 473 |
def handle_directory(self, kwdict): |
| 474 |
if self.format is not None: |
| 475 |
if self.format: |
| 476 |
self.format_directory = TestFormatter( |
| 477 |
"".join(self.extractor.directory_fmt)).format_map |
| 478 |
self.format_filename = TestFormatter( |
| 479 |
self.extractor.filename_fmt).format_map |
| 480 |
self.format_archive = TestFormatter( |
| 481 |
self.extractor.archive_fmt).format_map |
| 482 |
else: |
| 483 |
self.format_directory = \ |
| 484 |
self.format_filename = \ |
| 485 |
self.format_archive = lambda kwdict: "" |
| 486 |
self.format = None |
| 487 |
|
| 488 |
self._update_kwdict(kwdict, False) |
| 489 |
self.format_directory(kwdict) |
| 490 |
|
| 491 |
def handle_metadata(self, kwdict): |
| 492 |
pass |
| 493 |
|
| 494 |
def handle_queue(self, url, kwdict): |
| 495 |
self.queue = True |
| 496 |
self._update_url(url) |
| 497 |
self._update_kwdict(kwdict) |
| 498 |
|
| 499 |
def _update_url(self, url): |
| 500 |
self.url_list.append(url) |
| 501 |
self.url_hash.update(url.encode()) |
| 502 |
|
| 503 |
def _update_kwdict(self, kwdict, to_list=True): |
| 504 |
if to_list: |
| 505 |
self.kwdict_list.append(kwdict.copy()) |
| 506 |
else: |
| 507 |
self.kwdict_post.append(kwdict.copy()) |
| 508 |
kwdict = util.filter_dict(kwdict) |
| 509 |
self.kwdict_hash.update( |
| 510 |
json.dumps(kwdict, sort_keys=True, default=str).encode()) |
| 511 |
|
| 512 |
def _update_archive(self, kwdict): |
| 513 |
archive_id = self.format_archive(kwdict) |
| 514 |
self.archive_list.append(archive_id) |
| 515 |
self.archive_hash.update(archive_id.encode()) |
| 516 |
|
| 517 |
def _update_content(self, url, kwdict): |
| 518 |
self.fileobj.kwdict = kwdict |
| 519 |
|
| 520 |
downloader = self.get_downloader(url.partition(":")[0]) |
| 521 |
if downloader.download(url, self.fileobj): |
| 522 |
return |
| 523 |
|
| 524 |
for num, url in enumerate(kwdict.get("_fallback") or (), 1): |
| 525 |
self.log.warning("Trying fallback URL #%d", num) |
| 526 |
downloader = self.get_downloader(url.partition(":")[0]) |
| 527 |
if downloader.download(url, self.fileobj): |
| 528 |
return |
| 529 |
|
| 530 |
|
| 531 |
class TestPathfmt(): |
| 532 |
|
| 533 |
def __init__(self, hashobj): |
| 534 |
self.hashobj = hashobj |
| 535 |
self.path = "" |
| 536 |
self.size = 0 |
| 537 |
self.kwdict = {} |
| 538 |
self.extension = "jpg" |
| 539 |
|
| 540 |
def __enter__(self): |
| 541 |
return self |
| 542 |
|
| 543 |
def __exit__(self, exc_type, exc_value, traceback): |
| 544 |
pass |
| 545 |
|
| 546 |
def open(self, mode): |
| 547 |
self.size = 0 |
| 548 |
return self |
| 549 |
|
| 550 |
def write(self, content): |
| 551 |
"""Update SHA1 hash""" |
| 552 |
self.size += len(content) |
| 553 |
self.hashobj.update(content) |
| 554 |
|
| 555 |
def tell(self): |
| 556 |
return self.size |
| 557 |
|
| 558 |
def part_size(self): |
| 559 |
return 0 |
| 560 |
|
| 561 |
|
| 562 |
class TestFormatter(formatter.StringFormatter): |
| 563 |
|
| 564 |
def _apply_simple(self, key, fmt): |
| 565 |
if key == "extension" or "_parse_optional." in repr(fmt): |
| 566 |
def wrap(obj): |
| 567 |
try: |
| 568 |
return fmt(obj[key]) |
| 569 |
except KeyError: |
| 570 |
return "" |
| 571 |
elif "<function identity at " in repr(fmt): |
| 572 |
def wrap(obj): |
| 573 |
return "".join(obj[key]) |
| 574 |
else: |
| 575 |
def wrap(obj): |
| 576 |
return fmt(obj[key]) |
| 577 |
return wrap |
| 578 |
|
| 579 |
def _apply(self, key, funcs, fmt): |
| 580 |
if key == "extension" or "_parse_optional." in repr(fmt): |
| 581 |
def wrap(obj): |
| 582 |
if obj := obj.get(key): |
| 583 |
for func in funcs: |
| 584 |
obj = func(obj) |
| 585 |
else: |
| 586 |
obj = "" |
| 587 |
return fmt(obj) |
| 588 |
elif "<function identity at " in repr(fmt): |
| 589 |
def wrap(obj): |
| 590 |
return "".join(obj[key]) |
| 591 |
else: |
| 592 |
def wrap(obj): |
| 593 |
obj = obj[key] |
| 594 |
for func in funcs: |
| 595 |
obj = func(obj) |
| 596 |
return fmt(obj) |
| 597 |
return wrap |
| 598 |
|
| 599 |
|
| 600 |
def setup_test_config(): |
| 601 |
config._config.update(CONFIG) |
| 602 |
|
| 603 |
|
| 604 |
def load_test_config(): |
| 605 |
try: |
| 606 |
path = os.path.join( |
| 607 |
os.path.dirname(os.path.dirname(__file__)), |
| 608 |
"archive", "config.json") |
| 609 |
with open(path) as fp: |
| 610 |
CONFIG.update(json.loads(fp.read())) |
| 611 |
except FileNotFoundError: |
| 612 |
pass |
| 613 |
except Exception as exc: |
| 614 |
sys.exit(f"Error when loading {path}: {exc.__class__.__name__}: {exc}") |
| 615 |
|
| 616 |
|
| 617 |
def extractor_find_external(result, imported=set()): |
| 618 |
_module_iter_orig = extractor._module_iter |
| 619 |
try: |
| 620 |
file = sys.modules[result["#class"].__module__].__file__ |
| 621 |
if file not in imported: |
| 622 |
path, filename = os.path.split(file) |
| 623 |
extractor._module_iter = extractor._modules_path(path, (filename,)) |
| 624 |
imported.add(file) |
| 625 |
return extractor.find(result["#url"]) |
| 626 |
finally: |
| 627 |
extractor._module_iter = _module_iter_orig |
| 628 |
|
| 629 |
|
| 630 |
def result_categories(result): |
| 631 |
categories = result.get("#category") |
| 632 |
if categories: |
| 633 |
return categories |
| 634 |
|
| 635 |
cls = result["#class"] |
| 636 |
return cls.basecategory, cls.category, cls.subcategory |
| 637 |
|
| 638 |
|
| 639 |
def generate_tests(): |
| 640 |
"""Dynamically generate extractor unittests""" |
| 641 |
def _generate_method(result): |
| 642 |
def test(self): |
| 643 |
sys.stdout.write(f"\n{result['#url']}\n") |
| 644 |
if "#comment" in result: |
| 645 |
sys.stdout.write(f"# {result['#comment']}\n") |
| 646 |
|
| 647 |
try: |
| 648 |
self._run_test(result) |
| 649 |
except KeyboardInterrupt as exc: |
| 650 |
v = input("\n[e]xit | [f]ail | [S]kip ? ").strip().lower() |
| 651 |
if v in ("e", "exit"): |
| 652 |
raise |
| 653 |
if v in ("f", "fail"): |
| 654 |
self.fail("manual test failure") |
| 655 |
else: |
| 656 |
self._skipped.append((result["#url"], "manual skip")) |
| 657 |
self.skipTest(exc) |
| 658 |
return test |
| 659 |
|
| 660 |
# enable selective testing for direct calls |
| 661 |
if __name__ == "__main__" and len(sys.argv) > 1: |
| 662 |
category, _, subcategory = sys.argv[1].partition(":") |
| 663 |
del sys.argv[1:] |
| 664 |
|
| 665 |
if category.startswith("+"): |
| 666 |
basecategory = category[1:].lower() |
| 667 |
tests = [t for t in results.all() |
| 668 |
if result_categories(t)[0].lower() == basecategory] |
| 669 |
else: |
| 670 |
tests = results.category(category) |
| 671 |
|
| 672 |
if subcategory: |
| 673 |
if subcategory.startswith("+"): |
| 674 |
url = subcategory[1:] |
| 675 |
tests = [t for t in tests if url in t["#url"]] |
| 676 |
elif subcategory.startswith("~"): |
| 677 |
com = subcategory[1:] |
| 678 |
tests = [t for t in tests |
| 679 |
if "#comment" in t and com in t["#comment"].lower()] |
| 680 |
else: |
| 681 |
tests = [t for t in tests |
| 682 |
if result_categories(t)[-1] == subcategory] |
| 683 |
else: |
| 684 |
tests = results.all() |
| 685 |
|
| 686 |
# add 'test_...' methods |
| 687 |
enum = collections.defaultdict(int) |
| 688 |
for result in tests: |
| 689 |
base, cat, sub = result_categories(result) |
| 690 |
name = f"{cat}_{sub}" |
| 691 |
enum[name] += 1 |
| 692 |
|
| 693 |
method = _generate_method(result) |
| 694 |
method.__doc__ = result["#url"] |
| 695 |
method.__name__ = f"test_{name}_{enum[name]}" |
| 696 |
setattr(TestExtractorResults, method.__name__, method) |
| 697 |
|
| 698 |
|
| 699 |
generate_tests() |
| 700 |
if __name__ == "__main__": |
| 701 |
load_test_config() |
| 702 |
unittest.main(warnings="ignore") |