require_relative "test_helper" require "tmpdir" require "maptool/library" require "maptool/gpx_store" require "maptool/trip_log" class TripLogTest < Minitest::Test def library(dir) Maptool::Library.new(File.join(dir, "library.sqlite"), gpx_store: Maptool::GpxStore.new(File.join(dir, "gpx")), sources_dir: File.join(dir, "sources")) end def names(library) library.nodes.flat_map { |label, _key, _stamp, read| [label, *JSON.parse(read.call)["features"].map { |f| f.dig("properties", "name") }] }.compact.join(" ") end # Start makes the folder with the plan and its named stops; fixes 10 m # apart become the car's track; stop builds it into the library. def test_a_trip_records_into_its_folder Dir.mktmpdir do |dir| lib = library(dir) log = Maptool::TripLog.new(File.join(dir, "trip_log"), library: lib) plan = { geometry: { type: "LineString", coordinates: [[17.0, 48.0], [17.1, 48.0]] }, properties: { distance_km: 7.4, time_s: 600 } } folder = log.start("Tatry", plan: plan, stops: [{ lngLat: [17.0, 48.0], name: "My position" }, { lngLat: [17.1, 48.0], name: "Camp" }], now: Time.utc(2026, 12, 1, 8)) assert_equal "Trips/2026-12-01 Tatry", folder assert_raises(ArgumentError) { log.start("again") } log.record(17.0, 48.0, 150, 1000) log.record(17.00001, 48.0, 150, 1001) # < 10 m: skipped log.record(17.001, 48.0, 151, 1002) log.record(17.002, 48.0, 152, 1100) assert_equal 3, log.status[:points] assert_equal [[17.001, 48.0], [17.002, 48.0]], log.status(since: 1)[:coordinates] assert_equal folder, log.stop refute log.active? all = names(lib) %w[Camp Plan].each { |name| assert_includes all, name } assert_includes all, "Car 2026-12-01" refute_includes all, "My position" assert(lib.nodes.all? { |label, *| label.include?("2026-12-01 Tatry") }) # all in the trip's folder end end # A crash: the server restarts with the journal as it was — a torn last # line included — and the trip goes on from there, into the same track. def test_a_restart_picks_the_trip_up_from_its_journal Dir.mktmpdir do |dir| lib = library(dir) log_dir = File.join(dir, "trip_log") log = Maptool::TripLog.new(log_dir, library: lib) log.start("Crash", now: Time.utc(2026, 12, 1, 8)) log.record(17.0, 48.0, nil, 1000) log.record(17.001, 48.0, nil, 1010) log.send(:sync) # as the FSYNC_EVERY_S timer does; what's after it is lost in a crash journal = Dir[File.join(log_dir, "*.ndjson")].first File.open(journal, "a") { |f| f.write("[17.00") } # the power cut, mid-line again = Maptool::TripLog.new(log_dir, library: lib) assert again.active? assert_equal [2, "Trips/2026-12-01 Crash"], again.status.values_at(:points, :folder) again.record(17.002, 48.0, nil, 1020) again.stop assert_equal 3, File.readlines(journal).count { |l| l.start_with?("[") && (JSON.parse(l) rescue nil) } # the torn line alone lost assert_equal 1, lib.nodes.count { |label, *| label.include?("Car 2026-12-01") } # one track, not two refute Maptool::TripLog.new(log_dir, library: lib).active? # ended stays ended end end end