|
1 | | -import { createTestProject } from '@zenstackhq/testtools'; |
| 1 | +import { createTestProject, getTestDbProvider } from '@zenstackhq/testtools'; |
| 2 | +import { createHash } from 'node:crypto'; |
2 | 3 | import { execSync } from 'node:child_process'; |
3 | 4 | import fs from 'node:fs'; |
4 | 5 | import path from 'node:path'; |
| 6 | +import { expect } from 'vitest'; |
5 | 7 |
|
6 | | -const ZMODEL_PRELUDE = `datasource db { |
7 | | - provider = "sqlite" |
8 | | - url = "file:./dev.db" |
9 | | -}`; |
| 8 | +const TEST_PG_CONFIG = { |
| 9 | + host: process.env['TEST_PG_HOST'] ?? 'localhost', |
| 10 | + port: process.env['TEST_PG_PORT'] ? parseInt(process.env['TEST_PG_PORT']) : 5432, |
| 11 | + user: process.env['TEST_PG_USER'] ?? 'postgres', |
| 12 | + password: process.env['TEST_PG_PASSWORD'] ?? 'postgres', |
| 13 | +}; |
| 14 | + |
| 15 | +function getTestDbName(provider: string) { |
| 16 | + if (provider === 'sqlite') { |
| 17 | + return './test.db'; |
| 18 | + } |
| 19 | + const testName = expect.getState().currentTestName ?? 'unnamed'; |
| 20 | + const testPath = expect.getState().testPath ?? ''; |
| 21 | + // digest test name |
| 22 | + const digest = createHash('md5') |
| 23 | + .update(testName + testPath) |
| 24 | + .digest('hex'); |
| 25 | + // compute a database name based on test name |
| 26 | + return ( |
| 27 | + 'test_' + |
| 28 | + testName |
| 29 | + .toLowerCase() |
| 30 | + .replace(/[^a-z0-9_]/g, '_') |
| 31 | + .replace(/_+/g, '_') |
| 32 | + .substring(0, 30) + |
| 33 | + digest.slice(0, 6) |
| 34 | + ); |
| 35 | +} |
10 | 36 |
|
11 | 37 | export function createProject(zmodel: string, addPrelude = true) { |
| 38 | + const provider = getTestDbProvider() ?? 'sqlite'; |
| 39 | + const dbName = getTestDbName(provider); |
| 40 | + const dbUrl = |
| 41 | + provider === 'sqlite' |
| 42 | + ? `file:${dbName}` |
| 43 | + : `postgres://${TEST_PG_CONFIG.user}:${TEST_PG_CONFIG.password}@${TEST_PG_CONFIG.host}:${TEST_PG_CONFIG.port}/${dbName}`; |
| 44 | + |
| 45 | + const ZMODEL_PRELUDE = `datasource db { |
| 46 | + provider = "${provider}" |
| 47 | + url = "${dbUrl}" |
| 48 | +} |
| 49 | +`; |
12 | 50 | const workDir = createTestProject(); |
13 | 51 | fs.mkdirSync(path.join(workDir, 'zenstack'), { recursive: true }); |
14 | 52 | const schemaPath = path.join(workDir, 'zenstack/schema.zmodel'); |
|
0 commit comments