Files

84 lines
3.1 KiB
Ruby

require_relative "test_helper"
require "maptool/library"
require "stringio"
# Two servers' libraries (home, car) exchanging Library#sync_changes /
# #apply_sync the way Maptool::Sync does over HTTP.
class SyncTest < Minitest::Test
def setup
@dir = Dir.mktmpdir
@home = library("home")
@car = library("car")
end
def teardown
FileUtils.remove_entry(@dir)
end
def test_changes_flow_both_ways_with_source_files_and_stop_echoing
@home.import(folder: "Rides", filename: "ride.gpx", io: File.open(fixture_path("sample.gpx")))
pull(@car, from: @home)
assert_equal ["Rides"], @car.tree["children"].map { |c| c["name"] }
track = @car.tree["children"][0]["children"].find { |c| c["path"].start_with?("item:") }
assert File.exist?(@car.original(track["path"])), "the upload's source file came along"
@car.create_folder("Car notes")
pull(@home, from: @car)
assert_equal ["Car notes", "Rides"], @home.tree["children"].map { |c| c["name"] }.sort
# Each side's echo of what it just took ties and changes nothing more.
assert_equal 0, pull(@car, from: @home)
assert_equal 0, pull(@home, from: @car)
end
def test_the_later_edit_wins_and_a_delete_carries_over
@home.create_folder("Trip")
pull(@car, from: @home)
sleep 1.1 # updated_at has second resolution
@car.rename_folder("Trip", "Trip 2026")
pull(@home, from: @car)
assert_equal ["Trip 2026"], @home.tree["children"].map { |c| c["name"] }
stale = @home.sync_changes(0)
stale["folders"].each { |f| f["updated_at"] = "2000-01-01T00:00:00Z"; f["name"] = "Old" }
@car.apply_sync(stale)
assert_equal ["Trip 2026"], @car.tree["children"].map { |c| c["name"] }, "an older version doesn't overwrite"
end
def test_pages_until_caught_up
3.times { |i| @home.create_folder("F#{i}") }
since = 0
pages = 0
loop do
changes = @home.sync_changes(since, limit: 2)
@car.apply_sync(changes)
pages += 1
since = changes["next"]
break if since >= changes["rev"]
end
assert_equal %w[F0 F1 F2], @car.tree["children"].map { |c| c["name"] }
assert_operator pages, :>, 1
end
def test_a_source_path_from_the_other_server_stays_inside_sources
row = { "id" => "x", "type" => "track", "source_path" => "../../etc/passwd", "updated_at" => "2030-01-01T00:00:00Z", "properties" => "{}", "created_at" => "2030-01-01T00:00:00Z" }
assert_raises(Maptool::Library::InvalidValue) { @car.apply_sync("items" => [row]) }
end
private
def library(name)
Maptool::Library.new(File.join(@dir, name, "library.sqlite"), gpx_store: Maptool::GpxStore.new(File.join(@dir, name, "gpx")),
sources_dir: File.join(@dir, name, "sources"))
end
# What Sync#pull does, without HTTP (since 0 is fine: idempotent).
# Returns how many rows `target` took.
def pull(target, from:)
before = target.sync_changes(0)["rev"]
missing = target.apply_sync(from.sync_changes(0))
missing.each { |item| target.store_source(item, File.binread(from.item_source(item["id"]))) }
target.sync_changes(before).values_at("folders", "items").sum(&:size)
end
end