1 import { asValue } from "@medusajs/framework/awilix"
2 import { logger } from "@medusajs/framework/logger"
3 import { Migrator } from "@medusajs/framework/migrations"
4 import { MedusaAppOutput } from "@medusajs/framework/modules-sdk"
5 import { MedusaContainer } from "@medusajs/framework/types"
6 import {
7 ContainerRegistrationKeys,
8 getResolvedPlugins,
9 mergePluginModules,
10 } from "@medusajs/framework/utils"
11 import { dbTestUtilFactory, getDatabaseURL } from "./database"
12 import {
13 applyEnvVarsToProcess,
14 clearInstances,
15 closeWaitingroomClient,
16 configLoaderOverride,
17 formatError,
18 initDb,
19 migrateDatabase,
20 migrateSearchIndexes,
21 startApp,
22 syncLinks,
23 } from "./medusa-test-runner-utils"
24 import { waitWorkflowExecutions } from "./medusa-test-runner-utils/wait-workflow-executions"
25 import { ulid } from "ulid"
26
27 export interface MedusaSuiteOptions {
28 dbConnection: any // knex instance
29 getContainer: () => MedusaContainer
30 api: any
31 dbUtils: {
32 create: (dbName: string) => Promise<void>
33 snapshot: (options?: { templateName?: string }) => Promise<void>
34 restore: (options?: { templateName?: string }) => Promise<void>
35 teardown: (options: { schema?: string }) => Promise<void>
36 shutdown: (dbName: string) => Promise<void>
37 }
38 dbConfig: {
39 dbName: string
40 schema: string
41 clientUrl: string
42 }
43 getMedusaApp: () => MedusaAppOutput
44 utils: {
45 waitWorkflowExecutions: () => Promise<void>
46 }
47 }
48
49 interface TestRunnerConfig {
50 moduleName?: string
51 env?: Record<string, any>
52 dbName?: string
53 medusaConfigFile?: string
54 schema?: string
55 debug?: boolean
56 hooks?: {
57 beforeServerStart?: (container: MedusaContainer) => Promise<void>
58 }
59 cwd?: string
60 }
61
62 class MedusaTestRunner {
63 private dbName: string
64 private dbTemplateName: string
65 private schema: string
66 private modulesConfigPath: string
67 private cwd: string
68 private env: Record<string, any>
69 private debug: boolean
70
71 private dbUtils: ReturnType<typeof dbTestUtilFactory>
72 private dbConfig: {
73 dbName: string
74 clientUrl: string
75 schema: string
76 debug: boolean
77 }
78
79 private globalContainer: MedusaContainer | null = null
80 private apiUtils: any = null
81 private loadedApplication: any = null
82 private shutdown: () => Promise<void> = async () => void 0
83 private hooks: TestRunnerConfig["hooks"] = {}
84 private databaseTemplateReady = false
85 private skipNextRestore = false
86 private restoreEnvVars: () => void = () => void 0
87
88 constructor(config: TestRunnerConfig) {
89 const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
90 const moduleName = config.moduleName ?? ulid()
91 this.dbName =
92 config.dbName ??
93 `medusa-${moduleName.toLowerCase()}-integration-${tempName}`
94 this.dbTemplateName = `${this.dbName}-template`
95 this.schema = config.schema ?? "public"
96 this.cwd = config.cwd ?? config.medusaConfigFile ?? process.cwd()
97 this.modulesConfigPath = config.medusaConfigFile ?? this.cwd
98 this.env = config.env ?? {}
99 this.debug = config.debug ?? false
100
101 this.dbUtils = dbTestUtilFactory()
102 this.dbConfig = {
103 dbName: this.dbName,
104 clientUrl: getDatabaseURL(this.dbName),
105 schema: this.schema,
106 debug: this.debug,
107 }
108 this.hooks = config.hooks ?? {}
109
110 this.setupProcessHandlers()
111 }
112
113 private setupProcessHandlers(): void {
114 process.on("SIGTERM", async () => {
115 await this.cleanup()
116 process.exit(0)
117 })
118
119 process.on("SIGINT", async () => {
120 await this.cleanup()
121 process.exit(0)
122 })
123 }
124
125 private createApiProxy(): any {
126 return new Proxy(
127 {},
128 {
129 get: (target, prop) => {
130 return this.apiUtils?.[prop]
131 },
132 }
133 )
134 }
135
136 private createDbConnectionProxy(): any {
137 return new Proxy(
138 {},
139 {
140 get: (target, prop) => {
141 return this.dbUtils.pgConnection_?.[prop]
142 },
143 }
144 )
145 }
146
147 private async initializeDatabase(): Promise<void> {
148 try {
149 logger.info(`Creating database ${this.dbName}`)
150 await this.dbUtils.create(this.dbName)
151 this.dbUtils.pgConnection_ = await initDb()
152 } catch (error) {
153 logger.error(`Error initializing database:\n${formatError(error)}`)
154 await this.cleanup()
155 throw error
156 }
157 }
158
159 private async setupApplication(): Promise<void> {
160 const { container, MedusaAppLoader } = await import("@medusajs/framework")
161 const appLoader = new MedusaAppLoader({
162 medusaConfigPath: this.modulesConfigPath,
163 cwd: this.cwd,
164 })
165
166 // Load plugins modules
167 const configModule = container.resolve(
168 ContainerRegistrationKeys.CONFIG_MODULE
169 )
170 const plugins = await getResolvedPlugins(this.cwd, configModule)
171 mergePluginModules(configModule, plugins, this.cwd)
172
173 container.register({
174 [ContainerRegistrationKeys.LOGGER]: asValue(logger),
175 })
176
177 if (this.hooks?.beforeServerStart) {
178 await this.hooks.beforeServerStart(container)
179 }
180
181 await this.initializeDatabase()
182
183 const migrator = new Migrator({ container })
184 await migrator.ensureMigrationsTable()
185
186 logger.info(
187 `Migrating database with core migrations, links, and search indexes ${this.dbName}`
188 )
189 await migrateDatabase(appLoader)
190 await syncLinks(appLoader, this.modulesConfigPath, container, logger)
191 await clearInstances()
192
193 // The app is booted here as well as by `startApp` below, and the two share a
194 // container, so the Search Module built here is the one the test ends up with.
195 // The definitions have to be registered before that, the same way the http
196 // loader does it. `clearInstances` empties the registry, hence the placement.
197 const { loadSearchIndexes } = require("@medusajs/medusa/loaders/search")
198 await loadSearchIndexes({
199 plugins: await getResolvedPlugins(this.cwd, configModule, true),
200 configModule,
201 logger,
202 })
203
204 this.loadedApplication = await appLoader.load()
205
206 // Same role as `db:migrate:search` / link sync: create physical indexes
207 // before the HTTP app starts (and before suites seed data that is ingested).
208 await migrateSearchIndexes(container, logger)
209
210 try {
211 const {
212 shutdown,
213 container: appContainer,
214 port,
215 } = await startApp({
216 cwd: this.modulesConfigPath,
217 env: this.env,
218 })
219
220 this.globalContainer = appContainer
221 this.shutdown = async () => {
222 await shutdown()
223 if (this.apiUtils?.cancelToken?.source) {
224 this.apiUtils.cancelToken.source.cancel(
225 "Request canceled by shutdown"
226 )
227 }
228 }
229
230 const { default: axios } = (await import("axios")) as any
231 const cancelTokenSource = axios.CancelToken.source()
232
233 this.apiUtils = axios.create({
234 baseURL: `http://localhost:${port}`,
235 cancelToken: cancelTokenSource.token,
236 })
237
238 this.apiUtils.cancelToken = { source: cancelTokenSource }
239
240 await waitWorkflowExecutions(this.globalContainer as MedusaContainer)
241 } catch (error) {
242 logger.error(`Error starting the app:\n${formatError(error)}`)
243 await this.cleanup()
244 throw error
245 }
246 }
247
248 public async cleanup(): Promise<void> {
249 try {
250 process.removeAllListeners("SIGTERM")
251 process.removeAllListeners("SIGINT")
252
253 await this.shutdown()
254 await clearInstances()
255
256 if (this.apiUtils?.cancelToken?.source) {
257 this.apiUtils.cancelToken.source.cancel("Cleanup")
258 }
259
260 if (this.globalContainer?.dispose) {
261 await this.globalContainer.dispose()
262 }
263
264 if (this.databaseTemplateReady) {
265 await this.dbUtils.dropTemplate(this.dbTemplateName)
266 }
267
268 await this.dbUtils.shutdown(this.dbName)
269 await closeWaitingroomClient()
270
271 this.databaseTemplateReady = false
272 this.skipNextRestore = false
273 this.apiUtils = null
274 this.loadedApplication = null
275 this.globalContainer = null
276
277 if (global.gc) {
278 global.gc()
279 }
280 } catch (error) {
281 logger.error(`Error during cleanup:\n${formatError(error)}`)
282 } finally {
283 this.restoreEnvVars()
284 this.restoreEnvVars = () => void 0
285 }
286 }
287
288 public async beforeAll(): Promise<void> {
289 try {
290 this.setupProcessHandlers()
291 await configLoaderOverride(this.cwd, this.dbConfig)
292 this.restoreEnvVars = applyEnvVarsToProcess(this.env)
293 await this.setupApplication()
294 } catch (error) {
295 await this.cleanup()
296 throw error
297 }
298 }
299
300 private async snapshotDatabase(): Promise<void> {
301 await this.dbUtils.snapshot({
302 databaseName: this.dbName,
303 templateName: this.dbTemplateName,
304 })
305 this.databaseTemplateReady = true
306 }
307
308 public async beforeEach(): Promise<void> {
309 try {
310 if (!this.databaseTemplateReady) {
311 // Snapshot after the suite's own beforeAll hooks so custom schema changes
312 // (for example ad-hoc link tables) are included in the restore template.
313 await this.snapshotDatabase()
314 return
315 }
316
317 if (this.skipNextRestore) {
318 this.skipNextRestore = false
319 return
320 }
321
322 await this.dbUtils.restore({
323 databaseName: this.dbName,
324 templateName: this.dbTemplateName,
325 })
326 } catch (error) {
327 logger.error(`Error restoring database:\n${formatError(error)}`)
328 throw error
329 }
330 }
331
332 public async afterEach(): Promise<void> {
333 if (!this.globalContainer) {
334 return
335 }
336
337 try {
338 await waitWorkflowExecutions(this.globalContainer)
339 } catch (error) {
340 logger.error(
341 `Error waiting for workflow executions to finish:\n${formatError(
342 error
343 )}`
344 )
345 throw error
346 }
347 }
348
349 public getOptions(): MedusaSuiteOptions {
350 return {
351 api: this.createApiProxy(),
352 dbConnection: this.createDbConnectionProxy(),
353 getMedusaApp: () => this.loadedApplication,
354 getContainer: () => this.globalContainer as MedusaContainer,
355 dbConfig: {
356 dbName: this.dbName,
357 schema: this.schema,
358 clientUrl: this.dbConfig.clientUrl,
359 },
360 dbUtils: {
361 ...this.dbUtils,
362 snapshot: async (options) => {
363 await this.dbUtils.snapshot({
364 databaseName: this.dbName,
365 templateName: options?.templateName ?? this.dbTemplateName,
366 })
367 this.databaseTemplateReady = true
368 this.skipNextRestore = true
369 },
370 restore: (options) =>
371 this.dbUtils.restore({
372 databaseName: this.dbName,
373 templateName: options?.templateName ?? this.dbTemplateName,
374 }),
375 },
376 utils: {
377 waitWorkflowExecutions: () =>
378 waitWorkflowExecutions(this.globalContainer as MedusaContainer),
379 },
380 }
381 }
382 }
383
384 export function medusaIntegrationTestRunner({
385 moduleName,
386 dbName,
387 medusaConfigFile,
388 schema = "public",
389 env = {},
390 debug = false,
391 testSuite,
392 hooks,
393 cwd,
394 }: {
395 moduleName?: string
396 env?: Record<string, any>
397 dbName?: string
398 medusaConfigFile?: string
399 schema?: string
400 debug?: boolean
401 testSuite: (options: MedusaSuiteOptions) => void
402 hooks?: TestRunnerConfig["hooks"]
403 cwd?: string
404 }) {
405 const runner = new MedusaTestRunner({
406 moduleName,
407 dbName,
408 medusaConfigFile,
409 schema,
410 env,
411 debug,
412 hooks,
413 cwd,
414 })
415
416 return describe("", () => {
417 let testOptions: MedusaSuiteOptions
418
419 beforeAll(async () => {
420 await runner.beforeAll()
421 testOptions = runner.getOptions()
422 })
423
424 beforeEach(async () => {
425 await runner.beforeEach()
426 })
427
428 afterEach(async () => {
429 await runner.afterEach()
430 })
431
432 afterAll(async () => {
433 // Run main cleanup
434 await runner.cleanup()
435
436 // Clean references to the test options
437 for (const key in testOptions) {
438 if (typeof testOptions[key] === "function") {
439 testOptions[key] = null
440 } else if (
441 typeof testOptions[key] === "object" &&
442 testOptions[key] !== null
443 ) {
444 Object.keys(testOptions[key]).forEach((k) => {
445 testOptions[key][k] = null
446 })
447 testOptions[key] = null
448 }
449 }
450
451 // Encourage garbage collection
452 // @ts-ignore
453 testOptions = null
454
455 if (global.gc) {
456 global.gc()
457 }
458 })
459
460 // Run test suite with options
461 testSuite(runner.getOptions())
462 })
463 }