htmlcmp 2.4.1__tar.gz → 2.4.3__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.1 → htmlcmp-2.4.3}/PKG-INFO +23 -1
  2. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/README.md +21 -0
  3. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/pyproject.toml +2 -1
  4. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp/compare_output_cli.py +29 -36
  5. htmlcmp-2.4.3/src/htmlcmp/comparison_worker.py +147 -0
  6. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp/html_render_diff.py +12 -1
  7. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp.egg-info/PKG-INFO +23 -1
  8. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp.egg-info/SOURCES.txt +3 -0
  9. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp.egg-info/requires.txt +1 -0
  10. htmlcmp-2.4.3/tests/test_browser_transport.py +93 -0
  11. htmlcmp-2.4.3/tests/test_comparison_worker.py +178 -0
  12. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/tests/test_html_render_diff.py +8 -4
  13. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/setup.cfg +0 -0
  14. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp/__init__.py +0 -0
  15. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp/common.py +0 -0
  16. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp/compare_output_server.py +0 -0
  17. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp/static/common.js +0 -0
  18. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp/static/compare.js +0 -0
  19. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp/static/index.js +0 -0
  20. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp/static/style.css +0 -0
  21. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp/templates/compare.html +0 -0
  22. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp/templates/index.html +0 -0
  23. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp/templates/missing.html +0 -0
  24. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp/tidy_output.py +0 -0
  25. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp.egg-info/dependency_links.txt +0 -0
  26. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp.egg-info/entry_points.txt +0 -0
  27. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/src/htmlcmp.egg-info/top_level.txt +0 -0
  28. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/tests/test_collect_tasks.py +0 -0
  29. {htmlcmp-2.4.1 → htmlcmp-2.4.3}/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.1
3
+ Version: 2.4.3
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,27 @@ 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
+ The same value configures WebDriver's HTTP and page-load timeouts, so increasing
40
+ the deadline is not cut short by Selenium's default 120-second HTTP timeout.
41
+
42
+ A timeout is reported as an error and makes the command exit unsuccessfully.
43
+ The worker and its browser processes are discarded; the next file gets a fresh
44
+ browser. Successful comparisons reuse their browser. Shutdown also has bounded
45
+ cleanup, so an unresponsive Selenium `quit()` cannot block the command forever.
46
+ Cleanup can take a few seconds beyond the comparison deadline.
47
+
48
+ WebDriver HTTP requests are not automatically retried. `--retries` still
49
+ rechecks visual mismatches; it does not repeat a timed-out browser command.
50
+ This does not change the pixel comparison or hide errors from slow renderers.
51
+ The per-comparison deadline applies to `compare-html`, not the interactive
52
+ `compare-html-server`.
53
+
32
54
  ## Reviewing differences in the browser
33
55
 
34
56
  `compare-html-server` serves two pages:
@@ -10,6 +10,27 @@ 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
+ The same value configures WebDriver's HTTP and page-load timeouts, so increasing
20
+ the deadline is not cut short by Selenium's default 120-second HTTP timeout.
21
+
22
+ A timeout is reported as an error and makes the command exit unsuccessfully.
23
+ The worker and its browser processes are discarded; the next file gets a fresh
24
+ browser. Successful comparisons reuse their browser. Shutdown also has bounded
25
+ cleanup, so an unresponsive Selenium `quit()` cannot block the command forever.
26
+ Cleanup can take a few seconds beyond the comparison deadline.
27
+
28
+ WebDriver HTTP requests are not automatically retried. `--retries` still
29
+ rechecks visual mismatches; it does not repeat a timed-out browser command.
30
+ This does not change the pixel comparison or hide errors from slow renderers.
31
+ The per-comparison deadline applies to `compare-html`, not the interactive
32
+ `compare-html-server`.
33
+
13
34
  ## Reviewing differences in the browser
14
35
 
15
36
  `compare-html-server` serves two pages:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "htmlcmp"
3
- version = "2.4.1"
3
+ version = "2.4.3"
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
 
@@ -121,31 +117,6 @@ def collect_tasks(
121
117
  return tasks, failures
122
118
 
123
119
 
124
- def run_task(task: Task) -> bool:
125
- logger.debug("Comparing %s", task.rel)
126
- browser = getattr(Config.thread_local, "browser", None)
127
- return compare_files(
128
- task.a,
129
- task.b,
130
- browser=browser,
131
- diff_output=task.diff_output,
132
- retries=task.retries,
133
- )
134
-
135
-
136
- def make_executor(max_workers: int, driver: str | None) -> ThreadPoolExecutor:
137
- def initializer():
138
- # One browser per worker thread. Without a driver we only ever compare
139
- # JSON / byte-identical files, so no browser is needed.
140
- if driver is not None:
141
- if getattr(Config.thread_local, "browser", None) is None:
142
- logger.info("Starting %s browser for worker thread", driver)
143
- Config.thread_local.browser = get_browser(driver=driver)
144
-
145
- logger.info("Creating executor with %d worker(s)", max_workers)
146
- return ThreadPoolExecutor(max_workers=max_workers, initializer=initializer)
147
-
148
-
149
120
  def github_error(rel: Path, reason: str) -> None:
150
121
  """Emit a GitHub Actions error annotation so failures surface in the UI."""
151
122
  # https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions
@@ -256,7 +227,10 @@ def run(
256
227
  console: Console,
257
228
  live: bool,
258
229
  github: bool,
230
+ timeout: float = 120.0,
259
231
  ) -> int:
232
+ if not math.isfinite(timeout) or timeout <= 0:
233
+ raise ValueError("timeout must be a positive finite number")
260
234
  console.print(
261
235
  f"[bold]Comparing[/bold] {escape(str(a))} [dim]→[/dim] {escape(str(b))}"
262
236
  )
@@ -280,15 +254,24 @@ def run(
280
254
  if total == 0:
281
255
  console.print("[dim]No comparable files to compare.[/dim]")
282
256
  else:
283
- executor = make_executor(max_workers, driver)
257
+ executor = ComparisonExecutor(max_workers, driver, timeout)
284
258
  try:
285
- 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
+ }
286
269
  if live:
287
270
  _run_live(future_to_task, console, failures, github)
288
271
  else:
289
272
  _run_plain(future_to_task, console, failures, github)
290
273
  finally:
291
- executor.shutdown(wait=True)
274
+ executor.shutdown(wait=True, cancel_futures=True)
292
275
 
293
276
  _print_summary(console, total, failures)
294
277
 
@@ -338,11 +321,20 @@ def main():
338
321
  help="Re-render a mismatch this many times before reporting it "
339
322
  "(default: 1; 0 reports the first render)",
340
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
+ )
341
331
  parser.add_argument("--log-file", type=Path, help="Path to log file")
342
332
  parser.add_argument(
343
333
  "--log-file-verbosity", type=int, help="Log file verbosity level"
344
334
  )
345
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")
346
338
 
347
339
  setup_logging(args.verbose, args.log_file, args.log_file_verbosity)
348
340
 
@@ -367,6 +359,7 @@ def main():
367
359
  console=console,
368
360
  live=live,
369
361
  github=github,
362
+ timeout=args.timeout,
370
363
  )
371
364
 
372
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, timeout):
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, timeout=timeout)
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, self.timeout), 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()
@@ -100,7 +100,11 @@ def content_bottom(image: Image.Image) -> int:
100
100
 
101
101
 
102
102
  def get_browser(
103
- driver: str, max_width: int = 1000, max_height: int = 10000
103
+ driver: str,
104
+ max_width: int = 1000,
105
+ max_height: int = 10000,
106
+ *,
107
+ timeout: float | None = None,
104
108
  ) -> webdriver.Remote:
105
109
  if not isinstance(driver, str):
106
110
  raise TypeError(f"Expected str, got {type(driver)}")
@@ -119,6 +123,13 @@ def get_browser(
119
123
  browser = webdriver.Chrome(options=options)
120
124
  else:
121
125
  raise ValueError(f"Unsupported driver: {driver}")
126
+ # Local WebDriver constructors do not expose ClientConfig. Disable urllib3's
127
+ # automatic GET retries on their pool: a stalled screenshot must fail once.
128
+ browser.command_executor._conn.connection_pool_kw["retries"] = 0
129
+ if timeout is not None:
130
+ # The CLI's parent process enforces the whole comparison deadline.
131
+ browser.command_executor._client_config.timeout = timeout
132
+ browser.set_page_load_timeout(timeout)
122
133
  browser.set_window_size(max_width, max_height)
123
134
  return browser
124
135
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: htmlcmp
3
- Version: 2.4.1
3
+ Version: 2.4.3
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,27 @@ 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
+ The same value configures WebDriver's HTTP and page-load timeouts, so increasing
40
+ the deadline is not cut short by Selenium's default 120-second HTTP timeout.
41
+
42
+ A timeout is reported as an error and makes the command exit unsuccessfully.
43
+ The worker and its browser processes are discarded; the next file gets a fresh
44
+ browser. Successful comparisons reuse their browser. Shutdown also has bounded
45
+ cleanup, so an unresponsive Selenium `quit()` cannot block the command forever.
46
+ Cleanup can take a few seconds beyond the comparison deadline.
47
+
48
+ WebDriver HTTP requests are not automatically retried. `--retries` still
49
+ rechecks visual mismatches; it does not repeat a timed-out browser command.
50
+ This does not change the pixel comparison or hide errors from slow renderers.
51
+ The per-comparison deadline applies to `compare-html`, not the interactive
52
+ `compare-html-server`.
53
+
32
54
  ## Reviewing differences in the browser
33
55
 
34
56
  `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,6 +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
22
24
  tests/test_collect_tasks.py
23
25
  tests/test_compare_html_retries.py
26
+ tests/test_comparison_worker.py
24
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,93 @@
1
+ """A stalled screenshot gets one HTTP request, not four timeout periods."""
2
+
3
+ import threading
4
+ import time
5
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
6
+ from unittest.mock import Mock
7
+
8
+ import pytest
9
+ from selenium.webdriver.remote.client_config import ClientConfig
10
+ from selenium.webdriver.remote.command import Command
11
+ from selenium.webdriver.remote.remote_connection import RemoteConnection
12
+ from urllib3.exceptions import MaxRetryError, ReadTimeoutError
13
+
14
+ from htmlcmp import html_render_diff as render
15
+
16
+
17
+ @pytest.mark.parametrize(
18
+ "driver,factory", [("firefox", "Firefox"), ("chrome", "Chrome")]
19
+ )
20
+ def test_screenshot_transport_does_not_retry(monkeypatch, driver, factory):
21
+ requests = []
22
+ release = threading.Event()
23
+
24
+ class Handler(BaseHTTPRequestHandler):
25
+ def do_GET(self):
26
+ requests.append(self.path)
27
+ release.wait(5)
28
+
29
+ def log_message(self, *args):
30
+ pass
31
+
32
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
33
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
34
+ thread.start()
35
+ connection = RemoteConnection(
36
+ client_config=ClientConfig(
37
+ remote_server_addr=f"http://127.0.0.1:{server.server_port}", timeout=0.1
38
+ )
39
+ )
40
+ browser = Mock(command_executor=connection)
41
+ monkeypatch.setattr(render.webdriver, factory, Mock(return_value=browser))
42
+ try:
43
+ assert render.get_browser(driver) is browser
44
+ with pytest.raises((MaxRetryError, ReadTimeoutError)):
45
+ connection.execute(Command.SCREENSHOT, {"sessionId": "test"})
46
+ assert requests == ["/session/test/screenshot"]
47
+ finally:
48
+ release.set()
49
+ connection.close()
50
+ server.shutdown()
51
+ server.server_close()
52
+ thread.join()
53
+
54
+
55
+ @pytest.mark.parametrize(
56
+ "driver,factory", [("firefox", "Firefox"), ("chrome", "Chrome")]
57
+ )
58
+ def test_longer_deadline_allows_a_slow_screenshot(monkeypatch, driver, factory):
59
+ class Handler(BaseHTTPRequestHandler):
60
+ def do_GET(self):
61
+ time.sleep(0.25)
62
+ body = b'{"value":"image"}'
63
+ self.send_response(200)
64
+ self.send_header("Content-Type", "application/json")
65
+ self.send_header("Content-Length", str(len(body)))
66
+ self.end_headers()
67
+ self.wfile.write(body)
68
+
69
+ def log_message(self, *args):
70
+ pass
71
+
72
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
73
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
74
+ thread.start()
75
+ connection = RemoteConnection(
76
+ client_config=ClientConfig(
77
+ remote_server_addr=f"http://127.0.0.1:{server.server_port}",
78
+ timeout=0.1,
79
+ )
80
+ )
81
+ browser = Mock(command_executor=connection)
82
+ monkeypatch.setattr(render.webdriver, factory, Mock(return_value=browser))
83
+ try:
84
+ render.get_browser(driver, timeout=2)
85
+ browser.set_page_load_timeout.assert_called_once_with(2)
86
+ assert connection.execute(Command.SCREENSHOT, {"sessionId": "test"}) == {
87
+ "value": "image"
88
+ }
89
+ finally:
90
+ connection.close()
91
+ server.shutdown()
92
+ server.server_close()
93
+ thread.join()
@@ -0,0 +1,178 @@
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, timeout):
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, timeout):
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, timeout):
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_comparison_deadline_reaches_browser_transport(monkeypatch, tmp_path):
144
+ a, b = tmp_path / "a.html", tmp_path / "b.html"
145
+ a.write_text("one")
146
+ b.write_text("two")
147
+ connection = Mock()
148
+ connection.recv.side_effect = [(a, b, {}), None]
149
+ factory = Mock()
150
+ monkeypatch.setattr(worker_module, "get_browser", factory)
151
+ monkeypatch.setattr(worker_module, "compare_files", Mock(return_value=True))
152
+ worker_module._compare_loop(connection, "firefox", 900)
153
+ factory.assert_called_once_with("firefox", timeout=900)
154
+ connection.send.assert_called_once_with((True, True))
155
+
156
+
157
+ def test_startup_failure_is_reported_per_file(tmp_path):
158
+ a, b = tmp_path / "a.html", tmp_path / "b.html"
159
+ a.write_text("one")
160
+ b.write_text("two")
161
+ worker = ComparisonWorker("not-a-browser", timeout=5)
162
+ try:
163
+ with pytest.raises(RuntimeError, match="Unsupported driver"):
164
+ worker.compare(a, b)
165
+ a.write_text("two")
166
+ assert worker.compare(a, b) is True
167
+ finally:
168
+ worker.close()
169
+
170
+
171
+ @pytest.mark.parametrize("timeout", ["0", "-1", "nan", "inf"])
172
+ def test_cli_rejects_invalid_deadline(monkeypatch, timeout):
173
+ from htmlcmp.compare_output_cli import main
174
+
175
+ monkeypatch.setattr(sys, "argv", ["compare-html", "a", "b", "--timeout", timeout])
176
+ with pytest.raises(SystemExit) as exc:
177
+ main()
178
+ 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