Skip to content

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

tools: the wallpaper script takes a folder, not an option

xbsheng3ae78a16c838
diff --git a/tests/test_scenes_wallpapers_args.py b/tests/test_scenes_wallpapers_args.py
new file mode 100644
index 000000000..803d5ceda
--- /dev/null
+++ b/tests/test_scenes_wallpapers_args.py
@@ -0,0 +1,136 @@
+"""tools/scenes_wallpapers.py takes one argument, the folder to write the 14 scenes into, and read it as a
+folder whatever it was: `scenes_wallpapers.py --help`, the first thing a reader types at an unfamiliar
+script, made a directory named `--help` in the directory they were standing in, filled it with 14 SVGs and
+exited 0 - a stray folder nothing links to, easy to commit by accident. `--out /tmp/scenes`, the shape the
+other tools in tools/ take, would have made a folder called `--out`. And a path that is a file ended in
+os.makedirs' `FileExistsError: [Errno 17] File exists: .../README.md` traceback instead of naming it.
+
+The script now answers -h/--help with its own note and writes nothing, refuses any other leading dash and
+any run that is not exactly one argument, and names a path that is a file. So a test here has to be run,
+not read: every check below executes the script in a folder of its own and looks at what it left there.
+
+The 14 names are not copied in: the scenes' own record is themes/scenes/wallpapers/captions.txt, one
+`<file><TAB><name>` line per picture (themes/README.md), so a fifteenth scene, or a renamed one, fails here
+until the folder and the captions agree.
+
+Run from the repository root: python3 -m unittest discover -s tests -v
+"""
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[1]
+SCRIPT = ROOT / "tools" / "scenes_wallpapers.py"
+CAPTIONS = ROOT / "themes" / "scenes" / "wallpapers" / "captions.txt"
+USAGE_WORDS = ("scenes_wallpapers.py", "<folder>")
+
+
+def caption_names():
+ """The picture names themes/scenes ships a caption for, without the suffix: 01-dusk-peaks, ..."""
+ names = []
+ for line in CAPTIONS.read_text(encoding="utf-8").splitlines():
+ if not line.strip() or line.lstrip().startswith("#"):
+ continue
+ names.append(line.split("\t")[0].strip().rsplit(".", 1)[0])
+ return names
+
+
+def run(*args, cwd):
+ """The script, from `cwd`, with the arguments given: its exit code and both streams, as text."""
+ proc = subprocess.run([sys.executable, str(SCRIPT), *args], cwd=str(cwd),
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120)
+ return proc.returncode, proc.stdout.decode(), proc.stderr.decode()
+
+
+class ScenesWallpapersArgumentsTest(unittest.TestCase):
+ def setUp(self):
+ self._tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self._tmp.cleanup)
+ self.cwd = Path(self._tmp.name)
+
+ def assertNothingWritten(self):
+ self.assertEqual(sorted(p.name for p in self.cwd.iterdir()), [],
+ f"the script wrote into the directory it was run from: {self.cwd}")
+
+ def test_help_prints_the_note_and_writes_nothing(self):
+ code, out, err = run("--help", cwd=self.cwd)
+ self.assertEqual(code, 0, f"--help exited {code}: {err}")
+ for word in USAGE_WORDS:
+ self.assertIn(word, out, "--help does not print the script's own usage line")
+ self.assertIn("themes/scenes/wallpapers", out, "--help no longer says where the JPEGs live")
+ self.assertNothingWritten()
+
+ def test_help_does_not_make_a_folder_named_after_the_option(self):
+ # The defect itself: the option became the folder, and 14 SVGs went into a directory called --help.
+ run("--help", cwd=self.cwd)
+ self.assertFalse((self.cwd / "--help").exists(),
+ "a run with --help made a directory named '--help'")
+
+ def test_short_help_is_the_same_note(self):
+ code, out, _ = run("-h", cwd=self.cwd)
+ self.assertEqual(code, 0)
+ self.assertEqual(out, run("--help", cwd=self.cwd)[1], "-h and --help print different notes")
+ self.assertNothingWritten()
+
+ def test_an_option_it_does_not_take_is_refused_by_name(self):
+ # --out and --dry-run are what a reader tries on a script with no --help; neither is a folder.
+ for option in ("--out", "--dry-run"):
+ with self.subTest(option=option):
+ code, out, err = run(option, cwd=self.cwd)
+ self.assertEqual(code, 2, f"{option} was not refused (exit {code}, stdout {out!r})")
+ self.assertIn(option, err, f"{option} was refused without naming it")
+ self.assertIn("scenes_wallpapers.py", err, "the refusal does not print the usage line")
+ self.assertNotIn("Traceback", err)
+ self.assertFalse((self.cwd / option).exists(), f"made a folder called {option}")
+ self.assertNothingWritten()
+
+ def test_help_beside_a_folder_is_a_mistake_not_a_run(self):
+ code, _, err = run("-h", "scenes", cwd=self.cwd)
+ self.assertEqual(code, 2)
+ self.assertIn("<folder>", err)
+ self.assertNothingWritten()
+
+ def test_no_argument_prints_the_usage_and_names_nothing(self):
+ code, out, err = run(cwd=self.cwd)
+ self.assertEqual(code, 2, "a run with no folder should say so, not write scenes somewhere")
+ self.assertIn("<folder>", err)
+ self.assertNotIn("scenes written", out)
+ self.assertNothingWritten()
+
+ def test_two_folders_are_refused(self):
+ code, out, err = run("scenes", "more", cwd=self.cwd)
+ self.assertEqual(code, 2)
+ self.assertIn("<folder>", err)
+ self.assertNotIn("scenes written", out)
+ self.assertNothingWritten()
+
+ def test_a_file_is_named_instead_of_a_traceback(self):
+ picture = self.cwd / "README.md"
+ picture.write_text("not a folder\n", encoding="utf-8")
+ code, _, err = run(str(picture), cwd=self.cwd)
+ self.assertEqual(code, 2, f"a file as the folder exited {code}")
+ self.assertIn(str(picture), err, "the refusal does not name the path")
+ self.assertNotIn("Traceback", err, "a file as the folder still ends in a traceback")
+ self.assertEqual(picture.read_text(encoding="utf-8"), "not a folder\n", "the file was changed")
+
+ def test_the_scenes_land_in_the_folder_as_promised(self):
+ out_dir = self.cwd / "scenes"
+ code, out, err = run(str(out_dir), cwd=self.cwd)
+ self.assertEqual(code, 0, f"a plain run exited {code}: {err}")
+ self.assertIn(str(out_dir), out, "a plain run does not say where it wrote")
+ written = sorted(p.name for p in out_dir.iterdir())
+ expected = [f"{name}.svg" for name in caption_names()]
+ self.assertGreaterEqual(len(expected), 10, "read no picture names out of captions.txt")
+ self.assertEqual(written, sorted(expected),
+ "the SVGs written and the captions themes/scenes ships do not name the same set")
+ for name in written:
+ head = (out_dir / name).read_text(encoding="utf-8")[:200]
+ self.assertIn("<svg", head, f"{name} is not an SVG")
+ self.assertIn('width="1280"', head, f"{name} is not 1280 px wide")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/scenes_wallpapers.py b/tools/scenes_wallpapers.py
index cd64140b7..751876f7e 100644
--- a/tools/scenes_wallpapers.py
+++ b/tools/scenes_wallpapers.py
@@ -1,7 +1,7 @@
"""Draws the wallpapers of themes/scenes: 14 dark illustrated landscapes, as SVG (1280x720) from code, so the
collection is this repo's own work and can be changed or extended here.
- python3 tools/scenes_wallpapers.py /tmp/scenes # writes 01-dusk-peaks.svg ... 14-autumn-valley.svg
+ python3 tools/scenes_wallpapers.py <folder> # writes 01-dusk-peaks.svg ... 14-autumn-valley.svg
Every scene keeps its lower third dark, because the dock, the grid and the text sit there. The random seeds are
fixed, so the same code always draws the same SVGs.
@@ -376,10 +376,39 @@ SCENES = [("01-dusk-peaks", dusk_peaks), ("02-golden-coast", golden_coast), ("03
("10-city-lights", city_lights), ("11-balloon-sunrise", balloon_sunrise), ("12-monsoon", monsoon),
("13-lighthouse-coast", lighthouse_coast), ("14-autumn-valley", autumn_valley)]
+# ---- the one argument ---------------------------------------------------------------------------
+
+USAGE = "usage: scenes_wallpapers.py <folder> (the folder to write the 14 SVGs into; -h for the rest)"
+
+
+def target(argv):
+ """The folder to write into, from the command line; anything that is not one is refused here.
+
+ 'scenes_wallpapers.py --help' used to take the option for the folder: it made a directory called
+ '--help' in whatever directory the reader stood in and filled it with 14 SVGs, and said so with exit 0.
+ So -h/--help now prints this script's own note and writes nothing, any other leading dash is refused
+ ('--out x' would otherwise become a folder called '--out'), and a path that exists but is not a folder
+ is named instead of ending in os.makedirs' FileExistsError traceback.
+ """
+ if argv in (["-h"], ["--help"]):
+ print((__doc__ or USAGE).strip())
+ sys.exit(0)
+ if len(argv) != 1:
+ print(USAGE, file=sys.stderr)
+ sys.exit(2)
+ out = argv[0]
+ if out.startswith("-"):
+ print(f"scenes_wallpapers.py takes one folder and no options, so {out} is not one.\n{USAGE}",
+ file=sys.stderr)
+ sys.exit(2)
+ if os.path.exists(out) and not os.path.isdir(out):
+ print(f"scenes_wallpapers.py: {out} is a file, and the scenes need a folder", file=sys.stderr)
+ sys.exit(2)
+ return out
+
+
if __name__ == "__main__":
- if len(sys.argv) != 2:
- sys.exit(__doc__)
- out = sys.argv[1]
+ out = target(sys.argv[1:])
os.makedirs(out, exist_ok=True)
for name, scene in SCENES:
with open(os.path.join(out, f"{name}.svg"), "w") as f: