Skip to content

Commit 330be71

Browse files
authored
chore: reorg test runs (#121)
* chore: reorg test runs * update * update
1 parent a0c79b0 commit 330be71

File tree

7 files changed

+80
-100
lines changed

7 files changed

+80
-100
lines changed

packages/runtime/test/client-api/delegate.test.ts

Lines changed: 22 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,26 @@
1+
import path from 'node:path';
12
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
3+
import type { ClientContract } from '../../src';
4+
import { schema, type SchemaType } from '../schemas/delegate/schema';
25
import { createTestClient } from '../utils';
36

47
const DB_NAME = `client-api-delegate-tests`;
58

69
describe.each([{ provider: 'sqlite' as const }, { provider: 'postgresql' as const }])(
710
'Delegate model tests for $provider',
811
({ provider }) => {
9-
const POLYMORPHIC_SCHEMA = `
10-
model User {
11-
id Int @id @default(autoincrement())
12-
email String? @unique
13-
level Int @default(0)
14-
assets Asset[]
15-
ratedVideos RatedVideo[] @relation('direct')
16-
}
17-
18-
model Comment {
19-
id Int @id @default(autoincrement())
20-
content String
21-
asset Asset? @relation(fields: [assetId], references: [id], onDelete: Cascade)
22-
assetId Int?
23-
}
24-
25-
model Asset {
26-
id Int @id @default(autoincrement())
27-
createdAt DateTime @default(now())
28-
updatedAt DateTime @updatedAt
29-
viewCount Int @default(0)
30-
owner User? @relation(fields: [ownerId], references: [id], onDelete: Cascade)
31-
ownerId Int?
32-
comments Comment[]
33-
assetType String
34-
35-
@@delegate(assetType)
36-
}
37-
38-
model Video extends Asset {
39-
duration Int
40-
url String @unique
41-
videoType String
42-
43-
@@delegate(videoType)
44-
}
45-
46-
model RatedVideo extends Video {
47-
rating Int
48-
user User? @relation(name: 'direct', fields: [userId], references: [id], onDelete: Cascade)
49-
userId Int?
50-
}
51-
52-
model Image extends Asset {
53-
format String
54-
gallery Gallery? @relation(fields: [galleryId], references: [id], onDelete: Cascade)
55-
galleryId Int?
56-
}
57-
58-
model Gallery {
59-
id Int @id @default(autoincrement())
60-
images Image[]
61-
}
62-
`;
63-
64-
let client: any;
12+
let client: ClientContract<SchemaType>;
6513

6614
beforeEach(async () => {
67-
client = await createTestClient(POLYMORPHIC_SCHEMA, {
68-
usePrismaPush: true,
69-
provider,
70-
dbName: provider === 'postgresql' ? DB_NAME : undefined,
71-
});
15+
client = await createTestClient(
16+
schema,
17+
{
18+
usePrismaPush: true,
19+
provider,
20+
dbName: provider === 'postgresql' ? DB_NAME : undefined,
21+
},
22+
path.join(__dirname, '../schemas/delegate/schema.zmodel'),
23+
);
7224
});
7325

7426
afterEach(async () => {
@@ -79,6 +31,7 @@ model Gallery {
7931
it('works with create', async () => {
8032
// delegate model cannot be created directly
8133
await expect(
34+
// @ts-expect-error
8235
client.video.create({
8336
data: {
8437
duration: 100,
@@ -91,6 +44,7 @@ model Gallery {
9144
client.user.create({
9245
data: {
9346
assets: {
47+
// @ts-expect-error
9448
create: { assetType: 'Video' },
9549
},
9650
},
@@ -294,7 +248,7 @@ model Gallery {
294248
});
295249

296250
// omit fields
297-
const r = await client.ratedVideo.findUnique({
251+
const r: any = await client.ratedVideo.findUnique({
298252
where: { id: v.id },
299253
omit: {
300254
viewCount: true,
@@ -341,8 +295,10 @@ model Gallery {
341295
select: { id: true, assetType: true },
342296
},
343297
ratedVideos: {
344-
url: true,
345-
rating: true,
298+
select: {
299+
url: true,
300+
rating: true,
301+
},
346302
},
347303
},
348304
}),
@@ -568,7 +524,7 @@ model Gallery {
568524
client.video.findFirst({
569525
where: {
570526
comments: {
571-
all: { content: 'c2' },
527+
every: { content: 'c2' },
572528
},
573529
},
574530
}),
@@ -878,6 +834,7 @@ model Gallery {
878834

879835
it('works with upsert', async () => {
880836
await expect(
837+
// @ts-expect-error
881838
client.asset.upsert({
882839
where: { id: 2 },
883840
create: {

packages/runtime/test/client-api/relation.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ describe.each([
242242
});
243243

244244
describe.each([{ relationName: undefined }, { relationName: 'myM2M' }])(
245-
'Implicit many-to-many relation ($relationName)',
245+
'Implicit many-to-many relation (relation: $relationName)',
246246
({ relationName }) => {
247247
beforeEach(async () => {
248248
client = await createTestClient(
@@ -269,7 +269,7 @@ describe.each([
269269
`,
270270
{
271271
provider,
272-
dbName: provider === 'sqlite' ? 'file:./dev.db' : TEST_DB,
272+
dbName: provider === 'postgresql' ? TEST_DB : undefined,
273273
usePrismaPush: true,
274274
},
275275
);

packages/runtime/test/utils.ts

Lines changed: 48 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { invariant } from '@zenstackhq/common-helpers';
22
import { loadDocument } from '@zenstackhq/language';
33
import { PrismaSchemaGenerator } from '@zenstackhq/sdk';
4-
import { generateTsSchema } from '@zenstackhq/testtools';
4+
import { createTestProject, generateTsSchema } from '@zenstackhq/testtools';
55
import SQLite from 'better-sqlite3';
66
import { execSync } from 'node:child_process';
77
import fs from 'node:fs';
@@ -67,6 +67,7 @@ export type CreateTestClientOptions<Schema extends SchemaDef> = Omit<ClientOptio
6767
export async function createTestClient<Schema extends SchemaDef>(
6868
schema: Schema,
6969
options?: CreateTestClientOptions<Schema>,
70+
schemaFile?: string,
7071
): Promise<ClientContract<Schema>>;
7172
export async function createTestClient<Schema extends SchemaDef>(
7273
schema: string,
@@ -75,35 +76,70 @@ export async function createTestClient<Schema extends SchemaDef>(
7576
export async function createTestClient<Schema extends SchemaDef>(
7677
schema: Schema | string,
7778
options?: CreateTestClientOptions<Schema>,
79+
schemaFile?: string,
7880
): Promise<any> {
7981
let workDir: string | undefined;
8082
let _schema: Schema;
83+
const provider = options?.provider ?? 'sqlite';
8184

8285
let dbName = options?.dbName;
83-
const provider = options?.provider ?? 'sqlite';
84-
if (provider === 'sqlite' && options?.usePrismaPush && !dbName) {
85-
dbName = 'file:./test.db';
86+
if (!dbName) {
87+
if (provider === 'sqlite') {
88+
dbName = './test.db';
89+
} else {
90+
throw new Error(`dbName is required for ${provider} provider`);
91+
}
8692
}
8793

94+
const dbUrl =
95+
provider === 'sqlite'
96+
? `file:${dbName}`
97+
: `postgres://${TEST_PG_CONFIG.user}:${TEST_PG_CONFIG.password}@${TEST_PG_CONFIG.host}:${TEST_PG_CONFIG.port}/${dbName}`;
98+
8899
if (typeof schema === 'string') {
89-
const generated = await generateTsSchema(schema, provider, dbName, options?.extraSourceFiles);
100+
const generated = await generateTsSchema(schema, provider, dbUrl, options?.extraSourceFiles);
90101
workDir = generated.workDir;
91-
_schema = generated.schema as Schema;
102+
// replace schema's provider
103+
_schema = {
104+
...generated.schema,
105+
provider: {
106+
type: provider,
107+
},
108+
} as Schema;
92109
} else {
93-
_schema = schema;
94-
if (options?.extraSourceFiles) {
95-
throw new Error('`extraSourceFiles` is not supported when schema is a SchemaDef object');
110+
// replace schema's provider
111+
_schema = {
112+
...schema,
113+
provider: {
114+
type: provider,
115+
},
116+
};
117+
workDir = await createTestProject();
118+
if (schemaFile) {
119+
let schemaContent = fs.readFileSync(schemaFile, 'utf-8');
120+
if (dbUrl) {
121+
// replace `datasource db { }` section
122+
schemaContent = schemaContent.replace(
123+
/datasource\s+db\s*{[^}]*}/m,
124+
`datasource db {
125+
provider = '${provider}'
126+
url = '${dbUrl}'
127+
}`,
128+
);
129+
}
130+
fs.writeFileSync(path.join(workDir, 'schema.zmodel'), schemaContent);
96131
}
97132
}
98133

134+
console.log(`Work directory: ${workDir}`);
135+
99136
const { plugins, ...rest } = options ?? {};
100137
const _options: ClientOptions<Schema> = {
101138
...rest,
102139
} as ClientOptions<Schema>;
103140

104141
if (options?.usePrismaPush) {
105-
invariant(typeof schema === 'string', 'schema must be a string');
106-
invariant(workDir, 'workDir is required');
142+
invariant(typeof schema === 'string' || schemaFile, 'a schema file must be provided when using prisma db push');
107143
const r = await loadDocument(path.resolve(workDir, 'schema.zmodel'));
108144
if (!r.success) {
109145
throw new Error(r.errors.join('\n'));
@@ -135,7 +171,7 @@ export async function createTestClient<Schema extends SchemaDef>(
135171
} as unknown as ClientOptions<Schema>['dialectConfig'];
136172
} else {
137173
_options.dialectConfig = {
138-
database: new SQLite(options?.usePrismaPush ? getDbPath(path.join(workDir!, 'schema.prisma')) : ':memory:'),
174+
database: new SQLite(path.join(workDir!, dbName)),
139175
} as unknown as ClientOptions<Schema>['dialectConfig'];
140176
}
141177

@@ -153,15 +189,3 @@ export async function createTestClient<Schema extends SchemaDef>(
153189

154190
return client;
155191
}
156-
157-
function getDbPath(prismaSchemaPath: string) {
158-
const content = fs.readFileSync(prismaSchemaPath, 'utf-8');
159-
const found = content.match(/^\s*url\s*=(\s|")*([^"]+)(\s|")*$/m);
160-
if (!found) {
161-
throw new Error('No url found in prisma schema');
162-
}
163-
const dbPath = found[2]!;
164-
// convert 'file:./dev.db' to './dev.db'
165-
const r = path.join(path.dirname(prismaSchemaPath), dbPath.replace(/^file:/, ''));
166-
return r;
167-
}

packages/testtools/src/schema.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,21 +7,21 @@ import path from 'node:path';
77
import { match } from 'ts-pattern';
88
import { createTestProject } from './project';
99

10-
function makePrelude(provider: 'sqlite' | 'postgresql', dbName?: string) {
10+
function makePrelude(provider: 'sqlite' | 'postgresql', dbUrl?: string) {
1111
return match(provider)
1212
.with('sqlite', () => {
1313
return `
1414
datasource db {
1515
provider = 'sqlite'
16-
url = '${dbName ?? ':memory:'}'
16+
url = '${dbUrl ?? 'file:./test.db'}'
1717
}
1818
`;
1919
})
2020
.with('postgresql', () => {
2121
return `
2222
datasource db {
2323
provider = 'postgresql'
24-
url = 'postgres://postgres:postgres@localhost:5432/${dbName}'
24+
url = '${dbUrl ?? 'postgres://postgres:postgres@localhost:5432/db'}'
2525
}
2626
`;
2727
})
@@ -31,15 +31,14 @@ datasource db {
3131
export async function generateTsSchema(
3232
schemaText: string,
3333
provider: 'sqlite' | 'postgresql' = 'sqlite',
34-
dbName?: string,
34+
dbUrl?: string,
3535
extraSourceFiles?: Record<string, string>,
3636
) {
3737
const workDir = createTestProject();
38-
console.log(`Work directory: ${workDir}`);
3938

4039
const zmodelPath = path.join(workDir, 'schema.zmodel');
4140
const noPrelude = schemaText.includes('datasource ');
42-
fs.writeFileSync(zmodelPath, `${noPrelude ? '' : makePrelude(provider, dbName)}\n\n${schemaText}`);
41+
fs.writeFileSync(zmodelPath, `${noPrelude ? '' : makePrelude(provider, dbUrl)}\n\n${schemaText}`);
4342

4443
const pluginModelFiles = glob.sync(path.resolve(__dirname, '../../runtime/src/plugins/**/plugin.zmodel'));
4544

tests/e2e/cal.com/cal-com.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import path from 'node:path';
66
describe('Cal.com e2e tests', () => {
77
it('has a working schema', async () => {
88
await expect(
9-
generateTsSchema(fs.readFileSync(path.join(__dirname, 'schema.zmodel'), 'utf8'), 'postgresql', 'cal-com'),
9+
generateTsSchema(fs.readFileSync(path.join(__dirname, 'schema.zmodel'), 'utf8'), 'postgresql'),
1010
).resolves.toBeTruthy();
1111
});
1212
});

tests/e2e/formbricks/formbricks.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import path from 'node:path';
66
describe('Formbricks e2e tests', () => {
77
it('has a working schema', async () => {
88
await expect(
9-
generateTsSchema(fs.readFileSync(path.join(__dirname, 'schema.zmodel'), 'utf8'), 'postgresql', 'cal-com'),
9+
generateTsSchema(fs.readFileSync(path.join(__dirname, 'schema.zmodel'), 'utf8'), 'postgresql'),
1010
).resolves.toBeTruthy();
1111
});
1212
});

tests/e2e/trigger.dev/trigger-dev.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { describe, expect, it } from 'vitest';
66
describe('Trigger.dev e2e tests', () => {
77
it('has a working schema', async () => {
88
await expect(
9-
generateTsSchema(fs.readFileSync(path.join(__dirname, 'schema.zmodel'), 'utf8'), 'postgresql', 'cal-com'),
9+
generateTsSchema(fs.readFileSync(path.join(__dirname, 'schema.zmodel'), 'utf8'), 'postgresql'),
1010
).resolves.toBeTruthy();
1111
});
1212
});

0 commit comments

Comments
 (0)