@geekmidas/testkit 9.0.2 → 10.0.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Factory-CUM2767q.d.cts → Factory-C6W78ulZ.d.mts} +2 -2
- package/dist/{Factory-ClyZLRsO.d.mts.map → Factory-C6W78ulZ.d.mts.map} +1 -1
- package/dist/{Factory-ClyZLRsO.d.mts → Factory-DSEADOaF.d.cts} +2 -2
- package/dist/{Factory-CUM2767q.d.cts.map → Factory-DSEADOaF.d.cts.map} +1 -1
- package/dist/Factory.d.cts +2 -2
- package/dist/Factory.d.mts +2 -2
- package/dist/{KyselyFactory-OMwcuAX_.d.cts → KyselyFactory-Cc2UmOJk.d.mts} +3 -3
- package/dist/{KyselyFactory-CTZmiGI9.d.mts.map → KyselyFactory-Cc2UmOJk.d.mts.map} +1 -1
- package/dist/{KyselyFactory-CTZmiGI9.d.mts → KyselyFactory-DzH0N1zr.d.cts} +3 -3
- package/dist/{KyselyFactory-OMwcuAX_.d.cts.map → KyselyFactory-DzH0N1zr.d.cts.map} +1 -1
- package/dist/KyselyFactory.d.cts +3 -3
- package/dist/KyselyFactory.d.mts +3 -3
- package/dist/{ObjectionFactory-DDrKwAoO.d.mts → ObjectionFactory-BYnPr9ZP.d.mts} +3 -3
- package/dist/{ObjectionFactory-DDrKwAoO.d.mts.map → ObjectionFactory-BYnPr9ZP.d.mts.map} +1 -1
- package/dist/{ObjectionFactory-DvmZVHhe.d.cts → ObjectionFactory-BmKdG0nT.d.cts} +3 -3
- package/dist/{ObjectionFactory-DvmZVHhe.d.cts.map → ObjectionFactory-BmKdG0nT.d.cts.map} +1 -1
- package/dist/ObjectionFactory.d.cts +3 -3
- package/dist/ObjectionFactory.d.mts +3 -3
- package/dist/{VitestKyselyTransactionIsolator-CfSMOFlN.mjs → VitestKyselyTransactionIsolator-1Saieke7.mjs} +10 -3
- package/dist/VitestKyselyTransactionIsolator-1Saieke7.mjs.map +1 -0
- package/dist/{VitestKyselyTransactionIsolator-0CqOsuc9.cjs → VitestKyselyTransactionIsolator-BjJSXryR.cjs} +10 -3
- package/dist/VitestKyselyTransactionIsolator-BjJSXryR.cjs.map +1 -0
- package/dist/{VitestKyselyTransactionIsolator-CduJlHoT.d.cts → VitestKyselyTransactionIsolator-CwlTo6yf.d.mts} +8 -3
- package/dist/VitestKyselyTransactionIsolator-CwlTo6yf.d.mts.map +1 -0
- package/dist/{VitestKyselyTransactionIsolator-Cswnnj0k.d.mts → VitestKyselyTransactionIsolator-DJasVuIZ.d.cts} +8 -3
- package/dist/VitestKyselyTransactionIsolator-DJasVuIZ.d.cts.map +1 -0
- package/dist/VitestKyselyTransactionIsolator.cjs +2 -2
- package/dist/VitestKyselyTransactionIsolator.d.cts +2 -2
- package/dist/VitestKyselyTransactionIsolator.d.mts +2 -2
- package/dist/VitestKyselyTransactionIsolator.mjs +2 -2
- package/dist/{VitestObjectionTransactionIsolator-CNo40EdC.mjs → VitestObjectionTransactionIsolator-B_VSWFum.mjs} +2 -2
- package/dist/{VitestObjectionTransactionIsolator-CNo40EdC.mjs.map → VitestObjectionTransactionIsolator-B_VSWFum.mjs.map} +1 -1
- package/dist/{VitestObjectionTransactionIsolator-BXoR6xdG.d.cts → VitestObjectionTransactionIsolator-CTTjvTPO.d.cts} +2 -2
- package/dist/{VitestObjectionTransactionIsolator-BXoR6xdG.d.cts.map → VitestObjectionTransactionIsolator-CTTjvTPO.d.cts.map} +1 -1
- package/dist/{VitestObjectionTransactionIsolator-x6hY5j4u.d.mts → VitestObjectionTransactionIsolator-CyZG6nq4.d.mts} +2 -2
- package/dist/{VitestObjectionTransactionIsolator-x6hY5j4u.d.mts.map → VitestObjectionTransactionIsolator-CyZG6nq4.d.mts.map} +1 -1
- package/dist/{VitestObjectionTransactionIsolator-B5J9jjKq.cjs → VitestObjectionTransactionIsolator-DDoJTu7e.cjs} +2 -2
- package/dist/{VitestObjectionTransactionIsolator-B5J9jjKq.cjs.map → VitestObjectionTransactionIsolator-DDoJTu7e.cjs.map} +1 -1
- package/dist/VitestObjectionTransactionIsolator.cjs +2 -2
- package/dist/VitestObjectionTransactionIsolator.d.cts +2 -2
- package/dist/VitestObjectionTransactionIsolator.d.mts +2 -2
- package/dist/VitestObjectionTransactionIsolator.mjs +2 -2
- package/dist/{VitestTransactionIsolator-BNWJqh9f.d.mts → VitestTransactionIsolator-BLaw80cx.d.mts} +20 -4
- package/dist/VitestTransactionIsolator-BLaw80cx.d.mts.map +1 -0
- package/dist/{VitestTransactionIsolator-D6ZxLWys.mjs → VitestTransactionIsolator-CvwPecpl.mjs} +17 -4
- package/dist/VitestTransactionIsolator-CvwPecpl.mjs.map +1 -0
- package/dist/{VitestTransactionIsolator-CtZaOUjH.cjs → VitestTransactionIsolator-DyiX-QtK.cjs} +17 -4
- package/dist/VitestTransactionIsolator-DyiX-QtK.cjs.map +1 -0
- package/dist/{VitestTransactionIsolator-CSroc7Df.d.cts → VitestTransactionIsolator-glcxyS_R.d.cts} +20 -4
- package/dist/VitestTransactionIsolator-glcxyS_R.d.cts.map +1 -0
- package/dist/VitestTransactionIsolator.cjs +1 -1
- package/dist/VitestTransactionIsolator.d.cts +2 -2
- package/dist/VitestTransactionIsolator.d.mts +2 -2
- package/dist/VitestTransactionIsolator.mjs +1 -1
- package/dist/better-auth.d.cts +2 -2
- package/dist/better-auth.d.mts +2 -2
- package/dist/{faker-BcjUfHxx.d.mts → faker-D9gz7KjY.d.mts} +3 -3
- package/dist/{faker-BcjUfHxx.d.mts.map → faker-D9gz7KjY.d.mts.map} +1 -1
- package/dist/{faker-zVCm31nU.d.cts → faker-km9UhOS6.d.cts} +3 -3
- package/dist/{faker-zVCm31nU.d.cts.map → faker-km9UhOS6.d.cts.map} +1 -1
- package/dist/faker.d.cts +1 -1
- package/dist/faker.d.mts +1 -1
- package/dist/kysely.cjs +2 -2
- package/dist/kysely.d.cts +5 -5
- package/dist/kysely.d.mts +5 -5
- package/dist/kysely.mjs +2 -2
- package/dist/objection.cjs +2 -2
- package/dist/objection.d.cts +5 -5
- package/dist/objection.d.mts +5 -5
- package/dist/objection.mjs +2 -2
- package/dist/requestContext.cjs +1 -1
- package/dist/requestContext.d.cts +1 -1
- package/dist/requestContext.d.mts +1 -1
- package/dist/requestContext.mjs +1 -1
- package/package.json +10 -7
- package/CHANGELOG.md +0 -151
- package/dist/VitestKyselyTransactionIsolator-0CqOsuc9.cjs.map +0 -1
- package/dist/VitestKyselyTransactionIsolator-CduJlHoT.d.cts.map +0 -1
- package/dist/VitestKyselyTransactionIsolator-CfSMOFlN.mjs.map +0 -1
- package/dist/VitestKyselyTransactionIsolator-Cswnnj0k.d.mts.map +0 -1
- package/dist/VitestTransactionIsolator-BNWJqh9f.d.mts.map +0 -1
- package/dist/VitestTransactionIsolator-CSroc7Df.d.cts.map +0 -1
- package/dist/VitestTransactionIsolator-CtZaOUjH.cjs.map +0 -1
- package/dist/VitestTransactionIsolator-D6ZxLWys.mjs.map +0 -1
- package/src/Factory.ts +0 -174
- package/src/KyselyFactory.ts +0 -391
- package/src/ObjectionFactory.ts +0 -412
- package/src/PostgresKyselyMigrator.ts +0 -104
- package/src/PostgresMigrator.ts +0 -193
- package/src/PostgresObjectionMigrator.ts +0 -138
- package/src/VitestKyselyTransactionIsolator.ts +0 -72
- package/src/VitestObjectionTransactionIsolator.ts +0 -75
- package/src/VitestTransactionIsolator.ts +0 -348
- package/src/__tests__/Factory.spec.ts +0 -178
- package/src/__tests__/KyselyFactory.spec.ts +0 -458
- package/src/__tests__/ObjectionFactory.spec.ts +0 -586
- package/src/__tests__/PostgresKyselyMigrator.spec.ts +0 -794
- package/src/__tests__/PostgresMigrator.spec.ts +0 -471
- package/src/__tests__/PostgresObjectionMigrator.spec.ts +0 -634
- package/src/__tests__/VitestObjectionTransactionIsolator.spec.ts +0 -138
- package/src/__tests__/benchmark.spec.ts +0 -140
- package/src/__tests__/better-auth.spec.ts +0 -21
- package/src/__tests__/faker.spec.ts +0 -231
- package/src/__tests__/initScript.spec.ts +0 -332
- package/src/__tests__/integration.spec.ts +0 -610
- package/src/__tests__/requestContext.spec.ts +0 -113
- package/src/__tests__/utilities.spec.ts +0 -211
- package/src/aws.ts +0 -131
- package/src/benchmark.ts +0 -48
- package/src/better-auth.ts +0 -310
- package/src/faker.ts +0 -349
- package/src/helpers.ts +0 -45
- package/src/initScript.ts +0 -122
- package/src/kysely.ts +0 -166
- package/src/logger.ts +0 -18
- package/src/objection.ts +0 -157
- package/src/os/directory.ts +0 -26
- package/src/os/index.ts +0 -1
- package/src/requestContext.ts +0 -119
- package/src/timer.ts +0 -3
- package/test/globalSetup.ts +0 -54
- package/test/helpers.ts +0 -268
- package/test/migrations/1749664623372_user.ts +0 -22
- package/tsconfig.json +0 -9
- package/vitest.config.ts +0 -8
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
import type { Knex } from 'knex';
|
|
2
|
-
import { PostgresMigrator } from './PostgresMigrator';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Default logger instance for migration operations.
|
|
6
|
-
*/
|
|
7
|
-
const logger = console;
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* PostgreSQL migrator implementation for Objection.js ORM with Knex.
|
|
11
|
-
* Extends PostgresMigrator to provide Knex-specific migration functionality.
|
|
12
|
-
* Automatically creates test databases and applies migrations for testing environments.
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* ```typescript
|
|
16
|
-
* import knex from 'knex';
|
|
17
|
-
* import { PostgresObjectionMigrator } from '@geekmidas/testkit';
|
|
18
|
-
*
|
|
19
|
-
* // Create Knex instance
|
|
20
|
-
* const db = knex({
|
|
21
|
-
* client: 'pg',
|
|
22
|
-
* connection: uri,
|
|
23
|
-
* migrations: {
|
|
24
|
-
* directory: path.join(__dirname, 'migrations'),
|
|
25
|
-
* extension: 'ts'
|
|
26
|
-
* }
|
|
27
|
-
* });
|
|
28
|
-
*
|
|
29
|
-
* // Create and use migrator
|
|
30
|
-
* const migrator = new PostgresObjectionMigrator({
|
|
31
|
-
* uri: 'postgresql://localhost:5432/test_db',
|
|
32
|
-
* knex: db
|
|
33
|
-
* });
|
|
34
|
-
*
|
|
35
|
-
* const cleanup = await migrator.start();
|
|
36
|
-
* // Run tests...
|
|
37
|
-
* await cleanup();
|
|
38
|
-
* ```
|
|
39
|
-
*/
|
|
40
|
-
export class PostgresObjectionMigrator extends PostgresMigrator {
|
|
41
|
-
/**
|
|
42
|
-
* Creates a new PostgresObjectionMigrator instance.
|
|
43
|
-
*
|
|
44
|
-
* @param options - Configuration options
|
|
45
|
-
* @param options.uri - PostgreSQL connection URI
|
|
46
|
-
* @param options.knex - Knex database instance configured with migrations
|
|
47
|
-
*/
|
|
48
|
-
constructor(
|
|
49
|
-
private options: {
|
|
50
|
-
uri: string;
|
|
51
|
-
knex: Knex;
|
|
52
|
-
},
|
|
53
|
-
) {
|
|
54
|
-
super(options.uri);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Executes Knex migrations to the latest version.
|
|
59
|
-
* Implements the abstract migrate() method from PostgresMigrator.
|
|
60
|
-
*
|
|
61
|
-
* @throws Error if migrations fail to apply
|
|
62
|
-
* @returns Promise that resolves when all migrations are applied
|
|
63
|
-
*/
|
|
64
|
-
async migrate(): Promise<void> {
|
|
65
|
-
try {
|
|
66
|
-
// Run migrations to latest
|
|
67
|
-
const [batchNo, migrations] = await this.options.knex.migrate.latest();
|
|
68
|
-
|
|
69
|
-
if (migrations.length > 0) {
|
|
70
|
-
logger.log(
|
|
71
|
-
`Applied batch ${batchNo} with ${migrations.length} migrations:`,
|
|
72
|
-
);
|
|
73
|
-
migrations.forEach((migration: string) => {
|
|
74
|
-
logger.log(` - ${migration}`);
|
|
75
|
-
});
|
|
76
|
-
} else {
|
|
77
|
-
logger.log('No pending migrations to apply');
|
|
78
|
-
}
|
|
79
|
-
} catch (error) {
|
|
80
|
-
logger.error('Failed to apply migrations:', error);
|
|
81
|
-
throw error;
|
|
82
|
-
} finally {
|
|
83
|
-
// Always destroy the connection pool
|
|
84
|
-
await this.options.knex.destroy();
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* Rolls back the last batch of migrations.
|
|
90
|
-
* Useful for testing migration rollback scenarios.
|
|
91
|
-
*
|
|
92
|
-
* @returns Promise that resolves when rollback is complete
|
|
93
|
-
*/
|
|
94
|
-
async rollback(): Promise<void> {
|
|
95
|
-
try {
|
|
96
|
-
const [batchNo, migrations] = await this.options.knex.migrate.rollback();
|
|
97
|
-
|
|
98
|
-
if (migrations.length > 0) {
|
|
99
|
-
logger.log(
|
|
100
|
-
`Rolled back batch ${batchNo} with ${migrations.length} migrations:`,
|
|
101
|
-
);
|
|
102
|
-
migrations.forEach((migration: string) => {
|
|
103
|
-
logger.log(` - ${migration}`);
|
|
104
|
-
});
|
|
105
|
-
} else {
|
|
106
|
-
logger.log('No migrations to rollback');
|
|
107
|
-
}
|
|
108
|
-
} catch (error) {
|
|
109
|
-
logger.error('Failed to rollback migrations:', error);
|
|
110
|
-
throw error;
|
|
111
|
-
} finally {
|
|
112
|
-
await this.options.knex.destroy();
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* Gets the current migration status.
|
|
118
|
-
* Returns information about completed and pending migrations.
|
|
119
|
-
*
|
|
120
|
-
* @returns Promise with migration status information
|
|
121
|
-
*/
|
|
122
|
-
async status(): Promise<{
|
|
123
|
-
completed: string[];
|
|
124
|
-
pending: string[];
|
|
125
|
-
}> {
|
|
126
|
-
try {
|
|
127
|
-
const completed = await this.options.knex.migrate.list();
|
|
128
|
-
const [, pending] = await this.options.knex.migrate.currentVersion();
|
|
129
|
-
|
|
130
|
-
return {
|
|
131
|
-
completed: Array.isArray(completed[0]) ? completed[0] : [],
|
|
132
|
-
pending: Array.isArray(pending) ? pending : [],
|
|
133
|
-
};
|
|
134
|
-
} finally {
|
|
135
|
-
await this.options.knex.destroy();
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
}
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import type { Kysely, Transaction } from 'kysely';
|
|
2
|
-
import {
|
|
3
|
-
type IsolationLevel,
|
|
4
|
-
VitestPostgresTransactionIsolator,
|
|
5
|
-
} from './VitestTransactionIsolator';
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Kysely-specific implementation of the Vitest transaction isolator.
|
|
9
|
-
* Provides automatic transaction rollback for test isolation using Kysely's transaction API.
|
|
10
|
-
* Each test runs within a database transaction that is rolled back after completion,
|
|
11
|
-
* ensuring a clean state between tests without the overhead of recreating data.
|
|
12
|
-
*
|
|
13
|
-
* @template Database - The database schema type
|
|
14
|
-
*
|
|
15
|
-
* @example
|
|
16
|
-
* ```typescript
|
|
17
|
-
* import { VitestKyselyTransactionIsolator } from '@geekmidas/testkit';
|
|
18
|
-
* import { db } from './database';
|
|
19
|
-
*
|
|
20
|
-
* // Create isolator instance
|
|
21
|
-
* const isolator = new VitestKyselyTransactionIsolator<Database>();
|
|
22
|
-
*
|
|
23
|
-
* // In your test setup
|
|
24
|
-
* beforeEach(async () => {
|
|
25
|
-
* await isolator.start(db);
|
|
26
|
-
* });
|
|
27
|
-
*
|
|
28
|
-
* afterEach(async () => {
|
|
29
|
-
* await isolator.rollback();
|
|
30
|
-
* });
|
|
31
|
-
*
|
|
32
|
-
* // Tests run in isolated transactions
|
|
33
|
-
* it('should create user', async () => {
|
|
34
|
-
* const user = await db.insertInto('users')
|
|
35
|
-
* .values({ name: 'Test User' })
|
|
36
|
-
* .returningAll()
|
|
37
|
-
* .executeTakeFirst();
|
|
38
|
-
*
|
|
39
|
-
* expect(user).toBeDefined();
|
|
40
|
-
* // This data will be rolled back after the test
|
|
41
|
-
* });
|
|
42
|
-
* ```
|
|
43
|
-
*/
|
|
44
|
-
export class VitestKyselyTransactionIsolator<
|
|
45
|
-
Database,
|
|
46
|
-
> extends VitestPostgresTransactionIsolator<
|
|
47
|
-
Kysely<Database>,
|
|
48
|
-
Transaction<Database>
|
|
49
|
-
> {
|
|
50
|
-
async destroy(_conn: Kysely<Database>): Promise<void> {
|
|
51
|
-
// return conn.destroy();
|
|
52
|
-
}
|
|
53
|
-
/**
|
|
54
|
-
* Creates a Kysely transaction with the specified isolation level.
|
|
55
|
-
* Implements the abstract transact method from VitestPostgresTransactionIsolator.
|
|
56
|
-
*
|
|
57
|
-
* @param conn - The Kysely database connection
|
|
58
|
-
* @param level - The transaction isolation level
|
|
59
|
-
* @param fn - The function to execute within the transaction
|
|
60
|
-
* @returns Promise that resolves when the transaction completes
|
|
61
|
-
*/
|
|
62
|
-
async transact(
|
|
63
|
-
conn: Kysely<Database>,
|
|
64
|
-
level: IsolationLevel,
|
|
65
|
-
fn: (trx: Transaction<Database>) => Promise<void>,
|
|
66
|
-
): Promise<void> {
|
|
67
|
-
const isolationLevel =
|
|
68
|
-
level.toLocaleLowerCase() as Lowercase<IsolationLevel>;
|
|
69
|
-
await conn.transaction().setIsolationLevel(isolationLevel).execute(fn);
|
|
70
|
-
}
|
|
71
|
-
// Implement any Kysely-specific transaction logic here
|
|
72
|
-
}
|
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import type { Knex } from 'knex';
|
|
2
|
-
import {
|
|
3
|
-
type IsolationLevel,
|
|
4
|
-
VitestPostgresTransactionIsolator,
|
|
5
|
-
} from './VitestTransactionIsolator';
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Objection.js-specific implementation of the Vitest transaction isolator.
|
|
9
|
-
* Provides automatic transaction rollback for test isolation using Objection.js and Knex transaction API.
|
|
10
|
-
* Each test runs within a database transaction that is rolled back after completion,
|
|
11
|
-
* ensuring a clean state between tests without the overhead of recreating data.
|
|
12
|
-
*
|
|
13
|
-
* @example
|
|
14
|
-
* ```typescript
|
|
15
|
-
* import { VitestObjectionTransactionIsolator } from '@geekmidas/testkit';
|
|
16
|
-
* import { knex } from './database';
|
|
17
|
-
* import { User } from './models';
|
|
18
|
-
* import { test } from 'vitest';
|
|
19
|
-
*
|
|
20
|
-
* // Create isolator instance
|
|
21
|
-
* const isolator = new VitestObjectionTransactionIsolator(test);
|
|
22
|
-
*
|
|
23
|
-
* // Use with wrapped test API
|
|
24
|
-
* const isolatedTest = isolator.wrapVitestWithTransaction(knex);
|
|
25
|
-
*
|
|
26
|
-
* isolatedTest('should create user', async ({ trx }) => {
|
|
27
|
-
* const user = await User.query(trx)
|
|
28
|
-
* .insert({ name: 'Test User' });
|
|
29
|
-
*
|
|
30
|
-
* expect(user).toBeDefined();
|
|
31
|
-
* // This data will be rolled back after the test
|
|
32
|
-
* });
|
|
33
|
-
* ```
|
|
34
|
-
*/
|
|
35
|
-
export class VitestObjectionTransactionIsolator extends VitestPostgresTransactionIsolator<
|
|
36
|
-
Knex,
|
|
37
|
-
Knex.Transaction
|
|
38
|
-
> {
|
|
39
|
-
async destroy(_conn: Knex<any, any[]>): Promise<void> {}
|
|
40
|
-
/**
|
|
41
|
-
* Creates a Knex transaction with the specified isolation level.
|
|
42
|
-
* Implements the abstract transact method from VitestPostgresTransactionIsolator.
|
|
43
|
-
* This transaction can be used with Objection.js models via Model.query(trx).
|
|
44
|
-
*
|
|
45
|
-
* @param conn - The Knex database connection
|
|
46
|
-
* @param level - The transaction isolation level
|
|
47
|
-
* @param fn - The function to execute within the transaction
|
|
48
|
-
* @returns Promise that resolves when the transaction completes
|
|
49
|
-
*
|
|
50
|
-
* @example
|
|
51
|
-
* ```typescript
|
|
52
|
-
* await isolator.transact(knex, IsolationLevel.REPEATABLE_READ, async (trx) => {
|
|
53
|
-
* // Use transaction with Objection models
|
|
54
|
-
* await User.query(trx).insert({ name: 'Test' });
|
|
55
|
-
* await Post.query(trx).where('userId', user.id).delete();
|
|
56
|
-
* });
|
|
57
|
-
* ```
|
|
58
|
-
*/
|
|
59
|
-
async transact(
|
|
60
|
-
connection: Knex,
|
|
61
|
-
level: IsolationLevel,
|
|
62
|
-
fn: (trx: Knex.Transaction) => Promise<void>,
|
|
63
|
-
): Promise<void> {
|
|
64
|
-
const isolationLevel = level.toLowerCase() as Lowercase<IsolationLevel>;
|
|
65
|
-
|
|
66
|
-
await connection.transaction(
|
|
67
|
-
async (trx) => {
|
|
68
|
-
await fn(trx);
|
|
69
|
-
},
|
|
70
|
-
{
|
|
71
|
-
isolationLevel,
|
|
72
|
-
},
|
|
73
|
-
);
|
|
74
|
-
}
|
|
75
|
-
}
|
|
@@ -1,348 +0,0 @@
|
|
|
1
|
-
import type { TestAPI } from 'vitest';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Type definition for test fixtures that provide transaction access.
|
|
5
|
-
* Used with Vitest's test.extend() API to inject transactions into tests.
|
|
6
|
-
*
|
|
7
|
-
* @template Transaction - The transaction type specific to the database driver
|
|
8
|
-
* @template Extended - Additional context properties provided by the extend function
|
|
9
|
-
*/
|
|
10
|
-
export interface DatabaseFixtures<Transaction, _Extended = object> {
|
|
11
|
-
/**
|
|
12
|
-
* The database transaction available to the test.
|
|
13
|
-
* All database operations should use this transaction to ensure proper rollback.
|
|
14
|
-
*/
|
|
15
|
-
trx: Transaction;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Combined fixtures type that merges the base transaction fixture with extended context.
|
|
20
|
-
*/
|
|
21
|
-
export type ExtendedDatabaseFixtures<
|
|
22
|
-
Transaction,
|
|
23
|
-
Extended = object,
|
|
24
|
-
> = DatabaseFixtures<Transaction> & Extended;
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Function type for extending test context with additional properties.
|
|
28
|
-
* Receives the transaction and returns additional context to be merged with { trx }.
|
|
29
|
-
*
|
|
30
|
-
* @template Transaction - The transaction type
|
|
31
|
-
* @template Extended - The type of additional context to provide
|
|
32
|
-
*
|
|
33
|
-
* @example
|
|
34
|
-
* ```typescript
|
|
35
|
-
* const extendContext: ExtendContextFn<Transaction<DB>, { factory: KyselyFactory }> =
|
|
36
|
-
* (trx) => ({ factory: new KyselyFactory(builders, seeds, trx) });
|
|
37
|
-
* ```
|
|
38
|
-
*/
|
|
39
|
-
export type ExtendContextFn<Transaction, Extended> = (
|
|
40
|
-
trx: Transaction,
|
|
41
|
-
) => Extended | Promise<Extended>;
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* PostgreSQL transaction isolation levels.
|
|
45
|
-
* Controls the visibility of concurrent transactions.
|
|
46
|
-
*
|
|
47
|
-
* @see https://www.postgresql.org/docs/current/transaction-iso.html
|
|
48
|
-
*/
|
|
49
|
-
export enum IsolationLevel {
|
|
50
|
-
/**
|
|
51
|
-
* Lowest isolation level. Allows dirty reads.
|
|
52
|
-
* Not recommended for testing.
|
|
53
|
-
*/
|
|
54
|
-
READ_UNCOMMITTED = 'READ UNCOMMITTED',
|
|
55
|
-
/**
|
|
56
|
-
* Default PostgreSQL isolation level.
|
|
57
|
-
* Prevents dirty reads but allows non-repeatable reads.
|
|
58
|
-
*/
|
|
59
|
-
READ_COMMITTED = 'READ COMMITTED',
|
|
60
|
-
/**
|
|
61
|
-
* Prevents dirty reads and non-repeatable reads.
|
|
62
|
-
* Recommended for most test scenarios.
|
|
63
|
-
*/
|
|
64
|
-
REPEATABLE_READ = 'REPEATABLE READ',
|
|
65
|
-
/**
|
|
66
|
-
* Highest isolation level. Prevents all phenomena.
|
|
67
|
-
* May cause performance overhead in tests.
|
|
68
|
-
*/
|
|
69
|
-
SERIALIZABLE = 'SERIALIZABLE',
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* Abstract base class for implementing database transaction isolation in Vitest tests.
|
|
74
|
-
* Provides automatic transaction rollback after each test to maintain test isolation.
|
|
75
|
-
* Subclasses must implement the transact() method for their specific database driver.
|
|
76
|
-
*
|
|
77
|
-
* @template TConn - The database connection type
|
|
78
|
-
* @template Transaction - The transaction type
|
|
79
|
-
*
|
|
80
|
-
* @example
|
|
81
|
-
* ```typescript
|
|
82
|
-
* // Implement for your database driver
|
|
83
|
-
* class MyDatabaseIsolator extends VitestPostgresTransactionIsolator<MyDB, MyTx> {
|
|
84
|
-
* async transact(conn: MyDB, level: IsolationLevel, fn: (tx: MyTx) => Promise<void>) {
|
|
85
|
-
* await conn.transaction(level, fn);
|
|
86
|
-
* }
|
|
87
|
-
* }
|
|
88
|
-
*
|
|
89
|
-
* // Use in tests
|
|
90
|
-
* const isolator = new MyDatabaseIsolator(test);
|
|
91
|
-
* const isolatedTest = isolator.wrapVitestWithTransaction(db);
|
|
92
|
-
*
|
|
93
|
-
* isolatedTest('should create user', async ({ trx }) => {
|
|
94
|
-
* await trx.insert('users', { name: 'Test' });
|
|
95
|
-
* // Data is automatically rolled back after test
|
|
96
|
-
* });
|
|
97
|
-
* ```
|
|
98
|
-
*/
|
|
99
|
-
export abstract class VitestPostgresTransactionIsolator<TConn, Transaction> {
|
|
100
|
-
/**
|
|
101
|
-
* Abstract method to create a transaction with the specified isolation level.
|
|
102
|
-
* Must be implemented by subclasses for specific database drivers.
|
|
103
|
-
*
|
|
104
|
-
* @param conn - The database connection
|
|
105
|
-
* @param isolationLevel - The transaction isolation level
|
|
106
|
-
* @param fn - The function to execute within the transaction
|
|
107
|
-
* @returns Promise that resolves when the transaction completes
|
|
108
|
-
*/
|
|
109
|
-
abstract transact(
|
|
110
|
-
conn: TConn,
|
|
111
|
-
isolationLevel: IsolationLevel,
|
|
112
|
-
fn: (trx: Transaction) => Promise<void>,
|
|
113
|
-
): Promise<void>;
|
|
114
|
-
|
|
115
|
-
abstract destroy(conn: TConn): Promise<void>;
|
|
116
|
-
/**
|
|
117
|
-
* Creates a new VitestPostgresTransactionIsolator instance.
|
|
118
|
-
*
|
|
119
|
-
* @param api - The Vitest test API (usually the `test` export from vitest)
|
|
120
|
-
*/
|
|
121
|
-
constructor(private readonly api: TestAPI) {}
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* Creates a wrapped version of Vitest's test API that provides transaction isolation.
|
|
125
|
-
* Each test will run within a database transaction that is automatically rolled back.
|
|
126
|
-
*
|
|
127
|
-
* @param options - Configuration options for transaction wrapping
|
|
128
|
-
* @returns A wrapped test API with transaction support
|
|
129
|
-
*
|
|
130
|
-
* @example
|
|
131
|
-
* ```typescript
|
|
132
|
-
* const isolatedTest = isolator.wrapVitestWithTransaction({
|
|
133
|
-
* connection: db,
|
|
134
|
-
* setup: async (trx) => {
|
|
135
|
-
* await trx.insert('settings', { key: 'test', value: 'true' });
|
|
136
|
-
* },
|
|
137
|
-
* fixtures: {
|
|
138
|
-
* factory: (trx) => new Factory(trx),
|
|
139
|
-
* },
|
|
140
|
-
* });
|
|
141
|
-
*
|
|
142
|
-
* isolatedTest('test with transaction', async ({ trx, factory }) => {
|
|
143
|
-
* const user = await factory.insert('user', { name: 'Test' });
|
|
144
|
-
* expect(user).toBeDefined();
|
|
145
|
-
* });
|
|
146
|
-
* ```
|
|
147
|
-
*/
|
|
148
|
-
wrapVitestWithTransaction<Extended extends Record<string, unknown> = {}>(
|
|
149
|
-
options: TransactionWrapperOptions<TConn, Transaction, Extended>,
|
|
150
|
-
) {
|
|
151
|
-
const {
|
|
152
|
-
connection,
|
|
153
|
-
setup,
|
|
154
|
-
isolationLevel = IsolationLevel.REPEATABLE_READ,
|
|
155
|
-
fixtures,
|
|
156
|
-
} = options;
|
|
157
|
-
|
|
158
|
-
// Build fixture definitions for additional fixtures that depend on trx
|
|
159
|
-
const additionalFixtures: Record<string, unknown> = {};
|
|
160
|
-
if (fixtures) {
|
|
161
|
-
for (const [key, creator] of Object.entries(fixtures)) {
|
|
162
|
-
additionalFixtures[key] = async (
|
|
163
|
-
{ trx }: { trx: Transaction },
|
|
164
|
-
use: (value: unknown) => Promise<void>,
|
|
165
|
-
) => {
|
|
166
|
-
const value = await (creator as (trx: Transaction) => unknown)(trx);
|
|
167
|
-
await use(value);
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
type CombinedFixtures = DatabaseFixtures<Transaction> & Extended;
|
|
173
|
-
|
|
174
|
-
// Cast to bypass Vitest's strict fixture typing which can't infer
|
|
175
|
-
// dynamically built fixture objects
|
|
176
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
177
|
-
const api = this.api as TestAPI & {
|
|
178
|
-
extend: <T>(fixtures: any) => TestAPI<T>;
|
|
179
|
-
};
|
|
180
|
-
|
|
181
|
-
return api.extend<CombinedFixtures>({
|
|
182
|
-
// This fixture automatically provides a transaction to each test
|
|
183
|
-
// biome-ignore lint/correctness/noEmptyPattern: this has to be like this to satisfy Biome
|
|
184
|
-
trx: async ({}: {}, use: (value: Transaction) => Promise<void>) => {
|
|
185
|
-
// Create a custom error class for rollback
|
|
186
|
-
class TestRollback extends Error {
|
|
187
|
-
constructor() {
|
|
188
|
-
super('Test rollback');
|
|
189
|
-
this.name = 'TestRollback';
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
let testError: Error | undefined;
|
|
194
|
-
const conn = await connection();
|
|
195
|
-
try {
|
|
196
|
-
await this.transact(conn, isolationLevel, async (transaction) => {
|
|
197
|
-
try {
|
|
198
|
-
// Provide the transaction to the test
|
|
199
|
-
await setup?.(transaction);
|
|
200
|
-
await use(transaction);
|
|
201
|
-
} catch (error) {
|
|
202
|
-
// Capture any test errors
|
|
203
|
-
testError = error as Error;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
// Always throw to trigger rollback
|
|
207
|
-
throw new TestRollback();
|
|
208
|
-
});
|
|
209
|
-
} catch (error) {
|
|
210
|
-
// Only rethrow if it's not our rollback error
|
|
211
|
-
if (!(error instanceof TestRollback)) {
|
|
212
|
-
throw error;
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
// If the test had an error, throw it now
|
|
216
|
-
if (testError) {
|
|
217
|
-
throw testError;
|
|
218
|
-
}
|
|
219
|
-
} finally {
|
|
220
|
-
await this.destroy(conn);
|
|
221
|
-
}
|
|
222
|
-
},
|
|
223
|
-
...additionalFixtures,
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
export type DatabaseConnectionFn<Conn> = () => Conn | Promise<Conn>;
|
|
229
|
-
export type DatabaseConnection<Conn> = DatabaseConnectionFn<Conn>;
|
|
230
|
-
|
|
231
|
-
/**
|
|
232
|
-
* Options for wrapping Vitest tests with database transaction isolation.
|
|
233
|
-
*/
|
|
234
|
-
export interface TransactionWrapperOptions<
|
|
235
|
-
TConn,
|
|
236
|
-
Transaction,
|
|
237
|
-
Extended extends Record<string, unknown> = {},
|
|
238
|
-
> {
|
|
239
|
-
/** Function that creates or returns a database connection */
|
|
240
|
-
connection: DatabaseConnection<TConn>;
|
|
241
|
-
/** Optional setup function to run within the transaction before each test */
|
|
242
|
-
setup?: (trx: Transaction) => Promise<void>;
|
|
243
|
-
/** Transaction isolation level (defaults to REPEATABLE_READ) */
|
|
244
|
-
isolationLevel?: IsolationLevel;
|
|
245
|
-
/** Additional fixtures that depend on the transaction */
|
|
246
|
-
fixtures?: FixtureCreators<Transaction, Extended>;
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
/**
|
|
250
|
-
* Type for fixture creator functions that depend on the transaction.
|
|
251
|
-
* Each function receives the transaction and returns the fixture value.
|
|
252
|
-
*/
|
|
253
|
-
export type FixtureCreators<
|
|
254
|
-
Transaction,
|
|
255
|
-
Extended extends Record<string, unknown>,
|
|
256
|
-
> = {
|
|
257
|
-
[K in keyof Extended]: (
|
|
258
|
-
trx: Transaction,
|
|
259
|
-
) => Extended[K] | Promise<Extended[K]>;
|
|
260
|
-
};
|
|
261
|
-
|
|
262
|
-
/**
|
|
263
|
-
* The test API returned by extendWithFixtures.
|
|
264
|
-
* Provides access to both the transaction (trx) and all extended fixtures.
|
|
265
|
-
*
|
|
266
|
-
* @template Transaction - The transaction type
|
|
267
|
-
* @template Extended - The type of additional fixtures provided
|
|
268
|
-
* @template BaseTest - The base wrapped test type
|
|
269
|
-
*/
|
|
270
|
-
export type TestWithExtendedFixtures<
|
|
271
|
-
Transaction,
|
|
272
|
-
Extended extends Record<string, unknown>,
|
|
273
|
-
BaseTest extends ReturnType<TestAPI['extend']> = ReturnType<
|
|
274
|
-
TestAPI['extend']
|
|
275
|
-
>,
|
|
276
|
-
> = BaseTest & {
|
|
277
|
-
<C extends object>(
|
|
278
|
-
name: string,
|
|
279
|
-
fn: (
|
|
280
|
-
context: DatabaseFixtures<Transaction> & Extended & C,
|
|
281
|
-
) => Promise<void>,
|
|
282
|
-
): void;
|
|
283
|
-
<C extends object>(
|
|
284
|
-
name: string,
|
|
285
|
-
options: object,
|
|
286
|
-
fn: (
|
|
287
|
-
context: DatabaseFixtures<Transaction> & Extended & C,
|
|
288
|
-
) => Promise<void>,
|
|
289
|
-
): void;
|
|
290
|
-
};
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* Extends a wrapped test API with additional fixtures that depend on the transaction.
|
|
294
|
-
* This allows composing test context with factories, repositories, or other helpers.
|
|
295
|
-
*
|
|
296
|
-
* @template Transaction - The transaction type
|
|
297
|
-
* @template Extended - The type of additional context to provide
|
|
298
|
-
* @param wrappedTest - The base wrapped test from wrapVitestWithTransaction
|
|
299
|
-
* @param fixtures - Object mapping fixture names to creator functions
|
|
300
|
-
* @returns An extended test API with both trx and the additional fixtures
|
|
301
|
-
*
|
|
302
|
-
* @example
|
|
303
|
-
* ```typescript
|
|
304
|
-
* import { wrapVitestKyselyTransaction, extendWithFixtures } from '@geekmidas/testkit/kysely';
|
|
305
|
-
*
|
|
306
|
-
* // Create base wrapped test
|
|
307
|
-
* const baseTest = wrapVitestKyselyTransaction(test, {
|
|
308
|
-
* connection: db,
|
|
309
|
-
* setup: createTestTables,
|
|
310
|
-
* });
|
|
311
|
-
*
|
|
312
|
-
* // Extend with fixtures
|
|
313
|
-
* const it = extendWithFixtures(baseTest, {
|
|
314
|
-
* factory: (trx) => new KyselyFactory(builders, seeds, trx),
|
|
315
|
-
* userRepo: (trx) => new UserRepository(trx),
|
|
316
|
-
* });
|
|
317
|
-
*
|
|
318
|
-
* // Use in tests - trx and all fixtures are available
|
|
319
|
-
* it('should create user with factory', async ({ trx, factory, userRepo }) => {
|
|
320
|
-
* const user = await factory.insert('user', { name: 'Test' });
|
|
321
|
-
* expect(user).toBeDefined();
|
|
322
|
-
* });
|
|
323
|
-
* ```
|
|
324
|
-
*/
|
|
325
|
-
export function extendWithFixtures<
|
|
326
|
-
Transaction,
|
|
327
|
-
Extended extends Record<string, unknown>,
|
|
328
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
329
|
-
T extends ReturnType<TestAPI['extend']> = any,
|
|
330
|
-
>(
|
|
331
|
-
wrappedTest: T,
|
|
332
|
-
fixtures: FixtureCreators<Transaction, Extended>,
|
|
333
|
-
): TestWithExtendedFixtures<Transaction, Extended, T> {
|
|
334
|
-
// Build fixture definitions for Vitest's extend API
|
|
335
|
-
const fixtureDefinitions: Record<string, any> = {};
|
|
336
|
-
|
|
337
|
-
for (const [key, creator] of Object.entries(fixtures)) {
|
|
338
|
-
fixtureDefinitions[key] = async (
|
|
339
|
-
{ trx }: { trx: Transaction },
|
|
340
|
-
use: (value: unknown) => Promise<void>,
|
|
341
|
-
) => {
|
|
342
|
-
const value = await (creator as (trx: Transaction) => unknown)(trx);
|
|
343
|
-
await use(value);
|
|
344
|
-
};
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
return (wrappedTest as any).extend(fixtureDefinitions);
|
|
348
|
-
}
|