// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * Round-trip tests for the browser flat-binary postcode resolver: serialize entries, load the bytes. * * Assert exact-match, multi-country runs, coordinate-less membership, grouping and quantization fidelity. */ import { describe, expect, it } from "vitest" import { PostcodeBinaryLookup, serializePostcodeBinary, type PostcodeBinaryEntry } from "#binary-resolver" const ENTRIES: PostcodeBinaryEntry[] = [ { postcode: "94105", country: "US", lat: 37.789, lon: -122.396 }, // 75001 is the 1st arrondissement of Paris and Addison, Texas. { postcode: "75001", country: "FR", lat: 48.859, lon: 2.342 }, { postcode: "75001", country: "US", lat: 32.96, lon: -96.839 }, { postcode: "1012LM", country: "NL", lat: 52.375, lon: 4.9 }, { postcode: "80144", country: "IT", lat: 0, lon: 0 }, ] function resolver(): PostcodeBinaryLookup { return new PostcodeBinaryLookup(serializePostcodeBinary(ENTRIES)) } describe("PostcodeBinaryLookup", () => { it("rejects a buffer with a bad magic", () => { expect(() => new PostcodeBinaryLookup(new Uint8Array(16))).toThrow(/bad magic/) }) it("exact-matches a single-country postcode and round-trips the centroid within quantization", () => { const [hit, ...rest] = resolver().lookup("94105") expect(rest).toHaveLength(0) expect(hit!.country).toBe("US") expect(hit!.lat).toBeCloseTo(37.789, 2) expect(hit!.lon).toBeCloseTo(-122.396, 2) }) it("returns every country for a postcode shared across borders", () => { const hits = resolver().lookup("75001") expect(hits.map((h) => h.country).toSorted()).toEqual(["FR", "US"]) }) it("returns coordinate-less rows so membership survives without a centroid", () => { expect(resolver().lookup("80144")).toEqual([{ country: "IT", lat: 0, lon: 0 }]) }) it("handles keys of different lengths (US 5-digit vs NL 6-char)", () => { expect( resolver() .lookup("1012LM") .map((h) => h.country) ).toEqual(["NL"]) expect( resolver() .lookup("94105") .map((h) => h.country) ).toEqual(["US"]) }) it("returns [] for an unknown postcode and for an over-long query", () => { expect(resolver().lookup("00000")).toEqual([]) expect(resolver().lookup("THISISWAYTOOLONG")).toEqual([]) }) it("groups every place under its postcode, in key order", () => { const groups = [...resolver().groups()] expect(groups.map((g) => g.postcode)).toEqual(["1012LM", "75001", "80144", "94105"]) expect(groups.find((g) => g.postcode === "75001")!.places.map((p) => p.country)).toEqual(["FR", "US"]) expect(groups.find((g) => g.postcode === "80144")!.places).toEqual([{ country: "IT", lat: 0, lon: 0 }]) }) })