Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ef7335574 | ||
|
|
628394f572 |
No files matched your search
@@ -166,7 +166,6 @@ Built-in plugins are instantiated in `AppShell.tsx` and registered via `PluginRe
|
||||
> - **MUST Be Transparent & Narrate Actions (Gemini 3.1 Agents)**: If you are a Gemini 3.1 agent, you MUST always be fully transparent. **Whenever you do anything, you must explicitly say what you are going to do in a visible chat message to the user, and ONLY THEN do it.** This ensures the user can actually see and verify what you are doing in real time. Do not jump to destructive actions without stating your intent first. Keep this narration conversational and natural. Avoid stiff, robotic templates. Just explicitly drop a brief, casual note about what you are checking, fixing, or deleting *before* you run the tool.
|
||||
> - **MUST Require Explicit Authorization**: Do NOT execute any state-changing tools (e.g., modifying files, writing code, running scripts, executing git commands) without first obtaining clear, explicit permission from the user to proceed with that specific action, **UNLESS** the action is a simple, straightforward, and safe operation (e.g., no deletion or dangerous operations). For safe operations, you may proceed without explicit permission. Otherwise, inform the user of your proposed plan and WAIT for their approval before acting. **Crucially, if you realize you have violated this rule by taking an unauthorized action, DO NOT automatically revert it. Reverting is itself an action that requires authorization. Just answer the question.**
|
||||
> - **MUST Ask Clarifying Questions**: Never assume anything. If requirements are unclear, if you encounter an unexpected roadblock, or if the user's intent could be interpreted in multiple ways, you MUST pause and ask clarifying questions. Do NOT proceed until the developer has explicitly answered your question or requested you to proceed anyway.
|
||||
> - **MUST Add Property Tests**: Whenever possible and sensible, you MUST add property-based tests (using `fast-check`) to core logic, pure functions, parsers, and mathematical data transformations to ensure autonomous detection of edge cases.
|
||||
|
||||
### 5.8 Workspace Hygiene
|
||||
Whenever agents generate temporary debugging scripts, test REST endpoints via `.mjs`, or dump traces/JSON outputs, they **MUST** save these exclusively inside `/local-scripts/`. The root directory is strictly for production configuration files.
|
||||
@@ -269,8 +268,6 @@ Refer to these skill documents for specialized tasks:
|
||||
- **Commit Format**: We strictly enforce Conventional Commits (`feat:`, `fix:`, `refactor:`, `perf:`).
|
||||
- **Workflow**: You **MUST** use the `/commit` workflow before every git commit to ensure proper semantic versioning bumps.
|
||||
- **Required Checks**: Ensure `pnpm test` and `pnpm build` complete successfully before proposing a merge.
|
||||
- **Strict Coverage Thresholds**: Vitest coverage thresholds are enforced at **80% minimum** for branches, functions, and statements. You must ensure new code maintains or exceeds this baseline.
|
||||
- **Mutation Testing**: We utilize Stryker Mutator to prevent "vacuous" tests. Ensure your unit tests actually catch intentionally injected bugs in core logic.
|
||||
- **Review Process**: Use `/pr-review` to conduct a comprehensive multi-role review on any pull request.
|
||||
|
||||
---
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
"build": "next build --webpack",
|
||||
"start": "next start",
|
||||
"test": "vitest run",
|
||||
"test:mutate": "stryker run",
|
||||
"lint": "eslint .",
|
||||
"db:reset": "npx prisma migrate reset --force",
|
||||
"generate": "prisma generate"
|
||||
@@ -56,8 +55,6 @@
|
||||
"zustand": "^5.0.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@stryker-mutator/core": "^9.6.1",
|
||||
"@stryker-mutator/vitest-runner": "^9.6.1",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@types/bcryptjs": "^3.0.0",
|
||||
@@ -72,7 +69,6 @@
|
||||
"copy-webpack-plugin": "^14.0.0",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "^16.2.6",
|
||||
"fast-check": "^4.8.0",
|
||||
"jsdom": "^28.1.0",
|
||||
"rollup-plugin-external-globals": "^0.13.0",
|
||||
"tsx": "^4.21.0",
|
||||
|
||||
Generated
+2
-856
File diff suppressed because it is too large.
Load diff
@@ -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.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");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import { describe, test, expect } from "vitest";
|
||||
import fc from "fast-check";
|
||||
import { getNestedValue } from "./getNestedValue";
|
||||
|
||||
describe("getNestedValue", () => {
|
||||
@@ -46,49 +45,4 @@ describe("getNestedValue", () => {
|
||||
const obj = { properties: { mag: "5.2" } };
|
||||
expect(getNestedValue(obj, "properties.mag")).toBe("5.2");
|
||||
});
|
||||
|
||||
describe("Property-based testing", () => {
|
||||
test("never throws an exception regardless of object structure or path", () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.object(),
|
||||
fc.string(),
|
||||
(obj, path) => {
|
||||
// The core property: getNestedValue should be safe and never throw
|
||||
// It should either return a value or undefined
|
||||
try {
|
||||
getNestedValue(obj, path);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false; // Should never reach here
|
||||
}
|
||||
}
|
||||
),
|
||||
{ numRuns: 1000 }
|
||||
);
|
||||
});
|
||||
|
||||
test("always returns undefined for empty path if object is truthy", () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.object(),
|
||||
(obj) => {
|
||||
expect(getNestedValue(obj, "")).toBeUndefined();
|
||||
}
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
test("always returns undefined when object is null or undefined", () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.string(),
|
||||
(path) => {
|
||||
expect(getNestedValue(null, path)).toBeUndefined();
|
||||
expect(getNestedValue(undefined, path)).toBeUndefined();
|
||||
}
|
||||
)
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, test, expect } from "vitest";
|
||||
import { convertToGeoJson } from "./converter";
|
||||
import { detectGeoFields } from "./fieldDetector";
|
||||
import fc from "fast-check";
|
||||
|
||||
// ── Field Detector ──────────────────────────────────────────────
|
||||
|
||||
@@ -135,34 +134,4 @@ describe("convertToGeoJson", () => {
|
||||
category: "nature", active: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("property test: correctly converts arrays of random objects with valid auto-detected coords", () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.array(
|
||||
fc.record({
|
||||
lat: fc.double({ min: -90, max: 90, noNaN: true }),
|
||||
lon: fc.double({ min: -180, max: 180, noNaN: true }),
|
||||
randomProp: fc.string(),
|
||||
}),
|
||||
{ minLength: 1, maxLength: 100 }
|
||||
),
|
||||
(data) => {
|
||||
const result = convertToGeoJson(data);
|
||||
expect(result.type).toBe("FeatureCollection");
|
||||
expect(result.features).toHaveLength(data.length);
|
||||
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
const f = result.features[i];
|
||||
const row = data[i];
|
||||
expect(f.geometry.type).toBe("Point");
|
||||
expect(f.geometry.coordinates).toEqual([row.lon, row.lat]);
|
||||
expect(f.properties.randomProp).toBe(row.randomProp);
|
||||
expect(f.properties).not.toHaveProperty("lat");
|
||||
expect(f.properties).not.toHaveProperty("lon");
|
||||
}
|
||||
}
|
||||
)
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, test, expect } from "vitest";
|
||||
import { normalizeToGeoJson } from "./normalizer";
|
||||
import fc from "fast-check";
|
||||
|
||||
describe("normalizeToGeoJson", () => {
|
||||
test("passes through a valid FeatureCollection", () => {
|
||||
@@ -162,55 +161,4 @@ describe("normalizeToGeoJson", () => {
|
||||
test("throws on unrecognized format", () => {
|
||||
expect(() => normalizeToGeoJson({ foo: "bar" })).toThrow("Unrecognized");
|
||||
});
|
||||
|
||||
test("handles MultiPolygon geometry", () => {
|
||||
const input = {
|
||||
type: "Feature",
|
||||
geometry: {
|
||||
type: "MultiPolygon",
|
||||
coordinates: [[[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]]],
|
||||
},
|
||||
properties: {},
|
||||
};
|
||||
const result = normalizeToGeoJson(input);
|
||||
expect(result.geometryTypes).toEqual(["MultiPolygon"]);
|
||||
});
|
||||
|
||||
test("throws when input parses to a non-object/array", () => {
|
||||
expect(() => normalizeToGeoJson(123)).toThrow("Input must be a JSON object or array");
|
||||
expect(() => normalizeToGeoJson("123")).toThrow("Input must be a JSON object or array");
|
||||
});
|
||||
|
||||
test("property: handles random coordinate inputs autonomously", () => {
|
||||
// This property test autonomously generates random float pairs to test edge-cases
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.float({ noDefaultInfinity: true, noNaN: true }),
|
||||
fc.float({ noDefaultInfinity: true, noNaN: true }),
|
||||
(lon, lat) => {
|
||||
const input = {
|
||||
type: "Feature",
|
||||
geometry: { type: "Point", coordinates: [lon, lat] },
|
||||
properties: {},
|
||||
};
|
||||
|
||||
try {
|
||||
const result = normalizeToGeoJson(input);
|
||||
// normalizer skips coordinates outside valid bounds [-180, 180], [-90, 90]
|
||||
if (lon < -180 || lon > 180 || lat < -90 || lat > 90) {
|
||||
expect(result.skippedCount).toBe(1);
|
||||
} else {
|
||||
expect(result.skippedCount).toBe(0);
|
||||
expect(result.collection.features[0].geometry.coordinates).toEqual([lon, lat]);
|
||||
}
|
||||
} catch (e: any) {
|
||||
// Normalizer explicitly throws if ALL features are skipped
|
||||
if (e.message !== "No features with valid geometry found.") {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,11 @@ function fakeRequest(origin?: string): Request {
|
||||
|
||||
describe("CORS utility", () => {
|
||||
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", () => {
|
||||
const headers = corsHeaders(fakeRequest("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");
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import { RateLimiter, getClientIp } from "./rateLimit";
|
||||
import fc from "fast-check";
|
||||
|
||||
describe("RateLimiter", () => {
|
||||
let limiter: RateLimiter;
|
||||
@@ -61,20 +60,6 @@ describe("RateLimiter", () => {
|
||||
}, 60);
|
||||
});
|
||||
});
|
||||
|
||||
it("cleans up expired entries", () => {
|
||||
const localLimiter = new RateLimiter({ windowMs: 100, maxRequests: 5 });
|
||||
localLimiter.check("ip-cleanup");
|
||||
|
||||
// Force the store resetAt to be in the past
|
||||
const entry = (localLimiter as any).store.get("ip-cleanup");
|
||||
entry.resetAt = Date.now() - 1000;
|
||||
|
||||
(localLimiter as any).cleanup();
|
||||
|
||||
expect((localLimiter as any).store.has("ip-cleanup")).toBe(false);
|
||||
localLimiter.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getClientIp", () => {
|
||||
@@ -96,33 +81,4 @@ describe("getClientIp", () => {
|
||||
const req = new Request("http://localhost");
|
||||
expect(getClientIp(req)).toBe("unknown");
|
||||
});
|
||||
|
||||
it("property test: x-forwarded-for always returns the first IP in a list", () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.array(fc.ipV4(), { minLength: 1, maxLength: 10 }),
|
||||
(ips) => {
|
||||
const headerValue = ips.join(", ");
|
||||
const req = new Request("http://localhost", {
|
||||
headers: { "x-forwarded-for": headerValue },
|
||||
});
|
||||
expect(getClientIp(req)).toBe(ips[0]);
|
||||
}
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
it("property test: x-real-ip is used when x-forwarded-for is absent", () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.ipV4(),
|
||||
(ip) => {
|
||||
const req = new Request("http://localhost", {
|
||||
headers: { "x-real-ip": ip },
|
||||
});
|
||||
expect(getClientIp(req)).toBe(ip);
|
||||
}
|
||||
)
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"$schema": "./node_modules/@stryker-mutator/core/schema/stryker-schema.json",
|
||||
"packageManager": "pnpm",
|
||||
"reporters": [
|
||||
"html",
|
||||
"clear-text",
|
||||
"progress"
|
||||
],
|
||||
"testRunner": "vitest",
|
||||
"plugins": [
|
||||
"@stryker-mutator/vitest-runner"
|
||||
],
|
||||
"coverageAnalysis": "off",
|
||||
"ignorePatterns": [
|
||||
"**/*.css",
|
||||
"**/*.md",
|
||||
"**/*.json"
|
||||
],
|
||||
"mutate": [
|
||||
"src/core/**/*.ts",
|
||||
"src/lib/**/*.ts",
|
||||
"!src/**/*.test.ts",
|
||||
"!src/**/*.spec.ts"
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user