SPB Git

Repository Public

idempotency.test.ts 1.7 KB 38 lines typescript

1import { describe, expect, it } from "vitest";2import { fingerprint, IdempotencyIntent } from "./idempotency";34describe("IdempotencyIntent", () => {5  const counter = () => {6    let n = 0;7    return () => `key-${++n}`;8  };9  it("keeps the same key across retries of the same body", () => {10    const i = new IdempotencyIntent(counter());11    const body = { type: "service.restart", target: { kind: "service", id: "s1" }, params: { graceful: true } };12    expect(i.keyFor(body)).toBe("key-1");13    expect(i.keyFor(structuredClone(body))).toBe("key-1");14    expect(i.keyFor({ params: { graceful: true }, target: { id: "s1", kind: "service" }, type: "service.restart" })).toBe("key-1"); // key order is irrelevant15  });16  it("renews the key when the body changes (a different body with the same key would be a 409)", () => {17    const i = new IdempotencyIntent(counter());18    expect(i.keyFor({ a: 1 })).toBe("key-1");19    expect(i.keyFor({ a: 2 })).toBe("key-2");20    expect(i.keyFor({ a: 2 })).toBe("key-2");21    expect(i.keyFor({ a: 1 })).toBe("key-3");22  });23  it("starts a new intent after completion, even for an identical body", () => {24    const i = new IdempotencyIntent(counter());25    expect(i.keyFor({ a: 1 })).toBe("key-1");26    i.complete();27    expect(i.keyFor({ a: 1 })).toBe("key-2");28  });29  it("ignores undefined members like JSON does", () => {30    expect(fingerprint({ a: 1, b: undefined })).toBe(fingerprint({ a: 1 }));31    expect(fingerprint({ a: [1, { c: 2, b: 1 }] })).toBe(fingerprint({ a: [1, { b: 1, c: 2 }] }));32    expect(fingerprint([1, 2])).not.toBe(fingerprint([2, 1]));33  });34  it("generates UUIDs by default", () => {35    expect(new IdempotencyIntent().keyFor({})).toMatch(/^[0-9a-f-]{36}$/);36  });37});38
Files main
Menu

Theme