Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 34 additions & 2 deletions packages/vitest/src/node/test-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,21 @@ import { serializeValue } from '@vitest/utils/serialize'
import { parseErrorStacktrace, parseStacktrace } from '@vitest/utils/source-map'
import { extractSourcemapFromFile } from '@vitest/utils/source-map/node'
import mime from 'mime/lite'
import { basename, extname, resolve } from 'pathe'
import { basename, extname, relative, resolve } from 'pathe'
import { withLabel } from './reporters/renderers/utils'

export class TestRun {
private externalSourceMaps = new Map<string, unknown>()
// the first project that attached each file in this run
private attachmentProjects = new Map<string, string>()
private warnedProjectPairs = new Set<string>()

constructor(private vitest: Vitest) {}

async start(specifications: TestSpecification[]): Promise<void> {
this.externalSourceMaps.clear()
this.attachmentProjects.clear()
this.warnedProjectPairs.clear()
const filepaths = specifications.map((spec) => spec.moduleId)
this.vitest.state.collectPaths(filepaths)

Expand Down Expand Up @@ -345,9 +351,10 @@ export class TestRun {
if (path && !path.startsWith('http://') && !path.startsWith('https://')) {
const currentPath = resolve(project.config.root, path)
const hash = createHash('sha1').update(currentPath).digest('hex')
const suffix = this.getProjectSuffix(project, currentPath)
const newPath = resolve(
project.config.attachmentsDir,
`${filename ? `${sanitizeFilePath(filename)}-` : ''}${hash}${extname(currentPath)}`,
`${filename ? `${sanitizeFilePath(filename)}-` : ''}${hash}${suffix}${extname(currentPath)}`,
)
if (!existsSync(project.config.attachmentsDir)) {
await mkdir(project.config.attachmentsDir, { recursive: true })
Expand All @@ -361,6 +368,31 @@ export class TestRun {
return attachment
}

// the copies of a file that other projects attach get the project name,
// so each project keeps its own copy
private getProjectSuffix(project: TestProject, path: string): string {
const firstProject = this.attachmentProjects.get(path)
if (firstProject === undefined) {
this.attachmentProjects.set(path, project.name)
return ''
}
if (firstProject === project.name) {
return ''
}
const pair = `${firstProject}\0${project.name}`
if (!this.warnedProjectPairs.has(pair)) {
this.warnedProjectPairs.add(pair)
this.vitest.logger.warn(
withLabel(
'yellow',
'Vitest',
`The projects "${firstProject}" and "${project.name}" attach the same file "${relative(this.vitest.config.root, path)}", so they can overwrite each other's file. Save the file to a different path in each project.`,
),
)
}
return `-${sanitizeFilePath(project.name)}`
}

private async reportChildren(children: TestCollection) {
for (const child of children) {
if (child.type === 'test') {
Expand Down
40 changes: 40 additions & 0 deletions test/e2e/test/annotations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -722,3 +722,43 @@ test("world", ({ annotate }) => {
]
`)
})

test('projects that attach the same file keep their own copies', async () => {
const result = await runInlineTests(
{
'invoice.test.js': `
import { writeFileSync } from 'node:fs'
import { test } from 'vitest'
test('renders the invoice', async ({ annotate }) => {
writeFileSync(new URL('./invoice.html', import.meta.url), '<p>' + process.env.LOCALE + '</p>')
await annotate('invoice', { path: './invoice.html' })
})
`,
},
{
projects: [
{ extends: true, test: { name: 'en', env: { LOCALE: 'en' }, sequence: { groupOrder: 1 } } },
{ extends: true, test: { name: 'de', env: { LOCALE: 'de' }, sequence: { groupOrder: 2 } } },
],
},
)
expect(result.stderr).toMatchInlineSnapshot(`
" Vitest The projects "en" and "de" attach the same file "invoice.html", so they can overwrite each other's file. Save the file to a different path in each project.
"
`)
const copies = Object.fromEntries(
result.results.map((module) => {
const [testCase] = module.children.allTests()
const copy = testCase.annotations()[0]?.attachment?.path ?? ''
return [
module.project.name,
[path.basename(copy).replace(/[\da-f]{40}/, '<hash>'), readFileSync(copy, 'utf-8')],
]
}),
)
expect(copies).toEqual({
en: ['invoice-<hash>.html', '<p>en</p>'],
de: ['invoice-<hash>-de.html', '<p>de</p>'],
})
})
Loading