eletrotupi / tcc/ commit / 3292568

api: refuse to run the database tests against a non-test database

The test setup now aborts unless the database name ends in `_test`,
which is how it knows .env.test was loaded
Pedro Lucas Porcellis porcellis@eletrotupi.com · 10 days ago 32925689aa843a1fcbe8cb39437fd37fa532cd4d Browse files
Parents 5dc751d
Changed files
1
Additions
+28
Deletions
0
api/tests/setup.ts modified+28
api/tests/setup.ts
1 1
import { vi } from 'vitest'
2 2

3 +
// The database project truncates and repopulates a real database on every run.
4 +
// The container's ambient DATABASE_URL points at orbit_dev, so a vitest
5 +
// invocation that skips the npm scripts' dotenv wrapper would silently wipe the
6 +
// development database. Only a database named like the test one is safe to run
7 +
// against, so anything not ending in `_test` is refused.
8 +
const TEST_DATABASE_SUFFIX = '_test'
9 +

10 +
const databaseNameOf = (url: string | undefined): string => {
11 +
  if (!url) return '(unset)'
12 +

13 +
  try {
14 +
    return new URL(url).pathname.replace(/^\//, '') || '(none)'
15 +
  } catch {
16 +
    return '(unparseable)'
17 +
  }
18 +
}
19 +

20 +
const database = databaseNameOf(process.env.DATABASE_URL)
21 +

22 +
if (!database.endsWith(TEST_DATABASE_SUFFIX)) {
23 +
  throw new Error(
24 +
    `Refusing to run against "${database}": the database project only runs ` +
25 +
      `against a database ending in "${TEST_DATABASE_SUFFIX}" (e.g. ` +
26 +
      'orbit_test). Use `npm test` or `npm run test:coverage`, which load ' +
27 +
      '.env.test.',
28 +
  )
29 +
}
30 +

3 31
// Mock the barrel export used by controllers and most services. `getQueue`
4 32
// returns a stable per-name mock so specs can assert on scheduled jobs via
5 33
// `recordedJobs` from ./mocks/queue
6 34
vi.mock('@app/lib/queue', async () => {
7 35
  const { getQueueMock } = await import('./mocks/queue')
41 69

42 70
// The avatar controller deletes the previous object through the S3 client
43 71
vi.mock('@app/lib/s3', () => ({
44 72
  default: { send: vi.fn().mockResolvedValue({}) },
45 73
}))