2
0

util.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. __package__ = 'archivebox'
  2. import re
  3. import requests
  4. import json as pyjson
  5. import http.cookiejar
  6. from typing import List, Optional, Any
  7. from pathlib import Path
  8. from inspect import signature
  9. from functools import wraps
  10. from hashlib import sha256
  11. from urllib.parse import urlparse, quote, unquote
  12. from html import escape, unescape
  13. from datetime import datetime, timezone
  14. from dateparser import parse as dateparser
  15. from requests.exceptions import RequestException, ReadTimeout
  16. from base32_crockford import encode as base32_encode # type: ignore
  17. from w3lib.encoding import html_body_declared_encoding, http_content_type_encoding
  18. from os.path import lexists
  19. from os import remove as remove_file
  20. try:
  21. import chardet
  22. detect_encoding = lambda rawdata: chardet.detect(rawdata)["encoding"]
  23. except ImportError:
  24. detect_encoding = lambda rawdata: "utf-8"
  25. ### Parsing Helpers
  26. # All of these are (str) -> str
  27. # shortcuts to: https://docs.python.org/3/library/urllib.parse.html#url-parsing
  28. scheme = lambda url: urlparse(url).scheme.lower()
  29. without_scheme = lambda url: urlparse(url)._replace(scheme='').geturl().strip('//')
  30. without_query = lambda url: urlparse(url)._replace(query='').geturl().strip('//')
  31. without_fragment = lambda url: urlparse(url)._replace(fragment='').geturl().strip('//')
  32. without_path = lambda url: urlparse(url)._replace(path='', fragment='', query='').geturl().strip('//')
  33. path = lambda url: urlparse(url).path
  34. basename = lambda url: urlparse(url).path.rsplit('/', 1)[-1]
  35. domain = lambda url: urlparse(url).netloc
  36. query = lambda url: urlparse(url).query
  37. fragment = lambda url: urlparse(url).fragment
  38. extension = lambda url: basename(url).rsplit('.', 1)[-1].lower() if '.' in basename(url) else ''
  39. base_url = lambda url: without_scheme(url) # uniq base url used to dedupe links
  40. without_www = lambda url: url.replace('://www.', '://', 1)
  41. without_trailing_slash = lambda url: url[:-1] if url[-1] == '/' else url.replace('/?', '?')
  42. hashurl = lambda url: base32_encode(int(sha256(base_url(url).encode('utf-8')).hexdigest(), 16))[:20]
  43. urlencode = lambda s: s and quote(s, encoding='utf-8', errors='replace')
  44. urldecode = lambda s: s and unquote(s)
  45. htmlencode = lambda s: s and escape(s, quote=True)
  46. htmldecode = lambda s: s and unescape(s)
  47. short_ts = lambda ts: str(parse_date(ts).timestamp()).split('.')[0]
  48. ts_to_date_str = lambda ts: ts and parse_date(ts).strftime('%Y-%m-%d %H:%M')
  49. ts_to_iso = lambda ts: ts and parse_date(ts).isoformat()
  50. COLOR_REGEX = re.compile(r'\[(?P<arg_1>\d+)(;(?P<arg_2>\d+)(;(?P<arg_3>\d+))?)?m')
  51. # https://mathiasbynens.be/demo/url-regex
  52. URL_REGEX = re.compile(
  53. r'(?=('
  54. r'http[s]?://' # start matching from allowed schemes
  55. r'(?:[a-zA-Z]|[0-9]' # followed by allowed alphanum characters
  56. r'|[-_$@.&+!*\(\),]' # or allowed symbols (keep hyphen first to match literal hyphen)
  57. r'|[^\u0000-\u007F])+' # or allowed unicode bytes
  58. r'[^\]\[<>"\'\s]+' # stop parsing at these symbols
  59. r'))',
  60. re.IGNORECASE | re.UNICODE,
  61. )
  62. def parens_are_matched(string: str, open_char='(', close_char=')'):
  63. """check that all parentheses in a string are balanced and nested properly"""
  64. count = 0
  65. for c in string:
  66. if c == open_char:
  67. count += 1
  68. elif c == close_char:
  69. count -= 1
  70. if count < 0:
  71. return False
  72. return count == 0
  73. def fix_url_from_markdown(url_str: str) -> str:
  74. """
  75. cleanup a regex-parsed url that may contain dangling trailing parens from markdown link syntax
  76. helpful to fix URLs parsed from markdown e.g.
  77. input: https://wikipedia.org/en/some_article_(Disambiguation).html?abc=def).somemoretext
  78. result: https://wikipedia.org/en/some_article_(Disambiguation).html?abc=def
  79. IMPORTANT ASSUMPTION: valid urls wont have unbalanced or incorrectly nested parentheses
  80. e.g. this will fail the user actually wants to ingest a url like 'https://example.com/some_wei)(rd_url'
  81. in that case it will return https://example.com/some_wei (truncated up to the first unbalanced paren)
  82. This assumption is true 99.9999% of the time, and for the rare edge case the user can use url_list parser.
  83. """
  84. trimmed_url = url_str
  85. # cut off one trailing character at a time
  86. # until parens are balanced e.g. /a(b)c).x(y)z -> /a(b)c
  87. while not parens_are_matched(trimmed_url):
  88. trimmed_url = trimmed_url[:-1]
  89. # make sure trimmed url is still valid
  90. if re.findall(URL_REGEX, trimmed_url):
  91. return trimmed_url
  92. return url_str
  93. def find_all_urls(urls_str: str):
  94. for url in re.findall(URL_REGEX, urls_str):
  95. yield fix_url_from_markdown(url)
  96. def is_static_file(url: str):
  97. # TODO: the proper way is with MIME type detection + ext, not only extension
  98. from .config import STATICFILE_EXTENSIONS
  99. return extension(url).lower() in STATICFILE_EXTENSIONS
  100. def enforce_types(func):
  101. """
  102. Enforce function arg and kwarg types at runtime using its python3 type hints
  103. """
  104. # TODO: check return type as well
  105. @wraps(func)
  106. def typechecked_function(*args, **kwargs):
  107. sig = signature(func)
  108. def check_argument_type(arg_key, arg_val):
  109. try:
  110. annotation = sig.parameters[arg_key].annotation
  111. except KeyError:
  112. annotation = None
  113. if annotation is not None and annotation.__class__ is type:
  114. if not isinstance(arg_val, annotation):
  115. raise TypeError(
  116. '{}(..., {}: {}) got unexpected {} argument {}={}'.format(
  117. func.__name__,
  118. arg_key,
  119. annotation.__name__,
  120. type(arg_val).__name__,
  121. arg_key,
  122. str(arg_val)[:64],
  123. )
  124. )
  125. # check args
  126. for arg_val, arg_key in zip(args, sig.parameters):
  127. check_argument_type(arg_key, arg_val)
  128. # check kwargs
  129. for arg_key, arg_val in kwargs.items():
  130. check_argument_type(arg_key, arg_val)
  131. return func(*args, **kwargs)
  132. return typechecked_function
  133. def docstring(text: Optional[str]):
  134. """attach the given docstring to the decorated function"""
  135. def decorator(func):
  136. if text:
  137. func.__doc__ = text
  138. return func
  139. return decorator
  140. @enforce_types
  141. def str_between(string: str, start: str, end: str=None) -> str:
  142. """(<abc>12345</def>, <abc>, </def>) -> 12345"""
  143. content = string.split(start, 1)[-1]
  144. if end is not None:
  145. content = content.rsplit(end, 1)[0]
  146. return content
  147. @enforce_types
  148. def parse_date(date: Any) -> Optional[datetime]:
  149. """Parse unix timestamps, iso format, and human-readable strings"""
  150. if date is None:
  151. return None
  152. if isinstance(date, datetime):
  153. if date.tzinfo is None:
  154. return date.replace(tzinfo=timezone.utc)
  155. assert date.tzinfo.utcoffset(datetime.now()).seconds == 0, 'Refusing to load a non-UTC date!'
  156. return date
  157. if isinstance(date, (float, int)):
  158. date = str(date)
  159. if isinstance(date, str):
  160. return dateparser(date, settings={'TIMEZONE': 'UTC'}).replace(tzinfo=timezone.utc)
  161. raise ValueError('Tried to parse invalid date! {}'.format(date))
  162. @enforce_types
  163. def download_url(url: str, timeout: int=None) -> str:
  164. """Download the contents of a remote url and return the text"""
  165. from .config import (
  166. TIMEOUT,
  167. CHECK_SSL_VALIDITY,
  168. WGET_USER_AGENT,
  169. COOKIES_FILE,
  170. )
  171. timeout = timeout or TIMEOUT
  172. session = requests.Session()
  173. if COOKIES_FILE and Path(COOKIES_FILE).is_file():
  174. cookie_jar = http.cookiejar.MozillaCookieJar(COOKIES_FILE)
  175. cookie_jar.load(ignore_discard=True, ignore_expires=True)
  176. for cookie in cookie_jar:
  177. session.cookies.set(cookie.name, cookie.value, domain=cookie.domain, path=cookie.path)
  178. response = session.get(
  179. url,
  180. headers={'User-Agent': WGET_USER_AGENT},
  181. verify=CHECK_SSL_VALIDITY,
  182. timeout=timeout,
  183. )
  184. content_type = response.headers.get('Content-Type', '')
  185. encoding = http_content_type_encoding(content_type) or html_body_declared_encoding(response.text)
  186. if encoding is not None:
  187. response.encoding = encoding
  188. try:
  189. return response.text
  190. except UnicodeDecodeError:
  191. # if response is non-test (e.g. image or other binary files), just return the filename instead
  192. return url.rsplit('/', 1)[-1]
  193. @enforce_types
  194. def get_headers(url: str, timeout: int=None) -> str:
  195. """Download the contents of a remote url and return the headers"""
  196. from .config import TIMEOUT, CHECK_SSL_VALIDITY, WGET_USER_AGENT
  197. timeout = timeout or TIMEOUT
  198. try:
  199. response = requests.head(
  200. url,
  201. headers={'User-Agent': WGET_USER_AGENT},
  202. verify=CHECK_SSL_VALIDITY,
  203. timeout=timeout,
  204. allow_redirects=True,
  205. )
  206. if response.status_code >= 400:
  207. raise RequestException
  208. except ReadTimeout:
  209. raise
  210. except RequestException:
  211. response = requests.get(
  212. url,
  213. headers={'User-Agent': WGET_USER_AGENT},
  214. verify=CHECK_SSL_VALIDITY,
  215. timeout=timeout,
  216. stream=True
  217. )
  218. return pyjson.dumps(
  219. {
  220. 'URL': url,
  221. 'Status-Code': response.status_code,
  222. 'Elapsed': response.elapsed.total_seconds()*1000,
  223. 'Encoding': str(response.encoding),
  224. 'Apparent-Encoding': response.apparent_encoding,
  225. **dict(response.headers),
  226. },
  227. indent=4,
  228. )
  229. @enforce_types
  230. def chrome_args(**options) -> List[str]:
  231. """helper to build up a chrome shell command with arguments"""
  232. # Chrome CLI flag documentation: https://peter.sh/experiments/chromium-command-line-switches/
  233. from .config import (
  234. CHROME_OPTIONS,
  235. CHROME_VERSION,
  236. CHROME_EXTRA_ARGS,
  237. )
  238. options = {**CHROME_OPTIONS, **options}
  239. if not options['CHROME_BINARY']:
  240. raise Exception('Could not find any CHROME_BINARY installed on your system')
  241. cmd_args = [options['CHROME_BINARY']]
  242. cmd_args += CHROME_EXTRA_ARGS
  243. if options['CHROME_HEADLESS']:
  244. cmd_args += ("--headless=new",) # expects chrome version >= 111
  245. if not options['CHROME_SANDBOX']:
  246. # assume this means we are running inside a docker container
  247. # in docker, GPU support is limited, sandboxing is unecessary,
  248. # and SHM is limited to 64MB by default (which is too low to be usable).
  249. cmd_args += (
  250. "--no-sandbox",
  251. "--no-zygote",
  252. "--disable-dev-shm-usage",
  253. "--disable-software-rasterizer",
  254. "--run-all-compositor-stages-before-draw",
  255. "--hide-scrollbars",
  256. "--autoplay-policy=no-user-gesture-required",
  257. "--no-first-run",
  258. "--use-fake-ui-for-media-stream",
  259. "--use-fake-device-for-media-stream",
  260. "--disable-sync",
  261. # "--password-store=basic",
  262. )
  263. # disable automatic updating when running headless, as there's no user to see the upgrade prompts
  264. cmd_args += ("--simulate-outdated-no-au='Tue, 31 Dec 2099 23:59:59 GMT'",)
  265. # set window size for screenshot/pdf/etc. rendering
  266. cmd_args += ('--window-size={}'.format(options['RESOLUTION']),)
  267. if not options['CHECK_SSL_VALIDITY']:
  268. cmd_args += ('--disable-web-security', '--ignore-certificate-errors')
  269. if options['CHROME_USER_AGENT']:
  270. cmd_args += ('--user-agent={}'.format(options['CHROME_USER_AGENT']),)
  271. if options['CHROME_TIMEOUT']:
  272. cmd_args += ('--timeout={}'.format(options['CHROME_TIMEOUT'] * 1000),)
  273. if options['CHROME_USER_DATA_DIR']:
  274. cmd_args.append('--user-data-dir={}'.format(options['CHROME_USER_DATA_DIR']))
  275. cmd_args.append('--profile-directory=Default')
  276. return dedupe(cmd_args)
  277. def chrome_cleanup():
  278. """
  279. Cleans up any state or runtime files that chrome leaves behind when killed by
  280. a timeout or other error
  281. """
  282. from .config import IN_DOCKER
  283. if IN_DOCKER and lexists("/home/archivebox/.config/chromium/SingletonLock"):
  284. remove_file("/home/archivebox/.config/chromium/SingletonLock")
  285. @enforce_types
  286. def ansi_to_html(text: str) -> str:
  287. """
  288. Based on: https://stackoverflow.com/questions/19212665/python-converting-ansi-color-codes-to-html
  289. """
  290. from .config import COLOR_DICT
  291. TEMPLATE = '<span style="color: rgb{}"><br>'
  292. text = text.replace('[m', '</span>')
  293. def single_sub(match):
  294. argsdict = match.groupdict()
  295. if argsdict['arg_3'] is None:
  296. if argsdict['arg_2'] is None:
  297. _, color = 0, argsdict['arg_1']
  298. else:
  299. _, color = argsdict['arg_1'], argsdict['arg_2']
  300. else:
  301. _, color = argsdict['arg_3'], argsdict['arg_2']
  302. return TEMPLATE.format(COLOR_DICT[color][0])
  303. return COLOR_REGEX.sub(single_sub, text)
  304. @enforce_types
  305. def dedupe(options: List[str]) -> List[str]:
  306. """
  307. Deduplicates the given options. Options that come later clobber earlier
  308. conflicting options.
  309. """
  310. deduped = {}
  311. for option in options:
  312. deduped[option.split('=')[0]] = option
  313. return list(deduped.values())
  314. class AttributeDict(dict):
  315. """Helper to allow accessing dict values via Example.key or Example['key']"""
  316. def __init__(self, *args, **kwargs):
  317. super().__init__(*args, **kwargs)
  318. # Recursively convert nested dicts to AttributeDicts (optional):
  319. # for key, val in self.items():
  320. # if isinstance(val, dict) and type(val) is not AttributeDict:
  321. # self[key] = AttributeDict(val)
  322. def __getattr__(self, attr: str) -> Any:
  323. return dict.__getitem__(self, attr)
  324. def __setattr__(self, attr: str, value: Any) -> None:
  325. return dict.__setitem__(self, attr, value)
  326. class ExtendedEncoder(pyjson.JSONEncoder):
  327. """
  328. Extended json serializer that supports serializing several model
  329. fields and objects
  330. """
  331. def default(self, obj):
  332. cls_name = obj.__class__.__name__
  333. if hasattr(obj, '_asdict'):
  334. return obj._asdict()
  335. elif isinstance(obj, bytes):
  336. return obj.decode()
  337. elif isinstance(obj, datetime):
  338. return obj.isoformat()
  339. elif isinstance(obj, Exception):
  340. return '{}: {}'.format(obj.__class__.__name__, obj)
  341. elif isinstance(obj, Path):
  342. return str(obj)
  343. elif cls_name in ('dict_items', 'dict_keys', 'dict_values'):
  344. return tuple(obj)
  345. return pyjson.JSONEncoder.default(self, obj)
  346. ### URL PARSING TESTS / ASSERTIONS
  347. # Check that plain text regex URL parsing works as expected
  348. # this is last-line-of-defense to make sure the URL_REGEX isn't
  349. # misbehaving due to some OS-level or environment level quirks (e.g. regex engine / cpython / locale differences)
  350. # the consequences of bad URL parsing could be disastrous and lead to many
  351. # incorrect/badly parsed links being added to the archive, so this is worth the cost of checking
  352. assert fix_url_from_markdown('http://example.com/a(b)c).x(y)z') == 'http://example.com/a(b)c'
  353. assert fix_url_from_markdown('https://wikipedia.org/en/some_article_(Disambiguation).html?abc=def).link(with)_trailingtext') == 'https://wikipedia.org/en/some_article_(Disambiguation).html?abc=def'
  354. URL_REGEX_TESTS = [
  355. ('https://example.com', ['https://example.com']),
  356. ('http://abc-file234example.com/abc?def=abc&23423=sdfsdf#abc=234&234=a234', ['http://abc-file234example.com/abc?def=abc&23423=sdfsdf#abc=234&234=a234']),
  357. ('https://twitter.com/share?url=https://akaao.success-corp.co.jp&text=ア@サ!ト&hashtags=ア%オ,元+ア.ア-オ_イ*シ$ロ abc', ['https://twitter.com/share?url=https://akaao.success-corp.co.jp&text=ア@サ!ト&hashtags=ア%オ,元+ア.ア-オ_イ*シ$ロ', 'https://akaao.success-corp.co.jp&text=ア@サ!ト&hashtags=ア%オ,元+ア.ア-オ_イ*シ$ロ']),
  358. ('<a href="https://twitter.com/share#url=https://akaao.success-corp.co.jp&text=ア@サ!ト?hashtags=ア%オ,元+ア&abc=.ア-オ_イ*シ$ロ"> abc', ['https://twitter.com/share#url=https://akaao.success-corp.co.jp&text=ア@サ!ト?hashtags=ア%オ,元+ア&abc=.ア-オ_イ*シ$ロ', 'https://akaao.success-corp.co.jp&text=ア@サ!ト?hashtags=ア%オ,元+ア&abc=.ア-オ_イ*シ$ロ']),
  359. ('///a', []),
  360. ('http://', []),
  361. ('http://../', ['http://../']),
  362. ('http://-error-.invalid/', ['http://-error-.invalid/']),
  363. ('https://a(b)c+1#2?3&4/', ['https://a(b)c+1#2?3&4/']),
  364. ('http://उदाहरण.परीक्षा', ['http://उदाहरण.परीक्षा']),
  365. ('http://例子.测试', ['http://例子.测试']),
  366. ('http://➡.ws/䨹 htps://abc.1243?234', ['http://➡.ws/䨹']),
  367. ('http://⌘.ws">https://exa+mple.com//:abc ', ['http://⌘.ws', 'https://exa+mple.com//:abc']),
  368. ('http://مثال.إختبار/abc?def=ت&ب=abc#abc=234', ['http://مثال.إختبار/abc?def=ت&ب=abc#abc=234']),
  369. ('http://-.~_!$&()*+,;=:%40:80%2f::::::@example.c\'om', ['http://-.~_!$&()*+,;=:%40:80%2f::::::@example.c']),
  370. ('http://us:[email protected]:42/http://ex.co:19/a?_d=4#-a=2.3', ['http://us:[email protected]:42/http://ex.co:19/a?_d=4#-a=2.3', 'http://ex.co:19/a?_d=4#-a=2.3']),
  371. ('http://code.google.com/events/#&product=browser', ['http://code.google.com/events/#&product=browser']),
  372. ('http://foo.bar?q=Spaces should be encoded', ['http://foo.bar?q=Spaces']),
  373. ('http://foo.com/blah_(wikipedia)#c(i)t[e]-1', ['http://foo.com/blah_(wikipedia)#c(i)t']),
  374. ('http://foo.com/(something)?after=parens', ['http://foo.com/(something)?after=parens']),
  375. ('http://foo.com/unicode_(✪)_in_parens) abc', ['http://foo.com/unicode_(✪)_in_parens']),
  376. ('http://foo.bar/?q=Test%20URL-encoded%20stuff', ['http://foo.bar/?q=Test%20URL-encoded%20stuff']),
  377. ('[xyz](http://a.b/?q=(Test)%20U)RL-encoded%20stuff', ['http://a.b/?q=(Test)%20U']),
  378. ('[xyz](http://a.b/?q=(Test)%20U)-ab https://abc+123', ['http://a.b/?q=(Test)%20U', 'https://abc+123']),
  379. ('[xyz](http://a.b/?q=(Test)%20U) https://a(b)c+12)3', ['http://a.b/?q=(Test)%20U', 'https://a(b)c+12']),
  380. ('[xyz](http://a.b/?q=(Test)a\nabchttps://a(b)c+12)3', ['http://a.b/?q=(Test)a', 'https://a(b)c+12']),
  381. ('http://foo.bar/?q=Test%20URL-encoded%20stuff', ['http://foo.bar/?q=Test%20URL-encoded%20stuff']),
  382. ]
  383. for urls_str, expected_url_matches in URL_REGEX_TESTS:
  384. url_matches = list(find_all_urls(urls_str))
  385. assert url_matches == expected_url_matches, 'FAILED URL_REGEX CHECK!'
  386. # More test cases
  387. _test_url_strs = {
  388. 'example.com': 0,
  389. '/example.com': 0,
  390. '//example.com': 0,
  391. ':/example.com': 0,
  392. '://example.com': 0,
  393. 'htt://example8.com': 0,
  394. '/htt://example.com': 0,
  395. 'https://example': 1,
  396. 'https://localhost/2345': 1,
  397. 'https://localhost:1234/123': 1,
  398. '://': 0,
  399. 'https://': 0,
  400. 'http://': 0,
  401. 'ftp://': 0,
  402. 'ftp://example.com': 0,
  403. 'https://example.com': 1,
  404. 'https://example.com/': 1,
  405. 'https://a.example.com': 1,
  406. 'https://a.example.com/': 1,
  407. 'https://a.example.com/what/is/happening.html': 1,
  408. 'https://a.example.com/what/ís/happening.html': 1,
  409. 'https://a.example.com/what/is/happening.html?what=1&2%20b#höw-about-this=1a': 1,
  410. 'https://a.example.com/what/is/happéning/?what=1&2%20b#how-aboüt-this=1a': 1,
  411. 'HTtpS://a.example.com/what/is/happening/?what=1&2%20b#how-about-this=1af&2f%20b': 1,
  412. 'https://example.com/?what=1#how-about-this=1&2%20baf': 1,
  413. 'https://example.com?what=1#how-about-this=1&2%20baf': 1,
  414. '<test>http://example7.com</test>': 1,
  415. 'https://<test>': 0,
  416. 'https://[test]': 0,
  417. 'http://"test"': 0,
  418. 'http://\'test\'': 0,
  419. '[https://example8.com/what/is/this.php?what=1]': 1,
  420. '[and http://example9.com?what=1&other=3#and-thing=2]': 1,
  421. '<what>https://example10.com#and-thing=2 "</about>': 1,
  422. 'abc<this["https://example11.com/what/is#and-thing=2?whoami=23&where=1"]that>def': 1,
  423. 'sdflkf[what](https://example12.com/who/what.php?whoami=1#whatami=2)?am=hi': 1,
  424. '<or>http://examplehttp://15.badc</that>': 2,
  425. 'https://a.example.com/one.html?url=http://example.com/inside/of/another?=http://': 2,
  426. '[https://a.example.com/one.html?url=http://example.com/inside/of/another?=](http://a.example.com)': 3,
  427. }
  428. for url_str, num_urls in _test_url_strs.items():
  429. assert len(list(find_all_urls(url_str))) == num_urls, (
  430. f'{url_str} does not contain {num_urls} urls')