diff --git a/MIGRATIONS.md b/MIGRATIONS.md index 316649843..29a201ca4 100644 --- a/MIGRATIONS.md +++ b/MIGRATIONS.md @@ -4,6 +4,16 @@ Breaking changes and upgrade notes for downstream projects. --- +## Jest aborts on a non-test database (2026-11-23) + +- Running jest with a non-test DB now fails instead of running: `scripts/jest.globalSetup.js` throws when the resolved database name does not contain `test`, so no suite runs (before, only the drop was skipped and suites could wipe that database). `globalTeardown` keeps warning and skipping. Run tests through the npm `test*` scripts (`cross-env NODE_ENV=test`). + +### Action for downstream + +1. Run `/update-stack` to pull the change. Nothing else, unless a test config points at a database whose name lacks `test`: rename it. + +--- + ## Organization removal refused while a paid subscription is live (2026-11-19) - Removing an organization whose paid subscription is still `active`, `trialing` or `past_due` now answers **409** with `errorCode: ORGANIZATION_HAS_LIVE_SUBSCRIPTION` and the description `Cancel the subscription of "" before removing it.` Nothing is deleted and nothing is cancelled at the provider. A free organization (no provider subscription), a canceled subscription and a subscription already set to end (at period end, `cancelAtPeriodEnd`, or at a set date, `cancelAt`, as a customer-portal cancel writes) are not affected. diff --git a/README.md b/README.md index 97cb68777..627192807 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,8 @@ npm run test:coverage # Legacy alias: all suites + coverage (local npm run test:parallel-smoke # Regression gate for per-pid test DB isolation (#3515) ``` +Always run tests through the npm `test*` scripts (they set `cross-env NODE_ENV=test`). Jest refuses to start when the resolved database name does not contain `test`, so a bare `npx jest` under a project `NODE_ENV` aborts instead of letting suites wipe that env's database. + Tests are organized per module in `modules/*/tests/`. In CI the test job runs as a 3-way matrix (`unit` / `integration` / `e2e`) in parallel: `unit` and `integration` each upload a Codecov flag, and Codecov merges them server-side to compute combined coverage. e2e tests run as a pure pass/fail gate without coverage upload — they verify product-critical flows, not coverage. The `test:parallel-smoke` script spawns N concurrent jest children against the same mongod and asserts none of them trample each other — gates against accidental regression of the per-pid `NodeTest_${pid}` default in `config/defaults/test.config.js`. Off the critical path in CI (own job), so it never blocks merges. ### Code Quality diff --git a/scripts/jest.dbName.js b/scripts/jest.dbName.js new file mode 100644 index 000000000..eae971b9b --- /dev/null +++ b/scripts/jest.dbName.js @@ -0,0 +1,7 @@ +/** + * Database name of a Mongo URI, read the same way by jest globalSetup and globalTeardown. + * A regex, not `new URL`: the WHATWG parser rejects valid multi-host Mongo URIs. + * @param {string|undefined} uri - the resolved config.db.uri + * @returns {string} the database name, '' when the URI names none + */ +export default (uri) => /^mongodb(?:\+srv)?:\/\/[^/]*\/([^?]*)/.exec(uri ?? '')?.[1] ?? ''; diff --git a/scripts/jest.globalSetup.js b/scripts/jest.globalSetup.js index edca53d89..d14197e76 100644 --- a/scripts/jest.globalSetup.js +++ b/scripts/jest.globalSetup.js @@ -15,26 +15,37 @@ * initialisation — they land in the "protected" set and survive all * per-suite teardown cycles unchanged. * - * Safety guards (#3476): - * 1. Refuse to drop anything when `NODE_ENV !== 'test'`. Protects downstream - * projects that export `NODE_ENV=` in their shell and invoke - * jest directly (e.g. `npx jest`, IDE runners) bypassing the - * `cross-env NODE_ENV=test` wrapper used by the npm `test*` scripts. - * 2. Belt-and-suspenders: also refuse when the resolved DB name does not - * contain `test` (case-insensitive). Catches leaked overrides of - * `config.db.uri` that point at a non-test database. - * - * Both checks log a clear refusal reason and exit without connecting. + * Safety guards (#3476, #4335): + * 1. Abort the whole run (throw) when the resolved DB name does not contain + * `test` (case-insensitive). Integration suites clean collections in + * their hooks, so skipping only our own drop is not enough: a run started + * with `NODE_ENV=` (e.g. `npx jest`, IDE runners) bypassing the + * `cross-env NODE_ENV=test` wrapper of the npm `test*` scripts would let + * every suite wipe that env's database. The check runs outside the + * MongoDB-unreachable catch below so it can never be swallowed. + * 2. When the name is a test DB but `NODE_ENV !== 'test'`, skip the drop and + * the migrations pre-run (log a warning) and let the run go on. */ import mongoose from 'mongoose'; import path from 'path'; import { pathToFileURL } from 'url'; +import dbNameOf from './jest.dbName.js'; /** * Jest global setup entry point. * @returns {Promise} */ export default async () => { + // Guard: resolve the DB first and abort the whole run on a non-test name. + // Deliberately outside any try/catch so the throw reaches jest. + const config = (await import('../config/index.js')).default; + const dbName = dbNameOf(config.db.uri); + if (!/test/i.test(dbName)) { + throw new Error( + `[jest.globalSetup] jest refuses to run against "${dbName}": the database name must contain "test"; run through the npm test scripts (cross-env NODE_ENV=test).`, + ); + } + if (process.env.NODE_ENV !== 'test') { console.warn( `[jest.globalSetup] Refusing to drop DB: NODE_ENV is "${process.env.NODE_ENV}", expected "test". Skipping drop.`, @@ -44,14 +55,6 @@ export default async () => { // 1. Drop the test database (clean-slate guard) try { - const config = (await import('../config/index.js')).default; - const dbName = new URL(config.db.uri).pathname.replace(/^\//, ''); - if (!/test/i.test(dbName)) { - console.warn( - `[jest.globalSetup] Refusing to drop "${dbName}": name does not match /test/i. Aborting.`, - ); - return; - } await mongoose.connect(config.db.uri, config.db.options); try { await mongoose.connection.dropDatabase(); @@ -68,7 +71,6 @@ export default async () => { // Keys set on process.env HERE (before vm contexts) are included in jest's // protectProperties() pass and survive per-suite GlobalProxy teardown. try { - const config = (await import('../config/index.js')).default; if (!Array.isArray(config.files?.mongooseModels)) { console.warn('[jest.globalSetup] migrations pre-run skipped: config.files.mongooseModels is absent or not an array.'); return; diff --git a/scripts/jest.globalTeardown.js b/scripts/jest.globalTeardown.js index b54d2d582..6f764ba76 100644 --- a/scripts/jest.globalTeardown.js +++ b/scripts/jest.globalTeardown.js @@ -5,7 +5,8 @@ * orphan `NodeTest_` database on the local mongod and they accumulate * indefinitely. * - * Safety guards mirror globalSetup: + * Safety guards mirror globalSetup, but only warn and skip (a teardown never + * throws; globalSetup already aborts a run on a non-test DB name, #4335): * 1. Refuse to drop anything when `NODE_ENV !== 'test'`. * 2. Refuse when the resolved DB name does not contain `test` * (case-insensitive). @@ -14,6 +15,7 @@ * developer killed it manually) must not fail the jest exit code. */ import mongoose from 'mongoose'; +import dbNameOf from './jest.dbName.js'; /** * Jest global teardown entry point — drops the test DB resolved from config. @@ -30,7 +32,7 @@ export default async () => { } try { const config = (await import('../config/index.js')).default; - const dbName = new URL(config.db.uri).pathname.replace(/^\//, ''); + const dbName = dbNameOf(config.db.uri); if (!/test/i.test(dbName)) { console.warn( `[jest.globalTeardown] Refusing to drop "${dbName}": name does not match /test/i. Aborting.`, diff --git a/scripts/tests/jest.globalSetup.unit.tests.js b/scripts/tests/jest.globalSetup.unit.tests.js index 2b253daca..b9d1c2342 100644 --- a/scripts/tests/jest.globalSetup.unit.tests.js +++ b/scripts/tests/jest.globalSetup.unit.tests.js @@ -1,5 +1,5 @@ /** - * Unit tests for jest globalSetup safety guards (#3476). + * Unit tests for jest globalSetup safety guards (#3476, #4335). * * The globalSetup runs BEFORE any test suite, so its own behaviour can't be * observed from inside a test. These tests exercise the module as a plain @@ -47,40 +47,55 @@ describe('scripts/jest.globalSetup safety guards', () => { jest.resetModules(); }); - test('refuses to drop when NODE_ENV is not "test" (project env leak)', async () => { + test('throws (aborts the run) when NODE_ENV is a project env resolving a non-test DB', async () => { process.env.NODE_ENV = 'myproject'; + jest.unstable_mockModule('../../config/index.js', () => ({ + default: { db: { uri: 'mongodb://localhost:27017/MyProjectDev' } }, + })); const { default: globalSetup } = await import('../jest.globalSetup.js'); - await globalSetup(); - + await expect(globalSetup()).rejects.toThrow( + 'jest refuses to run against "MyProjectDev": the database name must contain "test"', + ); expect(connect).not.toHaveBeenCalled(); expect(dropDatabase).not.toHaveBeenCalled(); - expect(disconnect).not.toHaveBeenCalled(); - expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('NODE_ENV is "myproject"')); }); - test('refuses to drop when NODE_ENV is undefined', async () => { - delete process.env.NODE_ENV; + test('throws when NODE_ENV=test but the resolved DB name does not contain "test"', async () => { + process.env.NODE_ENV = 'test'; + jest.unstable_mockModule('../../config/index.js', () => ({ + default: { db: { uri: 'mongodb://localhost:27017/ProductionDb' }, files: { mongooseModels: [] } }, + })); const { default: globalSetup } = await import('../jest.globalSetup.js'); - await globalSetup(); - + await expect(globalSetup()).rejects.toThrow('"ProductionDb"'); + expect(connect).not.toHaveBeenCalled(); expect(dropDatabase).not.toHaveBeenCalled(); - expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('NODE_ENV is "undefined"')); }); - test('refuses to drop when resolved DB name does not contain "test"', async () => { - process.env.NODE_ENV = 'test'; + test('skips the drop but lets the run go on when NODE_ENV is not "test" and the DB is a test DB', async () => { + process.env.NODE_ENV = 'myproject'; jest.unstable_mockModule('../../config/index.js', () => ({ - default: { db: { uri: 'mongodb://localhost:27017/ProductionDb' } }, + default: { db: { uri: 'mongodb://localhost:27017/MyProjectTest' } }, })); const { default: globalSetup } = await import('../jest.globalSetup.js'); - await globalSetup(); - + await expect(globalSetup()).resolves.toBeUndefined(); expect(connect).not.toHaveBeenCalled(); expect(dropDatabase).not.toHaveBeenCalled(); - expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Refusing to drop "ProductionDb"')); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('NODE_ENV is "myproject"')); + }); + + test('skips the drop when NODE_ENV is undefined and the DB is a test DB', async () => { + delete process.env.NODE_ENV; + jest.unstable_mockModule('../../config/index.js', () => ({ + default: { db: { uri: 'mongodb://localhost:27017/NodeTest' } }, + })); + const { default: globalSetup } = await import('../jest.globalSetup.js'); + + await expect(globalSetup()).resolves.toBeUndefined(); + expect(dropDatabase).not.toHaveBeenCalled(); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('NODE_ENV is "undefined"')); }); test('drops database when NODE_ENV=test and DB name contains "test" (case-insensitive)', async () => { @@ -102,6 +117,17 @@ describe('scripts/jest.globalSetup safety guards', () => { expect(disconnect.mock.calls.length).toBeGreaterThanOrEqual(2); }); + test('accepts a multi-host URI: skips the drop outside NODE_ENV=test without throwing', async () => { + process.env.NODE_ENV = 'development'; + jest.unstable_mockModule('../../config/index.js', () => ({ + default: { db: { uri: 'mongodb://m1:27017,m2:27017/NodeTest?replicaSet=rs0' }, files: { mongooseModels: [] } }, + })); + const { default: globalSetup } = await import('../jest.globalSetup.js'); + + await expect(globalSetup()).resolves.toBeUndefined(); + expect(dropDatabase).not.toHaveBeenCalled(); + }); + test('swallows errors when MongoDB is unreachable', async () => { process.env.NODE_ENV = 'test'; connect.mockRejectedValueOnce(new Error('ECONNREFUSED')); diff --git a/scripts/tests/jest.globalTeardown.unit.tests.js b/scripts/tests/jest.globalTeardown.unit.tests.js index a7727808b..73860bcc4 100644 --- a/scripts/tests/jest.globalTeardown.unit.tests.js +++ b/scripts/tests/jest.globalTeardown.unit.tests.js @@ -80,6 +80,20 @@ describe('scripts/jest.globalTeardown safety guards', () => { expect(disconnect).toHaveBeenCalledTimes(1); }); + test('drops a multi-host test DB (same name parsing as globalSetup)', async () => { + process.env.NODE_ENV = 'test'; + const uri = 'mongodb://m1:27017,m2:27017/NodeTest_7?replicaSet=rs0'; + jest.unstable_mockModule('../../config/index.js', () => ({ + default: { db: { uri } }, + })); + const { default: globalTeardown } = await import('../jest.globalTeardown.js'); + + await globalTeardown(); + + expect(connect).toHaveBeenCalledWith(uri); + expect(dropDatabase).toHaveBeenCalledTimes(1); + }); + test('swallows errors when MongoDB is unreachable (no failed exit code)', async () => { process.env.NODE_ENV = 'test'; connect.mockRejectedValueOnce(new Error('ECONNREFUSED'));