You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

100 lines
2.6 KiB

import { describe, expect, it } from 'vitest'
import { Scope, startModules, type Module } from '@template/core'
describe('module lifecycle', () => {
it('orders dependencies and disposes in reverse order exactly once', async () => {
const operations: string[] = []
const modules: Module<null>[] = ['feature', 'foundation'].map((id) => ({
id,
dependsOn: id === 'feature' ? ['foundation'] : [],
setup(_context, scope) {
operations.push(`start:${id}`)
scope.add(() => {
operations.push(`stop:${id}`)
})
}
}))
const root = await startModules(modules, null)
await root.dispose()
await root.dispose()
expect(operations).toEqual([
'start:foundation',
'start:feature',
'stop:feature',
'stop:foundation'
])
})
it('rolls back the partially initialized module and earlier dependencies', async () => {
const operations: string[] = []
await expect(
startModules(
[
{
id: 'base',
setup(_context, scope) {
scope.add(() => {
operations.push('base')
})
}
},
{
id: 'broken',
dependsOn: ['base'],
setup(_context, scope) {
scope.add(() => {
operations.push('broken')
})
throw new Error('failed')
}
}
],
null
)
).rejects.toThrow('failed')
expect(operations).toEqual(['broken', 'base'])
})
it('rejects invalid graphs before running any setup', async () => {
let started = false
const setup = (): void => {
started = true
}
await expect(
startModules(
[
{ id: 'a', dependsOn: ['b'], setup },
{ id: 'b', dependsOn: ['a'], setup }
],
null
)
).rejects.toThrow('Circular')
await expect(startModules([{ id: 'a', dependsOn: ['missing'], setup }], null)).rejects.toThrow(
'Missing'
)
await expect(
startModules(
[
{ id: 'a', setup },
{ id: 'a', setup }
],
null
)
).rejects.toThrow('Duplicate')
expect(started).toBe(false)
})
it('continues cleanup when one resource fails', async () => {
const scope = new Scope()
let cleaned = false
scope.add(() => {
cleaned = true
})
scope.add(() => {
throw new Error('cleanup failed')
})
await expect(scope.dispose()).rejects.toThrow('Cleanup failed')
expect(cleaned).toBe(true)
expect(() => scope.add(() => {})).toThrow('already disposed')
})
})