A finished picture's key named its route, its options and its layers' keys, but not the credit
it draws from a pick. A pick whose author or licence changed while its file stayed the same kept
its photo layer's key, so the stored picture was served again with the old credit drawn on it,
while X-Credits already said the new one (seen locally for 1967, whose author lost Commons'
"upload by" appendix).
finished_key now also takes every text the picture draws from a pick: the credit of each layer
made from a pick's photo (Layer.from_pick, season and layout picks alike). A map's credit follows
its source, which its layer key already names. A picture drawn from no pick adds nothing to the
digest, so its key is the one it had: no kept race, session or pick-less season picture is drawn
again. Seen locally with the old store in place: the race poster, the session thumbnail and the
season poster with bg=none came from the store under their old keys; the 1967 and 1989 season
posters were drawn once under new keys. No release of master ever held a photo pick (neither
seasons/photos.json nor circuits/photos.json), so the running service keeps no picture whose key
changes.
The keys test: the same photo with another credit makes another key (on the old code finished_key
takes no credit; with the credit ignored the keys are equal), and a picture drawn from no pick
keeps the digest of render version, route, options and layer keys it had.
Builds: docs/posters.md at f6b9f937d0 (Finished images: the key names the credit of each layer drawn from a pick; Principles, 2: a changed input makes a new key)
Claude-Session: https://claude.ai/code/session_01JG73KFhbaNj3tyJ8tKmE3W
247 lines
16 KiB
Python
247 lines
16 KiB
Python
"""A poster's sources, credits, licence, options, keys and cache headers (docs/posters.md).
|
||
|
||
Standard library only (no PIL, no numpy), so the merge check runs it as it is.
|
||
"""
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import tempfile
|
||
import unittest
|
||
from pathlib import Path
|
||
|
||
import poster_options as po
|
||
import poster_sources as ps
|
||
|
||
ROOT = Path(__file__).resolve().parent.parent
|
||
|
||
|
||
class SatelliteChainTest(unittest.TestCase):
|
||
def test_the_first_source_that_has_the_layout(self):
|
||
early = 2016 if ps.EOX_2016_FOR_EARLY_LAYOUTS else 2025 # the one switch for EOX's year
|
||
photo, use_map = {"file": "A.jpg", "licence": "CC BY 4.0"}, {"use": "map"}
|
||
both = {**photo, **use_map}
|
||
cases = [
|
||
# (country, circuit, layout, the layout's entry in circuits/photos.json) → (source, year, tint)
|
||
(("bahrain", "bahrain-international-circuit", "2004-", photo), ("eox", early, None)), # a pick is bg=photo's
|
||
(("united-states", "miami-international-autodrome", "2022-", photo), ("usgs", None, None)),
|
||
(("netherlands", "circuit-park-zandvoort", "2020-", use_map), ("pdok", None, None)), # national wins
|
||
(("france", "circuit-paul-ricard", "2018-", None), ("ign", "2021-2023", None)),
|
||
(("bahrain", "bahrain-international-circuit", "2004-", None), ("eox", early, None)), # first raced by 2016
|
||
(("bahrain", "bahrain-international-circuit", "2004-", use_map), ("osm", None, "dark")), # the override
|
||
(("bahrain", "bahrain-international-circuit", "2004-", both), ("osm", None, "dark")), # a photo beside it
|
||
(("united-states", "miami-international-autodrome", "2022-", both), ("usgs", None, None)),
|
||
(("spain", "madring", "2026-", None), ("eox", 2025, None)),
|
||
]
|
||
for given, expected in cases:
|
||
chosen = ps.satellite_source(*given)
|
||
self.assertEqual((chosen.id, chosen.year, chosen.tint), expected, given)
|
||
self.assertEqual(ps.satellite_source("bahrain", "x", "2004-", use_map).credit, ps.OSM_CREDIT)
|
||
|
||
def test_bg_photo_takes_the_pick_else_the_satellite_chain(self):
|
||
photo = {"file": "A.jpg", "licence": "CC BY-SA 4.0"}
|
||
self.assertEqual(ps.photo_source("united-states", "miami-international-autodrome", "2022-", photo), ps.COMMONS)
|
||
self.assertEqual(ps.photo_source("bahrain", "bahrain-international-circuit", "2004-", {**photo, "use": "map"}),
|
||
ps.COMMONS) # with use: map beside the photo, bg=photo still draws the photo
|
||
for entry, source in ((None, "usgs"), ({"use": "map"}, "usgs")):
|
||
self.assertEqual(ps.photo_source("united-states", "miami-international-autodrome", "2022-", entry).id, source)
|
||
self.assertEqual(ps.photo_source("bahrain", "bahrain-international-circuit", "2004-", {"use": "map"}).tint, "dark")
|
||
options = po.parse_options([("bg", "photo")], "race")
|
||
self.assertEqual(options.bg, "photo")
|
||
self.assertTrue(all(po.parse_options([("style", style)], kind).bg == "satellite"
|
||
for style in po.STYLES for kind in po.FRAME_OF)) # never a style's default
|
||
|
||
def test_every_french_layout_takes_ign(self):
|
||
france = json.loads((ROOT / "circuits" / "circuits.json").read_text(encoding="utf-8"))["france"]
|
||
layouts = [(slug, layout) for locality in france["localities"].values()
|
||
for slug, circuit in locality["circuits"].items() for layout in circuit["layouts"]]
|
||
self.assertTrue(layouts)
|
||
for slug, layout in layouts:
|
||
self.assertEqual(ps.satellite_source("france", slug, layout).id, "ign", (slug, layout))
|
||
|
||
|
||
class CreditAndLicenceTest(unittest.TestCase):
|
||
def test_credit_line_and_its_header(self):
|
||
line = ps.credit_line([ps.ign().credit, ps.OSM_CREDIT, ps.OSM_CREDIT, ""])
|
||
self.assertEqual(line, "© IGN – BD ORTHO, 2021–2023 · © OpenStreetMap contributors")
|
||
self.assertEqual(ps.ascii_header(line), "(c) IGN - BD ORTHO, 2021-2023 | (c) OpenStreetMap contributors")
|
||
self.assertEqual(ps.ascii_header("Photo: José Müller — 王 CC BY-SA 4.0"), "Photo: Jose Muller - ? CC BY-SA 4.0")
|
||
self.assertEqual(ps.ascii_header("Steffen Prößdorf, Søren Bækgaard, Œuvre, Đorđe"),
|
||
"Steffen Prossdorf, Soren Baekgaard, OEuvre, Dorde")
|
||
|
||
def test_a_pictures_licence_follows_its_sources(self):
|
||
by_sa = ps.pick_share({"licence": "CC BY-SA 3.0 de"})
|
||
cases = [
|
||
([by_sa, ps.osm().share], "CC BY-SA 4.0"),
|
||
([ps.eox(2025).share, ps.osm().share], "CC BY-NC-SA 4.0"),
|
||
([ps.eox(2016).share, ps.osm().share], "CC BY 4.0"),
|
||
([ps.pick_share({"licence": "CC BY 2.0"}), ps.usgs().share, ps.pdok().share, ps.ign().share], "CC BY 4.0"),
|
||
([], "CC BY 4.0"),
|
||
]
|
||
for shares, licence in cases:
|
||
self.assertEqual(ps.picture_licence(shares), licence, shares)
|
||
with self.assertRaises(ps.LicenceClash):
|
||
ps.picture_licence([by_sa, ps.eox(2025).share])
|
||
# 2.5 and the ported licences allow a later version with the same elements, as 2.0 and 3.0 do
|
||
for licence in ("CC BY-SA 2.5", "CC BY-SA 2.0 de", "CC BY-SA 3.0 de", "CC BY-SA 3.0 nl"):
|
||
self.assertTrue(ps.is_free_licence(licence), licence)
|
||
self.assertEqual(ps.picture_licence([ps.pick_share({"licence": licence})]), "CC BY-SA 4.0", licence)
|
||
|
||
def test_picks_skip_notes_and_refuse_what_they_cannot_use(self):
|
||
with tempfile.TemporaryDirectory() as kept:
|
||
path = Path(kept) / "photos.json"
|
||
def photo(file, licence):
|
||
return {"file": file, "licence": licence, "author": "A", "credit": "Photo: A", "date": "2020"}
|
||
path.write_text(json.dumps({
|
||
"$comment": "a note",
|
||
"a/b/c/2004-": photo("A.jpg", "CC BY-SA 4.0"),
|
||
"a/b/c/2010": photo("C.jpg", "Public domain"),
|
||
"a/b/c/2020-": {"use": "map"},
|
||
"a/b/c/2021-": {**photo("D.jpg", "CC0"), "use": "map"},
|
||
"a/b/c/1950-": photo("B.jpg", "CC BY-NC-SA 2.0"), # refused: not a free licence
|
||
"a/b/c/1990": {"use": "satellite"}, # refused: an unknown use
|
||
"a/b/c/1991": {"use": "map", "file": "E.jpg", "licence": "CC0"}, # refused: incomplete photo fields
|
||
"a/b/c/1992": {}, # refused: neither
|
||
}))
|
||
with self.assertLogs(ps.logger, "ERROR") as logged:
|
||
self.assertEqual(sorted(ps.read_picks(path)), ["a/b/c/2004-", "a/b/c/2010", "a/b/c/2020-", "a/b/c/2021-"])
|
||
self.assertEqual(len(logged.output), 4)
|
||
for name in ("circuits/photos.json", "seasons/photos.json"):
|
||
self.assertEqual(ps.read_picks(ROOT / name).get("$comment"), None, name)
|
||
# Every season from 1950 to 2026 has its picked photo, keyed in year order, and the reader accepts each one
|
||
written = json.loads((ROOT / "seasons/photos.json").read_text(encoding="utf-8"))
|
||
seasons = [str(year) for year in range(1950, 2027)]
|
||
self.assertEqual([key for key in written if not key.startswith("$")], seasons)
|
||
self.assertEqual(list(ps.read_picks(ROOT / "seasons/photos.json")), seasons)
|
||
for year in seasons: # where the date was read when Commons' own date cannot be when the photo was taken
|
||
self.assertIn(written[year].get("date_from", "description"), ("description", "category", "upload"), year)
|
||
|
||
def test_the_table_of_picks_names_the_match_per_season(self):
|
||
"""seasons/picks.md: one row per picked season, newest first, its file and licence those of
|
||
seasons/photos.json, its match one of the design's four (docs/posters.md, Season posters)."""
|
||
matches = ("same car", "same model, other livery", "same team and season", "champion")
|
||
picks = ps.read_picks(ROOT / "seasons/photos.json")
|
||
rows = []
|
||
for line in (ROOT / "seasons/picks.md").read_text(encoding="utf-8").splitlines():
|
||
if line.startswith("| ") and line[2:6].isdigit():
|
||
rows.append([cell.strip() for cell in line.strip().strip("|").split(" | ")])
|
||
self.assertEqual([row[0] for row in rows], sorted(picks, key=int, reverse=True))
|
||
for year, curated, file, licence, match, why in rows:
|
||
self.assertEqual((file, licence), (picks[year]["file"], picks[year]["licence"]), year)
|
||
self.assertIn(match, matches, year)
|
||
self.assertTrue(curated and why, year)
|
||
|
||
def test_the_picks_routes_answer_the_picks_as_the_service_has_them_loaded(self):
|
||
photo = {"file": "A.jpg", "licence": "CC BY 4.0", "author": "A", "credit": "Photo: A", "date": "2020"}
|
||
refused = {"use": "satellite"}
|
||
cases = [
|
||
# (route, the file the poster service reads, a pick's key in it)
|
||
("/picks/circuits.json", "circuits/photos.json", "a/b/c/2004-"),
|
||
("/picks/seasons.json", "seasons/photos.json", "2024"),
|
||
]
|
||
self.assertEqual(sorted(ps.PICKS_ROUTES), sorted(route for route, _, _ in cases))
|
||
with tempfile.TemporaryDirectory() as kept:
|
||
root = Path(kept)
|
||
picks = ps.Picks(root)
|
||
for route, name, key in cases:
|
||
path = ps.PICKS_ROUTES[route]
|
||
self.assertEqual(path, Path(name), route)
|
||
(root / name).parent.mkdir()
|
||
(root / name).write_text(json.dumps({"$comment": f"a note on {name}", key: photo, "x": refused}))
|
||
os.utime(root / name, (1, 1))
|
||
with self.assertLogs(ps.logger, "ERROR"): # the refused entry, logged once when read
|
||
self.assertEqual(picks.entries(path), {key: photo}, route) # what the service draws from
|
||
answer = picks.answer(path)
|
||
self.assertEqual(list(answer), ["$comment", key], route) # its notes first, the refused one left out
|
||
self.assertEqual(answer, {"$comment": f"a note on {name}", key: photo}, route)
|
||
(root / name).write_text(json.dumps({key: {"use": "map"}}))
|
||
os.utime(root / name, (2, 2)) # a changed file is read again
|
||
self.assertEqual(picks.answer(path), {key: {"use": "map"}}, route)
|
||
|
||
def test_licences_name_every_source_and_the_pictures_rule(self):
|
||
licences = ps.licences()
|
||
self.assertEqual([entry["licence"] for entry in licences["pictures"]["licences"]],
|
||
["CC BY-SA 4.0", "CC BY-NC-SA 4.0", "CC BY 4.0"])
|
||
self.assertEqual([source["id"] for source in licences["sources"]],
|
||
["commons", "usgs", "pdok", "ign"] + (["eox-2016"] if ps.EOX_2016_FOR_EARLY_LAYOUTS else [])
|
||
+ ["eox", "osm", "jolpica", "traces"])
|
||
for source in licences["sources"]:
|
||
for field in ("name", "used_for", "licence", "licence_url", "credit", "terms", "picture_licence"):
|
||
self.assertTrue(source[field], f"{source['id']} has no {field}")
|
||
|
||
|
||
class OptionsTest(unittest.TestCase):
|
||
def parse(self, query: str, kind: str = "race") -> po.Options:
|
||
return po.parse_options([tuple(part.split("=", 1)) for part in query.split("&") if part], kind)
|
||
|
||
def test_presets_per_kind(self):
|
||
race, thumb, season = self.parse(""), self.parse("", "session"), self.parse("", "season")
|
||
self.assertEqual((race.bg, race.photo, race.checker, race.locator, race.dim, race.track, race.width),
|
||
("satellite", "natural", True, True, 0.43, ("#ffffff", 6), 1000))
|
||
self.assertEqual((thumb.checker, thumb.locator, thumb.width), (False, False, 1920)) # classic: as before
|
||
self.assertEqual(sorted(self.parse("style=minimal", "session").show), ["name", "session"])
|
||
self.assertEqual(sorted(self.parse("style=minimal").show), ["date", "name"])
|
||
self.assertEqual(sorted(season.show), ["name", "subtitle", "wordmark"])
|
||
# Any option given overrides the style; equal pictures share one canonical form, whatever their address
|
||
self.assertEqual(self.parse("style=minimal&checker=on").checker, True)
|
||
self.assertEqual(self.parse("bg=aerial&v=r1").canonical(), self.parse("").canonical())
|
||
# Kept for good: an address with the address version, never one with the render version it carried before
|
||
self.assertTrue(self.parse(f"v={po.ADDRESS_VERSION}").versioned)
|
||
self.assertNotEqual(po.ADDRESS_VERSION, po.RENDER_VERSION)
|
||
self.assertFalse(self.parse("v=r3").versioned)
|
||
self.assertFalse(self.parse("v=r2").versioned)
|
||
|
||
def test_an_unknown_option_or_value_is_named(self):
|
||
cases = {
|
||
"colour=red": "'colour'", "bg=esri": "'esri'", "photo=duotone": "'duotone'", "show=name,logo": "'logo'",
|
||
"track=#fff": "'#fff'", "track=#ffffff,31": "'#ffffff,31'", "dim=1.5": "'1.5'", "dim=nan": "'nan'",
|
||
"width=399": "takes 400", "width=1001": "'1001'", "format=gif": "'gif'", "bg=osm&bg=dark": "'bg'",
|
||
"locator=yes": "'yes'", "accent=red": "'red'",
|
||
}
|
||
for query, named in cases.items():
|
||
with self.assertRaises(po.OptionError, msg=query) as caught:
|
||
self.parse(query)
|
||
self.assertIn(named, str(caught.exception), query)
|
||
self.assertEqual(self.parse("width=1920", "session").width, 1920)
|
||
|
||
def test_keys(self):
|
||
options = self.parse("")
|
||
key = po.finished_key("race/Bahrain Grand Prix/2024", options, ["map/eox-2016/x-poster-z15-r3"])
|
||
self.assertNotEqual(key, po.finished_key("race/Bahrain Grand Prix/2024", self.parse("photo=bw"),
|
||
["map/eox-2016/x-poster-z15-r3"]))
|
||
self.assertNotEqual(key, po.finished_key("race/Bahrain Grand Prix/2023", options,
|
||
["map/eox-2016/x-poster-z15-r3"]))
|
||
self.assertTrue(key.endswith(".png"))
|
||
self.assertTrue(po.finished_key("race/Bahrain Grand Prix/2024", self.parse("format=webp"), []).endswith(".webp"))
|
||
# A changed credit with the same photo makes a new key; a picture drawn from no pick keeps the key it had
|
||
season, photo = self.parse("", "season"), ["photo/a1b2c3-sha1-poster-r3"]
|
||
credited = po.finished_key("season/1967", season, photo, ["Photo: A, CC BY 2.0, via Wikimedia Commons"])
|
||
self.assertNotEqual(credited, po.finished_key("season/1967", season, photo,
|
||
["Photo: B, CC BY 2.0, via Wikimedia Commons"]))
|
||
before = hashlib.sha256(f"{po.RENDER_VERSION}\nrace/Bahrain Grand Prix/2024\n{options.canonical()}\n"
|
||
"map/eox-2016/x-poster-z15-r3".encode()).hexdigest()
|
||
self.assertEqual(key, f"{before[:40]}.png")
|
||
self.assertEqual(po.locator_layer_key(26.0325, 50.5106), f"locator/26.03_50.51-{po.RENDER_VERSION}")
|
||
self.assertIn(po.RENDER_VERSION, po.map_layer_key("eox-2025", po.trace_hash([[1, 2]]), "thumb", 15))
|
||
|
||
|
||
class CachingTest(unittest.TestCase):
|
||
def test_what_clients_keep(self):
|
||
self.assertEqual(po.cache_headers(True, True, '"e"'),
|
||
{"Cache-Control": "public, max-age=31536000, immutable", "ETag": '"e"'})
|
||
self.assertEqual(po.cache_headers(True, False, '"e"'), {"Cache-Control": "public, max-age=86400", "ETag": '"e"'})
|
||
self.assertEqual(po.cache_headers(False, True, '"e"'), {"Cache-Control": "public, max-age=300"})
|
||
for asked in ('"a", W/"e"', '"e"', 'W/"e"', "*"):
|
||
self.assertTrue(po.etag_matches(asked, 'W/"e"'), asked) # the weak comparison
|
||
self.assertFalse(po.etag_matches("", 'W/"e"'))
|
||
self.assertFalse(po.etag_matches('W/"a"', 'W/"e"'))
|
||
|
||
def test_the_least_recently_used_go_first(self):
|
||
entries = {"old": (1.0, 600), "new": (3.0, 600), "mid": (2.0, 600)}
|
||
self.assertEqual(po.evictions(entries, 1300), ["old"])
|
||
self.assertEqual(po.evictions(entries, 600), ["old", "mid"])
|
||
self.assertEqual(po.evictions(entries, 1800), [])
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|