test: add AssetModel API tests
This commit is contained in:
@@ -0,0 +1,500 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Mock } from "vitest";
|
||||
import type { Session } from "next-auth";
|
||||
import {
|
||||
createAssetModel,
|
||||
listAssetModels,
|
||||
validateCreateAssetModelInput,
|
||||
} from "@/lib/asset-models";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Note: this file has two layers of coverage, mirroring
|
||||
// tests/asset-category-attribute-defs.test.ts:
|
||||
// - lib-level tests below exercise src/lib/asset-models.ts directly
|
||||
// (validation, FK/business-rule error handling, list ordering).
|
||||
// - route-level tests (further down) exercise
|
||||
// src/app/api/asset-models/route.ts over HTTP, including the auth() gate,
|
||||
// malformed JSON, and non-object bodies.
|
||||
vi.mock("@/auth", () => ({ auth: vi.fn() }));
|
||||
|
||||
import { GET, POST } from "@/app/api/asset-models/route";
|
||||
import { auth } from "@/auth";
|
||||
|
||||
const mockedAuth = auth as unknown as Mock<() => Promise<Session | null>>;
|
||||
|
||||
const testSession: Session = {
|
||||
user: { id: "test-user-id" },
|
||||
expires: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
|
||||
};
|
||||
|
||||
function postRequest(body: unknown): Request {
|
||||
return new Request("http://localhost/api/asset-models", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
// AssetModel.categoryId is a real FK to AssetCategory, and the referenced
|
||||
// category must be valueGroup=high_value (see docs/
|
||||
// asset-license-management.md's "Cập nhật 2026-08-02 (2)" section). Tests
|
||||
// that need valid ids create real rows first and use their ids. Mirrors
|
||||
// tests/asset-category-attribute-defs.test.ts's createTestAssetCategory()
|
||||
// helper.
|
||||
function createTestAssetCategory(
|
||||
overrides: { name?: string; valueGroup?: "high_value" | "low_value" } = {}
|
||||
) {
|
||||
return prisma.assetCategory.create({
|
||||
data: {
|
||||
name: overrides.name ?? "Laptop",
|
||||
valueGroup: overrides.valueGroup ?? "high_value",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
// Each test starts from empty tables so listing/order assertions are
|
||||
// deterministic. asset_models must be cleared before asset_categories
|
||||
// since it has an FK (ON DELETE RESTRICT) to it.
|
||||
await prisma.assetModel.deleteMany();
|
||||
await prisma.assetCategory.deleteMany();
|
||||
// Default to a logged-in session — the lib-level tests below don't go
|
||||
// through the route at all (so this is a no-op for them), and the
|
||||
// route-level tests exercise business logic, not auth gating (that's
|
||||
// covered by the "auth gating" describe block further down).
|
||||
mockedAuth.mockResolvedValue(testSession);
|
||||
});
|
||||
|
||||
describe("validateCreateAssetModelInput", () => {
|
||||
it("accepts valid input with a non-trivial specs object", () => {
|
||||
const result = validateCreateAssetModelInput({
|
||||
categoryId: "11111111-1111-1111-1111-111111111111",
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
specs: { ram_gb: 16, cpu: "i7-1165G7" },
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.value).toMatchObject({
|
||||
categoryId: "11111111-1111-1111-1111-111111111111",
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
specs: { ram_gb: 16, cpu: "i7-1165G7" },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("defaults specs to {} when omitted", () => {
|
||||
const result = validateCreateAssetModelInput({
|
||||
categoryId: "11111111-1111-1111-1111-111111111111",
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.value.specs).toEqual({});
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a missing categoryId", () => {
|
||||
const result = validateCreateAssetModelInput({
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toMatch(/categoryId/i);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a categoryId that is not a valid UUID", () => {
|
||||
const result = validateCreateAssetModelInput({
|
||||
categoryId: "not-a-uuid",
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toMatch(/categoryId/i);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects an empty manufacturer", () => {
|
||||
const result = validateCreateAssetModelInput({
|
||||
categoryId: "11111111-1111-1111-1111-111111111111",
|
||||
manufacturer: "",
|
||||
name: "Latitude 5420",
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toMatch(/manufacturer/i);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects an empty name", () => {
|
||||
const result = validateCreateAssetModelInput({
|
||||
categoryId: "11111111-1111-1111-1111-111111111111",
|
||||
manufacturer: "Dell",
|
||||
name: "",
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toMatch(/name/i);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a specs value that is not a plain object", () => {
|
||||
const result = validateCreateAssetModelInput({
|
||||
categoryId: "11111111-1111-1111-1111-111111111111",
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
specs: "not an object",
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toMatch(/specs/i);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a specs value that is an array", () => {
|
||||
const result = validateCreateAssetModelInput({
|
||||
categoryId: "11111111-1111-1111-1111-111111111111",
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
specs: ["not", "an", "object"],
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toMatch(/specs/i);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("createAssetModel", () => {
|
||||
it("creates a model for a real high_value category, with a non-trivial specs object", async () => {
|
||||
const category = await createTestAssetCategory({ valueGroup: "high_value" });
|
||||
const result = validateCreateAssetModelInput({
|
||||
categoryId: category.id,
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
specs: { ram_gb: 16, cpu: "i7-1165G7" },
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
|
||||
const created = await createAssetModel(result.value);
|
||||
|
||||
expect(created.ok).toBe(true);
|
||||
if (!created.ok) return;
|
||||
expect(created.value).toMatchObject({
|
||||
category_id: category.id,
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
specs: { ram_gb: 16, cpu: "i7-1165G7" },
|
||||
});
|
||||
expect(typeof created.value.id).toBe("string");
|
||||
expect(created.value.id.length).toBeGreaterThan(0);
|
||||
expect(Number.isNaN(Date.parse(created.value.created_at))).toBe(false);
|
||||
});
|
||||
|
||||
it("defaults specs to {} in the created record when omitted", async () => {
|
||||
const category = await createTestAssetCategory({ valueGroup: "high_value" });
|
||||
const result = validateCreateAssetModelInput({
|
||||
categoryId: category.id,
|
||||
manufacturer: "Apple",
|
||||
name: "MacBook Pro 14",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
|
||||
const created = await createAssetModel(result.value);
|
||||
|
||||
expect(created.ok).toBe(true);
|
||||
if (!created.ok) return;
|
||||
expect(created.value.specs).toEqual({});
|
||||
});
|
||||
|
||||
it("returns a clean error when categoryId doesn't reference an existing category", async () => {
|
||||
const result = validateCreateAssetModelInput({
|
||||
categoryId: "00000000-0000-0000-0000-000000000000",
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
|
||||
const created = await createAssetModel(result.value);
|
||||
expect(created.ok).toBe(false);
|
||||
if (created.ok) return;
|
||||
expect(created.error).toMatch(/categoryId/i);
|
||||
expect(created.error).toMatch(/does not reference an existing asset category/i);
|
||||
|
||||
const remaining = await prisma.assetModel.findMany();
|
||||
expect(remaining).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("returns a distinct clean error when categoryId references an existing but low_value category", async () => {
|
||||
const category = await createTestAssetCategory({
|
||||
name: "Cáp HDMI",
|
||||
valueGroup: "low_value",
|
||||
});
|
||||
const result = validateCreateAssetModelInput({
|
||||
categoryId: category.id,
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
|
||||
const created = await createAssetModel(result.value);
|
||||
expect(created.ok).toBe(false);
|
||||
if (created.ok) return;
|
||||
expect(created.error).toMatch(/high_value/i);
|
||||
// Distinct message from the "doesn't exist at all" case.
|
||||
expect(created.error).not.toMatch(/does not reference an existing asset category/i);
|
||||
|
||||
const remaining = await prisma.assetModel.findMany();
|
||||
expect(remaining).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("listAssetModels", () => {
|
||||
it("lists created models, newest first", async () => {
|
||||
const category = await createTestAssetCategory({ valueGroup: "high_value" });
|
||||
|
||||
const first = validateCreateAssetModelInput({
|
||||
categoryId: category.id,
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
});
|
||||
expect(first.ok).toBe(true);
|
||||
if (first.ok) await createAssetModel(first.value);
|
||||
|
||||
// Ensure a distinct created_at ordering even on fast filesystems/clocks.
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
|
||||
const second = validateCreateAssetModelInput({
|
||||
categoryId: category.id,
|
||||
manufacturer: "Apple",
|
||||
name: "MacBook Pro 14",
|
||||
});
|
||||
expect(second.ok).toBe(true);
|
||||
if (second.ok) await createAssetModel(second.value);
|
||||
|
||||
const records = await listAssetModels();
|
||||
|
||||
expect(records).toHaveLength(2);
|
||||
// newest first
|
||||
expect(records[0]).toMatchObject({ name: "MacBook Pro 14" });
|
||||
expect(records[1]).toMatchObject({ name: "Latitude 5420" });
|
||||
});
|
||||
|
||||
it("returns an empty list when there are no models", async () => {
|
||||
const records = await listAssetModels();
|
||||
expect(records).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/asset-models", () => {
|
||||
it("creates a model on valid input", async () => {
|
||||
const category = await createTestAssetCategory({ valueGroup: "high_value" });
|
||||
const res = await POST(
|
||||
postRequest({
|
||||
categoryId: category.id,
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
specs: { ram_gb: 16, cpu: "i7-1165G7" },
|
||||
})
|
||||
);
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
const body = await res.json();
|
||||
|
||||
expect(body).toMatchObject({
|
||||
category_id: category.id,
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
specs: { ram_gb: 16, cpu: "i7-1165G7" },
|
||||
});
|
||||
expect(typeof body.id).toBe("string");
|
||||
expect(body.id.length).toBeGreaterThan(0);
|
||||
expect(Number.isNaN(Date.parse(body.created_at))).toBe(false);
|
||||
});
|
||||
|
||||
it("defaults specs to {} when omitted from the request body", async () => {
|
||||
const category = await createTestAssetCategory({ valueGroup: "high_value" });
|
||||
const res = await POST(
|
||||
postRequest({
|
||||
categoryId: category.id,
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
})
|
||||
);
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
const body = await res.json();
|
||||
expect(body.specs).toEqual({});
|
||||
});
|
||||
|
||||
it("rejects a missing manufacturer", async () => {
|
||||
const category = await createTestAssetCategory({ valueGroup: "high_value" });
|
||||
const res = await POST(
|
||||
postRequest({
|
||||
categoryId: category.id,
|
||||
name: "Latitude 5420",
|
||||
})
|
||||
);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
const body = await res.json();
|
||||
expect(body.error).toMatch(/manufacturer/i);
|
||||
});
|
||||
|
||||
it("rejects a categoryId that is a well-formed UUID but doesn't reference an existing category", async () => {
|
||||
const res = await POST(
|
||||
postRequest({
|
||||
categoryId: "00000000-0000-0000-0000-000000000000",
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
})
|
||||
);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
const body = await res.json();
|
||||
expect(body.error).toMatch(/categoryId/i);
|
||||
expect(body.error).toMatch(/does not reference an existing asset category/i);
|
||||
|
||||
const remaining = await prisma.assetModel.findMany();
|
||||
expect(remaining).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("rejects a categoryId referencing an existing but low_value category, with a distinct 400", async () => {
|
||||
const category = await createTestAssetCategory({
|
||||
name: "Cáp HDMI",
|
||||
valueGroup: "low_value",
|
||||
});
|
||||
const res = await POST(
|
||||
postRequest({
|
||||
categoryId: category.id,
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
})
|
||||
);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
const body = await res.json();
|
||||
expect(body.error).toMatch(/high_value/i);
|
||||
|
||||
const remaining = await prisma.assetModel.findMany();
|
||||
expect(remaining).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("rejects an invalid JSON body", async () => {
|
||||
const req = new Request("http://localhost/api/asset-models", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: "not json",
|
||||
});
|
||||
|
||||
const res = await POST(req);
|
||||
expect(res.status).toBe(400);
|
||||
const body = await res.json();
|
||||
expect(body.error).toMatch(/JSON/i);
|
||||
});
|
||||
|
||||
it("rejects a non-object JSON body", async () => {
|
||||
// Note: arrays are `typeof "object"` in JS, so they pass the route's
|
||||
// object check (same behavior as /api/asset-category-attribute-defs) —
|
||||
// use a JSON string primitive here to actually exercise the "not an
|
||||
// object" branch.
|
||||
const res = await POST(postRequest("not an object"));
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
const body = await res.json();
|
||||
expect(body.error).toMatch(/JSON object/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/asset-models", () => {
|
||||
it("lists created models, newest first", async () => {
|
||||
const category = await createTestAssetCategory({ valueGroup: "high_value" });
|
||||
await POST(
|
||||
postRequest({
|
||||
categoryId: category.id,
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
})
|
||||
);
|
||||
// Ensure a distinct created_at ordering even on fast filesystems/clocks.
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
await POST(
|
||||
postRequest({
|
||||
categoryId: category.id,
|
||||
manufacturer: "Apple",
|
||||
name: "MacBook Pro 14",
|
||||
})
|
||||
);
|
||||
|
||||
const res = await GET();
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const body = await res.json();
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
expect(body).toHaveLength(2);
|
||||
|
||||
// newest first
|
||||
expect(body[0]).toMatchObject({ name: "MacBook Pro 14" });
|
||||
expect(body[1]).toMatchObject({ name: "Latitude 5420" });
|
||||
});
|
||||
|
||||
it("returns an empty list when there are no models", async () => {
|
||||
const res = await GET();
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("auth gating on /api/asset-models", () => {
|
||||
// Mirrors tests/asset-category-attribute-defs.test.ts's "auth gating"
|
||||
// block — only checks session presence, per the flat permission model (no
|
||||
// role/permission logic).
|
||||
it("POST /api/asset-models returns 401 without a session", async () => {
|
||||
const category = await createTestAssetCategory({ valueGroup: "high_value" });
|
||||
mockedAuth.mockResolvedValue(null);
|
||||
|
||||
const res = await POST(
|
||||
postRequest({
|
||||
categoryId: category.id,
|
||||
manufacturer: "Dell",
|
||||
name: "Latitude 5420",
|
||||
})
|
||||
);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
const body = await res.json();
|
||||
expect(body).toEqual({ error: "Unauthorized" });
|
||||
|
||||
// And it must not have created anything.
|
||||
const remaining = await prisma.assetModel.findMany();
|
||||
expect(remaining).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("GET /api/asset-models returns 401 without a session", async () => {
|
||||
mockedAuth.mockResolvedValue(null);
|
||||
|
||||
const res = await GET();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
const body = await res.json();
|
||||
expect(body).toEqual({ error: "Unauthorized" });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user