@better-auth/test-utils 1.5.0-beta.9
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/.turbo/turbo-build.log +17 -0
- package/LICENSE.md +20 -0
- package/dist/adapter.d.mts +3 -0
- package/dist/adapter.mjs +4 -0
- package/dist/create-test-suite.d.mts +118 -0
- package/dist/create-test-suite.mjs +461 -0
- package/dist/test-adapter.d.mts +75 -0
- package/dist/test-adapter.mjs +162 -0
- package/package.json +31 -0
- package/src/adapter/create-test-suite.ts +898 -0
- package/src/adapter/index.ts +7 -0
- package/src/adapter/test-adapter.ts +384 -0
- package/tsconfig.json +11 -0
- package/tsdown.config.ts +12 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
|
|
2
|
+
> @better-auth/test-utils@1.5.0-beta.9 build /home/runner/work/better-auth/better-auth/packages/test-utils
|
|
3
|
+
> tsdown
|
|
4
|
+
|
|
5
|
+
[34mℹ[39m tsdown [2mv0.19.0[22m powered by rolldown [2mv1.0.0-beta.59[22m
|
|
6
|
+
[34mℹ[39m config file: [4m/home/runner/work/better-auth/better-auth/packages/test-utils/tsdown.config.ts[24m
|
|
7
|
+
[34mℹ[39m entry: [34msrc/adapter/index.ts[39m
|
|
8
|
+
[34mℹ[39m tsconfig: [34mtsconfig.json[39m
|
|
9
|
+
[34mℹ[39m Build start
|
|
10
|
+
[34mℹ[39m [2mdist/[22m[1madapter.mjs[22m [2m 0.15 kB[22m [2m│ gzip: 0.10 kB[22m
|
|
11
|
+
[34mℹ[39m [2mdist/[22mcreate-test-suite.mjs [2m15.94 kB[22m [2m│ gzip: 3.97 kB[22m
|
|
12
|
+
[34mℹ[39m [2mdist/[22mtest-adapter.mjs [2m 8.11 kB[22m [2m│ gzip: 1.97 kB[22m
|
|
13
|
+
[34mℹ[39m [2mdist/[22m[32m[1madapter.d.mts[22m[39m [2m 0.27 kB[22m [2m│ gzip: 0.16 kB[22m
|
|
14
|
+
[34mℹ[39m [2mdist/[22m[32mcreate-test-suite.d.mts[39m [2m 5.13 kB[22m [2m│ gzip: 1.69 kB[22m
|
|
15
|
+
[34mℹ[39m [2mdist/[22m[32mtest-adapter.d.mts[39m [2m 2.17 kB[22m [2m│ gzip: 0.85 kB[22m
|
|
16
|
+
[34mℹ[39m 6 files, total: 31.77 kB
|
|
17
|
+
[32m✔[39m Build complete in [32m10721ms[39m
|
package/LICENSE.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
Copyright (c) 2024 - present, Bereket Engida
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
5
|
+
this software and associated documentation files (the “Software”), to deal in
|
|
6
|
+
the Software without restriction, including without limitation the rights to
|
|
7
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
8
|
+
the Software, and to permit persons to whom the Software is furnished to do so,
|
|
9
|
+
subject to the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
16
|
+
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
17
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
|
18
|
+
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
|
19
|
+
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
20
|
+
DEALINGS IN THE SOFTWARE.
|
package/dist/adapter.mjs
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { Logger } from "./test-adapter.mjs";
|
|
2
|
+
import { Account, Session, User, Verification } from "@better-auth/core/db";
|
|
3
|
+
import { DBAdapter } from "@better-auth/core/db/adapter";
|
|
4
|
+
import { betterAuth } from "better-auth";
|
|
5
|
+
import { BetterAuthOptions } from "@better-auth/core";
|
|
6
|
+
|
|
7
|
+
//#region src/adapter/create-test-suite.d.ts
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Test entry type that supports both callback and object formats.
|
|
11
|
+
* Object format allows specifying migration options that will be applied before the test runs.
|
|
12
|
+
*/
|
|
13
|
+
type TestEntry = ((context: {
|
|
14
|
+
readonly skip: {
|
|
15
|
+
(note?: string | undefined): never;
|
|
16
|
+
(condition: boolean, note?: string | undefined): void;
|
|
17
|
+
};
|
|
18
|
+
}) => Promise<void>) | {
|
|
19
|
+
migrateBetterAuth?: BetterAuthOptions;
|
|
20
|
+
test: (context: {
|
|
21
|
+
readonly skip: {
|
|
22
|
+
(note?: string | undefined): never;
|
|
23
|
+
(condition: boolean, note?: string | undefined): void;
|
|
24
|
+
};
|
|
25
|
+
}) => Promise<void>;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Statistics tracking for test suites.
|
|
29
|
+
*/
|
|
30
|
+
type TestSuiteStats = {
|
|
31
|
+
migrationCount: number;
|
|
32
|
+
totalMigrationTime: number;
|
|
33
|
+
testCount: number;
|
|
34
|
+
suiteStartTime: number;
|
|
35
|
+
suiteDuration: number;
|
|
36
|
+
suiteName: string;
|
|
37
|
+
groupingStats?: {
|
|
38
|
+
totalGroups: number;
|
|
39
|
+
averageTestsPerGroup: number;
|
|
40
|
+
largestGroupSize: number;
|
|
41
|
+
smallestGroupSize: number;
|
|
42
|
+
groupsWithMultipleTests: number;
|
|
43
|
+
totalTestsInGroups: number;
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
type GenerateFn = <M extends "user" | "session" | "verification" | "account">(Model: M) => Promise<M extends "user" ? User : M extends "session" ? Session : M extends "verification" ? Verification : M extends "account" ? Account : undefined>;
|
|
47
|
+
type Success<T> = {
|
|
48
|
+
data: T;
|
|
49
|
+
error: null;
|
|
50
|
+
};
|
|
51
|
+
type Failure<E> = {
|
|
52
|
+
data: null;
|
|
53
|
+
error: E;
|
|
54
|
+
};
|
|
55
|
+
type Result<T, E = Error> = Success<T> | Failure<E>;
|
|
56
|
+
type InsertRandomFn = <M extends "user" | "session" | "verification" | "account", Count extends number = 1>(model: M, count?: Count | undefined) => Promise<Count extends 1 ? M extends "user" ? [User] : M extends "session" ? [User, Session] : M extends "verification" ? [Verification] : M extends "account" ? [User, Account] : [undefined] : Array<M extends "user" ? [User] : M extends "session" ? [User, Session] : M extends "verification" ? [Verification] : M extends "account" ? [User, Account] : [undefined]>>;
|
|
57
|
+
declare const createTestSuite: <Tests extends Record<string, TestEntry>, AdditionalOptions extends Record<string, any> = {}>(suiteName: string, config: {
|
|
58
|
+
defaultBetterAuthOptions?: BetterAuthOptions | undefined;
|
|
59
|
+
/**
|
|
60
|
+
* Helpful if the default better auth options require migrations to be run.
|
|
61
|
+
*/
|
|
62
|
+
alwaysMigrate?: boolean | undefined;
|
|
63
|
+
prefixTests?: string | undefined;
|
|
64
|
+
customIdGenerator?: () => any | Promise<any> | undefined;
|
|
65
|
+
}, tests: (helpers: {
|
|
66
|
+
adapter: DBAdapter<BetterAuthOptions>;
|
|
67
|
+
log: Logger;
|
|
68
|
+
generate: GenerateFn;
|
|
69
|
+
insertRandom: InsertRandomFn;
|
|
70
|
+
/**
|
|
71
|
+
* A light cleanup function that will only delete rows it knows about.
|
|
72
|
+
*/
|
|
73
|
+
cleanup: () => Promise<void>;
|
|
74
|
+
/**
|
|
75
|
+
* A hard cleanup function that will delete all rows from the database.
|
|
76
|
+
*/
|
|
77
|
+
hardCleanup: () => Promise<void>;
|
|
78
|
+
modifyBetterAuthOptions: (options: BetterAuthOptions, shouldRunMigrations: boolean) => Promise<BetterAuthOptions>;
|
|
79
|
+
getBetterAuthOptions: () => BetterAuthOptions;
|
|
80
|
+
sortModels: (models: Array<Record<string, any> & {
|
|
81
|
+
id: string;
|
|
82
|
+
}>, by?: ("id" | "createdAt") | undefined) => (Record<string, any> & {
|
|
83
|
+
id: string;
|
|
84
|
+
})[];
|
|
85
|
+
getAuth: () => Promise<ReturnType<typeof betterAuth>>;
|
|
86
|
+
tryCatch<T, E = Error>(promise: Promise<T>): Promise<Result<T, E>>;
|
|
87
|
+
customIdGenerator?: () => any | Promise<any> | undefined;
|
|
88
|
+
transformIdOutput?: (id: any) => string | undefined;
|
|
89
|
+
/**
|
|
90
|
+
* Some adapters may change the ID type, this function allows you to pass the entire model
|
|
91
|
+
* data and it will return the correct better-auth-expected transformed data.
|
|
92
|
+
*
|
|
93
|
+
* Eg:
|
|
94
|
+
* MongoDB uses ObjectId for IDs, but it's possible the user can disable that option in the adapter config.
|
|
95
|
+
* Because of this, the expected data would be a string.
|
|
96
|
+
* These sorts of conversions will cause issues with the test when you use the `generate` function.
|
|
97
|
+
* This is because the `generate` function will return the raw data expected to be saved in DB, not the excpected BA output.
|
|
98
|
+
*/
|
|
99
|
+
transformGeneratedModel: (data: Record<string, any>) => Record<string, any>;
|
|
100
|
+
}, additionalOptions?: AdditionalOptions | undefined) => Tests) => (options?: ({
|
|
101
|
+
disableTests?: Partial<Record<keyof Tests, boolean> & {
|
|
102
|
+
ALL?: boolean;
|
|
103
|
+
}>;
|
|
104
|
+
} & AdditionalOptions) | undefined) => (helpers: {
|
|
105
|
+
adapter: () => Promise<DBAdapter<BetterAuthOptions>>;
|
|
106
|
+
log: Logger;
|
|
107
|
+
adapterDisplayName: string;
|
|
108
|
+
getBetterAuthOptions: () => BetterAuthOptions;
|
|
109
|
+
modifyBetterAuthOptions: (options: BetterAuthOptions) => Promise<BetterAuthOptions>;
|
|
110
|
+
cleanup: () => Promise<void>;
|
|
111
|
+
runMigrations: () => Promise<void>;
|
|
112
|
+
prefixTests?: string | undefined;
|
|
113
|
+
onTestFinish: (stats: TestSuiteStats) => Promise<void>;
|
|
114
|
+
customIdGenerator?: () => any | Promise<any> | undefined;
|
|
115
|
+
transformIdOutput?: (id: any) => string | undefined;
|
|
116
|
+
}) => Promise<void>;
|
|
117
|
+
//#endregion
|
|
118
|
+
export { InsertRandomFn, TestEntry, TestSuiteStats, createTestSuite };
|
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
import { getAuthTables } from "@better-auth/core/db";
|
|
2
|
+
import { createAdapterFactory, deepmerge, initGetDefaultModelName } from "@better-auth/core/db/adapter";
|
|
3
|
+
import { TTY_COLORS } from "@better-auth/core/env";
|
|
4
|
+
import { generateId } from "@better-auth/core/utils/id";
|
|
5
|
+
import { betterAuth } from "better-auth";
|
|
6
|
+
import { test } from "vitest";
|
|
7
|
+
|
|
8
|
+
//#region src/adapter/create-test-suite.ts
|
|
9
|
+
/**
|
|
10
|
+
* Deep equality comparison for BetterAuthOptions.
|
|
11
|
+
* Handles nested objects, arrays, and primitive values.
|
|
12
|
+
*/
|
|
13
|
+
function deepEqual(a, b) {
|
|
14
|
+
if (a === b) return true;
|
|
15
|
+
if (a == null || b == null) return a === b;
|
|
16
|
+
if (typeof a !== typeof b) return false;
|
|
17
|
+
if (typeof a === "object") {
|
|
18
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
19
|
+
if (Array.isArray(a)) {
|
|
20
|
+
if (a.length !== b.length) return false;
|
|
21
|
+
for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false;
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
24
|
+
const keysA = Object.keys(a);
|
|
25
|
+
const keysB = Object.keys(b);
|
|
26
|
+
if (keysA.length !== keysB.length) return false;
|
|
27
|
+
for (const key of keysA) {
|
|
28
|
+
if (!keysB.includes(key)) return false;
|
|
29
|
+
if (!deepEqual(a[key], b[key])) return false;
|
|
30
|
+
}
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
async function tryCatch(promise) {
|
|
36
|
+
try {
|
|
37
|
+
return {
|
|
38
|
+
data: await promise,
|
|
39
|
+
error: null
|
|
40
|
+
};
|
|
41
|
+
} catch (error) {
|
|
42
|
+
return {
|
|
43
|
+
data: null,
|
|
44
|
+
error
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const createTestSuite = (suiteName, config, tests) => {
|
|
49
|
+
return (options) => {
|
|
50
|
+
return async (helpers) => {
|
|
51
|
+
const createdRows = {};
|
|
52
|
+
let adapter = await helpers.adapter();
|
|
53
|
+
const wrapperAdapter = (overrideOptions) => {
|
|
54
|
+
const options$1 = deepmerge(deepmerge(helpers.getBetterAuthOptions(), config?.defaultBetterAuthOptions || {}), overrideOptions || {});
|
|
55
|
+
const adapterConfig = {
|
|
56
|
+
adapterId: helpers.adapterDisplayName,
|
|
57
|
+
...adapter.options?.adapterConfig || {},
|
|
58
|
+
adapterName: `Wrapped ${adapter.options?.adapterConfig.adapterName}`,
|
|
59
|
+
disableTransformOutput: true,
|
|
60
|
+
disableTransformInput: true,
|
|
61
|
+
disableTransformJoin: true
|
|
62
|
+
};
|
|
63
|
+
const adapterCreator = (options$2) => createAdapterFactory({
|
|
64
|
+
config: {
|
|
65
|
+
...adapterConfig,
|
|
66
|
+
transaction: adapter.transaction
|
|
67
|
+
},
|
|
68
|
+
adapter: ({ getDefaultModelName }) => {
|
|
69
|
+
adapter.transaction = void 0;
|
|
70
|
+
return {
|
|
71
|
+
count: async (args) => {
|
|
72
|
+
adapter = await helpers.adapter();
|
|
73
|
+
return await adapter.count(args);
|
|
74
|
+
},
|
|
75
|
+
deleteMany: async (args) => {
|
|
76
|
+
adapter = await helpers.adapter();
|
|
77
|
+
return await adapter.deleteMany(args);
|
|
78
|
+
},
|
|
79
|
+
delete: async (args) => {
|
|
80
|
+
adapter = await helpers.adapter();
|
|
81
|
+
return await adapter.delete(args);
|
|
82
|
+
},
|
|
83
|
+
findOne: async (args) => {
|
|
84
|
+
adapter = await helpers.adapter();
|
|
85
|
+
return await adapter.findOne(args);
|
|
86
|
+
},
|
|
87
|
+
findMany: async (args) => {
|
|
88
|
+
adapter = await helpers.adapter();
|
|
89
|
+
return await adapter.findMany(args);
|
|
90
|
+
},
|
|
91
|
+
update: async (args) => {
|
|
92
|
+
adapter = await helpers.adapter();
|
|
93
|
+
return await adapter.update(args);
|
|
94
|
+
},
|
|
95
|
+
updateMany: async (args) => {
|
|
96
|
+
adapter = await helpers.adapter();
|
|
97
|
+
return await adapter.updateMany(args);
|
|
98
|
+
},
|
|
99
|
+
createSchema: adapter.createSchema,
|
|
100
|
+
async create({ data, model, select }) {
|
|
101
|
+
const defaultModelName = getDefaultModelName(model);
|
|
102
|
+
adapter = await helpers.adapter();
|
|
103
|
+
const res = await adapter.create({
|
|
104
|
+
data,
|
|
105
|
+
model: defaultModelName,
|
|
106
|
+
select,
|
|
107
|
+
forceAllowId: true
|
|
108
|
+
});
|
|
109
|
+
createdRows[model] = [...createdRows[model] || [], res];
|
|
110
|
+
return res;
|
|
111
|
+
},
|
|
112
|
+
options: adapter.options
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
})(options$2);
|
|
116
|
+
return adapterCreator(options$1);
|
|
117
|
+
};
|
|
118
|
+
const resetDebugLogs = () => {
|
|
119
|
+
wrapperAdapter()?.adapterTestDebugLogs?.resetDebugLogs();
|
|
120
|
+
};
|
|
121
|
+
const printDebugLogs = () => {
|
|
122
|
+
wrapperAdapter()?.adapterTestDebugLogs?.printDebugLogs();
|
|
123
|
+
};
|
|
124
|
+
const cleanupCreatedRows = async () => {
|
|
125
|
+
adapter = await helpers.adapter();
|
|
126
|
+
for (const model of Object.keys(createdRows)) for (const row of createdRows[model]) {
|
|
127
|
+
const schema = getAuthTables(helpers.getBetterAuthOptions());
|
|
128
|
+
const getDefaultModelName = initGetDefaultModelName({
|
|
129
|
+
schema,
|
|
130
|
+
usePlural: adapter.options?.adapterConfig.usePlural
|
|
131
|
+
});
|
|
132
|
+
let defaultModelName;
|
|
133
|
+
try {
|
|
134
|
+
defaultModelName = getDefaultModelName(model);
|
|
135
|
+
} catch {
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (!schema[defaultModelName]) continue;
|
|
139
|
+
try {
|
|
140
|
+
await adapter.delete({
|
|
141
|
+
model,
|
|
142
|
+
where: [{
|
|
143
|
+
field: "id",
|
|
144
|
+
value: row.id
|
|
145
|
+
}]
|
|
146
|
+
});
|
|
147
|
+
} catch {}
|
|
148
|
+
if (createdRows[model].length === 1) delete createdRows[model];
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
let currentAppliedOptions = null;
|
|
152
|
+
const stats = {
|
|
153
|
+
migrationCount: 0,
|
|
154
|
+
totalMigrationTime: 0,
|
|
155
|
+
testCount: 0,
|
|
156
|
+
suiteStartTime: performance.now(),
|
|
157
|
+
suiteDuration: 0,
|
|
158
|
+
suiteName
|
|
159
|
+
};
|
|
160
|
+
/**
|
|
161
|
+
* Apply BetterAuth options and run migrations if needed.
|
|
162
|
+
* Tracks migration statistics.
|
|
163
|
+
*/
|
|
164
|
+
const applyOptionsAndMigrate = async (options$1, forceMigrate = false) => {
|
|
165
|
+
const finalOptions = deepmerge(config?.defaultBetterAuthOptions || {}, options$1 || {});
|
|
166
|
+
if (!deepEqual(currentAppliedOptions, finalOptions) || forceMigrate) {
|
|
167
|
+
adapter = await helpers.adapter();
|
|
168
|
+
await helpers.modifyBetterAuthOptions(finalOptions);
|
|
169
|
+
if (config.alwaysMigrate || forceMigrate) {
|
|
170
|
+
const migrationStart = performance.now();
|
|
171
|
+
await helpers.runMigrations();
|
|
172
|
+
const migrationTime = performance.now() - migrationStart;
|
|
173
|
+
stats.migrationCount++;
|
|
174
|
+
stats.totalMigrationTime += migrationTime;
|
|
175
|
+
adapter = await helpers.adapter();
|
|
176
|
+
}
|
|
177
|
+
currentAppliedOptions = finalOptions;
|
|
178
|
+
} else currentAppliedOptions = finalOptions;
|
|
179
|
+
return finalOptions;
|
|
180
|
+
};
|
|
181
|
+
const transformGeneratedModel = (data) => {
|
|
182
|
+
const newData = { ...data };
|
|
183
|
+
if (helpers.transformIdOutput) newData.id = helpers.transformIdOutput(newData.id);
|
|
184
|
+
return newData;
|
|
185
|
+
};
|
|
186
|
+
const idGenerator = async () => {
|
|
187
|
+
if (config.customIdGenerator) return config.customIdGenerator();
|
|
188
|
+
if (helpers.customIdGenerator) return helpers.customIdGenerator();
|
|
189
|
+
return generateId();
|
|
190
|
+
};
|
|
191
|
+
const generateModel = async (model) => {
|
|
192
|
+
const id = await idGenerator();
|
|
193
|
+
const randomDate = /* @__PURE__ */ new Date(Date.now() - Math.random() * 1e3 * 60 * 60 * 24 * 365);
|
|
194
|
+
if (model === "user") return {
|
|
195
|
+
id,
|
|
196
|
+
createdAt: randomDate,
|
|
197
|
+
updatedAt: /* @__PURE__ */ new Date(),
|
|
198
|
+
email: `user-${helpers.transformIdOutput?.(id) ?? id}@email.com`.toLowerCase(),
|
|
199
|
+
emailVerified: true,
|
|
200
|
+
name: `user-${helpers.transformIdOutput?.(id) ?? id}`,
|
|
201
|
+
image: null
|
|
202
|
+
};
|
|
203
|
+
if (model === "session") return {
|
|
204
|
+
id,
|
|
205
|
+
createdAt: randomDate,
|
|
206
|
+
updatedAt: /* @__PURE__ */ new Date(),
|
|
207
|
+
expiresAt: /* @__PURE__ */ new Date(),
|
|
208
|
+
token: generateId(32),
|
|
209
|
+
userId: generateId(),
|
|
210
|
+
ipAddress: "127.0.0.1",
|
|
211
|
+
userAgent: "Some User Agent"
|
|
212
|
+
};
|
|
213
|
+
if (model === "verification") return {
|
|
214
|
+
id,
|
|
215
|
+
createdAt: randomDate,
|
|
216
|
+
updatedAt: /* @__PURE__ */ new Date(),
|
|
217
|
+
expiresAt: /* @__PURE__ */ new Date(),
|
|
218
|
+
identifier: `test:${generateId()}`,
|
|
219
|
+
value: generateId()
|
|
220
|
+
};
|
|
221
|
+
if (model === "account") return {
|
|
222
|
+
id,
|
|
223
|
+
createdAt: randomDate,
|
|
224
|
+
updatedAt: /* @__PURE__ */ new Date(),
|
|
225
|
+
accountId: generateId(),
|
|
226
|
+
providerId: "test",
|
|
227
|
+
userId: generateId(),
|
|
228
|
+
accessToken: generateId(),
|
|
229
|
+
refreshToken: generateId(),
|
|
230
|
+
idToken: generateId(),
|
|
231
|
+
accessTokenExpiresAt: /* @__PURE__ */ new Date(),
|
|
232
|
+
refreshTokenExpiresAt: /* @__PURE__ */ new Date(),
|
|
233
|
+
scope: "test"
|
|
234
|
+
};
|
|
235
|
+
throw new Error(`Unknown model type: ${model}`);
|
|
236
|
+
};
|
|
237
|
+
const insertRandom = async (model, count = 1) => {
|
|
238
|
+
const res = [];
|
|
239
|
+
const a = wrapperAdapter();
|
|
240
|
+
for (let i = 0; i < count; i++) {
|
|
241
|
+
const modelResults = [];
|
|
242
|
+
if (model === "user") {
|
|
243
|
+
const user = await generateModel("user");
|
|
244
|
+
modelResults.push(await a.create({
|
|
245
|
+
data: user,
|
|
246
|
+
model: "user",
|
|
247
|
+
forceAllowId: true
|
|
248
|
+
}));
|
|
249
|
+
}
|
|
250
|
+
if (model === "session") {
|
|
251
|
+
const user = await generateModel("user");
|
|
252
|
+
const userRes = await a.create({
|
|
253
|
+
data: user,
|
|
254
|
+
model: "user",
|
|
255
|
+
forceAllowId: true
|
|
256
|
+
});
|
|
257
|
+
const session = await generateModel("session");
|
|
258
|
+
session.userId = userRes.id;
|
|
259
|
+
const sessionRes = await a.create({
|
|
260
|
+
data: session,
|
|
261
|
+
model: "session",
|
|
262
|
+
forceAllowId: true
|
|
263
|
+
});
|
|
264
|
+
modelResults.push(userRes, sessionRes);
|
|
265
|
+
}
|
|
266
|
+
if (model === "verification") {
|
|
267
|
+
const verification = await generateModel("verification");
|
|
268
|
+
modelResults.push(await a.create({
|
|
269
|
+
data: verification,
|
|
270
|
+
model: "verification",
|
|
271
|
+
forceAllowId: true
|
|
272
|
+
}));
|
|
273
|
+
}
|
|
274
|
+
if (model === "account") {
|
|
275
|
+
const user = await generateModel("user");
|
|
276
|
+
const account = await generateModel("account");
|
|
277
|
+
const userRes = await a.create({
|
|
278
|
+
data: user,
|
|
279
|
+
model: "user",
|
|
280
|
+
forceAllowId: true
|
|
281
|
+
});
|
|
282
|
+
account.userId = userRes.id;
|
|
283
|
+
const accRes = await a.create({
|
|
284
|
+
data: account,
|
|
285
|
+
model: "account",
|
|
286
|
+
forceAllowId: true
|
|
287
|
+
});
|
|
288
|
+
modelResults.push(userRes, accRes);
|
|
289
|
+
}
|
|
290
|
+
res.push(modelResults);
|
|
291
|
+
}
|
|
292
|
+
return res.length === 1 ? res[0] : res;
|
|
293
|
+
};
|
|
294
|
+
const sortModels = (models, by = "id") => {
|
|
295
|
+
return models.sort((a, b) => {
|
|
296
|
+
if (by === "createdAt") return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
|
|
297
|
+
return a.id.localeCompare(b.id);
|
|
298
|
+
});
|
|
299
|
+
};
|
|
300
|
+
const modifyBetterAuthOptions = async (opts, shouldRunMigrations) => {
|
|
301
|
+
return await applyOptionsAndMigrate(opts, shouldRunMigrations);
|
|
302
|
+
};
|
|
303
|
+
const additionalOptions = { ...options };
|
|
304
|
+
additionalOptions.disableTests = void 0;
|
|
305
|
+
const fullTests = tests({
|
|
306
|
+
adapter: new Proxy({}, { get(target, prop) {
|
|
307
|
+
const adapter$1 = wrapperAdapter();
|
|
308
|
+
if (prop === "transaction") return adapter$1.transaction;
|
|
309
|
+
const value = adapter$1[prop];
|
|
310
|
+
if (typeof value === "function") return value.bind(adapter$1);
|
|
311
|
+
return value;
|
|
312
|
+
} }),
|
|
313
|
+
getAuth: async () => {
|
|
314
|
+
adapter = await helpers.adapter();
|
|
315
|
+
return betterAuth({
|
|
316
|
+
...helpers.getBetterAuthOptions(),
|
|
317
|
+
...config?.defaultBetterAuthOptions || {},
|
|
318
|
+
database: (options$1) => {
|
|
319
|
+
return wrapperAdapter(options$1);
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
},
|
|
323
|
+
log: helpers.log,
|
|
324
|
+
generate: generateModel,
|
|
325
|
+
cleanup: cleanupCreatedRows,
|
|
326
|
+
hardCleanup: helpers.cleanup,
|
|
327
|
+
insertRandom,
|
|
328
|
+
modifyBetterAuthOptions,
|
|
329
|
+
getBetterAuthOptions: helpers.getBetterAuthOptions,
|
|
330
|
+
sortModels,
|
|
331
|
+
tryCatch,
|
|
332
|
+
customIdGenerator: helpers.customIdGenerator,
|
|
333
|
+
transformGeneratedModel,
|
|
334
|
+
transformIdOutput: helpers.transformIdOutput
|
|
335
|
+
}, additionalOptions);
|
|
336
|
+
const dash = `─`;
|
|
337
|
+
const allDisabled = options?.disableTests?.ALL ?? false;
|
|
338
|
+
test(`\n${TTY_COLORS.fg.white}${" ".repeat(3)}${dash.repeat(35)} [${TTY_COLORS.fg.magenta}${suiteName}${TTY_COLORS.fg.white}] ${dash.repeat(35)}`, async () => {
|
|
339
|
+
try {
|
|
340
|
+
await helpers.cleanup();
|
|
341
|
+
} catch {}
|
|
342
|
+
if (config.defaultBetterAuthOptions && !allDisabled) await applyOptionsAndMigrate(config.defaultBetterAuthOptions, config.alwaysMigrate);
|
|
343
|
+
});
|
|
344
|
+
/**
|
|
345
|
+
* Extract test function and migration options from a test entry.
|
|
346
|
+
*/
|
|
347
|
+
const extractTestEntry = (entry) => {
|
|
348
|
+
if (typeof entry === "function") return { testFn: entry };
|
|
349
|
+
return {
|
|
350
|
+
testFn: entry.test,
|
|
351
|
+
migrateBetterAuth: entry.migrateBetterAuth
|
|
352
|
+
};
|
|
353
|
+
};
|
|
354
|
+
const testEntries = Object.entries(fullTests).map(([name, entry]) => {
|
|
355
|
+
const { testFn, migrateBetterAuth } = extractTestEntry(entry);
|
|
356
|
+
return {
|
|
357
|
+
name,
|
|
358
|
+
testFn,
|
|
359
|
+
migrateBetterAuth
|
|
360
|
+
};
|
|
361
|
+
});
|
|
362
|
+
const groupTestsByMigrationOptions = () => {
|
|
363
|
+
const groups = [];
|
|
364
|
+
let currentGroup = null;
|
|
365
|
+
for (let i = 0; i < testEntries.length; i++) {
|
|
366
|
+
const { migrateBetterAuth } = testEntries[i];
|
|
367
|
+
if (allDisabled && options?.disableTests?.[testEntries[i].name] !== false || (options?.disableTests?.[testEntries[i].name] ?? false)) {
|
|
368
|
+
if (currentGroup) {
|
|
369
|
+
groups.push(currentGroup);
|
|
370
|
+
currentGroup = null;
|
|
371
|
+
}
|
|
372
|
+
groups.push({
|
|
373
|
+
migrationOptions: migrateBetterAuth,
|
|
374
|
+
testIndices: [i]
|
|
375
|
+
});
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
if (currentGroup && deepEqual(currentGroup.migrationOptions, migrateBetterAuth)) currentGroup.testIndices.push(i);
|
|
379
|
+
else {
|
|
380
|
+
if (currentGroup) groups.push(currentGroup);
|
|
381
|
+
currentGroup = {
|
|
382
|
+
migrationOptions: migrateBetterAuth,
|
|
383
|
+
testIndices: [i]
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
if (currentGroup) groups.push(currentGroup);
|
|
388
|
+
return groups;
|
|
389
|
+
};
|
|
390
|
+
const testGroups = groupTestsByMigrationOptions();
|
|
391
|
+
const calculateGroupingStats = () => {
|
|
392
|
+
const nonSkippedGroups = testGroups.filter((group) => group.testIndices.length > 0);
|
|
393
|
+
const groupSizes = nonSkippedGroups.map((group) => group.testIndices.length);
|
|
394
|
+
if (groupSizes.length === 0) return {
|
|
395
|
+
totalGroups: 0,
|
|
396
|
+
averageTestsPerGroup: 0,
|
|
397
|
+
largestGroupSize: 0,
|
|
398
|
+
smallestGroupSize: 0,
|
|
399
|
+
groupsWithMultipleTests: 0,
|
|
400
|
+
totalTestsInGroups: 0
|
|
401
|
+
};
|
|
402
|
+
const totalTestsInGroups = groupSizes.reduce((sum, size) => sum + size, 0);
|
|
403
|
+
const groupsWithMultipleTests = groupSizes.filter((size) => size > 1).length;
|
|
404
|
+
return {
|
|
405
|
+
totalGroups: nonSkippedGroups.length,
|
|
406
|
+
averageTestsPerGroup: totalTestsInGroups / nonSkippedGroups.length,
|
|
407
|
+
largestGroupSize: Math.max(...groupSizes),
|
|
408
|
+
smallestGroupSize: Math.min(...groupSizes),
|
|
409
|
+
groupsWithMultipleTests,
|
|
410
|
+
totalTestsInGroups
|
|
411
|
+
};
|
|
412
|
+
};
|
|
413
|
+
const onFinish = async (testName) => {
|
|
414
|
+
await cleanupCreatedRows();
|
|
415
|
+
if (testEntries.findIndex(({ name }) => name === testName) === testEntries.length - 1) {
|
|
416
|
+
stats.suiteDuration = performance.now() - stats.suiteStartTime;
|
|
417
|
+
stats.groupingStats = calculateGroupingStats();
|
|
418
|
+
await helpers.onTestFinish(stats);
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
let currentGroupMigrationOptions = null;
|
|
422
|
+
for (let i = 0; i < testEntries.length; i++) {
|
|
423
|
+
const { name: testName, testFn, migrateBetterAuth } = testEntries[i];
|
|
424
|
+
const testGroup = testGroups.find((group) => group.testIndices.includes(i));
|
|
425
|
+
const isFirstInGroup = testGroup && testGroup.testIndices[0] === i;
|
|
426
|
+
const shouldSkip = allDisabled && options?.disableTests?.[testName] !== false || (options?.disableTests?.[testName] ?? false);
|
|
427
|
+
let displayName = testName.replace(" - ", ` ${TTY_COLORS.dim}${dash}${TTY_COLORS.undim} `);
|
|
428
|
+
if (config.prefixTests) displayName = `${config.prefixTests} ${TTY_COLORS.dim}>${TTY_COLORS.undim} ${displayName}`;
|
|
429
|
+
if (helpers.prefixTests) displayName = `[${TTY_COLORS.dim}${helpers.prefixTests}${TTY_COLORS.undim}] ${displayName}`;
|
|
430
|
+
test.skipIf(shouldSkip)(displayName, { timeout: 3e4 }, async ({ onTestFailed, skip }) => {
|
|
431
|
+
resetDebugLogs();
|
|
432
|
+
await (async () => {
|
|
433
|
+
if (shouldSkip) return;
|
|
434
|
+
const thisMigration = deepmerge(config.defaultBetterAuthOptions || {}, migrateBetterAuth || {});
|
|
435
|
+
if (isFirstInGroup && testGroup) {
|
|
436
|
+
const groupMigrationOptions = testGroup.migrationOptions;
|
|
437
|
+
const groupFinalOptions = deepmerge(config.defaultBetterAuthOptions || {}, groupMigrationOptions || {});
|
|
438
|
+
if (!deepEqual(currentGroupMigrationOptions, groupMigrationOptions)) {
|
|
439
|
+
await applyOptionsAndMigrate(groupFinalOptions, true);
|
|
440
|
+
currentGroupMigrationOptions = groupMigrationOptions;
|
|
441
|
+
}
|
|
442
|
+
} else if (!deepEqual(currentGroupMigrationOptions, migrateBetterAuth)) {
|
|
443
|
+
await applyOptionsAndMigrate(thisMigration, true);
|
|
444
|
+
currentGroupMigrationOptions = migrateBetterAuth;
|
|
445
|
+
}
|
|
446
|
+
})();
|
|
447
|
+
stats.testCount++;
|
|
448
|
+
onTestFailed(async () => {
|
|
449
|
+
printDebugLogs();
|
|
450
|
+
await onFinish(testName);
|
|
451
|
+
});
|
|
452
|
+
await testFn({ skip });
|
|
453
|
+
await onFinish(testName);
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
};
|
|
457
|
+
};
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
//#endregion
|
|
461
|
+
export { createTestSuite };
|