Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,17 @@ A page is screenshotted once it has stopped changing:
- two frames have been painted since

Waiting stops after 10 seconds, and the page is screenshotted as it is then.
`--settle-timeout` changes that limit in `compare-html`, `compare-html-server`
and `html-render-diff`.

## Browser timeouts in the CLI

`compare-html --timeout 120` limits each browser comparison to 120 seconds,
including browser startup, both screenshots, and any `--retries` of a pixel
mismatch. The deadline starts when a worker takes the file, not while it waits
in the queue. Use a larger positive value for especially expensive pages.
Each screenshot may wait up to `--settle-timeout` for its page, so keep
`--timeout` above twice that times one more than `--retries`.
The same value configures WebDriver's HTTP and page-load timeouts, so increasing
the deadline is not cut short by Selenium's default 120-second HTTP timeout.

Expand Down
14 changes: 11 additions & 3 deletions src/htmlcmp/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import filecmp
from pathlib import Path

from htmlcmp import defaults
from htmlcmp.html_render_diff import get_browser, html_render_diff

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -43,7 +44,12 @@ def compare_json(a: Path, b: Path) -> bool:


def compare_html(
a: Path, b: Path, browser=None, diff_output: Path = None, retries: int = 1
a: Path,
b: Path,
browser=None,
diff_output: Path = None,
retries: int = defaults.RETRIES,
settle_timeout: float = defaults.SETTLE_TIMEOUT,
) -> bool:
"""Whether `a` and `b` render to the same pixels.

Expand All @@ -61,10 +67,12 @@ def compare_html(
raise ValueError(f"retries must be a non-negative int, got {retries!r}")

if browser is None:
browser = get_browser("firefox")
browser = get_browser(defaults.DRIVER)

for attempt in range(retries + 1):
diff, (image_a, image_b) = html_render_diff(a, b, browser=browser)
diff, (image_a, image_b) = html_render_diff(
a, b, browser=browser, settle_timeout=settle_timeout
)
if diff.getbbox() is None:
return True
logger.debug(
Expand Down
43 changes: 32 additions & 11 deletions src/htmlcmp/compare_output_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,13 @@
TimeRemainingColumn,
)

from htmlcmp import defaults
from htmlcmp.common import comparable_file, setup_logging
from htmlcmp.comparison_worker import ComparisonExecutor
from htmlcmp.html_render_diff import (
add_settle_timeout_argument,
check_settle_timeout,
)

logger = logging.getLogger(__name__)

Expand All @@ -31,7 +36,12 @@ class Task:
"""A single file comparison between the reference (A) and monitored (B) tree."""

def __init__(
self, rel: Path, a: Path, b: Path, diff_output: Path = None, retries: int = 1
self,
rel: Path,
a: Path,
b: Path,
diff_output: Path = None,
retries: int = defaults.RETRIES,
):
self.rel = rel
self.a = a
Expand All @@ -53,7 +63,11 @@ def __init__(self, rel: Path, kind: str, reason: str):


def collect_tasks(
a: Path, b: Path, rel: Path = Path(), diff_output: Path = None, retries: int = 1
a: Path,
b: Path,
rel: Path = Path(),
diff_output: Path = None,
retries: int = defaults.RETRIES,
) -> tuple[list[Task], list[Failure]]:
"""Walk both trees once and return (comparable tasks, structural failures).

Expand Down Expand Up @@ -227,10 +241,13 @@ def run(
console: Console,
live: bool,
github: bool,
timeout: float = 120.0,
timeout: float = defaults.TIMEOUT,
settle_timeout: float = defaults.SETTLE_TIMEOUT,
) -> int:
if not math.isfinite(timeout) or timeout <= 0:
raise ValueError("timeout must be a positive finite number")
if not math.isfinite(settle_timeout) or settle_timeout <= 0:
raise ValueError("settle_timeout must be a positive finite number")
console.print(
f"[bold]Comparing[/bold] {escape(str(a))} [dim]→[/dim] {escape(str(b))}"
)
Expand Down Expand Up @@ -263,6 +280,7 @@ def run(
t.b,
diff_output=t.diff_output,
retries=t.retries,
settle_timeout=settle_timeout,
): t
for t in tasks
}
Expand All @@ -288,9 +306,9 @@ def main():
parser.add_argument(
"--driver",
choices=["chrome", "firefox", "none"],
default="firefox",
default=defaults.DRIVER,
help="Browser used to render HTML diffs; 'none' compares only "
"JSON and byte-identical files (default: firefox)",
"JSON and byte-identical files (default: %(default)s)",
)
parser.add_argument(
"--diff-output", type=Path, help="Directory to write diff images for mismatches"
Expand All @@ -299,8 +317,8 @@ def main():
"-j",
"--max-workers",
type=int,
default=1,
help="Number of parallel comparison workers (default: 1)",
default=defaults.MAX_WORKERS,
help="Number of parallel comparison workers (default: %(default)s)",
)
parser.add_argument(
"--no-progress",
Expand All @@ -317,24 +335,26 @@ def main():
parser.add_argument(
"--retries",
type=int,
default=1,
default=defaults.RETRIES,
help="Re-render a mismatch this many times before reporting it "
"(default: 1; 0 reports the first render)",
"(default: %(default)s; 0 reports the first render)",
)
parser.add_argument(
"--timeout",
type=float,
default=120.0,
default=defaults.TIMEOUT,
help="Deadline in seconds per browser comparison, including startup "
"and mismatch retries (default: 120)",
"and mismatch retries (default: %(default)g)",
)
add_settle_timeout_argument(parser)
parser.add_argument("--log-file", type=Path, help="Path to log file")
parser.add_argument(
"--log-file-verbosity", type=int, help="Log file verbosity level"
)
args = parser.parse_args()
if not math.isfinite(args.timeout) or args.timeout <= 0:
parser.error("--timeout must be a positive finite number")
check_settle_timeout(parser, args.settle_timeout)

setup_logging(args.verbose, args.log_file, args.log_file_verbosity)

Expand All @@ -360,6 +380,7 @@ def main():
live=live,
github=github,
timeout=args.timeout,
settle_timeout=args.settle_timeout,
)


Expand Down
19 changes: 16 additions & 3 deletions src/htmlcmp/compare_output_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,18 @@

from PIL import Image

from htmlcmp import defaults
from htmlcmp.common import (
comparable_file,
compare_files,
setup_logging,
)
from htmlcmp.html_render_diff import get_browser, html_render_diff
from htmlcmp.html_render_diff import (
add_settle_timeout_argument,
check_settle_timeout,
get_browser,
html_render_diff,
)

logger = logging.getLogger(__name__)

Expand All @@ -33,6 +39,7 @@ class Config:
path_a: Path = None
path_b: Path = None
driver: str = None
settle_timeout: float = defaults.SETTLE_TIMEOUT
observer = None
comparator = None
browser = None
Expand Down Expand Up @@ -177,6 +184,7 @@ def compare(self, path: Path) -> None:
Config.path_a / path,
Config.path_b / path,
browser=browser,
settle_timeout=Config.settle_timeout,
)
except Exception:
# A file may have vanished or failed to render between submission
Expand Down Expand Up @@ -374,7 +382,9 @@ def get(self, path: str) -> tuple[bytes, dict]:

logger.debug(f"Rendering diff: {path}")
with Config.browser_lock:
diff, _ = html_render_diff(a, b, Config.browser)
diff, _ = html_render_diff(
a, b, Config.browser, settle_timeout=Config.settle_timeout
)

width, height = diff.size
bbox = diff.getbbox()
Expand Down Expand Up @@ -707,14 +717,15 @@ def main():
parser.add_argument("ref", type=Path, help="Path to the reference directory")
parser.add_argument("mon", type=Path, help="Path to the monitored directory")
parser.add_argument("--driver", choices=["chrome", "firefox"])
parser.add_argument("--max-workers", type=int, default=1)
parser.add_argument("--max-workers", type=int, default=defaults.MAX_WORKERS)
parser.add_argument("--compare", action="store_true")
parser.add_argument(
"--host",
default="0.0.0.0",
help="Host/interface to bind the server to (default: 0.0.0.0)",
)
parser.add_argument("--port", type=int, default=5000)
add_settle_timeout_argument(parser)
parser.add_argument(
"-v",
"--verbose",
Expand All @@ -731,12 +742,14 @@ def main():
"--log-file-verbosity", type=int, help="Log file verbosity level"
)
args = parser.parse_args()
check_settle_timeout(parser, args.settle_timeout)

setup_logging(args.verbose, args.log_file, args.log_file_verbosity)

Config.path_a = args.ref
Config.path_b = args.mon
Config.driver = args.driver
Config.settle_timeout = args.settle_timeout
Config.browser = (
get_browser(driver=args.driver) if args.driver is not None else None
)
Expand Down
5 changes: 3 additions & 2 deletions src/htmlcmp/comparison_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import psutil

from htmlcmp import defaults
from htmlcmp.common import compare_files
from htmlcmp.html_render_diff import get_browser

Expand Down Expand Up @@ -42,7 +43,7 @@ def _compare_loop(connection, driver, timeout):


class ComparisonWorker:
def __init__(self, driver, timeout=120.0):
def __init__(self, driver, timeout=defaults.TIMEOUT):
self.driver = driver
self.timeout = timeout
self._process = None
Expand Down Expand Up @@ -120,7 +121,7 @@ def close(self, *, abort=False):


class ComparisonExecutor(ThreadPoolExecutor):
def __init__(self, max_workers, driver, timeout=120.0):
def __init__(self, max_workers, driver, timeout=defaults.TIMEOUT):
self._driver = driver
self._timeout = timeout
self._local = threading.local()
Expand Down
15 changes: 15 additions & 0 deletions src/htmlcmp/defaults.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""Defaults shared by the library functions and the command line tools."""

#: Browser used to render HTML.
DRIVER = "firefox"
#: Browser window size in pixels; the height fits long pages in one shot.
MAX_WIDTH = 1000
MAX_HEIGHT = 10000
#: Parallel comparison or tidy workers.
MAX_WORKERS = 1
#: How many times a mismatch is rendered again before it is reported.
RETRIES = 1
#: Deadline in seconds per browser comparison.
TIMEOUT = 120.0
#: How long `settle` waits for the page, in seconds.
SETTLE_TIMEOUT = 10.0
Loading
Loading