htmlcmp 2.3.0__tar.gz → 2.4.1__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 (26) hide show
  1. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/PKG-INFO +1 -1
  2. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/pyproject.toml +1 -1
  3. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp/common.py +26 -5
  4. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp/compare_output_cli.py +32 -19
  5. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp/html_render_diff.py +38 -7
  6. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp.egg-info/PKG-INFO +1 -1
  7. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp.egg-info/SOURCES.txt +2 -0
  8. htmlcmp-2.4.1/tests/test_collect_tasks.py +30 -0
  9. htmlcmp-2.4.1/tests/test_compare_html_retries.py +80 -0
  10. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/README.md +0 -0
  11. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/setup.cfg +0 -0
  12. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp/__init__.py +0 -0
  13. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp/compare_output_server.py +0 -0
  14. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp/static/common.js +0 -0
  15. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp/static/compare.js +0 -0
  16. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp/static/index.js +0 -0
  17. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp/static/style.css +0 -0
  18. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp/templates/compare.html +0 -0
  19. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp/templates/index.html +0 -0
  20. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp/templates/missing.html +0 -0
  21. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp/tidy_output.py +0 -0
  22. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp.egg-info/dependency_links.txt +0 -0
  23. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp.egg-info/entry_points.txt +0 -0
  24. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp.egg-info/requires.txt +0 -0
  25. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/src/htmlcmp.egg-info/top_level.txt +0 -0
  26. {htmlcmp-2.3.0 → htmlcmp-2.4.1}/tests/test_html_render_diff.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: htmlcmp
3
- Version: 2.3.0
3
+ Version: 2.4.1
4
4
  Summary: Compare HTML files by rendered output
5
5
  Author: Andreas Stefl
6
6
  Maintainer-email: Andreas Stefl <stefl.andreas@gmail.com>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "htmlcmp"
3
- version = "2.3.0"
3
+ version = "2.4.1"
4
4
  description = "Compare HTML files by rendered output"
5
5
  classifiers = []
6
6
  authors = [
@@ -6,6 +6,8 @@ from pathlib import Path
6
6
 
7
7
  from htmlcmp.html_render_diff import get_browser, html_render_diff
8
8
 
9
+ logger = logging.getLogger(__name__)
10
+
9
11
 
10
12
  class bcolors:
11
13
  HEADER = "\033[95m"
@@ -40,22 +42,41 @@ def compare_json(a: Path, b: Path) -> bool:
40
42
  return json_a == json_b
41
43
 
42
44
 
43
- def compare_html(a: Path, b: Path, browser=None, diff_output: Path = None) -> bool:
45
+ def compare_html(
46
+ a: Path, b: Path, browser=None, diff_output: Path = None, retries: int = 1
47
+ ) -> bool:
48
+ """Whether `a` and `b` render to the same pixels.
49
+
50
+ A mismatch is rendered again before it is reported, `retries` times. A real
51
+ difference is in the markup and comes back every time; one that does not is
52
+ the page having been caught mid-render, and a browser gives no promise that
53
+ two runs of the same page paint alike at the same instant. The retry costs
54
+ nothing on the matching files, which are almost all of them.
55
+ """
44
56
  if not isinstance(a, Path) or not isinstance(b, Path):
45
57
  raise TypeError("Both arguments must be of type Path")
46
58
  if not a.is_file() or not b.is_file():
47
59
  raise FileNotFoundError("Both arguments must be files")
60
+ if not isinstance(retries, int) or retries < 0:
61
+ raise ValueError(f"retries must be a non-negative int, got {retries!r}")
48
62
 
49
63
  if browser is None:
50
64
  browser = get_browser("firefox")
51
- diff, (image_a, image_b) = html_render_diff(a, b, browser=browser)
52
- result = diff.getbbox() is None
53
- if diff_output is not None and not result:
65
+
66
+ for attempt in range(retries + 1):
67
+ diff, (image_a, image_b) = html_render_diff(a, b, browser=browser)
68
+ if diff.getbbox() is None:
69
+ return True
70
+ logger.debug(
71
+ "%s and %s differ on attempt %d of %d", a, b, attempt + 1, retries + 1
72
+ )
73
+
74
+ if diff_output is not None:
54
75
  diff_output.mkdir(parents=True, exist_ok=True)
55
76
  image_a.save(diff_output / "a.png")
56
77
  image_b.save(diff_output / "b.png")
57
78
  diff.save(diff_output / "diff.png")
58
- return result
79
+ return False
59
80
 
60
81
 
61
82
  def compare_files(a: Path, b: Path, **kwargs) -> bool:
@@ -34,11 +34,14 @@ class Config:
34
34
  class Task:
35
35
  """A single file comparison between the reference (A) and monitored (B) tree."""
36
36
 
37
- def __init__(self, rel: Path, a: Path, b: Path, diff_output: Path = None):
37
+ def __init__(
38
+ self, rel: Path, a: Path, b: Path, diff_output: Path = None, retries: int = 1
39
+ ):
38
40
  self.rel = rel
39
41
  self.a = a
40
42
  self.b = b
41
43
  self.diff_output = diff_output
44
+ self.retries = retries
42
45
 
43
46
 
44
47
  class Failure:
@@ -54,21 +57,19 @@ class Failure:
54
57
 
55
58
 
56
59
  def collect_tasks(
57
- a: Path, b: Path, root: Path = None, diff_output: Path = None
60
+ a: Path, b: Path, rel: Path = Path(), diff_output: Path = None, retries: int = 1
58
61
  ) -> tuple[list[Task], list[Failure]]:
59
62
  """Walk both trees once and return (comparable tasks, structural failures).
60
63
 
61
64
  Structural failures are files/directories present on only one side; they are
62
- known to differ up-front and never get submitted to the executor.
65
+ known to differ up-front and never get submitted to the executor. `rel` is
66
+ the path of `a` and `b` below the roots of the walk.
63
67
  """
64
68
  if not isinstance(a, Path) or not isinstance(b, Path):
65
69
  raise TypeError("Both arguments must be of type Path")
66
70
  if not a.is_dir() or not b.is_dir():
67
71
  raise FileNotFoundError("Both arguments must be directories")
68
72
 
69
- if root is None:
70
- root = a
71
-
72
73
  tasks: list[Task] = []
73
74
  failures: list[Failure] = []
74
75
 
@@ -83,20 +84,20 @@ def collect_tasks(
83
84
  }
84
85
 
85
86
  for name in sorted(left_files | right_files):
86
- rel = (a / name).relative_to(root)
87
87
  if name in left_files and name in right_files:
88
88
  tasks.append(
89
89
  Task(
90
- rel,
90
+ rel / name,
91
91
  a / name,
92
92
  b / name,
93
93
  None if diff_output is None else diff_output / name,
94
+ retries=retries,
94
95
  )
95
96
  )
96
97
  elif name in left_files:
97
- failures.append(Failure(rel, "missing", "missing in monitored (B)"))
98
+ failures.append(Failure(rel / name, "missing", "missing in monitored (B)"))
98
99
  else:
99
- failures.append(Failure(rel, "missing", "missing in reference (A)"))
100
+ failures.append(Failure(rel / name, "missing", "missing in reference (A)"))
100
101
 
101
102
  left_dirs = {name for name in left if (a / name).is_dir()}
102
103
  right_dirs = {name for name in right if (b / name).is_dir()}
@@ -105,20 +106,17 @@ def collect_tasks(
105
106
  sub_tasks, sub_failures = collect_tasks(
106
107
  a / name,
107
108
  b / name,
108
- root=root,
109
+ rel=rel / name,
109
110
  diff_output=None if diff_output is None else diff_output / name,
111
+ retries=retries,
110
112
  )
111
113
  tasks.extend(sub_tasks)
112
114
  failures.extend(sub_failures)
113
115
 
114
116
  for name in sorted(left_dirs - right_dirs):
115
- failures.append(
116
- Failure((a / name).relative_to(root), "missing", "missing in monitored (B)")
117
- )
117
+ failures.append(Failure(rel / name, "missing", "missing in monitored (B)"))
118
118
  for name in sorted(right_dirs - left_dirs):
119
- failures.append(
120
- Failure((b / name).relative_to(root), "missing", "missing in reference (A)")
121
- )
119
+ failures.append(Failure(rel / name, "missing", "missing in reference (A)"))
122
120
 
123
121
  return tasks, failures
124
122
 
@@ -126,7 +124,13 @@ def collect_tasks(
126
124
  def run_task(task: Task) -> bool:
127
125
  logger.debug("Comparing %s", task.rel)
128
126
  browser = getattr(Config.thread_local, "browser", None)
129
- return compare_files(task.a, task.b, browser=browser, diff_output=task.diff_output)
127
+ return compare_files(
128
+ task.a,
129
+ task.b,
130
+ browser=browser,
131
+ diff_output=task.diff_output,
132
+ retries=task.retries,
133
+ )
130
134
 
131
135
 
132
136
  def make_executor(max_workers: int, driver: str | None) -> ThreadPoolExecutor:
@@ -248,6 +252,7 @@ def run(
248
252
  driver: str | None,
249
253
  max_workers: int,
250
254
  diff_output: Path | None,
255
+ retries: int,
251
256
  console: Console,
252
257
  live: bool,
253
258
  github: bool,
@@ -256,7 +261,7 @@ def run(
256
261
  f"[bold]Comparing[/bold] {escape(str(a))} [dim]→[/dim] {escape(str(b))}"
257
262
  )
258
263
 
259
- tasks, failures = collect_tasks(a, b, diff_output=diff_output)
264
+ tasks, failures = collect_tasks(a, b, diff_output=diff_output, retries=retries)
260
265
  logger.info(
261
266
  "Collected %d comparable file(s), %d structural difference(s)",
262
267
  len(tasks),
@@ -326,6 +331,13 @@ def main():
326
331
  default=0,
327
332
  help="Increase verbosity (-v, -vv, -vvv)",
328
333
  )
334
+ parser.add_argument(
335
+ "--retries",
336
+ type=int,
337
+ default=1,
338
+ help="Re-render a mismatch this many times before reporting it "
339
+ "(default: 1; 0 reports the first render)",
340
+ )
329
341
  parser.add_argument("--log-file", type=Path, help="Path to log file")
330
342
  parser.add_argument(
331
343
  "--log-file-verbosity", type=int, help="Log file verbosity level"
@@ -351,6 +363,7 @@ def main():
351
363
  driver=driver,
352
364
  max_workers=args.max_workers,
353
365
  diff_output=args.diff_output,
366
+ retries=args.retries,
354
367
  console=console,
355
368
  live=live,
356
369
  github=github,
@@ -9,6 +9,7 @@ from pathlib import Path
9
9
 
10
10
  from PIL import Image, ImageChops
11
11
  from selenium import webdriver
12
+ from selenium.common.exceptions import WebDriverException
12
13
  from selenium.webdriver.common.by import By
13
14
  from selenium.webdriver.support import expected_conditions
14
15
  from selenium.webdriver.support.ui import WebDriverWait
@@ -25,7 +26,9 @@ def to_url(path: str | Path) -> str:
25
26
  return path
26
27
 
27
28
 
28
- def screenshot(browser: webdriver.Remote, url: str) -> Image.Image:
29
+ def screenshot(
30
+ browser: webdriver.Remote, url: str, settling_time: float = 0
31
+ ) -> Image.Image:
29
32
  if not isinstance(url, str):
30
33
  raise TypeError(f"Expected str, got {type(url)}")
31
34
  if not isinstance(browser, webdriver.Remote):
@@ -35,11 +38,6 @@ def screenshot(browser: webdriver.Remote, url: str) -> Image.Image:
35
38
 
36
39
  target_find_by = By.TAG_NAME
37
40
  target = "body"
38
- loaded_page_settling_time = 0
39
-
40
- # TODO for pdf2htmlex the second screenshot sometimes fades in from white... not sure why, but a sleep solves it
41
- if "poppler" in url:
42
- loaded_page_settling_time = 0.3
43
41
 
44
42
  web_driver_wait = WebDriverWait(browser, 10)
45
43
  web_driver_wait.until(
@@ -49,12 +47,45 @@ def screenshot(browser: webdriver.Remote, url: str) -> Image.Image:
49
47
  lambda driver: driver.execute_script("return document.readyState") == "complete"
50
48
  )
51
49
 
52
- time.sleep(loaded_page_settling_time)
50
+ settle(browser, settling_time)
53
51
 
54
52
  png = browser.get_screenshot_as_png()
55
53
  return Image.open(io.BytesIO(png))
56
54
 
57
55
 
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.
60
+ _SETTLE = """
61
+ 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);
65
+ """
66
+
67
+
68
+ def settle(browser: webdriver.Remote, settling_time: float = 0) -> None:
69
+ """Waits until the page has finished painting what it loaded.
70
+
71
+ A screenshot taken before that catches the page mid-render, which is what
72
+ makes an otherwise identical pair compare as different from one run to the
73
+ next.
74
+ """
75
+ if not isinstance(browser, webdriver.Remote):
76
+ raise TypeError(f"Expected webdriver.Remote, got {type(browser)}")
77
+
78
+ browser.set_script_timeout(10)
79
+ try:
80
+ browser.execute_async_script(_SETTLE)
81
+ except WebDriverException:
82
+ # an old driver without async scripts still gets the sleep below
83
+ pass
84
+
85
+ if settling_time:
86
+ time.sleep(settling_time)
87
+
88
+
58
89
  def content_bottom(image: Image.Image) -> int:
59
90
  """Row just below the last pixel that differs from the page background.
60
91
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: htmlcmp
3
- Version: 2.3.0
3
+ Version: 2.4.1
4
4
  Summary: Compare HTML files by rendered output
5
5
  Author: Andreas Stefl
6
6
  Maintainer-email: Andreas Stefl <stefl.andreas@gmail.com>
@@ -19,4 +19,6 @@ src/htmlcmp/static/style.css
19
19
  src/htmlcmp/templates/compare.html
20
20
  src/htmlcmp/templates/index.html
21
21
  src/htmlcmp/templates/missing.html
22
+ tests/test_collect_tasks.py
23
+ tests/test_compare_html_retries.py
22
24
  tests/test_html_render_diff.py
@@ -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,80 @@
1
+ """A mismatch is rendered again before it is reported.
2
+
3
+ A browser gives no promise that two runs of the same page paint alike at the
4
+ same instant, so a single mismatching render does not say the two files differ.
5
+ These drive `compare_html` over a stub renderer, because what is under test is
6
+ what it does with a mismatch rather than how a page paints.
7
+ """
8
+
9
+ from pathlib import Path
10
+
11
+ import pytest
12
+ from PIL import Image
13
+
14
+ from htmlcmp import common
15
+
16
+ TEST1 = Path(__file__).parent / "test1.html"
17
+
18
+
19
+ def images(same: bool):
20
+ """A `html_render_diff` result that says the pair matches, or does not."""
21
+ diff = Image.new("RGB", (4, 4), (0, 0, 0) if same else (255, 0, 0))
22
+ return diff, (Image.new("RGB", (4, 4)), Image.new("RGB", (4, 4)))
23
+
24
+
25
+ def renderer(pattern, calls):
26
+ """Stands in for `html_render_diff`, answering `pattern` in turn."""
27
+
28
+ def render(a, b, browser=None):
29
+ calls.append((a, b))
30
+ return images(pattern[min(len(calls) - 1, len(pattern) - 1)])
31
+
32
+ return render
33
+
34
+
35
+ def test_a_mismatch_that_does_not_come_back_is_a_match(monkeypatch):
36
+ calls = []
37
+ monkeypatch.setattr(common, "html_render_diff", renderer([False, True], calls))
38
+
39
+ assert common.compare_html(TEST1, TEST1, browser=object()) is True
40
+ assert len(calls) == 2
41
+
42
+
43
+ def test_a_mismatch_that_comes_back_is_reported(monkeypatch, tmp_path):
44
+ calls = []
45
+ monkeypatch.setattr(common, "html_render_diff", renderer([False], calls))
46
+
47
+ assert (
48
+ common.compare_html(TEST1, TEST1, browser=object(), diff_output=tmp_path)
49
+ is False
50
+ )
51
+ assert len(calls) == 2
52
+ assert (tmp_path / "a.png").is_file()
53
+ assert (tmp_path / "b.png").is_file()
54
+ assert (tmp_path / "diff.png").is_file()
55
+
56
+
57
+ def test_a_match_is_rendered_once(monkeypatch):
58
+ calls = []
59
+ monkeypatch.setattr(common, "html_render_diff", renderer([True], calls))
60
+
61
+ assert common.compare_html(TEST1, TEST1, browser=object()) is True
62
+ assert len(calls) == 1
63
+
64
+
65
+ def test_retries_zero_reports_the_first_render(monkeypatch):
66
+ calls = []
67
+ monkeypatch.setattr(common, "html_render_diff", renderer([False, True], calls))
68
+
69
+ assert common.compare_html(TEST1, TEST1, browser=object(), retries=0) is False
70
+ assert len(calls) == 1
71
+
72
+
73
+ def test_retries_is_a_count(monkeypatch):
74
+ calls = []
75
+ monkeypatch.setattr(common, "html_render_diff", renderer([True], calls))
76
+
77
+ with pytest.raises(ValueError):
78
+ common.compare_html(TEST1, TEST1, browser=object(), retries=-1)
79
+ with pytest.raises(ValueError):
80
+ common.compare_html(TEST1, TEST1, browser=object(), retries="two")
File without changes
File without changes
File without changes