import { Prisma } from '../generated/prisma'; import { seedAdmin } from '../prisma/seed'; type SeedClient = Parameters[0]; function fakeClient( userCount: number, create = jest.fn().mockResolvedValue({}), ) { const client = { user: { count: jest.fn().mockResolvedValue(userCount), create }, role: { findUniqueOrThrow: jest.fn().mockResolvedValue({ id: 'role-admin' }), }, }; return { client, prisma: client as unknown as SeedClient }; } describe('seedAdmin (prisma/seed.ts)', () => { it('creates no admin once any user exists, even when SEED_ADMIN_EMAIL is unknown', async () => { const { client, prisma } = fakeClient(1); const lines: string[] = []; const result = await seedAdmin( prisma, { SEED_ADMIN_EMAIL: 'admin@apicore.local' }, (line) => lines.push(line), ); expect(result).toBe('skipped'); expect(client.user.create).not.toHaveBeenCalled(); expect(lines.join('\n')).not.toMatch(/Passwort/); }); it('creates the admin on an empty user table and prints a generated password once', async () => { const { client, prisma } = fakeClient(0); const lines: string[] = []; const result = await seedAdmin(prisma, {}, (line) => lines.push(line)); expect(result).toBe('created'); const [args] = client.user.create.mock.calls[0] as [ { data: { email: string; roleId: string } }, ]; expect(args.data).toMatchObject({ email: 'admin@apicore.local', roleId: 'role-admin', }); const passwordLine = lines.find((line) => line.includes('Passwort:')); expect(passwordLine).toMatch(/Passwort: +\S{20,}/); }); it('never prints an operator-supplied password', async () => { const { prisma } = fakeClient(0); const lines: string[] = []; await seedAdmin( prisma, { SEED_ADMIN_EMAIL: 'chef@example.org', SEED_ADMIN_PASSWORD: 'geheim-vom-betrieb', }, (line) => lines.push(line), ); const output = lines.join('\n'); expect(output).toContain('chef@example.org'); expect(output).not.toContain('geheim-vom-betrieb'); expect(output).toContain('SEED_ADMIN_PASSWORD'); }); it('treats a concurrent create by another replica as done', async () => { const conflict = new Prisma.PrismaClientKnownRequestError('unique', { code: 'P2002', clientVersion: 'test', }); const { prisma } = fakeClient(0, jest.fn().mockRejectedValue(conflict)); const lines: string[] = []; const result = await seedAdmin(prisma, {}, (line) => lines.push(line)); expect(result).toBe('skipped'); expect(lines.join('\n')).not.toMatch(/Passwort/); }); });