Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/vitest-dev/vscode. VS Code extension for Vitest vitest.dev/vscode
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499import type { RunnerTask, RunnerTestFile } from 'vitest'import type { ExtensionTestFileSpecification } from 'vitest-vscode-shared'import type { VitestProcessAPI } from './apiProcess'import type { TransformSchemaProvider } from './schemaProvider'import type { TagsManager } from './tagsManager'import type { TestFileMetadata } from './testTreeData'import { realpathSync } from 'node:fs'import { resolve } from 'node:path'import { basename, dirname, normalize } from 'pathe'import * as vscode from 'vscode'import { log } from './log'import { getTestData, TestCase, TestFile, TestFolder, TestSuite } from './testTreeData'import { ExtensionWatcher } from './watcher'
// testItem -> vscode.TestItem// testData -> our wrapper// task -> vitest.Task
export class TestTree extends vscode.Disposable { private flatTestItems = new Map<string, vscode.TestItem>() private fileItems: Map<string, vscode.TestItem> = new Map() private folderItems: Map<string, vscode.TestItem> = new Map()
// it's possible to have several test items for the same file // file test items have the project name in their id, so we need a separate map // to store all of them private testItemsByFile = new Map<string, vscode.TestItem[]>() // this is used by the "when" clause in commands private testFiles = new Set<string>()
private watcher: ExtensionWatcher
constructor( private readonly controller: vscode.TestController, private readonly loaderItem: vscode.TestItem, private readonly tagsManager: TagsManager, transformSchemaProvider: TransformSchemaProvider, ) { super(() => { this.folderItems.clear() this.fileItems.clear() this.flatTestItems.clear() this.testItemsByFile.clear() this.watcher.dispose() }) this.watcher = new ExtensionWatcher(this, transformSchemaProvider) }
public getFileTestItems(fsPath: string) { return this.testItemsByFile.get(normalize(fsPath)) || [] }
public getAllFileItems() { return [...this.fileItems.values()] }
public reset(workspaceFolders: vscode.WorkspaceFolder[]) { this.folderItems.clear() this.testItemsByFile.clear() this.fileItems.clear() this.flatTestItems.clear() this.watcher.reset()
this.loaderItem.busy = true
if (workspaceFolders.length === 1) { const rootItem = this.getOrCreateInlineFolderItem(workspaceFolders[0].uri) rootItem.children.replace([this.loaderItem]) } else { const folderItems = workspaceFolders.map((x) => { const item = this.getOrCreateWorkspaceFolderItem(x.uri) item.children.replace([]) item.busy = true return item }) this.controller.items.replace(folderItems) } }
discoverAllTestFiles(api: VitestProcessAPI, files: ExtensionTestFileSpecification[]) { const folderItem = this.folderItems.get(normalize(api.workspaceFolder.uri.fsPath)) if (folderItem) folderItem.busy = false
for (const [file, metadata] of files) this.getOrCreateFileTestItem(api, metadata, file)
return files }
getSymlinkFolder(uri: vscode.Uri) { const realPath = realpathSync(uri.fsPath) if (realPath === uri.fsPath) { return uri }
return vscode.Uri.file(realPath) }
// in cases where there is only a single workspace, we don't show it as a folder // this inline folder is required for "createFolderItem" to properly resolve the parent, // otherwise it will go into an infinite loop getOrCreateInlineFolderItem(folderUri: vscode.Uri) { const symlinkUri = this.getSymlinkFolder(folderUri) const id = normalize(symlinkUri.fsPath) const cached = this.folderItems.get(id) if (cached) return cached const item: vscode.TestItem = { id: symlinkUri.toString(), children: this.controller.items, uri: symlinkUri, label: '<root>', canResolveChildren: false, busy: false, parent: undefined, tags: [], range: undefined, error: undefined, } TestFolder.register(item) this.folderItems.set(id, item)
if (symlinkUri !== folderUri) { const originalId = normalize(folderUri.fsPath) this.folderItems.set(originalId, item) } return item }
getOrCreateWorkspaceFolderItem(folderUri: vscode.Uri) { const symlinkUri = this.getSymlinkFolder(folderUri) const folderId = normalize(symlinkUri.fsPath) const cached = this.folderItems.get(folderId) if (cached) return cached
const folderItem = this._createFolderItem(symlinkUri) this.folderItems.set(folderId, folderItem) // if item is symlink, also store it in the symlink location if (symlinkUri !== folderUri) { const originalId = normalize(folderUri.fsPath) this.folderItems.set(originalId, folderItem) } return folderItem }
getOrCreateFileTestItem(api: VitestProcessAPI, metadata: TestFileMetadata, file: string) { const project = metadata.project const normalizedFile = normalize(file) const fileId = `${normalizedFile}${project}` const cached = this.fileItems.get(fileId) if (cached) return cached
const fileUri = vscode.Uri.file(resolve(file)) const parentItem = this.getOrCreateFolderTestItem(api, dirname(file)) const label = `${basename(file)}${project ? ` [${project}]` : ''}` const testFileItem = this.controller.createTestItem(fileId, label, fileUri) // "description" looks nicer in the test explorer, // but it's not displayed in the gutter icon // testFileItem.description = project testFileItem.tags = [api.tag] testFileItem.canResolveChildren = true TestFile.register(testFileItem, parentItem, normalizedFile, api, metadata) parentItem.children.add(testFileItem) this.fileItems.set(fileId, testFileItem) const cachedItems = this.testItemsByFile.get(normalizedFile) || [] cachedItems.push(testFileItem) this.testItemsByFile.set(normalizedFile, cachedItems) this.testFiles.add(fileUri.fsPath) vscode.commands.executeCommand('setContext', 'vitest.testFiles', [...this.testFiles])
return testFileItem }
getOrCreateFolderTestItem(api: VitestProcessAPI, normalizedFolder: string) { const cached = this.folderItems.get(normalizedFolder) if (cached) { if (!cached.tags.includes(api.tag)) cached.tags = [...cached.tags, api.tag] return cached }
const parent = dirname(normalizedFolder) // If the parent is the same as the folder, we are at the root if (parent === normalizedFolder) { throw new Error(`Fatal Error: Attempted to get parent of root folder "${normalizedFolder}".`) }
const folderUri = vscode.Uri.file(normalizedFolder) const parentItem = this.getOrCreateFolderTestItem(api, parent) const folderItem = this._createFolderItem(folderUri, parentItem) folderItem.tags = [api.tag] parentItem.children.add(folderItem) this.folderItems.set(normalizedFolder, folderItem) return folderItem }
private _createFolderItem(folderUri: vscode.Uri, parentItem?: vscode.TestItem) { const folderFsPath = normalize(folderUri.fsPath) const folderItem = this.controller.createTestItem( folderFsPath, basename(folderFsPath), folderUri, ) TestFolder.register(folderItem, parentItem) folderItem.canResolveChildren = false return folderItem }
watchTestFilesInWorkspace(api: VitestProcessAPI, testFiles: ExtensionTestFileSpecification[]) { this.discoverAllTestFiles(api, testFiles) this.watcher.watchTestFilesInWorkspace(api) }
public removeFile(filepath: string) { const items = this.testItemsByFile.get(normalize(filepath)) items?.forEach((item) => this.recursiveDelete(item)) }
public removeFolder(folderPath: string) { const folderItem = this.folderItems.get(normalize(folderPath)) if (folderItem) { this.recursiveDelete(folderItem) } }
private recursiveDelete(item: vscode.TestItem) { if (!item.parent) return
// Clean up children first so no stale entries remain in Maps this.cleanupChildren(item)
item.parent.children.delete(item.id) this.flatTestItems.delete(item.id) const data = getTestData(item)
if (data instanceof TestFile) { this.testItemsByFile.delete(data.filepath) this.fileItems.delete(item.id) } if (data instanceof TestFolder) this.folderItems.delete(item.id)
if (!item.parent.children.size) this.recursiveDelete(item.parent) }
private cleanupChildren(item: vscode.TestItem) { item.children.forEach((child) => { this.cleanupChildren(child) this.flatTestItems.delete(child.id) const data = getTestData(child) if (data instanceof TestFile) { this.testItemsByFile.delete(data.filepath) this.fileItems.delete(child.id) } if (data instanceof TestFolder) this.folderItems.delete(child.id) }) }
public getAPIFromTestItem(testItem: vscode.TestItem) { return getAPIFromTestItem(testItem) }
async discoverTestsInFile(testItem: vscode.TestItem) { const data = getTestData(testItem) if (!(data instanceof TestFile)) return const api = data.api if (!api) { log.error(`Cannot find collector for ${testItem.uri?.fsPath}`) return null } testItem.busy = true try { await api.collectTests(data.project, testItem.uri!.fsPath) return testItem } finally { testItem.busy = false } }
public getTestItemByTaskId(taskId: string): vscode.TestItem | undefined { const testItem = this.flatTestItems.get(taskId) if (!testItem) return undefined return testItem || undefined }
public getTestItemByTask(task: RunnerTask): vscode.TestItem | null { const cachedItem = this.flatTestItems.get(task.id) if (cachedItem) return cachedItem if ('filepath' in task && task.filepath) { const testItem = this.fileItems.get(`${task.filepath}${task.projectName || ''}`) return testItem || null } return null }
public getFolderFiles(folder: vscode.TestItem): vscode.TestItem[] { const files: vscode.TestItem[] = [] for (const [_, item] of folder.children) { const data = getTestData(item) if (data instanceof TestFile) files.push(item) else if (data instanceof TestFolder) files.push(...this.getFolderFiles(item)) } return files }
collectFile(api: VitestProcessAPI, file: RunnerTestFile) { const normalizedFile = normalize(file.filepath) const fileId = `${normalizedFile}${file.projectName || ''}` const fileTestItem = this.fileItems.get(fileId) if (!fileTestItem) { log.error( `Cannot find a file test item for ${file.filepath} in "${file.projectName || 'core'}" project.`, ) return } fileTestItem.error = undefined this.flatTestItems.set(file.id, fileTestItem) const data = getTestData(fileTestItem) as TestFile this.collectTasks(api.tag, data, file.tasks, fileTestItem) if (file.result?.errors) { const error = file.result.errors.map((error) => error.stack || error.message).join('\n') fileTestItem.error = error log.error(`Error in ${file.filepath}`, error) } else if (!file.tasks.length) { fileTestItem.error = `No tests found in ${file.filepath}` } fileTestItem.canResolveChildren = false }
private cacheDynamic: { [file: string]: { [dynamicTitle: string]: { id: string type: 'test' | 'suite' children: Set<string> } } } = {}
collectTasks( tag: vscode.TestTag, fileData: TestFile, tasks: RunnerTask[], parent: vscode.TestItem, ) { const fileCachedTests = this.cacheDynamic[fileData.filepath] || (this.cacheDynamic[fileData.filepath] = {}) const ids = new Set()
for (const task of tasks) { ids.add(task.id) const cachedItem = this.flatTestItems.get(task.id) // suite became a test or vice versa if (cachedItem) { const data = getTestData(cachedItem) const taskType = isTest(task) ? 'test' : task.type if (data.type !== taskType) { parent.children.delete(cachedItem.id) this.flatTestItems.delete(task.id) } }
const testItem = this.flatTestItems.get(task.id) || this.controller.createTestItem(task.id, task.name, parent.uri) testItem.tags = [...new Set([...parent.tags, tag])] testItem.error = undefined testItem.label = task.name const location = task.location if (location) { const position = new vscode.Position(location.line - 1, location.column) testItem.range = new vscode.Range(position, position) } else { log.error(`Cannot find location for "${testItem.label}". Using "id" to sort instead.`) testItem.sortText = task.id } // dynamic exists only during AST collection // see src/worker/collect.ts:172 const isDynamic = (task as any).dynamic if (task.type === 'suite') TestSuite.register(testItem, parent, fileData, isDynamic) else if (isTest(task)) TestCase.register(testItem, parent, fileData, isDynamic)
if (isDynamic) { testItem.description = 'pattern' const dynamicTestRegExp = ( getTestData(testItem) as TestCase | TestSuite ).getTestNamePattern()
const cachedDynamicTest = fileCachedTests[dynamicTestRegExp] || (fileCachedTests[dynamicTestRegExp] = { id: task.id, type: isTest(task) ? 'test' : task.type, children: new Set(), }) cachedDynamicTest.children.forEach((fileId) => { // don't remove tests that were collected during runtime ids.add(fileId) }) } else if (task.each) { // the separator has to match the one used in getTestNamePattern const separator = fileData.api.usesJestTestNamePattern ? ' ' : ' > ' const fullName = getTaskFullName(task, separator) // order in the opposite order so we only match one item with the longest name const orderedTests = Object.entries(fileCachedTests).sort(([a1], [a2]) => a2.localeCompare(a1), ) for (const [testRegexp, cachedDynamicTask] of orderedTests) { if (new RegExp(testRegexp).test(fullName)) { const testId = cachedDynamicTask.id const childId = `${testId}_${task.suite?.id || 'none'}`
// keep the dynamic pattern to display it alongside normal tests, // if the parent suite was also dynamic, this item will be duplicated // in every suite, but scoped only to that suite const dynamicTestItem = this.flatTestItems.get(testId) ids.add(childId) if (dynamicTestItem) { // we are creating a separate one because we can't use the same one in multiple places const suiteCopyChild = this.flatTestItems.get(childId) || this.controller.createTestItem(childId, dynamicTestItem.label, dynamicTestItem.uri) this.flatTestItems.set(childId, suiteCopyChild) suiteCopyChild.tags = dynamicTestItem.tags suiteCopyChild.canResolveChildren = dynamicTestItem.canResolveChildren suiteCopyChild.description = dynamicTestItem.description suiteCopyChild.range = dynamicTestItem.range suiteCopyChild.error = dynamicTestItem.error suiteCopyChild.sortText = dynamicTestItem.sortText
if (task.type === 'suite') { TestSuite.register(suiteCopyChild, parent, fileData, true) } else { TestCase.register(suiteCopyChild, parent, fileData, true) }
parent.children.add(suiteCopyChild) break } cachedDynamicTask.children.add(task.id) } } }
this.flatTestItems.set(task.id, testItem) parent.children.add(testItem)
// errors during collection are not test failures, they need to be // displayed as errors in the tree if (task.result?.errors) { const error = task.result.errors.map((error) => error.stack).join('\n') testItem.error = error }
if ('tasks' in task) { this.collectTasks(tag, fileData, task.tasks, testItem) } // only tests have tags, and 'tasks' in task narrows it down else if ('tags' in task) { const tags = (task.tags as string[]).map((tag) => this.tagsManager.getTestTag(tag)) testItem.tags = [...testItem.tags, ...tags] } }
// remove tasks that are no longer present parent.children.forEach((child) => { if (!ids.has(child.id)) parent.children.delete(child.id) }) }}
function isTest(task: RunnerTask) { if (task.type === 'suite') { return false } return true}
function getAPIFromFolder(folder: vscode.TestItem): VitestProcessAPI | null { const data = getTestData(folder) if (data instanceof TestFile) return data.api if (!(data instanceof TestFolder)) return null for (const [, child] of folder.children) { const api = getAPIFromTestItem(child) if (api) return api } return null}
function getAPIFromTestItem(testItem: vscode.TestItem): VitestProcessAPI | null { const data = getTestData(testItem) // API is stored in test files - if this is a folder, try to find a file inside, // otherwise go up until we find a file, this should never be a folder if (data instanceof TestFolder) return getAPIFromFolder(testItem)
if (data instanceof TestFile) return data.api return data.file.api}
function getTaskFullName(task: RunnerTask, separator: string): string { return `${task.suite ? `${getTaskFullName(task.suite, separator)}${separator}` : ''}${task.name}`}