Skip to content

Commit e5c80b7

Browse files
authored
fix: apply --shard before the test run starts (#11846)
1 parent 1fa69e0 commit e5c80b7

15 files changed

Lines changed: 301 additions & 44 deletions

File tree

‎docs/api/advanced/test-module.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ This is a Vite's [`DevEnvironment`](https://vite.dev/guide/api-environment) that
5050
function state(): TestModuleState
5151
```
5252

53-
Works the same way as [`testSuite.state()`](/api/advanced/test-suite#state), but can also return `queued` if module wasn't executed yet.
53+
Works the same way as [`testSuite.state()`](/api/advanced/test-suite#state), but can also return `queued` if the module is queued, but Vitest did not collect its tests yet.
5454

5555
## meta <Version>3.1.0</Version> {#meta}
5656

‎docs/api/advanced/test-specification.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,9 @@ The ID of the module in Vite's module graph. Usually, it's an absolute file path
3838

3939
## testModule
4040

41-
Instance of [`TestModule`](/api/advanced/test-module) associated with the specification. If test wasn't queued yet, this will be `undefined`.
41+
Instance of [`TestModule`](/api/advanced/test-module) associated with the specification. This is `undefined` until Vitest queues the module or parses it, for example, with [`experimental.preParse`](/config/experimental#experimental-preparse) or [`parseSpecifications`](/api/advanced/vitest#parsespecifications).
42+
43+
Vitest keeps the module after the test run finishes. If the specification runs again, this returns the module of the previous run until the module is queued again.
4244

4345
## pool {#pool}
4446

‎docs/api/advanced/test-suite.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ Checks the running state of the suite. Possible return values:
171171
- **skipped**: this suite was skipped during collection.
172172

173173
::: warning
174-
Note that [test module](/api/advanced/test-module) also has a `state` method that returns the same values, but it can also return an additional `queued` state if the module wasn't executed yet.
174+
Note that [test module](/api/advanced/test-module) also has a `state` method that returns the same values, but it can also return an additional `queued` state if the module is queued, but Vitest did not collect its tests yet.
175175
:::
176176

177177
## errors

‎docs/api/advanced/vitest.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ function collect(
236236

237237
Based on `staticParse`, this will either statically analyse test files to collect them (the default) or run the code without executing test callbacks. `collect` returns unhandled errors and an array of [test modules](/api/advanced/test-module). It accepts string filters to match the test files - these are the same filters that [CLI supports](/guide/filtering#cli).
238238

239-
This method resolves tests specifications based on the config `include`, `exclude`, and `includeSource` values. Read more at [`project.globTestFiles`](/api/advanced/test-project#globtestfiles). If `--changed` flag was specified, the list will be filtered to include only files that changed.
239+
This method resolves tests specifications based on the config `include`, `exclude`, and `includeSource` values. Read more at [`project.globTestFiles`](/api/advanced/test-project#globtestfiles). If `--changed` flag was specified, the list will be filtered to include only files that changed. If [`--shard`](/guide/cli#shard) was specified, only the files of the current shard are collected.
240240

241241
::: warning
242242
Note that since Vitest 5, the tests are collected by static analysis by default. If disabled via the second option, Vitest will run every test file in isolation, just like it runs regular tests. This would make this method very slow, unless you disable isolation manually before collecting tests.
@@ -305,7 +305,7 @@ function runTestSpecifications(
305305
): Promise<TestRunResult>
306306
```
307307

308-
This method runs every test based on the received [specifications](/api/advanced/test-specification). The second argument, `allTestsRun`, is used by the coverage provider to determine if it needs to include uncovered files in report.
308+
This method runs every test based on the received [specifications](/api/advanced/test-specification). It does not apply the [`--shard`](/guide/cli#shard) option. The second argument, `allTestsRun`, is used by the coverage provider to determine if it needs to include uncovered files in report.
309309

310310
::: warning
311311
This method doesn't trigger `onWatcherRerun`, `onWatcherStart` and `onTestsRerun` callbacks. If you are rerunning tests based on the file change, consider using [`rerunTestSpecifications`](#reruntestspecifications) instead.
@@ -355,7 +355,7 @@ function collectTests(
355355

356356
Execute test files without running test callbacks. `collectTests` returns unhandled errors and an array of [test modules](/api/advanced/test-module).
357357

358-
This method works exactly the same as [`collect`](#collect), but you need to provide test specifications yourself.
358+
This method works exactly the same as [`collect`](#collect), but you need to provide test specifications yourself. It does not apply the [`--shard`](/guide/cli#shard) option.
359359

360360
::: warning
361361
Note that Vitest doesn't use static analysis to collect tests. Vitest will run every test file in isolation, just like it runs regular tests.

‎packages/vitest/src/node/cli/cac.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,9 @@ async function collect(cliFilters: string[], options: CliOptions): Promise<void>
383383

384384
processCollected(ctx, tests, options)
385385
} else {
386-
const files = await ctx.getRelevantTestSpecifications(cliFilters.map(normalize))
386+
const files = await ctx._shardSpecifications(
387+
await ctx.getRelevantTestSpecifications(cliFilters.map(normalize)),
388+
)
387389
outputFileList(files, options)
388390
}
389391

‎packages/vitest/src/node/core.ts‎

Lines changed: 63 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import type { VitestPackageInstaller } from './packageInstaller'
1212
import type { ProcessPool } from './pool'
1313
import type { Report } from './reporters/report'
1414
import type { TestModule } from './reporters/reported-tasks'
15+
import type { TestSequencer } from './sequencers/types'
1516
import type { TestSpecification } from './test-specification'
1617
import type { ParentProjectBrowser } from './types/browser'
1718
import type { ResolvedConfig, TestProjectConfiguration } from './types/config'
@@ -185,6 +186,7 @@ export class Vitest {
185186

186187
private readonly specifications: VitestSpecifications
187188
private pool: ProcessPool | undefined
189+
private sequencer: TestSequencer | undefined
188190
private _coverageProvider?: CoverageProvider | null | undefined
189191

190192
/**
@@ -236,6 +238,7 @@ export class Vitest {
236238
this.restartsCount += 1
237239
this.pool?.close?.()
238240
this.pool = undefined
241+
this.sequencer = undefined
239242
this.closingPromise = undefined
240243
this.projects = []
241244
this.runningPromise = undefined
@@ -802,7 +805,7 @@ export class Vitest {
802805
const filenamePattern = filters && filters?.length > 0 ? filters : []
803806
collectSpan.setAttribute('vitest.collect.filters', filenamePattern)
804807

805-
const files = await this._traces.$('vitest.config.resolve_include_glob', async () => {
808+
let files = await this._traces.$('vitest.config.resolve_include_glob', async () => {
806809
const specifications = await this.specifications.getRelevantTestSpecifications(filters)
807810
collectSpan.setAttribute(
808811
'vitest.collect.specifications',
@@ -816,6 +819,7 @@ export class Vitest {
816819
)
817820
return specifications
818821
})
822+
files = await this._shardSpecifications(files)
819823

820824
// if run with --changed, don't exit if no tests are found
821825
if (!files.length) {
@@ -890,13 +894,9 @@ export class Vitest {
890894
},
891895
)
892896

893-
if (this.config.experimental.preParse) {
894-
// This populates specification.testModule with parsed information
895-
await this.parseSpecifications(specifications)
896-
specifications = specifications.filter(({ testModule }) => {
897-
return !testModule || testModule.task.mode !== 'skip'
898-
})
899-
}
897+
specifications = this.config.experimental.preParse
898+
? await this.preParseSpecifications(specifications)
899+
: await this._shardSpecifications(specifications)
900900

901901
// if run with --changed or --last-failed, don't exit if no tests are found
902902
if (!specifications.length) {
@@ -1078,7 +1078,8 @@ export class Vitest {
10781078
await this.initializeGlobalSetup(specs)
10791079

10801080
try {
1081-
await this.pool.runTests(specs, invalidates)
1081+
const sorted = await this.getSequencer().sort(specs)
1082+
await this.pool.runTests(sorted, invalidates)
10821083
} catch (err) {
10831084
this.state.catchError(err, 'Unhandled Error')
10841085
}
@@ -1184,6 +1185,33 @@ export class Vitest {
11841185
concurrency?: number
11851186
},
11861187
): Promise<TestModule[]> {
1188+
const files = await this.parseFiles(specifications, options)
1189+
return files.map((file, index) => {
1190+
this.state.collectFiles(specifications[index].project, [file])
1191+
return this.state.getReportedEntity(file) as TestModule
1192+
})
1193+
}
1194+
1195+
private async preParseSpecifications(
1196+
specifications: TestSpecification[],
1197+
): Promise<TestSpecification[]> {
1198+
const files = await this.parseFiles(specifications)
1199+
const runnable = specifications.filter((_, index) => files[index].mode !== 'skip')
1200+
const sharded = await this._shardSpecifications(runnable)
1201+
const inShard = new Set(sharded)
1202+
specifications.forEach((specification, index) => {
1203+
// files of other shards are not part of this run
1204+
if (files[index].mode === 'skip' || inShard.has(specification)) {
1205+
this.state.collectFiles(specification.project, [files[index]])
1206+
}
1207+
})
1208+
return sharded
1209+
}
1210+
1211+
private async parseFiles(
1212+
specifications: TestSpecification[],
1213+
options?: { concurrency?: number },
1214+
): Promise<File[]> {
11871215
const concurrency =
11881216
options?.concurrency ??
11891217
(typeof os.availableParallelism === 'function' ? os.availableParallelism() : os.cpus().length)
@@ -1221,10 +1249,9 @@ export class Vitest {
12211249
false,
12221250
config.allowOnly,
12231251
)
1224-
this.state.collectFiles(specification.project, [file])
12251252
}
12261253

1227-
return results.map(({ file }) => this.state.getReportedEntity(file) as TestModule)
1254+
return results.map(({ file }) => file)
12281255
}
12291256

12301257
public async experimental_parseSpecification(
@@ -1284,7 +1311,8 @@ export class Vitest {
12841311
await this.initializeGlobalSetup(specifications)
12851312

12861313
try {
1287-
await this.pool.collectTests(specifications, invalidates)
1314+
const sorted = await this.getSequencer().sort(specifications)
1315+
await this.pool.collectTests(sorted, invalidates)
12881316
} catch (err) {
12891317
this.state.catchError(err, 'Unhandled Error')
12901318
}
@@ -1327,6 +1355,29 @@ export class Vitest {
13271355
await this.runningPromise
13281356
}
13291357

1358+
private getSequencer(): TestSequencer {
1359+
if (!this.sequencer) {
1360+
const Sequencer = this.config.sequence.sequencer
1361+
this.sequencer = new Sequencer(this)
1362+
}
1363+
return this.sequencer
1364+
}
1365+
1366+
/** @internal */
1367+
async _shardSpecifications(specifications: TestSpecification[]): Promise<TestSpecification[]> {
1368+
const shard = this.config.shard
1369+
if (!shard) {
1370+
return specifications
1371+
}
1372+
if (!this.config.passWithNoTests && shard.count > specifications.length) {
1373+
throw new Error(
1374+
'--shard <count> must be a smaller than count of test files. ' +
1375+
`Resolved ${specifications.length} test files for --shard=${shard.index}/${shard.count}.`,
1376+
)
1377+
}
1378+
return this.getSequencer().shard(Array.from(specifications))
1379+
}
1380+
13301381
private async initializeGlobalSetup(paths: TestSpecification[]): Promise<void> {
13311382
const projects = new Set(paths.map((spec) => spec.project))
13321383
const coreProject = this.getRootProject()

‎packages/vitest/src/node/pool.ts‎

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,6 @@ export function createPool(ctx: Vitest): ProcessPool {
5353

5454
const options = resolveOptions(ctx)
5555

56-
const Sequencer = ctx.config.sequence.sequencer
57-
const sequencer = new Sequencer(ctx)
58-
5956
let browserPool: BrowserPool | undefined
6057

6158
async function executeTests(
@@ -65,16 +62,6 @@ export function createPool(ctx: Vitest): ProcessPool {
6562
): Promise<void> {
6663
ctx.onCancel(() => pool.cancel())
6764

68-
if (ctx.config.shard) {
69-
if (!ctx.config.passWithNoTests && ctx.config.shard.count > specs.length) {
70-
throw new Error(
71-
'--shard <count> must be a smaller than count of test files. ' +
72-
`Resolved ${specs.length} test files for --shard=${ctx.config.shard.index}/${ctx.config.shard.count}.`,
73-
)
74-
}
75-
specs = await sequencer.shard(Array.from(specs))
76-
}
77-
7865
const taskGroups: {
7966
tasks: PoolTask[]
8067
maxWorkers: number
@@ -83,9 +70,8 @@ export function createPool(ctx: Vitest): ProcessPool {
8370
}[] = []
8471
let workerId = 1
8572

86-
const sorted = await sequencer.sort(specs)
8773
const { environments, tags } = await getSpecificationsOptions(specs)
88-
const groups = groupSpecs(sorted, environments)
74+
const groups = groupSpecs(specs, environments)
8975

9076
const projectEnvs = new WeakMap<TestProject, Partial<NodeJS.ProcessEnv>>()
9177
const projectExecArgvs = new WeakMap<TestProject, string[]>()

‎packages/vitest/src/node/reporters/reported-tasks.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -547,8 +547,7 @@ export class TestModule extends SuiteImplementation {
547547
* Checks the running state of the test file.
548548
*/
549549
public state(): TestModuleState {
550-
const state = this.task.result?.state
551-
if (state === 'queued') {
550+
if (this.task.mode === 'queued' && !this.task.result) {
552551
return 'queued'
553552
}
554553
return getSuiteState(this.task)

‎packages/vitest/src/node/state.ts‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -151,12 +151,7 @@ export class StateManager {
151151
collectFiles(project: TestProject, files: File[] = []): void {
152152
files.forEach((file) => {
153153
const existing = this.filesMap.get(file.filepath) || []
154-
const currentFile = existing.find(
155-
(i) =>
156-
i.projectName === file.projectName &&
157-
i.meta.typecheck === file.meta.typecheck &&
158-
i.meta.__vitest_label__ === file.meta.__vitest_label__,
159-
)
154+
const currentFile = existing.find((i) => i.id === file.id)
160155
// keep logs for the previous file because it should always be initiated before the collections phase
161156
// which means that all logs are collected during the collection and not inside tests
162157
if (currentFile) {

‎packages/vitest/src/node/test-run.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,6 @@ export class TestRun {
157157
await this.vitest.report('onCoverage', coverage)
158158
}
159159

160-
// specification won't have the File task if they were filtered by the --shard command
161160
const modules = specifications.map((spec) => spec.testModule).filter((s) => s != null)
162161

163162
const state: TestRunEndReason = this.vitest.isCancelling
@@ -194,7 +193,10 @@ export class TestRun {
194193
return !this.vitest.config.passWithNoTests
195194
}
196195

197-
return modules.some((m) => !m.ok() || m.state() === 'pending')
196+
return modules.some((m) => {
197+
const state = m.state()
198+
return !m.ok() || state === 'pending' || state === 'queued'
199+
})
198200
}
199201

200202
// make sure the error always has a "stacks" property

0 commit comments

Comments
 (0)