818 lines
38 KiB
Ruby
818 lines
38 KiB
Ruby
require_relative "test_helper"
|
||
require "tempfile"
|
||
|
||
class AppTest < Minitest::Test
|
||
include AppTestHelper
|
||
|
||
def test_health
|
||
response = request.get("/api/health")
|
||
assert_equal 200, response.status
|
||
assert_equal({ "status" => "ok", "revision" => "dev" }, json_body(response))
|
||
end
|
||
|
||
def test_index_renders_with_asset_versioning_and_importmap
|
||
response = request.get("/")
|
||
assert_equal 200, response.status
|
||
assert_match(/\/js\/map\.js\?v=\d+/, response.body)
|
||
assert_includes response.body, "importmap"
|
||
assert_includes response.body, "livetrack-panel"
|
||
end
|
||
|
||
# Every public/js/*.js module map.js (or something it imports) can reach
|
||
# needs its own versioned importmap entry (views/layout.erb) or it skips
|
||
# ASSET_VERSION's whole cache-busting story — easy to forget when adding a
|
||
# new module, since the app still works fine locally either way (a plain
|
||
# unmapped import just resolves straight to the unversioned file).
|
||
# map.js itself is excluded: it's the one entry point loaded directly by
|
||
# its own <script> tag, not imported by anything, so it has no importmap
|
||
# entry of its own by design.
|
||
def test_every_own_js_module_has_a_versioned_importmap_entry
|
||
response = request.get("/")
|
||
modules = Dir.glob(File.join(__dir__, "..", "public", "js", "*.js")).map { |path| File.basename(path) } - ["map.js"]
|
||
modules.each do |name|
|
||
assert_match(%r{"/js/#{Regexp.escape(name)}":\s*"/js/#{Regexp.escape(name)}\?v=\d+"}, response.body, "#{name} is missing from the importmap")
|
||
end
|
||
end
|
||
|
||
# Same for every /vendor module our own JS imports: one that changes with
|
||
# the app (mdi.mjs gaining an icon) left cached under the old URL while
|
||
# its freshly versioned importer asks for a new export is a dead page.
|
||
def test_every_imported_vendor_module_has_a_versioned_importmap_entry
|
||
response = request.get("/")
|
||
sources = Dir.glob(File.join(__dir__, "..", "public", "js", "*.js")).map { |path| File.read(path) }.join("\n")
|
||
vendor = sources.scan(%r{from\s+"(/vendor/[^"?]+)"}).flatten.uniq
|
||
refute_empty vendor
|
||
vendor.each do |path|
|
||
assert_match(%r{"#{Regexp.escape(path)}":\s*"#{Regexp.escape(path)}\?v=\d+"}, response.body, "#{path} is missing from the importmap")
|
||
end
|
||
end
|
||
|
||
# The legend page imports app and vendor modules too: it must get the
|
||
# same versioned importmap, and stay light (auto-darkening washed out its
|
||
# color swatches on a tablet).
|
||
def test_symbols_page_has_the_versioned_importmap_and_a_light_color_scheme
|
||
response = request.get("/symbols.html")
|
||
assert_equal 200, response.status
|
||
assert_match(%r{"/vendor/mdi/mdi\.mjs":\s*"/vendor/mdi/mdi\.mjs\?v=\d+"}, response.body)
|
||
assert_match(%r{"/js/icons\.js":\s*"/js/icons\.js\?v=\d+"}, response.body)
|
||
assert_includes response.body, '<meta name="color-scheme" content="light">'
|
||
assert_operator response.body.index("importmap"), :<, response.body.index('<script type="module">')
|
||
end
|
||
|
||
# Unversioned /vendor modules must be revalidated, or a deploy adding an
|
||
# export to one (imported by a freshly versioned /js module) breaks a
|
||
# browser still holding the old copy — see static_cache_control in app.rb.
|
||
def test_static_files_are_revalidated
|
||
response = request.get("/vendor/mdi/mdi.mjs")
|
||
assert_equal 200, response.status
|
||
assert_includes response.headers["Cache-Control"], "no-cache"
|
||
end
|
||
|
||
def test_offline_tiles_reports_unavailable_when_no_pmtiles_present
|
||
response = request.get("/api/offline-tiles")
|
||
assert_equal({ "available" => false }, json_body(response))
|
||
end
|
||
|
||
def test_hiking_trails_reports_no_countries_when_none_extracted_yet
|
||
response = request.get("/api/hiking-trails")
|
||
assert_equal({ "countries" => [], "bboxes" => {} }, json_body(response))
|
||
end
|
||
|
||
def test_hiking_trails_file_404s_for_a_country_with_no_extract
|
||
assert_equal 404, request.get("/tiles/hiking_trails/SK.geojson").status
|
||
end
|
||
|
||
def test_hiking_trails_file_404s_for_a_malformed_country_code
|
||
assert_equal 404, request.get("/tiles/hiking_trails/../../etc/passwd.geojson").status
|
||
end
|
||
|
||
def test_kiwix_reports_unavailable_when_no_url_configured
|
||
response = request.get("/api/kiwix")
|
||
assert_equal({ "available" => false, "url" => "" }, json_body(response))
|
||
end
|
||
|
||
def test_kiwix_proxy_404s_when_no_url_configured
|
||
assert_equal 404, request.get("/kiwix/search").status
|
||
end
|
||
|
||
def test_kiwix_nearby_404s_when_no_url_configured
|
||
assert_equal 404, request.get("/api/kiwix/nearby", params: { south: "48", west: "17", north: "48.1", east: "17.1" }).status
|
||
end
|
||
|
||
def test_gnss_position_unavailable_with_no_fix
|
||
response = request.get("/api/gnss/position", **logged_in_env)
|
||
assert_equal({ "available" => false }, json_body(response))
|
||
end
|
||
|
||
def test_gnss_position_requires_login
|
||
assert_equal 401, request.get("/api/gnss/position").status
|
||
end
|
||
|
||
def test_nps_index_404s_without_data
|
||
assert_equal 404, request.get("/api/nps").status
|
||
end
|
||
|
||
# The NPS overlay's index and files, public; only overlay/, geotiff/ and
|
||
# pdf/ under data/nps/ are reachable.
|
||
def test_nps_serves_the_index_and_its_files_only
|
||
dir = Maptool::App::NPS_DIR
|
||
FileUtils.mkdir_p(File.join(dir, "pdf"))
|
||
File.write(File.join(dir, "nps.json"), '{"parks":{},"maps":[]}')
|
||
File.write(File.join(dir, "pdf", "zion_abc.pdf"), "%PDF")
|
||
File.write(File.join(dir, "secret.txt"), "no")
|
||
|
||
response = request.get("/api/nps")
|
||
assert_equal 200, response.status
|
||
assert_equal({ "parks" => {}, "maps" => [] }, json_body(response))
|
||
assert_equal "%PDF", request.get("/nps/pdf/zion_abc.pdf").body
|
||
assert_equal 404, request.get("/nps/pdf/missing.pdf").status
|
||
assert_equal 404, request.get("/nps/secret.txt").status
|
||
assert_equal 404, request.get("/nps/pdf/..%2Fsecret.txt").status
|
||
assert_equal 404, request.get("/nps/other/zion_abc.pdf").status
|
||
ensure
|
||
FileUtils.rm_rf(Maptool::App::NPS_DIR)
|
||
end
|
||
|
||
def test_live_requires_login
|
||
assert_equal 401, request.get("/api/live").status
|
||
end
|
||
|
||
def test_the_sync_feed_needs_the_sync_token
|
||
# No SYNC_TOKEN in tests: closed, even with a login or an empty bearer.
|
||
assert_equal 401, request.get("/api/sync/changes").status
|
||
assert_equal 401, request.get("/api/sync/changes", "HTTP_AUTHORIZATION" => "Bearer ", **logged_in_env).status
|
||
assert_equal 401, request.get("/api/sync/source/x").status
|
||
assert_equal 401, request.post("/api/sync/apply", input: "{}").status
|
||
assert_equal 401, request.put("/api/sync/source/x", input: "x").status
|
||
assert_equal 401, request.get("/api/sync/maps", **logged_in_env).status
|
||
assert_equal 401, request.get("/api/sync/maps/file", params: { "path" => "offline.pmtiles" }).status
|
||
end
|
||
|
||
def test_connected_networks_are_the_interfaces_subnets
|
||
networks = Maptool::App.connected_networks
|
||
assert(networks.any? { |n| n.include?(IPAddr.new("127.0.0.1")) }, "loopback's 127.0.0.0/8")
|
||
refute(networks.any? { |n| n.include?(IPAddr.new("8.8.8.8")) })
|
||
end
|
||
|
||
def test_map_data_offered_to_clients_is_only_the_map_files
|
||
data = Maptool::App::DATA_DIR
|
||
files = %w[terrain.pmtiles places/SK.sqlite places/.rsync-partial/SK.sqlite routing/tiles.tar.part routing/service.sh can.json]
|
||
files.each { |f| FileUtils.mkdir_p(File.dirname(File.join(data, f))); File.write(File.join(data, f), "x") }
|
||
offered = Maptool::App.map_sync_files
|
||
assert_includes offered.keys, "terrain.pmtiles"
|
||
assert_includes offered.keys, "places/SK.sqlite"
|
||
refute(offered.keys.any? { |f| f.include?(".rsync-partial") || f.end_with?(".part") || %w[can.json routing/service.sh].include?(f) })
|
||
ensure
|
||
files.each { |f| FileUtils.rm_f(File.join(data, f)) }
|
||
end
|
||
|
||
def test_the_sync_button_is_only_a_clients
|
||
assert_equal 401, request.post("/api/sync/run").status
|
||
assert_equal 404, request.post("/api/sync/run", **logged_in_env).status
|
||
refute_includes request.get("/", **logged_in_env).body, "data-sync-client"
|
||
end
|
||
|
||
def test_can_recordings_are_listed_and_served_by_name_only
|
||
assert_equal 401, request.get("/api/can/recording").status
|
||
dir = File.join(Maptool::App::DATA_DIR, "can_rec")
|
||
FileUtils.mkdir_p(dir)
|
||
File.write(File.join(dir, "20261202-181105.mf4"), "MDF")
|
||
File.write(File.join(dir, "20261202-181105.mf4.part"), "")
|
||
body = json_body(request.get("/api/can/recording", **logged_in_env))
|
||
assert_equal [false, false, ["20261202-181105.mf4"]], [body["available"], body["running"], body["files"].map { |f| f["name"] }]
|
||
assert_equal 409, request.post("/api/can/recording", **logged_in_env).status
|
||
assert_equal "MDF", request.get("/api/can/recordings/20261202-181105.mf4", **logged_in_env).body
|
||
assert_equal 404, request.get("/api/can/recordings/20261202-181105.mf4.part", **logged_in_env).status
|
||
assert_equal 404, request.get("/api/can/recordings/..%2Fcan.json", **logged_in_env).status
|
||
ensure
|
||
FileUtils.rm_rf(dir)
|
||
end
|
||
|
||
def test_can_requires_login_and_is_off_without_a_config
|
||
assert_equal 401, request.get("/api/can").status
|
||
assert_equal 409, request.post("/api/can/actions/0", **logged_in_env).status
|
||
assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false, "simulated" => false, "actions" => [] }, json_body(request.get("/api/can", **logged_in_env)))
|
||
end
|
||
|
||
# MQTT messages land in the tracker / ITS-G5 parts of /api/live.
|
||
def test_live_routes_topics_into_the_snapshot
|
||
app = Maptool::App
|
||
now = Time.now.to_f
|
||
app.record_live(app::TRACKER_TOPIC, '{"latitude":48.1,"longitude":17.1,"speed":3}', at: now - 600)
|
||
app.record_live(app::TRACKER_POWER_TOPIC, "ON")
|
||
app.record_live(app::ITS_TOPIC, '{"id":"new","msg":"DENM","lat":48.2,"lon":17.2}', at: now)
|
||
app.record_live(app::ITS_TOPIC, "not json")
|
||
body = json_body(request.get("/api/live", **logged_in_env))
|
||
assert_equal 48.1, body["tracker"]["latitude"]
|
||
assert_in_delta 600, body["tracker"]["age"], 2
|
||
assert_equal true, body["tracker"]["usb_power"]
|
||
assert_equal ["new"], body["its"].map { |s| s["id"] }
|
||
assert_equal "Tracker", body["settings"]["name"]
|
||
assert_equal false, body["available"] # no MQTT_URL in tests
|
||
end
|
||
|
||
def test_live_settings_require_login_and_save
|
||
assert_equal 401, request.put("/api/live/settings", params: { name: "x" }).status
|
||
body = json_body(request.put("/api/live/settings", params: { name: "Car", trail_hours: "2" }, **logged_in_env))
|
||
assert_equal "Car", body["name"]
|
||
assert_equal 2, body["trail_hours"]
|
||
ensure
|
||
Maptool::App::LIVE_STORE.update_settings("name" => "Tracker", "trail_hours" => "1")
|
||
end
|
||
|
||
# --- auth guard ---
|
||
|
||
def test_write_routes_require_login
|
||
assert_equal 401, request.post("/api/library/import").status
|
||
assert_equal 401, request.post("/api/library/folder").status
|
||
assert_equal 401, request.delete("/api/library/node/item:x").status
|
||
assert_equal 401, request.delete("/api/library/folder/x").status
|
||
assert_equal 401, request.post("/api/library/move").status
|
||
assert_equal 401, request.post("/api/plugins/test-plugin/run").status
|
||
assert_equal 401, request.post("/api/offline-tiles/build").status
|
||
assert_equal 401, request.post("/api/terrain-tiles/build").status
|
||
assert_equal 401, request.delete("/api/offline-tiles").status
|
||
assert_equal 401, request.delete("/api/offline-tiles/cache/SK").status
|
||
assert_equal 401, request.delete("/api/terrain-tiles").status
|
||
end
|
||
|
||
# --- Tracks & Points library (lib/maptool/library.rb) ---
|
||
|
||
def test_gpx_import_makes_one_track_node_carrying_its_waypoint
|
||
response = upload("ride.gpx", File.read(fixture_path("sample.gpx")))
|
||
|
||
assert_equal 200, response.status
|
||
body = json_body(response)
|
||
assert_equal 1, body["paths"].size
|
||
assert_match(/\Aitem:/, body["paths"].first)
|
||
node = body["tree"]["children"].first
|
||
assert_equal ["Morning Loop", %w[track waypoint]], node.values_at("name", "kinds")
|
||
|
||
features = json_body(request.get(node_url(node["path"])))["features"]
|
||
assert_equal %w[track waypoint], features.map { |f| f["properties"]["kind"] }
|
||
assert_operator features.first["properties"]["distance_meters"], :>, 0
|
||
assert(features.all? { |f| f["properties"]["id"] })
|
||
end
|
||
|
||
def test_importing_the_same_file_again_adds_nothing
|
||
first = json_body(upload("ride.gpx", File.read(fixture_path("sample.gpx"))))
|
||
second = json_body(upload("ride (1).gpx", File.read(fixture_path("sample.gpx"))))
|
||
|
||
assert_equal first["paths"], second["paths"]
|
||
assert_equal 1, second["tree"]["children"].size
|
||
end
|
||
|
||
def test_geojson_points_land_in_the_folders_points_node
|
||
content = '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"kind":"waypoint","name":"Spot"},"geometry":{"type":"Point","coordinates":[17.1,48.1]}}]}'
|
||
response = upload("spots.geojson", content, folder: "trips")
|
||
|
||
assert_equal 200, response.status
|
||
key = json_body(response)["paths"].first
|
||
assert_match(/\Apoints:/, key)
|
||
trips = json_body(response)["tree"]["children"].find { |c| c["name"] == "trips" }
|
||
assert_equal ["Points (1)"], trips["children"].map { |c| c["name"] }
|
||
assert_equal "Spot", json_body(request.get(node_url(key)))["features"][0]["properties"]["name"]
|
||
end
|
||
|
||
def test_downloads_need_login_and_serve_the_original_or_geojson
|
||
content = File.read(fixture_path("sample.gpx"))
|
||
key = json_body(upload("ride.gpx", content))["paths"].first
|
||
|
||
assert_equal 401, request.get("#{node_url(key)}?download=original").status
|
||
assert_equal 401, request.get("#{node_url(key)}?download=geojson").status
|
||
|
||
original = request.get("#{node_url(key)}?download=original", **logged_in_env)
|
||
assert_equal content, original.body
|
||
assert_includes original.headers["Content-Disposition"], 'filename="ride.gpx"'
|
||
geojson = request.get("#{node_url(key)}?download=geojson&name=Morning+Loop", **logged_in_env)
|
||
assert_includes geojson.headers["Content-Disposition"], 'filename="Morning Loop.geojson"'
|
||
end
|
||
|
||
def test_unparseable_gpx_is_rejected_at_import
|
||
assert_equal 422, upload("bad.gpx", "<gpx><trk unclosed>").status
|
||
assert_empty json_body(request.get("/api/library/tree"))["children"]
|
||
end
|
||
|
||
def test_fit_upload_is_parsed_the_same_as_gpx
|
||
fit_bytes = build_fit_file([[100_000_000, 200_000_000], [100_000_100, 200_000_100]])
|
||
key = json_body(upload("activity.fit", fit_bytes))["paths"].first
|
||
|
||
geojson = json_body(request.get(node_url(key)))
|
||
assert_equal 2, geojson["features"][0]["geometry"]["coordinates"][0].size
|
||
end
|
||
|
||
def test_tcx_upload_and_fit_course_download
|
||
tcx = <<~XML
|
||
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"><Activities><Activity Sport="Biking"><Lap><Track>
|
||
<Trackpoint><Time>2026-05-01T10:00:00Z</Time><Position><LatitudeDegrees>48.1</LatitudeDegrees><LongitudeDegrees>17.1</LongitudeDegrees></Position><AltitudeMeters>140</AltitudeMeters></Trackpoint>
|
||
</Track></Lap><Lap><Track>
|
||
<Trackpoint><Time>2026-05-01T10:01:00Z</Time><Position><LatitudeDegrees>48.11</LatitudeDegrees><LongitudeDegrees>17.1</LongitudeDegrees></Position><AltitudeMeters>150</AltitudeMeters></Trackpoint>
|
||
</Track></Lap></Activity></Activities></TrainingCenterDatabase>
|
||
XML
|
||
key = json_body(upload("ride.tcx", tcx))["paths"].first
|
||
properties = json_body(request.get(node_url(key)))["features"][0]["properties"]
|
||
assert_equal "cycling", properties["activity_type"]
|
||
assert_equal [0, 1], properties["laps"]
|
||
assert_equal "ride", properties["name"] # no name in the file: the file's
|
||
|
||
fit = request.get("#{node_url(key)}?download=fit&name=Ride", **logged_in_env)
|
||
assert_equal 200, fit.status
|
||
assert_includes fit.headers["Content-Disposition"], 'filename="Ride.fit"'
|
||
assert_equal ".FIT", fit.body.byteslice(8, 4)
|
||
end
|
||
|
||
def test_zip_upload_expands_into_its_track_entries_and_skips_the_rest
|
||
zip_bytes = build_zip(
|
||
"one.gpx" => File.read(fixture_path("sample.gpx")),
|
||
"two.fit" => build_fit_file([[100_000_000, 200_000_000], [100_000_100, 200_000_100]]),
|
||
"readme.txt" => "not a track file",
|
||
)
|
||
response = upload("export.zip", zip_bytes, folder: "imported", content_type: "application/zip")
|
||
|
||
assert_equal 200, response.status
|
||
assert_equal 2, json_body(response)["paths"].size
|
||
imported = json_body(response)["tree"]["children"].find { |c| c["name"] == "imported" }
|
||
assert_equal 2, imported["children"].size
|
||
end
|
||
|
||
def test_zip_whose_contents_exceed_the_size_limit_is_rejected_before_saving_anything
|
||
zip_bytes = build_zip("big.gpx" => "x" * 2048)
|
||
original = Maptool::App::MAX_ZIP_UNCOMPRESSED
|
||
Maptool::App.send(:remove_const, :MAX_ZIP_UNCOMPRESSED)
|
||
Maptool::App.const_set(:MAX_ZIP_UNCOMPRESSED, 1024)
|
||
response = upload("bomb.zip", zip_bytes, content_type: "application/zip")
|
||
|
||
assert_equal 413, response.status
|
||
assert_empty json_body(request.get("/api/library/tree"))["children"]
|
||
ensure
|
||
Maptool::App.send(:remove_const, :MAX_ZIP_UNCOMPRESSED)
|
||
Maptool::App.const_set(:MAX_ZIP_UNCOMPRESSED, original)
|
||
end
|
||
|
||
def test_pwa_manifest_is_served_as_a_manifest_and_declares_the_share_target
|
||
response = request.get("/manifest.webmanifest")
|
||
assert_equal 200, response.status
|
||
assert_equal "application/manifest+json", response.content_type
|
||
assert_equal "/share-target", JSON.parse(response.body).dig("share_target", "action")
|
||
end
|
||
|
||
def test_share_target_without_a_service_worker_goes_back_to_the_map
|
||
response = request.post("/share-target")
|
||
assert_equal 303, response.status
|
||
assert_equal "/", URI(response.location).path
|
||
end
|
||
|
||
def test_corrupt_zip_is_rejected
|
||
assert_equal 400, upload("bad.zip", "not a zip", content_type: "application/zip").status
|
||
end
|
||
|
||
def test_folder_create_move_and_delete
|
||
key = json_body(upload("ride.gpx", File.read(fixture_path("sample.gpx"))))["paths"].first
|
||
|
||
assert_equal 200, request.post("/api/library/folder?path=trips", **logged_in_env).status
|
||
|
||
move = request.post("/api/library/move", params: { key: key, to_folder: "trips" }, **logged_in_env)
|
||
assert_equal key, json_body(move)["path"]
|
||
trips = json_body(move)["tree"]["children"].find { |c| c["name"] == "trips" }
|
||
assert_equal ["Morning Loop"], trips["children"].map { |c| c["name"] }
|
||
|
||
delete = request.delete("/api/library/folder/trips", **logged_in_env)
|
||
assert_equal 200, delete.status
|
||
assert_empty json_body(delete)["tree"]["children"]
|
||
assert_equal 404, request.get(node_url(key)).status
|
||
end
|
||
|
||
def test_renaming_a_node_and_a_folder_needs_login
|
||
key = json_body(upload("ride.gpx", File.read(fixture_path("sample.gpx")), folder: "trips"))["paths"].first
|
||
assert_equal 401, request.patch(node_url(key), params: { name: "x" }).status
|
||
|
||
renamed = request.patch(node_url(key), params: { name: "Evening", color: "#123456" }, **logged_in_env)
|
||
assert_equal [["Evening", "#123456"]], json_body(renamed)["tree"]["children"][0]["children"].map { |c| c.values_at("name", "color") }
|
||
assert_equal 400, request.patch(node_url(key), params: { color: "red" }, **logged_in_env).status
|
||
|
||
folder = request.patch("/api/library/folder/trips", params: { name: "2026", to_folder: "Van" }, **logged_in_env)
|
||
assert_equal "Van/2026", json_body(folder)["path"]
|
||
request.post("/api/library/folder?path=Bus", **logged_in_env)
|
||
assert_equal 409, request.patch("/api/library/folder/Van", params: { name: "Bus" }, **logged_in_env).status
|
||
end
|
||
|
||
def test_routing_without_a_valhalla_service_says_so
|
||
assert_equal 503, request.post("/api/route", input: JSON.generate(locations: [[17.1, 48.1], [17.2, 48.2]]), "CONTENT_TYPE" => "application/json").status
|
||
assert_equal 400, request.post("/api/route", input: JSON.generate(locations: "x"), "CONTENT_TYPE" => "application/json").status
|
||
assert_equal 503, request.post("/api/isochrone", input: JSON.generate(center: [17.1, 48.1], minutes: [60]), "CONTENT_TYPE" => "application/json").status
|
||
assert_equal 422, request.post("/api/isochrone", input: JSON.generate(center: [17.1, 48.1], minutes: [999]), "CONTENT_TYPE" => "application/json").status
|
||
end
|
||
|
||
def test_vehicles_are_readable_by_anyone_but_saved_only_when_logged_in
|
||
assert_equal "Car", json_body(request.get("/api/vehicles")).first["name"]
|
||
vehicles = JSON.generate([{ id: "car", name: "Car" }, { id: "van", name: "Van", height: 3.3 }])
|
||
assert_equal 401, request.put("/api/vehicles", input: vehicles).status
|
||
assert_equal 3.3, json_body(request.put("/api/vehicles", input: vehicles, **logged_in_env)).last["height"]
|
||
assert_equal 400, request.put("/api/vehicles", input: "[]", **logged_in_env).status
|
||
ensure
|
||
FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "vehicles.json"))
|
||
end
|
||
|
||
def test_changes_and_exports_need_login
|
||
upload("ride.gpx", File.read(fixture_path("sample.gpx")), folder: "trips")
|
||
assert_equal 401, request.get("/api/library/changes").status
|
||
assert_equal 401, request.get("/api/library/export?folder=trips&flavor=locus").status
|
||
|
||
changes = json_body(request.get("/api/library/changes?since=0", **logged_in_env))
|
||
assert_equal ["Morning Loop", "Start"], changes["items"].map { |i| i["name"] }.sort
|
||
|
||
locus = request.get("/api/library/export?folder=trips&flavor=locus", **logged_in_env)
|
||
assert_includes locus.body, "<name>Morning Loop</name>"
|
||
osmand = request.get("/api/library/export?folder=trips&flavor=osmand", **logged_in_env)
|
||
entries = nil
|
||
Zip::File.open_buffer(StringIO.new(osmand.body)) { |zip| entries = zip.map(&:name) }
|
||
assert_equal ["tracks/trips/Morning Loop.gpx"], entries
|
||
assert_equal 400, request.get("/api/library/export?folder=trips&flavor=x", **logged_in_env).status
|
||
end
|
||
|
||
def test_invalid_folder_path_is_rejected
|
||
assert_equal 400, request.post("/api/library/folder?path=..%2F..%2Fescape", **logged_in_env).status
|
||
end
|
||
|
||
# --- Notes (hand-drawn points/areas, notes.js) ---
|
||
|
||
def test_notes_accepts_a_polygon_feature
|
||
polygon = JSON.generate(
|
||
"type" => "Feature",
|
||
"properties" => { "name" => "Turning area", "category" => "Note" },
|
||
"geometry" => { "type" => "Polygon", "coordinates" => [[[17.1, 48.1], [17.2, 48.1], [17.2, 48.2], [17.1, 48.1]]] },
|
||
)
|
||
response = request.post("/api/library/notes", params: { feature: polygon, folder: "Areas" }, **logged_in_env)
|
||
|
||
assert_equal 200, response.status
|
||
geometry = json_body(request.get(node_url(json_body(response)["path"])))["features"][0]["geometry"]
|
||
assert_equal "Polygon", geometry["type"]
|
||
end
|
||
|
||
def test_notes_requires_login
|
||
assert_equal 401, request.post("/api/library/notes", params: { feature: sample_note_feature, folder: "Notes" }).status
|
||
end
|
||
|
||
def test_notes_go_into_one_points_node_per_folder
|
||
first = json_body(request.post("/api/library/notes", params: { feature: sample_note_feature("Turning spot"), folder: "My Notes" }, **logged_in_env))
|
||
second = json_body(request.post("/api/library/notes", params: { feature: sample_note_feature("Narrow gate"), folder: "My Notes" }, **logged_in_env))
|
||
|
||
assert_equal first["path"], second["path"]
|
||
features = json_body(request.get(node_url(first["path"])))["features"]
|
||
assert_equal ["Narrow gate", "Turning spot"], features.map { |f| f["properties"]["name"] }.sort
|
||
end
|
||
|
||
def test_notes_rejects_malformed_or_geometryless_features
|
||
assert_equal 400, request.post("/api/library/notes", params: { feature: "not json" }, **logged_in_env).status
|
||
assert_equal 400, request.post("/api/library/notes", params: { feature: '{"type":"Feature","properties":{}}' }, **logged_in_env).status
|
||
end
|
||
|
||
def test_notes_update_and_delete_need_login
|
||
assert_equal 401, request.put("/api/library/notes", params: { feature: sample_note_feature, path: "points:root", id: "a" }).status
|
||
assert_equal 401, request.delete("/api/library/notes", params: { path: "points:root", id: "a" }).status
|
||
end
|
||
|
||
def test_notes_update_edits_the_matching_note
|
||
created = json_body(request.post("/api/library/notes", params: { feature: sample_note_feature("Original", id: "a") }, **logged_in_env))
|
||
|
||
response = request.put("/api/library/notes", params: { feature: sample_note_feature("Edited", id: "a"), path: created["path"], id: "a" }, **logged_in_env)
|
||
assert_equal 200, response.status
|
||
features = json_body(request.get(node_url(created["path"])))["features"]
|
||
assert_equal [%w[Edited a]], features.map { |f| f["properties"].values_at("name", "id") }
|
||
|
||
missing = request.put("/api/library/notes", params: { feature: sample_note_feature, path: created["path"], id: "nope" }, **logged_in_env)
|
||
assert_equal 404, missing.status
|
||
end
|
||
|
||
def test_notes_delete_removes_the_matching_note
|
||
created = json_body(request.post("/api/library/notes", params: { feature: sample_note_feature("Turning spot", id: "a") }, **logged_in_env))
|
||
request.post("/api/library/notes", params: { feature: sample_note_feature("Narrow gate", id: "b") }, **logged_in_env)
|
||
|
||
assert_equal 200, request.delete("/api/library/notes", params: { path: created["path"], id: "a" }, **logged_in_env).status
|
||
features = json_body(request.get(node_url(created["path"])))["features"]
|
||
assert_equal ["Narrow gate"], features.map { |f| f["properties"]["name"] }
|
||
assert_equal 404, request.delete("/api/library/notes", params: { path: created["path"], id: "a" }, **logged_in_env).status
|
||
end
|
||
|
||
# --- Import plugins (lib/maptool/plugins.rb) ---
|
||
|
||
def test_plugins_lists_whatever_is_on_disk
|
||
response = request.get("/api/plugins")
|
||
assert_equal 200, response.status
|
||
assert_equal [{ "name" => "test-plugin", "label" => "Test plugin", "route" => false, "settings" => [], "set" => [] }], json_body(response)
|
||
end
|
||
|
||
def test_plugins_run_imports_the_output_into_a_folder_of_its_own
|
||
response = request.post(
|
||
"/api/plugins/test-plugin/run",
|
||
params: { south: "48.0", west: "17.0", north: "48.1", east: "17.1" },
|
||
**logged_in_env,
|
||
)
|
||
assert_equal 200, response.status
|
||
body = json_body(response)
|
||
assert_match(/\Atest-plugin_48\.05_17\.05_\d{6}_\d{4}\z/, body["tree"]["children"].first["name"])
|
||
|
||
saved = json_body(request.get(node_url(body["path"])))
|
||
assert_equal "Test POI", saved["features"][0]["properties"]["name"]
|
||
end
|
||
|
||
# Along the trip's route: what lies further off than the corridor dropped.
|
||
def test_plugins_run_along_the_route_keeps_the_corridor
|
||
store = Maptool::App::TRIP_STORE
|
||
saved = store.instance_variable_get(:@trip)
|
||
run = lambda do |line|
|
||
store.instance_variable_set(:@trip, saved.merge(route: { geometry: { coordinates: line } }))
|
||
json_body(request.post("/api/plugins/test-plugin/run", params: { route: "1", corridor_km: "2" }, **logged_in_env))["count"]
|
||
end
|
||
assert_equal 1, run.([[17.0, 47.99], [17.1, 47.99]]) # the POI ~1.1 km off
|
||
assert_equal 0, run.([[17.0, 47.95], [17.1, 47.95]]) # ~5.6 km off
|
||
store.instance_variable_set(:@trip, saved.merge(route: nil))
|
||
assert_equal 422, request.post("/api/plugins/test-plugin/run", params: { route: "1", corridor_km: "2" }, **logged_in_env).status
|
||
ensure
|
||
store.instance_variable_set(:@trip, saved)
|
||
end
|
||
|
||
def test_plugins_run_requires_a_bbox
|
||
response = request.post("/api/plugins/test-plugin/run", **logged_in_env)
|
||
assert_equal 400, response.status
|
||
end
|
||
|
||
def test_plugins_run_unknown_plugin_is_502
|
||
response = request.post(
|
||
"/api/plugins/nope/run",
|
||
params: { south: "48.0", west: "17.0", north: "48.1", east: "17.1" },
|
||
**logged_in_env,
|
||
)
|
||
assert_equal 502, response.status
|
||
end
|
||
|
||
# --- offline regions ---
|
||
|
||
def test_offline_regions_lists_available_and_selected
|
||
body = json_body(request.get("/api/offline-regions"))
|
||
assert_operator body["available"].size, :>, 0
|
||
assert_includes body["available"], { "code" => "SK", "name" => "Slovakia", "continent" => "europe", "parent" => nil }
|
||
assert_includes body["continents"], { "id" => "europe", "name" => "Europe" }
|
||
assert_equal [], body["selected"]
|
||
end
|
||
|
||
def test_offline_regions_post_requires_login
|
||
assert_equal 401, request.post("/api/offline-regions").status
|
||
end
|
||
|
||
def test_offline_regions_post_saves_the_selection
|
||
response = request.post("/api/offline-regions", params: { "codes" => %w[SK AT] }, **logged_in_env)
|
||
assert_equal 200, response.status
|
||
assert_equal %w[SK AT], json_body(request.get("/api/offline-regions"))["selected"]
|
||
end
|
||
|
||
def test_offline_regions_post_rejects_an_unknown_code
|
||
response = request.post("/api/offline-regions", params: { "codes" => ["XX"] }, **logged_in_env)
|
||
assert_equal 400, response.status
|
||
end
|
||
|
||
# --- pmtiles regeneration ---
|
||
#
|
||
# The full build (network + go-pmtiles) is covered in isolation, with
|
||
# fakes injected, by test_pmtiles_builder.rb — same "keep this offline"
|
||
# reasoning as the rest of this file. What's route-specific and worth
|
||
# covering here is the empty-selection validation and the
|
||
# 409-while-running guard, neither of which needs a real build to
|
||
# actually run.
|
||
|
||
def test_offline_tiles_build_status_defaults_to_idle
|
||
assert_equal({ "state" => "idle" }, json_body(request.get("/api/offline-tiles/build-status")))
|
||
assert_equal({ "state" => "idle" }, json_body(request.get("/api/terrain-tiles/build-status")))
|
||
end
|
||
|
||
def test_check_update_is_null_before_any_build
|
||
assert_nil json_body(request.get("/api/offline-tiles/check-update"))["update_available"]
|
||
assert_nil json_body(request.get("/api/terrain-tiles/check-update"))["update_available"]
|
||
end
|
||
|
||
def test_offline_tiles_build_is_409_with_no_selection
|
||
response = request.post("/api/offline-tiles/build", **logged_in_env)
|
||
assert_equal 409, response.status
|
||
end
|
||
|
||
def test_terrain_tiles_build_is_409_with_no_selection
|
||
response = request.post("/api/terrain-tiles/build", **logged_in_env)
|
||
assert_equal 409, response.status
|
||
end
|
||
|
||
# download_extract blocks on a Queue, called directly (not through the
|
||
# route, which has no way to inject a fake) so the build is
|
||
# deterministically still "running" when the route call below happens.
|
||
def test_offline_tiles_build_is_409_when_one_is_already_running
|
||
Maptool::PmtilesBuilder.set_selected_regions(Maptool::App::DATA_DIR, ["SK"])
|
||
gate = Queue.new
|
||
thread = Maptool::PmtilesBuilder.build_offline(data_dir: Maptool::App::DATA_DIR, download_extract: ->(_url, _dest) { gate.pop })
|
||
|
||
response = request.post("/api/offline-tiles/build", **logged_in_env)
|
||
assert_equal 409, response.status
|
||
ensure
|
||
gate.push("unused")
|
||
thread&.join
|
||
end
|
||
|
||
def test_offline_tiles_delete_is_ok_when_nothing_was_built
|
||
assert_equal 200, request.delete("/api/offline-tiles", **logged_in_env).status
|
||
end
|
||
|
||
def test_offline_tiles_delete_removes_the_file_and_cache
|
||
path = File.join(Maptool::App::DATA_DIR, "offline.pmtiles")
|
||
cache_dir = File.join(Maptool::App::DATA_DIR, "geofabrik_cache")
|
||
File.write(path, "fake")
|
||
FileUtils.mkdir_p(cache_dir)
|
||
File.write(File.join(cache_dir, "SK.osm.pbf"), "fake")
|
||
|
||
response = request.delete("/api/offline-tiles", **logged_in_env)
|
||
|
||
assert_equal 200, response.status
|
||
refute_path_exists path
|
||
refute_path_exists cache_dir
|
||
end
|
||
|
||
def test_offline_tiles_cache_lists_and_deletes_one_country
|
||
cache_dir = File.join(Maptool::App::DATA_DIR, "geofabrik_cache")
|
||
FileUtils.mkdir_p(cache_dir)
|
||
File.write(File.join(cache_dir, "SK.osm.pbf"), "fake")
|
||
|
||
extracts = json_body(request.get("/api/offline-tiles/cache"))["extracts"]
|
||
assert_equal ["SK"], extracts.map { |e| e["code"] }
|
||
|
||
response = request.delete("/api/offline-tiles/cache/SK", **logged_in_env)
|
||
assert_equal 200, response.status
|
||
refute_path_exists File.join(cache_dir, "SK.osm.pbf")
|
||
ensure
|
||
FileUtils.remove_entry(cache_dir) if cache_dir && Dir.exist?(cache_dir)
|
||
end
|
||
|
||
def test_offline_tiles_delete_is_409_when_a_build_is_running
|
||
Maptool::PmtilesBuilder.set_selected_regions(Maptool::App::DATA_DIR, ["SK"])
|
||
gate = Queue.new
|
||
thread = Maptool::PmtilesBuilder.build_offline(data_dir: Maptool::App::DATA_DIR, download_extract: ->(_url, _dest) { gate.pop })
|
||
|
||
assert_equal 409, request.delete("/api/offline-tiles", **logged_in_env).status
|
||
ensure
|
||
gate.push("unused")
|
||
thread&.join
|
||
end
|
||
|
||
# --- LiveTrack webhook ---
|
||
|
||
def test_livetrack_webhook_requires_the_configured_secret
|
||
response = request.post("/api/livetrack/session", params: { secret: "wrong", session_id: "abc" })
|
||
assert_equal 403, response.status
|
||
end
|
||
|
||
def test_livetrack_webhook_stores_session_id_and_token
|
||
response = request.post(
|
||
"/api/livetrack/session",
|
||
params: { secret: ENV.fetch("LIVETRACK_WEBHOOK_SECRET"), session_id: "abc123", session_token: "tok" },
|
||
)
|
||
assert_equal 200, response.status
|
||
|
||
sessions = json_body(request.get("/api/livetrack/sessions"))["sessions"]
|
||
assert_equal "abc123", sessions.first["id"]
|
||
assert_equal "tok", sessions.first["token"]
|
||
end
|
||
|
||
def test_livetrack_track_unknown_session_is_404
|
||
response = request.get("/api/livetrack/sessions/does-not-exist/track")
|
||
assert_equal 404, response.status
|
||
end
|
||
|
||
# LiveTrackClient's actual page-fetching/parsing has its own tests
|
||
# (test_livetrack_client.rb, no network) and was checked against real
|
||
# Garmin sessions by hand during development — this only covers the
|
||
# route's own guard clause, not the success path, since exercising that
|
||
# here would mean a real network call in every test run.
|
||
def test_livetrack_track_session_without_token_is_404
|
||
request.post("/api/livetrack/session", params: { secret: ENV.fetch("LIVETRACK_WEBHOOK_SECRET"), session_id: "no-token" })
|
||
|
||
response = request.get("/api/livetrack/sessions/no-token/track")
|
||
assert_equal 404, response.status
|
||
end
|
||
|
||
def test_a_gnss_fix_without_a_course_gets_one_from_the_fixes_before
|
||
latest = Maptool::App::GNSS_LATEST
|
||
latest.clear
|
||
step = 10.0 / 111_320 # 10 m north each fix
|
||
Maptool::App.gnss_update({ lat: 48.0, lon: 17.0, speed: 10.0 })
|
||
assert_nil latest[:track]
|
||
Maptool::App.gnss_update({ lat: 48.0 + step, lon: 17.0 })
|
||
assert_in_delta 0.0, latest[:track], 0.1
|
||
Maptool::App.gnss_update({ lat: 48.0 + step, lon: 17.0 + step / Math.cos(48 * Math::PI / 180) })
|
||
assert_in_delta 90.0, latest[:track], 0.5
|
||
Maptool::App.gnss_update({ speed: 0.0 })
|
||
Maptool::App.gnss_update({ lat: 48.0, lon: 17.0 }) # standing still: the course stays
|
||
assert_in_delta 90.0, latest[:track], 0.5
|
||
ensure
|
||
latest.clear
|
||
end
|
||
|
||
# The recording's days and its export: a GPX with a track per day, or a .zip.
|
||
def test_trip_log_days_and_export
|
||
log = Maptool::App::TRIP_LOG
|
||
log.stop
|
||
assert_equal 200, request.post("/api/trip/log", input: JSON.generate(name: "Export test"), "CONTENT_TYPE" => "application/json", **logged_in_env).status
|
||
t0 = Time.new(2026, 12, 1, 10).to_f
|
||
10.times { |i| log.record(17.0, 48.0 + i * 0.001, 100.0, t0 + i * 60) }
|
||
10.times { |i| log.record(17.0, 48.1 + i * 0.001, 100.0, t0 + 10 * 3600 + i * 60) } # stood 10 h
|
||
log.record(17.0, 48.2, 100.0, t0 + 11 * 3600)
|
||
|
||
days = json_body(request.get("/api/trip/log/days?track=1", **logged_in_env))
|
||
assert_equal [true, 2, "auto"], [days["active"], days["days"].size, days["days"][0]["cut"]["kind"]]
|
||
assert_equal 21, days["track"].size
|
||
gpx = request.get("/api/trip/log/export?pauses=1", **logged_in_env)
|
||
assert_equal 2, gpx.body.scan("<trk>").size
|
||
assert_includes gpx.body, "Stood "
|
||
one = request.get("/api/trip/log/export?days=2", **logged_in_env).body
|
||
assert_equal 1, one.scan("<trk>").size
|
||
zip = request.get("/api/trip/log/export?per_day=1", **logged_in_env)
|
||
assert_equal "application/zip", zip.content_type
|
||
assert_equal 200, request.post("/api/trip/log/days", input: JSON.generate(join: days["track"][10][2]), "CONTENT_TYPE" => "application/json", **logged_in_env).status
|
||
assert_equal 1, json_body(request.get("/api/trip/log/days", **logged_in_env))["days"].size
|
||
ensure
|
||
log.stop
|
||
end
|
||
|
||
# A tunnel: no fix for a while, the position carried along the trip's
|
||
# route — at the average speed it was entered at, by the CAN speed when there is one.
|
||
def test_no_fix_on_the_route_is_dead_reckoned_along_it
|
||
latest = Maptool::App::GNSS_LATEST
|
||
latest.clear
|
||
store = Maptool::App::TRIP_STORE
|
||
saved = store.instance_variable_get(:@trip)
|
||
north = 1000.0 / 111_320 # 1 km north
|
||
store.instance_variable_set(:@trip, saved.merge(points: [], route: { geometry: { coordinates: [[17.0, 48.0], [17.0, 48.0 + 5 * north]] } }))
|
||
Maptool::App.gnss_update({ lat: 48.0, lon: 17.0, speed: 20.0, mode: 3 }, at: 100.0)
|
||
Maptool::App.gnss_update({ lat: 48.0, lon: 17.0, speed: 20.0 }, at: 101.0)
|
||
|
||
assert_nil Maptool::App.gnss_position(now: 102.0)[:estimated] # not yet: a fix may just be late
|
||
position = Maptool::App.gnss_position(now: 111.0) # 10 s × 20 m/s
|
||
assert position[:estimated]
|
||
assert_in_delta 48.0 + 0.2 * north, position[:lat], 1e-6
|
||
assert_in_delta 0.0, position[:track], 0.5
|
||
|
||
Maptool::App.gnss_update({ lat: 48.0, lon: 17.0, mode: 1 }, at: 105.0) # the receiver repeating its last fix
|
||
assert Maptool::App.gnss_position(now: 111.0)[:estimated]
|
||
|
||
Maptool::App.vehicle_speed_update(10.0, at: 102.0) # the car's own speed: 10 m/s
|
||
Maptool::App.vehicle_speed_update(10.0, at: 103.0)
|
||
position = Maptool::App.gnss_position(now: 104.0)
|
||
assert_in_delta 48.0 + 0.02 * north, position[:lat], 1e-6
|
||
assert_equal 10.0, position[:speed]
|
||
ensure
|
||
latest.clear
|
||
store.instance_variable_set(:@trip, saved)
|
||
end
|
||
|
||
private
|
||
|
||
def upload(filename, content, folder: "", content_type: "application/octet-stream")
|
||
post_file("/api/library/import?#{URI.encode_www_form(folder: folder)}", filename: filename, content: content,
|
||
content_type: content_type, env: logged_in_env)
|
||
end
|
||
|
||
def node_url(key)
|
||
"/api/library/node/#{Rack::Utils.escape_path(key)}"
|
||
end
|
||
|
||
def sample_note_feature(name = "Turning spot", id: nil)
|
||
JSON.generate(
|
||
"type" => "Feature",
|
||
"properties" => { "name" => name, "category" => "Note", "id" => id },
|
||
"geometry" => { "type" => "Point", "coordinates" => [17.1, 48.1] },
|
||
)
|
||
end
|
||
|
||
def le32(n)
|
||
[n].pack("l<")
|
||
end
|
||
|
||
# Mirrors FitTest#build_fit — a minimal single-definition FIT file, just
|
||
# enough to exercise the upload -> store -> parse path end to end.
|
||
def build_fit_file(records)
|
||
definition = [0, 0].pack("CC") + [20].pack("S<") + [2].pack("C") +
|
||
[0, 4, 0x85].pack("C3") + [1, 4, 0x85].pack("C3")
|
||
definition_header = [0b01000000].pack("C")
|
||
data = records.map { |lat, lon| [0b00000000].pack("C") + le32(lat) + le32(lon) }.join
|
||
body = definition_header + definition + data
|
||
header = [12, 16, 0, 0].pack("C2S<") + le32(body.bytesize) + ".FIT"
|
||
header + body + "\x00\x00"
|
||
end
|
||
|
||
def build_zip(entries)
|
||
require "zip"
|
||
Tempfile.create(["test", ".zip"]) do |file|
|
||
file.close
|
||
Zip::File.open(file.path, create: true) do |zip|
|
||
entries.each { |name, content| zip.get_output_stream(name) { |f| f.write(content) } }
|
||
end
|
||
File.binread(file.path)
|
||
end
|
||
end
|
||
end
|