38 lines
1.4 KiB
TypeScript
38 lines
1.4 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
const dbMock = vi.hoisted(() => ({ $transaction: vi.fn() }));
|
|
vi.mock("~/utils/db.server", () => ({ db: dbMock, dbRead: dbMock }));
|
|
|
|
import { withTenantRLS } from "./tenantRls.server";
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
describe("withTenantRLS", () => {
|
|
it("sets app.tenant_id transaction-locally and runs the callback in the same transaction", async () => {
|
|
const tx = { $executeRaw: vi.fn().mockResolvedValue(1) };
|
|
dbMock.$transaction.mockImplementation(async (fn: (tx: unknown) => Promise<unknown>) => fn(tx));
|
|
|
|
const result = await withTenantRLS("tenantA", async (handed) => {
|
|
expect(handed).toBe(tx);
|
|
return "ok";
|
|
});
|
|
|
|
expect(result).toBe("ok");
|
|
// Tagged-Template: strings-Array an [0], interpolierter tenantId an [1].
|
|
const [strings, value] = tx.$executeRaw.mock.calls[0];
|
|
expect(value).toBe("tenantA");
|
|
const sql = (strings as string[]).join("?");
|
|
expect(sql).toContain("set_config");
|
|
expect(sql).toContain("app.tenant_id");
|
|
// 3. Argument von set_config ist 'true' (transaktions-lokal) und steht als Literal im SQL.
|
|
expect(sql).toContain("true");
|
|
});
|
|
|
|
it("rejects an empty tenantId before opening a transaction", async () => {
|
|
await expect(withTenantRLS("", async () => "x")).rejects.toThrow(/tenantId/);
|
|
expect(dbMock.$transaction).not.toHaveBeenCalled();
|
|
});
|
|
});
|