Cache what has been looked up, make it browsable, and say where this lives
Four things asked for in turn, landing together because they run through the same files. THE MAPS. The tiles were already cached and always had been -- a second evening on the same view was measured at nought network requests -- but the work done on them was not. Every window open decoded forty PNGs and resampled a megapixel and a half into this program's own projection, for an answer that cannot have changed, because a coastline does not move. The finished map is kept beside the tiles now: 0.61 seconds become 0.01, byte for byte identical, two hundred kilobytes a view. Both windows and both kinds of still picture get it, all four reaching the ground through one function. A map with squares missing is deliberately not kept, since caching a hole would keep it for a month and the point of calling a partial map provisional is that it is asked for again. And because this adds a disk consumer, the whole cache is now pruned to four hundred megabytes, least recently *used* first: a tile fetched a year ago and looked at last night is the receiver's own neighbourhood, and discarding that to keep last week's holiday is the wrong way round. THE LOOKUPS. APRS and FT8 now ask who each station is licensed to. Every other mode that hears a callsign already did -- speech transcripts, Morse idents, the recording browser -- and all five resolve through one file, so a callsign heard on two bands is asked about once. The rules for finding the licensed callsign inside a heard one are now in one place rather than per band, because getting them wrong is silent: a register asked about W1AW-9 returns nothing, which looks exactly like a station that is not licensed. An SSID, a rover suffix, a guest prefix, a digipeater alias and an unspelled hash all come off or are refused. The bug worth recording is that the first cut of this did the lookups and threw them away. The book has to be told to save and was not, so every evening would have asked the register about the same net again -- which is the one thing caching them was for, and is invisible from inside a single run because the answers are all in memory while it lasts. Caught by looking at the file on disk rather than at the display. There is a test for each side of it now, and a register of which modules resolve callsigns at all, which fails when a new one starts so that somebody has to decide whether it should. THE REGISTER. c in saunterbrowse opens everything ever looked up: sixty-odd callsigns and sixteen hundred aircraft here, every field of each in two columns because a licence has a dozen and a screen is wider than it is tall. tab switches, / searches every field rather than the name -- the question is usually "who was in Arizona" rather than "which callsign" -- and g opens the place in a browser. Only the coordinates go into that link: a map does not need to be told whose licence it is looking at, and the link is the one part of this that leaves the machine. A headless box, which is the normal case for a receiver, gets the coordinates printed instead. Callsigns no register could place are kept rather than dropped, because "asked about, and in no register reachable from here" is a fact about a station. THE FRONT OF IT. A title screen for each program: five rows of blocks cut by hand, a figlet dependency to draw eleven letters being the largest thing that would then be in the requirements, coloured blue to red across the width, which is the ramp every waterfall here already uses because it is what a spectrum looks like. The interesting part is where it does not appear -- everything here can be piped into something else and a banner in the middle of that is corruption rather than decoration, so anything that is not a terminal gets nothing, --help is untouched because it is drawn after parsing, --no-splash turns it off for a run and BANDSAUNTER_NO_SPLASH=1 for good. And the address. INSTALL.md said "git clone <the repository>" for a long time: a placeholder in the first command anybody types, unnoticed because nothing reads install instructions except somebody installing, who then cannot. It is filled in, along with the readme, the metadata, both manuals and the Homepage field of all three packages. The tile server's User-Agent pointed at a topic listing on somebody else's site for want of an address of its own; the usage policy of that service asks for one naming the application and giving somewhere to look it up, so an operator with a question about the traffic has somebody to ask, and now it gives the real one. Seven tests so the placeholder cannot come back, verified by putting it back and watching two of them fail. One thing forced by all this: the keys page in saunterbrowse was exactly as tall as an eighty-by-twenty-four terminal, so the register entry pushed "q quit" off the bottom. A test caught it. Home and End have merged into the Page Up line, which were always the same thought. THE WINDOWS. They open maximised now, this being a map and the thing anybody wants more of being map; f goes to true full screen and back, and is written along the top of the screen because a window with no frame is one somebody has to know a key to get out of. Maximised rather than frameless by default, because the title bar is where the band and the frequency are written. And a map made bigger now gets a sharper map, which it did not. The window only ever re-examined the ground when the view left the box that had been fetched, so a window opened at its default size and taken to the whole screen kept the map it started with until an aircraft wandered far enough to move it -- on a quiet band, a long time to look at a blurred coastline. Measured before it was believed: 1100 to 1920 asked for nothing and stretched a 1364-pixel map across 1920, then across 3840. It now compares map pixels per degree in hand against what the view wants, and asks when it is being blown up by more than fifteen per cent. That comparison has to be per degree rather than pixel against pixel, which a surviving mutation was what established: the fetched box is a quarter wider than the view, so a map with exactly as many pixels as the window is wide has only four fifths of them on the screen. The two ways of measuring agree everywhere except a narrow band, and the realistic case sits inside it. There is a test pinning that case now. Asking is safe at any size, because the request is keyed on the window's dimensions: once answered, nothing more is asked, which is what stops a window larger than the tile budget can cover from asking all evening. The braille, while this was open. The banners were blocks in capitals; they are braille in mixed case, two dots wide and four tall to a character, which is eight times the detail and is what makes room for two heights of letter at once -- a five-row block font has no second height to spend, so the name came out shouted. Two attempts failed first: thin one-dot strokes came out as confetti, because braille dots render as dots and a one-dot stroke reads as a dotted line rather than a line. What worked was cutting the font small, at cap height seven where there is only one way to draw each letter, and doubling it. Coloured deep blue through cyan to a cool white, which is deliberately not the waterfall ramp the rest of the program draws in: that one has to run to red because it stands in for a spectrum, and a title screen stands in for nothing. One hundred and four new tests. Full suite 2892 passed. Built as 2026-09-24_01. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016PsWPTweCT6pwxKngvVxcg
This commit is contained in:
parent
93120b80a6
commit
2665a17a22
27 changed files with 3733 additions and 49 deletions
|
|
@ -1222,3 +1222,194 @@ def test_a_station_that_never_said_where_it_is_has_no_position_row():
|
|||
rows = dict((label, value) for label, value, _f
|
||||
in ap.station_lines(station_of(">Monitoring 146.52")))
|
||||
assert "position" not in rows
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Who each station is
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _book(tmp_path, entries=()):
|
||||
"""A register that knows what it is told and asks nobody anything."""
|
||||
from bandsaunter.callsign import CACHE_VERSION, Callsign, CallsignBook
|
||||
|
||||
book = CallsignBook(online=False, cache=tmp_path / "callsigns.json")
|
||||
for call, name, where in entries:
|
||||
book._entries[call] = Callsign(
|
||||
call=call, name=name, location=where, status="found",
|
||||
version=CACHE_VERSION, fetched_at=time.time())
|
||||
return book
|
||||
|
||||
|
||||
@pytest.mark.parametrize("given,wanted", [
|
||||
("W1AW-9", "W1AW"), ("KU0W", "KU0W"), ("VK4BLE-7*", "VK4BLE"),
|
||||
("n0call-15", "N0CALL"), ("", ""),
|
||||
])
|
||||
def test_the_licensed_callsign_is_found_inside_the_aprs_one(given, wanted):
|
||||
"""An SSID says which of a station's radios this is -- the ninth is a
|
||||
car, the second a digipeater -- and a star marks the hop a packet came
|
||||
through. No licence register has heard of either."""
|
||||
assert ap.base_call(given) == wanted
|
||||
|
||||
|
||||
def test_a_station_is_looked_up_once_when_it_is_first_heard(tmp_path):
|
||||
book = _book(tmp_path)
|
||||
net = ap.Net(book=book)
|
||||
for _ in range(5):
|
||||
net.add(packet(source="W1AW-9"))
|
||||
net.add(packet(source="KU0W"))
|
||||
# One entry per licensed callsign, not per packet and not per SSID.
|
||||
assert set(book._entries) == {"W1AW", "KU0W"}
|
||||
|
||||
|
||||
def test_an_object_somebody_placed_is_not_looked_up(tmp_path):
|
||||
"""An object is a marker one station put on the map on behalf of
|
||||
something that has no licence of its own -- a net, a hilltop, a
|
||||
storm -- so asking who it is licensed to is asking the wrong question."""
|
||||
book = _book(tmp_path)
|
||||
net = ap.Net(book=book)
|
||||
net.add(packet(";LEADVL *111111z3900.00N/10500.00W- a place",
|
||||
source="W1AW"))
|
||||
assert "LEADVL" not in book._entries
|
||||
|
||||
|
||||
def test_the_name_arrives_without_the_display_waiting_for_it(tmp_path):
|
||||
"""A table that stopped for a network request would stop for every new
|
||||
station on a busy channel."""
|
||||
book = _book(tmp_path)
|
||||
net = ap.Net(book=book)
|
||||
net.add(packet(source="W1AW-9"))
|
||||
who = ap.licensee(net, "W1AW-9")
|
||||
assert who is not None and who.call == "W1AW"
|
||||
# Nothing is known yet and that is not an error.
|
||||
assert ap.who_text(who) in ("", "…", "United States")
|
||||
|
||||
|
||||
def test_a_name_that_has_arrived_is_shown_with_where_it_is(tmp_path):
|
||||
book = _book(tmp_path, [("W1AW", "ARRL HQ Operators Club",
|
||||
"Newington, CT")])
|
||||
net = ap.Net(book=book)
|
||||
net.add(packet(source="W1AW-9"))
|
||||
assert ap.who_text(ap.licensee(net, "W1AW-9")) == \
|
||||
"ARRL HQ Operators Club — Newington, CT"
|
||||
|
||||
|
||||
def test_a_station_the_register_cannot_know_still_says_where_it_is_from():
|
||||
"""The databases are United States registers. A blank cell beside an
|
||||
Australian callsign reads as a lookup that failed rather than as a
|
||||
question that was never going to be answered, and the country comes out
|
||||
of the callsign's own structure with no network at all."""
|
||||
from bandsaunter.callsign import Callsign
|
||||
|
||||
who = Callsign(call="VK4BLE", country="Australia", status="unlisted")
|
||||
assert ap.who_text(who) == "Australia"
|
||||
|
||||
|
||||
def test_no_lookups_at_all_when_they_are_turned_off():
|
||||
book = ap.open_book(ap.AprsOptions(lookup=False))
|
||||
assert book.online is False
|
||||
|
||||
|
||||
def test_the_box_on_the_map_says_who_the_station_is(tmp_path):
|
||||
book = _book(tmp_path, [("W1AW", "ARRL HQ Operators Club",
|
||||
"Newington, CT")])
|
||||
net = ap.Net(book=book)
|
||||
station = net.add(packet(source="W1AW-9"))
|
||||
lines = ap.station_lines(station, None, False, ap.licensee(net, "W1AW-9"))
|
||||
labels = [label for label, _value, _flag in lines]
|
||||
assert labels[:2] == ["licensed to", "at"], labels
|
||||
assert lines[0][1] == "ARRL HQ Operators Club"
|
||||
assert lines[1][1] == "Newington, CT"
|
||||
|
||||
|
||||
def test_the_box_says_nothing_about_a_licence_it_does_not_have(tmp_path):
|
||||
net = ap.Net(book=_book(tmp_path))
|
||||
station = net.add(packet(source="W1AW-9"))
|
||||
lines = ap.station_lines(station, None, False, None)
|
||||
assert "licensed to" not in [label for label, _v, _f in lines]
|
||||
|
||||
|
||||
def test_the_report_gives_a_column_for_who_each_station_is(tmp_path):
|
||||
book = _book(tmp_path, [("W1AW", "ARRL HQ Operators Club",
|
||||
"Newington, CT")])
|
||||
net = ap.Net(book=book)
|
||||
net.add(packet(source="W1AW-9"))
|
||||
console = Console(width=160, force_terminal=False)
|
||||
with console.capture() as caught:
|
||||
ap.report(console, net, ap.AprsOptions(lookup=True))
|
||||
shown = caught.get()
|
||||
assert "licensed to" in shown
|
||||
assert "ARRL HQ Operators Club" in shown
|
||||
|
||||
|
||||
def test_the_report_leaves_the_column_out_when_lookups_are_off(tmp_path):
|
||||
net = ap.Net(book=_book(tmp_path))
|
||||
net.add(packet(source="W1AW-9"))
|
||||
console = Console(width=160, force_terminal=False)
|
||||
with console.capture() as caught:
|
||||
ap.report(console, net, ap.AprsOptions(lookup=False))
|
||||
assert "licensed to" not in caught.get()
|
||||
|
||||
|
||||
def test_the_answers_are_kept_on_the_disk_and_shared(tmp_path):
|
||||
"""The point of the whole thing: the same net logged night after night
|
||||
is asked about once a month, and every part of this program that
|
||||
resolves a callsign reads the same file."""
|
||||
from bandsaunter.callsign import CallsignBook, _cache_path
|
||||
|
||||
book = _book(tmp_path, [("W1AW", "ARRL HQ Operators Club",
|
||||
"Newington, CT")])
|
||||
book._dirty = True
|
||||
book.save()
|
||||
again = CallsignBook(online=False, cache=tmp_path / "callsigns.json")
|
||||
assert again.get("W1AW").name == "ARRL HQ Operators Club"
|
||||
# And by default it is the one file everything else uses.
|
||||
assert _cache_path() == ap.open_book(ap.defaults()).cache_path
|
||||
|
||||
|
||||
def test_the_answers_are_written_to_the_disk_when_the_run_ends(tmp_path):
|
||||
"""Without this the lookups happen and are thrown away, so every
|
||||
evening asks the register about the same net again -- which is the one
|
||||
thing caching them was for, and is invisible from inside a single run
|
||||
because the answers are all in memory while it lasts."""
|
||||
from bandsaunter.callsign import CACHE_VERSION, Callsign, CallsignBook
|
||||
|
||||
where = tmp_path / "callsigns.json"
|
||||
book = CallsignBook(online=False, cache=where)
|
||||
net = ap.Net(book=book)
|
||||
net.add(packet(source="W1AW-9"))
|
||||
book._entries["W1AW"] = Callsign(call="W1AW", name="ARRL HQ",
|
||||
location="Newington, CT",
|
||||
status="found", version=CACHE_VERSION,
|
||||
fetched_at=time.time())
|
||||
book._dirty = True
|
||||
|
||||
heard = ap.Heard()
|
||||
heard.net = net
|
||||
console = Console(width=120, force_terminal=False)
|
||||
with console.capture():
|
||||
ap.finish(console, ap.AprsOptions(report=False, csv=False, kml=False),
|
||||
str(tmp_path), heard)
|
||||
assert where.exists(), "the run ended without writing what it learned"
|
||||
assert CallsignBook(online=False, cache=where).get("W1AW").name == "ARRL HQ"
|
||||
|
||||
|
||||
def test_a_quiet_evening_still_keeps_what_it_learned(tmp_path):
|
||||
"""A run that heard one station and no more still found out who that
|
||||
station was. The early return for an empty net used to skip the
|
||||
saving with it."""
|
||||
from bandsaunter.callsign import CACHE_VERSION, Callsign, CallsignBook
|
||||
|
||||
where = tmp_path / "callsigns.json"
|
||||
book = CallsignBook(online=False, cache=where)
|
||||
book._entries["KU0W"] = Callsign(call="KU0W", name="Rod R Gowdy",
|
||||
status="found", version=CACHE_VERSION,
|
||||
fetched_at=time.time())
|
||||
book._dirty = True
|
||||
heard = ap.Heard()
|
||||
heard.net = ap.Net(book=book) # nothing heard at all
|
||||
console = Console(width=120, force_terminal=False)
|
||||
with console.capture() as caught:
|
||||
ap.finish(console, ap.AprsOptions(report=False), str(tmp_path), heard)
|
||||
assert "nothing heard" in caught.get()
|
||||
assert CallsignBook(online=False, cache=where).get("KU0W").name == \
|
||||
"Rod R Gowdy"
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ in through the same door the real ones come through, and the PNGs are built
|
|||
here from the specification rather than by the decoder they are testing.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import time
|
||||
import zlib
|
||||
|
|
@ -333,10 +334,14 @@ def test_a_missing_tile_is_a_gap_rather_than_the_brightest_thing_on_the_map():
|
|||
so a square that never arrived used to come out as the brightest thing
|
||||
on the picture: a glowing rectangle where the map should be."""
|
||||
zoom, hole = _hole_at()
|
||||
# remember=False throughout: these two are the same view with different
|
||||
# tiles under it, which cannot happen on the air and would otherwise be
|
||||
# answered from the first one's cache entry.
|
||||
whole, _ = bm.ground_under(*BOX, 400, 400, fetch=_patchy(()), pause=0,
|
||||
zoom=zoom)
|
||||
zoom=zoom, remember=False)
|
||||
holed, _ = bm.ground_under(*BOX, 400, 400, fetch=_patchy({hole}),
|
||||
pause=0, retry_pause=0, zoom=zoom)
|
||||
pause=0, retry_pause=0, zoom=zoom,
|
||||
remember=False)
|
||||
assert whole is not None and holed is not None
|
||||
gap = _hole_mask(hole, zoom)
|
||||
assert gap.sum() > 1000, "the hole is not where this test thinks it is"
|
||||
|
|
@ -358,9 +363,10 @@ def test_a_missing_tile_does_not_dim_the_rest_of_the_map():
|
|||
not there."""
|
||||
zoom, hole = _hole_at()
|
||||
whole, _ = bm.ground_under(*BOX, 400, 400, fetch=_patchy(()), pause=0,
|
||||
zoom=zoom)
|
||||
zoom=zoom, remember=False)
|
||||
holed, _ = bm.ground_under(*BOX, 400, 400, fetch=_patchy({hole}),
|
||||
pause=0, retry_pause=0, zoom=zoom)
|
||||
pause=0, retry_pause=0, zoom=zoom,
|
||||
remember=False)
|
||||
# Outside the gap and the averaged band along its edge, the map is the
|
||||
# map: the hole took nothing else with it.
|
||||
elsewhere = ~_hole_mask(hole, zoom, grow=2)
|
||||
|
|
@ -374,10 +380,10 @@ def test_a_map_with_squares_missing_says_it_is_not_the_whole_answer():
|
|||
again."""
|
||||
_zoom, hole = _hole_at()
|
||||
whole, settled = bm.ground_under(*BOX, 400, 400, fetch=_patchy(()),
|
||||
pause=0)
|
||||
pause=0, remember=False)
|
||||
assert whole is not None and settled
|
||||
holed, settled = bm.ground_under(*BOX, 400, 400, fetch=_patchy({hole}),
|
||||
pause=0, retry_pause=0)
|
||||
pause=0, retry_pause=0, remember=False)
|
||||
assert holed is not None and not settled
|
||||
|
||||
|
||||
|
|
@ -394,9 +400,10 @@ def test_a_tile_that_fails_once_is_asked_for_again():
|
|||
return None
|
||||
return solid(40 if (x + y) % 3 == 0 else 230)
|
||||
|
||||
whole, _ = bm.ground_under(*BOX, 400, 400, fetch=_patchy(()), pause=0)
|
||||
whole, _ = bm.ground_under(*BOX, 400, 400, fetch=_patchy(()), pause=0,
|
||||
remember=False)
|
||||
healed, settled = bm.ground_under(*BOX, 400, 400, fetch=flaky, pause=0,
|
||||
retry_pause=0)
|
||||
retry_pause=0, remember=False)
|
||||
assert refused["left"] == 0, "the tile was never asked for a second time"
|
||||
assert settled, "a recovered map is the whole answer"
|
||||
assert bool((healed == whole).all())
|
||||
|
|
@ -878,3 +885,157 @@ def test_a_map_asked_for_at_more_detail_than_the_tiles_hold_still_works():
|
|||
fetch=gradient_tile, zoom=9, pause=0)
|
||||
assert levels.shape == (2000, 2000)
|
||||
assert levels[0].mean() != levels[-1].mean()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Keeping the finished map
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_a_map_already_built_is_not_built_again(monkeypatch):
|
||||
"""The tiles were always cached; the work done on them was not. Opening
|
||||
the same window twice used to decode forty PNGs and resample a
|
||||
megapixel and a half into this program's own projection, both times,
|
||||
for an answer that cannot have changed."""
|
||||
box = (47.0, -123.0, 48.0, -122.0)
|
||||
asked = []
|
||||
|
||||
def counting(z, x, y, **kw):
|
||||
asked.append((z, x, y))
|
||||
return gradient_tile(z, x, y, **kw)
|
||||
|
||||
first, settled = bm.ground_under(*box, 300, 300, shades=32,
|
||||
fetch=counting, pause=0)
|
||||
assert settled and first is not None
|
||||
built = len(asked)
|
||||
assert built > 1
|
||||
|
||||
asked.clear()
|
||||
again, settled = bm.ground_under(*box, 300, 300, shades=32,
|
||||
fetch=counting, pause=0)
|
||||
assert settled
|
||||
assert asked == [], "it went back to the tiles for a map it already had"
|
||||
assert bool((again == first).all()), "the kept map is a different map"
|
||||
|
||||
|
||||
def test_a_map_with_squares_missing_is_not_kept():
|
||||
"""Caching a hole would keep it for a month, and the whole point of
|
||||
calling a partial map provisional is that it gets asked for again."""
|
||||
zoom, hole = _hole_at()
|
||||
holed, settled = bm.ground_under(*BOX, 400, 400, fetch=_patchy({hole}),
|
||||
pause=0, retry_pause=0, zoom=zoom)
|
||||
assert holed is not None and not settled
|
||||
assert list(bm.ground_cache_dir().glob("*.npz")) == []
|
||||
|
||||
|
||||
def test_a_different_picture_is_a_different_map():
|
||||
"""Same piece of world, bigger window: reusing the smaller one would be
|
||||
exactly the upscale this program went to some trouble to avoid."""
|
||||
box = (47.0, -123.0, 48.0, -122.0)
|
||||
small, _ = bm.ground_under(*box, 200, 200, shades=32,
|
||||
fetch=gradient_tile, pause=0)
|
||||
large, _ = bm.ground_under(*box, 400, 400, shades=32,
|
||||
fetch=gradient_tile, pause=0)
|
||||
assert small.shape == (200, 200) and large.shape == (400, 400)
|
||||
elsewhere, _ = bm.ground_under(48.0, -123.0, 49.0, -122.0, 200, 200,
|
||||
shades=32, fetch=gradient_tile, pause=0)
|
||||
assert len(list(bm.ground_cache_dir().glob("*.npz"))) == 3
|
||||
|
||||
|
||||
def test_a_view_that_drifted_a_few_metres_is_the_same_view():
|
||||
"""Rounded to about a hundred metres, which is finer than a tile and
|
||||
far finer than anything visible: a map rebuilt because the middle
|
||||
moved by a pixel would defeat the point of keeping it."""
|
||||
a, _ = bm.ground_under(47.0, -123.0, 48.0, -122.0, 200, 200, shades=32,
|
||||
fetch=gradient_tile, pause=0)
|
||||
asked = []
|
||||
|
||||
def counting(z, x, y, **kw):
|
||||
asked.append((z, x, y))
|
||||
return gradient_tile(z, x, y, **kw)
|
||||
|
||||
b, _ = bm.ground_under(47.00002, -123.00002, 48.00002, -121.99998,
|
||||
200, 200, shades=32, fetch=counting, pause=0)
|
||||
assert asked == []
|
||||
assert bool((a == b).all())
|
||||
|
||||
|
||||
def test_keeping_the_map_can_be_turned_off():
|
||||
box = (47.0, -123.0, 48.0, -122.0)
|
||||
bm.ground_under(*box, 250, 250, shades=32, fetch=gradient_tile,
|
||||
pause=0, remember=False)
|
||||
assert list(bm.ground_cache_dir().glob("*.npz")) == []
|
||||
|
||||
|
||||
def test_a_truncated_cache_file_is_a_miss_rather_than_a_crash():
|
||||
"""Which is what a cache looks like after a power cut."""
|
||||
box = (47.0, -123.0, 48.0, -122.0)
|
||||
bm.ground_under(*box, 220, 220, shades=32, fetch=gradient_tile, pause=0)
|
||||
kept = list(bm.ground_cache_dir().glob("*.npz"))
|
||||
assert len(kept) == 1
|
||||
kept[0].write_bytes(b"PK\x03\x04 truncated")
|
||||
levels, settled = bm.ground_under(*box, 220, 220, shades=32,
|
||||
fetch=gradient_tile, pause=0)
|
||||
assert levels is not None and settled and levels.shape == (220, 220)
|
||||
|
||||
|
||||
def test_a_map_kept_too_long_ago_is_built_again(monkeypatch):
|
||||
box = (47.0, -123.0, 48.0, -122.0)
|
||||
bm.ground_under(*box, 210, 210, shades=32, fetch=gradient_tile, pause=0)
|
||||
later = time.time() + bm.GROUND_CACHE_DAYS * 86_400 + 1
|
||||
monkeypatch.setattr(bm.time, "time", lambda: later)
|
||||
asked = []
|
||||
|
||||
def counting(z, x, y, **kw):
|
||||
asked.append(1)
|
||||
return gradient_tile(z, x, y, **kw)
|
||||
|
||||
bm.ground_under(*box, 210, 210, shades=32, fetch=counting, pause=0)
|
||||
assert asked, "a month-old map was believed"
|
||||
|
||||
|
||||
def test_forgetting_the_maps_keeps_the_tiles():
|
||||
"""The maps are quick to rebuild from tiles and the tiles are not quick
|
||||
to fetch again, so the cheap thing goes first."""
|
||||
bm.ground_under(47.0, -123.0, 48.0, -122.0, 230, 230, shades=32,
|
||||
fetch=gradient_tile, pause=0)
|
||||
before = bm.cache_size()
|
||||
assert before["ground"]["files"] == 1
|
||||
assert bm.forget_ground() == 1
|
||||
after = bm.cache_size()
|
||||
assert after["ground"]["files"] == 0
|
||||
assert after["tiles"]["files"] == before["tiles"]["files"]
|
||||
|
||||
|
||||
def test_the_cache_says_how_big_it_is(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path))
|
||||
empty = bm.cache_size()
|
||||
assert empty["total"]["bytes"] == 0 and empty["total"]["files"] == 0
|
||||
root = tmp_path / "bandsaunter" / "tiles" / "9" / "81"
|
||||
root.mkdir(parents=True)
|
||||
(root / "178.png").write_bytes(b"x" * 1000)
|
||||
got = bm.cache_size()
|
||||
assert got["tiles"] == {"bytes": 1000, "files": 1}
|
||||
assert got["total"]["bytes"] == 1000
|
||||
|
||||
|
||||
def test_pruning_throws_away_the_least_recently_used(tmp_path, monkeypatch):
|
||||
"""Least recently *used*, not oldest: a tile fetched a year ago and
|
||||
looked at last night is the receiver's own neighbourhood, and throwing
|
||||
that away to keep last week's holiday is the wrong way round."""
|
||||
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path))
|
||||
where = tmp_path / "bandsaunter" / "tiles" / "9" / "81"
|
||||
where.mkdir(parents=True)
|
||||
now = time.time()
|
||||
for i, age in enumerate((100.0, 0.0, 50.0)): # middle one is freshest
|
||||
path = where / f"{i}.png"
|
||||
path.write_bytes(b"x" * 400_000)
|
||||
os.utime(path, (now - age * 86_400, now - age * 86_400))
|
||||
assert bm.cache_size()["tiles"]["files"] == 3
|
||||
gone = bm.prune_cache(limit_mb=0.5)
|
||||
assert gone == 2
|
||||
left = list(where.glob("*.png"))
|
||||
assert [p.name for p in left] == ["1.png"], "it kept the wrong one"
|
||||
|
||||
|
||||
def test_pruning_a_cache_that_already_fits_does_nothing():
|
||||
assert bm.prune_cache(limit_mb=10_000) == 0
|
||||
|
|
|
|||
|
|
@ -837,3 +837,235 @@ def test_nothing_claims_to_be_listening_before_there_is_a_receiver(tmp_path):
|
|||
shown = caught.get()
|
||||
assert "cannot open the receiver" in shown
|
||||
assert "listening on" not in shown
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Who each station is
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _register(tmp_path, entries=()):
|
||||
"""A licence register that knows what it is told and asks nobody."""
|
||||
from bandsaunter.callsign import CACHE_VERSION, Callsign, CallsignBook
|
||||
|
||||
book = CallsignBook(online=False, cache=tmp_path / "callsigns.json")
|
||||
for call, name, where in entries:
|
||||
book._entries[call] = Callsign(
|
||||
call=call, name=name, location=where, status="found",
|
||||
version=CACHE_VERSION, fetched_at=time.time())
|
||||
return book
|
||||
|
||||
|
||||
def _heard_from(band, text, calls, grid="", at=1_700_000_000.0):
|
||||
band.add(ft8wave.Decode(text=text, kind="standard", calls=calls,
|
||||
grid=grid, hertz=1200.0, offset=0.2,
|
||||
snr_db=-7.0, calling=text.startswith("CQ"),
|
||||
at=at))
|
||||
|
||||
|
||||
def test_both_callsigns_in_an_exchange_are_looked_up(tmp_path):
|
||||
"""The station being answered may never transmit within earshot, and is
|
||||
still a station this receiver knows about."""
|
||||
register = _register(tmp_path)
|
||||
band = ft8.Band()
|
||||
band.register = register
|
||||
_heard_from(band, "W1AW KU0W DM42", ("W1AW", "KU0W"), "DM42")
|
||||
assert set(register._entries) == {"W1AW", "KU0W"}
|
||||
|
||||
|
||||
def test_a_station_is_asked_about_once_however_often_it_transmits(tmp_path):
|
||||
register = _register(tmp_path)
|
||||
band = ft8.Band()
|
||||
band.register = register
|
||||
for i in range(6):
|
||||
_heard_from(band, "CQ W1AW FN31", ("W1AW",), "FN31",
|
||||
at=1_700_000_000.0 + i * 15)
|
||||
assert set(register._entries) == {"W1AW"}
|
||||
|
||||
|
||||
def test_a_callsign_nobody_has_spelled_out_is_not_asked_about(tmp_path):
|
||||
"""FT8 carries a compound callsign as a hash and expects the receiver to
|
||||
have heard it in full earlier. Until it has, there is nothing to ask."""
|
||||
register = _register(tmp_path)
|
||||
band = ft8.Band()
|
||||
band.register = register
|
||||
_heard_from(band, "<...> ON7EE JO10", ("<...>", "ON7EE"), "JO10")
|
||||
assert set(register._entries) == {"ON7EE"}
|
||||
|
||||
|
||||
def test_a_rover_is_looked_up_under_its_licence(tmp_path):
|
||||
"""ET3RFG/R is ET3RFG operating away from the licensed address, and no
|
||||
register has heard of the suffix."""
|
||||
register = _register(tmp_path)
|
||||
band = ft8.Band()
|
||||
band.register = register
|
||||
_heard_from(band, "ET3RFG/R IN3ADG -23", ("ET3RFG/R", "IN3ADG"))
|
||||
assert set(register._entries) == {"ET3RFG", "IN3ADG"}
|
||||
|
||||
|
||||
def test_the_name_is_shown_when_it_has_arrived(tmp_path):
|
||||
register = _register(tmp_path, [("W1AW", "ARRL HQ Operators Club",
|
||||
"Newington, CT")])
|
||||
band = ft8.Band()
|
||||
band.register = register
|
||||
_heard_from(band, "CQ W1AW FN31", ("W1AW",), "FN31")
|
||||
assert ft8.who_text(ft8.licensee(band, "W1AW")) == \
|
||||
"ARRL HQ Operators Club — Newington, CT"
|
||||
|
||||
|
||||
def test_the_dx_the_register_cannot_know_still_says_which_country():
|
||||
"""Which on this band is the point: the databases are United States
|
||||
registers and the interesting stations are all somewhere else."""
|
||||
from bandsaunter.callsign import Callsign
|
||||
|
||||
who = Callsign(call="VK4BLE", country="Australia", status="unlisted")
|
||||
assert ft8.who_text(who) == "Australia"
|
||||
|
||||
|
||||
def test_nothing_is_looked_up_without_a_register():
|
||||
band = ft8.Band()
|
||||
_heard_from(band, "CQ W1AW FN31", ("W1AW",), "FN31")
|
||||
assert ft8.licensee(band, "W1AW") is None
|
||||
assert ft8.open_register(ft8.Ft8Options(lookup=False)).online is False
|
||||
|
||||
|
||||
def test_the_report_gives_a_column_for_who_each_station_is(tmp_path):
|
||||
from rich.console import Console
|
||||
|
||||
band = ft8.Band()
|
||||
band.register = _register(tmp_path, [("W1AW", "ARRL HQ Operators Club",
|
||||
"Newington, CT")])
|
||||
band.slots = 2
|
||||
_heard_from(band, "CQ W1AW FN31", ("W1AW",), "FN31")
|
||||
console = Console(width=150, force_terminal=False)
|
||||
with console.capture() as caught:
|
||||
ft8.report(console, band, ft8.Ft8Options(lookup=True))
|
||||
shown = caught.get()
|
||||
assert "licensed to" in shown and "ARRL HQ Operators Club" in shown
|
||||
|
||||
|
||||
def test_the_report_leaves_the_column_out_when_lookups_are_off(tmp_path):
|
||||
from rich.console import Console
|
||||
|
||||
band = ft8.Band()
|
||||
band.slots = 2
|
||||
_heard_from(band, "CQ W1AW FN31", ("W1AW",), "FN31")
|
||||
console = Console(width=150, force_terminal=False)
|
||||
with console.capture() as caught:
|
||||
ft8.report(console, band, ft8.Ft8Options(lookup=False))
|
||||
assert "licensed to" not in caught.get()
|
||||
|
||||
|
||||
def test_what_was_learned_is_written_to_the_disk(tmp_path):
|
||||
"""Otherwise every evening asks the register about the same band again,
|
||||
which is the one thing caching it was for."""
|
||||
from bandsaunter.callsign import CallsignBook
|
||||
|
||||
where = tmp_path / "callsigns.json"
|
||||
band = ft8.Band()
|
||||
band.register = _register(tmp_path, [("W1AW", "ARRL HQ", "Newington, CT")])
|
||||
band.register._dirty = True
|
||||
ft8.keep_lookups(band)
|
||||
assert where.exists()
|
||||
assert CallsignBook(online=False, cache=where).get("W1AW").name == "ARRL HQ"
|
||||
|
||||
|
||||
def test_listening_ends_by_writing_what_it_learned(tmp_path, monkeypatch):
|
||||
"""Through the real path rather than by calling the helper directly."""
|
||||
from rich.console import Console
|
||||
from bandsaunter.callsign import CACHE_VERSION, Callsign, CallsignBook
|
||||
|
||||
where = tmp_path / "callsigns.json"
|
||||
monkeypatch.setattr(ft8, "open_register",
|
||||
lambda options: CallsignBook(online=False,
|
||||
cache=where))
|
||||
monkeypatch.setattr(ft8, "open_device", lambda console, options: None)
|
||||
console = Console(width=100, force_terminal=False)
|
||||
options = ft8.defaults()
|
||||
options.log = False
|
||||
heard = ft8.Heard()
|
||||
heard.band.register = CallsignBook(online=False, cache=where)
|
||||
heard.band.register._entries["KU0W"] = Callsign(
|
||||
call="KU0W", name="Rod R Gowdy", status="found",
|
||||
version=CACHE_VERSION, fetched_at=time.time())
|
||||
heard.band.register._dirty = True
|
||||
with console.capture():
|
||||
ft8.finish(console, options, str(tmp_path), heard)
|
||||
assert CallsignBook(online=False, cache=where).get("KU0W").name == \
|
||||
"Rod R Gowdy"
|
||||
|
||||
|
||||
def test_every_mode_that_hears_callsigns_looks_them_up_and_caches_them():
|
||||
"""The whole of the answer to "all possible features", as a test rather
|
||||
than as a promise.
|
||||
|
||||
Written as a register of what is known to resolve callsigns, so that a
|
||||
module which starts doing it later fails here until somebody has
|
||||
decided whether it should. Checking only that the current ones work
|
||||
would say nothing about the next one.
|
||||
|
||||
Aircraft are deliberately absent: a registration is not an amateur
|
||||
callsign and no amateur register has heard of one. They have their own
|
||||
cached book, which test_flights covers.
|
||||
"""
|
||||
import ast
|
||||
import importlib
|
||||
|
||||
from bandsaunter import aprs, browse, scanner
|
||||
from bandsaunter.callsign import CallsignBook, _cache_path
|
||||
|
||||
known = {
|
||||
"scanner": "speech transcripts and Morse idents",
|
||||
"browse": "the recording browser",
|
||||
"aprs": "APRS stations",
|
||||
"ft8": "FT8 exchanges",
|
||||
}
|
||||
found = {}
|
||||
for path in sorted(Path(aprs.__file__).parent.glob("*.py")):
|
||||
if path.stem in ("callsign", "__init__"):
|
||||
continue
|
||||
tree = ast.parse(path.read_text())
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.ImportFrom) and node.module == "callsign":
|
||||
if any(a.name in ("CallsignBook", "find_callsigns",
|
||||
"licensed_call") for a in node.names):
|
||||
found[path.stem] = True
|
||||
assert set(found) == set(known), (
|
||||
f"modules resolving callsigns changed: {sorted(found)} "
|
||||
f"vs {sorted(known)} -- add it here and give it a lookup, or "
|
||||
f"explain why it should not have one")
|
||||
|
||||
# And every one of them resolves through the same file, so a callsign
|
||||
# heard on two bands is asked about once rather than twice.
|
||||
for book in (aprs.open_book(aprs.defaults()),
|
||||
ft8.open_register(ft8.defaults()),
|
||||
CallsignBook(online=False)):
|
||||
assert book.cache_path == _cache_path()
|
||||
assert browse is not None and scanner is not None
|
||||
|
||||
|
||||
def test_a_callsign_heard_on_two_bands_is_asked_about_once(tmp_path):
|
||||
"""The point of one shared file: APRS and FT8 hear the same operators,
|
||||
and a register asked twice for the same answer is a register being
|
||||
asked one time too many."""
|
||||
from bandsaunter import aprs
|
||||
from bandsaunter.callsign import CACHE_VERSION, Callsign, CallsignBook
|
||||
|
||||
where = tmp_path / "callsigns.json"
|
||||
asked = []
|
||||
|
||||
class Counting(CallsignBook):
|
||||
def _request(self, url, call):
|
||||
asked.append(call)
|
||||
raise AssertionError("no network in tests")
|
||||
|
||||
first = Counting(online=False, cache=where)
|
||||
first._entries["W1AW"] = Callsign(call="W1AW", name="ARRL HQ",
|
||||
status="found", version=CACHE_VERSION,
|
||||
fetched_at=time.time())
|
||||
first._dirty = True
|
||||
first.save()
|
||||
|
||||
# A different mode, a later evening, the same file.
|
||||
second = Counting(online=True, cache=where)
|
||||
assert second.get("W1AW").name == "ARRL HQ"
|
||||
assert asked == [], "it went back to the register for an answer it had"
|
||||
|
|
|
|||
|
|
@ -243,3 +243,79 @@ def test_the_flags_it_tells_you_to_use_are_real():
|
|||
for line in ("scan -b 2m --simulate", "adsb --simulate --seconds 30",
|
||||
"devices --test", "transcribe --engines"):
|
||||
parser.parse_args(line.split()) # raises SystemExit if not
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Where it lives
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
REPOSITORY = "https://frostwarning.com/git/dustcouncil/bandsaunter"
|
||||
|
||||
|
||||
def test_the_install_instructions_say_where_to_clone_from():
|
||||
"""This said "git clone <the repository>" for a long time.
|
||||
|
||||
Nothing noticed, because nothing reads the install instructions except
|
||||
somebody installing -- who then cannot. A placeholder in the one
|
||||
command a new person types first is the worst place for one, so it is
|
||||
checked here rather than hoped about.
|
||||
"""
|
||||
body = INSTALL.read_text()
|
||||
clones = re.findall(r"^git clone\s+(\S+)", body, re.MULTILINE)
|
||||
assert clones, "the install instructions do not say how to get the source"
|
||||
for where in clones:
|
||||
assert where.startswith(("http://", "https://", "git@", "ssh://")), \
|
||||
f"not a repository anybody can clone: {where!r}"
|
||||
assert "<" not in where and ">" not in where, \
|
||||
f"still a placeholder: {where!r}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["INSTALL.md", "README.md",
|
||||
"pyproject.toml"])
|
||||
def test_the_files_a_new_person_reads_have_no_placeholders_left(path):
|
||||
"""Angle brackets around a word are how a placeholder is written, and
|
||||
every one of them is a sentence somebody cannot act on."""
|
||||
body = (ROOT / path).read_text()
|
||||
# Inside a fenced block a placeholder is an instruction to substitute;
|
||||
# outside one it is prose. Both are checked, and both are wrong when the
|
||||
# thing to substitute is the repository.
|
||||
for bad in ("<the repository>", "<repository>", "<repo>", "<URL>",
|
||||
"<url>"):
|
||||
assert bad not in body, f"{path} still says {bad}"
|
||||
|
||||
|
||||
def test_the_packaging_metadata_names_the_repository():
|
||||
import tomllib
|
||||
|
||||
body = tomllib.load(open(ROOT / "pyproject.toml", "rb"))
|
||||
urls = body["project"].get("urls") or {}
|
||||
assert urls, "pyproject names no homepage at all"
|
||||
assert any(REPOSITORY in v for v in urls.values())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("page", ["bandsaunter.1", "saunterbrowse.1"])
|
||||
def test_both_manuals_say_where_the_source_is(page):
|
||||
body = (ROOT / "packaging" / page).read_text()
|
||||
assert REPOSITORY in body, f"{page} does not say where to find the source"
|
||||
|
||||
|
||||
def test_the_built_package_says_where_it_came_from():
|
||||
"""Debian policy asks for a Homepage field, and an installed package
|
||||
that cannot say where it came from is one nobody can update."""
|
||||
for script in ("build-deb.sh", "build-repo.sh"):
|
||||
body = (ROOT / "packaging" / script).read_text()
|
||||
assert f"Homepage: {REPOSITORY}" in body, script
|
||||
assert "Maintainer: bandsaunter" not in body, \
|
||||
f"{script} still names the package as its own maintainer"
|
||||
|
||||
|
||||
def test_the_tile_server_is_told_where_to_look_this_program_up():
|
||||
"""Not decoration: the usage policy of the service the default tiles
|
||||
come from asks for a User-Agent that identifies the application and
|
||||
gives somewhere to look it up, so that an operator with a question
|
||||
about the traffic has somebody to ask."""
|
||||
from bandsaunter.basemap import USER_AGENT
|
||||
|
||||
assert "bandsaunter/" in USER_AGENT
|
||||
assert REPOSITORY in USER_AGENT
|
||||
assert bandsaunter.__version__ in USER_AGENT
|
||||
|
|
|
|||
|
|
@ -2419,3 +2419,249 @@ def test_the_empty_picture_draws_the_words_it_was_given(app):
|
|||
waiting="listening on 144.39 MHz\n\nnothing placed yet — a station "
|
||||
"appears\nonce it has said where it is"))
|
||||
assert int((plane != station).any(axis=2).sum()) > 200
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Keeping up with the window
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class _Quiet(_NoPainter):
|
||||
"""A painter that lets the ground be drawn, once there is any.
|
||||
|
||||
_NoPainter refuses, on purpose, so that a test of "it asked and drew
|
||||
nothing" cannot pass by drawing something. These tests are about what
|
||||
happens once there *is* a map.
|
||||
"""
|
||||
|
||||
def drawImage(self, *a):
|
||||
pass
|
||||
|
||||
|
||||
def _grown(sky, view, painter, width, height):
|
||||
"""Resize, paint the ground, and say what was asked for."""
|
||||
view.resize(width, height)
|
||||
view._draw_ground(painter, view.projection())
|
||||
return sky.wanted_ground()
|
||||
|
||||
|
||||
@qt
|
||||
def test_a_window_made_bigger_fetches_a_sharper_map(app):
|
||||
"""A map fetched for a smaller window is still a map of the right piece
|
||||
of world, so nothing else notices it is being stretched. Opening at the
|
||||
default size and then going to the whole screen used to keep the first
|
||||
map until an aircraft wandered far enough to move the view out of the
|
||||
fetched box -- which on a quiet band is a long time to look at a blurred
|
||||
coastline.
|
||||
"""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
painter = _Quiet()
|
||||
|
||||
asked = _grown(sky, view, painter, 900, 650)
|
||||
assert asked is not None
|
||||
key, box, size = asked
|
||||
first = size[0]
|
||||
sky.set_ground(np.zeros((size[1], size[0]), dtype=np.uint8), key, box)
|
||||
|
||||
# Twice as wide: the map in hand now covers each of its pixels with two.
|
||||
asked = _grown(sky, view, painter, 1800, 1300)
|
||||
assert asked is not None, "it kept stretching the map it had"
|
||||
assert asked[2][0] > first * 1.5, asked[2]
|
||||
|
||||
|
||||
@qt
|
||||
def test_a_window_nudged_a_few_pixels_does_not_refetch(app):
|
||||
"""Dragging an edge must not send somebody's evening to a tile server a
|
||||
hundred times."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
painter = _Quiet()
|
||||
key, box, size = _grown(sky, view, painter, 1200, 850)
|
||||
sky.set_ground(np.zeros((size[1], size[0]), dtype=np.uint8), key, box)
|
||||
|
||||
for extra in (1, 4, 20, 60):
|
||||
sky._wanted = None
|
||||
view.resize(1200 + extra, 850)
|
||||
view._draw_ground(painter, view.projection())
|
||||
assert sky.wanted_ground() is None, f"refetched over {extra} pixels"
|
||||
|
||||
|
||||
@qt
|
||||
def test_it_stops_asking_once_the_sharper_map_has_arrived(app):
|
||||
"""The check is "am I being stretched", and a window larger than the
|
||||
tile budget can cover is stretched by design -- so this had better be
|
||||
answered by the request rather than by the result, or a 4K window asks
|
||||
for a map for the rest of the evening."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
painter = _Quiet()
|
||||
key, box, size = _grown(sky, view, painter, 3840, 2160)
|
||||
# Answered with a map of the size asked for, which is what the fetching
|
||||
# does however far the zoom had to be capped to get it.
|
||||
sky.set_ground(np.zeros((size[1], size[0]), dtype=np.uint8), key, box)
|
||||
for _ in range(5):
|
||||
sky._wanted = None
|
||||
view._draw_ground(painter, view.projection())
|
||||
assert sky.wanted_ground() is None, "it is still asking"
|
||||
|
||||
|
||||
@qt
|
||||
def test_a_window_made_smaller_does_not_refetch(app):
|
||||
"""Shrinking leaves the map finer than it needs to be, which costs
|
||||
nothing and looks perfect."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
painter = _Quiet()
|
||||
key, box, size = _grown(sky, view, painter, 1800, 1300)
|
||||
sky.set_ground(np.zeros((size[1], size[0]), dtype=np.uint8), key, box)
|
||||
sky._wanted = None
|
||||
view.resize(900, 650)
|
||||
view._draw_ground(painter, view.projection())
|
||||
assert sky.wanted_ground() is None
|
||||
|
||||
|
||||
@qt
|
||||
def test_the_stretch_is_measured_in_map_pixels_per_degree(app):
|
||||
"""Not in window pixels: the fetched box is wider than the view, so the
|
||||
two numbers are not the same and comparing the wrong pair would either
|
||||
never refetch or always."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
view.resize(1000, 700)
|
||||
projection = view.projection()
|
||||
box = view.ground_box(projection)
|
||||
across = box[3] - box[1]
|
||||
shown = projection.east - projection.west
|
||||
assert across > shown, "the fetched box is not wider than the view"
|
||||
|
||||
# A map at exactly the density the view wants is not stretched; one at
|
||||
# half that is.
|
||||
want = projection.width / shown
|
||||
exact = np.zeros((10, int(round(want * across))), dtype=np.uint8)
|
||||
assert not SkyView._stretched(exact, box, projection)
|
||||
half = np.zeros((10, max(1, exact.shape[1] // 2)), dtype=np.uint8)
|
||||
assert SkyView._stretched(half, box, projection)
|
||||
|
||||
# The case that tells the two ways of measuring apart, and the realistic
|
||||
# one: a map with exactly as many pixels as the window is wide, spread
|
||||
# over a box a quarter wider than the view. Only four fifths of those
|
||||
# pixels land on the screen, so it *is* being stretched -- and counting
|
||||
# raw pixels against raw pixels would call it fine.
|
||||
same = np.zeros((10, projection.width), dtype=np.uint8)
|
||||
assert SkyView._stretched(same, box, projection), (
|
||||
"the stretch is being measured in window pixels rather than in map "
|
||||
"pixels per degree")
|
||||
|
||||
|
||||
@qt
|
||||
def test_nothing_is_stretched_when_there_is_nothing_to_stretch(app):
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
view.resize(900, 650)
|
||||
projection = view.projection()
|
||||
assert not SkyView._stretched(None, (0.0, 0.0, 1.0, 1.0), projection)
|
||||
assert not SkyView._stretched(np.zeros((4, 4), dtype=np.uint8), None,
|
||||
projection)
|
||||
# A box with no width at all cannot be divided by.
|
||||
assert not SkyView._stretched(np.zeros((4, 4), dtype=np.uint8),
|
||||
(1.0, 2.0, 1.0, 2.0), projection)
|
||||
|
||||
|
||||
@qt
|
||||
def test_the_window_opens_maximised(app):
|
||||
"""This is a map, and the thing somebody wants more of is map. It used
|
||||
to open at eleven hundred by eight hundred whatever the screen was."""
|
||||
from bandsaunter.livemap import _build
|
||||
|
||||
window = _build()["Window"](a_sky(a_blip()), "test")
|
||||
assert window.isMaximized()
|
||||
assert not window.isFullScreen()
|
||||
|
||||
|
||||
@qt
|
||||
def test_un_maximising_gives_back_a_usable_window(app):
|
||||
"""Set before maximising, so that there is a size to come back to: a
|
||||
window maximised from nothing restores to whatever the toolkit guessed."""
|
||||
from bandsaunter.livemap import _build
|
||||
|
||||
window = _build()["Window"](a_sky(a_blip()), "test")
|
||||
restored = window.normalGeometry()
|
||||
assert restored.width() >= 800 and restored.height() >= 600
|
||||
|
||||
|
||||
@qt
|
||||
def test_f_goes_to_true_full_screen_and_back_to_maximised(app):
|
||||
"""Back to maximised rather than to the size it was built at: leaving
|
||||
full screen should not shrink the map to a quarter of the screen."""
|
||||
from bandsaunter.livemap import _build, _qt
|
||||
|
||||
_name, core, gui, _widgets, _signal = _qt()
|
||||
window = _build()["Window"](a_sky(a_blip()), "test")
|
||||
|
||||
def press(letter):
|
||||
window.keyPressEvent(gui.QKeyEvent(
|
||||
core.QEvent.Type.KeyPress, 0,
|
||||
core.Qt.KeyboardModifier.NoModifier, letter))
|
||||
|
||||
press("f")
|
||||
assert window.isFullScreen() and not window.isMaximized()
|
||||
press("f")
|
||||
assert window.isMaximized() and not window.isFullScreen()
|
||||
|
||||
|
||||
@qt
|
||||
def test_the_keys_along_the_top_say_how_to_go_full_screen(app):
|
||||
"""A window with no frame is one somebody has to know a key to get out
|
||||
of, so the key is on the screen rather than only in the manual."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
view.resize(1400, 700)
|
||||
said = []
|
||||
|
||||
class _Spy:
|
||||
"""Swallows everything a painter is asked to do, and keeps the text."""
|
||||
|
||||
def __getattr__(self, name):
|
||||
return lambda *a, **k: None
|
||||
|
||||
def drawText(self, *a):
|
||||
said.append(a[-1])
|
||||
|
||||
view._draw_header(_Spy(), 1)
|
||||
assert any("f full" in line for line in said), said
|
||||
|
||||
|
||||
@qt
|
||||
def test_opening_maximised_fetches_a_map_for_the_size_it_opened_at(app):
|
||||
"""The two halves of this belong together: a window that opens big is no
|
||||
use if the map it fetches is for a window that opened small."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
painter = _Quiet()
|
||||
|
||||
# The small size a window used to open at, answered.
|
||||
key, box, size = _grown(sky, view, painter, 1100, 800)
|
||||
small = size[0]
|
||||
sky.set_ground(np.zeros((size[1], size[0]), dtype=np.uint8), key, box)
|
||||
|
||||
# Now the size a maximised window on an ordinary screen has.
|
||||
sky._wanted = None
|
||||
asked = _grown(sky, view, painter, 1920, 1080)
|
||||
assert asked is not None, "it opened big and kept the small map"
|
||||
assert asked[2][0] > small
|
||||
|
|
|
|||
412
tests/test_register.py
Normal file
412
tests/test_register.py
Normal file
|
|
@ -0,0 +1,412 @@
|
|||
"""The register: everything ever looked up, read back and made browsable.
|
||||
|
||||
Nothing here touches a network or a receiver. Both caches are written by
|
||||
the tests and read by the code, which is the whole reason the reading lives
|
||||
in a module of its own.
|
||||
"""
|
||||
import json
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from rich.console import Console
|
||||
|
||||
from bandsaunter import register as reg
|
||||
from bandsaunter.browse import Browser
|
||||
|
||||
|
||||
def write_callsigns(path: Path, entries) -> Path:
|
||||
body = {}
|
||||
for one in entries:
|
||||
row = {"call": one["call"], "status": one.get("status", "found"),
|
||||
"fetched_at": one.get("fetched_at", 1_700_000_000.0),
|
||||
"version": 4}
|
||||
row.update({k: v for k, v in one.items() if k != "call"})
|
||||
body[one["call"]] = row
|
||||
path.write_text(json.dumps(body))
|
||||
return path
|
||||
|
||||
|
||||
def write_aircraft(path: Path, planes, routes=None) -> Path:
|
||||
path.write_text(json.dumps({"aircraft": {p["icao"]: p for p in planes},
|
||||
"routes": routes or {},
|
||||
"airports": {}}))
|
||||
return path
|
||||
|
||||
|
||||
SOME = [
|
||||
{"call": "AB7IC", "name": "Thomas G Britton", "location": "Tucson, AZ",
|
||||
"street": "8410 E Brookwood Dr", "postcode": "85750-2468",
|
||||
"country": "United States", "district": "district 7",
|
||||
"grid": "DM42og", "oper_class": "EXTRA", "licence_type": "PERSON",
|
||||
"expires": "12/21/2033", "latitude": 32.2750431,
|
||||
"longitude": -110.8131236, "source": "callook.info"},
|
||||
{"call": "VK4BLE", "country": "Australia", "status": "unlisted"},
|
||||
{"call": "WQVF960", "country": "United States", "status": "service"},
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reading the caches
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_a_callsign_comes_back_with_everything_that_was_known(tmp_path):
|
||||
where = write_callsigns(tmp_path / "c.json", SOME)
|
||||
entries = reg.load_callsigns(where)
|
||||
got = {e.title: e for e in entries}
|
||||
one = got["AB7IC"]
|
||||
assert one.what == "Thomas G Britton"
|
||||
assert one.where == "Tucson, AZ"
|
||||
assert one.position == pytest.approx((32.2750431, -110.8131236))
|
||||
shown = dict(one.rows)
|
||||
for label in ("licensed to", "class", "licence", "street", "town",
|
||||
"postcode", "country", "district", "grid", "expires",
|
||||
"position", "status", "answered by", "looked up"):
|
||||
assert label in shown, label
|
||||
assert shown["street"] == "8410 E Brookwood Dr"
|
||||
assert shown["answered by"] == "callook.info"
|
||||
|
||||
|
||||
def test_a_callsign_nobody_could_place_is_kept_rather_than_dropped(tmp_path):
|
||||
""""Asked about and in no register" is a fact about a station. A list
|
||||
that quietly dropped them would make an evening of unlisted foreign
|
||||
stations look like an evening when nothing was looked up."""
|
||||
entries = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))
|
||||
assert {e.title for e in entries} == {"AB7IC", "VK4BLE", "WQVF960"}
|
||||
vk = next(e for e in entries if e.title == "VK4BLE")
|
||||
assert vk.position is None and not vk.mappable
|
||||
assert dict(vk.rows)["status"] == \
|
||||
"asked about, in no register reachable from here"
|
||||
|
||||
|
||||
def test_a_status_says_what_it_means_rather_than_what_it_is_called(tmp_path):
|
||||
entries = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))
|
||||
service = next(e for e in entries if e.title == "WQVF960")
|
||||
assert "not an amateur callsign" in dict(service.rows)["status"]
|
||||
|
||||
|
||||
def test_a_position_taken_from_the_grid_says_so(tmp_path):
|
||||
"""A grid square is a few kilometres across and a licensed address is a
|
||||
street, so which one a coordinate came from matters."""
|
||||
where = write_callsigns(tmp_path / "c.json", [
|
||||
{"call": "G4ABC", "grid": "IO91", "latitude": 51.5,
|
||||
"longitude": -1.0, "from_grid": True}])
|
||||
one = reg.load_callsigns(where)[0]
|
||||
assert "from the grid square" in dict(one.rows)["position"]
|
||||
|
||||
|
||||
def test_an_aircraft_comes_back_with_its_route(tmp_path):
|
||||
"""The route is filed against the flight number and the airframe against
|
||||
the address, so the two halves have to be joined."""
|
||||
where = write_aircraft(
|
||||
tmp_path / "f.json",
|
||||
[{"icao": "4CA2D3", "registration": "EI-DYM", "callsign": "RYR1234",
|
||||
"manufacturer": "Boeing", "model": "737-8AS", "type_code": "B738",
|
||||
"operator": "Ryanair", "country": "Ireland", "status": "found",
|
||||
"fetched_at": 1_700_000_000.0}],
|
||||
{"RYR1234": {"origin": "Dublin", "origin_code": "EIDW",
|
||||
"origin_lat": 53.4213, "origin_lon": -6.2701,
|
||||
"destination": "Stansted", "destination_code": "EGSS",
|
||||
"route_source": "a schedule service"}})
|
||||
one = reg.load_aircraft(where)[0]
|
||||
assert one.title == "EI-DYM"
|
||||
assert one.what == "Boeing 737-8AS"
|
||||
assert one.where == "EIDW → EGSS"
|
||||
shown = dict(one.rows)
|
||||
assert shown["from"] == "Dublin (EIDW)"
|
||||
assert shown["to"] == "Stansted (EGSS)"
|
||||
assert shown["route from"] == "a schedule service"
|
||||
assert shown["ICAO address"] == "4CA2D3"
|
||||
assert one.position == pytest.approx((53.4213, -6.2701))
|
||||
|
||||
|
||||
def test_an_aircraft_with_no_registration_is_shown_by_its_address(tmp_path):
|
||||
where = write_aircraft(tmp_path / "f.json",
|
||||
[{"icao": "ABCDEF", "status": "unlisted"}])
|
||||
assert reg.load_aircraft(where)[0].title == "ABCDEF"
|
||||
|
||||
|
||||
def test_a_cache_that_is_not_there_is_no_entries_rather_than_an_error(tmp_path):
|
||||
assert reg.load_callsigns(tmp_path / "nope.json") == []
|
||||
assert reg.load_aircraft(tmp_path / "nope.json") == []
|
||||
|
||||
|
||||
def test_a_cache_full_of_rubbish_is_no_entries_rather_than_an_error(tmp_path):
|
||||
bad = tmp_path / "c.json"
|
||||
bad.write_text("{ not json at all")
|
||||
assert reg.load_callsigns(bad) == []
|
||||
bad.write_text("[1, 2, 3]")
|
||||
assert reg.load_callsigns(bad) == []
|
||||
|
||||
|
||||
def test_the_two_caches_are_the_ones_everything_else_writes():
|
||||
from bandsaunter.callsign import _cache_path as calls
|
||||
from bandsaunter.flights import _cache_path as planes
|
||||
|
||||
where = reg.cache_paths()
|
||||
assert where["callsigns"] == calls()
|
||||
assert where["aircraft"] == planes()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Maps
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_a_map_link_points_at_the_coordinates_and_says_nothing_else(tmp_path):
|
||||
"""The one part of this that leaves the machine, so it carries as little
|
||||
as it can: a map does not need to be told whose licence it is looking
|
||||
at in order to show a place."""
|
||||
one = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))[0]
|
||||
url = one.maps()
|
||||
assert url.startswith("https://www.google.com/maps/")
|
||||
assert "32.275043" in url and "-110.813124" in url
|
||||
assert "AB7IC" not in url
|
||||
assert "Britton" not in url and "Brookwood" not in url
|
||||
|
||||
|
||||
def test_nothing_to_point_at_is_no_link_rather_than_a_wrong_one(tmp_path):
|
||||
entries = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))
|
||||
vk = next(e for e in entries if e.title == "VK4BLE")
|
||||
assert vk.maps() == "" and reg.maps_url(None) == ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Searching
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_searching_looks_at_every_field_and_not_only_the_name(tmp_path):
|
||||
"""The interesting question is usually not "which callsign" but "who was
|
||||
in Arizona", and that lives in the detail."""
|
||||
entries = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))
|
||||
assert [e.title for e in reg.search(entries, "tucson")] == ["AB7IC"]
|
||||
assert [e.title for e in reg.search(entries, "brookwood")] == ["AB7IC"]
|
||||
assert [e.title for e in reg.search(entries, "australia")] == ["VK4BLE"]
|
||||
assert [e.title for e in reg.search(entries, "EXTRA")] == ["AB7IC"]
|
||||
|
||||
|
||||
def test_every_word_has_to_match_so_a_search_can_be_narrowed(tmp_path):
|
||||
entries = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))
|
||||
assert [e.title for e in reg.search(entries, "united states")] != []
|
||||
assert reg.search(entries, "tucson australia") == []
|
||||
|
||||
|
||||
def test_an_empty_search_is_everything(tmp_path):
|
||||
entries = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))
|
||||
assert len(reg.search(entries, "")) == len(entries)
|
||||
assert len(reg.search(entries, " ")) == len(entries)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Browsing it
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def browser(tmp_path, monkeypatch):
|
||||
"""A browser whose register reads caches the test wrote."""
|
||||
calls = write_callsigns(tmp_path / "callsigns.json", SOME)
|
||||
planes = write_aircraft(tmp_path / "flights.json", [
|
||||
{"icao": "4CA2D3", "registration": "EI-DYM", "manufacturer": "Boeing",
|
||||
"model": "737-8AS", "status": "found", "fetched_at": 1.7e9}])
|
||||
monkeypatch.setattr(reg, "cache_paths",
|
||||
lambda: {"callsigns": calls, "aircraft": planes})
|
||||
console = Console(width=116, height=30, force_terminal=False)
|
||||
return Browser(tmp_path, console=console)
|
||||
|
||||
|
||||
def _screen(browser) -> str:
|
||||
with browser.console.capture() as caught:
|
||||
browser.console.print(browser.render())
|
||||
return caught.get()
|
||||
|
||||
|
||||
def test_c_opens_the_register_and_closes_it_again(browser):
|
||||
assert not browser.showing_register
|
||||
browser.handle("c")
|
||||
assert browser.showing_register
|
||||
assert "62" not in browser.message # it read the test's caches
|
||||
assert "3 callsigns" in browser.message
|
||||
browser.handle("c")
|
||||
assert not browser.showing_register
|
||||
browser.handle("c")
|
||||
browser.handle("escape")
|
||||
assert not browser.showing_register
|
||||
|
||||
|
||||
def test_the_register_shows_what_is_in_it(browser):
|
||||
browser.handle("c")
|
||||
shown = _screen(browser)
|
||||
assert "the register" in shown
|
||||
assert "AB7IC" in shown and "Thomas G Britton" in shown
|
||||
assert "Tucson, AZ" in shown
|
||||
# A date, because when something was looked up is part of the record.
|
||||
assert "2023-" in shown or "2026-" in shown or "2020-" in shown
|
||||
|
||||
|
||||
def test_the_detail_shows_every_field_for_the_current_one(browser):
|
||||
browser.handle("c")
|
||||
browser.reg_index = 0
|
||||
shown = _screen(browser)
|
||||
for bit in ("8410 E Brookwood Dr", "85750-2468", "DM42og", "EXTRA",
|
||||
"12/21/2033", "callook.info"):
|
||||
assert bit in shown, bit
|
||||
|
||||
|
||||
def test_tab_switches_between_callsigns_and_aircraft(browser):
|
||||
browser.handle("c")
|
||||
assert browser.reg_kind == "callsigns"
|
||||
browser.handle("tab")
|
||||
assert browser.reg_kind == "aircraft"
|
||||
shown = _screen(browser)
|
||||
assert "EI-DYM" in shown and "Boeing 737-8AS" in shown
|
||||
browser.handle("tab")
|
||||
assert browser.reg_kind == "callsigns"
|
||||
|
||||
|
||||
def test_moving_about_stays_inside_the_list(browser):
|
||||
browser.handle("c")
|
||||
for _ in range(20):
|
||||
browser.handle("down")
|
||||
_screen(browser) # the panel clamps as it draws
|
||||
assert browser.reg_index == 2 # three entries
|
||||
for _ in range(20):
|
||||
browser.handle("up")
|
||||
assert browser.reg_index == 0
|
||||
browser.handle("end")
|
||||
_screen(browser)
|
||||
assert browser.reg_index == 2
|
||||
browser.handle("home")
|
||||
assert browser.reg_index == 0
|
||||
|
||||
|
||||
def test_searching_in_the_register_narrows_the_list(browser):
|
||||
browser.handle("c")
|
||||
browser.handle("/")
|
||||
for ch in "tucson":
|
||||
browser.handle(ch)
|
||||
assert browser.reg_query == "tucson"
|
||||
browser.handle("enter")
|
||||
shown = _screen(browser)
|
||||
assert "AB7IC" in shown and "VK4BLE" not in shown
|
||||
assert "matching" in shown
|
||||
browser.handle("/")
|
||||
browser.handle("escape")
|
||||
assert browser.reg_query == ""
|
||||
|
||||
|
||||
def test_backspace_takes_a_letter_off_a_search(browser):
|
||||
browser.handle("c")
|
||||
browser.handle("/")
|
||||
for ch in "tucsonx":
|
||||
browser.handle(ch)
|
||||
browser.handle("backspace")
|
||||
assert browser.reg_query == "tucson"
|
||||
|
||||
|
||||
def test_g_opens_the_place_in_a_browser(browser, monkeypatch):
|
||||
import webbrowser
|
||||
|
||||
asked = []
|
||||
monkeypatch.setattr(webbrowser, "open",
|
||||
lambda url: asked.append(url) or True)
|
||||
browser.handle("c")
|
||||
browser.reg_index = 0
|
||||
browser.handle("g")
|
||||
assert len(asked) == 1
|
||||
assert "32.275043" in asked[0] and "maps" in asked[0]
|
||||
assert "opened AB7IC" in browser.message
|
||||
|
||||
|
||||
def test_g_on_something_with_no_position_says_so_rather_than_guessing(
|
||||
browser, monkeypatch):
|
||||
import webbrowser
|
||||
|
||||
asked = []
|
||||
monkeypatch.setattr(webbrowser, "open",
|
||||
lambda url: asked.append(url) or True)
|
||||
browser.handle("c")
|
||||
browser.handle("/")
|
||||
for ch in "australia":
|
||||
browser.handle(ch)
|
||||
browser.handle("enter")
|
||||
browser.handle("g")
|
||||
assert asked == []
|
||||
assert "where this one is" in browser.message
|
||||
|
||||
|
||||
def test_a_machine_with_no_browser_prints_the_place_instead(browser,
|
||||
monkeypatch):
|
||||
"""A headless box is the normal case for a receiver, and the coordinates
|
||||
are still the answer somebody wanted."""
|
||||
import webbrowser
|
||||
|
||||
monkeypatch.setattr(webbrowser, "open", lambda url: False)
|
||||
browser.handle("c")
|
||||
browser.reg_index = 0
|
||||
browser.handle("g")
|
||||
assert "no browser to open" in browser.message
|
||||
assert "32.275043" in browser.message
|
||||
|
||||
|
||||
def test_a_browser_that_will_not_start_is_reported_rather_than_raising(
|
||||
browser, monkeypatch):
|
||||
import webbrowser
|
||||
|
||||
def boom(url):
|
||||
raise RuntimeError("no display")
|
||||
|
||||
monkeypatch.setattr(webbrowser, "open", boom)
|
||||
browser.handle("c")
|
||||
browser.reg_index = 0
|
||||
assert browser.handle("g") is True
|
||||
assert "could not open a browser" in browser.message
|
||||
|
||||
|
||||
def test_q_still_quits_from_the_register(browser):
|
||||
browser.handle("c")
|
||||
assert browser.handle("q") is False
|
||||
|
||||
|
||||
def test_the_register_is_read_once_rather_than_on_every_frame(browser,
|
||||
monkeypatch):
|
||||
reads = []
|
||||
real = reg.load_all
|
||||
monkeypatch.setattr(reg, "load_all",
|
||||
lambda *a, **k: reads.append(1) or real(*a, **k))
|
||||
browser.handle("c")
|
||||
for _ in range(5):
|
||||
_screen(browser)
|
||||
browser.handle("down")
|
||||
assert len(reads) == 1
|
||||
# And r asks again, for somebody who has just finished a scan.
|
||||
browser.handle("r")
|
||||
assert len(reads) == 2
|
||||
assert "read the caches again" in browser.message
|
||||
|
||||
|
||||
def test_the_keys_page_says_the_register_is_there(browser):
|
||||
browser.handle("?")
|
||||
shown = _screen(browser)
|
||||
assert "every callsign and aircraft ever looked up" in shown
|
||||
# The register's own keys are named on the register's own screen, the
|
||||
# keys page being exactly as tall as an eighty-by-twenty-four terminal.
|
||||
browser.handle("?") # close the keys page
|
||||
browser.handle("c")
|
||||
browser.message = "" # the footer shows counts first
|
||||
assert "g map" in _screen(browser)
|
||||
assert "tab switch" in _screen(browser)
|
||||
|
||||
|
||||
def test_an_empty_register_says_so_rather_than_drawing_a_blank(tmp_path,
|
||||
monkeypatch):
|
||||
monkeypatch.setattr(reg, "cache_paths",
|
||||
lambda: {"callsigns": tmp_path / "none.json",
|
||||
"aircraft": tmp_path / "none.json"})
|
||||
console = Console(width=100, height=24, force_terminal=False)
|
||||
browser = Browser(tmp_path, console=console)
|
||||
browser.handle("c")
|
||||
shown = _screen(browser)
|
||||
assert "nothing here" in shown
|
||||
assert browser.reg_current is None
|
||||
# And g on nothing at all does not fall over.
|
||||
assert browser.handle("g") is True
|
||||
239
tests/test_splash.py
Normal file
239
tests/test_splash.py
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
"""The title screen.
|
||||
|
||||
Most of what matters here is when it does *not* appear. Everything in this
|
||||
program can be piped into something else, and a banner in the middle of a
|
||||
table somebody is parsing is corruption rather than decoration.
|
||||
"""
|
||||
from rich.console import Console
|
||||
|
||||
from bandsaunter import splash
|
||||
|
||||
|
||||
def _plain(console: Console, drawing) -> str:
|
||||
with console.capture() as caught:
|
||||
drawing()
|
||||
return caught.get()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The drawing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_both_names_come_out_as_four_rows_of_braille():
|
||||
for word in (splash.SCANNER_NAME, splash.BROWSER_NAME):
|
||||
rows = splash.banner(word)
|
||||
assert len(rows) == splash.ROWS
|
||||
assert all(all(0x2800 <= ord(c) <= 0x28FF for c in row)
|
||||
for row in rows), "something in there is not braille"
|
||||
assert any(c != "\u2800" for row in rows for c in row)
|
||||
|
||||
|
||||
def test_the_names_are_written_the_way_they_are_spelled():
|
||||
"""Not shouted. Braille gives four times the vertical detail a block
|
||||
does, which is what makes room for two heights of letter at once."""
|
||||
assert splash.SCANNER_NAME == "BandSaunter"
|
||||
assert splash.BROWSER_NAME == "SaunterBrowse"
|
||||
assert set("BS") <= set(splash.CAPS)
|
||||
assert "a" in splash.LOWER and "d" in splash.ASCENDERS
|
||||
|
||||
|
||||
def test_a_capital_stands_taller_than_the_letter_beside_it():
|
||||
"""The point of the whole exercise: if both were drawn the same height
|
||||
the name would read as BANDSAUNTER, which is not its name."""
|
||||
def top_of(word):
|
||||
drawn = splash.pixels(word)
|
||||
return next(i for i, row in enumerate(drawn) if row.strip())
|
||||
|
||||
assert top_of("B") < top_of("a"), "the capital does not rise"
|
||||
assert top_of("d") == top_of("B"), "the ascender does not reach"
|
||||
assert top_of("t") < top_of("a"), "the t does not rise at all"
|
||||
assert top_of("o") == top_of("a"), "two x-height letters disagree"
|
||||
|
||||
|
||||
def test_every_letter_sits_on_the_same_baseline():
|
||||
def bottom_of(word):
|
||||
drawn = splash.pixels(word)
|
||||
return max(i for i, row in enumerate(drawn) if row.strip())
|
||||
|
||||
heights = {ch: bottom_of(ch) for ch in "BSandutersow"}
|
||||
assert len(set(heights.values())) == 1, heights
|
||||
|
||||
|
||||
def test_both_names_fit_an_eighty_column_terminal():
|
||||
"""Which is the narrowest terminal anybody still has, and the width a
|
||||
banner has to be cut to rather than wrapped at."""
|
||||
for word in (splash.SCANNER_NAME, splash.BROWSER_NAME):
|
||||
assert max(len(r) for r in splash.banner(word)) <= 78, word
|
||||
|
||||
|
||||
def test_every_letter_the_two_names_need_has_a_glyph():
|
||||
"""A missing one would silently shorten the name rather than fail."""
|
||||
for word in (splash.SCANNER_NAME, splash.BROWSER_NAME):
|
||||
for letter in word:
|
||||
assert letter in splash.FONT, letter
|
||||
|
||||
|
||||
def test_a_stroke_is_two_dots_thick_in_both_directions():
|
||||
"""One dot thick reads as a dotted line rather than a line, which is
|
||||
the one thing that makes drawing in braille difficult. Doubling the
|
||||
small font is what avoids it."""
|
||||
doubled = splash._double(("#.",))
|
||||
assert doubled == ["##..", "##.."]
|
||||
|
||||
|
||||
def test_a_letter_with_no_glyph_is_left_out_rather_than_drawn_as_a_hole():
|
||||
assert splash.banner("Band!!") == splash.banner("Band")
|
||||
assert splash.banner("!!!") == []
|
||||
assert splash.banner("") == []
|
||||
# And an uppercase name is no longer the same as a lowercase one, which
|
||||
# is the whole change: the font has two heights now.
|
||||
assert splash.banner("Band") != splash.banner("BAND")
|
||||
|
||||
|
||||
def test_the_gradient_is_cold_the_whole_way_along():
|
||||
"""Digital blues, cyans and white, and nothing warm anywhere.
|
||||
|
||||
Checked as an invariant rather than by naming the five stops: blue is
|
||||
never the weakest channel and red is never the strongest, which is what
|
||||
"blue through cyan to white" *means* and what any warm colour slipping
|
||||
back in would break. This is deliberately not the waterfall ramp the
|
||||
rest of the program draws in -- that one has to run to red because it
|
||||
stands in for a spectrum.
|
||||
"""
|
||||
for step in range(0, 101):
|
||||
style = splash._colour(step / 100)
|
||||
red, green, blue = (int(v) for v in style[4:-1].split(","))
|
||||
assert blue >= green >= red, (step, style)
|
||||
assert blue >= 120, f"too dark to read at {step}: {style}"
|
||||
|
||||
|
||||
def test_the_gradient_ends_pale_and_starts_deep():
|
||||
"""A gradient that did not travel would be a colour."""
|
||||
start = [int(v) for v in splash._colour(0.0)[4:-1].split(",")]
|
||||
end = [int(v) for v in splash._colour(1.0)[4:-1].split(",")]
|
||||
assert sum(end) > sum(start) * 2, "it barely brightens"
|
||||
assert start[2] >= 120 and end[1] >= 200
|
||||
|
||||
|
||||
def test_the_gradient_runs_from_one_end_of_the_ramp_to_the_other():
|
||||
first, last = splash._colour(0.0), splash._colour(1.0)
|
||||
assert first != last
|
||||
assert first.startswith("rgb(") and last.startswith("rgb(")
|
||||
# And it is clamped rather than extrapolated off either end.
|
||||
assert splash._colour(-5.0) == first
|
||||
assert splash._colour(5.0) == last
|
||||
|
||||
|
||||
def test_the_lines_under_it_are_drawn_in_the_order_they_were_given():
|
||||
console = Console(width=100, force_terminal=False)
|
||||
shown = _plain(console, lambda: splash.show(
|
||||
console, splash.SCANNER_NAME,
|
||||
("Conceived by: The Dust Council", "100% AI Coded by Claude Code."),
|
||||
force=True))
|
||||
assert "Conceived by: The Dust Council" in shown
|
||||
assert "100% AI Coded by Claude Code." in shown
|
||||
assert shown.index("Conceived") < shown.index("100%")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# When it stays out of the way
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_nothing_is_drawn_when_the_output_is_not_a_terminal():
|
||||
"""The one that matters. A table piped into something else must come
|
||||
out as a table."""
|
||||
console = Console(width=100, force_terminal=False)
|
||||
shown = _plain(console, lambda: splash.show(console, splash.SCANNER_NAME,
|
||||
("a", "b")))
|
||||
assert shown == ""
|
||||
assert splash.wanted(console) is False
|
||||
|
||||
|
||||
def test_no_splash_turns_it_off_on_a_terminal_too():
|
||||
console = Console(width=100, force_terminal=True)
|
||||
assert splash.wanted(console) is True
|
||||
assert splash.wanted(console, no_splash=True) is False
|
||||
shown = _plain(console, lambda: splash.show(console, splash.SCANNER_NAME,
|
||||
("a",), no_splash=True))
|
||||
assert shown == ""
|
||||
|
||||
|
||||
def test_the_environment_can_turn_it_off_for_good(monkeypatch):
|
||||
"""For anybody who would rather it did not, without having to remember a
|
||||
flag on every invocation."""
|
||||
console = Console(width=100, force_terminal=True)
|
||||
monkeypatch.setenv("BANDSAUNTER_NO_SPLASH", "1")
|
||||
assert splash.wanted(console) is False
|
||||
shown = _plain(console, lambda: splash.show(console, splash.SCANNER_NAME,
|
||||
("a",)))
|
||||
assert shown == ""
|
||||
|
||||
|
||||
def test_it_says_whether_it_drew_anything():
|
||||
console = Console(width=100, force_terminal=False)
|
||||
assert splash.show(console, splash.SCANNER_NAME, ("a",)) is False
|
||||
assert splash.show(console, splash.SCANNER_NAME, ("a",), force=True) is True
|
||||
assert splash.show(console, "!!!", ("a",), force=True) is False
|
||||
|
||||
|
||||
def test_nothing_sleeps_when_nothing_is_drawn(monkeypatch):
|
||||
"""The pause is for a program about to take the screen over. Paying it
|
||||
with no banner drawn would be a tenth of a second added to every piped
|
||||
command for nothing."""
|
||||
import time
|
||||
|
||||
slept = []
|
||||
monkeypatch.setattr(time, "sleep", lambda s: slept.append(s))
|
||||
console = Console(width=100, force_terminal=False)
|
||||
splash.show(console, splash.BROWSER_NAME, ("a",), pause=5.0)
|
||||
assert slept == []
|
||||
splash.show(console, splash.BROWSER_NAME, ("a",), pause=0.25, force=True)
|
||||
assert slept == [0.25]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Where it is wired in
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_both_programs_can_be_told_not_to_draw_one():
|
||||
from bandsaunter.browse import build_parser as browse_parser
|
||||
from bandsaunter.cli import build_parser as cli_parser
|
||||
|
||||
assert cli_parser().parse_args(["--no-splash", "devices"]).no_splash
|
||||
assert not cli_parser().parse_args(["devices"]).no_splash
|
||||
assert browse_parser().parse_args(["--no-splash"]).no_splash
|
||||
assert not browse_parser().parse_args([]).no_splash
|
||||
|
||||
|
||||
def test_the_scanner_draws_its_own_name(monkeypatch):
|
||||
drawn = []
|
||||
monkeypatch.setattr(splash, "show",
|
||||
lambda console, word, lines=(), **kw:
|
||||
drawn.append((word, tuple(lines))) or False)
|
||||
from bandsaunter import cli
|
||||
|
||||
cli.main(["devices"])
|
||||
assert drawn and drawn[0][0] == splash.SCANNER_NAME
|
||||
lines = drawn[0][1]
|
||||
assert lines[0] == "Conceived by: The Dust Council"
|
||||
assert lines[1] == "100% AI Coded by Claude Code."
|
||||
|
||||
|
||||
def test_the_browser_draws_its_own_name_and_waits_a_moment(monkeypatch,
|
||||
tmp_path):
|
||||
drawn = []
|
||||
|
||||
def fake(console, word, lines=(), **kw):
|
||||
drawn.append((word, tuple(lines), kw.get("pause", 0.0)))
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(splash, "show", fake)
|
||||
from bandsaunter import browse
|
||||
|
||||
# Straight back out again: the banner is drawn before anything else.
|
||||
browse.main([str(tmp_path), "--callsigns"])
|
||||
assert drawn and drawn[0][0] == splash.BROWSER_NAME
|
||||
assert drawn[0][1][0] == "Conceived by: The Dust Council"
|
||||
assert drawn[0][1][1] == "100% AI Coded by Claude Code."
|
||||
# The browser runs on the alternate screen, so the banner needs a beat.
|
||||
assert drawn[0][2] > 0
|
||||
Loading…
Add table
Add a link
Reference in a new issue