Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

tools: screendiff.py names an --out or --diff it cannot write

xbsheng65d2abff5d2c
diff --git a/tests/test_screendiff.py b/tests/test_screendiff.py
index cbac80bd2..5a0f13c95 100644
--- a/tests/test_screendiff.py
+++ b/tests/test_screendiff.py
@@ -6,6 +6,12 @@ the picture it writes must hide what the person blurred (the Wi-Fi name) in both
arguments are checked before anything is read. The image tests need Pillow, which CI does not
install (it is optional, in tools/requirements-perf.txt), so they skip without it.
+`--out` and `--diff` are judged the same way, before the screenshots are opened and before Pillow is
+imported: exit status 1 is the page's word for "the two screenshots differ", so a folder typed wrong, a
+folder given in place of a file name, a file in the middle of the path and a name with no extension are
+all exit 2 with the path named. A write that fails once it has started - Pillow answers that with OSError,
+and an extension it does not know with ValueError - is also named, not left as a traceback with exit 1.
+
Run from the repository root: python3 -m unittest discover -s tests -v
"""
import argparse
@@ -14,6 +20,8 @@ import importlib.util
import io
import os
from pathlib import Path
+import subprocess
+import sys
import tempfile
import unittest
@@ -139,6 +147,116 @@ class CompareTest(unittest.TestCase):
blurred = pair.crop((left, 60, left + 60, 80))
self.assertNotEqual(list(blurred.getdata()), list(original.getdata()))
+ def test_a_run_with_both_pictures_still_writes_both(self):
+ a, b = self.shot("a.png"), self.shot("b.png")
+ out = os.path.join(self.tmp.name, "pair.png")
+ diff = os.path.join(self.tmp.name, "diff.png")
+ code, text = self.run_tool([a, b, "--out", out, "--diff", diff])
+ self.assertEqual(code, 0)
+ self.assertIn(f"{out}: written", text)
+ self.assertTrue(os.path.isfile(out) and os.path.isfile(diff))
+
+ def test_a_write_that_cannot_start_is_named_not_a_difference(self):
+ if not os.path.exists("/dev/full"):
+ self.skipTest("needs /dev/full, a file whose writes fail with ENOSPC")
+ a, b = self.shot("a.png"), self.shot("b.png")
+ out = os.path.join(self.tmp.name, "full.png")
+ os.symlink("/dev/full", out)
+ code, text = self.run_tool([a, b, "--out", out])
+ self.assertEqual(code, 2, "a failed write must not read as 'the screenshots differ'")
+ self.assertIn(f"cannot write {out}", text)
+ self.assertIn("No space left on device", text)
+ self.assertNotIn("Traceback", text)
+ self.assertNotIn("identical", text)
+ self.assertNotIn("pixels differ", text)
+
+ def test_an_extension_pillow_does_not_know_is_named(self):
+ a, b = self.shot("a.png"), self.shot("b.png")
+ out = os.path.join(self.tmp.name, "pair.txt")
+ code, text = self.run_tool([a, b, "--out", out])
+ self.assertEqual(code, 2)
+ self.assertIn(f"cannot write {out}", text)
+ self.assertIn("unknown file extension", text)
+ self.assertNotIn("Traceback", text)
+ self.assertFalse(os.path.exists(out))
+
+
+class OutputPathTest(unittest.TestCase):
+ """A --out or --diff that cannot be written is exit 2, not the 1 the page reads as 'they differ'."""
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.dir = Path(self.tmp.name)
+
+ def run_tool(self, argv):
+ with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err:
+ code = screendiff.main(argv)
+ return code, out.getvalue(), err.getvalue()
+
+ def test_a_folder_that_is_not_there_is_named(self):
+ out = self.dir / "nope" / "pair.png"
+ code, stdout, stderr = self.run_tool(["before.png", "after.png", "--out", str(out)])
+ self.assertEqual(code, 2)
+ self.assertEqual(stdout, "")
+ self.assertIn(f"--out {out}: there is no folder {out.parent}", stderr)
+ self.assertIn("Nothing was read or written", stderr)
+ self.assertFalse(out.parent.exists())
+
+ def test_the_diff_path_is_checked_the_same_way(self):
+ diff = self.dir / "nope" / "diff.png"
+ code, stdout, stderr = self.run_tool(["before.png", "after.png", "--diff", str(diff)])
+ self.assertEqual(code, 2)
+ self.assertEqual(stdout, "")
+ self.assertIn(f"--diff {diff}: there is no folder", stderr)
+
+ def test_a_folder_as_the_pair_is_refused(self):
+ code, _, stderr = self.run_tool(["before.png", "after.png", "--out", str(self.dir)])
+ self.assertEqual(code, 2)
+ self.assertIn(f"--out {self.dir} is a folder", stderr)
+ self.assertIn("--out shots/before-after.png", stderr)
+
+ def test_a_file_in_the_middle_of_the_path_is_named(self):
+ afile = self.dir / "shots"
+ afile.write_text("", encoding="utf-8")
+ out = afile / "pair.png"
+ code, _, stderr = self.run_tool(["before.png", "after.png", "--out", str(out)])
+ self.assertEqual(code, 2)
+ self.assertIn(f"{afile} is a file, not a folder", stderr)
+
+ def test_a_path_with_no_extension_is_refused(self):
+ out = self.dir / "pair"
+ code, _, stderr = self.run_tool(["before.png", "after.png", "--out", str(out)])
+ self.assertEqual(code, 2)
+ self.assertIn(f"--out {out} has no extension", stderr)
+ self.assertIn(f"name it {out}.png", stderr)
+
+ def test_the_paths_are_judged_before_the_screenshots_are_opened(self):
+ # Neither argument exists, so anything that opened them would say so first.
+ code, _, stderr = self.run_tool(["missing-before.png", "missing-after.png",
+ "--out", str(self.dir / "nope" / "pair.png")])
+ self.assertEqual(code, 2)
+ self.assertIn("there is no folder", stderr)
+ self.assertNotIn("cannot read a screenshot", stderr)
+
+ def test_the_paths_are_judged_before_pillow_is_read(self):
+ """CI has no Pillow, and the folder a reader typed wrong is the likelier failure either way."""
+ with tempfile.TemporaryDirectory() as shadow:
+ blocker = Path(shadow) / "PIL"
+ blocker.mkdir()
+ (blocker / "__init__.py").write_text('raise ImportError("No module named \'PIL\'")\n',
+ encoding="utf-8")
+ env = dict(os.environ, PYTHONPATH=shadow)
+ out = self.dir / "nope" / "pair.png"
+ run = subprocess.run([sys.executable, str(ROOT / "tools" / "screendiff.py"),
+ "before.png", "after.png", "--out", str(out)],
+ cwd=ROOT, env=env, capture_output=True, text=True)
+ self.assertEqual(run.returncode, 2)
+ self.assertIn("there is no folder", run.stderr)
+ self.assertNotIn("requirements-perf.txt", run.stderr, "Pillow was reported first")
+ self.assertNotIn("Traceback", run.stderr)
+ self.assertEqual(run.stdout, "")
+
if __name__ == "__main__":
unittest.main()
diff --git a/tools/screendiff.md b/tools/screendiff.md
index 931652021..540df3d1b 100644
--- a/tools/screendiff.md
+++ b/tools/screendiff.md
@@ -13,7 +13,7 @@ tools/venv/bin/python tools/screendiff.py shots/before.png shots/after.png \
|---|---|---|
| 0 | `identical (1 region masked): ...` | No pixel outside the masks differs by more than 8 |
| 1 | `different: N pixels differ ..., inside x0,y0,x1,y1` | Find out why before posting |
-| 2 | an error | Different sizes, a box outside the picture, an unreadable file |
+| 2 | an error | Different sizes, a box outside the picture, an unreadable file, an `--out` or `--diff` it cannot write |
| Option | Notes |
|---|---|
diff --git a/tools/screendiff.py b/tools/screendiff.py
index 4dd135717..262db8197 100644
--- a/tools/screendiff.py
+++ b/tools/screendiff.py
@@ -13,6 +13,7 @@ Boxes are x0,y0,x1,y1 in the screenshots' pixels. Exit status: 0 identical, 1 di
Needs Pillow (tools/requirements-perf.txt). Read tools/screendiff.md first.
"""
import argparse
+from pathlib import Path
import re
import sys
@@ -29,6 +30,41 @@ def box(text):
return x0, y0, x1, y1
+def output_path(option, path):
+ """The file a picture will be written to, checked before the screenshots are read.
+
+ Exit status 1 is 'the two screenshots differ', a finding the reader acts on, so a folder typed wrong
+ must not come back as one: --out and --diff are judged here, before the images are opened and before
+ Pillow is imported, and a path that cannot be written is named rather than attempted.
+ """
+ if not path:
+ return None
+ target = Path(path)
+ if target.is_dir():
+ raise ValueError(f"{option} {path} is a folder, so nothing could be written there: "
+ f"name the file, e.g. --out shots/before-after.png")
+ if not target.parent.is_dir():
+ if target.parent.is_file():
+ raise ValueError(f"{option} {path}: {target.parent} is a file, not a folder")
+ raise ValueError(f"{option} {path}: there is no folder {target.parent} - create it first")
+ if not target.suffix:
+ raise ValueError(f"{option} {path} has no extension, so its format is unknown: name it {path}.png")
+ return target
+
+
+def write(image, path):
+ """Save one picture, naming the path and the reason if it cannot be written.
+
+ Pillow answers an unwritable destination with OSError and an extension it does not know with
+ ValueError; either left alone ends the run in a traceback with exit 1, the status the page reads as
+ 'the screenshots differ'.
+ """
+ try:
+ image.save(path)
+ except (OSError, ValueError) as e:
+ raise ValueError(f"cannot write {path}: {getattr(e, 'strerror', None) or e}") from e
+
+
def compare(a, b, masks, threshold):
"""(pixels that differ by more than threshold in any channel, their bounding box or None, the largest difference)."""
return _compare(a, b, masks, threshold)[:3]
@@ -106,6 +142,12 @@ def parse(argv):
def main(argv=None):
args = parse(sys.argv[1:] if argv is None else argv)
+ for option, path in (("--out", args.out), ("--diff", args.diff)):
+ try:
+ output_path(option, path)
+ except ValueError as e:
+ print(f"{e}. Nothing was read or written.", file=sys.stderr)
+ return 2
try:
from PIL import Image
except ImportError:
@@ -125,10 +167,18 @@ def main(argv=None):
return 2
count, bbox, worst, diff = _compare(a, b, args.mask, args.threshold)
if args.out:
- pair(a, b, args.blur, args.label_pair, args.scale).save(args.out)
+ try:
+ write(pair(a, b, args.blur, args.label_pair, args.scale), args.out)
+ except ValueError as e:
+ print(f"{e}. The comparison was not reported.", file=sys.stderr)
+ return 2
print(f"{args.out}: written")
if args.diff:
- diff.save(args.diff)
+ try:
+ write(diff, args.diff)
+ except ValueError as e:
+ print(f"{e}. The comparison was not reported.", file=sys.stderr)
+ return 2
masked = f" ({len(args.mask)} region{'s' if len(args.mask) != 1 else ''} masked)" if args.mask else ""
if count == 0:
print(f"identical{masked}: no pixel differs by more than {args.threshold}")