-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathdispatch.rs
2705 lines (2468 loc) · 89.5 KB
/
dispatch.rs
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
use crate::{
cargo_cli::{CargoCli, CargoOptions},
output::{should_redact, OutputContext, OutputOpts, OutputWriter, StderrStyles},
reuse_build::{make_path_mapper, ArchiveFormatOpt, ReuseBuildOpts},
version, ExpectedError, Result, ReuseBuildKind,
};
use camino::{Utf8Path, Utf8PathBuf};
use clap::{builder::BoolishValueParser, ArgAction, Args, Parser, Subcommand, ValueEnum};
use guppy::graph::PackageGraph;
use itertools::Itertools;
use nextest_filtering::{EvalContext, Filterset, FiltersetKind, ParseContext};
use nextest_metadata::BuildPlatform;
use nextest_runner::{
cargo_config::{CargoConfigs, EnvironmentMap, TargetTriple},
config::{
get_num_cpus, ConfigExperimental, NextestConfig, NextestProfile, NextestVersionConfig,
NextestVersionEval, PreBuildPlatform, RetryPolicy, TestGroup, TestThreads, ToolConfigFile,
VersionOnlyConfig,
},
double_spawn::DoubleSpawnInfo,
errors::WriteTestListError,
list::{
BinaryList, OutputFormat, RustTestArtifact, SerializableFormat, TestExecuteContext,
TestList,
},
partition::PartitionerBuilder,
platform::{BuildPlatforms, HostPlatform, PlatformLibdir, TargetPlatform},
redact::Redactor,
reporter::{
heuristic_extract_description, highlight_end, structured, DescriptionKind,
FinalStatusLevel, StatusLevel, TestOutputDisplay, TestReporterBuilder,
},
reuse_build::{archive_to_file, ArchiveReporter, PathMapper, ReuseBuildInfo},
runner::{
configure_handle_inheritance, ExecutionResult, FinalRunStats, RunStatsFailureKind,
TestRunnerBuilder,
},
show_config::{ShowNextestVersion, ShowTestGroupSettings, ShowTestGroups, ShowTestGroupsMode},
signal::SignalHandlerKind,
target_runner::{PlatformRunner, TargetRunner},
test_filter::{FilterBound, RunIgnored, TestFilterBuilder, TestFilterPatterns},
write_str::WriteStr,
RustcCli,
};
use once_cell::sync::OnceCell;
use owo_colors::OwoColorize;
use quick_junit::XmlString;
use semver::Version;
use std::{
collections::BTreeSet,
env::VarError,
fmt,
io::{Cursor, Write},
sync::Arc,
};
use swrite::{swrite, SWrite};
use tracing::{debug, info, warn, Level};
/// A next-generation test runner for Rust.
///
/// This binary should typically be invoked as `cargo nextest` (in which case
/// this message will not be seen), not `cargo-nextest`.
#[derive(Debug, Parser)]
#[command(
version = version::short(),
long_version = version::long(),
bin_name = "cargo",
styles = crate::output::clap_styles::style(),
max_term_width = 100,
)]
pub struct CargoNextestApp {
#[clap(subcommand)]
subcommand: NextestSubcommand,
}
impl CargoNextestApp {
/// Initializes the output context.
pub fn init_output(&self) -> OutputContext {
match &self.subcommand {
NextestSubcommand::Nextest(args) => args.common.output.init(),
NextestSubcommand::Ntr(args) => args.common.output.init(),
#[cfg(unix)]
// Double-spawned processes should never use coloring.
NextestSubcommand::DoubleSpawn(_) => OutputContext::color_never_init(),
}
}
/// Executes the app.
pub fn exec(
self,
cli_args: Vec<String>,
output: OutputContext,
output_writer: &mut OutputWriter,
) -> Result<i32> {
match self.subcommand {
NextestSubcommand::Nextest(app) => app.exec(cli_args, output, output_writer),
NextestSubcommand::Ntr(opts) => opts.exec(cli_args, output, output_writer),
#[cfg(unix)]
NextestSubcommand::DoubleSpawn(opts) => opts.exec(output),
}
}
}
#[derive(Debug, Subcommand)]
enum NextestSubcommand {
/// A next-generation test runner for Rust. <https://nexte.st>
Nextest(Box<AppOpts>),
/// Build and run tests: a shortcut for `cargo nextest run`.
Ntr(Box<NtrOpts>),
/// Private command, used to double-spawn test processes.
#[cfg(unix)]
#[command(name = nextest_runner::double_spawn::DoubleSpawnInfo::SUBCOMMAND_NAME, hide = true)]
DoubleSpawn(crate::double_spawn::DoubleSpawnOpts),
}
#[derive(Debug, Args)]
#[clap(
version = version::short(),
long_version = version::long(),
display_name = "cargo-nextest",
)]
struct AppOpts {
#[clap(flatten)]
common: CommonOpts,
#[clap(subcommand)]
command: Command,
}
impl AppOpts {
/// Execute the command.
///
/// Returns the exit code.
fn exec(
self,
cli_args: Vec<String>,
output: OutputContext,
output_writer: &mut OutputWriter,
) -> Result<i32> {
match self.command {
Command::List {
cargo_options,
build_filter,
message_format,
list_type,
reuse_build,
..
} => {
let base = BaseApp::new(
output,
reuse_build,
cargo_options,
self.common.config_opts,
self.common.manifest_path,
output_writer,
)?;
let app = App::new(base, build_filter)?;
app.exec_list(message_format, list_type, output_writer)?;
Ok(0)
}
Command::Run(run_opts) => {
let base = BaseApp::new(
output,
run_opts.reuse_build,
run_opts.cargo_options,
self.common.config_opts,
self.common.manifest_path,
output_writer,
)?;
let app = App::new(base, run_opts.build_filter)?;
app.exec_run(
run_opts.no_capture,
&run_opts.runner_opts,
&run_opts.reporter_opts,
cli_args,
output_writer,
)?;
Ok(0)
}
Command::Archive {
cargo_options,
archive_file,
archive_format,
zstd_level,
} => {
let app = BaseApp::new(
output,
ReuseBuildOpts::default(),
cargo_options,
self.common.config_opts,
self.common.manifest_path,
output_writer,
)?;
app.exec_archive(&archive_file, archive_format, zstd_level, output_writer)?;
Ok(0)
}
Command::ShowConfig { command } => command.exec(
self.common.manifest_path,
self.common.config_opts,
output,
output_writer,
),
Command::Self_ { command } => command.exec(self.common.output),
Command::Debug { command } => command.exec(self.common.output),
}
}
}
// Options shared between cargo nextest and cargo ntr.
#[derive(Debug, Args)]
struct CommonOpts {
/// Path to Cargo.toml
#[arg(
long,
global = true,
value_name = "PATH",
help_heading = "Manifest options"
)]
manifest_path: Option<Utf8PathBuf>,
#[clap(flatten)]
output: OutputOpts,
#[clap(flatten)]
config_opts: ConfigOpts,
}
#[derive(Debug, Args)]
#[command(next_help_heading = "Config options")]
struct ConfigOpts {
/// Config file [default: workspace-root/.config/nextest.toml]
#[arg(long, global = true, value_name = "PATH")]
pub config_file: Option<Utf8PathBuf>,
/// Tool-specific config files
///
/// Some tools on top of nextest may want to set up their own default configuration but
/// prioritize user configuration on top. Use this argument to insert configuration
/// that's lower than --config-file in priority but above the default config shipped with
/// nextest.
///
/// Arguments are specified in the format "tool:abs_path", for example
/// "my-tool:/path/to/nextest.toml" (or "my-tool:C:\\path\\to\\nextest.toml" on Windows).
/// Paths must be absolute.
///
/// This argument may be specified multiple times. Files that come later are lower priority
/// than those that come earlier.
#[arg(long = "tool-config-file", global = true, value_name = "TOOL:ABS_PATH")]
pub tool_config_files: Vec<ToolConfigFile>,
/// Override checks for the minimum version defined in nextest's config.
///
/// Repository and tool-specific configuration files can specify minimum required and
/// recommended versions of nextest. This option overrides those checks.
#[arg(long, global = true)]
pub override_version_check: bool,
/// The nextest profile to use.
///
/// Nextest's configuration supports multiple profiles, which can be used to set up different
/// configurations for different purposes. (For example, a configuration for local runs and one
/// for CI.) This option selects the profile to use.
#[arg(
long,
short = 'P',
env = "NEXTEST_PROFILE",
global = true,
help_heading = "Config options"
)]
profile: Option<String>,
}
impl ConfigOpts {
/// Creates a nextest version-only config with the given options.
pub fn make_version_only_config(&self, workspace_root: &Utf8Path) -> Result<VersionOnlyConfig> {
VersionOnlyConfig::from_sources(
workspace_root,
self.config_file.as_deref(),
&self.tool_config_files,
)
.map_err(ExpectedError::config_parse_error)
}
/// Creates a nextest config with the given options.
pub fn make_config(
&self,
workspace_root: &Utf8Path,
graph: &PackageGraph,
experimental: &BTreeSet<ConfigExperimental>,
) -> Result<NextestConfig> {
NextestConfig::from_sources(
workspace_root,
graph,
self.config_file.as_deref(),
&self.tool_config_files,
experimental,
)
.map_err(ExpectedError::config_parse_error)
}
}
#[derive(Debug, Subcommand)]
enum Command {
/// List tests in workspace
///
/// This command builds test binaries and queries them for the tests they contain.
///
/// Use --verbose to get more information about tests, including test binary paths and skipped
/// tests.
///
/// Use --message-format json to get machine-readable output.
///
/// For more information, see <https://nexte.st/docs/listing>.
List {
#[clap(flatten)]
cargo_options: CargoOptions,
#[clap(flatten)]
build_filter: TestBuildFilter,
/// Output format
#[arg(
short = 'T',
long,
value_enum,
default_value_t,
help_heading = "Output options",
value_name = "FMT"
)]
message_format: MessageFormatOpts,
/// Type of listing
#[arg(
long,
value_enum,
default_value_t,
help_heading = "Output options",
value_name = "TYPE"
)]
list_type: ListType,
#[clap(flatten)]
reuse_build: ReuseBuildOpts,
},
/// Build and run tests
///
/// This command builds test binaries and queries them for the tests they contain,
/// then runs each test in parallel.
///
/// For more information, see <https://nexte.st/docs/running>.
#[command(visible_alias = "r")]
Run(RunOpts),
/// Build and archive tests
///
/// This command builds test binaries and archives them to a file. The archive can then be
/// transferred to another machine, and tests within it can be run with `cargo nextest run
/// --archive-file`.
///
/// The archive is a tarball compressed with Zstandard (.tar.zst).
Archive {
#[clap(flatten)]
cargo_options: CargoOptions,
/// File to write archive to
#[arg(
long,
name = "archive-file",
help_heading = "Archive options",
value_name = "PATH"
)]
archive_file: Utf8PathBuf,
/// Archive format
///
/// `auto` uses the file extension to determine the archive format. Currently supported is
/// `.tar.zst`.
#[arg(
long,
value_enum,
help_heading = "Archive options",
value_name = "FORMAT",
default_value_t
)]
archive_format: ArchiveFormatOpt,
/// Zstandard compression level (-7 to 22, higher is more compressed + slower)
#[arg(
long,
help_heading = "Archive options",
value_name = "LEVEL",
default_value_t = 0,
allow_negative_numbers = true
)]
zstd_level: i32,
// ReuseBuildOpts, while it can theoretically work, is way too confusing so skip it.
},
/// Show information about nextest's configuration in this workspace.
///
/// This command shows configuration information about nextest, including overrides applied to
/// individual tests.
///
/// In the future, this will show more information about configurations and overrides.
ShowConfig {
#[clap(subcommand)]
command: ShowConfigCommand,
},
/// Manage the nextest installation
#[clap(name = "self")]
Self_ {
#[clap(subcommand)]
command: SelfCommand,
},
/// Debug commands
///
/// The commands in this section are for nextest's own developers and those integrating with it
/// to debug issues. They are not part of the public API and may change at any time.
#[clap(hide = true)]
Debug {
#[clap(subcommand)]
command: DebugCommand,
},
}
#[derive(Debug, Args)]
struct NtrOpts {
#[clap(flatten)]
common: CommonOpts,
#[clap(flatten)]
run_opts: RunOpts,
}
impl NtrOpts {
fn exec(
self,
cli_args: Vec<String>,
output: OutputContext,
output_writer: &mut OutputWriter,
) -> Result<i32> {
let base = BaseApp::new(
output,
self.run_opts.reuse_build,
self.run_opts.cargo_options,
self.common.config_opts,
self.common.manifest_path,
output_writer,
)?;
let app = App::new(base, self.run_opts.build_filter)?;
app.exec_run(
self.run_opts.no_capture,
&self.run_opts.runner_opts,
&self.run_opts.reporter_opts,
cli_args,
output_writer,
)
}
}
#[derive(Debug, Args)]
struct RunOpts {
#[clap(flatten)]
cargo_options: CargoOptions,
#[clap(flatten)]
build_filter: TestBuildFilter,
#[clap(flatten)]
runner_opts: TestRunnerOpts,
/// Run tests serially and do not capture output
#[arg(
long,
name = "no-capture",
alias = "nocapture",
help_heading = "Runner options",
display_order = 100
)]
no_capture: bool,
#[clap(flatten)]
reporter_opts: TestReporterOpts,
#[clap(flatten)]
reuse_build: ReuseBuildOpts,
}
#[derive(Copy, Clone, Debug, ValueEnum)]
pub(crate) enum PlatformFilterOpts {
Target,
Host,
Any,
}
impl Default for PlatformFilterOpts {
fn default() -> Self {
Self::Any
}
}
impl From<PlatformFilterOpts> for Option<BuildPlatform> {
fn from(opt: PlatformFilterOpts) -> Self {
match opt {
PlatformFilterOpts::Target => Some(BuildPlatform::Target),
PlatformFilterOpts::Host => Some(BuildPlatform::Host),
PlatformFilterOpts::Any => None,
}
}
}
#[derive(Copy, Clone, Debug, ValueEnum)]
enum ListType {
Full,
BinariesOnly,
}
impl Default for ListType {
fn default() -> Self {
Self::Full
}
}
#[derive(Copy, Clone, Debug, ValueEnum)]
enum MessageFormatOpts {
Human,
Json,
JsonPretty,
}
impl MessageFormatOpts {
fn to_output_format(self, verbose: bool) -> OutputFormat {
match self {
Self::Human => OutputFormat::Human { verbose },
Self::Json => OutputFormat::Serializable(SerializableFormat::Json),
Self::JsonPretty => OutputFormat::Serializable(SerializableFormat::JsonPretty),
}
}
}
impl Default for MessageFormatOpts {
fn default() -> Self {
Self::Human
}
}
#[derive(Debug, Args)]
#[command(next_help_heading = "Filter options")]
struct TestBuildFilter {
/// Run ignored tests
#[arg(long, value_enum, value_name = "WHICH")]
run_ignored: Option<RunIgnoredOpt>,
/// Test partition, e.g. hash:1/2 or count:2/3
#[arg(long)]
partition: Option<PartitionerBuilder>,
/// Filter test binaries by build platform (DEPRECATED)
///
/// Instead, use -E with 'platform(host)' or 'platform(target)'.
#[arg(
long,
hide_short_help = true,
value_enum,
value_name = "PLATFORM",
default_value_t
)]
pub(crate) platform_filter: PlatformFilterOpts,
/// Test filterset (see {n}<https://nexte.st/docs/filtersets>).
#[arg(
long,
alias = "filter-expr",
short = 'E',
value_name = "EXPR",
action(ArgAction::Append)
)]
filterset: Vec<String>,
/// Ignore the default filter configured in the profile.
///
/// By default, all filtersets are intersected with the default filter configured in the
/// profile. This flag disables that behavior.
///
/// This flag doesn't change the definition of the `default()` filterset.
#[arg(long)]
ignore_default_filter: bool,
/// Test name filters.
#[arg(help_heading = None, name = "FILTERS")]
pre_double_dash_filters: Vec<String>,
/// Test name filters and emulated test binary arguments.
///
/// Supported arguments:{n}
/// - --ignored: Only run ignored tests{n}
/// - --include-ignored: Run both ignored and non-ignored tests{n}
/// - --skip PATTERN: Skip tests that match the pattern{n}
/// - --exact: Run tests that exactly match patterns after `--`
#[arg(help_heading = None, value_name = "FILTERS_AND_ARGS", last = true)]
filters: Vec<String>,
}
impl TestBuildFilter {
#[allow(clippy::too_many_arguments)]
fn compute_test_list<'g>(
&self,
ctx: &TestExecuteContext<'_>,
graph: &'g PackageGraph,
workspace_root: Utf8PathBuf,
binary_list: Arc<BinaryList>,
test_filter_builder: TestFilterBuilder,
env: EnvironmentMap,
ecx: &EvalContext<'_>,
reuse_build: &ReuseBuildInfo,
) -> Result<TestList<'g>> {
let path_mapper = make_path_mapper(
reuse_build,
graph,
&binary_list.rust_build_meta.target_directory,
)?;
let rust_build_meta = binary_list.rust_build_meta.map_paths(&path_mapper);
let test_artifacts = RustTestArtifact::from_binary_list(
graph,
binary_list,
&rust_build_meta,
&path_mapper,
self.platform_filter.into(),
)?;
TestList::new(
ctx,
test_artifacts,
rust_build_meta,
&test_filter_builder,
workspace_root,
env,
ecx,
if self.ignore_default_filter {
FilterBound::All
} else {
FilterBound::DefaultSet
},
// TODO: do we need to allow customizing this?
get_num_cpus(),
)
.map_err(|err| ExpectedError::CreateTestListError { err })
}
fn make_test_filter_builder(&self, filter_exprs: Vec<Filterset>) -> Result<TestFilterBuilder> {
// Merge the test binary args into the patterns.
let mut run_ignored = self.run_ignored.map(Into::into);
let mut patterns = TestFilterPatterns::new(self.pre_double_dash_filters.clone());
self.merge_test_binary_args(&mut run_ignored, &mut patterns)?;
Ok(TestFilterBuilder::new(
run_ignored.unwrap_or_default(),
self.partition.clone(),
patterns,
filter_exprs,
)?)
}
fn merge_test_binary_args(
&self,
run_ignored: &mut Option<RunIgnored>,
patterns: &mut TestFilterPatterns,
) -> Result<()> {
// First scan to see if `--exact` is specified. If so, then everything here will be added to
// `--exact`.
let mut is_exact = false;
for arg in &self.filters {
if arg == "--" {
break;
}
if arg == "--exact" {
if is_exact {
return Err(ExpectedError::test_binary_args_parse_error(
"duplicated",
vec![arg.clone()],
));
}
is_exact = true;
}
}
let mut ignore_filters = Vec::new();
let mut read_trailing_filters = false;
let mut unsupported_args = Vec::new();
let mut it = self.filters.iter();
while let Some(arg) = it.next() {
if read_trailing_filters || !arg.starts_with('-') {
if is_exact {
patterns.add_exact_pattern(arg.clone());
} else {
patterns.add_substring_pattern(arg.clone());
}
} else if arg == "--include-ignored" {
ignore_filters.push((arg.clone(), RunIgnored::All));
} else if arg == "--ignored" {
ignore_filters.push((arg.clone(), RunIgnored::Only));
} else if arg == "--" {
read_trailing_filters = true;
} else if arg == "--skip" {
let skip_arg = it.next().ok_or_else(|| {
ExpectedError::test_binary_args_parse_error(
"missing required argument",
vec![arg.clone()],
)
})?;
if is_exact {
patterns.add_skip_exact_pattern(skip_arg.clone());
} else {
patterns.add_skip_pattern(skip_arg.clone());
}
} else if arg == "--exact" {
// Already handled above.
} else {
unsupported_args.push(arg.clone());
}
}
for (s, f) in ignore_filters {
if let Some(run_ignored) = run_ignored {
if *run_ignored != f {
return Err(ExpectedError::test_binary_args_parse_error(
"mutually exclusive",
vec![s],
));
} else {
return Err(ExpectedError::test_binary_args_parse_error(
"duplicated",
vec![s],
));
}
} else {
*run_ignored = Some(f);
}
}
if !unsupported_args.is_empty() {
return Err(ExpectedError::test_binary_args_parse_error(
"unsupported",
unsupported_args,
));
}
Ok(())
}
}
#[derive(Copy, Clone, Debug, ValueEnum)]
enum RunIgnoredOpt {
/// Run non-ignored tests.
Default,
/// Run ignored tests.
#[clap(alias = "ignored-only")]
Only,
/// Run both ignored and non-ignored tests.
All,
}
impl From<RunIgnoredOpt> for RunIgnored {
fn from(opt: RunIgnoredOpt) -> Self {
match opt {
RunIgnoredOpt::Default => RunIgnored::Default,
RunIgnoredOpt::Only => RunIgnored::Only,
RunIgnoredOpt::All => RunIgnored::All,
}
}
}
impl CargoOptions {
fn compute_binary_list(
&self,
graph: &PackageGraph,
manifest_path: Option<&Utf8Path>,
output: OutputContext,
build_platforms: BuildPlatforms,
) -> Result<BinaryList> {
// Don't use the manifest path from the graph to ensure that if the user cd's into a
// particular crate and runs cargo nextest, then it behaves identically to cargo test.
let mut cargo_cli = CargoCli::new("test", manifest_path, output);
// Only build tests in the cargo test invocation, do not run them.
cargo_cli.add_args(["--no-run", "--message-format", "json-render-diagnostics"]);
cargo_cli.add_options(self);
let expression = cargo_cli.to_expression();
let output = expression
.stdout_capture()
.unchecked()
.run()
.map_err(|err| ExpectedError::build_exec_failed(cargo_cli.all_args(), err))?;
if !output.status.success() {
return Err(ExpectedError::build_failed(
cargo_cli.all_args(),
output.status.code(),
));
}
let test_binaries =
BinaryList::from_messages(Cursor::new(output.stdout), graph, build_platforms)?;
Ok(test_binaries)
}
}
/// Test runner options.
#[derive(Debug, Default, Args)]
#[command(next_help_heading = "Runner options")]
pub struct TestRunnerOpts {
/// Compile, but don't run tests
#[arg(long, name = "no-run")]
no_run: bool,
/// Number of tests to run simultaneously [possible values: integer or "num-cpus"]
/// [default: from profile]
#[arg(
long,
short = 'j',
visible_alias = "jobs",
value_name = "N",
conflicts_with_all = &["no-capture", "no-run"],
env = "NEXTEST_TEST_THREADS",
allow_negative_numbers = true,
)]
test_threads: Option<TestThreads>,
/// Number of retries for failing tests [default: from profile]
#[arg(
long,
env = "NEXTEST_RETRIES",
value_name = "N",
conflicts_with = "no-run"
)]
retries: Option<usize>,
/// Cancel test run on the first failure
#[arg(long, name = "fail-fast", conflicts_with = "no-run")]
fail_fast: bool,
/// Run all tests regardless of failure
#[arg(long, conflicts_with = "no-run", overrides_with = "fail-fast")]
no_fail_fast: bool,
/// Behavior if there are no tests to run.
///
/// The default is currently `warn`, but it will change to `fail` in the future.
#[arg(
long,
value_enum,
conflicts_with = "no-run",
value_name = "ACTION",
require_equals = true,
env = "NEXTEST_NO_TESTS"
)]
no_tests: Option<NoTestsBehavior>,
}
#[derive(Clone, Copy, Debug, Default, ValueEnum)]
enum NoTestsBehavior {
/// Silently exit with code 0.
Pass,
/// Produce a warning and exit with code 0.
#[default]
Warn,
/// Produce an error message and exit with code 4.
#[clap(alias = "error")]
Fail,
}
impl TestRunnerOpts {
fn to_builder(
&self,
cap_strat: nextest_runner::test_output::CaptureStrategy,
) -> Option<TestRunnerBuilder> {
if self.no_run {
return None;
}
let mut builder = TestRunnerBuilder::default();
builder.set_capture_strategy(cap_strat);
if let Some(retries) = self.retries {
builder.set_retries(RetryPolicy::new_without_delay(retries));
}
if self.no_fail_fast {
builder.set_fail_fast(false);
} else if self.fail_fast {
builder.set_fail_fast(true);
}
if let Some(test_threads) = self.test_threads {
builder.set_test_threads(test_threads);
}
Some(builder)
}
}
#[derive(Clone, Copy, Debug, ValueEnum)]
enum IgnoreOverridesOpt {
Retries,
All,
}
#[derive(Clone, Copy, Debug, ValueEnum, Default)]
enum MessageFormat {
/// The default output format.
#[default]
Human,
/// Output test information in the same format as libtest.
LibtestJson,
/// Output test information in the same format as libtest, with a `nextest` subobject that
/// includes additional metadata.
LibtestJsonPlus,
}
#[derive(Debug, Default, Args)]
#[command(next_help_heading = "Reporter options")]
struct TestReporterOpts {
/// Output stdout and stderr on failure
#[arg(
long,
value_enum,
conflicts_with_all = &["no-capture", "no-run"],
value_name = "WHEN",
env = "NEXTEST_FAILURE_OUTPUT",
)]
failure_output: Option<TestOutputDisplayOpt>,
/// Output stdout and stderr on success
#[arg(
long,
value_enum,
conflicts_with_all = &["no-capture", "no-run"],
value_name = "WHEN",
env = "NEXTEST_SUCCESS_OUTPUT",
)]
success_output: Option<TestOutputDisplayOpt>,
// status_level does not conflict with --no-capture because pass vs skip still makes sense.
/// Test statuses to output
#[arg(
long,
value_enum,
conflicts_with = "no-run",
value_name = "LEVEL",
env = "NEXTEST_STATUS_LEVEL"
)]
status_level: Option<StatusLevelOpt>,
/// Test statuses to output at the end of the run.
#[arg(
long,
value_enum,
conflicts_with = "no-run",
value_name = "LEVEL",
env = "NEXTEST_FINAL_STATUS_LEVEL"
)]
final_status_level: Option<FinalStatusLevelOpt>,
/// Do not display the progress bar
#[arg(long, env = "NEXTEST_HIDE_PROGRESS_BAR", value_parser = BoolishValueParser::new())]
hide_progress_bar: bool,
/// Format to use for test results (experimental).
#[arg(
long,
name = "message-format",
value_enum,
default_value_t,
conflicts_with = "no-run",
value_name = "FORMAT",
env = "NEXTEST_MESSAGE_FORMAT"
)]
message_format: MessageFormat,
/// Version of structured message-format to use (experimental).
///
/// This allows the machine-readable formats to use a stable structure for consistent
/// consumption across changes to nextest. If not specified, the latest version is used.
#[arg(
long,
conflicts_with = "no-run",
requires = "message-format",
value_name = "VERSION",
env = "NEXTEST_MESSAGE_FORMAT_VERSION"
)]
message_format_version: Option<String>,
}
impl TestReporterOpts {
fn to_builder(&self, no_capture: bool) -> TestReporterBuilder {