95 lines
3.0 KiB
TypeScript
95 lines
3.0 KiB
TypeScript
import { describe, expect, it } from "@suaveplan/testing/runner";
|
|
import { Hono } from "hono";
|
|
import {
|
|
CAMPAIGNS_API_CODES,
|
|
CampaignsApiError,
|
|
} from "../../error-codes/error-codes.js";
|
|
import { requireTenant } from "./require-tenant.js";
|
|
|
|
function makeContext(principal: unknown) {
|
|
const app = new Hono();
|
|
let captured: { id: string; tenantId: string } | undefined;
|
|
let caught: unknown;
|
|
app.use("*", async (c, next) => {
|
|
if (principal !== undefined) {
|
|
c.set("user", principal as never);
|
|
}
|
|
try {
|
|
captured = requireTenant(c);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
await next();
|
|
});
|
|
app.get("/", (c) => c.text("ok"));
|
|
return { app, get: () => ({ captured, caught }) };
|
|
}
|
|
|
|
describe("requireTenant", () => {
|
|
it("returns id + tenantId when principal carries both", {
|
|
timeout: 5000,
|
|
}, async () => {
|
|
const { app, get } = makeContext({ id: "u1", tenantId: "t1" });
|
|
await app.request("/");
|
|
expect(get().captured).toEqual({ id: "u1", tenantId: "t1" });
|
|
});
|
|
|
|
it("falls back to empty id when principal has no id field", {
|
|
timeout: 5000,
|
|
}, async () => {
|
|
const { app, get } = makeContext({ tenantId: "t1" });
|
|
await app.request("/");
|
|
expect(get().captured).toEqual({ id: "", tenantId: "t1" });
|
|
});
|
|
|
|
it("throws TENANT_REQUIRED when user is null", {
|
|
timeout: 5000,
|
|
}, async () => {
|
|
const { app, get } = makeContext(null);
|
|
await app.request("/");
|
|
const err = get().caught;
|
|
expect(err).toBeInstanceOf(CampaignsApiError);
|
|
expect((err as CampaignsApiError).code).toBe(
|
|
CAMPAIGNS_API_CODES.TENANT_REQUIRED
|
|
);
|
|
});
|
|
|
|
it("throws TENANT_REQUIRED when user is undefined", {
|
|
timeout: 5000,
|
|
}, async () => {
|
|
const { app, get } = makeContext(undefined);
|
|
await app.request("/");
|
|
expect((get().caught as CampaignsApiError).code).toBe(
|
|
CAMPAIGNS_API_CODES.TENANT_REQUIRED
|
|
);
|
|
});
|
|
|
|
it("throws TENANT_REQUIRED when tenantId is the empty string", {
|
|
timeout: 5000,
|
|
}, async () => {
|
|
const { app, get } = makeContext({ id: "u", tenantId: "" });
|
|
await app.request("/");
|
|
expect((get().caught as CampaignsApiError).code).toBe(
|
|
CAMPAIGNS_API_CODES.TENANT_REQUIRED
|
|
);
|
|
});
|
|
|
|
it("throws TENANT_REQUIRED when tenantId is not a string", {
|
|
timeout: 5000,
|
|
}, async () => {
|
|
const { app, get } = makeContext({ id: "u", tenantId: 42 });
|
|
await app.request("/");
|
|
expect((get().caught as CampaignsApiError).code).toBe(
|
|
CAMPAIGNS_API_CODES.TENANT_REQUIRED
|
|
);
|
|
});
|
|
|
|
it("falls back to empty id when id is the empty string", {
|
|
timeout: 5000,
|
|
}, async () => {
|
|
const { app, get } = makeContext({ id: "", tenantId: "t1" });
|
|
await app.request("/");
|
|
expect(get().captured).toEqual({ id: "", tenantId: "t1" });
|
|
});
|
|
});
|