htmlcmp 2.4.0__tar.gz → 2.4.2__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 (29) hide show
  1. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/PKG-INFO +21 -1
  2. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/README.md +19 -0
  3. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/pyproject.toml +2 -1
  4. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp/compare_output_cli.py +38 -52
  5. htmlcmp-2.4.2/src/htmlcmp/comparison_worker.py +147 -0
  6. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp/html_render_diff.py +3 -0
  7. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp.egg-info/PKG-INFO +21 -1
  8. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp.egg-info/SOURCES.txt +4 -0
  9. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp.egg-info/requires.txt +1 -0
  10. htmlcmp-2.4.2/tests/test_browser_transport.py +51 -0
  11. htmlcmp-2.4.2/tests/test_collect_tasks.py +30 -0
  12. htmlcmp-2.4.2/tests/test_comparison_worker.py +164 -0
  13. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/tests/test_html_render_diff.py +8 -4
  14. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/setup.cfg +0 -0
  15. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp/__init__.py +0 -0
  16. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp/common.py +0 -0
  17. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp/compare_output_server.py +0 -0
  18. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp/static/common.js +0 -0
  19. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp/static/compare.js +0 -0
  20. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp/static/index.js +0 -0
  21. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp/static/style.css +0 -0
  22. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp/templates/compare.html +0 -0
  23. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp/templates/index.html +0 -0
  24. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp/templates/missing.html +0 -0
  25. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp/tidy_output.py +0 -0
  26. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp.egg-info/dependency_links.txt +0 -0
  27. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp.egg-info/entry_points.txt +0 -0
  28. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/src/htmlcmp.egg-info/top_level.txt +0 -0
  29. {htmlcmp-2.4.0 → htmlcmp-2.4.2}/tests/test_compare_html_retries.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: htmlcmp
3
- Version: 2.4.0
3
+ Version: 2.4.2
4
4
  Summary: Compare HTML files by rendered output
5
5
  Author: Andreas Stefl
6
6
  Maintainer-email: Andreas Stefl <stefl.andreas@gmail.com>
@@ -16,6 +16,7 @@ Requires-Dist: selenium
16
16
  Requires-Dist: flask
17
17
  Requires-Dist: watchdog
18
18
  Requires-Dist: rich
19
+ Requires-Dist: psutil
19
20
 
20
21
  # htmlcmp
21
22
 
@@ -29,6 +30,25 @@ Provides various entry points to run:
29
30
 
30
31
  Used for regression testing in https://github.com/opendocument-app/OpenDocument.core.
31
32
 
33
+ ## Browser timeouts in the CLI
34
+
35
+ `compare-html --timeout 120` limits each browser comparison to 120 seconds,
36
+ including browser startup, both screenshots, and any `--retries` of a pixel
37
+ mismatch. The deadline starts when a worker takes the file, not while it waits
38
+ in the queue. Use a larger positive value for especially expensive pages.
39
+
40
+ A timeout is reported as an error and makes the command exit unsuccessfully.
41
+ The worker and its browser processes are discarded; the next file gets a fresh
42
+ browser. Successful comparisons reuse their browser. Shutdown also has bounded
43
+ cleanup, so an unresponsive Selenium `quit()` cannot block the command forever.
44
+ Cleanup can take a few seconds beyond the comparison deadline.
45
+
46
+ WebDriver HTTP requests are not automatically retried. `--retries` still
47
+ rechecks visual mismatches; it does not repeat a timed-out browser command.
48
+ This does not change the pixel comparison or hide errors from slow renderers.
49
+ The per-comparison deadline applies to `compare-html`, not the interactive
50
+ `compare-html-server`.
51
+
32
52
  ## Reviewing differences in the browser
33
53
 
34
54
  `compare-html-server` serves two pages:
@@ -10,6 +10,25 @@ 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
+ ## Browser timeouts in the CLI
14
+
15
+ `compare-html --timeout 120` limits each browser comparison to 120 seconds,
16
+ including browser startup, both screenshots, and any `--retries` of a pixel
17
+ mismatch. The deadline starts when a worker takes the file, not while it waits
18
+ in the queue. Use a larger positive value for especially expensive pages.
19
+
20
+ A timeout is reported as an error and makes the command exit unsuccessfully.
21
+ The worker and its browser processes are discarded; the next file gets a fresh
22
+ browser. Successful comparisons reuse their browser. Shutdown also has bounded
23
+ cleanup, so an unresponsive Selenium `quit()` cannot block the command forever.
24
+ Cleanup can take a few seconds beyond the comparison deadline.
25
+
26
+ WebDriver HTTP requests are not automatically retried. `--retries` still
27
+ rechecks visual mismatches; it does not repeat a timed-out browser command.
28
+ This does not change the pixel comparison or hide errors from slow renderers.
29
+ The per-comparison deadline applies to `compare-html`, not the interactive
30
+ `compare-html-server`.
31
+
13
32
  ## Reviewing differences in the browser
14
33
 
15
34
  `compare-html-server` serves two pages:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "htmlcmp"
3
- version = "2.4.0"
3
+ version = "2.4.2"
4
4
  description = "Compare HTML files by rendered output"
5
5
  classifiers = []
6
6
  authors = [
@@ -18,6 +18,7 @@ dependencies = [
18
18
  "flask",
19
19
  "watchdog",
20
20
  "rich",
21
+ "psutil",
21
22
  ]
22
23
 
23
24
  [project.scripts]
@@ -5,9 +5,9 @@ import os
5
5
  import sys
6
6
  import logging
7
7
  import argparse
8
- import threading
8
+ import math
9
9
  from pathlib import Path
10
- from concurrent.futures import ThreadPoolExecutor, as_completed
10
+ from concurrent.futures import as_completed
11
11
 
12
12
  from rich.console import Console
13
13
  from rich.markup import escape
@@ -21,16 +21,12 @@ from rich.progress import (
21
21
  TimeRemainingColumn,
22
22
  )
23
23
 
24
- from htmlcmp.html_render_diff import get_browser
25
- from htmlcmp.common import comparable_file, compare_files, setup_logging
24
+ from htmlcmp.common import comparable_file, setup_logging
25
+ from htmlcmp.comparison_worker import ComparisonExecutor
26
26
 
27
27
  logger = logging.getLogger(__name__)
28
28
 
29
29
 
30
- class Config:
31
- thread_local = threading.local()
32
-
33
-
34
30
  class Task:
35
31
  """A single file comparison between the reference (A) and monitored (B) tree."""
36
32
 
@@ -57,21 +53,19 @@ class Failure:
57
53
 
58
54
 
59
55
  def collect_tasks(
60
- a: Path, b: Path, root: Path = None, diff_output: Path = None, retries: int = 1
56
+ a: Path, b: Path, rel: Path = Path(), diff_output: Path = None, retries: int = 1
61
57
  ) -> tuple[list[Task], list[Failure]]:
62
58
  """Walk both trees once and return (comparable tasks, structural failures).
63
59
 
64
60
  Structural failures are files/directories present on only one side; they are
65
- known to differ up-front and never get submitted to the executor.
61
+ known to differ up-front and never get submitted to the executor. `rel` is
62
+ the path of `a` and `b` below the roots of the walk.
66
63
  """
67
64
  if not isinstance(a, Path) or not isinstance(b, Path):
68
65
  raise TypeError("Both arguments must be of type Path")
69
66
  if not a.is_dir() or not b.is_dir():
70
67
  raise FileNotFoundError("Both arguments must be directories")
71
68
 
72
- if root is None:
73
- root = a
74
-
75
69
  tasks: list[Task] = []
76
70
  failures: list[Failure] = []
77
71
 
@@ -86,11 +80,10 @@ def collect_tasks(
86
80
  }
87
81
 
88
82
  for name in sorted(left_files | right_files):
89
- rel = (a / name).relative_to(root)
90
83
  if name in left_files and name in right_files:
91
84
  tasks.append(
92
85
  Task(
93
- rel,
86
+ rel / name,
94
87
  a / name,
95
88
  b / name,
96
89
  None if diff_output is None else diff_output / name,
@@ -98,9 +91,9 @@ def collect_tasks(
98
91
  )
99
92
  )
100
93
  elif name in left_files:
101
- failures.append(Failure(rel, "missing", "missing in monitored (B)"))
94
+ failures.append(Failure(rel / name, "missing", "missing in monitored (B)"))
102
95
  else:
103
- failures.append(Failure(rel, "missing", "missing in reference (A)"))
96
+ failures.append(Failure(rel / name, "missing", "missing in reference (A)"))
104
97
 
105
98
  left_dirs = {name for name in left if (a / name).is_dir()}
106
99
  right_dirs = {name for name in right if (b / name).is_dir()}
@@ -109,7 +102,7 @@ def collect_tasks(
109
102
  sub_tasks, sub_failures = collect_tasks(
110
103
  a / name,
111
104
  b / name,
112
- root=root,
105
+ rel=rel / name,
113
106
  diff_output=None if diff_output is None else diff_output / name,
114
107
  retries=retries,
115
108
  )
@@ -117,42 +110,13 @@ def collect_tasks(
117
110
  failures.extend(sub_failures)
118
111
 
119
112
  for name in sorted(left_dirs - right_dirs):
120
- failures.append(
121
- Failure((a / name).relative_to(root), "missing", "missing in monitored (B)")
122
- )
113
+ failures.append(Failure(rel / name, "missing", "missing in monitored (B)"))
123
114
  for name in sorted(right_dirs - left_dirs):
124
- failures.append(
125
- Failure((b / name).relative_to(root), "missing", "missing in reference (A)")
126
- )
115
+ failures.append(Failure(rel / name, "missing", "missing in reference (A)"))
127
116
 
128
117
  return tasks, failures
129
118
 
130
119
 
131
- def run_task(task: Task) -> bool:
132
- logger.debug("Comparing %s", task.rel)
133
- browser = getattr(Config.thread_local, "browser", None)
134
- return compare_files(
135
- task.a,
136
- task.b,
137
- browser=browser,
138
- diff_output=task.diff_output,
139
- retries=task.retries,
140
- )
141
-
142
-
143
- def make_executor(max_workers: int, driver: str | None) -> ThreadPoolExecutor:
144
- def initializer():
145
- # One browser per worker thread. Without a driver we only ever compare
146
- # JSON / byte-identical files, so no browser is needed.
147
- if driver is not None:
148
- if getattr(Config.thread_local, "browser", None) is None:
149
- logger.info("Starting %s browser for worker thread", driver)
150
- Config.thread_local.browser = get_browser(driver=driver)
151
-
152
- logger.info("Creating executor with %d worker(s)", max_workers)
153
- return ThreadPoolExecutor(max_workers=max_workers, initializer=initializer)
154
-
155
-
156
120
  def github_error(rel: Path, reason: str) -> None:
157
121
  """Emit a GitHub Actions error annotation so failures surface in the UI."""
158
122
  # https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions
@@ -263,7 +227,10 @@ def run(
263
227
  console: Console,
264
228
  live: bool,
265
229
  github: bool,
230
+ timeout: float = 120.0,
266
231
  ) -> int:
232
+ if not math.isfinite(timeout) or timeout <= 0:
233
+ raise ValueError("timeout must be a positive finite number")
267
234
  console.print(
268
235
  f"[bold]Comparing[/bold] {escape(str(a))} [dim]→[/dim] {escape(str(b))}"
269
236
  )
@@ -287,15 +254,24 @@ def run(
287
254
  if total == 0:
288
255
  console.print("[dim]No comparable files to compare.[/dim]")
289
256
  else:
290
- executor = make_executor(max_workers, driver)
257
+ executor = ComparisonExecutor(max_workers, driver, timeout)
291
258
  try:
292
- future_to_task = {executor.submit(run_task, t): t for t in tasks}
259
+ future_to_task = {
260
+ executor.submit(
261
+ executor.compare,
262
+ t.a,
263
+ t.b,
264
+ diff_output=t.diff_output,
265
+ retries=t.retries,
266
+ ): t
267
+ for t in tasks
268
+ }
293
269
  if live:
294
270
  _run_live(future_to_task, console, failures, github)
295
271
  else:
296
272
  _run_plain(future_to_task, console, failures, github)
297
273
  finally:
298
- executor.shutdown(wait=True)
274
+ executor.shutdown(wait=True, cancel_futures=True)
299
275
 
300
276
  _print_summary(console, total, failures)
301
277
 
@@ -345,11 +321,20 @@ def main():
345
321
  help="Re-render a mismatch this many times before reporting it "
346
322
  "(default: 1; 0 reports the first render)",
347
323
  )
324
+ parser.add_argument(
325
+ "--timeout",
326
+ type=float,
327
+ default=120.0,
328
+ help="Deadline in seconds per browser comparison, including startup "
329
+ "and mismatch retries (default: 120)",
330
+ )
348
331
  parser.add_argument("--log-file", type=Path, help="Path to log file")
349
332
  parser.add_argument(
350
333
  "--log-file-verbosity", type=int, help="Log file verbosity level"
351
334
  )
352
335
  args = parser.parse_args()
336
+ if not math.isfinite(args.timeout) or args.timeout <= 0:
337
+ parser.error("--timeout must be a positive finite number")
353
338
 
354
339
  setup_logging(args.verbose, args.log_file, args.log_file_verbosity)
355
340
 
@@ -374,6 +359,7 @@ def main():
374
359
  console=console,
375
360
  live=live,
376
361
  github=github,
362
+ timeout=args.timeout,
377
363
  )
378
364
 
379
365
 
@@ -0,0 +1,147 @@
1
+ """Reusable browser processes with a deadline owned by the caller."""
2
+
3
+ import filecmp
4
+ import logging
5
+ import multiprocessing
6
+ import threading
7
+ import time
8
+ from concurrent.futures import ThreadPoolExecutor
9
+
10
+ import psutil
11
+
12
+ from htmlcmp.common import compare_files
13
+ from htmlcmp.html_render_diff import get_browser
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ def _compare_loop(connection, driver):
19
+ browser = None
20
+ try:
21
+ while True:
22
+ request = connection.recv()
23
+ if request is None:
24
+ return
25
+ a, b, kwargs = request
26
+ if (
27
+ browser is None
28
+ and a.suffix == ".html"
29
+ and not filecmp.cmp(a, b, shallow=False)
30
+ ):
31
+ browser = get_browser(driver)
32
+ result = compare_files(a, b, browser=browser, **kwargs)
33
+ connection.send((True, result))
34
+ except Exception as exc:
35
+ connection.send((False, f"{type(exc).__name__}: {exc}"))
36
+ # Keep the process tree attached until the parent discards this worker.
37
+ connection.recv()
38
+ finally:
39
+ if browser is not None:
40
+ browser.quit()
41
+ connection.close()
42
+
43
+
44
+ class ComparisonWorker:
45
+ def __init__(self, driver, timeout=120.0):
46
+ self.driver = driver
47
+ self.timeout = timeout
48
+ self._process = None
49
+ self._connection = None
50
+
51
+ def _start(self):
52
+ context = multiprocessing.get_context("spawn")
53
+ self._connection, child = context.Pipe()
54
+ self._process = context.Process(
55
+ target=_compare_loop, args=(child, self.driver), daemon=True
56
+ )
57
+ try:
58
+ self._process.start()
59
+ finally:
60
+ child.close()
61
+
62
+ def compare(self, a, b, **kwargs):
63
+ started = time.monotonic()
64
+ try:
65
+ if self._process is None:
66
+ self._start()
67
+ self._connection.send((a, b, kwargs))
68
+ remaining = max(0, self.timeout - (time.monotonic() - started))
69
+ if not self._connection.poll(remaining):
70
+ raise TimeoutError(
71
+ f"Comparison exceeded {self.timeout:g}s; browser discarded"
72
+ )
73
+ success, result = self._connection.recv()
74
+ if not success:
75
+ raise RuntimeError(result)
76
+ return result
77
+ except BaseException:
78
+ self.close(abort=True)
79
+ raise
80
+
81
+ def close(self, *, abort=False):
82
+ process, connection = self._process, self._connection
83
+ self._process = self._connection = None
84
+ if process is None:
85
+ return
86
+ descendants = []
87
+ try:
88
+ if process.pid is not None:
89
+ try:
90
+ descendants = psutil.Process(process.pid).children(recursive=True)
91
+ except psutil.NoSuchProcess:
92
+ pass
93
+ except psutil.AccessDenied:
94
+ logger.warning("Cannot inspect children of worker %s", process.pid)
95
+ if not abort and process.is_alive():
96
+ try:
97
+ connection.send(None)
98
+ except (BrokenPipeError, EOFError, OSError):
99
+ pass
100
+ process.join(timeout=2)
101
+ # Selenium's quit/service.stop can themselves hang. Never wait for
102
+ # their transport timeout, and include the browser's child processes.
103
+ for child in reversed(descendants):
104
+ try:
105
+ child.kill()
106
+ except psutil.NoSuchProcess:
107
+ pass
108
+ except psutil.AccessDenied:
109
+ logger.warning("Cannot kill browser process %s", child.pid)
110
+ if process.is_alive():
111
+ process.kill()
112
+ if process.pid is not None:
113
+ process.join(timeout=2)
114
+ psutil.wait_procs(descendants, timeout=2)
115
+ finally:
116
+ if connection is not None:
117
+ connection.close()
118
+ if process.pid is None or not process.is_alive():
119
+ process.close()
120
+
121
+
122
+ class ComparisonExecutor(ThreadPoolExecutor):
123
+ def __init__(self, max_workers, driver, timeout=120.0):
124
+ self._driver = driver
125
+ self._timeout = timeout
126
+ self._local = threading.local()
127
+ self._workers = []
128
+ self._workers_lock = threading.Lock()
129
+ super().__init__(max_workers=max_workers)
130
+
131
+ def compare(self, a, b, **kwargs):
132
+ if self._driver is None:
133
+ return compare_files(a, b, **kwargs)
134
+ worker = getattr(self._local, "worker", None)
135
+ if worker is None:
136
+ worker = ComparisonWorker(self._driver, self._timeout)
137
+ self._local.worker = worker
138
+ with self._workers_lock:
139
+ self._workers.append(worker)
140
+ return worker.compare(a, b, **kwargs)
141
+
142
+ def shutdown(self, wait=True, *, cancel_futures=False):
143
+ # A worker's deadline bounds this wait, including browser startup.
144
+ super().shutdown(wait=wait, cancel_futures=cancel_futures)
145
+ if wait:
146
+ for worker in self._workers:
147
+ worker.close()
@@ -119,6 +119,9 @@ def get_browser(
119
119
  browser = webdriver.Chrome(options=options)
120
120
  else:
121
121
  raise ValueError(f"Unsupported driver: {driver}")
122
+ # Local WebDriver constructors do not expose ClientConfig. Disable urllib3's
123
+ # automatic GET retries on their pool: a stalled screenshot must fail once.
124
+ browser.command_executor._conn.connection_pool_kw["retries"] = 0
122
125
  browser.set_window_size(max_width, max_height)
123
126
  return browser
124
127
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: htmlcmp
3
- Version: 2.4.0
3
+ Version: 2.4.2
4
4
  Summary: Compare HTML files by rendered output
5
5
  Author: Andreas Stefl
6
6
  Maintainer-email: Andreas Stefl <stefl.andreas@gmail.com>
@@ -16,6 +16,7 @@ Requires-Dist: selenium
16
16
  Requires-Dist: flask
17
17
  Requires-Dist: watchdog
18
18
  Requires-Dist: rich
19
+ Requires-Dist: psutil
19
20
 
20
21
  # htmlcmp
21
22
 
@@ -29,6 +30,25 @@ Provides various entry points to run:
29
30
 
30
31
  Used for regression testing in https://github.com/opendocument-app/OpenDocument.core.
31
32
 
33
+ ## Browser timeouts in the CLI
34
+
35
+ `compare-html --timeout 120` limits each browser comparison to 120 seconds,
36
+ including browser startup, both screenshots, and any `--retries` of a pixel
37
+ mismatch. The deadline starts when a worker takes the file, not while it waits
38
+ in the queue. Use a larger positive value for especially expensive pages.
39
+
40
+ A timeout is reported as an error and makes the command exit unsuccessfully.
41
+ The worker and its browser processes are discarded; the next file gets a fresh
42
+ browser. Successful comparisons reuse their browser. Shutdown also has bounded
43
+ cleanup, so an unresponsive Selenium `quit()` cannot block the command forever.
44
+ Cleanup can take a few seconds beyond the comparison deadline.
45
+
46
+ WebDriver HTTP requests are not automatically retried. `--retries` still
47
+ rechecks visual mismatches; it does not repeat a timed-out browser command.
48
+ This does not change the pixel comparison or hide errors from slow renderers.
49
+ The per-comparison deadline applies to `compare-html`, not the interactive
50
+ `compare-html-server`.
51
+
32
52
  ## Reviewing differences in the browser
33
53
 
34
54
  `compare-html-server` serves two pages:
@@ -4,6 +4,7 @@ src/htmlcmp/__init__.py
4
4
  src/htmlcmp/common.py
5
5
  src/htmlcmp/compare_output_cli.py
6
6
  src/htmlcmp/compare_output_server.py
7
+ src/htmlcmp/comparison_worker.py
7
8
  src/htmlcmp/html_render_diff.py
8
9
  src/htmlcmp/tidy_output.py
9
10
  src/htmlcmp.egg-info/PKG-INFO
@@ -19,5 +20,8 @@ src/htmlcmp/static/style.css
19
20
  src/htmlcmp/templates/compare.html
20
21
  src/htmlcmp/templates/index.html
21
22
  src/htmlcmp/templates/missing.html
23
+ tests/test_browser_transport.py
24
+ tests/test_collect_tasks.py
22
25
  tests/test_compare_html_retries.py
26
+ tests/test_comparison_worker.py
23
27
  tests/test_html_render_diff.py
@@ -3,3 +3,4 @@ selenium
3
3
  flask
4
4
  watchdog
5
5
  rich
6
+ psutil
@@ -0,0 +1,51 @@
1
+ """A stalled screenshot gets one HTTP request, not four timeout periods."""
2
+
3
+ import threading
4
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
5
+ from unittest.mock import Mock
6
+
7
+ import pytest
8
+ from selenium.webdriver.remote.client_config import ClientConfig
9
+ from selenium.webdriver.remote.command import Command
10
+ from selenium.webdriver.remote.remote_connection import RemoteConnection
11
+ from urllib3.exceptions import MaxRetryError, ReadTimeoutError
12
+
13
+ from htmlcmp import html_render_diff as render
14
+
15
+
16
+ @pytest.mark.parametrize(
17
+ "driver,factory", [("firefox", "Firefox"), ("chrome", "Chrome")]
18
+ )
19
+ def test_screenshot_transport_does_not_retry(monkeypatch, driver, factory):
20
+ requests = []
21
+ release = threading.Event()
22
+
23
+ class Handler(BaseHTTPRequestHandler):
24
+ def do_GET(self):
25
+ requests.append(self.path)
26
+ release.wait(5)
27
+
28
+ def log_message(self, *args):
29
+ pass
30
+
31
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
32
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
33
+ thread.start()
34
+ connection = RemoteConnection(
35
+ client_config=ClientConfig(
36
+ remote_server_addr=f"http://127.0.0.1:{server.server_port}", timeout=0.1
37
+ )
38
+ )
39
+ browser = Mock(command_executor=connection)
40
+ monkeypatch.setattr(render.webdriver, factory, Mock(return_value=browser))
41
+ try:
42
+ assert render.get_browser(driver) is browser
43
+ with pytest.raises((MaxRetryError, ReadTimeoutError)):
44
+ connection.execute(Command.SCREENSHOT, {"sessionId": "test"})
45
+ assert requests == ["/session/test/screenshot"]
46
+ finally:
47
+ release.set()
48
+ connection.close()
49
+ server.shutdown()
50
+ server.server_close()
51
+ thread.join()
@@ -0,0 +1,30 @@
1
+ """A file or directory on one side only is a failure, named below the roots."""
2
+
3
+ from pathlib import Path
4
+
5
+ from htmlcmp.compare_output_cli import collect_tasks
6
+
7
+
8
+ def write(path: Path):
9
+ path.parent.mkdir(parents=True, exist_ok=True)
10
+ path.write_text("<html></html>")
11
+
12
+
13
+ def test_one_sided_entries_are_named_below_the_roots(tmp_path):
14
+ a, b = tmp_path / "a", tmp_path / "b"
15
+ write(a / "both" / "page.html")
16
+ write(b / "both" / "page.html")
17
+ write(a / "both" / "only_a.html")
18
+ write(b / "both" / "only_b.html")
19
+ write(a / "dir_a" / "page.html")
20
+ write(b / "dir_b" / "page.html")
21
+
22
+ tasks, failures = collect_tasks(a, b)
23
+
24
+ assert [task.rel for task in tasks] == [Path("both/page.html")]
25
+ assert sorted((str(f.rel), f.reason) for f in failures) == [
26
+ ("both/only_a.html", "missing in monitored (B)"),
27
+ ("both/only_b.html", "missing in reference (A)"),
28
+ ("dir_a", "missing in monitored (B)"),
29
+ ("dir_b", "missing in reference (A)"),
30
+ ]
@@ -0,0 +1,164 @@
1
+ """Exercise deadlines with real subprocesses, without requiring a browser."""
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ import time
7
+ from pathlib import Path
8
+ from unittest.mock import Mock
9
+
10
+ import psutil
11
+ import pytest
12
+
13
+ from htmlcmp import comparison_worker as worker_module
14
+ from htmlcmp.comparison_worker import ComparisonExecutor, ComparisonWorker
15
+
16
+
17
+ def controlled_worker(connection, driver):
18
+ while True:
19
+ request = connection.recv()
20
+ if request is None:
21
+ return
22
+ a, b, kwargs = request
23
+ if a.name == "hang.html":
24
+ child = subprocess.Popen(
25
+ [sys.executable, "-c", "import time; time.sleep(60)"]
26
+ )
27
+ b.write_text(f"{os.getpid()} {child.pid}")
28
+ time.sleep(60)
29
+ elif a.name == "error.html":
30
+ connection.send((False, "ReadTimeoutError: screenshot timed out"))
31
+ connection.recv()
32
+ elif a.name == "crash.html":
33
+ os._exit(1)
34
+ else:
35
+ connection.send((True, os.getpid()))
36
+
37
+
38
+ def hanging_shutdown(connection, driver):
39
+ connection.recv()
40
+ connection.send((True, os.getpid()))
41
+ connection.recv()
42
+ time.sleep(60)
43
+
44
+
45
+ def no_startup_response(connection, driver):
46
+ time.sleep(60)
47
+
48
+
49
+ def test_timeout_kills_descendants_and_next_file_gets_a_new_worker(
50
+ monkeypatch, tmp_path
51
+ ):
52
+ monkeypatch.setattr(worker_module, "_compare_loop", controlled_worker)
53
+ worker = ComparisonWorker("firefox", timeout=2)
54
+ try:
55
+ original = worker.compare(Path("healthy.html"), tmp_path / "unused")
56
+ started = time.monotonic()
57
+ with pytest.raises(TimeoutError, match="browser discarded"):
58
+ worker.compare(Path("hang.html"), tmp_path / "pids")
59
+ assert time.monotonic() - started < 10
60
+ parent, child = map(int, (tmp_path / "pids").read_text().split())
61
+ assert original == parent
62
+ assert not psutil.pid_exists(parent)
63
+ try:
64
+ assert psutil.Process(child).status() == psutil.STATUS_ZOMBIE
65
+ except psutil.NoSuchProcess:
66
+ pass
67
+ assert worker.compare(Path("healthy.html"), tmp_path / "unused") != original
68
+ finally:
69
+ worker.close()
70
+
71
+
72
+ def test_browser_error_does_not_poison_later_tasks(monkeypatch, tmp_path):
73
+ monkeypatch.setattr(worker_module, "_compare_loop", controlled_worker)
74
+ with ComparisonExecutor(1, "firefox", timeout=5) as executor:
75
+ first = executor.submit(
76
+ executor.compare, Path("healthy.html"), tmp_path
77
+ ).result()
78
+ error = executor.submit(executor.compare, Path("error.html"), tmp_path)
79
+ healthy = executor.submit(executor.compare, Path("healthy.html"), tmp_path)
80
+ with pytest.raises(RuntimeError, match="ReadTimeoutError"):
81
+ error.result()
82
+ replacement = healthy.result()
83
+ assert replacement != first
84
+ assert (
85
+ executor.submit(executor.compare, Path("healthy.html"), tmp_path).result()
86
+ == replacement
87
+ )
88
+ assert not psutil.pid_exists(replacement)
89
+
90
+
91
+ def test_abrupt_worker_exit_does_not_break_the_pool(monkeypatch, tmp_path):
92
+ monkeypatch.setattr(worker_module, "_compare_loop", controlled_worker)
93
+ worker = ComparisonWorker("firefox", timeout=5)
94
+ try:
95
+ with pytest.raises((EOFError, ConnectionResetError)):
96
+ worker.compare(Path("crash.html"), tmp_path)
97
+ assert worker.compare(Path("healthy.html"), tmp_path)
98
+ finally:
99
+ worker.close()
100
+
101
+
102
+ def test_deadline_includes_browser_startup(monkeypatch, tmp_path):
103
+ monkeypatch.setattr(worker_module, "_compare_loop", no_startup_response)
104
+ worker = ComparisonWorker("firefox", timeout=0.2)
105
+ started = time.monotonic()
106
+ with pytest.raises(TimeoutError):
107
+ worker.compare(Path("healthy.html"), tmp_path)
108
+ assert time.monotonic() - started < 5
109
+ worker.close()
110
+
111
+
112
+ def test_shutdown_does_not_wait_forever_for_selenium_quit(monkeypatch, tmp_path):
113
+ monkeypatch.setattr(worker_module, "_compare_loop", hanging_shutdown)
114
+ worker = ComparisonWorker("firefox", timeout=5)
115
+ pid = worker.compare(Path("healthy.html"), tmp_path)
116
+ started = time.monotonic()
117
+ worker.close()
118
+ assert time.monotonic() - started < 8
119
+ assert not psutil.pid_exists(pid)
120
+ worker.close()
121
+
122
+
123
+ def test_driver_none_never_starts_a_process(monkeypatch, tmp_path):
124
+ start = Mock(side_effect=AssertionError("browser must not start"))
125
+ monkeypatch.setattr(ComparisonWorker, "_start", start)
126
+ a, b = tmp_path / "a.html", tmp_path / "b.html"
127
+ a.write_text("one")
128
+ b.write_text("two")
129
+ with ComparisonExecutor(1, None) as executor:
130
+ assert executor.submit(executor.compare, a, b).result() is False
131
+ start.assert_not_called()
132
+
133
+
134
+ def test_identical_html_does_not_need_a_browser(tmp_path):
135
+ a, b = tmp_path / "a.html", tmp_path / "b.html"
136
+ a.write_text("identical")
137
+ b.write_text("identical")
138
+ # An invalid driver would fail if startup were attempted.
139
+ with ComparisonExecutor(1, "not-a-browser", timeout=5) as executor:
140
+ assert executor.submit(executor.compare, a, b).result() is True
141
+
142
+
143
+ def test_startup_failure_is_reported_per_file(tmp_path):
144
+ a, b = tmp_path / "a.html", tmp_path / "b.html"
145
+ a.write_text("one")
146
+ b.write_text("two")
147
+ worker = ComparisonWorker("not-a-browser", timeout=5)
148
+ try:
149
+ with pytest.raises(RuntimeError, match="Unsupported driver"):
150
+ worker.compare(a, b)
151
+ a.write_text("two")
152
+ assert worker.compare(a, b) is True
153
+ finally:
154
+ worker.close()
155
+
156
+
157
+ @pytest.mark.parametrize("timeout", ["0", "-1", "nan", "inf"])
158
+ def test_cli_rejects_invalid_deadline(monkeypatch, timeout):
159
+ from htmlcmp.compare_output_cli import main
160
+
161
+ monkeypatch.setattr(sys, "argv", ["compare-html", "a", "b", "--timeout", timeout])
162
+ with pytest.raises(SystemExit) as exc:
163
+ main()
164
+ assert exc.value.code == 2
@@ -41,7 +41,11 @@ def test_html_render_diff():
41
41
  with pytest.raises(TypeError):
42
42
  html_render_diff(str(test1), str(test2), None)
43
43
 
44
- diff, _ = html_render_diff(test1, test1, get_browser("firefox"))
45
- assert diff.getbbox() is None
46
- diff, _ = html_render_diff(test1, test2, get_browser("firefox"))
47
- assert diff.getbbox() is not None
44
+ browser = get_browser("firefox")
45
+ try:
46
+ diff, _ = html_render_diff(test1, test1, browser)
47
+ assert diff.getbbox() is None
48
+ diff, _ = html_render_diff(test1, test2, browser)
49
+ assert diff.getbbox() is not None
50
+ finally:
51
+ browser.quit()
File without changes
File without changes
File without changes