htmlcmp 2.4.3__tar.gz → 2.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/PKG-INFO +18 -1
  2. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/README.md +17 -0
  3. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/pyproject.toml +1 -1
  4. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/common.py +11 -3
  5. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/compare_output_cli.py +32 -11
  6. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/compare_output_server.py +16 -3
  7. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/comparison_worker.py +3 -2
  8. htmlcmp-2.6.0/src/htmlcmp/defaults.py +15 -0
  9. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/html_render_diff.py +100 -21
  10. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/tidy_output.py +3 -2
  11. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp.egg-info/PKG-INFO +18 -1
  12. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp.egg-info/SOURCES.txt +1 -0
  13. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/tests/test_compare_html_retries.py +1 -1
  14. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/tests/test_comparison_worker.py +3 -2
  15. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/tests/test_html_render_diff.py +44 -1
  16. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/setup.cfg +0 -0
  17. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/__init__.py +0 -0
  18. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/static/common.js +0 -0
  19. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/static/compare.js +0 -0
  20. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/static/index.js +0 -0
  21. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/static/style.css +0 -0
  22. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/templates/compare.html +0 -0
  23. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/templates/index.html +0 -0
  24. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp/templates/missing.html +0 -0
  25. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp.egg-info/dependency_links.txt +0 -0
  26. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp.egg-info/entry_points.txt +0 -0
  27. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp.egg-info/requires.txt +0 -0
  28. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/src/htmlcmp.egg-info/top_level.txt +0 -0
  29. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/tests/test_browser_transport.py +0 -0
  30. {htmlcmp-2.4.3 → htmlcmp-2.6.0}/tests/test_collect_tasks.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: htmlcmp
3
- Version: 2.4.3
3
+ Version: 2.6.0
4
4
  Summary: Compare HTML files by rendered output
5
5
  Author: Andreas Stefl
6
6
  Maintainer-email: Andreas Stefl <stefl.andreas@gmail.com>
@@ -30,12 +30,29 @@ Provides various entry points to run:
30
30
 
31
31
  Used for regression testing in https://github.com/opendocument-app/OpenDocument.core.
32
32
 
33
+ ## When a screenshot is taken
34
+
35
+ A page is screenshotted once it has stopped changing:
36
+
37
+ - the document has loaded and its web fonts have arrived
38
+ - no element carries `aria-busy="true"`, the WAI-ARIA way for a page that keeps
39
+ laying itself out after load to say it is not done yet
40
+ - finite animations, such as a fade-in, have finished; an infinite one is left
41
+ running
42
+ - two frames have been painted since
43
+
44
+ Waiting stops after 10 seconds, and the page is screenshotted as it is then.
45
+ `--settle-timeout` changes that limit in `compare-html`, `compare-html-server`
46
+ and `html-render-diff`.
47
+
33
48
  ## Browser timeouts in the CLI
34
49
 
35
50
  `compare-html --timeout 120` limits each browser comparison to 120 seconds,
36
51
  including browser startup, both screenshots, and any `--retries` of a pixel
37
52
  mismatch. The deadline starts when a worker takes the file, not while it waits
38
53
  in the queue. Use a larger positive value for especially expensive pages.
54
+ Each screenshot may wait up to `--settle-timeout` for its page, so keep
55
+ `--timeout` above twice that times one more than `--retries`.
39
56
  The same value configures WebDriver's HTTP and page-load timeouts, so increasing
40
57
  the deadline is not cut short by Selenium's default 120-second HTTP timeout.
41
58
 
@@ -10,12 +10,29 @@ Provides various entry points to run:
10
10
 
11
11
  Used for regression testing in https://github.com/opendocument-app/OpenDocument.core.
12
12
 
13
+ ## When a screenshot is taken
14
+
15
+ A page is screenshotted once it has stopped changing:
16
+
17
+ - the document has loaded and its web fonts have arrived
18
+ - no element carries `aria-busy="true"`, the WAI-ARIA way for a page that keeps
19
+ laying itself out after load to say it is not done yet
20
+ - finite animations, such as a fade-in, have finished; an infinite one is left
21
+ running
22
+ - two frames have been painted since
23
+
24
+ Waiting stops after 10 seconds, and the page is screenshotted as it is then.
25
+ `--settle-timeout` changes that limit in `compare-html`, `compare-html-server`
26
+ and `html-render-diff`.
27
+
13
28
  ## Browser timeouts in the CLI
14
29
 
15
30
  `compare-html --timeout 120` limits each browser comparison to 120 seconds,
16
31
  including browser startup, both screenshots, and any `--retries` of a pixel
17
32
  mismatch. The deadline starts when a worker takes the file, not while it waits
18
33
  in the queue. Use a larger positive value for especially expensive pages.
34
+ Each screenshot may wait up to `--settle-timeout` for its page, so keep
35
+ `--timeout` above twice that times one more than `--retries`.
19
36
  The same value configures WebDriver's HTTP and page-load timeouts, so increasing
20
37
  the deadline is not cut short by Selenium's default 120-second HTTP timeout.
21
38
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "htmlcmp"
3
- version = "2.4.3"
3
+ version = "2.6.0"
4
4
  description = "Compare HTML files by rendered output"
5
5
  classifiers = []
6
6
  authors = [
@@ -4,6 +4,7 @@ import logging
4
4
  import filecmp
5
5
  from pathlib import Path
6
6
 
7
+ from htmlcmp import defaults
7
8
  from htmlcmp.html_render_diff import get_browser, html_render_diff
8
9
 
9
10
  logger = logging.getLogger(__name__)
@@ -43,7 +44,12 @@ def compare_json(a: Path, b: Path) -> bool:
43
44
 
44
45
 
45
46
  def compare_html(
46
- a: Path, b: Path, browser=None, diff_output: Path = None, retries: int = 1
47
+ a: Path,
48
+ b: Path,
49
+ browser=None,
50
+ diff_output: Path = None,
51
+ retries: int = defaults.RETRIES,
52
+ settle_timeout: float = defaults.SETTLE_TIMEOUT,
47
53
  ) -> bool:
48
54
  """Whether `a` and `b` render to the same pixels.
49
55
 
@@ -61,10 +67,12 @@ def compare_html(
61
67
  raise ValueError(f"retries must be a non-negative int, got {retries!r}")
62
68
 
63
69
  if browser is None:
64
- browser = get_browser("firefox")
70
+ browser = get_browser(defaults.DRIVER)
65
71
 
66
72
  for attempt in range(retries + 1):
67
- diff, (image_a, image_b) = html_render_diff(a, b, browser=browser)
73
+ diff, (image_a, image_b) = html_render_diff(
74
+ a, b, browser=browser, settle_timeout=settle_timeout
75
+ )
68
76
  if diff.getbbox() is None:
69
77
  return True
70
78
  logger.debug(
@@ -21,8 +21,13 @@ from rich.progress import (
21
21
  TimeRemainingColumn,
22
22
  )
23
23
 
24
+ from htmlcmp import defaults
24
25
  from htmlcmp.common import comparable_file, setup_logging
25
26
  from htmlcmp.comparison_worker import ComparisonExecutor
27
+ from htmlcmp.html_render_diff import (
28
+ add_settle_timeout_argument,
29
+ check_settle_timeout,
30
+ )
26
31
 
27
32
  logger = logging.getLogger(__name__)
28
33
 
@@ -31,7 +36,12 @@ class Task:
31
36
  """A single file comparison between the reference (A) and monitored (B) tree."""
32
37
 
33
38
  def __init__(
34
- self, rel: Path, a: Path, b: Path, diff_output: Path = None, retries: int = 1
39
+ self,
40
+ rel: Path,
41
+ a: Path,
42
+ b: Path,
43
+ diff_output: Path = None,
44
+ retries: int = defaults.RETRIES,
35
45
  ):
36
46
  self.rel = rel
37
47
  self.a = a
@@ -53,7 +63,11 @@ class Failure:
53
63
 
54
64
 
55
65
  def collect_tasks(
56
- a: Path, b: Path, rel: Path = Path(), diff_output: Path = None, retries: int = 1
66
+ a: Path,
67
+ b: Path,
68
+ rel: Path = Path(),
69
+ diff_output: Path = None,
70
+ retries: int = defaults.RETRIES,
57
71
  ) -> tuple[list[Task], list[Failure]]:
58
72
  """Walk both trees once and return (comparable tasks, structural failures).
59
73
 
@@ -227,10 +241,13 @@ def run(
227
241
  console: Console,
228
242
  live: bool,
229
243
  github: bool,
230
- timeout: float = 120.0,
244
+ timeout: float = defaults.TIMEOUT,
245
+ settle_timeout: float = defaults.SETTLE_TIMEOUT,
231
246
  ) -> int:
232
247
  if not math.isfinite(timeout) or timeout <= 0:
233
248
  raise ValueError("timeout must be a positive finite number")
249
+ if not math.isfinite(settle_timeout) or settle_timeout <= 0:
250
+ raise ValueError("settle_timeout must be a positive finite number")
234
251
  console.print(
235
252
  f"[bold]Comparing[/bold] {escape(str(a))} [dim]→[/dim] {escape(str(b))}"
236
253
  )
@@ -263,6 +280,7 @@ def run(
263
280
  t.b,
264
281
  diff_output=t.diff_output,
265
282
  retries=t.retries,
283
+ settle_timeout=settle_timeout,
266
284
  ): t
267
285
  for t in tasks
268
286
  }
@@ -288,9 +306,9 @@ def main():
288
306
  parser.add_argument(
289
307
  "--driver",
290
308
  choices=["chrome", "firefox", "none"],
291
- default="firefox",
309
+ default=defaults.DRIVER,
292
310
  help="Browser used to render HTML diffs; 'none' compares only "
293
- "JSON and byte-identical files (default: firefox)",
311
+ "JSON and byte-identical files (default: %(default)s)",
294
312
  )
295
313
  parser.add_argument(
296
314
  "--diff-output", type=Path, help="Directory to write diff images for mismatches"
@@ -299,8 +317,8 @@ def main():
299
317
  "-j",
300
318
  "--max-workers",
301
319
  type=int,
302
- default=1,
303
- help="Number of parallel comparison workers (default: 1)",
320
+ default=defaults.MAX_WORKERS,
321
+ help="Number of parallel comparison workers (default: %(default)s)",
304
322
  )
305
323
  parser.add_argument(
306
324
  "--no-progress",
@@ -317,17 +335,18 @@ def main():
317
335
  parser.add_argument(
318
336
  "--retries",
319
337
  type=int,
320
- default=1,
338
+ default=defaults.RETRIES,
321
339
  help="Re-render a mismatch this many times before reporting it "
322
- "(default: 1; 0 reports the first render)",
340
+ "(default: %(default)s; 0 reports the first render)",
323
341
  )
324
342
  parser.add_argument(
325
343
  "--timeout",
326
344
  type=float,
327
- default=120.0,
345
+ default=defaults.TIMEOUT,
328
346
  help="Deadline in seconds per browser comparison, including startup "
329
- "and mismatch retries (default: 120)",
347
+ "and mismatch retries (default: %(default)g)",
330
348
  )
349
+ add_settle_timeout_argument(parser)
331
350
  parser.add_argument("--log-file", type=Path, help="Path to log file")
332
351
  parser.add_argument(
333
352
  "--log-file-verbosity", type=int, help="Log file verbosity level"
@@ -335,6 +354,7 @@ def main():
335
354
  args = parser.parse_args()
336
355
  if not math.isfinite(args.timeout) or args.timeout <= 0:
337
356
  parser.error("--timeout must be a positive finite number")
357
+ check_settle_timeout(parser, args.settle_timeout)
338
358
 
339
359
  setup_logging(args.verbose, args.log_file, args.log_file_verbosity)
340
360
 
@@ -360,6 +380,7 @@ def main():
360
380
  live=live,
361
381
  github=github,
362
382
  timeout=args.timeout,
383
+ settle_timeout=args.settle_timeout,
363
384
  )
364
385
 
365
386
 
@@ -19,12 +19,18 @@ import watchdog.events
19
19
 
20
20
  from PIL import Image
21
21
 
22
+ from htmlcmp import defaults
22
23
  from htmlcmp.common import (
23
24
  comparable_file,
24
25
  compare_files,
25
26
  setup_logging,
26
27
  )
27
- from htmlcmp.html_render_diff import get_browser, html_render_diff
28
+ from htmlcmp.html_render_diff import (
29
+ add_settle_timeout_argument,
30
+ check_settle_timeout,
31
+ get_browser,
32
+ html_render_diff,
33
+ )
28
34
 
29
35
  logger = logging.getLogger(__name__)
30
36
 
@@ -33,6 +39,7 @@ class Config:
33
39
  path_a: Path = None
34
40
  path_b: Path = None
35
41
  driver: str = None
42
+ settle_timeout: float = defaults.SETTLE_TIMEOUT
36
43
  observer = None
37
44
  comparator = None
38
45
  browser = None
@@ -177,6 +184,7 @@ class Comparator:
177
184
  Config.path_a / path,
178
185
  Config.path_b / path,
179
186
  browser=browser,
187
+ settle_timeout=Config.settle_timeout,
180
188
  )
181
189
  except Exception:
182
190
  # A file may have vanished or failed to render between submission
@@ -374,7 +382,9 @@ class DiffCache:
374
382
 
375
383
  logger.debug(f"Rendering diff: {path}")
376
384
  with Config.browser_lock:
377
- diff, _ = html_render_diff(a, b, Config.browser)
385
+ diff, _ = html_render_diff(
386
+ a, b, Config.browser, settle_timeout=Config.settle_timeout
387
+ )
378
388
 
379
389
  width, height = diff.size
380
390
  bbox = diff.getbbox()
@@ -707,7 +717,7 @@ def main():
707
717
  parser.add_argument("ref", type=Path, help="Path to the reference directory")
708
718
  parser.add_argument("mon", type=Path, help="Path to the monitored directory")
709
719
  parser.add_argument("--driver", choices=["chrome", "firefox"])
710
- parser.add_argument("--max-workers", type=int, default=1)
720
+ parser.add_argument("--max-workers", type=int, default=defaults.MAX_WORKERS)
711
721
  parser.add_argument("--compare", action="store_true")
712
722
  parser.add_argument(
713
723
  "--host",
@@ -715,6 +725,7 @@ def main():
715
725
  help="Host/interface to bind the server to (default: 0.0.0.0)",
716
726
  )
717
727
  parser.add_argument("--port", type=int, default=5000)
728
+ add_settle_timeout_argument(parser)
718
729
  parser.add_argument(
719
730
  "-v",
720
731
  "--verbose",
@@ -731,12 +742,14 @@ def main():
731
742
  "--log-file-verbosity", type=int, help="Log file verbosity level"
732
743
  )
733
744
  args = parser.parse_args()
745
+ check_settle_timeout(parser, args.settle_timeout)
734
746
 
735
747
  setup_logging(args.verbose, args.log_file, args.log_file_verbosity)
736
748
 
737
749
  Config.path_a = args.ref
738
750
  Config.path_b = args.mon
739
751
  Config.driver = args.driver
752
+ Config.settle_timeout = args.settle_timeout
740
753
  Config.browser = (
741
754
  get_browser(driver=args.driver) if args.driver is not None else None
742
755
  )
@@ -9,6 +9,7 @@ from concurrent.futures import ThreadPoolExecutor
9
9
 
10
10
  import psutil
11
11
 
12
+ from htmlcmp import defaults
12
13
  from htmlcmp.common import compare_files
13
14
  from htmlcmp.html_render_diff import get_browser
14
15
 
@@ -42,7 +43,7 @@ def _compare_loop(connection, driver, timeout):
42
43
 
43
44
 
44
45
  class ComparisonWorker:
45
- def __init__(self, driver, timeout=120.0):
46
+ def __init__(self, driver, timeout=defaults.TIMEOUT):
46
47
  self.driver = driver
47
48
  self.timeout = timeout
48
49
  self._process = None
@@ -120,7 +121,7 @@ class ComparisonWorker:
120
121
 
121
122
 
122
123
  class ComparisonExecutor(ThreadPoolExecutor):
123
- def __init__(self, max_workers, driver, timeout=120.0):
124
+ def __init__(self, max_workers, driver, timeout=defaults.TIMEOUT):
124
125
  self._driver = driver
125
126
  self._timeout = timeout
126
127
  self._local = threading.local()
@@ -0,0 +1,15 @@
1
+ """Defaults shared by the library functions and the command line tools."""
2
+
3
+ #: Browser used to render HTML.
4
+ DRIVER = "firefox"
5
+ #: Browser window size in pixels; the height fits long pages in one shot.
6
+ MAX_WIDTH = 1000
7
+ MAX_HEIGHT = 10000
8
+ #: Parallel comparison or tidy workers.
9
+ MAX_WORKERS = 1
10
+ #: How many times a mismatch is rendered again before it is reported.
11
+ RETRIES = 1
12
+ #: Deadline in seconds per browser comparison.
13
+ TIMEOUT = 120.0
14
+ #: How long `settle` waits for the page, in seconds.
15
+ SETTLE_TIMEOUT = 10.0
@@ -4,6 +4,7 @@
4
4
  import sys
5
5
  import argparse
6
6
  import io
7
+ import math
7
8
  import time
8
9
  from pathlib import Path
9
10
 
@@ -14,6 +15,8 @@ from selenium.webdriver.common.by import By
14
15
  from selenium.webdriver.support import expected_conditions
15
16
  from selenium.webdriver.support.ui import WebDriverWait
16
17
 
18
+ from htmlcmp import defaults
19
+
17
20
 
18
21
  def to_url(path: str | Path) -> str:
19
22
  if not isinstance(path, (str, Path)):
@@ -27,7 +30,10 @@ def to_url(path: str | Path) -> str:
27
30
 
28
31
 
29
32
  def screenshot(
30
- browser: webdriver.Remote, url: str, settling_time: float = 0
33
+ browser: webdriver.Remote,
34
+ url: str,
35
+ settling_time: float = 0,
36
+ settle_timeout: float = defaults.SETTLE_TIMEOUT,
31
37
  ) -> Image.Image:
32
38
  if not isinstance(url, str):
33
39
  raise TypeError(f"Expected str, got {type(url)}")
@@ -47,37 +53,84 @@ def screenshot(
47
53
  lambda driver: driver.execute_script("return document.readyState") == "complete"
48
54
  )
49
55
 
50
- settle(browser, settling_time)
56
+ settle(browser, settling_time, settle_timeout)
51
57
 
52
58
  png = browser.get_screenshot_as_png()
53
59
  return Image.open(io.BytesIO(png))
54
60
 
55
61
 
56
- #: Waits for the fonts and then for two frames, and answers when both are done.
57
- #: `readyState` does not cover a web font: the load event fires while the face
58
- #: is still arriving, and the text is laid out again once it lands. Two frames
59
- #: then say a paint has happened rather than merely been asked for.
62
+ #: Waits until the page has stopped changing, then for two frames, and answers
63
+ #: when that is done or the deadline passes.
64
+ #:
65
+ #: - `readyState` does not cover a web font: the load event fires while the face
66
+ #: is still arriving, and the text is laid out again once it lands.
67
+ #: - A page that keeps laying itself out after load marks what is still changing
68
+ #: with `aria-busy="true"` (WAI-ARIA), and clears it once that is done.
69
+ #: - A finite animation, such as a fade-in, is waited out; an infinite one never
70
+ #: ends, so it is left running.
71
+ #:
72
+ #: Two frames then say a paint has happened rather than merely been asked for.
73
+ #: The checks repeat until one round finds nothing to wait for, since finishing
74
+ #: one kind of work can start another.
60
75
  _SETTLE = """
61
76
  const done = arguments[arguments.length - 1];
62
- const frames = () =>
63
- requestAnimationFrame(() => requestAnimationFrame(() => done(true)));
64
- (document.fonts ? document.fonts.ready : Promise.resolve()).then(frames, frames);
77
+ const deadline = performance.now() + arguments[0];
78
+ const left = () => Math.max(0, deadline - performance.now());
79
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
80
+ const frame = () => new Promise((resolve) => requestAnimationFrame(resolve));
81
+ const busy = () => document.querySelector('[aria-busy="true"]') !== null;
82
+ const animations = () =>
83
+ document.getAnimations
84
+ ? document.getAnimations().filter((animation) => {
85
+ const timing = animation.effect && animation.effect.getComputedTiming();
86
+ return (
87
+ animation.playState === "running" &&
88
+ timing !== null &&
89
+ timing.endTime !== Infinity
90
+ );
91
+ })
92
+ : [];
93
+ (async () => {
94
+ if (document.fonts) {
95
+ await Promise.race([document.fonts.ready.catch(() => {}), sleep(left())]);
96
+ }
97
+ for (;;) {
98
+ while (busy() && left() > 0) await sleep(50);
99
+ const running = animations();
100
+ if (running.length) {
101
+ await Promise.race([
102
+ Promise.all(running.map((a) => a.finished.catch(() => {}))),
103
+ sleep(left()),
104
+ ]);
105
+ }
106
+ await frame();
107
+ await frame();
108
+ if (left() === 0 || (!busy() && animations().length === 0)) break;
109
+ }
110
+ done(true);
111
+ })();
65
112
  """
66
113
 
67
114
 
68
- def settle(browser: webdriver.Remote, settling_time: float = 0) -> None:
115
+ def settle(
116
+ browser: webdriver.Remote,
117
+ settling_time: float = 0,
118
+ settle_timeout: float = defaults.SETTLE_TIMEOUT,
119
+ ) -> None:
69
120
  """Waits until the page has finished painting what it loaded.
70
121
 
71
122
  A screenshot taken before that catches the page mid-render, which is what
72
123
  makes an otherwise identical pair compare as different from one run to the
73
- next.
124
+ next. A page still busy at the deadline is screenshotted as it is.
74
125
  """
75
126
  if not isinstance(browser, webdriver.Remote):
76
127
  raise TypeError(f"Expected webdriver.Remote, got {type(browser)}")
77
128
 
78
- browser.set_script_timeout(10)
129
+ # WebDriver gets a second more than the page, so the page gives up first
130
+ # and the screenshot follows either way.
131
+ browser.set_script_timeout(settle_timeout + 1)
79
132
  try:
80
- browser.execute_async_script(_SETTLE)
133
+ browser.execute_async_script(_SETTLE, settle_timeout * 1000)
81
134
  except WebDriverException:
82
135
  # an old driver without async scripts still gets the sleep below
83
136
  pass
@@ -86,6 +139,21 @@ def settle(browser: webdriver.Remote, settling_time: float = 0) -> None:
86
139
  time.sleep(settling_time)
87
140
 
88
141
 
142
+ def add_settle_timeout_argument(parser: argparse.ArgumentParser) -> None:
143
+ parser.add_argument(
144
+ "--settle-timeout",
145
+ type=float,
146
+ default=defaults.SETTLE_TIMEOUT,
147
+ help="Seconds to wait for a page to settle before its screenshot is "
148
+ "taken as it is (default: %(default)g)",
149
+ )
150
+
151
+
152
+ def check_settle_timeout(parser: argparse.ArgumentParser, value: float) -> None:
153
+ if not math.isfinite(value) or value <= 0:
154
+ parser.error("--settle-timeout must be a positive finite number")
155
+
156
+
89
157
  def content_bottom(image: Image.Image) -> int:
90
158
  """Row just below the last pixel that differs from the page background.
91
159
 
@@ -101,8 +169,8 @@ def content_bottom(image: Image.Image) -> int:
101
169
 
102
170
  def get_browser(
103
171
  driver: str,
104
- max_width: int = 1000,
105
- max_height: int = 10000,
172
+ max_width: int = defaults.MAX_WIDTH,
173
+ max_height: int = defaults.MAX_HEIGHT,
106
174
  *,
107
175
  timeout: float | None = None,
108
176
  ) -> webdriver.Remote:
@@ -139,6 +207,7 @@ def html_render_diff(
139
207
  b: str | Path,
140
208
  browser: webdriver.Remote,
141
209
  browser_b: webdriver.Remote = None,
210
+ settle_timeout: float = defaults.SETTLE_TIMEOUT,
142
211
  ) -> tuple[Image.Image, tuple[Image.Image, Image.Image]]:
143
212
  if not isinstance(a, (str, Path)) or not isinstance(b, (str, Path)):
144
213
  raise TypeError("Both a and b must be str or Path instances")
@@ -149,8 +218,12 @@ def html_render_diff(
149
218
  elif not isinstance(browser_b, webdriver.Remote):
150
219
  raise TypeError(f"Expected webdriver.Remote, got {type(browser_b)}")
151
220
 
152
- image_a = screenshot(browser, to_url(a)).convert("RGB")
153
- image_b = screenshot(browser_b, to_url(b)).convert("RGB")
221
+ image_a = screenshot(browser, to_url(a), settle_timeout=settle_timeout).convert(
222
+ "RGB"
223
+ )
224
+ image_b = screenshot(browser_b, to_url(b), settle_timeout=settle_timeout).convert(
225
+ "RGB"
226
+ )
154
227
 
155
228
  # The browser window is deliberately very tall so that long pages fit into
156
229
  # one screenshot, which leaves most shots mostly empty. That empty tail is
@@ -169,13 +242,19 @@ def main():
169
242
  parser = argparse.ArgumentParser()
170
243
  parser.add_argument("a", type=Path, help="Path to the first HTML file")
171
244
  parser.add_argument("b", type=Path, help="Path to the second HTML file")
172
- parser.add_argument("--driver", choices=["chrome", "firefox"], default="firefox")
173
- parser.add_argument("--max-width", type=int, default=1000)
174
- parser.add_argument("--max-height", type=int, default=10000)
245
+ parser.add_argument(
246
+ "--driver", choices=["chrome", "firefox"], default=defaults.DRIVER
247
+ )
248
+ parser.add_argument("--max-width", type=int, default=defaults.MAX_WIDTH)
249
+ parser.add_argument("--max-height", type=int, default=defaults.MAX_HEIGHT)
250
+ add_settle_timeout_argument(parser)
175
251
  args = parser.parse_args()
252
+ check_settle_timeout(parser, args.settle_timeout)
176
253
 
177
254
  browser = get_browser(args.driver, args.max_width, args.max_height)
178
- diff, _ = html_render_diff(args.a, args.b, browser)
255
+ diff, _ = html_render_diff(
256
+ args.a, args.b, browser, settle_timeout=args.settle_timeout
257
+ )
179
258
  browser.quit()
180
259
  bounding_box = diff.getbbox()
181
260
 
@@ -23,6 +23,7 @@ from rich.progress import (
23
23
  TimeRemainingColumn,
24
24
  )
25
25
 
26
+ from htmlcmp import defaults
26
27
  from htmlcmp.common import setup_logging
27
28
 
28
29
  logger = logging.getLogger(__name__)
@@ -314,8 +315,8 @@ def main():
314
315
  "-j",
315
316
  "--max-workers",
316
317
  type=int,
317
- default=1,
318
- help="Number of parallel tidy workers (default: 1)",
318
+ default=defaults.MAX_WORKERS,
319
+ help="Number of parallel tidy workers (default: %(default)s)",
319
320
  )
320
321
  parser.add_argument(
321
322
  "--details",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: htmlcmp
3
- Version: 2.4.3
3
+ Version: 2.6.0
4
4
  Summary: Compare HTML files by rendered output
5
5
  Author: Andreas Stefl
6
6
  Maintainer-email: Andreas Stefl <stefl.andreas@gmail.com>
@@ -30,12 +30,29 @@ Provides various entry points to run:
30
30
 
31
31
  Used for regression testing in https://github.com/opendocument-app/OpenDocument.core.
32
32
 
33
+ ## When a screenshot is taken
34
+
35
+ A page is screenshotted once it has stopped changing:
36
+
37
+ - the document has loaded and its web fonts have arrived
38
+ - no element carries `aria-busy="true"`, the WAI-ARIA way for a page that keeps
39
+ laying itself out after load to say it is not done yet
40
+ - finite animations, such as a fade-in, have finished; an infinite one is left
41
+ running
42
+ - two frames have been painted since
43
+
44
+ Waiting stops after 10 seconds, and the page is screenshotted as it is then.
45
+ `--settle-timeout` changes that limit in `compare-html`, `compare-html-server`
46
+ and `html-render-diff`.
47
+
33
48
  ## Browser timeouts in the CLI
34
49
 
35
50
  `compare-html --timeout 120` limits each browser comparison to 120 seconds,
36
51
  including browser startup, both screenshots, and any `--retries` of a pixel
37
52
  mismatch. The deadline starts when a worker takes the file, not while it waits
38
53
  in the queue. Use a larger positive value for especially expensive pages.
54
+ Each screenshot may wait up to `--settle-timeout` for its page, so keep
55
+ `--timeout` above twice that times one more than `--retries`.
39
56
  The same value configures WebDriver's HTTP and page-load timeouts, so increasing
40
57
  the deadline is not cut short by Selenium's default 120-second HTTP timeout.
41
58
 
@@ -5,6 +5,7 @@ src/htmlcmp/common.py
5
5
  src/htmlcmp/compare_output_cli.py
6
6
  src/htmlcmp/compare_output_server.py
7
7
  src/htmlcmp/comparison_worker.py
8
+ src/htmlcmp/defaults.py
8
9
  src/htmlcmp/html_render_diff.py
9
10
  src/htmlcmp/tidy_output.py
10
11
  src/htmlcmp.egg-info/PKG-INFO
@@ -25,7 +25,7 @@ def images(same: bool):
25
25
  def renderer(pattern, calls):
26
26
  """Stands in for `html_render_diff`, answering `pattern` in turn."""
27
27
 
28
- def render(a, b, browser=None):
28
+ def render(a, b, browser=None, settle_timeout=None):
29
29
  calls.append((a, b))
30
30
  return images(pattern[min(len(calls) - 1, len(pattern) - 1)])
31
31
 
@@ -168,11 +168,12 @@ def test_startup_failure_is_reported_per_file(tmp_path):
168
168
  worker.close()
169
169
 
170
170
 
171
+ @pytest.mark.parametrize("flag", ["--timeout", "--settle-timeout"])
171
172
  @pytest.mark.parametrize("timeout", ["0", "-1", "nan", "inf"])
172
- def test_cli_rejects_invalid_deadline(monkeypatch, timeout):
173
+ def test_cli_rejects_invalid_deadline(monkeypatch, flag, timeout):
173
174
  from htmlcmp.compare_output_cli import main
174
175
 
175
- monkeypatch.setattr(sys, "argv", ["compare-html", "a", "b", "--timeout", timeout])
176
+ monkeypatch.setattr(sys, "argv", ["compare-html", "a", "b", flag, timeout])
176
177
  with pytest.raises(SystemExit) as exc:
177
178
  main()
178
179
  assert exc.value.code == 2
@@ -2,7 +2,14 @@ import pytest
2
2
  from pathlib import Path
3
3
  import shutil
4
4
 
5
- from htmlcmp.html_render_diff import to_url, get_browser, html_render_diff
5
+ import time
6
+
7
+ from htmlcmp.html_render_diff import (
8
+ to_url,
9
+ get_browser,
10
+ html_render_diff,
11
+ screenshot,
12
+ )
6
13
 
7
14
 
8
15
  def test_to_url():
@@ -49,3 +56,39 @@ def test_html_render_diff():
49
56
  assert diff.getbbox() is not None
50
57
  finally:
51
58
  browser.quit()
59
+
60
+
61
+ @pytest.mark.parametrize("driver", ["chrome", "firefox"])
62
+ @pytest.mark.parametrize("page", ["busy.html", "animated.html"])
63
+ def test_screenshot_waits_for_the_page_to_settle(driver, page):
64
+ here = Path(__file__).parent
65
+ browser = get_browser(driver)
66
+ try:
67
+ diff, _ = html_render_diff(here / page, here / "settled.html", browser)
68
+ assert diff.getbbox() is None
69
+ finally:
70
+ browser.quit()
71
+
72
+
73
+ @pytest.mark.parametrize("driver", ["chrome", "firefox"])
74
+ def test_screenshot_leaves_an_infinite_animation_running(driver):
75
+ browser = get_browser(driver)
76
+ try:
77
+ started = time.monotonic()
78
+ screenshot(browser, to_url(Path(__file__).parent / "spinning.html"))
79
+ assert time.monotonic() - started < 5
80
+ finally:
81
+ browser.quit()
82
+
83
+
84
+ @pytest.mark.parametrize("driver", ["chrome", "firefox"])
85
+ def test_screenshot_stops_waiting_at_the_settle_timeout(driver):
86
+ here = Path(__file__).parent
87
+ browser = get_browser(driver)
88
+ try:
89
+ diff, _ = html_render_diff(
90
+ here / "busy.html", here / "settled.html", browser, settle_timeout=0.3
91
+ )
92
+ assert diff.getbbox() is not None
93
+ finally:
94
+ browser.quit()
File without changes
File without changes