Skip to content

Commit

Permalink
chore: make the rest into getters with a check
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Nov 26, 2024
1 parent 7f4be1a commit 8e36c29
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 65 deletions.
4 changes: 2 additions & 2 deletions packages/snapshot/src/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import type {
import { basename, dirname, isAbsolute, join, resolve } from 'pathe'

export class SnapshotManager {
summary: SnapshotSummary = undefined!
extension = '.snap'
public summary!: SnapshotSummary
public extension = '.snap'

constructor(
public options: Omit<SnapshotStateOptions, 'snapshotEnvironment'>,
Expand Down
120 changes: 64 additions & 56 deletions packages/vitest/src/node/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,57 +57,37 @@ export class Vitest {
public readonly watcher: VitestWatcher
public readonly distPath = distDir

/**
* @experimental The State API is experimental and not subject to semver.
*/
// TODO: getter
public state: StateManager = undefined!
// TODO: getter
public snapshot: SnapshotManager = undefined!
// TODO: getter
public cache: VitestCache = undefined!

public projects: TestProject[] = []

/** @internal */
configOverride: Partial<ResolvedConfig> = {}
/** @internal */
reporters: Reporter[] = undefined!

coverageProvider: CoverageProvider | null | undefined
pool: ProcessPool | undefined

vitenode: ViteNodeServer = undefined!
runner: ViteNodeRunner = undefined!

/** @internal */
filenamePattern?: string
/** @internal */
runningPromise?: Promise<TestRunResult>
/** @internal */
closingPromise?: Promise<void>
/** @internal */
isCancelling = false
/** @internal */
coreWorkspaceProject: TestProject | undefined
/** @internal */
resolvedProjects: TestProject[] = []
/** @internal */
_browserLastPort = defaultBrowserPort
/** @internal */
_options: UserConfig = {}
/** @internal */ coverageProvider: CoverageProvider | null | undefined
/** @internal */ filenamePattern?: string
/** @internal */ runningPromise?: Promise<TestRunResult>
/** @internal */ closingPromise?: Promise<void>
/** @internal */ isCancelling = false
/** @internal */ coreWorkspaceProject: TestProject | undefined
/** @internal */ resolvedProjects: TestProject[] = []
/** @internal */ _browserLastPort = defaultBrowserPort
/** @internal */ _options: UserConfig = {}
/** @internal */ configOverride: Partial<ResolvedConfig> = {}
/** @internal */ reporters: Reporter[] = undefined!
/** @internal */ vitenode: ViteNodeServer = undefined!
/** @internal */ runner: ViteNodeRunner = undefined!

// TODO: remove in 3.0
private watchedTests: Set<string> = new Set()

private isFirstRun = true
private restartsCount = 0

private specifications: VitestSpecifications
private pool: ProcessPool | undefined
private _ready = false
private _config: ResolvedConfig | undefined
private _vite: ViteDevServer | undefined
private _config?: ResolvedConfig
private _vite?: ViteDevServer
private _state?: StateManager
private _cache?: VitestCache
private _snapshot?: SnapshotManager
private _workspaceConfigPath?: string
private specifications: VitestSpecifications

constructor(
public readonly mode: VitestRunMode,
Expand All @@ -127,12 +107,12 @@ export class Vitest {
private _onCancelListeners: ((reason: CancelReason) => Awaitable<void>)[] = []
private _onUserTestsRerun: OnTestsRerunHandler[] = []

/** @deprecated will be removed in 3.0 */
/** @deprecated will be removed in 3.0, use `vitest.watcher` */
public get invalidates() {
return this.watcher.invalidates
}

/** @deprecated will be removed in 3.0 */
/** @deprecated will be removed in 3.0, use `vitest.watcher` */
public get changedTests() {
return this.watcher.changedTests
}
Expand All @@ -141,9 +121,7 @@ export class Vitest {
* The global config.
*/
get config(): ResolvedConfig {
if (!this._config) {
throw new Error('The config was not set. It means that `vitest.config` was called before the Vite server was established.')
}
assert(this._config, 'config')
return this._config
}

Expand All @@ -156,12 +134,35 @@ export class Vitest {
* Global Vite's dev server instance.
*/
get vite(): ViteDevServer {
if (!this._vite) {
throw new Error('The server was not set. It means that `vitest.vite` was called before the Vite server was established.')
}
assert(this._vite, 'vite', 'server')
return this._vite
}

/**
* The global test state manager.
* @experimental The State API is experimental and not subject to semver.
*/
get state(): StateManager {
assert(this._state, 'state')
return this._state
}

/**
* The global snapshot manager. You can access the current state on `snapshot.summary`.
*/
get snapshot(): SnapshotManager {
assert(this._snapshot, 'snapshot', 'snapshot manager')
return this._snapshot
}

/**
* Test results and test file stats cache. Primarily used by the sequencer to order tests.
*/
get cache(): VitestCache {
assert(this._cache, 'cache')
return this._cache
}

/**
* Returns whether Vitest was fully initialised. This means that the Vite server was established and the workspace config was resolved.
* It's not necessary to call this method unless the instance was created manually via the public API, and the promise was not awaited.
Expand Down Expand Up @@ -198,9 +199,9 @@ export class Vitest {

this._vite = server
this._config = resolved
this.state = new StateManager()
this.cache = new VitestCache(this.version)
this.snapshot = new SnapshotManager({ ...resolved.snapshotOptions })
this._state = new StateManager()
this._cache = new VitestCache(this.version)
this._snapshot = new SnapshotManager({ ...resolved.snapshotOptions })

if (this.config.watch) {
this.watcher.registerWatcher()
Expand Down Expand Up @@ -286,7 +287,10 @@ export class Vitest {
}

/** @internal */
_createRootProject() {
_ensureRootProject() {
if (this.coreWorkspaceProject) {
return this.coreWorkspaceProject
}
this.coreWorkspaceProject = TestProject._createBasicProject(this)
return this.coreWorkspaceProject
}
Expand All @@ -307,9 +311,7 @@ export class Vitest {
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.name === projectName)
|| this.getRootTestProject()
|| this.projects[0]
return this.getProjectByName(projectName)
}

public getProjectByName(name: string): TestProject {
Expand Down Expand Up @@ -359,7 +361,7 @@ export class Vitest {
this._workspaceConfigPath = workspaceConfigPath

if (!workspaceConfigPath) {
return [this._createRootProject()]
return [this._ensureRootProject()]
}

const workspaceModule = await this.runner.executeFile(workspaceConfigPath) as {
Expand Down Expand Up @@ -1135,3 +1137,9 @@ export class Vitest {
this._onSetServer.push(fn)
}
}

function assert(condition: unknown, property: string, name: string = property): asserts condition {
if (!condition) {
throw new Error(`The ${name} was not set. It means that \`vitest.${property}\` was called before the Vite server was established. Either await the Vitest promise or check that it is initialized with \`vitest.ready()\` before accessing \`vitest.${property}\`.`)
}
}
4 changes: 2 additions & 2 deletions packages/vitest/src/node/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { noop, slash } from '@vitest/utils'
import mm from 'micromatch'

export class VitestWatcher {
public invalidates: Set<string> = new Set()
public changedTests: Set<string> = new Set()
public readonly invalidates: Set<string> = new Set()
public readonly changedTests: Set<string> = new Set()

private _onRerun: ((file: string) => void)[] = []
private _onFilterTestFile: ((file: string) => boolean)[] = []
Expand Down
10 changes: 5 additions & 5 deletions packages/vitest/src/node/workspace/resolveWorkspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ export async function resolveWorkspace(

for (const path of fileProjects) {
// if file leads to the root config, then we can just reuse it because we already initialized it
if (vitest.server.config.configFile === path) {
projectPromises.push(Promise.resolve(vitest._createRootProject()))
if (vitest.vite.config.configFile === path) {
projectPromises.push(Promise.resolve(vitest._ensureRootProject()))
continue
}

Expand All @@ -97,7 +97,7 @@ export async function resolveWorkspace(

// pretty rare case - the glob didn't match anything and there are no inline configs
if (!projectPromises.length) {
return [vitest._createRootProject()]
return [vitest._ensureRootProject()]
}

const resolvedProjects = await Promise.all(projectPromises)
Expand Down Expand Up @@ -193,8 +193,8 @@ async function resolveTestProjectConfigs(
// if the config is inlined, we can resolve it immediately
else if (typeof definition === 'function') {
projectsOptions.push(await definition({
command: vitest.server.config.command,
mode: vitest.server.config.mode,
command: vitest.vite.config.command,
mode: vitest.vite.config.mode,
isPreview: false,
isSsrBuild: false,
}))
Expand Down

0 comments on commit 8e36c29

Please sign in to comment.