|
| 1 | +import { execSync } from 'node:child_process'; |
| 2 | +import fs from 'node:fs'; |
| 3 | +import path from 'node:path'; |
| 4 | +import { describe, expect, it } from 'vitest'; |
| 5 | +import { fileURLToPath } from 'node:url'; |
| 6 | +import tmp from 'tmp'; |
| 7 | + |
| 8 | +const __filename = fileURLToPath(import.meta.url); |
| 9 | +const __dirname = path.dirname(__filename); |
| 10 | + |
| 11 | +/** |
| 12 | + * Helper function to generate schema using better-auth CLI |
| 13 | + */ |
| 14 | +function generateSchema(configFile: string): string { |
| 15 | + const { name: workDir } = tmp.dirSync({ unsafeCleanup: true }); |
| 16 | + const schemaPath = path.join(workDir, 'schema.zmodel'); |
| 17 | + const configPath = path.join(__dirname, configFile); |
| 18 | + |
| 19 | + execSync(`pnpm better-auth generate --config ${configPath} --output ${schemaPath} --yes`, { |
| 20 | + cwd: __dirname, |
| 21 | + stdio: 'pipe', |
| 22 | + }); |
| 23 | + |
| 24 | + return schemaPath; |
| 25 | +} |
| 26 | + |
| 27 | +/** |
| 28 | + * Helper function to verify schema with zenstack check |
| 29 | + */ |
| 30 | +function verifySchema(schemaPath: string) { |
| 31 | + const cliPath = path.join(__dirname, '../../../cli/dist/index.js'); |
| 32 | + const workDir = path.dirname(schemaPath); |
| 33 | + |
| 34 | + expect(fs.existsSync(schemaPath)).toBe(true); |
| 35 | + |
| 36 | + expect(() => { |
| 37 | + execSync(`node ${cliPath} check --schema ${schemaPath}`, { |
| 38 | + cwd: workDir, |
| 39 | + stdio: 'pipe', |
| 40 | + }); |
| 41 | + }).not.toThrow(); |
| 42 | +} |
| 43 | + |
| 44 | +describe('Cli schema generation tests', () => { |
| 45 | + it('works with simple config', async () => { |
| 46 | + const schemaPath = generateSchema('auth.ts'); |
| 47 | + verifySchema(schemaPath); |
| 48 | + }); |
| 49 | + |
| 50 | + it('works with custom config', async () => { |
| 51 | + const schemaPath = generateSchema('auth-custom.ts'); |
| 52 | + verifySchema(schemaPath); |
| 53 | + |
| 54 | + // Verify that the generated schema contains the expected default values |
| 55 | + const schemaContent = fs.readFileSync(schemaPath, 'utf-8'); |
| 56 | + expect(schemaContent).toMatch(/role\s+String/); |
| 57 | + expect(schemaContent).toContain("@default('user')"); |
| 58 | + expect(schemaContent).toMatch(/lang\s+String/); |
| 59 | + expect(schemaContent).toContain("@default('en')"); |
| 60 | + expect(schemaContent).toMatch(/age\s+Int/); |
| 61 | + expect(schemaContent).toContain('@default(18)'); |
| 62 | + expect(schemaContent).toMatch(/admin\s+Boolean/); |
| 63 | + expect(schemaContent).toContain('@default(false)'); |
| 64 | + }); |
| 65 | +}); |
0 commit comments