1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
use crate::execution::TestSuiteExecution;
use crate::output::TestRunnerOutput;
use clap::{Parser, ValueEnum};
use std::ffi::OsString;
use std::num::NonZero;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
/// Command line arguments.
///
/// This type represents everything the user can specify via CLI args. The main
/// method is [`from_args`][Arguments::from_args] which reads the global
/// `std::env::args()` and parses them into this type.
#[derive(Parser, Debug, Clone, Default)]
#[command(
help_template = "USAGE: [OPTIONS] [FILTERS...]\n\n{all-args}\n",
disable_version_flag = true
)]
pub struct Arguments {
/// Run ignored and not ignored tests
#[arg(long = "include-ignored")]
pub include_ignored: bool,
/// Run only ignored tests
#[arg(long = "ignored")]
pub ignored: bool,
/// Excludes tests marked as should_panic
#[arg(long = "exclude-should-panic")]
pub exclude_should_panic: bool,
/// Run tests and not benchmarks
#[arg(long = "test", conflicts_with = "bench")]
pub test: bool,
/// Run benchmarks instead of tests
#[arg(long = "bench")]
pub bench: bool,
/// List all tests and benchmarks
#[arg(long = "list")]
pub list: bool,
/// Write logs to the specified file
#[arg(long = "logfile", value_name = "PATH")]
pub logfile: Option<String>,
/// don't capture stdout/stderr of each task, allow printing directly
#[arg(long = "nocapture")]
pub nocapture: bool,
/// Number of threads used for running tests in parallel
#[arg(long = "test-threads")]
pub test_threads: Option<usize>,
/// Skip tests whose names contains FILTER (this flag can be used multiple times)
#[arg(long = "skip", value_name = "FILTER")]
pub skip: Vec<String>,
/// Display one character per test instead of one line.
/// Alias to `--format=terse`
#[arg(short = 'q', long = "quiet", conflicts_with = "format")]
pub quiet: bool,
/// Exactly match filters rather than by substring
#[arg(long = "exact")]
pub exact: bool,
/// Configure coloring of output
#[arg(long = "color", value_enum, value_name = "auto|always|never")]
pub color: Option<ColorSetting>,
/// Configure formatting of output
#[arg(long = "format", value_enum, value_name = "pretty|terse|json|junit")]
pub format: Option<FormatSetting>,
/// Show captured stdout of successful tests
#[arg(long = "show-output")]
pub show_output: bool,
/// Enable nightly-only flags
#[arg(short = 'Z')]
pub unstable_flags: Option<UnstableFlags>,
/// Show execution time of each test.
/// Threshold values for colorized output can be configured via `RUST_TEST_TIME_UNIT`,
/// `RUST_TEST_TIME_INTEGRATION` and `RUST_TEST_TIME_DOCTEST` environment variables.
/// Expected format of the environment variables is `VARIABLE=WARN_TIME,CRITICAL_TIME`.
/// Durations must be specified in milliseconds, e.g. `500,2000` means that the warn time is 0.5
/// seconds, and the critical time is 2 seconds.
/// Not available for `--format=terse`.
#[arg(long = "report-time")]
pub report_time: bool,
/// Treat excess of the test execution time limit as error.
/// Threshold values for this option can be configured via `RUST_TEST_TIME_UNIT`,
/// `RUST_TEST_TIME_INTEGRATION` and `RUST_TEST_TIME_DOCTEST` environment variables.
/// Expected format of the environment variables is `VARIABLE=WARN_TIME,CRITICAL_TIME`.
/// `CRITICAL_TIME` here means the limit that should not be exceeded by test.
#[arg(long = "ensure-time")]
pub ensure_time: bool,
/// Run tests in random order
#[arg(long = "shuffle", conflicts_with = "shuffle_seed")]
pub shuffle: bool,
/// Run tests in random order; seed the random number generator with SEED
#[arg(long = "shuffle-seed", value_name = "SEED", conflicts_with = "shuffle")]
pub shuffle_seed: Option<u64>,
/// Show detailed benchmark statistics for each benchmark
#[arg(long = "show-stats")]
pub show_stats: bool,
/// The FILTER string is tested against the name of all tests, and only those
/// tests whose names contain the filter are run. Multiple filter strings may
/// be passed, which will run all tests matching any of the filters.
#[arg(value_name = "FILTER")]
pub filter: Vec<String>,
/// Marks the whole run (all the selected tests) as expected to be flaky, to
/// be retried on top level a given number of times if needed.
#[arg(long = "flaky-run", value_name = "COUNT")]
pub flaky_run: Option<usize>,
/// Run the test suite in worker IPC mode - listening on the given local socket waiting
/// for the test runner to connect and send test execution requests. The only stdout/stderr
/// output will be the one emitted by the actual test runs so the test runner can capture them.
#[arg(long = "ipc", hide = true)]
pub ipc: Option<String>,
/// If true, spawn worker processes in IPC mode and run the tests on those
#[arg(long = "spawn-workers", hide = true)]
pub spawn_workers: bool,
/// Zero-based worker index assigned by the parent runner when it spawns
/// a child worker process. Available to `PerWorker` constructors via
/// [`crate::worker_index`]. Set only on spawned worker subprocesses;
/// the top-level parent leaves it unset and observes index `0`.
#[arg(long = "worker-index", hide = true)]
pub worker_index: Option<usize>,
}
impl Arguments {
/// Parses the global CLI arguments given to the application.
///
/// If the parsing fails (due to incorrect CLI args), an error is shown and
/// the application exits. If help is requested (`-h` or `--help`), a help
/// message is shown and the application exits, too.
pub fn from_args() -> Self {
let mut result: Self = Parser::parse();
if result.shuffle && result.shuffle_seed.is_none() {
// Setting a specific shuffle seed so all spawned workers use the same
result.shuffle_seed = Some(rand::random());
result.shuffle = false;
}
result
}
/// Renders the arguments as a list of strings that can be passed to a subprocess
pub fn to_args(&self) -> Vec<OsString> {
let mut result = Vec::new();
if self.include_ignored {
result.push(OsString::from("--include-ignored"));
}
if self.ignored {
result.push(OsString::from("--ignored"));
}
if self.exclude_should_panic {
result.push(OsString::from("--exclude-should-panic"));
}
if self.test {
result.push(OsString::from("--test"));
}
if self.bench {
result.push(OsString::from("--bench"));
}
if self.list {
result.push(OsString::from("--list"));
}
if let Some(logfile) = &self.logfile {
result.push(OsString::from("--logfile"));
result.push(OsString::from(logfile));
}
if self.nocapture {
result.push(OsString::from("--nocapture"));
}
if let Some(test_threads) = self.test_threads {
result.push(OsString::from("--test-threads"));
result.push(OsString::from(test_threads.to_string()));
}
for skip in &self.skip {
result.push(OsString::from("--skip"));
result.push(OsString::from(skip));
}
if self.quiet {
result.push(OsString::from("--quiet"));
}
if self.exact {
result.push(OsString::from("--exact"));
}
if let Some(color) = self.color {
result.push(OsString::from("--color"));
match color {
ColorSetting::Auto => result.push(OsString::from("auto")),
ColorSetting::Always => result.push(OsString::from("always")),
ColorSetting::Never => result.push(OsString::from("never")),
}
}
if let Some(format) = self.format {
result.push(OsString::from("--format"));
match format {
FormatSetting::Pretty => result.push(OsString::from("pretty")),
FormatSetting::Terse => result.push(OsString::from("terse")),
FormatSetting::Json => result.push(OsString::from("json")),
FormatSetting::Junit => result.push(OsString::from("junit")),
FormatSetting::Ctrf => result.push(OsString::from("ctrf")),
}
}
if self.show_output {
result.push(OsString::from("--show-output"));
}
if let Some(unstable_flags) = &self.unstable_flags {
result.push(OsString::from("-Z"));
match unstable_flags {
UnstableFlags::UnstableOptions => result.push(OsString::from("unstable-options")),
}
}
if self.report_time {
result.push(OsString::from("--report-time"));
}
if self.ensure_time {
result.push(OsString::from("--ensure-time"));
}
if self.shuffle {
result.push(OsString::from("--shuffle"));
}
if let Some(shuffle_seed) = &self.shuffle_seed {
result.push(OsString::from("--shuffle-seed"));
result.push(OsString::from(shuffle_seed.to_string()));
}
if self.show_stats {
result.push(OsString::from("--show-stats"));
}
if let Some(flaky_run) = &self.flaky_run {
result.push(OsString::from("--flaky-run"));
result.push(OsString::from(flaky_run.to_string()));
}
if let Some(ipc) = &self.ipc {
result.push(OsString::from("--ipc"));
result.push(OsString::from(ipc));
}
if self.spawn_workers {
result.push(OsString::from("--spawn-workers"));
}
if let Some(worker_index) = self.worker_index {
result.push(OsString::from("--worker-index"));
result.push(OsString::from(worker_index.to_string()));
}
for filter in &self.filter {
result.push(OsString::from(filter));
}
result
}
pub fn unit_test_threshold(&self) -> TimeThreshold {
TimeThreshold::from_env_var("RUST_TEST_TIME_UNIT").unwrap_or(TimeThreshold::new(
Duration::from_millis(50),
Duration::from_millis(100),
))
}
pub fn integration_test_threshold(&self) -> TimeThreshold {
TimeThreshold::from_env_var("RUST_TEST_TIME_INTEGRATION").unwrap_or(TimeThreshold::new(
Duration::from_millis(500),
Duration::from_millis(1000),
))
}
pub(crate) fn test_threads(&self) -> NonZero<usize> {
if self.ipc.is_some() {
// When running as an IPC-controlled worker, always use a single
// thread (the worker processes tests one at a time on behalf of
// the parent).
NonZero::new(1).unwrap()
} else {
self.test_threads
.and_then(NonZero::new)
.or_else(|| std::thread::available_parallelism().ok())
.unwrap_or(NonZero::new(1).unwrap())
}
}
/// Returns `true` when this process is the top-level test-suite parent.
///
/// The top-level parent is the only place that may materialise
/// `Cloneable` and `Hosted` test-dependency owners. IPC worker
/// subprocesses (where `--ipc <name>` is set) MUST NOT run those
/// constructors — they receive the parent's materialised values /
/// descriptors via IPC instead.
pub(crate) fn is_top_level_parent(&self) -> bool {
self.ipc.is_none()
}
/// Make necessary adjustments to the configuration if needed based on the final execution plan
pub(crate) fn finalize_for_execution(
&mut self,
execution: &TestSuiteExecution,
output: Arc<dyn TestRunnerOutput>,
) {
let requires_capturing = execution.requires_capturing(!self.nocapture);
if !requires_capturing || self.ipc.is_some() {
// If there is no need to capture the output, there are no restrictions to check and apply
// If this is an IPC worker, we don't need to do anything either, as the top level test runner already sets the proper arguments
} else {
// If capture is enabled, we need to spawn at least one worker process
self.spawn_workers = true;
if self.test_threads().get() > 1 {
// Parallel + capture requires worker processes. Only `Shared`
// dependencies force a single-threaded fallback, because
// their materialised value cannot cross the parent/worker
// boundary. `PerWorker` deps are materialised independently
// in each worker, `Cloneable` deps ship their wire bytes via
// IPC, `Hosted` deps materialise their owner once in the
// parent and ship a descriptor to each worker — all three
// are safe to run in parallel.
if execution.has_shared_dependencies() {
if execution.remaining() > 1 {
// If there is only one test, the warning does not make sense
output.warning("Cannot run tests in parallel when tests have shared dependencies and output capturing is on. Using a single thread.");
}
self.test_threads = Some(1); // Falling back to single-threaded execution
}
}
}
}
}
impl<A: Into<OsString> + Clone> FromIterator<A> for Arguments {
fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
Parser::parse_from(iter)
}
}
/// Possible values for the `--color` option.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
pub enum ColorSetting {
/// Colorize if stdout is a tty and tests are run on serially (default)
#[default]
Auto,
/// Always colorize output
Always,
/// Never colorize output
Never,
}
/// Possible values for the `-Z` option
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum UnstableFlags {
/// Allow use of experimental features
UnstableOptions,
}
/// Possible values for the `--format` option.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
pub enum FormatSetting {
/// Print verbose output
#[default]
Pretty,
/// Display one character per test
Terse,
/// Output a json document
Json,
/// Output a JUnit document
Junit,
/// Output to Common Test Report Format
Ctrf,
}
/// Structure denoting time limits for test execution.
///
/// From https://github.com/rust-lang/rust/blob/master/library/test/src/time.rs
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct TimeThreshold {
pub warn: Duration,
pub critical: Duration,
}
impl TimeThreshold {
/// Creates a new `TimeThreshold` instance with provided durations.
pub fn new(warn: Duration, critical: Duration) -> Self {
Self { warn, critical }
}
/// Attempts to create a `TimeThreshold` instance with values obtained
/// from the environment variable, and returns `None` if the variable
/// is not set.
/// Environment variable format is expected to match `\d+,\d+`.
///
/// # Panics
///
/// Panics if variable with provided name is set but contains inappropriate
/// value.
pub fn from_env_var(env_var_name: &str) -> Option<Self> {
let durations_str = std::env::var(env_var_name).ok()?;
let (warn_str, critical_str) = durations_str.split_once(',').unwrap_or_else(|| {
panic!(
"Duration variable {env_var_name} expected to have 2 numbers separated by comma, but got {durations_str}"
)
});
let parse_u64 = |v| {
u64::from_str(v).unwrap_or_else(|_| {
panic!(
"Duration value in variable {env_var_name} is expected to be a number, but got {v}"
)
})
};
let warn = parse_u64(warn_str);
let critical = parse_u64(critical_str);
if warn > critical {
panic!("Test execution warn time should be less or equal to the critical time");
}
Some(Self::new(
Duration::from_millis(warn),
Duration::from_millis(critical),
))
}
pub fn is_critical(&self, duration: &Duration) -> bool {
*duration >= self.critical
}
pub fn is_warn(&self, duration: &Duration) -> bool {
*duration >= self.warn
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn verify_cli() {
use clap::CommandFactory;
Arguments::command().debug_assert();
}
/// Regression coverage for the parent-only Hosted-owner materialisation
/// gating in `sync.rs` / `tokio.rs`. If this assertion ever flips,
/// IPC worker subprocesses could start running Hosted owner
/// constructors again — duplicating singleton resources (TCP listeners,
/// containers, env-based test environments) across every worker.
#[test]
fn is_top_level_parent_when_ipc_unset() {
// Use a single placeholder binary name so clap definitely sees a
// well-formed argv with no `--ipc` flag.
let mut args: Arguments = Parser::parse_from(["test-bin"]);
// Sanity: a freshly parsed Arguments with no overrides has no IPC.
assert!(args.ipc.is_none());
assert!(
args.is_top_level_parent(),
"process without --ipc must be treated as top-level parent"
);
// Even when the parent decides to spawn workers, it is still the
// top-level parent itself.
args.spawn_workers = true;
assert!(args.is_top_level_parent());
}
#[test]
fn ipc_worker_is_not_top_level_parent() {
let mut args: Arguments = Parser::parse_from(["test-bin"]);
args.ipc = Some("test-ipc-socket".to_string());
assert!(
!args.is_top_level_parent(),
"IPC worker subprocesses must NOT be treated as top-level parent — \
otherwise they would duplicate Hosted owner construction"
);
// And `test_threads()` must already collapse to 1 for IPC workers,
// independent of the user's `--test-threads` value.
args.test_threads = Some(4);
assert_eq!(args.test_threads().get(), 1);
}
/// Phase 3.3: regression coverage for the `--worker-index` round trip.
/// If `to_args` ever drops the field or `Parser::parse_from` ever fails
/// to populate it, spawned workers would silently fall back to index 0
/// and lose the per-worker namespace partitioning that PerWorker deps
/// like `LastUniqueId` depend on.
#[test]
fn worker_index_round_trips_through_to_args_and_parse() {
let mut args: Arguments = Parser::parse_from(["test-bin"]);
args.worker_index = Some(3);
let argv = args.to_args();
let argv_strings: Vec<String> = argv
.iter()
.map(|s| s.to_string_lossy().into_owned())
.collect();
assert!(
argv_strings.iter().any(|s| s == "--worker-index"),
"to_args() must emit --worker-index when worker_index is Some; \
got {argv_strings:?}"
);
// Round-trip back through clap with the binary name prepended.
let mut roundtripped_argv: Vec<String> = vec!["test-bin".to_string()];
roundtripped_argv.extend(argv_strings);
let parsed: Arguments = Parser::parse_from(roundtripped_argv);
assert_eq!(parsed.worker_index, Some(3));
}
#[test]
fn worker_index_absent_round_trip_stays_none() {
let args: Arguments = Parser::parse_from(["test-bin"]);
assert!(args.worker_index.is_none());
let argv = args.to_args();
let argv_strings: Vec<String> = argv
.iter()
.map(|s| s.to_string_lossy().into_owned())
.collect();
assert!(
!argv_strings.iter().any(|s| s == "--worker-index"),
"to_args() must NOT emit --worker-index when worker_index is None; \
got {argv_strings:?}"
);
}
}