-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
setupTestSuiteEnv.ts
283 lines (255 loc) · 8.93 KB
/
setupTestSuiteEnv.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
272
273
274
275
276
277
278
279
280
281
282
283
import { assertNever } from '@prisma/internals'
import * as miniProxy from '@prisma/mini-proxy'
import cuid from 'cuid'
import fs from 'fs-extra'
import path from 'path'
import { match } from 'ts-pattern'
import { Script } from 'vm'
import { DbDrop } from '../../../../migrate/src/commands/DbDrop'
import { DbExecute } from '../../../../migrate/src/commands/DbExecute'
import { DbPush } from '../../../../migrate/src/commands/DbPush'
import type { NamedTestSuiteConfig } from './getTestSuiteInfo'
import { getTestSuiteFolderPath, getTestSuiteSchemaPath } from './getTestSuiteInfo'
import { Providers } from './providers'
import { ProviderFlavor, ProviderFlavors } from './relationMode/ProviderFlavor'
import type { TestSuiteMeta } from './setupTestSuiteMatrix'
import { AlterStatementCallback, ClientMeta } from './types'
const DB_NAME_VAR = 'PRISMA_DB_NAME'
/**
* Copies the necessary files for the generated test suite folder.
* @param suiteMeta
* @param suiteConfig
*/
export async function setupTestSuiteFiles(suiteMeta: TestSuiteMeta, suiteConfig: NamedTestSuiteConfig) {
const suiteFolder = getTestSuiteFolderPath(suiteMeta, suiteConfig)
// we copy the minimum amount of files needed for the test suite
await fs.copy(path.join(suiteMeta.testRoot, 'prisma'), path.join(suiteFolder, 'prisma'))
await fs.mkdir(path.join(suiteFolder, suiteMeta.rootRelativeTestDir), { recursive: true })
await copyPreprocessed(
suiteMeta.testPath,
path.join(suiteFolder, suiteMeta.rootRelativeTestPath),
suiteConfig.matrixOptions,
)
}
/**
* Copies test file into generated subdirectory and pre-processes it
* in the following way:
*
* 1. Adjusts relative imports so they'll work from generated subfolder
* 2. Evaluates @ts-test-if magic comments and replaces them with @ts-expect-error
* if necessary
*
* @param from
* @param to
* @param suiteConfig
*/
async function copyPreprocessed(from: string, to: string, suiteConfig: Record<string, string>): Promise<void> {
// we adjust the relative paths to work from the generated folder
const contents = await fs.readFile(from, 'utf8')
const newContents = contents
.replace(/'..\//g, "'../../../")
.replace(/'.\//g, "'../../")
.replace(/'..\/..\/node_modules/g, "'./node_modules")
.replace(/\/\/\s*@ts-ignore.*/g, '')
.replace(/\/\/\s*@ts-test-if:(.+)/g, (match, condition) => {
if (!evaluateMagicComment(condition, suiteConfig)) {
return '// @ts-expect-error'
}
return match
})
await fs.writeFile(to, newContents, 'utf8')
}
/**
* Evaluates the condition from @ts-test-if magic comment as
* a JS expression.
* All properties from suite config are available as variables
* within the expression.
*
* @param conditionFromComment
* @param suiteConfig
* @returns
*/
function evaluateMagicComment(conditionFromComment: string, suiteConfig: Record<string, string>): boolean {
const script = new Script(conditionFromComment)
const value = script.runInNewContext({
...suiteConfig,
})
return Boolean(value)
}
/**
* Write the generated test suite schema to the test suite folder.
* @param suiteMeta
* @param suiteConfig
* @param schema
*/
export async function setupTestSuiteSchema(
suiteMeta: TestSuiteMeta,
suiteConfig: NamedTestSuiteConfig,
schema: string,
) {
const schemaPath = getTestSuiteSchemaPath(suiteMeta, suiteConfig)
await fs.writeFile(schemaPath, schema)
}
/**
* Create a database for the generated schema of the test suite.
* @param suiteMeta
* @param suiteConfig
*/
export async function setupTestSuiteDatabase(
suiteMeta: TestSuiteMeta,
suiteConfig: NamedTestSuiteConfig,
errors: Error[] = [],
alterStatementCallback?: AlterStatementCallback,
) {
const schemaPath = getTestSuiteSchemaPath(suiteMeta, suiteConfig)
try {
const consoleInfoMock = jest.spyOn(console, 'info').mockImplementation()
await DbPush.new().parse(['--schema', schemaPath, '--force-reset', '--skip-generate'])
if (alterStatementCallback) {
const prismaDir = path.dirname(schemaPath)
const timestamp = new Date().getTime()
const provider = suiteConfig.matrixOptions['provider'] as Providers
await fs.promises.mkdir(`${prismaDir}/migrations/${timestamp}`, { recursive: true })
await fs.promises.writeFile(`${prismaDir}/migrations/migration_lock.toml`, `provider = "${provider}"`)
await fs.promises.writeFile(
`${prismaDir}/migrations/${timestamp}/migration.sql`,
alterStatementCallback(provider),
)
await DbExecute.new().parse([
'--file',
`${prismaDir}/migrations/${timestamp}/migration.sql`,
'--schema',
`${schemaPath}`,
])
}
consoleInfoMock.mockRestore()
} catch (e) {
errors.push(e as Error)
if (errors.length > 2) {
throw new Error(errors.map((e) => `${e.message}\n${e.stack}`).join(`\n`))
} else {
await setupTestSuiteDatabase(suiteMeta, suiteConfig, errors) // retry logic
}
}
}
/**
* Drop the database for the generated schema of the test suite.
* @param suiteMeta
* @param suiteConfig
*/
export async function dropTestSuiteDatabase(
suiteMeta: TestSuiteMeta,
suiteConfig: NamedTestSuiteConfig,
errors: Error[] = [],
) {
const schemaPath = getTestSuiteSchemaPath(suiteMeta, suiteConfig)
try {
const consoleInfoMock = jest.spyOn(console, 'info').mockImplementation()
await DbDrop.new().parse(['--schema', schemaPath, '--force', '--preview-feature'])
consoleInfoMock.mockRestore()
} catch (e) {
errors.push(e as Error)
if (errors.length > 2) {
throw new Error(errors.map((e) => `${e.message}\n${e.stack}`).join(`\n`))
} else {
await dropTestSuiteDatabase(suiteMeta, suiteConfig, errors) // retry logic
}
}
}
export type DatasourceInfo = {
envVarName: string
databaseUrl: string
dataProxyUrl?: string
}
/**
* Generate a random string to be used as a test suite db name, and derive the
* corresponding database URL and, if required, Mini-Proxy connection string to
* that database.
*
* @param suiteConfig
* @param clientMeta
* @returns
*/
export function setupTestSuiteDbURI(suiteConfig: Record<string, string>, clientMeta: ClientMeta): DatasourceInfo {
const provider = suiteConfig['provider'] as Providers
const providerFlavor = suiteConfig['providerFlavor'] as ProviderFlavor | undefined
const dbId = cuid()
const { envVarName, newURI } = match(providerFlavor)
.with(undefined, () => {
const envVarName = `DATABASE_URI_${provider}`
const newURI = getDbUrl(provider)
return { envVarName, newURI }
})
.otherwise(() => {
const envVarName = `DATABASE_URI_${providerFlavor!}`
const newURI = getDbUrlFromFlavor(providerFlavor, provider)
return { envVarName, newURI }
})
const databaseUrl = newURI.replace(DB_NAME_VAR, dbId)
let dataProxyUrl: string | undefined
if (clientMeta.dataProxy) {
dataProxyUrl = miniProxy.generateConnectionString({
databaseUrl,
envVar: envVarName,
port: miniProxy.defaultServerConfig.port,
})
}
return {
envVarName,
databaseUrl,
dataProxyUrl,
}
}
/**
* Returns configured database URL for specified provider
* @param provider
* @returns
*/
function getDbUrl(provider: Providers): string {
switch (provider) {
case Providers.SQLITE:
return `file:${DB_NAME_VAR}.db`
case Providers.MONGODB:
return requireEnvVariable('TEST_FUNCTIONAL_MONGO_URI')
case Providers.POSTGRESQL:
return requireEnvVariable('TEST_FUNCTIONAL_POSTGRES_URI')
case Providers.MYSQL:
return requireEnvVariable('TEST_FUNCTIONAL_MYSQL_URI')
case Providers.COCKROACHDB:
return requireEnvVariable('TEST_FUNCTIONAL_COCKROACH_URI')
case Providers.SQLSERVER:
return requireEnvVariable('TEST_FUNCTIONAL_MSSQL_URI')
default:
assertNever(provider, `No URL for provider ${provider} configured`)
}
}
/**
* Returns configured database URL for specified provider flavor, falling back to
* `getDbUrl(provider)` if no flavor-specific URL is configured.
* @param providerFlavor provider variant, e.g. `vitess` for `mysql`
* @param provider provider supported by Prisma, e.g. `mysql`
*/
function getDbUrlFromFlavor(providerFlavor: ProviderFlavor | undefined, provider: Providers): string {
return match(providerFlavor)
.with(ProviderFlavors.VITESS_8, () => requireEnvVariable('TEST_FUNCTIONAL_VITESS_8_URI'))
.otherwise(() => getDbUrl(provider))
}
/**
* Gets the value of environment variable or throws error if it is not set
* @param varName
* @returns
*/
function requireEnvVariable(varName: string): string {
const value = process.env[varName]
if (!value) {
throw new Error(
`Required env variable ${varName} is not set. See https://github.com/prisma/prisma/blob/main/TESTING.md for instructions`,
)
}
if (!value.includes(DB_NAME_VAR)) {
throw new Error(
`Env variable ${varName} must include ${DB_NAME_VAR} placeholder. See https://github.com/prisma/prisma/blob/main/TESTING.md for instructions`,
)
}
return value
}