Skip to content

Commit

Permalink
refactor: merge TestProject with WorkspaceProject
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Nov 14, 2024
1 parent 6324a00 commit 06e6d3a
Show file tree
Hide file tree
Showing 27 changed files with 473 additions and 363 deletions.
18 changes: 9 additions & 9 deletions packages/browser/src/node/pool.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { BrowserProvider, ProcessPool, Vitest, WorkspaceProject, WorkspaceSpec } from 'vitest/node'
import type { BrowserProvider, ProcessPool, TestProject, TestSpecification, Vitest } from 'vitest/node'
import crypto from 'node:crypto'
import * as nodeos from 'node:os'
import { relative } from 'pathe'
Expand All @@ -9,7 +9,7 @@ const debug = createDebugger('vitest:browser:pool')
async function waitForTests(
method: 'run' | 'collect',
contextId: string,
project: WorkspaceProject,
project: TestProject,
files: string[],
) {
const context = project.browser!.state.createAsyncContext(method, contextId, files)
Expand All @@ -19,7 +19,7 @@ async function waitForTests(
export function createBrowserPool(ctx: Vitest): ProcessPool {
const providers = new Set<BrowserProvider>()

const executeTests = async (method: 'run' | 'collect', project: WorkspaceProject, files: string[]) => {
const executeTests = async (method: 'run' | 'collect', project: TestProject, files: string[]) => {
ctx.state.clearFiles(project, files)
const browser = project.browser!

Expand Down Expand Up @@ -113,11 +113,11 @@ export function createBrowserPool(ctx: Vitest): ProcessPool {
await Promise.all(promises)
}

const runWorkspaceTests = async (method: 'run' | 'collect', specs: WorkspaceSpec[]) => {
const groupedFiles = new Map<WorkspaceProject, string[]>()
for (const [project, file] of specs) {
const runWorkspaceTests = async (method: 'run' | 'collect', specs: TestSpecification[]) => {
const groupedFiles = new Map<TestProject, string[]>()
for (const { project, moduleId } of specs) {
const files = groupedFiles.get(project) || []
files.push(file)
files.push(moduleId)
groupedFiles.set(project, files)
}

Expand All @@ -131,7 +131,7 @@ export function createBrowserPool(ctx: Vitest): ProcessPool {
if (isCancelled) {
break
}
await project.initBrowserProvider()
await project._initBrowserProvider()

await executeTests(method, project, files)
}
Expand All @@ -142,7 +142,7 @@ export function createBrowserPool(ctx: Vitest): ProcessPool {
? nodeos.availableParallelism()
: nodeos.cpus().length

function getThreadsCount(project: WorkspaceProject) {
function getThreadsCount(project: TestProject) {
const config = project.config.browser
if (!config.headless || !project.browser!.provider.supportsParallelism) {
return 1
Expand Down
71 changes: 35 additions & 36 deletions packages/vitest/src/node/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { TestSpecification } from './spec'
import type { ResolvedConfig, UserConfig, VitestRunMode } from './types/config'
import type { CoverageProvider } from './types/coverage'
import type { Reporter } from './types/reporter'
import { existsSync, promises as fs } from 'node:fs'
import { existsSync, promises as fs, readFileSync } from 'node:fs'
import { getTasks, hasFailed } from '@vitest/runner/utils'
import { SnapshotManager } from '@vitest/snapshot/manager'
import { noop, slash, toArray } from '@vitest/utils'
Expand All @@ -28,11 +28,11 @@ import { resolveConfig } from './config/resolveConfig'
import { FilesNotFoundError, GitNotFoundError } from './errors'
import { Logger } from './logger'
import { VitestPackageInstaller } from './packageInstaller'
import { createPool, getFilePoolName } from './pool'
import { createPool } from './pool'
import { TestProject } from './project'
import { BlobReporter, readBlobs } from './reporters/blob'
import { createBenchmarkReporters, createReporters } from './reporters/utils'
import { StateManager } from './state'
import { WorkspaceProject } from './workspace'
import { resolveWorkspace } from './workspace/resolveWorkspace'

const WATCHER_DEBOUNCE = 100
Expand Down Expand Up @@ -75,15 +75,15 @@ export class Vitest {

public packageInstaller: VitestPackageInstaller

private coreWorkspaceProject!: WorkspaceProject
private coreWorkspaceProject!: TestProject

/** @private */
public resolvedProjects: WorkspaceProject[] = []
public projects: WorkspaceProject[] = []
public resolvedProjects: TestProject[] = []
public projects: TestProject[] = []

public distPath = distDir

private _cachedSpecs = new Map<string, WorkspaceSpec[]>()
private _cachedSpecs = new Map<string, TestSpecification[]>()
private _workspaceConfigPath?: string

/** @deprecated use `_cachedSpecs` */
Expand Down Expand Up @@ -193,7 +193,7 @@ export class Vitest {
)
}
if (!this.coreWorkspaceProject) {
this.coreWorkspaceProject = WorkspaceProject.createBasicProject(this)
this.coreWorkspaceProject = TestProject.createBasicProject(this)
}

if (this.config.testNamePattern) {
Expand All @@ -217,19 +217,19 @@ export class Vitest {
/**
* @internal
*/
async _createCoreProject() {
this.coreWorkspaceProject = await WorkspaceProject.createCoreProject(this)
_createCoreProject() {
this.coreWorkspaceProject = TestProject.createBasicProject(this)
return this.coreWorkspaceProject
}

public getCoreWorkspaceProject(): WorkspaceProject {
public getCoreWorkspaceProject(): TestProject {
return this.coreWorkspaceProject
}

/**
* @deprecated use Reported Task API instead
*/
public getProjectByTaskId(taskId: string): WorkspaceProject {
public getProjectByTaskId(taskId: string): TestProject {
const task = this.state.idMap.get(taskId)
const projectName = (task as File).projectName || task?.file?.projectName || ''
return this.projects.find(p => p.getName() === projectName)
Expand Down Expand Up @@ -271,7 +271,7 @@ export class Vitest {
this._workspaceConfigPath = workspaceConfigPath

if (!workspaceConfigPath) {
return [await this._createCoreProject()]
return [this._createCoreProject()]
}

const workspaceModule = await this.runner.executeFile(workspaceConfigPath) as {
Expand Down Expand Up @@ -315,7 +315,7 @@ export class Vitest {
await this.report('onInit', this)
await this.report('onPathsCollected', files.flatMap(f => f.filepath))

const workspaceSpecs = new Map<WorkspaceProject, File[]>()
const workspaceSpecs = new Map<TestProject, File[]>()
for (const file of files) {
const project = this.getProjectByName(file.projectName)
const specs = workspaceSpecs.get(project) || []
Expand Down Expand Up @@ -454,7 +454,7 @@ export class Vitest {
}

private async getTestDependencies(spec: WorkspaceSpec, deps = new Set<string>()) {
const addImports = async (project: WorkspaceProject, filepath: string) => {
const addImports = async (project: TestProject, filepath: string) => {
if (deps.has(filepath)) {
return
}
Expand Down Expand Up @@ -534,7 +534,7 @@ export class Vitest {
* @deprecated remove when vscode extension supports "getFileWorkspaceSpecs"
*/
getProjectsByTestFile(file: string) {
return this.getFileWorkspaceSpecs(file)
return this.getFileWorkspaceSpecs(file) as WorkspaceSpec[]
}

getFileWorkspaceSpecs(file: string) {
Expand All @@ -543,28 +543,27 @@ export class Vitest {
return _cached
}

const specs: WorkspaceSpec[] = []
const specs: TestSpecification[] = []
for (const project of this.projects) {
if (project.isTestFile(file)) {
const pool = getFilePoolName(project, file)
specs.push(project.createSpec(file, pool))
specs.push(project.createSpecification(file))
}
if (project.isTypecheckFile(file)) {
specs.push(project.createSpec(file, 'typescript'))
specs.push(project.createSpecification(file, 'typescript'))
}
}
specs.forEach(spec => this.ensureSpecCached(spec))
return specs
}

async initializeGlobalSetup(paths: TestSpecification[]) {
const projects = new Set(paths.map(spec => spec.project.workspaceProject))
const projects = new Set(paths.map(spec => spec.project))
const coreProject = this.getCoreWorkspaceProject()
if (!projects.has(coreProject)) {
projects.add(coreProject)
}
for (const project of projects) {
await project.initializeGlobalSetup()
await project._initializeGlobalSetup()
}
}

Expand Down Expand Up @@ -688,7 +687,7 @@ export class Vitest {
}

async initBrowserServers() {
await Promise.all(this.projects.map(p => p.initBrowserServer()))
await Promise.all(this.projects.map(p => p._initBrowserServer()))
}

async rerunFiles(files: string[] = this.state.getFilepaths(), trigger?: string, allTestsRun = true) {
Expand Down Expand Up @@ -889,14 +888,15 @@ export class Vitest {
onAdd = async (id: string) => {
id = slash(id)
this.updateLastChanged(id)
const fileContent = readFileSync(id, 'utf-8')

const matchingProjects: WorkspaceProject[] = []
await Promise.all(this.projects.map(async (project) => {
if (await project.isTargetFile(id)) {
const matchingProjects: TestProject[] = []
this.projects.forEach((project) => {
if (project.matchesTestGlob(id, fileContent)) {
matchingProjects.push(project)
project.testFilesList?.push(id)
project._markTestFile(id)
}
}))
})

if (matchingProjects.length > 0) {
this.changedTests.add(id)
Expand Down Expand Up @@ -1029,10 +1029,10 @@ export class Vitest {
}
// do teardown before closing the server
for await (const project of teardownProjects.reverse()) {
await project.teardownGlobalSetup()
await project._teardownGlobalSetup()
}

const closePromises: unknown[] = this.resolvedProjects.map(w => w.close().then(() => w.server = undefined as any))
const closePromises: unknown[] = this.resolvedProjects.map(w => w.close().then(() => (w as any)._vite = undefined as any))
// close the core workspace server only once
// it's possible that it's not initialized at all because it's not running any tests
if (!this.resolvedProjects.includes(this.coreWorkspaceProject)) {
Expand Down Expand Up @@ -1107,22 +1107,21 @@ export class Vitest {
}

public async globTestSpecs(filters: string[] = []) {
const files: WorkspaceSpec[] = []
const files: TestSpecification[] = []
await Promise.all(this.projects.map(async (project) => {
const { testFiles, typecheckTestFiles } = await project.globTestFiles(filters)
testFiles.forEach((file) => {
const pool = getFilePoolName(project, file)
const spec = project.createSpec(file, pool)
const spec = project.createSpecification(file)
this.ensureSpecCached(spec)
files.push(spec)
})
typecheckTestFiles.forEach((file) => {
const spec = project.createSpec(file, 'typescript')
const spec = project.createSpecification(file, 'typescript')
this.ensureSpecCached(spec)
files.push(spec)
})
}))
return files
return files as WorkspaceSpec[]
}

/**
Expand All @@ -1132,7 +1131,7 @@ export class Vitest {
return this.globTestSpecs(filters)
}

private ensureSpecCached(spec: WorkspaceSpec) {
private ensureSpecCached(spec: TestSpecification) {
const file = spec[1]
const specs = this._cachedSpecs.get(file) || []
const included = specs.some(_s => _s[0] === spec[0] && _s[2].pool === spec[2].pool)
Expand Down
6 changes: 3 additions & 3 deletions packages/vitest/src/node/error.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ErrorWithDiff, ParsedStack } from '@vitest/utils'
import type { Vitest } from './core'
import type { ErrorOptions } from './logger'
import type { WorkspaceProject } from './workspace'
import type { TestProject } from './project'
/* eslint-disable prefer-template */
import { existsSync, readFileSync } from 'node:fs'
import { Writable } from 'node:stream'
Expand Down Expand Up @@ -55,7 +55,7 @@ export function capturePrintError(

export function printError(
error: unknown,
project: WorkspaceProject | undefined,
project: TestProject | undefined,
options: PrintErrorOptions,
): PrintErrorResult | undefined {
const { showCodeFrame = true, type, printProperties = true } = options
Expand Down Expand Up @@ -338,7 +338,7 @@ function printErrorMessage(error: ErrorWithDiff, logger: Logger) {

export function printStack(
logger: Logger,
project: WorkspaceProject,
project: TestProject,
stack: ParsedStack[],
highlight: ParsedStack | undefined,
errorProperties: Record<string, unknown>,
Expand Down
9 changes: 9 additions & 0 deletions packages/vitest/src/node/globalSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,20 @@ import type { ResolvedConfig } from './types/config'
import { toArray } from '@vitest/utils'

export interface GlobalSetupContext {
/**
* Config of the current project.
*/
config: ResolvedConfig
/**
* Provide a value to the test context. This value will be available to all tests via `inject`.
*/
provide: <T extends keyof ProvidedContext & string>(
key: T,
value: ProvidedContext[T]
) => void
/**
* Register a function that will be called before tests run again in watch mode.
*/
onTestsRerun: (cb: OnTestsRerunHandler) => void
}

Expand Down
6 changes: 3 additions & 3 deletions packages/vitest/src/node/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { Writable } from 'node:stream'
import type { TypeCheckError } from '../typecheck/typechecker'
import type { Vitest } from './core'
import type { PrintErrorResult } from './error'
import type { WorkspaceProject } from './workspace'
import type { TestProject } from './project'
import { Console } from 'node:console'
import { toArray } from '@vitest/utils'
import { parseErrorStacktrace } from '@vitest/utils/source-map'
Expand All @@ -18,7 +18,7 @@ import { RandomSequencer } from './sequencers/RandomSequencer'
export interface ErrorOptions {
type?: string
fullStack?: boolean
project?: WorkspaceProject
project?: TestProject
verbose?: boolean
screenshotPaths?: string[]
task?: Task
Expand Down Expand Up @@ -245,7 +245,7 @@ export class Logger {
}
}

printBrowserBanner(project: WorkspaceProject) {
printBrowserBanner(project: TestProject) {
if (!project.browser) {
return
}
Expand Down
6 changes: 3 additions & 3 deletions packages/vitest/src/node/plugins/workspace.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { UserConfig as ViteConfig, Plugin as VitePlugin } from 'vite'
import type { TestProject } from '../project'
import type { ResolvedConfig, UserWorkspaceConfig } from '../types/config'
import type { WorkspaceProject } from '../workspace'
import { existsSync, readFileSync } from 'node:fs'
import { deepMerge } from '@vitest/utils'
import { basename, dirname, relative, resolve } from 'pathe'
Expand All @@ -26,7 +26,7 @@ interface WorkspaceOptions extends UserWorkspaceConfig {
}

export function WorkspaceVitestPlugin(
project: WorkspaceProject,
project: TestProject,
options: WorkspaceOptions,
) {
return <VitePlugin[]>[
Expand Down Expand Up @@ -153,7 +153,7 @@ export function WorkspaceVitestPlugin(
},
async configureServer(server) {
const options = deepMerge({}, configDefaults, server.config.test || {})
await project.setServer(options, server)
await project._configureServer(options, server)

await server.watcher.close()
},
Expand Down
Loading

0 comments on commit 06e6d3a

Please sign in to comment.