@zenstackhq/testtools 3.5.6 → 3.6.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/index.cjs +411 -584
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +86 -82
- package/dist/index.d.mts +110 -0
- package/dist/index.mjs +444 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +16 -15
- package/dist/index.d.ts +0 -106
- package/dist/index.js +0 -613
- package/dist/index.js.map +0 -1
package/dist/index.js
DELETED
|
@@ -1,613 +0,0 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
2
|
-
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
-
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
4
|
-
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
5
|
-
}) : x)(function(x) {
|
|
6
|
-
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
7
|
-
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
8
|
-
});
|
|
9
|
-
|
|
10
|
-
// src/client.ts
|
|
11
|
-
import { invariant as invariant2 } from "@zenstackhq/common-helpers";
|
|
12
|
-
import { ZenStackClient } from "@zenstackhq/orm";
|
|
13
|
-
import { PolicyPlugin } from "@zenstackhq/plugin-policy";
|
|
14
|
-
import { PrismaSchemaGenerator } from "@zenstackhq/sdk";
|
|
15
|
-
import SQLite from "better-sqlite3";
|
|
16
|
-
import { glob } from "glob";
|
|
17
|
-
import { MysqlDialect, PostgresDialect, SqliteDialect } from "kysely";
|
|
18
|
-
import { createPool as createMysqlPool } from "mysql2";
|
|
19
|
-
import { execSync as execSync2 } from "child_process";
|
|
20
|
-
import { createHash } from "crypto";
|
|
21
|
-
import fs3 from "fs";
|
|
22
|
-
import path3 from "path";
|
|
23
|
-
import { Client as PGClient, Pool } from "pg";
|
|
24
|
-
import { match as match2 } from "ts-pattern";
|
|
25
|
-
import { expect as expect2 } from "vitest";
|
|
26
|
-
|
|
27
|
-
// src/project.ts
|
|
28
|
-
import fs from "fs";
|
|
29
|
-
import path from "path";
|
|
30
|
-
import tmp from "tmp";
|
|
31
|
-
function createTestProject(zmodelContent) {
|
|
32
|
-
const { name: workDir } = tmp.dirSync({
|
|
33
|
-
unsafeCleanup: true
|
|
34
|
-
});
|
|
35
|
-
fs.mkdirSync(path.join(workDir, "node_modules"));
|
|
36
|
-
const nodeModules = fs.readdirSync(path.join(__dirname, "../node_modules"));
|
|
37
|
-
for (const entry of nodeModules) {
|
|
38
|
-
if (entry.startsWith("@zenstackhq")) {
|
|
39
|
-
continue;
|
|
40
|
-
}
|
|
41
|
-
fs.symlinkSync(path.join(__dirname, "../node_modules", entry), path.join(workDir, "node_modules", entry), "dir");
|
|
42
|
-
}
|
|
43
|
-
const zenstackPackages = [
|
|
44
|
-
"language",
|
|
45
|
-
"sdk",
|
|
46
|
-
"schema",
|
|
47
|
-
"orm",
|
|
48
|
-
"cli"
|
|
49
|
-
];
|
|
50
|
-
fs.mkdirSync(path.join(workDir, "node_modules/@zenstackhq"));
|
|
51
|
-
for (const pkg of zenstackPackages) {
|
|
52
|
-
fs.symlinkSync(path.join(__dirname, `../../${pkg}`), path.join(workDir, `node_modules/@zenstackhq/${pkg}`), "dir");
|
|
53
|
-
}
|
|
54
|
-
fs.writeFileSync(path.join(workDir, "package.json"), JSON.stringify({
|
|
55
|
-
name: "test",
|
|
56
|
-
version: "1.0.0",
|
|
57
|
-
type: "module"
|
|
58
|
-
}, null, 4));
|
|
59
|
-
fs.writeFileSync(path.join(workDir, "tsconfig.json"), JSON.stringify({
|
|
60
|
-
compilerOptions: {
|
|
61
|
-
module: "ESNext",
|
|
62
|
-
target: "ESNext",
|
|
63
|
-
moduleResolution: "Bundler",
|
|
64
|
-
esModuleInterop: true,
|
|
65
|
-
skipLibCheck: true,
|
|
66
|
-
strict: true
|
|
67
|
-
},
|
|
68
|
-
include: [
|
|
69
|
-
"**/*.ts"
|
|
70
|
-
]
|
|
71
|
-
}, null, 4));
|
|
72
|
-
if (zmodelContent) {
|
|
73
|
-
fs.writeFileSync(path.join(workDir, "schema.zmodel"), zmodelContent);
|
|
74
|
-
}
|
|
75
|
-
return workDir;
|
|
76
|
-
}
|
|
77
|
-
__name(createTestProject, "createTestProject");
|
|
78
|
-
|
|
79
|
-
// src/schema.ts
|
|
80
|
-
import { invariant } from "@zenstackhq/common-helpers";
|
|
81
|
-
import { TsSchemaGenerator } from "@zenstackhq/sdk";
|
|
82
|
-
import { execSync } from "child_process";
|
|
83
|
-
import crypto from "crypto";
|
|
84
|
-
import fs2 from "fs";
|
|
85
|
-
import os from "os";
|
|
86
|
-
import path2 from "path";
|
|
87
|
-
import { match } from "ts-pattern";
|
|
88
|
-
import { expect } from "vitest";
|
|
89
|
-
|
|
90
|
-
// src/utils.ts
|
|
91
|
-
import { loadDocument } from "@zenstackhq/language";
|
|
92
|
-
function loadDocumentWithPlugins(filePath) {
|
|
93
|
-
const pluginModelFiles = [
|
|
94
|
-
__require.resolve("@zenstackhq/plugin-policy/plugin.zmodel")
|
|
95
|
-
];
|
|
96
|
-
return loadDocument(filePath, pluginModelFiles);
|
|
97
|
-
}
|
|
98
|
-
__name(loadDocumentWithPlugins, "loadDocumentWithPlugins");
|
|
99
|
-
|
|
100
|
-
// src/schema.ts
|
|
101
|
-
function makePrelude(provider, dbUrl) {
|
|
102
|
-
return match(provider).with("sqlite", () => {
|
|
103
|
-
return `
|
|
104
|
-
datasource db {
|
|
105
|
-
provider = 'sqlite'
|
|
106
|
-
url = '${dbUrl ?? "file:./test.db"}'
|
|
107
|
-
}
|
|
108
|
-
`;
|
|
109
|
-
}).with("postgresql", () => {
|
|
110
|
-
return `
|
|
111
|
-
datasource db {
|
|
112
|
-
provider = 'postgresql'
|
|
113
|
-
url = '${dbUrl ?? "postgres://postgres:postgres@localhost:5432/db"}'
|
|
114
|
-
}
|
|
115
|
-
`;
|
|
116
|
-
}).with("mysql", () => {
|
|
117
|
-
return `
|
|
118
|
-
datasource db {
|
|
119
|
-
provider = 'mysql'
|
|
120
|
-
url = '${dbUrl ?? "mysql://root:mysql@localhost:3306/db"}'
|
|
121
|
-
}
|
|
122
|
-
`;
|
|
123
|
-
}).exhaustive();
|
|
124
|
-
}
|
|
125
|
-
__name(makePrelude, "makePrelude");
|
|
126
|
-
function replacePlaceholders(schemaText, provider, dbUrl) {
|
|
127
|
-
const url = dbUrl ?? (provider === "sqlite" ? "file:./test.db" : provider === "mysql" ? "mysql://root:mysql@localhost:3306/db" : "postgres://postgres:postgres@localhost:5432/db");
|
|
128
|
-
return schemaText.replace(/\$DB_URL/g, url).replace(/\$PROVIDER/g, provider);
|
|
129
|
-
}
|
|
130
|
-
__name(replacePlaceholders, "replacePlaceholders");
|
|
131
|
-
async function generateTsSchema(schemaText, provider = "sqlite", dbUrl, extraSourceFiles, withLiteSchema, extraZModelFiles) {
|
|
132
|
-
const workDir = createTestProject();
|
|
133
|
-
const zmodelPath = path2.join(workDir, "schema.zmodel");
|
|
134
|
-
const noPrelude = schemaText.includes("datasource ");
|
|
135
|
-
fs2.writeFileSync(zmodelPath, `${noPrelude ? "" : makePrelude(provider, dbUrl)}
|
|
136
|
-
|
|
137
|
-
${replacePlaceholders(schemaText, provider, dbUrl)}`);
|
|
138
|
-
if (extraZModelFiles) {
|
|
139
|
-
for (const [fileName, content] of Object.entries(extraZModelFiles)) {
|
|
140
|
-
let name = fileName;
|
|
141
|
-
if (!name.endsWith(".zmodel")) {
|
|
142
|
-
name += ".zmodel";
|
|
143
|
-
}
|
|
144
|
-
const filePath = path2.join(workDir, name);
|
|
145
|
-
fs2.mkdirSync(path2.dirname(filePath), {
|
|
146
|
-
recursive: true
|
|
147
|
-
});
|
|
148
|
-
fs2.writeFileSync(filePath, content);
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
const result = await loadDocumentWithPlugins(zmodelPath);
|
|
152
|
-
if (!result.success) {
|
|
153
|
-
throw new Error(`Failed to load schema from ${zmodelPath}: ${result.errors}`);
|
|
154
|
-
}
|
|
155
|
-
const generator = new TsSchemaGenerator();
|
|
156
|
-
await generator.generate(result.model, {
|
|
157
|
-
outDir: workDir,
|
|
158
|
-
lite: withLiteSchema
|
|
159
|
-
});
|
|
160
|
-
if (extraSourceFiles) {
|
|
161
|
-
for (const [fileName, content] of Object.entries(extraSourceFiles)) {
|
|
162
|
-
const filePath = path2.resolve(workDir, !fileName.endsWith(".ts") ? `${fileName}.ts` : fileName);
|
|
163
|
-
fs2.mkdirSync(path2.dirname(filePath), {
|
|
164
|
-
recursive: true
|
|
165
|
-
});
|
|
166
|
-
fs2.writeFileSync(filePath, content);
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
return {
|
|
170
|
-
...await compileAndLoad(workDir),
|
|
171
|
-
model: result.model
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
__name(generateTsSchema, "generateTsSchema");
|
|
175
|
-
async function compileAndLoad(workDir) {
|
|
176
|
-
execSync("npx tsc", {
|
|
177
|
-
cwd: workDir,
|
|
178
|
-
stdio: "inherit"
|
|
179
|
-
});
|
|
180
|
-
const module = await import(path2.join(workDir, "schema.js"));
|
|
181
|
-
let moduleLite;
|
|
182
|
-
try {
|
|
183
|
-
moduleLite = await import(path2.join(workDir, "schema-lite.js"));
|
|
184
|
-
} catch {
|
|
185
|
-
}
|
|
186
|
-
return {
|
|
187
|
-
workDir,
|
|
188
|
-
schema: module.schema,
|
|
189
|
-
schemaLite: moduleLite?.schema
|
|
190
|
-
};
|
|
191
|
-
}
|
|
192
|
-
__name(compileAndLoad, "compileAndLoad");
|
|
193
|
-
function generateTsSchemaFromFile(filePath) {
|
|
194
|
-
const schemaText = fs2.readFileSync(filePath, "utf8");
|
|
195
|
-
return generateTsSchema(schemaText);
|
|
196
|
-
}
|
|
197
|
-
__name(generateTsSchemaFromFile, "generateTsSchemaFromFile");
|
|
198
|
-
async function generateTsSchemaInPlace(schemaPath) {
|
|
199
|
-
const workDir = path2.dirname(schemaPath);
|
|
200
|
-
const result = await loadDocumentWithPlugins(schemaPath);
|
|
201
|
-
if (!result.success) {
|
|
202
|
-
throw new Error(`Failed to load schema from ${schemaPath}: ${result.errors}`);
|
|
203
|
-
}
|
|
204
|
-
const generator = new TsSchemaGenerator();
|
|
205
|
-
await generator.generate(result.model, {
|
|
206
|
-
outDir: workDir
|
|
207
|
-
});
|
|
208
|
-
return compileAndLoad(workDir);
|
|
209
|
-
}
|
|
210
|
-
__name(generateTsSchemaInPlace, "generateTsSchemaInPlace");
|
|
211
|
-
async function loadSchema(schema, additionalSchemas) {
|
|
212
|
-
if (!schema.includes("datasource ")) {
|
|
213
|
-
schema = `${makePrelude("sqlite")}
|
|
214
|
-
|
|
215
|
-
${schema}`;
|
|
216
|
-
}
|
|
217
|
-
const tempDir = fs2.mkdtempSync(path2.join(os.tmpdir(), "zenstack-schema"));
|
|
218
|
-
const tempFile = path2.join(tempDir, `schema.zmodel`);
|
|
219
|
-
fs2.writeFileSync(tempFile, schema);
|
|
220
|
-
if (additionalSchemas) {
|
|
221
|
-
for (const [fileName, content] of Object.entries(additionalSchemas)) {
|
|
222
|
-
let name = fileName;
|
|
223
|
-
if (!name.endsWith(".zmodel")) {
|
|
224
|
-
name += ".zmodel";
|
|
225
|
-
}
|
|
226
|
-
const filePath = path2.join(tempDir, name);
|
|
227
|
-
fs2.writeFileSync(filePath, content);
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
const r = await loadDocumentWithPlugins(tempFile);
|
|
231
|
-
expect(r).toSatisfy((r2) => r2.success, `Failed to load schema: ${r.errors?.map((e) => e.toString()).join(", ")}`);
|
|
232
|
-
invariant(r.success);
|
|
233
|
-
return r.model;
|
|
234
|
-
}
|
|
235
|
-
__name(loadSchema, "loadSchema");
|
|
236
|
-
async function loadSchemaWithError(schema, error) {
|
|
237
|
-
if (!schema.includes("datasource ")) {
|
|
238
|
-
schema = `${makePrelude("sqlite")}
|
|
239
|
-
|
|
240
|
-
${schema}`;
|
|
241
|
-
}
|
|
242
|
-
const tempFile = path2.join(os.tmpdir(), `zenstack-schema-${crypto.randomUUID()}.zmodel`);
|
|
243
|
-
fs2.writeFileSync(tempFile, schema);
|
|
244
|
-
const r = await loadDocumentWithPlugins(tempFile);
|
|
245
|
-
expect(r.success).toBe(false);
|
|
246
|
-
invariant(!r.success);
|
|
247
|
-
if (typeof error === "string") {
|
|
248
|
-
expect(r).toSatisfy((r2) => r2.errors.some((e) => e.toString().toLowerCase().includes(error.toLowerCase())), `Expected error message to include "${error}" but got: ${r.errors.map((e) => e.toString()).join(", ")}`);
|
|
249
|
-
} else {
|
|
250
|
-
expect(r).toSatisfy((r2) => r2.errors.some((e) => error.test(e)), `Expected error message to match "${error}" but got: ${r.errors.map((e) => e.toString()).join(", ")}`);
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
__name(loadSchemaWithError, "loadSchemaWithError");
|
|
254
|
-
|
|
255
|
-
// src/client.ts
|
|
256
|
-
function getTestDbProvider() {
|
|
257
|
-
const val = process.env["TEST_DB_PROVIDER"] ?? "sqlite";
|
|
258
|
-
if (![
|
|
259
|
-
"sqlite",
|
|
260
|
-
"postgresql",
|
|
261
|
-
"mysql"
|
|
262
|
-
].includes(val)) {
|
|
263
|
-
throw new Error(`Invalid TEST_DB_PROVIDER value: ${val}`);
|
|
264
|
-
}
|
|
265
|
-
return val;
|
|
266
|
-
}
|
|
267
|
-
__name(getTestDbProvider, "getTestDbProvider");
|
|
268
|
-
var TEST_PG_CONFIG = {
|
|
269
|
-
host: process.env["TEST_PG_HOST"] ?? "localhost",
|
|
270
|
-
port: process.env["TEST_PG_PORT"] ? parseInt(process.env["TEST_PG_PORT"]) : 5432,
|
|
271
|
-
user: process.env["TEST_PG_USER"] ?? "postgres",
|
|
272
|
-
password: process.env["TEST_PG_PASSWORD"] ?? "postgres"
|
|
273
|
-
};
|
|
274
|
-
var TEST_PG_URL = `postgres://${TEST_PG_CONFIG.user}:${TEST_PG_CONFIG.password}@${TEST_PG_CONFIG.host}:${TEST_PG_CONFIG.port}`;
|
|
275
|
-
var TEST_MYSQL_CONFIG = {
|
|
276
|
-
host: process.env["TEST_MYSQL_HOST"] ?? "localhost",
|
|
277
|
-
port: process.env["TEST_MYSQL_PORT"] ? parseInt(process.env["TEST_MYSQL_PORT"]) : 3306,
|
|
278
|
-
user: process.env["TEST_MYSQL_USER"] ?? "root",
|
|
279
|
-
password: process.env["TEST_MYSQL_PASSWORD"] ?? "mysql",
|
|
280
|
-
timezone: "Z"
|
|
281
|
-
};
|
|
282
|
-
var TEST_MYSQL_URL = `mysql://${TEST_MYSQL_CONFIG.user}:${TEST_MYSQL_CONFIG.password}@${TEST_MYSQL_CONFIG.host}:${TEST_MYSQL_CONFIG.port}`;
|
|
283
|
-
async function createTestClient(schema, options) {
|
|
284
|
-
let workDir = options?.workDir;
|
|
285
|
-
let _schema;
|
|
286
|
-
const provider = options?.provider ?? getTestDbProvider() ?? "sqlite";
|
|
287
|
-
const dbName = options?.dbName ?? getTestDbName(provider);
|
|
288
|
-
const dbUrl = match2(provider).with("sqlite", () => `file:${dbName}`).with("mysql", () => `${TEST_MYSQL_URL}/${dbName}`).with("postgresql", () => `${TEST_PG_URL}/${dbName}`).exhaustive();
|
|
289
|
-
let model;
|
|
290
|
-
if (typeof schema === "string") {
|
|
291
|
-
const generated = await generateTsSchema(schema, provider, dbUrl, options?.extraSourceFiles, void 0, options?.extraZModelFiles);
|
|
292
|
-
workDir = generated.workDir;
|
|
293
|
-
model = generated.model;
|
|
294
|
-
_schema = {
|
|
295
|
-
...generated.schema,
|
|
296
|
-
provider: {
|
|
297
|
-
...generated.schema.provider,
|
|
298
|
-
type: provider
|
|
299
|
-
}
|
|
300
|
-
};
|
|
301
|
-
} else {
|
|
302
|
-
_schema = {
|
|
303
|
-
...schema,
|
|
304
|
-
provider: {
|
|
305
|
-
type: provider
|
|
306
|
-
}
|
|
307
|
-
};
|
|
308
|
-
workDir ??= createTestProject();
|
|
309
|
-
if (options?.schemaFile) {
|
|
310
|
-
let schemaContent = fs3.readFileSync(options.schemaFile, "utf-8");
|
|
311
|
-
if (dbUrl) {
|
|
312
|
-
schemaContent = schemaContent.replace(/datasource\s+db\s*{[^}]*}/m, `datasource db {
|
|
313
|
-
provider = '${provider}'
|
|
314
|
-
url = '${dbUrl}'
|
|
315
|
-
${options.dataSourceExtensions ? `extensions = [${options.dataSourceExtensions.join(", ")}]` : ""}
|
|
316
|
-
}`);
|
|
317
|
-
}
|
|
318
|
-
fs3.writeFileSync(path3.join(workDir, "schema.zmodel"), schemaContent);
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
invariant2(workDir);
|
|
322
|
-
const { plugins, ...rest } = options ?? {};
|
|
323
|
-
const _options = {
|
|
324
|
-
...rest
|
|
325
|
-
};
|
|
326
|
-
if (options?.debug) {
|
|
327
|
-
console.log(`Work directory: ${workDir}`);
|
|
328
|
-
console.log(`Database name: ${dbName}`);
|
|
329
|
-
_options.log ??= testLogger;
|
|
330
|
-
}
|
|
331
|
-
if (options?.dbFile) {
|
|
332
|
-
if (provider !== "sqlite") {
|
|
333
|
-
throw new Error("dbFile option is only supported for sqlite provider");
|
|
334
|
-
}
|
|
335
|
-
fs3.copyFileSync(options.dbFile, path3.join(workDir, dbName));
|
|
336
|
-
}
|
|
337
|
-
if (options?.copyFiles) {
|
|
338
|
-
const state = expect2.getState();
|
|
339
|
-
const currentTestPath = state.testPath;
|
|
340
|
-
if (!currentTestPath) {
|
|
341
|
-
throw new Error("Unable to determine current test file path");
|
|
342
|
-
}
|
|
343
|
-
for (const { globPattern, destination } of options.copyFiles) {
|
|
344
|
-
const files = glob.sync(globPattern, {
|
|
345
|
-
cwd: path3.dirname(currentTestPath)
|
|
346
|
-
});
|
|
347
|
-
for (const file of files) {
|
|
348
|
-
const src = path3.resolve(path3.dirname(currentTestPath), file);
|
|
349
|
-
const dest = path3.resolve(workDir, destination, path3.basename(file));
|
|
350
|
-
fs3.mkdirSync(path3.dirname(dest), {
|
|
351
|
-
recursive: true
|
|
352
|
-
});
|
|
353
|
-
fs3.copyFileSync(src, dest);
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
if (!options?.dbFile) {
|
|
358
|
-
if (options?.usePrismaPush) {
|
|
359
|
-
invariant2(typeof schema === "string" || options?.schemaFile, "a schema file must be provided when using prisma db push");
|
|
360
|
-
if (!model) {
|
|
361
|
-
const r = await loadDocumentWithPlugins(path3.join(workDir, "schema.zmodel"));
|
|
362
|
-
if (!r.success) {
|
|
363
|
-
throw new Error(r.errors.join("\n"));
|
|
364
|
-
}
|
|
365
|
-
model = r.model;
|
|
366
|
-
}
|
|
367
|
-
const prismaSchema = new PrismaSchemaGenerator(model);
|
|
368
|
-
const prismaSchemaText = await prismaSchema.generate();
|
|
369
|
-
fs3.writeFileSync(path3.resolve(workDir, "schema.prisma"), prismaSchemaText);
|
|
370
|
-
execSync2("npx prisma db push --schema ./schema.prisma --skip-generate --force-reset", {
|
|
371
|
-
cwd: workDir,
|
|
372
|
-
stdio: options.debug ? "inherit" : "ignore",
|
|
373
|
-
env: {
|
|
374
|
-
...process.env,
|
|
375
|
-
PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION: "true"
|
|
376
|
-
}
|
|
377
|
-
});
|
|
378
|
-
} else {
|
|
379
|
-
await prepareDatabase(provider, dbName);
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
_options.dialect = createDialect(provider, dbName, workDir);
|
|
383
|
-
let client = new ZenStackClient(_schema, _options);
|
|
384
|
-
if (!options?.usePrismaPush && !options?.dbFile) {
|
|
385
|
-
await client.$pushSchema();
|
|
386
|
-
}
|
|
387
|
-
if (plugins) {
|
|
388
|
-
for (const plugin of plugins) {
|
|
389
|
-
client = client.$use(plugin);
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
return client;
|
|
393
|
-
}
|
|
394
|
-
__name(createTestClient, "createTestClient");
|
|
395
|
-
function createDialect(provider, dbName, workDir) {
|
|
396
|
-
return match2(provider).with("postgresql", () => new PostgresDialect({
|
|
397
|
-
pool: new Pool({
|
|
398
|
-
...TEST_PG_CONFIG,
|
|
399
|
-
database: dbName
|
|
400
|
-
})
|
|
401
|
-
})).with("mysql", () => new MysqlDialect({
|
|
402
|
-
pool: createMysqlPool({
|
|
403
|
-
...TEST_MYSQL_CONFIG,
|
|
404
|
-
database: dbName
|
|
405
|
-
})
|
|
406
|
-
})).with("sqlite", () => new SqliteDialect({
|
|
407
|
-
database: new SQLite(path3.join(workDir, dbName))
|
|
408
|
-
})).exhaustive();
|
|
409
|
-
}
|
|
410
|
-
__name(createDialect, "createDialect");
|
|
411
|
-
async function prepareDatabase(provider, dbName) {
|
|
412
|
-
if (provider === "postgresql") {
|
|
413
|
-
invariant2(dbName, "dbName is required");
|
|
414
|
-
const pgClient = new PGClient(TEST_PG_CONFIG);
|
|
415
|
-
await pgClient.connect();
|
|
416
|
-
await pgClient.query(`DROP DATABASE IF EXISTS "${dbName}"`);
|
|
417
|
-
await pgClient.query(`CREATE DATABASE "${dbName}"`);
|
|
418
|
-
await pgClient.end();
|
|
419
|
-
} else if (provider === "mysql") {
|
|
420
|
-
invariant2(dbName, "dbName is required");
|
|
421
|
-
const mysqlPool = createMysqlPool(TEST_MYSQL_CONFIG);
|
|
422
|
-
await mysqlPool.promise().query(`DROP DATABASE IF EXISTS \`${dbName}\``);
|
|
423
|
-
await mysqlPool.promise().query(`CREATE DATABASE \`${dbName}\``);
|
|
424
|
-
await mysqlPool.promise().end();
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
__name(prepareDatabase, "prepareDatabase");
|
|
428
|
-
async function createPolicyTestClient(schema, options) {
|
|
429
|
-
return createTestClient(schema, {
|
|
430
|
-
...options,
|
|
431
|
-
plugins: [
|
|
432
|
-
...options?.plugins ?? [],
|
|
433
|
-
new PolicyPlugin()
|
|
434
|
-
]
|
|
435
|
-
});
|
|
436
|
-
}
|
|
437
|
-
__name(createPolicyTestClient, "createPolicyTestClient");
|
|
438
|
-
function testLogger(e) {
|
|
439
|
-
console.log(e.query.sql, e.query.parameters);
|
|
440
|
-
}
|
|
441
|
-
__name(testLogger, "testLogger");
|
|
442
|
-
function getTestDbName(provider) {
|
|
443
|
-
if (provider === "sqlite") {
|
|
444
|
-
return "./test.db";
|
|
445
|
-
}
|
|
446
|
-
const testName = expect2.getState().currentTestName ?? "unnamed";
|
|
447
|
-
const testPath = expect2.getState().testPath ?? "";
|
|
448
|
-
const digest = createHash("md5").update(testName + testPath).digest("hex");
|
|
449
|
-
return "test_" + testName.toLowerCase().replace(/[^a-z0-9_]/g, "_").replace(/_+/g, "_").substring(0, 30) + digest.slice(0, 6);
|
|
450
|
-
}
|
|
451
|
-
__name(getTestDbName, "getTestDbName");
|
|
452
|
-
|
|
453
|
-
// src/vitest-ext.ts
|
|
454
|
-
import { ORMError, ORMErrorReason } from "@zenstackhq/orm";
|
|
455
|
-
import { expect as expect3 } from "vitest";
|
|
456
|
-
function isPromise(value) {
|
|
457
|
-
return typeof value.then === "function" && typeof value.catch === "function";
|
|
458
|
-
}
|
|
459
|
-
__name(isPromise, "isPromise");
|
|
460
|
-
function expectErrorReason(err, errorReason) {
|
|
461
|
-
if (err instanceof ORMError && err.reason === errorReason) {
|
|
462
|
-
return {
|
|
463
|
-
message: /* @__PURE__ */ __name(() => "", "message"),
|
|
464
|
-
pass: true
|
|
465
|
-
};
|
|
466
|
-
} else {
|
|
467
|
-
return {
|
|
468
|
-
message: /* @__PURE__ */ __name(() => `expected ORMError of reason ${errorReason}, got ${err}`, "message"),
|
|
469
|
-
pass: false
|
|
470
|
-
};
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
__name(expectErrorReason, "expectErrorReason");
|
|
474
|
-
function expectErrorMessages(expectedMessages, message) {
|
|
475
|
-
for (const m of expectedMessages) {
|
|
476
|
-
if (!message.toLowerCase().includes(m.toLowerCase())) {
|
|
477
|
-
return {
|
|
478
|
-
message: /* @__PURE__ */ __name(() => `expected message not found in error: ${m}, got message: ${message}`, "message"),
|
|
479
|
-
pass: false
|
|
480
|
-
};
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
return void 0;
|
|
484
|
-
}
|
|
485
|
-
__name(expectErrorMessages, "expectErrorMessages");
|
|
486
|
-
expect3.extend({
|
|
487
|
-
async toResolveTruthy(received) {
|
|
488
|
-
if (!isPromise(received)) {
|
|
489
|
-
return {
|
|
490
|
-
message: /* @__PURE__ */ __name(() => "a promise is expected", "message"),
|
|
491
|
-
pass: false
|
|
492
|
-
};
|
|
493
|
-
}
|
|
494
|
-
const r = await received;
|
|
495
|
-
return {
|
|
496
|
-
pass: !!r,
|
|
497
|
-
message: /* @__PURE__ */ __name(() => `Expected promise to resolve to a truthy value, but got ${r}`, "message")
|
|
498
|
-
};
|
|
499
|
-
},
|
|
500
|
-
async toResolveFalsy(received) {
|
|
501
|
-
if (!isPromise(received)) {
|
|
502
|
-
return {
|
|
503
|
-
message: /* @__PURE__ */ __name(() => "a promise is expected", "message"),
|
|
504
|
-
pass: false
|
|
505
|
-
};
|
|
506
|
-
}
|
|
507
|
-
const r = await received;
|
|
508
|
-
return {
|
|
509
|
-
pass: !r,
|
|
510
|
-
message: /* @__PURE__ */ __name(() => `Expected promise to resolve to a falsy value, but got ${r}`, "message")
|
|
511
|
-
};
|
|
512
|
-
},
|
|
513
|
-
async toResolveNull(received) {
|
|
514
|
-
if (!isPromise(received)) {
|
|
515
|
-
return {
|
|
516
|
-
message: /* @__PURE__ */ __name(() => "a promise is expected", "message"),
|
|
517
|
-
pass: false
|
|
518
|
-
};
|
|
519
|
-
}
|
|
520
|
-
const r = await received;
|
|
521
|
-
return {
|
|
522
|
-
pass: r === null,
|
|
523
|
-
message: /* @__PURE__ */ __name(() => `Expected promise to resolve to a null value, but got ${r}`, "message")
|
|
524
|
-
};
|
|
525
|
-
},
|
|
526
|
-
async toResolveWithLength(received, length) {
|
|
527
|
-
const r = await received;
|
|
528
|
-
return {
|
|
529
|
-
pass: Array.isArray(r) && r.length === length,
|
|
530
|
-
message: /* @__PURE__ */ __name(() => `Expected promise to resolve with an array with length ${length}, but got ${r}`, "message")
|
|
531
|
-
};
|
|
532
|
-
},
|
|
533
|
-
async toBeRejectedNotFound(received) {
|
|
534
|
-
if (!isPromise(received)) {
|
|
535
|
-
return {
|
|
536
|
-
message: /* @__PURE__ */ __name(() => "a promise is expected", "message"),
|
|
537
|
-
pass: false
|
|
538
|
-
};
|
|
539
|
-
}
|
|
540
|
-
try {
|
|
541
|
-
await received;
|
|
542
|
-
} catch (err) {
|
|
543
|
-
return expectErrorReason(err, ORMErrorReason.NOT_FOUND);
|
|
544
|
-
}
|
|
545
|
-
return {
|
|
546
|
-
message: /* @__PURE__ */ __name(() => `expected NotFoundError, got no error`, "message"),
|
|
547
|
-
pass: false
|
|
548
|
-
};
|
|
549
|
-
},
|
|
550
|
-
async toBeRejectedByPolicy(received, expectedMessages) {
|
|
551
|
-
if (!isPromise(received)) {
|
|
552
|
-
return {
|
|
553
|
-
message: /* @__PURE__ */ __name(() => "a promise is expected", "message"),
|
|
554
|
-
pass: false
|
|
555
|
-
};
|
|
556
|
-
}
|
|
557
|
-
try {
|
|
558
|
-
await received;
|
|
559
|
-
} catch (err) {
|
|
560
|
-
if (expectedMessages && err instanceof ORMError && err.reason === ORMErrorReason.REJECTED_BY_POLICY) {
|
|
561
|
-
const r = expectErrorMessages(expectedMessages, err.message || "");
|
|
562
|
-
if (r) {
|
|
563
|
-
return r;
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
return expectErrorReason(err, ORMErrorReason.REJECTED_BY_POLICY);
|
|
567
|
-
}
|
|
568
|
-
return {
|
|
569
|
-
message: /* @__PURE__ */ __name(() => `expected PolicyError, got no error`, "message"),
|
|
570
|
-
pass: false
|
|
571
|
-
};
|
|
572
|
-
},
|
|
573
|
-
async toBeRejectedByValidation(received, expectedMessages) {
|
|
574
|
-
if (!isPromise(received)) {
|
|
575
|
-
return {
|
|
576
|
-
message: /* @__PURE__ */ __name(() => "a promise is expected", "message"),
|
|
577
|
-
pass: false
|
|
578
|
-
};
|
|
579
|
-
}
|
|
580
|
-
try {
|
|
581
|
-
await received;
|
|
582
|
-
} catch (err) {
|
|
583
|
-
if (expectedMessages && err instanceof ORMError && err.reason === ORMErrorReason.INVALID_INPUT) {
|
|
584
|
-
const r = expectErrorMessages(expectedMessages, err.message || "");
|
|
585
|
-
if (r) {
|
|
586
|
-
return r;
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
return expectErrorReason(err, ORMErrorReason.INVALID_INPUT);
|
|
590
|
-
}
|
|
591
|
-
return {
|
|
592
|
-
message: /* @__PURE__ */ __name(() => `expected InputValidationError, got no error`, "message"),
|
|
593
|
-
pass: false
|
|
594
|
-
};
|
|
595
|
-
}
|
|
596
|
-
});
|
|
597
|
-
export {
|
|
598
|
-
TEST_MYSQL_CONFIG,
|
|
599
|
-
TEST_MYSQL_URL,
|
|
600
|
-
TEST_PG_CONFIG,
|
|
601
|
-
TEST_PG_URL,
|
|
602
|
-
createPolicyTestClient,
|
|
603
|
-
createTestClient,
|
|
604
|
-
createTestProject,
|
|
605
|
-
generateTsSchema,
|
|
606
|
-
generateTsSchemaFromFile,
|
|
607
|
-
generateTsSchemaInPlace,
|
|
608
|
-
getTestDbProvider,
|
|
609
|
-
loadSchema,
|
|
610
|
-
loadSchemaWithError,
|
|
611
|
-
testLogger
|
|
612
|
-
};
|
|
613
|
-
//# sourceMappingURL=index.js.map
|