Compare commits

...
Author SHA1 Message Date
Sapphire 5ef7335574 fix(tests): type-correct against SDK contracts; drop fast-check dep
The new test files were written against field names that don't exist on
the SDK types — CI surfaced 11 TS errors. Two fixes:

filterEngine.test.ts:
  - GeoEntity has `latitude`/`longitude` at the top level (not nested
    `position: {lat,lon,alt}`), `label` (not `name`), and a required
    `timestamp: Date`. Rewrote the fixtures via a small `entity()`
    helper that fills in the required fields and lets each test
    override only what it cares about.
  - FilterDefinition's range bounds live in a nested `range: {min, max,
    step}` config, not as top-level `min`/`max` properties.
  - Replaced the two `fast-check`-based property tests with traditional
    vitest cases that verify the same invariants (no-op when no
    filters, subset/equal when text-filtering). `fast-check` lands as a
    workspace dep in PR #116; until that merges, importing it breaks
    this PR's type check.

DeclarativePlugin.test.ts:
  - 4 `dataSource: {...}` fixtures were missing the required
    `method`, `pollInterval`, and `format` fields. Added them inline.

After the fix: `pnpm exec tsc --noEmit` clean; full vitest suite 148/148
passing (was 137 before this PR, the 4 new test files contribute 11
real tests, no regressions).
2026-05-13 11:08:25 -04:00
Antigravity AI 628394f572 test(core): optimize test coverage across WorldWideView to >80% 2026-05-14 00:56:44 +12:00
7 changed files with 513 additions and 1 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "worldwideview", "name": "worldwideview",
"version": "2.9.2", "version": "2.9.10",
"private": true, "private": true,
"type": "module", "type": "module",
"packageManager": "[email protected]", "packageManager": "[email protected]",
+146
View File
@@ -0,0 +1,146 @@
import { describe, it, expect } from "vitest";
import { applyFilters } from "./filterEngine";
import type { GeoEntity, FilterDefinition, FilterValue } from "@/core/plugins/PluginTypes";
/**
* Helper to keep the fixture set small and on-spec. `GeoEntity` requires
* `latitude`, `longitude`, `timestamp`, and `properties`; everything
* else (label, altitude, heading, speed) is optional. We omit the
* optional fields except where a specific test exercises them.
*/
function entity(overrides: Partial<GeoEntity> & Pick<GeoEntity, "id" | "pluginId" | "properties">): GeoEntity {
return {
latitude: 0,
longitude: 0,
timestamp: new Date(0),
...overrides,
};
}
describe("applyFilters", () => {
it("returns the original array unchanged when no active filters are provided", () => {
const entities: GeoEntity[] = [
entity({ id: "1", pluginId: "test", properties: {} }),
entity({ id: "2", pluginId: "test", properties: {} }),
];
expect(applyFilters(entities, [], {})).toEqual(entities);
});
it("returns a subset (or equal) of the input when filtering by text", () => {
const entities: GeoEntity[] = [
entity({ id: "1", pluginId: "test", label: "alpha", properties: { name: "alpha" } }),
entity({ id: "2", pluginId: "test", label: "beta", properties: { name: "beta" } }),
entity({ id: "3", pluginId: "test", label: "gamma", properties: { name: "gamma" } }),
];
const definitions: FilterDefinition[] = [
{ id: "name", label: "Name", type: "text", propertyKey: "name" },
];
const activeFilters: Record<string, FilterValue> = {
name: { type: "text", value: "a" },
};
const result = applyFilters(entities, definitions, activeFilters);
expect(result.length).toBeLessThanOrEqual(entities.length);
for (const item of result) expect(entities).toContainEqual(item);
});
it("handles each filter type and the missing-definition / unknown-type fallbacks", () => {
const entities: GeoEntity[] = [
entity({
id: "1",
pluginId: "test",
label: "test1",
properties: { category: "A", speed: 50, active: true, invalidNum: "NaN" },
}),
entity({
id: "2",
pluginId: "test",
label: "test2",
properties: { category: "B", speed: 100, active: false, noProp: undefined },
}),
];
// 1. Missing definition — filter is silently ignored
expect(
applyFilters(entities, [], { missing: { type: "boolean", value: true } }),
).toEqual(entities);
// 2. Select filter
const selectDef: FilterDefinition = {
id: "cat",
label: "Category",
type: "select",
propertyKey: "category",
};
expect(applyFilters(entities, [selectDef], { cat: { type: "select", values: ["A"] } })).toEqual([
entities[0],
]);
expect(applyFilters(entities, [selectDef], { cat: { type: "select", values: [] } })).toEqual(
entities,
); // empty select == no filter
expect(applyFilters(entities, [selectDef], { cat: { type: "select", values: ["C"] } })).toEqual(
[],
);
// 3. Range filter — note: `range` is a NESTED config on FilterDefinition
const rangeDef: FilterDefinition = {
id: "spd",
label: "Speed",
type: "range",
propertyKey: "speed",
range: { min: 0, max: 200, step: 1 },
};
expect(applyFilters(entities, [rangeDef], { spd: { type: "range", min: 60, max: 150 } })).toEqual(
[entities[1]],
);
const invalidRangeDef: FilterDefinition = {
id: "inv",
label: "Invalid",
type: "range",
propertyKey: "invalidNum",
range: { min: 0, max: 200, step: 1 },
};
// entities[0] has invalidNum: "NaN" → fails; entities[1] has it undefined → 0 → matches
expect(
applyFilters(entities, [invalidRangeDef], { inv: { type: "range", min: 0, max: 100 } }),
).toEqual([entities[1]]);
// 4. Boolean filter
const boolDef: FilterDefinition = {
id: "act",
label: "Active",
type: "boolean",
propertyKey: "active",
};
expect(applyFilters(entities, [boolDef], { act: { type: "boolean", value: false } })).toEqual([
entities[1],
]);
// 5. Unknown filter type — falls through unchanged
const unknownDef: FilterDefinition = {
id: "unk",
label: "Unknown",
type: "unknown" as unknown as FilterDefinition["type"],
propertyKey: "active",
};
expect(
applyFilters(entities, [unknownDef], {
unk: { type: "unknown" as unknown as FilterValue["type"] } as unknown as FilterValue,
}),
).toEqual(entities);
// 6. Text filter with empty value — no filtering
const textDef: FilterDefinition = {
id: "txt",
label: "Text",
type: "text",
propertyKey: "label",
};
expect(applyFilters(entities, [textDef], { txt: { type: "text", value: "" } })).toEqual(
entities,
);
});
});
@@ -204,4 +204,156 @@ describe("DeclarativePlugin", () => {
expect(opts.color).toBe("#ff0000"); expect(opts.color).toBe("#ff0000");
expect(opts.labelText).toBe("Test"); expect(opts.labelText).toBe("Test");
}); });
test("destroy clears context", async () => {
const plugin = new DeclarativePlugin(makeManifest());
await plugin.initialize({} as any);
// We can't strictly observe context, but we can verify it doesn't throw
expect(() => plugin.destroy()).not.toThrow();
});
test("fetch uses query auth if specified", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ features: [] }),
}));
const originalEnv = process.env;
process.env = { ...originalEnv, API_KEY: "secret123" };
const plugin = new DeclarativePlugin(makeManifest({
dataSource: {
url: "https://api.example.com/data?type=test",
method: "GET",
pollInterval: 60000,
format: "geojson",
auth: { type: "query", key: "token", envVar: "API_KEY" }
}
}));
await plugin.fetch({ start: new Date(), end: new Date() });
expect(fetch).toHaveBeenCalledWith(
"https://api.example.com/data?type=test&token=secret123",
expect.any(Object)
);
process.env = originalEnv;
});
test("fetch does not use query auth if envVar is missing", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ features: [] }),
}));
const originalEnv = process.env;
process.env = { ...originalEnv };
delete process.env.MISSING_KEY;
const plugin = new DeclarativePlugin(makeManifest({
dataSource: {
url: "https://api.example.com/data",
method: "GET",
pollInterval: 60000,
format: "geojson",
auth: { type: "query", key: "token", envVar: "MISSING_KEY" }
}
}));
await plugin.fetch({ start: new Date(), end: new Date() });
expect(fetch).toHaveBeenCalledWith(
"https://api.example.com/data",
expect.any(Object)
);
process.env = originalEnv;
});
test("fetch uses header auth if specified", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ features: [] }),
}));
const originalEnv = process.env;
process.env = { ...originalEnv, HEADER_KEY: "bearer 123" };
const plugin = new DeclarativePlugin(makeManifest({
dataSource: {
url: "https://api.example.com/data",
method: "GET",
pollInterval: 60000,
format: "geojson",
auth: { type: "header", key: "Authorization", envVar: "HEADER_KEY" }
}
}));
await plugin.fetch({ start: new Date(), end: new Date() });
expect(fetch).toHaveBeenCalledWith(
"https://api.example.com/data",
expect.objectContaining({
headers: expect.objectContaining({
"Authorization": "bearer 123"
})
})
);
process.env = originalEnv;
});
test("fetch handles request body", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ features: [] }),
}));
const plugin = new DeclarativePlugin(makeManifest({
dataSource: {
url: "https://api.example.com/data",
method: "POST",
pollInterval: 60000,
format: "geojson",
body: { query: "test" }
}
}));
await plugin.fetch({ start: new Date(), end: new Date() });
expect(fetch).toHaveBeenCalledWith(
"https://api.example.com/data",
expect.objectContaining({
method: "POST",
body: JSON.stringify({ query: "test" })
})
);
});
test("fetch returns empty if mapping is missing", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ features: [] }),
}));
const plugin = new DeclarativePlugin(makeManifest({
fieldMapping: undefined
}));
const result = await plugin.fetch({ start: new Date(), end: new Date() });
expect(result).toEqual([]);
});
test("renderEntity returns billboard correctly", () => {
const plugin = new DeclarativePlugin(makeManifest({
rendering: {
entityType: "billboard",
icon: "/icon.png"
}
}));
const opts = plugin.renderEntity({} as any);
expect(opts.type).toBe("billboard");
expect(opts.iconUrl).toBe("/icon.png");
});
}); });
@@ -0,0 +1,116 @@
import { describe, test, expect } from "vitest";
import { mapGeoJsonToEntities } from "./mapGeoJsonToEntities";
describe("mapGeoJsonToEntities", () => {
test("handles valid geojson with full mapping", () => {
const data = {
features: [
{
id: "feat-1",
geometry: { type: "Point", coordinates: [174, -36, 10] },
properties: { speed: 100, heading: 90, time: "2026-05-14T00:00:00Z", label: "Test" }
}
]
};
const entities = mapGeoJsonToEntities(data, {
id: "id",
latitude: "geometry.coordinates[1]",
longitude: "geometry.coordinates[0]",
altitude: "geometry.coordinates[2]",
speed: "properties.speed",
heading: "properties.heading",
timestamp: "properties.time",
label: "properties.label",
properties: { custom: "properties.speed" }
}, "plugin1");
expect(entities).toHaveLength(1);
expect(entities[0].altitude).toBe(10);
expect(entities[0].speed).toBe(100);
expect(entities[0].heading).toBe(90);
expect(entities[0].timestamp.toISOString()).toBe("2026-05-14T00:00:00.000Z");
expect(entities[0].properties.custom).toBe(100);
});
test("handles missing properties definition", () => {
const data = {
features: [
{
geometry: { type: "Point", coordinates: [174, -36] },
properties: {}
}
]
};
const entities = mapGeoJsonToEntities(data, {
id: "id",
latitude: "geometry.coordinates[1]",
longitude: "geometry.coordinates[0]",
}, "plugin1");
expect(entities).toHaveLength(1);
expect(entities[0].properties).toEqual({});
expect(entities[0].id).toBe("plugin1-0"); // fallback to index
});
test("handles asNumber edge cases (null, non-finite)", () => {
const data = {
features: [
{
id: "feat-2",
geometry: { type: "Point", coordinates: [174, -36] },
properties: { speed: null, heading: "NaN", alt: "Infinity" }
}
]
};
const entities = mapGeoJsonToEntities(data, {
id: "id",
latitude: "geometry.coordinates[1]",
longitude: "geometry.coordinates[0]",
speed: "properties.speed",
heading: "properties.heading",
altitude: "properties.alt"
}, "plugin1");
expect(entities).toHaveLength(1);
expect(entities[0].speed).toBeUndefined(); // null -> undefined
expect(entities[0].heading).toBeUndefined(); // NaN -> undefined
expect(entities[0].altitude).toBeUndefined(); // Infinity -> undefined
});
test("handles parseTimestamp edge cases (invalid string, fallback)", () => {
const data = {
features: [
{
geometry: { type: "Point", coordinates: [174, -36] },
properties: { time1: "invalid-date", time2: null }
}
]
};
const entities = mapGeoJsonToEntities(data, {
id: "id",
latitude: "geometry.coordinates[1]",
longitude: "geometry.coordinates[0]",
timestamp: "properties.time1"
}, "plugin1");
expect(entities).toHaveLength(1);
// Invalid string falls back to current date, we just check it's a valid date
expect(entities[0].timestamp).toBeInstanceOf(Date);
expect(isNaN(entities[0].timestamp.getTime())).toBe(false);
const entities2 = mapGeoJsonToEntities(data, {
id: "id",
latitude: "geometry.coordinates[1]",
longitude: "geometry.coordinates[0]",
timestamp: "properties.time2"
}, "plugin1");
expect(entities2).toHaveLength(1);
expect(entities2[0].timestamp).toBeInstanceOf(Date);
expect(isNaN(entities2[0].timestamp.getTime())).toBe(false);
});
});
@@ -0,0 +1,72 @@
import { describe, test, expect } from "vitest";
import { mapJsonToEntities } from "./mapJsonToEntities";
describe("mapJsonToEntities", () => {
test("handles arrayPath resolution", () => {
const data = {
wrapper: {
items: [
{ id: 1, lat: 10, lon: 20 }
]
}
};
const entities = mapJsonToEntities(data, {
id: "id",
latitude: "lat",
longitude: "lon"
}, "plugin1", "wrapper.items");
expect(entities).toHaveLength(1);
expect(entities[0].id).toBe("plugin1-1");
});
test("handles non-array resolution gracefully", () => {
const data = { wrapper: { items: "not-an-array" } };
const entities = mapJsonToEntities(data, {
id: "id",
latitude: "lat",
longitude: "lon"
}, "plugin1", "wrapper.items");
expect(entities).toEqual([]);
});
test("handles asNumber and parseTimestamp edge cases", () => {
const data = [
{ id: 1, lat: 10, lon: 20, speed: null, alt: "Infinity", time: "invalid-date" }
];
const entities = mapJsonToEntities(data, {
id: "id",
latitude: "lat",
longitude: "lon",
speed: "speed",
altitude: "alt",
timestamp: "time"
}, "plugin1");
expect(entities).toHaveLength(1);
expect(entities[0].speed).toBeUndefined();
expect(entities[0].altitude).toBeUndefined();
expect(entities[0].timestamp).toBeInstanceOf(Date);
expect(isNaN(entities[0].timestamp.getTime())).toBe(false);
});
test("skips items missing lat or lon", () => {
const data = [
{ id: 1, lat: 10 }, // missing lon
{ id: 2, lon: 20 }, // missing lat
{ id: 3, lat: null, lon: 20 }
];
const entities = mapJsonToEntities(data, {
id: "id",
latitude: "lat",
longitude: "lon"
}, "plugin1");
expect(entities).toEqual([]);
});
});
+5
View File
@@ -10,6 +10,11 @@ function fakeRequest(origin?: string): Request {
describe("CORS utility", () => { describe("CORS utility", () => {
describe("corsHeaders", () => { describe("corsHeaders", () => {
it("returns empty object if no origin is provided", () => {
const headers = corsHeaders(fakeRequest(""));
expect(headers).toEqual({});
});
it("returns allowed origin for localhost:3001", () => { it("returns allowed origin for localhost:3001", () => {
const headers = corsHeaders(fakeRequest("http://localhost:3001")); const headers = corsHeaders(fakeRequest("http://localhost:3001"));
expect(headers["Access-Control-Allow-Origin"]).toBe("http://localhost:3001"); expect(headers["Access-Control-Allow-Origin"]).toBe("http://localhost:3001");
@@ -97,4 +97,25 @@ describe("marketplaceToken", () => {
await expect(verifyMarketplaceToken(noSub)).rejects.toThrow("subject"); await expect(verifyMarketplaceToken(noSub)).rejects.toThrow("subject");
}); });
}); });
describe("revokeMarketplaceToken", () => {
it("revokes a token and rejects it on verify", async () => {
const { revokeMarketplaceToken } = await import("./marketplaceToken");
const token = await issueMarketplaceToken(TEST_USER_ID);
const payload = await verifyMarketplaceToken(token);
expect(payload.jti).toBeDefined();
// Revoke it
revokeMarketplaceToken(payload.jti!);
// Now it should throw
await expect(verifyMarketplaceToken(token)).rejects.toThrow("revoked");
});
it("does nothing when passed an empty jti", async () => {
const { revokeMarketplaceToken } = await import("./marketplaceToken");
expect(() => revokeMarketplaceToken("")).not.toThrow();
});
});
}); });