Aircraft, from the menus, on a live board, over a real map

Four things the ADS-B mode was missing, and one it was actively getting
wrong.

The band plan lists 1090 MHz because that is where ADS-B is, so choosing
it from the band plan is the obvious thing to do -- and it records the
bursts as clicks in a WAV file and decodes nothing, silently.  Both the
scanner and the menus now say so, before the sweep starts, and name the
mode that does decode it.  It is not refused: looking at the raw spectrum
is a fair thing to want.

Menu 5, Aircraft (ADS-B), is the whole mode without a command line.  Every
option on one screen with a line saying what it does, ?N for the long
version and the flag it corresponds to, l to listen, m to draw a map from
any log, s to keep the options.  The listening and the drawing moved into
bandsaunter/aircraft.py so the menus and the command line run the same
code.

While it listens the screen is a live board: one line per aircraft in the
order first heard, the counter climbing as frames arrive, height coloured
low warm to high cold with an arrow for climb or descent, the age of the
last report going green to red, and the line removed once nothing has been
heard for --hold seconds, everything below moving up.  The registers are
asked while it runs, so registration, type, operator and route fill
themselves in as the answers arrive.

--speed-unit knots|mph|kph changes the heading of that board, the speed
beside every aircraft on the map and the speeds in the report, and moves
the distances with it so that one picture never carries two different
miles.  The log stays in knots, which is what the aircraft broadcast.

And there is a real map under the flight paths: {z}/{x}/{y} tiles fetched
once, cached in ~/.cache/bandsaunter/tiles, reprojected from Web Mercator
pixel by pixel, inverted and dimmed so the aircraft stay the brightest
thing on the picture.  The PNGs are decoded here -- zlib and the five row
filters from the specification, checked byte for byte against Pillow on
real tiles -- so nothing new is depended on.  Tiles are cached and never
re-fetched, every request says who is asking, and the attribution is drawn
onto the picture, because a GIF travels without its readme.

conftest now fails any test that reaches for a tile server or a register.
It caught four of these on the way in.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016PsWPTweCT6pwxKngvVxcg
This commit is contained in:
The Dust Council 2026-09-04 00:05:32 -07:00
parent 4239635f74
commit 96fc21ac7d
18 changed files with 3298 additions and 281 deletions

View file

@ -45,6 +45,43 @@ def no_licence_lookups(monkeypatch):
monkeypatch.setattr(bandsaunter.callsign.CallsignBook, "_request", refuse)
class NoNetwork(BaseException):
"""Raised when a test reaches for the network.
Deliberately not an ``Exception``: the code that fetches map tiles and
looks aircraft up treats any ordinary failure as "no map today" and
carries on, which would turn this guard into a silent pass.
"""
@pytest.fixture(autouse=True)
def no_aircraft_lookups(monkeypatch):
"""Nor may a test ask a register who an aircraft is."""
import bandsaunter.flights
def refuse(self, url):
raise NoNetwork(f"a test tried to fetch {url} for real")
monkeypatch.setattr(bandsaunter.flights.FlightBook, "_request", refuse)
@pytest.fixture(autouse=True)
def no_map_tiles(monkeypatch):
"""Nor fetch map tiles from somebody's tile server.
A test that wants a map builds its own tiles and passes them in; one
that forgets fails here rather than drawing an evening's worth of
requests at a volunteer-funded service.
"""
import bandsaunter.basemap
def refuse(request, timeout=None):
where = getattr(request, "full_url", request)
raise NoNetwork(f"a test tried to fetch {where} for real")
monkeypatch.setattr(bandsaunter.basemap.urllib.request, "urlopen", refuse)
@pytest.fixture(autouse=True)
def isolated_settings(tmp_path_factory, monkeypatch):
where = tmp_path_factory.mktemp("config")

View file

@ -0,0 +1,280 @@
"""The live display: one line per aircraft, updated in place.
What matters here is not that it is pretty but that it says the right things
and stops saying them at the right time -- an aircraft that has gone must
leave the screen, and everything below it must move up.
"""
import time
import pytest
from rich.console import Console
from bandsaunter import aircraft as air
from bandsaunter.adsb import Aircraft, AircraftRegistry
from bandsaunter.ui import AircraftDisplay, age_style, altitude_style, compass
NOW = 1_000_000.0
def craft(icao="4CA1FA", callsign="RYR1234", seen=NOW, first=None, **over):
one = Aircraft(icao=icao, callsign=callsign,
first_seen=first if first is not None else seen,
last_seen=seen)
one.altitude_ft = over.pop("altitude_ft", 35_000)
one.ground_speed_kt = over.pop("ground_speed_kt", 420.0)
one.track_deg = over.pop("track_deg", 90.0)
one.latitude = over.pop("latitude", 51.5)
one.longitude = over.pop("longitude", -0.12)
one.messages = over.pop("messages", 7)
for key, value in over.items():
setattr(one, key, value)
return one
def registry(*aircraft) -> AircraftRegistry:
reg = AircraftRegistry()
for one in aircraft:
reg.aircraft[one.icao] = one
return reg
def shown(display, now=NOW, width=140) -> str:
console = Console(width=width, record=True, force_terminal=True)
console.print(display.render(now=now, width=width))
return console.export_text()
def display_for(*aircraft, frames=None, hold=45.0, book=None, width=140):
reg = registry(*aircraft)
console = Console(width=width, force_terminal=True)
d = AircraftDisplay(console, book=book, hold=hold)
d.started = NOW - 10
d.update(reg, frames if frames is not None else
sum(a.messages for a in aircraft))
return d
# ---------------------------------------------------------------------------
# What is on the line
# ---------------------------------------------------------------------------
def test_an_aircraft_appears_with_everything_it_has_said():
d = display_for(craft())
text = shown(d)
assert "RYR1234" in text # who
assert "4CA1FA" in text # its address
assert "35,000" in text # how high
assert "420" in text # how fast
assert "090°" in text and "E" in text # which way
assert "51.5000" in text and "-0.1200" in text
assert "7" in text # how many frames
def test_the_counter_is_the_frame_count_and_it_climbs():
one = craft(messages=3)
d = display_for(one)
assert " 3 " in shown(d).replace(" ", " ")
one.messages = 41
d.update(d.registry, 41)
assert "41" in shown(d)
def test_a_climb_and_a_descent_are_marked():
up = shown(display_for(craft(vertical_rate_fpm=1600)))
down = shown(display_for(craft(icao="A0B1C2", vertical_rate_fpm=-1600)))
assert "" in up and "" not in up
assert "" in down and "" not in down
def test_an_aircraft_that_has_not_said_its_name_still_gets_a_line():
text = shown(display_for(craft(callsign="")))
assert "4CA1FA" in text
assert "" in text # the callsign it never gave
def test_an_aircraft_with_no_position_yet_says_so_rather_than_nothing():
one = craft(latitude=0.0, longitude=0.0)
assert "no fix yet" in shown(display_for(one))
def test_what_a_register_says_is_shown_beside_it():
class _Book:
def get(self, icao, callsign=""):
from bandsaunter.flights import Flight
return Flight(icao=icao, callsign=callsign, type_code="B738",
registration="EI-DYP", operator="Ryanair",
origin="Stansted", destination="East Midlands")
text = shown(display_for(craft(), book=_Book()))
assert "B738" in text and "EI-DYP" in text
assert "Ryanair" in text
assert "Stansted" in text
# ---------------------------------------------------------------------------
# Coming and going
# ---------------------------------------------------------------------------
def test_a_second_aircraft_is_added_under_the_first():
first = craft(icao="4CA1FA", callsign="RYR1234", first=NOW - 100)
second = craft(icao="A0B1C2", callsign="UAL99", first=NOW - 50)
text = shown(display_for(first, second))
assert text.index("RYR1234") < text.index("UAL99")
def test_an_aircraft_nothing_has_been_heard_from_is_dropped():
"""It has gone out of range; its line would otherwise sit there all
evening saying the same thing."""
here = craft(icao="4CA1FA", callsign="RYR1234", seen=NOW - 2)
gone = craft(icao="A0B1C2", callsign="UAL99", seen=NOW - 120)
text = shown(display_for(here, gone, hold=45.0))
assert "RYR1234" in text
assert "UAL99" not in text
def test_the_ones_below_move_up_when_one_goes():
top = craft(icao="111111", callsign="FIRST", first=NOW - 300, seen=NOW - 300)
middle = craft(icao="222222", callsign="SECOND", first=NOW - 200, seen=NOW)
bottom = craft(icao="333333", callsign="THIRD", first=NOW - 100, seen=NOW)
d = display_for(top, middle, bottom, hold=45.0)
lines = [x for x in shown(d).splitlines() if "SECOND" in x or "THIRD" in x
or "FIRST" in x]
assert len(lines) == 2 # FIRST has gone
assert "SECOND" in lines[0] and "THIRD" in lines[1]
def test_how_long_they_stay_can_be_changed():
quiet = craft(seen=NOW - 30)
assert "RYR1234" in shown(display_for(quiet, hold=45.0))
assert "RYR1234" not in shown(display_for(quiet, hold=10.0))
def test_the_age_of_the_last_frame_is_shown_and_coloured():
text = shown(display_for(craft(seen=NOW - 12)))
assert "12s" in text
assert age_style(1.0) != age_style(12.0) != age_style(40.0)
def test_nothing_heard_yet_says_so_rather_than_drawing_an_empty_table():
d = AircraftDisplay(Console(width=120, force_terminal=True))
d.update(AircraftRegistry(), 0)
assert "nothing heard yet" in shown(d)
# ---------------------------------------------------------------------------
# The heading
# ---------------------------------------------------------------------------
def test_the_heading_counts_what_is_overhead_and_what_has_been_seen():
here = craft(icao="4CA1FA", callsign="RYR1234", seen=NOW)
gone = craft(icao="A0B1C2", callsign="UAL99", seen=NOW - 500)
text = shown(display_for(here, gone, frames=99, hold=45.0))
assert "1 overhead" in text
assert "2 seen" in text # nothing is forgotten
assert "99 frames" in text
def test_the_heading_names_the_log_being_written(tmp_path):
d = display_for(craft())
d.update(d.registry, 5, tmp_path / "adsb_2026-09-03_20_00_00.jsonl")
assert "adsb_2026-09-03_20_00_00.jsonl" in shown(d)
# ---------------------------------------------------------------------------
# Colour, and a narrow terminal
# ---------------------------------------------------------------------------
def test_height_is_a_colour_low_warm_to_high_cold():
low, high = altitude_style(800), altitude_style(38_000)
assert low != high
assert "red" in low and "blue" in high
def test_the_colours_reach_the_screen():
console = Console(width=140, record=True, force_terminal=True,
color_system="truecolor")
console.print(display_for(craft(altitude_ft=1_200)).render(now=NOW))
assert "\x1b[" in console.export_text(styles=True)
@pytest.mark.parametrize("degrees,point", [(0, "N"), (90, "E"), (180, "S"),
(270, "W"), (45, "NE"),
(359, "N"), (247, "WSW")])
def test_a_heading_is_also_given_as_a_point_of_the_compass(degrees, point):
assert compass(degrees) == point
def test_a_narrow_terminal_keeps_what_only_the_aircraft_can_say():
"""A website can be read later; the aeroplane cannot."""
text = shown(display_for(craft()), width=80)
assert "RYR1234" in text and "35,000" in text and "420" in text
for line in text.splitlines():
assert len(line) <= 80
# ---------------------------------------------------------------------------
# When there is no terminal to draw on
# ---------------------------------------------------------------------------
def test_a_pipe_or_a_log_file_gets_no_live_display():
"""Four redraws a second is unreadable as a stream and useless in a file."""
console = Console(width=100, file=open("/dev/null", "w"),
force_terminal=False)
display, live = air._open_display(console, air.AircraftOptions(), None,
time.time())
assert display is None and live is None
def test_asking_for_every_frame_turns_the_table_off():
console = Console(width=100, force_terminal=True)
options = air.AircraftOptions(frames=True)
display, live = air._open_display(console, options, None, time.time())
assert display is None and live is None
def test_a_terminal_gets_one():
console = Console(width=100, force_terminal=True,
file=open("/dev/null", "w"))
display, live = air._open_display(console, air.AircraftOptions(), None,
time.time())
try:
assert display is not None and live is not None
assert display.hold == air.AircraftOptions().hold
finally:
if live is not None:
live.stop()
# ---------------------------------------------------------------------------
# Speeds in whatever the user reads
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("unit,heading,shown_speed", [
("knots", "speed kt", "420"),
("mph", "speed mph", "483"),
("kph", "speed km/h", "778"),
])
def test_the_heading_and_the_number_change_together(unit, heading, shown_speed):
"""A number with the wrong unit over it is worse than no number."""
d = display_for(craft(ground_speed_kt=420.0))
d.unit = unit
text = shown(d)
assert heading in text
assert shown_speed in text
def test_knots_are_what_it_shows_unless_told_otherwise():
assert AircraftDisplay(Console(width=100)).unit == "knots"
assert air.AircraftOptions().speed_unit == "knots"
def test_the_unit_reaches_the_display_from_the_options():
console = Console(width=100, force_terminal=True, file=open("/dev/null", "w"))
options = air.AircraftOptions(speed_unit="kph")
display, live = air._open_display(console, options, None, time.time())
try:
assert display.unit == "kph"
finally:
if live is not None:
live.stop()

346
tests/test_aircraft_menu.py Normal file
View file

@ -0,0 +1,346 @@
"""The aircraft menu: listening and drawing without a command line.
Everything here runs against the invented sky, so nothing needs a receiver,
an aerial or a network.
"""
import json
import pytest
from rich.console import Console
from bandsaunter import aircraft as air, tui
from bandsaunter.config import ScanConfig
from bandsaunter.ranges import parse_range_list
@pytest.fixture
def console():
return Console(width=100, file=open("/dev/null", "w"),
force_terminal=False)
@pytest.fixture
def settings_dir(tmp_path, monkeypatch):
"""Options are saved beside the settings, which must not be the real ones."""
monkeypatch.setenv("BANDSAUNTER_CONFIG_DIR", str(tmp_path / "cfg"))
monkeypatch.setattr("bandsaunter.config.DEFAULT_CONFIG_DIR",
tmp_path / "cfg")
return tmp_path / "cfg"
class _Done(Exception):
"""Raised when the script runs out, to break out of a menu loop."""
def drive(monkeypatch, answers):
script = list(answers)
def fake_ask(console, prompt, default=""):
if not script:
raise _Done()
return script.pop(0)
monkeypatch.setattr(tui, "_ask", fake_ask)
monkeypatch.setattr(tui.Confirm, "ask", lambda *a, **k: True)
return script
def number(key: str) -> str:
"""The menu number of one option, looked up rather than counted.
The numbering moves whenever an option is added, and a test that has
memorised it silently edits the wrong one.
"""
return str(air.OPTIONS.index(air.by_key(key)) + 1)
def run(monkeypatch, console, answers, cfg):
drive(monkeypatch, answers)
try:
tui.aircraft_menu(console, cfg)
except _Done:
pass
# ---------------------------------------------------------------------------
# The band that is not a scan
# ---------------------------------------------------------------------------
def test_the_band_plan_still_lists_where_ads_b_is():
"""It is a real band and belongs in the plan; the warning is the fix,
not removing it."""
from bandsaunter.bandplan import PRESETS
assert any(p.key == "adsb" for p in PRESETS)
@pytest.mark.parametrize("spec", ["1089M-1091M", "1080M-1100M", "1.09G-1.1G"])
def test_a_sweep_over_1090_says_it_cannot_decode_it(spec):
warning = air.scanning_aircraft_band(parse_range_list(spec))
assert "ADS-B" in warning and "cannot decode" in warning
def test_the_uat_band_is_named_too():
assert "UAT" in air.scanning_aircraft_band(parse_range_list("977M-979M"))
@pytest.mark.parametrize("spec", ["144M-148M", "462M-468M", "88M-108M"])
def test_an_ordinary_sweep_is_not_warned_about(spec):
assert air.scanning_aircraft_band(parse_range_list(spec)) == ""
def test_nothing_configured_warns_about_nothing():
assert air.scanning_aircraft_band([]) == ""
assert air.scanning_aircraft_band(None) == ""
def test_the_menu_says_so_the_moment_the_band_is_chosen(console, capsys):
"""The band plan is where this mistake is made, so that is where it is
caught."""
loud = Console(width=100)
cfg = ScanConfig(ranges=parse_range_list("1089M-1091M"))
tui.warn_about_aircraft_bands(loud, cfg)
printed = capsys.readouterr().out
assert "aircraft mode" in printed
assert "Aircraft (ADS-B)" in printed
def test_the_scan_command_says_so_before_it_starts(capsys):
from bandsaunter import cli
cfg = ScanConfig(ranges=parse_range_list("1089M-1091M"))
cli._warn_about_aircraft_bands(cfg)
printed = capsys.readouterr().out
assert "bandsaunter adsb" in printed
assert "flights" in printed
def test_a_scan_of_an_ordinary_band_says_nothing(capsys):
from bandsaunter import cli
cli._warn_about_aircraft_bands(ScanConfig(ranges=parse_range_list("2m")))
assert capsys.readouterr().out.strip() == ""
# ---------------------------------------------------------------------------
# The options
# ---------------------------------------------------------------------------
def test_every_option_has_help_and_a_home_on_the_screen():
for option in air.OPTIONS:
assert option.help, option.key
assert option.detail, option.key
assert option.group in air.OPTION_GROUPS, option.key
assert hasattr(air.AircraftOptions(), option.key), option.key
def test_the_options_are_the_ones_the_listening_and_drawing_take():
"""Anything settable must be something the code actually reads."""
named = {o.key for o in air.OPTIONS}
assert named == set(air.AircraftOptions().__dict__)
def test_a_zero_that_means_something_says_what_it_means():
options = air.AircraftOptions()
assert air.format_option(air.by_key("seconds"), 0.0) == "until stopped"
assert air.format_option(air.by_key("trail"), 0.0) == "the whole path"
assert air.format_option(air.by_key("seconds"), 60.0) == "60 s"
assert "gif" in air.describe(options)
def test_an_option_is_changed_from_the_menu(monkeypatch, console, settings_dir,
tmp_path):
cfg = ScanConfig(output_dir=str(tmp_path))
run(monkeypatch, console, [number("width"), "640", "b"], cfg)
assert air.load_options().width == 960 # not saved yet
run(monkeypatch, console, [number("width"), "640", "s", "b"], cfg)
assert air.load_options().width == 640 # saved on request
def test_a_bad_value_is_refused_and_the_old_one_kept(monkeypatch, console,
settings_dir, tmp_path):
cfg = ScanConfig(output_dir=str(tmp_path))
run(monkeypatch, console, [number("width"), "banana", "", "s", "b"], cfg)
assert air.load_options().width == 960
def test_a_value_the_options_refuse_is_rolled_back(monkeypatch, console,
settings_dir, tmp_path):
"""Two megasamples a second is the floor; below it a bit cannot be seen."""
cfg = ScanConfig(output_dir=str(tmp_path))
run(monkeypatch, console, [number("rate"), "500000", "", "s", "b"], cfg)
assert air.load_options().rate >= 2_000_000
def test_help_for_one_option_is_shown_without_changing_it(monkeypatch,
settings_dir,
tmp_path, capsys):
loud = Console(width=100)
cfg = ScanConfig(output_dir=str(tmp_path))
run(monkeypatch, loud, ["?" + number("simulate"), "b"], cfg)
printed = capsys.readouterr().out
assert "Invent a sky" in printed
assert "command line:" in printed and "--simulate" in printed
assert air.load_options().simulate is False
def test_the_options_survive_being_saved_and_read_back(settings_dir):
options = air.AircraftOptions(seconds=90.0, picture="png", simulate=True,
width=640, labels=False)
air.save_options(options)
again = air.load_options()
assert (again.seconds, again.picture, again.simulate) == (90.0, "png", True)
assert again.width == 640 and again.labels is False
def test_a_broken_options_file_falls_back_to_the_defaults(settings_dir):
air.options_path().parent.mkdir(parents=True, exist_ok=True)
air.options_path().write_text("{{{ not yaml at all")
assert air.load_options().picture == "png" or True # must not raise
assert air.load_options().width == 960
# ---------------------------------------------------------------------------
# Listening and drawing, from the menu alone
# ---------------------------------------------------------------------------
def _listen_and_draw(monkeypatch, console, tmp_path, picture="png"):
cfg = ScanConfig(output_dir=str(tmp_path))
run(monkeypatch, console,
[number("simulate"), "yes", # invent a sky
number("seconds"), "3", # listen for three seconds
number("picture"), picture, # what to draw
number("lookup"), "no", # no lookups: no network in a test
number("basemap"), "no", # nor a tile server
"l", # listen now
"m", "1", # draw the newest log
"b"], cfg)
return cfg
def test_listening_from_the_menu_writes_a_log_and_a_report(monkeypatch,
console,
settings_dir,
tmp_path):
_listen_and_draw(monkeypatch, console, tmp_path)
logs = list(tmp_path.glob("adsb_*.jsonl"))
assert len(logs) == 1
lines = [json.loads(x) for x in logs[0].read_text().splitlines() if x]
assert lines[0]["log"] == "bandsaunter-adsb"
assert any(line.get("icao") for line in lines[1:])
told = logs[0].with_suffix(".txt")
assert told.is_file() and "aircraft" in told.read_text()
def test_drawing_from_the_menu_writes_the_picture(monkeypatch, console,
settings_dir, tmp_path):
from bandsaunter.images import PNG_SIGNATURE
_listen_and_draw(monkeypatch, console, tmp_path)
pictures = list(tmp_path.glob("adsb_*.png"))
assert len(pictures) == 1
assert pictures[0].read_bytes()[:8] == PNG_SIGNATURE
def test_the_animation_can_be_chosen_instead(monkeypatch, console,
settings_dir, tmp_path):
_listen_and_draw(monkeypatch, console, tmp_path, picture="gif")
made = list(tmp_path.glob("adsb_*.gif"))
assert len(made) == 1
assert made[0].read_bytes()[:6] == b"GIF89a"
def test_drawing_when_there_is_nothing_to_draw_says_so(monkeypatch,
settings_dir,
tmp_path, capsys):
loud = Console(width=100)
cfg = ScanConfig(output_dir=str(tmp_path))
run(monkeypatch, loud, ["m", "b"], cfg)
assert "no logs" in capsys.readouterr().out
def test_listening_can_draw_as_soon_as_it_stops(monkeypatch, console,
settings_dir, tmp_path):
"""One key, from nothing to a picture."""
cfg = ScanConfig(output_dir=str(tmp_path))
run(monkeypatch, console,
[number("simulate"), "yes", number("seconds"), "3",
number("lookup"), "no", number("basemap"), "no",
number("draw_after"), "yes",
number("picture"), "png", "l", "b"], cfg)
assert list(tmp_path.glob("adsb_*.png"))
def test_a_receiver_that_cannot_be_opened_returns_to_the_menu(monkeypatch,
settings_dir,
tmp_path,
capsys):
"""No dongle, or one in use by something else: say so and come back."""
from bandsaunter.device import RtlSdrError
def refuse(*a, **k):
raise RtlSdrError("no device found")
monkeypatch.setattr("bandsaunter.device.RtlSdrDevice", refuse)
loud = Console(width=100)
cfg = ScanConfig(output_dir=str(tmp_path))
run(monkeypatch, loud, ["l", "b"], cfg) # simulate is off
assert "cannot open the receiver" in capsys.readouterr().out
def test_the_logs_are_listed_newest_first(tmp_path):
import os
import time
for i, name in enumerate(("adsb_a.jsonl", "adsb_b.jsonl", "adsb_c.jsonl")):
path = tmp_path / name
path.write_text("{}\n")
os.utime(path, (time.time() + i, time.time() + i))
assert [p.name for p in air.logs_in(tmp_path)] == \
["adsb_c.jsonl", "adsb_b.jsonl", "adsb_a.jsonl"]
def test_the_main_menu_offers_it(monkeypatch, console):
"""It has to be reachable, or none of the above matters."""
from bandsaunter import tui as menus
seen = {}
monkeypatch.setattr(menus, "aircraft_menu",
lambda console, cfg: seen.setdefault("opened", True))
drive(monkeypatch, ["5", "q"])
menus._main_loop(console, ScanConfig())
assert seen.get("opened")
def test_the_speed_unit_is_an_option_with_the_three_choices():
option = air.by_key("speed_unit")
assert option is not None
assert set(option.choices) == {"knots", "mph", "kph"}
assert "distance" in option.detail # it moves the miles too
def test_the_speed_unit_is_changed_from_the_menu(monkeypatch, console,
settings_dir, tmp_path):
cfg = ScanConfig(output_dir=str(tmp_path))
run(monkeypatch, console, [number("speed_unit"), "mph", "s", "b"], cfg)
assert air.load_options().speed_unit == "mph"
def test_a_unit_that_is_not_one_of_the_three_is_refused(monkeypatch, console,
settings_dir, tmp_path):
cfg = ScanConfig(output_dir=str(tmp_path))
run(monkeypatch, console,
[number("speed_unit"), "furlongs", "", "s", "b"], cfg)
assert air.load_options().speed_unit == "knots"
def test_the_map_underneath_is_an_option_that_can_be_turned_off(monkeypatch,
console,
settings_dir,
tmp_path):
"""It fetches from a tile server the first time an area is drawn, so it
has to be possible to say no."""
assert air.AircraftOptions().basemap is True
cfg = ScanConfig(output_dir=str(tmp_path))
run(monkeypatch, console, [number("basemap"), "no", "s", "b"], cfg)
assert air.load_options().basemap is False

459
tests/test_basemap.py Normal file
View file

@ -0,0 +1,459 @@
"""The ground under the aircraft: reading tiles, and putting them on the map.
Nothing here touches the network. The tiles are made up in the test and fed
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 struct
import zlib
import numpy as np
import pytest
from bandsaunter import basemap as bm
from bandsaunter import flightmap as fm
from test_flightmap import _has_text, two_aircraft
# ---------------------------------------------------------------------------
# Making PNGs the hard way, so the decoder is tested against the format
# ---------------------------------------------------------------------------
def _chunk(tag: bytes, body: bytes) -> bytes:
return (struct.pack(">I", len(body)) + tag + body
+ struct.pack(">I", zlib.crc32(tag + body) & 0xFFFFFFFF))
def _paeth(a: int, b: int, c: int) -> int:
p = a + b - c
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
if pa <= pb and pa <= pc:
return a
return b if pb <= pc else c
def make_png(pixels: np.ndarray, colour: int = 2, filter_type: int = 0,
palette: np.ndarray | None = None) -> bytes:
"""A PNG with every row written using one filter, built from the spec."""
pixels = np.asarray(pixels, dtype=np.uint8)
height, width = pixels.shape[0], pixels.shape[1]
channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}[colour]
flat = pixels.reshape(height, width * channels)
raw = bytearray()
previous = bytearray(width * channels)
for row in flat:
line = bytearray(int(v) for v in row)
out = bytearray(len(line))
for i, value in enumerate(line):
left_raw = line[i - channels] if i >= channels else 0
above = previous[i]
upleft = previous[i - channels] if i >= channels else 0
if filter_type == 0:
out[i] = value
elif filter_type == 1:
out[i] = (value - left_raw) & 0xFF
elif filter_type == 2:
out[i] = (value - above) & 0xFF
elif filter_type == 3:
out[i] = (value - ((left_raw + above) >> 1)) & 0xFF
else:
out[i] = (value - _paeth(left_raw, above, upleft)) & 0xFF
raw.append(filter_type)
raw += out
previous = line
body = (b"\x89PNG\r\n\x1a\n"
+ _chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8,
colour, 0, 0, 0)))
if palette is not None:
body += _chunk(b"PLTE", np.asarray(palette, dtype=np.uint8).tobytes())
body += _chunk(b"IDAT", zlib.compress(bytes(raw), 6))
return body + _chunk(b"IEND", b"")
def a_picture(height=9, width=7, seed=3) -> np.ndarray:
rng = np.random.default_rng(seed)
return rng.integers(0, 256, size=(height, width, 3), dtype=np.uint8)
# ---------------------------------------------------------------------------
# Reading a PNG
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("filter_type", [0, 1, 2, 3, 4])
def test_every_filter_the_format_defines_is_undone(filter_type):
"""None, Sub, Up, Average and Paeth: all five, or a tile comes back as
coloured noise and nobody notices until the map looks wrong."""
want = a_picture()
assert np.array_equal(bm.decode_png(make_png(want, 2, filter_type)), want)
def test_what_this_program_writes_it_can_read_back():
from bandsaunter.images import write_png
import tempfile
from pathlib import Path
want = a_picture(height=20, width=13, seed=9)
with tempfile.TemporaryDirectory() as tmp:
path = write_png(Path(tmp) / "x.png", want)
assert np.array_equal(bm.decode_png(path.read_bytes()), want)
def test_a_palette_image_is_looked_up():
"""The tiles most servers send are palette images."""
palette = np.array([[0, 0, 0], [255, 0, 0], [0, 128, 255]], dtype=np.uint8)
indices = np.array([[0, 1, 2], [2, 1, 0]], dtype=np.uint8)[:, :, None]
got = bm.decode_png(make_png(indices, colour=3, palette=palette))
assert np.array_equal(got, palette[indices[:, :, 0]])
def test_a_grey_image_becomes_grey_pixels():
grey = np.array([[0, 64], [128, 255]], dtype=np.uint8)[:, :, None]
got = bm.decode_png(make_png(grey, colour=0))
assert got.shape == (2, 2, 3)
assert np.array_equal(got[:, :, 0], got[:, :, 2])
assert got[1, 1, 0] == 255
def test_transparency_is_dropped_rather_than_misread():
rng = np.random.default_rng(1)
rgba = rng.integers(0, 256, size=(4, 4, 4), dtype=np.uint8)
got = bm.decode_png(make_png(rgba, colour=6))
assert np.array_equal(got, rgba[:, :, :3])
@pytest.mark.parametrize("body,why", [
(b"not a png at all", "not a PNG"),
(b"\x89PNG\r\n\x1a\n", "no image"),
])
def test_something_that_is_not_a_tile_is_refused(body, why):
with pytest.raises(bm.PNGError):
bm.decode_png(body)
def test_a_depth_this_cannot_read_says_so_rather_than_guessing():
header = (b"\x89PNG\r\n\x1a\n"
+ _chunk(b"IHDR", struct.pack(">IIBBBBB", 2, 2, 16, 2, 0, 0, 0))
+ _chunk(b"IEND", b""))
with pytest.raises(bm.PNGError):
bm.decode_png(header)
def test_an_interlaced_tile_is_refused():
header = (b"\x89PNG\r\n\x1a\n"
+ _chunk(b"IHDR", struct.pack(">IIBBBBB", 2, 2, 8, 2, 0, 0, 1))
+ _chunk(b"IEND", b""))
with pytest.raises(bm.PNGError):
bm.decode_png(header)
# ---------------------------------------------------------------------------
# Which tiles, and where they go
# ---------------------------------------------------------------------------
def test_the_middle_of_the_world_is_the_middle_of_the_grid():
assert bm.tile_of(0.0, 0.0, 0) == pytest.approx((0.5, 0.5))
assert bm.tile_of(0.0, -180.0, 1)[0] == pytest.approx(0.0)
assert bm.tile_of(85.05, 0.0, 1)[1] == pytest.approx(0.0, abs=0.001)
def test_a_known_place_lands_in_its_known_tile():
"""Seattle at zoom 10 is tile 164, 357 -- worked out from the standard
formula, not from this module."""
import math
lat, lon, z = 47.6062, -122.3321, 10
n = 2 ** z
x = int((lon + 180.0) / 360.0 * n)
y = int((1.0 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2.0 * n)
got = bm.tile_of(lat, lon, z)
assert (int(got[0]), int(got[1])) == (x, y)
def test_a_small_box_gets_more_detail_than_a_large_one():
tight = bm.choose_zoom(47.5, -122.4, 47.7, -122.2)
wide = bm.choose_zoom(30.0, -130.0, 50.0, -70.0)
assert tight > wide
assert tight <= bm.MAX_ZOOM and wide >= bm.MIN_ZOOM
def test_the_zoom_is_chosen_to_stay_inside_the_tile_budget():
south, west, north, east = 47.0, -122.8, 48.5, -121.0
zoom = bm.choose_zoom(south, west, north, east, max_tiles=12)
x0, y0 = bm.tile_of(north, west, zoom)
x1, y1 = bm.tile_of(south, east, zoom)
tiles = (int(x1) - int(x0) + 1) * (int(y1) - int(y0) + 1)
assert tiles <= 12
# ---------------------------------------------------------------------------
# Stitching, without a network
# ---------------------------------------------------------------------------
def solid(value):
"""A tile of one colour, as PNG bytes."""
px = np.zeros((bm.TILE_PIXELS, bm.TILE_PIXELS, 3), dtype=np.uint8) + value
return make_png(px)
def counting_fetcher(answers=None, fail_on=()):
"""A stand-in for the tile server that records what it was asked for."""
asked = []
def fetch(z, x, y, **kw):
asked.append((z, x, y))
if (z, x, y) in fail_on:
return None
if answers is not None:
return answers(z, x, y)
return solid((x * 37 + y * 11) % 256)
fetch.asked = asked
return fetch
def test_the_tiles_are_stitched_in_the_right_places():
fetch = counting_fetcher()
raster, ox, oy = bm.mosaic(47.0, -122.8, 48.5, -121.0, 9, fetch=fetch,
pause=0)
assert raster is not None
assert raster.shape[2] == 3
assert raster.shape[0] % bm.TILE_PIXELS == 0
assert len(fetch.asked) == (raster.shape[0] // bm.TILE_PIXELS) * \
(raster.shape[1] // bm.TILE_PIXELS)
# The first tile fetched is the north-west corner, and it is drawn there.
z, x, y = fetch.asked[0]
assert (ox, oy) == (x * bm.TILE_PIXELS, y * bm.TILE_PIXELS)
assert raster[0, 0, 0] == (x * 37 + y * 11) % 256
def test_a_tile_that_does_not_arrive_leaves_a_hole_rather_than_an_error():
"""One tile missing is a hole in the map, not a failed drawing."""
seen = counting_fetcher()
bm.mosaic(47.0, -122.8, 48.5, -121.0, 9, fetch=seen, pause=0)
missing = seen.asked[:1]
raster, _, _ = bm.mosaic(47.0, -122.8, 48.5, -121.0, 9,
fetch=counting_fetcher(fail_on=missing), pause=0)
assert raster is not None
assert not raster[:bm.TILE_PIXELS, :bm.TILE_PIXELS].any() # the hole
def test_nothing_at_all_gives_no_map():
def nothing(z, x, y, **kw):
return None
raster, _, _ = bm.mosaic(47.0, -122.8, 48.5, -121.0, 9, fetch=nothing,
pause=0)
assert raster is None
def test_a_corrupt_tile_is_skipped():
def rubbish(z, x, y, **kw):
return b"not a png"
raster, _, _ = bm.mosaic(47.0, -122.8, 48.5, -121.0, 9, fetch=rubbish,
pause=0)
assert raster is None
# ---------------------------------------------------------------------------
# On to the picture
# ---------------------------------------------------------------------------
def gradient_tile(z, x, y, **kw):
"""A tile that is black at the top and white at the bottom."""
column = np.linspace(0, 255, bm.TILE_PIXELS).astype(np.uint8)
px = np.repeat(column[:, None], bm.TILE_PIXELS, axis=1)
return make_png(np.repeat(px[:, :, None], 3, axis=2))
def test_the_ground_comes_back_as_levels_the_map_can_paint():
levels = bm.ground_under(47.0, -122.8, 48.5, -121.0, 200, 150,
shades=32, fetch=gradient_tile, pause=0)
assert levels is not None
assert levels.shape == (150, 200)
assert levels.dtype == np.uint8
assert levels.max() <= 31
def tile_bounds(zoom: int, x: int, y: int):
"""The corners of one tile, from the inverse of the standard formula.
Written here rather than taken from the module, so that a test of where
the pixels land is not asking the code under test where they land.
"""
import math
n = 2.0 ** zoom
def lat_of(row):
return math.degrees(math.atan(math.sinh(math.pi * (1 - 2 * row / n))))
return (lat_of(y + 1), x / n * 360.0 - 180.0, # south, west
lat_of(y), (x + 1) / n * 360.0 - 180.0) # north, east
def test_the_map_is_inverted_so_that_ink_shows_on_a_dark_picture():
"""A printed map is dark ink on white paper; this picture is the other
way round, so the dark parts of a tile are the bright parts here."""
south, west, north, east = tile_bounds(9, 81, 178)
levels = bm.ground_under(south, west, north, east, 64, 64, shades=32,
fetch=gradient_tile, zoom=9, pause=0)
# The tile is black at the top and white at the bottom, so the picture
# has to be bright at the top and dark at the bottom.
assert levels[0].mean() > levels[-1].mean()
assert levels[0].mean() > 25 and levels[-1].mean() < 6
def test_north_is_at_the_top():
def half_and_half(z, x, y, **kw):
px = np.zeros((bm.TILE_PIXELS, bm.TILE_PIXELS, 3), dtype=np.uint8)
px[:bm.TILE_PIXELS // 2] = 255 # white in the north
return make_png(px)
south, west, north, east = tile_bounds(9, 81, 178)
levels = bm.ground_under(south, west, north, east, 40, 40, shades=32,
fetch=half_and_half, zoom=9, pause=0)
assert levels[0].mean() < levels[-1].mean() # white inverts to dark
def test_east_is_to_the_right():
def half_and_half(z, x, y, **kw):
px = np.zeros((bm.TILE_PIXELS, bm.TILE_PIXELS, 3), dtype=np.uint8)
px[:, :bm.TILE_PIXELS // 2] = 255 # white in the west
return make_png(px)
south, west, north, east = tile_bounds(9, 81, 178)
levels = bm.ground_under(south, west, north, east, 40, 40, shades=32,
fetch=half_and_half, zoom=9, pause=0)
assert levels[:, 0].mean() < levels[:, -1].mean()
def test_one_tile_covers_its_own_box_exactly():
"""The reprojection has to put the tile where the tile says it is."""
def corner_marks(z, x, y, **kw):
px = np.zeros((bm.TILE_PIXELS, bm.TILE_PIXELS, 3), dtype=np.uint8)
px[:8, :8] = 255 # a mark in the north-west
return make_png(px)
south, west, north, east = tile_bounds(9, 81, 178)
levels = bm.ground_under(south, west, north, east, 128, 128, shades=32,
fetch=corner_marks, zoom=9, pause=0)
dark = levels < levels.max() / 2 # the white corner, inverted
assert dark[:4, :4].all()
assert not dark[64:, 64:].any()
def test_no_tiles_means_no_ground_rather_than_an_exception():
def nothing(z, x, y, **kw):
return None
assert bm.ground_under(47.0, -122.8, 48.5, -121.0, 50, 50,
fetch=nothing, pause=0) is None
def test_a_box_that_makes_no_sense_is_refused_quietly():
assert bm.ground_under(48.0, -122.0, 47.0, -123.0, 50, 50,
fetch=gradient_tile, pause=0) is None
# ---------------------------------------------------------------------------
# Fetching once, and saying who it came from
# ---------------------------------------------------------------------------
def test_a_tile_is_fetched_once_and_then_read_from_the_disk(tmp_path,
monkeypatch):
calls = []
class _Answer:
def __init__(self, body):
self.body = body
def read(self, *a):
return self.body
def __enter__(self):
return self
def __exit__(self, *exc):
return False
def fake_urlopen(request, timeout=None):
calls.append(request.full_url)
assert "bandsaunter" in request.headers.get("User-agent", ""), \
"a tile server is told who is asking"
return _Answer(solid(120))
monkeypatch.setattr(bm.urllib.request, "urlopen", fake_urlopen)
first = bm.fetch_tile(9, 81, 178, cache=tmp_path)
second = bm.fetch_tile(9, 81, 178, cache=tmp_path)
assert first == second
assert len(calls) == 1, "the second one came off the disk"
assert (tmp_path / "9" / "81" / "178.png").is_file()
def test_a_tile_server_that_is_not_there_is_not_an_error(tmp_path, monkeypatch):
def refuse(request, timeout=None):
raise OSError("no route to host")
monkeypatch.setattr(bm.urllib.request, "urlopen", refuse)
assert bm.fetch_tile(9, 81, 178, cache=tmp_path) is None
def test_the_tile_server_can_be_pointed_somewhere_else(tmp_path, monkeypatch):
seen = []
def fake_urlopen(request, timeout=None):
seen.append(request.full_url)
raise OSError("stop here")
monkeypatch.setattr(bm.urllib.request, "urlopen", fake_urlopen)
bm.fetch_tile(4, 2, 3, url="https://example.invalid/{z}/{x}/{y}.png",
cache=tmp_path)
assert seen == ["https://example.invalid/4/2/3.png"]
# ---------------------------------------------------------------------------
# And under the aircraft
# ---------------------------------------------------------------------------
def test_the_map_goes_under_the_picture_and_is_credited(tmp_path):
out = fm.animate(two_aircraft(), tmp_path / "on-the-map.png", width=400,
ground=True, fetch=gradient_tile)
assert out is not None and out.ground
assert "on the map" in out.summary()
from bandsaunter.images import PNG_SIGNATURE
assert out.path.read_bytes()[:8] == PNG_SIGNATURE
def test_the_ground_is_drawn_in_its_own_shades():
view = fm.fit(two_aircraft(), width=400)
levels, credit = fm.ground_for(view, fetch=gradient_tile)
assert levels is not None and credit
base = fm.background(view, ground=levels, attribution=credit)
body = base[view.top:view.top + view.height,
view.left:view.left + view.width]
ground = (body >= fm.GROUND) & (body < fm.GROUND + fm.GROUND_SHADES)
assert ground.mean() > 0.9 # nearly all of the body is map
def test_without_it_the_picture_is_the_plain_grid_it_always_was():
view = fm.fit(two_aircraft(), width=400)
base = fm.background(view)
assert not ((base >= fm.GROUND) & (base < fm.GROUND + fm.GROUND_SHADES)).any()
def test_no_network_falls_back_to_the_plain_grid(monkeypatch):
def nothing(z, x, y, **kw):
return None
view = fm.fit(two_aircraft(), width=400)
levels, credit = fm.ground_for(view, fetch=nothing)
assert levels is None and credit == ""
def test_the_credit_is_written_on_the_picture_itself():
"""A GIF travels without the readme that would otherwise carry it."""
view = fm.fit(two_aircraft(), width=520)
levels, credit = fm.ground_for(view, fetch=gradient_tile)
base = fm.background(view, ground=levels, attribution=credit)
assert _has_text(base, "OPENSTREETMAP")

View file

@ -398,3 +398,65 @@ def test_the_picture_is_an_even_number_of_pixels_across(tmp_path):
view = fm.fit(two_aircraft(), width=width)
w, h = fm.canvas_size(view)
assert w % 2 == 0 and h % 2 == 0
# ---------------------------------------------------------------------------
# Speeds in whatever the user reads
# ---------------------------------------------------------------------------
def _label_text(unit: str, width: int = 700) -> np.ndarray:
"""Draw one aircraft and hand back the pixels its label was written in."""
tracks = [straight(speed=480.0)]
view = fm.fit(tracks, width=width)
base = fm.background(view, unit=unit)
return fm.render_frame(base, view, tracks, tracks[0].first_seen + 120,
unit=unit)
def _has_text(frame: np.ndarray, text: str) -> bool:
"""Whether a string was stamped anywhere in the frame, found by drawing
it again and looking for the same pattern."""
from bandsaunter.images import GLYPH_H, draw_text, text_width
stamp = np.zeros((GLYPH_H, max(1, text_width(text))), dtype=np.uint8)
draw_text(stamp, 0, 0, text, 1)
rows, cols = stamp.shape
wanted = stamp.astype(bool)
if not wanted.any():
return False
for y in range(frame.shape[0] - rows):
for x in range(frame.shape[1] - cols):
patch = frame[y:y + rows, x:x + cols]
if np.all(patch[wanted] != fm.BG) and \
np.all(patch[~wanted] == patch[~wanted][0]):
return True
return False
@pytest.mark.parametrize("unit,label", [("knots", "KT"), ("mph", "MPH"),
("kph", "KM/H")])
def test_the_speed_on_the_map_carries_its_unit(unit, label):
"""A bare 480 beside an aircraft is three different speeds depending on
who is reading it."""
assert _has_text(_label_text(unit), label)
def test_the_number_beside_it_is_converted():
assert _has_text(_label_text("knots"), "480KT")
assert _has_text(_label_text("mph"), "552MPH")
assert _has_text(_label_text("kph"), "889KM/H")
@pytest.mark.parametrize("unit,label", [("knots", "NM"), ("mph", "MI"),
("kph", "KM")])
def test_the_scale_bar_uses_the_same_kind_of_mile(unit, label):
"""Miles an hour beside a scale in nautical miles is two different miles
on one picture."""
view = fm.fit(two_aircraft(), width=700)
assert _has_text(fm.background(view, unit=unit), label)
def test_the_animation_takes_the_unit_through_to_the_file(tmp_path):
out = fm.animate(two_aircraft(), tmp_path / "mph.png", width=500,
unit="mph")
assert out is not None and out.path.is_file()

View file

@ -486,3 +486,64 @@ def test_a_simulated_sky_is_heard_recorded_and_read_back(tmp_path):
flown = track.distance_nm
expected = track.top_speed_kt * track.seconds / 3600.0
assert flown == pytest.approx(expected, rel=0.35, abs=0.2)
# ---------------------------------------------------------------------------
# Speeds and distances in whatever the user reads
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("unit,speed,distance", [
("knots", "kt", "nm"), ("mph", "mph", "mi"), ("kph", "km/h", "km"),
])
def test_the_report_says_which_unit_it_is_using(tmp_path, unit, speed,
distance):
log = _log(tmp_path)
for i in range(4):
log.append(_Frame(callsign="RYR1234", altitude_ft=30_000,
ground_speed_kt=420.0, track_deg=90.0),
_Craft(51.5, -0.12 + i * 0.05, "RYR1234"),
when=1_000_000.0 + i * 30)
log.close()
text = "\n".join(report(read_logs(log.path), unit=unit))
assert "speed: up to " in text and speed in text
assert distance in text
def test_the_numbers_are_the_right_ones():
from bandsaunter.flightlog import in_distance, in_speed
assert in_speed(100, "knots") == pytest.approx(100.0)
assert in_speed(100, "mph") == pytest.approx(115.08, abs=0.01)
assert in_speed(100, "kph") == pytest.approx(185.2, abs=0.01)
assert in_distance(100, "mph") == pytest.approx(115.08, abs=0.01)
assert in_distance(100, "kph") == pytest.approx(185.2, abs=0.01)
def test_an_unknown_unit_falls_back_to_what_the_aircraft_said():
from bandsaunter.flightlog import in_speed, speed_label
assert in_speed(100, "furlongs per fortnight") == 100.0
assert speed_label("") == "kt"
def test_the_log_itself_is_always_in_knots(tmp_path):
"""The recording is what arrived; converting it would lose the original."""
log = _log(tmp_path)
log.append(_Frame(ground_speed_kt=420.0, track_deg=90.0),
_Craft(51.5, -0.12), when=1_000_000.0)
log.close()
line = [json.loads(x) for x in log.path.read_text().splitlines()][1]
assert line["gs_kt"] == 420.0
def test_what_one_track_says_of_itself_follows_the_unit(tmp_path):
log = _log(tmp_path)
for i in range(3):
log.append(_Frame(ground_speed_kt=420.0, track_deg=90.0,
altitude_ft=30_000),
_Craft(51.5, -0.12 + i * 0.05), when=1_000_000.0 + i * 30)
log.close()
track = read_logs(log.path)[0]
assert "kt" in track.describe()
assert "mph" in track.describe("mph")
assert "km/h" in track.describe("kph")