This repository has been archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path__testers__.ts
271 lines (246 loc) · 8.82 KB
/
__testers__.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import { PrismaTemplates } from '../../src'
import { konn, providers } from 'konn'
import { values } from 'lodash'
import stripAnsi from 'strip-ansi'
import { ClientBase } from '@prisma-spectrum/reflector/dist-cjs/Client'
import { Reflector } from '@prisma-spectrum/reflector'
import { PrismaClient } from '@prisma/client'
import { log } from 'floggy'
import { casesHandled } from '~/src/utils'
import { PrismaClientOptions } from '@prisma/client/runtime'
export interface DBTestParams {
templateName: PrismaTemplates.$Types.Template['_tag']
expectedDevOutput: RegExp | string
datasourceProvider: Reflector.Schema.DatasourceProviderNormalized
templateConfig?: Pick<PrismaTemplates.$Types.BaseTemplateParameters, 'referentialIntegrity'>
}
async function dropDatabase(
prismaClient: PrismaClient,
databaseName: string,
datasourceProvider: Reflector.Schema.DatasourceProviderNormalized
) {
switch (datasourceProvider) {
case 'postgres':
try {
await prismaClient.$executeRawUnsafe(`DROP DATABASE ${databaseName} WITH (FORCE);`)
} catch (error) {
const isDatabaseNotFoundError = error instanceof Error && error.message.match(/does not exist/)
if (!isDatabaseNotFoundError) throw error
}
return
case 'mysql':
try {
await prismaClient.$executeRawUnsafe(`DROP DATABASE IF EXISTS ${databaseName};`)
} catch (error) {
const isDatabaseNotFoundError = error instanceof Error && error.message.match(/database not found/)
if (!isDatabaseNotFoundError) throw error
}
return
case 'cockroachdb':
case 'mongodb':
case 'sqlserver':
case 'sqlite':
throw new Error(`Testing with ${datasourceProvider} not supported yet.`)
default:
casesHandled(datasourceProvider)
}
}
async function createDatabase(
prismaClient: PrismaClient,
databaseName: string,
datasourceProvider: Reflector.Schema.DatasourceProviderNormalized
) {
switch (datasourceProvider) {
case 'postgres':
try {
await prismaClient.$executeRawUnsafe(`create database ${databaseName}`)
} catch (e) {
log.info(`Error initialising DB ${databaseName}`)
}
return
case 'mysql':
return prismaClient.$executeRawUnsafe(`CREATE DATABASE IF NOT EXISTS ${databaseName}`)
case 'cockroachdb':
case 'mongodb':
case 'sqlserver':
case 'sqlite':
throw new Error(`Testing with ${datasourceProvider} not supported yet.`)
default:
throw new Error(`Case not handled for ${datasourceProvider}`)
}
}
export function getConnectionStringBase(
dataSourceProvider: Reflector.Schema.DatasourceProviderNormalized
): string {
switch (dataSourceProvider) {
case 'postgres':
return 'postgres://prisma:prisma@localhost:5401'
case 'mysql':
return 'mysql://prisma:prisma@localhost:33577'
case 'cockroachdb':
case 'mongodb':
case 'sqlserver':
case 'sqlite':
throw new Error(`Testing with ${dataSourceProvider} not supported yet.`)
default:
throw new Error(`Case not handled for ${dataSourceProvider}`)
}
}
export async function getAdminPrismaClient(
databaseUrlBase: string,
CtxPrismaClient: new (options: PrismaClientOptions) => PrismaClient,
dataSourceProvider: Reflector.Schema.DatasourceProviderNormalized
): Promise<PrismaClient> {
switch (dataSourceProvider) {
case 'postgres':
return new CtxPrismaClient({
datasources: {
db: {
url: `${databaseUrlBase}/postgres`,
},
},
}) as ClientBase
case 'mysql':
return new CtxPrismaClient({
datasources: {
db: {
url: `${databaseUrlBase}/mysql`,
},
},
})
default:
throw new Error(`Case not handled for ${dataSourceProvider}`)
}
}
export const testTemplate = (params: DBTestParams) => {
jest.setTimeout(100_000)
const ctx = konn()
.useBeforeAll(providers.dir())
.useBeforeAll(providers.run())
.beforeAll(async (ctx) => {
const connectionStringBase = getConnectionStringBase(params.datasourceProvider)
const datasourceProvider = params.datasourceProvider
const Template = PrismaTemplates.Templates[params.templateName]
const template = new Template({
dataproxy: false,
datasourceProvider,
repositoryOwner: 'prisma',
repositoryHandle: `templates-node-test-${Template.metadata.handles.kebab}`,
referentialIntegrity: params.templateConfig?.referentialIntegrity,
})
const databaseUrlBase = connectionStringBase
const databaseName = template.metadata.handles.snake
const databaseUrl = `${databaseUrlBase}/${databaseName}`
const getPrismaClientModule = () => import(`${ctx.fs.cwd()}/node_modules/@prisma/client`)
const getApplicationPrisma = async () =>
new (await getPrismaClientModule()).PrismaClient({
datasources: {
db: {
url: databaseUrl,
},
},
}) as ClientBase
const getAdminPrisma = async () => {
return getAdminPrismaClient(
databaseUrlBase,
(await getPrismaClientModule()).PrismaClient,
datasourceProvider
)
}
const dropTestDatabase = async () => {
return dropDatabase(await getAdminPrisma(), databaseName, datasourceProvider)
}
const createTestDatabase = async () => {
return createDatabase(await getAdminPrisma(), databaseName, datasourceProvider)
}
return {
getApplicationPrisma,
getAdminPrisma,
template,
dropTestDatabase,
createTestDatabase,
databaseName,
databaseUrl,
}
})
.afterAll(async (ctx) => {
if (params.templateName !== 'Empty') {
await ctx.dropTestDatabase?.()
}
})
.done()
/**
* Test 1
* Check that the initialization script works. This includes running migrate triggering generators and executing the seed.
*/
it(`${params.templateName} - init script should work`, async () => {
if (!process.env.CI) console.log(ctx.fs.cwd())
console.log(`Starting the test ${params.templateName} for DB ${params.datasourceProvider}`)
/**
* Setup the project. Write files to disk, install deps, etc.
*/
await ctx.fs.writeAsync(`.npmrc`, `scripts-prepend-node-path=true`)
await Promise.all(values(ctx.template.files).map((file) => ctx.fs.writeAsync(file.path, file.content)))
ctx.run(`npm install`)
await ctx.fs.writeAsync('.env', `DATABASE_URL='${ctx.databaseUrl}'`)
console.log('Writing to .env file and .npmrc')
/**
* Exit early for empty template as there is nothing more to test.
*/
if (ctx.template._tag === 'Empty') return
/**
* Drop database before running the tests case it wasn't cleaned up from the previous test run.
*/
await ctx.dropTestDatabase()
await ctx.createTestDatabase()
const initResult = await ctx.runAsync(`npm run init`, { reject: true })
expect(initResult.stderr).toMatch('')
expect(stripAnsi(initResult.stdout)).toMatch('Generated Prisma Client')
expect(stripAnsi(initResult.stdout)).toMatch('Running seed command')
})
/**
* Test 2
* Check that the template migration script works.
*/
if (params.templateName !== 'Empty') {
it(`${params.templateName} - template migration script should work`, async () => {
await ctx.dropTestDatabase()
await ctx.createTestDatabase()
const prisma = await ctx.getApplicationPrisma()
await Reflector.Client.runMigrationScript(
prisma,
ctx.template.migrationScript,
params.datasourceProvider
)
})
}
/**
* Test 3
* Check the seed again but this time using the derived seed function.
*/
if (params.templateName !== 'Empty') {
it(`${params.templateName} - seed using the derived seed function should work`, async () => {
const prisma = await ctx.getApplicationPrisma()
// TODO improve seed scripts to return reports that we can use to capture feedback here not to mention for users generally.
await ctx.template.seed({ prisma })
})
}
/**
* Test 4
* Check the development project script. For most templates this will run some kind of sandbox script against the database.
*
* The Nextjs template launches next dev for its dev script and thus is exempt from this test.
*/
it(`${params.templateName} - development project script should work`, async () => {
if (ctx.template._tag !== 'Nextjs') {
const devResult = ctx.run(`npm run dev`, { reject: true })
expect(devResult.stderr).toMatch('')
expect(devResult.stdout).toMatch(params.expectedDevOutput)
}
// TODO Test the Vercel API (next dev for Blog template)
// await ctx.fs.writeAsync('.vercel/project.json', {
// projectId: 'prj_6yrTe9CGQagAQwGjr7JEejkxhz3A',
// orgId: 'team_ASKXQ5Yc1an2RqJc5BCI9rGw',
// })
})
}