nextest-runner 0.114.0

Core runner logic for cargo nextest.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

use serde::{Deserialize, Serialize};
use std::{cmp::Ordering, fmt, time::Duration};

/// Type for the retry config key.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum RetryPolicy {
    /// Fixed backoff.
    Fixed {
        /// Maximum retry count.
        count: u32,

        /// Delay between retries.
        delay: Duration,

        /// If set to true, randomness will be added to the delay on each retry attempt.
        jitter: bool,
    },

    /// Exponential backoff.
    Exponential {
        /// Maximum retry count.
        count: u32,

        /// Delay between retries. Not optional for exponential backoff.
        delay: Duration,

        /// If set to true, randomness will be added to the delay on each retry attempt.
        jitter: bool,

        /// If set, limits the delay between retries.
        max_delay: Option<Duration>,
    },
}

impl Default for RetryPolicy {
    #[inline]
    fn default() -> Self {
        Self::new_without_delay(0)
    }
}

impl RetryPolicy {
    /// Create new policy with no delay between retries.
    pub fn new_without_delay(count: u32) -> Self {
        Self::Fixed {
            count,
            delay: Duration::ZERO,
            jitter: false,
        }
    }

    /// Returns the number of retries.
    pub fn count(&self) -> u32 {
        match self {
            Self::Fixed { count, .. } | Self::Exponential { count, .. } => *count,
        }
    }
}

/// Controls whether a flaky test is treated as a pass or a failure.
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(test, derive(test_strategy::Arbitrary))]
pub enum FlakyResult {
    /// The test is marked as failed.
    Fail,

    /// The test is marked as passed.
    #[default]
    Pass,
}

impl FlakyResult {
    /// Returns a message describing a flaky failure, or `None` if the result is
    /// `Pass`.
    ///
    /// Used by both JUnit and Chrome trace output to produce a consistent
    /// message.
    pub fn fail_message(self, attempt: u32, total_attempts: u32) -> Option<String> {
        match self {
            Self::Fail => Some(format!(
                "test passed on attempt {attempt}/{total_attempts} \
                 but is configured to fail when flaky",
            )),
            Self::Pass => None,
        }
    }
}

/// Serde-compatible intermediate type for the `retries` config field. After
/// deserialization, this is converted into a `RetryPolicy`.
#[derive(Debug, Copy, Clone, Deserialize)]
#[serde(tag = "backoff", rename_all = "kebab-case", deny_unknown_fields)]
enum RetryPolicySerde {
    #[serde(rename_all = "kebab-case")]
    Fixed {
        count: u32,
        #[serde(default, with = "humantime_serde")]
        delay: Duration,
        #[serde(default)]
        jitter: bool,
    },
    #[serde(rename_all = "kebab-case")]
    Exponential {
        count: u32,
        #[serde(with = "humantime_serde")]
        delay: Duration,
        #[serde(default)]
        jitter: bool,
        #[serde(default, with = "humantime_serde")]
        max_delay: Option<Duration>,
    },
}

impl RetryPolicySerde {
    fn into_policy(self) -> RetryPolicy {
        match self {
            RetryPolicySerde::Fixed {
                count,
                delay,
                jitter,
            } => RetryPolicy::Fixed {
                count,
                delay,
                jitter,
            },
            RetryPolicySerde::Exponential {
                count,
                delay,
                jitter,
                max_delay,
            } => RetryPolicy::Exponential {
                count,
                delay,
                jitter,
                max_delay,
            },
        }
    }
}

pub(in crate::config) fn deserialize_retry_policy<'de, D>(
    deserializer: D,
) -> Result<Option<RetryPolicy>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    struct V;

    impl<'de2> serde::de::Visitor<'de2> for V {
        type Value = Option<RetryPolicy>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            write!(
                formatter,
                "a table ({{ backoff = \"fixed\", count = 5 }}) or a number (5)"
            )
        }

        // Note that TOML uses i64, not u64.
        fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            match v.cmp(&0) {
                Ordering::Greater | Ordering::Equal => {
                    let v = u32::try_from(v).map_err(|_| {
                        serde::de::Error::invalid_value(
                            serde::de::Unexpected::Signed(v),
                            &"a positive u32",
                        )
                    })?;
                    Ok(Some(RetryPolicy::new_without_delay(v)))
                }
                Ordering::Less => Err(serde::de::Error::invalid_value(
                    serde::de::Unexpected::Signed(v),
                    &self,
                )),
            }
        }

        fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
        where
            A: serde::de::MapAccess<'de2>,
        {
            RetryPolicySerde::deserialize(serde::de::value::MapAccessDeserializer::new(map))
                .map(|s| Some(s.into_policy()))
        }
    }

    // Post-deserialize validation of retry policy.
    let policy = deserializer.deserialize_any(V)?;
    match &policy {
        Some(RetryPolicy::Fixed {
            count: _,
            delay,
            jitter,
        }) => {
            // Jitter can't be specified if delay is 0.
            if delay.is_zero() && *jitter {
                return Err(serde::de::Error::custom(
                    "`jitter` cannot be true if `delay` isn't specified or is zero",
                ));
            }
        }
        Some(RetryPolicy::Exponential {
            count,
            delay,
            jitter: _,
            max_delay,
        }) => {
            // Count can't be zero.
            if *count == 0 {
                return Err(serde::de::Error::custom(
                    "`count` cannot be zero with exponential backoff",
                ));
            }
            // Delay can't be zero.
            if delay.is_zero() {
                return Err(serde::de::Error::custom(
                    "`delay` cannot be zero with exponential backoff",
                ));
            }
            // Max delay, if specified, can't be zero.
            if max_delay.is_some_and(|f| f.is_zero()) {
                return Err(serde::de::Error::custom(
                    "`max-delay` cannot be zero with exponential backoff",
                ));
            }
            // Max delay can't be less than delay.
            if max_delay.is_some_and(|max_delay| max_delay < *delay) {
                return Err(serde::de::Error::custom(
                    "`max-delay` cannot be less than delay with exponential backoff",
                ));
            }
        }
        None => {}
    }

    Ok(policy)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        config::{core::NextestConfig, utils::test_helpers::*},
        errors::ConfigParseErrorKind,
        run_mode::NextestRunMode,
    };
    use camino_tempfile::tempdir;
    use config::ConfigError;
    use guppy::graph::cargo::BuildPlatform;
    use indoc::indoc;
    use nextest_filtering::{ParseContext, TestQuery};
    use nextest_metadata::TestCaseName;
    use test_case::test_case;

    #[test]
    fn parse_retries_valid() {
        let config_contents = indoc! {r#"
            [profile.default]
            retries = { backoff = "fixed", count = 3 }

            [profile.no-retries]
            retries = 0

            [profile.fixed-with-delay]
            retries = { backoff = "fixed", count = 3, delay = "1s" }

            [profile.exp]
            retries = { backoff = "exponential", count = 4, delay = "2s" }

            [profile.exp-with-max-delay]
            retries = { backoff = "exponential", count = 5, delay = "3s", max-delay = "10s" }

            [profile.exp-with-max-delay-and-jitter]
            retries = { backoff = "exponential", count = 6, delay = "4s", max-delay = "1m", jitter = true }

            [profile.with-flaky-result-fail]
            retries = { backoff = "fixed", count = 2 }
            flaky-result = "fail"

            [profile.with-flaky-result-pass]
            retries = { backoff = "fixed", count = 2 }
            flaky-result = "pass"

            [profile.exp-with-flaky-result-fail]
            retries = { backoff = "exponential", count = 3, delay = "1s" }
            flaky-result = "fail"

            [profile.flaky-result-only]
            flaky-result = "fail"
        "#};

        let workspace_dir = tempdir().unwrap();

        let graph = temp_workspace(&workspace_dir, config_contents);
        let pcx = ParseContext::new(&graph);

        let config = NextestConfig::from_sources(
            graph.workspace().root(),
            &pcx,
            None,
            [],
            &Default::default(),
        )
        .expect("config is valid");

        let default_profile = config
            .profile("default")
            .expect("default profile exists")
            .apply_build_platforms(&build_platforms());
        assert_eq!(
            default_profile.retries(),
            RetryPolicy::Fixed {
                count: 3,
                delay: Duration::ZERO,
                jitter: false,
            },
            "default retries matches"
        );
        assert_eq!(
            default_profile.flaky_result(),
            FlakyResult::Pass,
            "default flaky_result matches"
        );

        assert_eq!(
            config
                .profile("no-retries")
                .expect("profile exists")
                .apply_build_platforms(&build_platforms())
                .retries(),
            RetryPolicy::new_without_delay(0),
            "no-retries retries matches"
        );

        assert_eq!(
            config
                .profile("fixed-with-delay")
                .expect("profile exists")
                .apply_build_platforms(&build_platforms())
                .retries(),
            RetryPolicy::Fixed {
                count: 3,
                delay: Duration::from_secs(1),
                jitter: false,
            },
            "fixed-with-delay retries matches"
        );

        assert_eq!(
            config
                .profile("exp")
                .expect("profile exists")
                .apply_build_platforms(&build_platforms())
                .retries(),
            RetryPolicy::Exponential {
                count: 4,
                delay: Duration::from_secs(2),
                jitter: false,
                max_delay: None,
            },
            "exp retries matches"
        );

        assert_eq!(
            config
                .profile("exp-with-max-delay")
                .expect("profile exists")
                .apply_build_platforms(&build_platforms())
                .retries(),
            RetryPolicy::Exponential {
                count: 5,
                delay: Duration::from_secs(3),
                jitter: false,
                max_delay: Some(Duration::from_secs(10)),
            },
            "exp-with-max-delay retries matches"
        );

        assert_eq!(
            config
                .profile("exp-with-max-delay-and-jitter")
                .expect("profile exists")
                .apply_build_platforms(&build_platforms())
                .retries(),
            RetryPolicy::Exponential {
                count: 6,
                delay: Duration::from_secs(4),
                jitter: true,
                max_delay: Some(Duration::from_secs(60)),
            },
            "exp-with-max-delay-and-jitter retries matches"
        );

        let with_flaky_result_fail = config
            .profile("with-flaky-result-fail")
            .expect("profile exists")
            .apply_build_platforms(&build_platforms());
        assert_eq!(
            with_flaky_result_fail.retries(),
            RetryPolicy::new_without_delay(2),
            "with-flaky-result-fail retries matches"
        );
        assert_eq!(
            with_flaky_result_fail.flaky_result(),
            FlakyResult::Fail,
            "with-flaky-result-fail flaky_result matches"
        );

        let with_flaky_result_pass = config
            .profile("with-flaky-result-pass")
            .expect("profile exists")
            .apply_build_platforms(&build_platforms());
        assert_eq!(
            with_flaky_result_pass.retries(),
            RetryPolicy::new_without_delay(2),
            "with-flaky-result-pass retries matches"
        );
        assert_eq!(
            with_flaky_result_pass.flaky_result(),
            FlakyResult::Pass,
            "with-flaky-result-pass flaky_result matches"
        );

        let exp_with_flaky_result_fail = config
            .profile("exp-with-flaky-result-fail")
            .expect("profile exists")
            .apply_build_platforms(&build_platforms());
        assert_eq!(
            exp_with_flaky_result_fail.retries(),
            RetryPolicy::Exponential {
                count: 3,
                delay: Duration::from_secs(1),
                jitter: false,
                max_delay: None,
            },
            "exp-with-flaky-result-fail retries matches"
        );
        assert_eq!(
            exp_with_flaky_result_fail.flaky_result(),
            FlakyResult::Fail,
            "exp-with-flaky-result-fail flaky_result matches"
        );

        // flaky-result-only: retries inherited from default (count=3), flaky
        // result set to fail.
        let flaky_result_only = config
            .profile("flaky-result-only")
            .expect("profile exists")
            .apply_build_platforms(&build_platforms());
        assert_eq!(
            flaky_result_only.retries(),
            RetryPolicy::Fixed {
                count: 3,
                delay: Duration::ZERO,
                jitter: false,
            },
            "flaky-result-only retries inherited from default"
        );
        assert_eq!(
            flaky_result_only.flaky_result(),
            FlakyResult::Fail,
            "flaky-result-only flaky_result matches"
        );
    }

    #[test_case(
        indoc!{r#"
            [profile.default]
            retries = { backoff = "foo" }
        "#},
        ConfigErrorKind::Message,
        "unknown variant `foo`, expected `fixed` or `exponential`"
        ; "invalid value for backoff")]
    #[test_case(
        indoc!{r#"
            [profile.default]
            retries = { backoff = "fixed" }
        "#},
        ConfigErrorKind::NotFound,
        "profile.default.retries.count"
        ; "fixed specified without count")]
    #[test_case(
        indoc!{r#"
            [profile.default]
            retries = { backoff = "fixed", count = 1, delay = "foobar" }
        "#},
        ConfigErrorKind::Message,
        "invalid value: string \"foobar\", expected a duration"
        ; "delay is not a valid duration")]
    #[test_case(
        indoc!{r#"
            [profile.default]
            retries = { backoff = "fixed", count = 1, jitter = true }
        "#},
        ConfigErrorKind::Message,
        "`jitter` cannot be true if `delay` isn't specified or is zero"
        ; "jitter specified without delay")]
    #[test_case(
        indoc!{r#"
            [profile.default]
            retries = { backoff = "fixed", count = 1, max-delay = "10s" }
        "#},
        ConfigErrorKind::Message,
        "unknown field `max-delay`, expected one of `count`, `delay`, `jitter`"
        ; "max-delay is incompatible with fixed backoff")]
    #[test_case(
        indoc!{r#"
            [profile.default]
            retries = { backoff = "exponential", count = 1 }
        "#},
        ConfigErrorKind::NotFound,
        "profile.default.retries.delay"
        ; "exponential backoff must specify delay")]
    #[test_case(
        indoc!{r#"
            [profile.default]
            retries = { backoff = "exponential", delay = "1s" }
        "#},
        ConfigErrorKind::NotFound,
        "profile.default.retries.count"
        ; "exponential backoff must specify count")]
    #[test_case(
        indoc!{r#"
            [profile.default]
            retries = { backoff = "exponential", count = 0, delay = "1s" }
        "#},
        ConfigErrorKind::Message,
        "`count` cannot be zero with exponential backoff"
        ; "exponential backoff must have a non-zero count")]
    #[test_case(
        indoc!{r#"
            [profile.default]
            retries = { backoff = "exponential", count = 1, delay = "0s" }
        "#},
        ConfigErrorKind::Message,
        "`delay` cannot be zero with exponential backoff"
        ; "exponential backoff must have a non-zero delay")]
    #[test_case(
        indoc!{r#"
            [profile.default]
            retries = { backoff = "exponential", count = 1, delay = "1s", max-delay = "0s" }
        "#},
        ConfigErrorKind::Message,
        "`max-delay` cannot be zero with exponential backoff"
        ; "exponential backoff must have a non-zero max delay")]
    #[test_case(
        indoc!{r#"
            [profile.default]
            retries = { backoff = "exponential", count = 1, delay = "4s", max-delay = "2s", jitter = true }
        "#},
        ConfigErrorKind::Message,
        "`max-delay` cannot be less than delay"
        ; "max-delay greater than delay")]
    #[test_case(
        indoc!{r#"
            [profile.default]
            flaky-result = "unknown"
        "#},
        ConfigErrorKind::Message,
        "enum FlakyResult does not have variant constructor unknown"
        ; "invalid flaky-result value")]
    fn parse_retries_invalid(
        config_contents: &str,
        expected_kind: ConfigErrorKind,
        expected_message: &str,
    ) {
        let workspace_dir = tempdir().unwrap();

        let graph = temp_workspace(&workspace_dir, config_contents);
        let pcx = ParseContext::new(&graph);

        let config_err = NextestConfig::from_sources(
            graph.workspace().root(),
            &pcx,
            None,
            [],
            &Default::default(),
        )
        .expect_err("config expected to be invalid");

        let message = match config_err.kind() {
            ConfigParseErrorKind::DeserializeError(path_error) => {
                match (path_error.inner(), expected_kind) {
                    (ConfigError::Message(message), ConfigErrorKind::Message) => message,
                    (ConfigError::NotFound(message), ConfigErrorKind::NotFound) => message,
                    (other, expected) => {
                        panic!(
                            "for config error {config_err:?}, expected \
                             ConfigErrorKind::{expected:?} for inner error {other:?}"
                        );
                    }
                }
            }
            other => {
                panic!(
                    "for config error {other:?}, expected ConfigParseErrorKind::DeserializeError"
                );
            }
        };

        assert!(
            message.contains(expected_message),
            "expected message \"{message}\" to contain \"{expected_message}\""
        );
    }

    #[test_case(
        indoc! {r#"
            [[profile.default.overrides]]
            filter = "test(=my_test)"
            retries = 2

            [profile.ci]
        "#},
        BuildPlatform::Target,
        RetryPolicy::new_without_delay(2)

        ; "my_test matches exactly"
    )]
    #[test_case(
        indoc! {r#"
            [[profile.default.overrides]]
            filter = "!test(=my_test)"
            retries = 2

            [profile.ci]
        "#},
        BuildPlatform::Target,
        RetryPolicy::new_without_delay(0)

        ; "not match"
    )]
    #[test_case(
        indoc! {r#"
            [[profile.default.overrides]]
            filter = "test(=my_test)"

            [profile.ci]
        "#},
        BuildPlatform::Target,
        RetryPolicy::new_without_delay(0)

        ; "no retries specified"
    )]
    #[test_case(
        indoc! {r#"
            [[profile.default.overrides]]
            filter = "test(test)"
            retries = 2

            [[profile.default.overrides]]
            filter = "test(=my_test)"
            retries = 3

            [profile.ci]
        "#},
        BuildPlatform::Target,
        RetryPolicy::new_without_delay(2)

        ; "earlier configs override later ones"
    )]
    #[test_case(
        indoc! {r#"
            [[profile.default.overrides]]
            filter = "test(test)"
            retries = 2

            [profile.ci]

            [[profile.ci.overrides]]
            filter = "test(=my_test)"
            retries = 3
        "#},
        BuildPlatform::Target,
        RetryPolicy::new_without_delay(3)

        ; "profile-specific configs override default ones"
    )]
    #[test_case(
        indoc! {r#"
            [[profile.default.overrides]]
            filter = "(!package(test-package)) and test(test)"
            retries = 2

            [profile.ci]

            [[profile.ci.overrides]]
            filter = "!test(=my_test_2)"
            retries = 3
        "#},
        BuildPlatform::Target,
        RetryPolicy::new_without_delay(3)

        ; "no overrides match my_test exactly"
    )]
    #[test_case(
        indoc! {r#"
            [[profile.default.overrides]]
            platform = "x86_64-unknown-linux-gnu"
            filter = "test(test)"
            retries = 2

            [[profile.default.overrides]]
            filter = "test(=my_test)"
            retries = 3

            [profile.ci]
        "#},
        BuildPlatform::Host,
        RetryPolicy::new_without_delay(2)

        ; "earlier config applied because it matches host triple"
    )]
    #[test_case(
        indoc! {r#"
            [[profile.default.overrides]]
            platform = "aarch64-apple-darwin"
            filter = "test(test)"
            retries = 2

            [[profile.default.overrides]]
            filter = "test(=my_test)"
            retries = 3

            [profile.ci]
        "#},
        BuildPlatform::Host,
        RetryPolicy::new_without_delay(3)

        ; "earlier config ignored because it doesn't match host triple"
    )]
    #[test_case(
        indoc! {r#"
            [[profile.default.overrides]]
            platform = "aarch64-apple-darwin"
            filter = "test(test)"
            retries = 2

            [[profile.default.overrides]]
            filter = "test(=my_test)"
            retries = 3

            [profile.ci]
        "#},
        BuildPlatform::Target,
        RetryPolicy::new_without_delay(2)

        ; "earlier config applied because it matches target triple"
    )]
    #[test_case(
        indoc! {r#"
            [[profile.default.overrides]]
            platform = "x86_64-unknown-linux-gnu"
            filter = "test(test)"
            retries = 2

            [[profile.default.overrides]]
            filter = "test(=my_test)"
            retries = 3

            [profile.ci]
        "#},
        BuildPlatform::Target,
        RetryPolicy::new_without_delay(3)

        ; "earlier config ignored because it doesn't match target triple"
    )]
    #[test_case(
        indoc! {r#"
            [[profile.default.overrides]]
            platform = 'cfg(target_os = "macos")'
            filter = "test(test)"
            retries = 2

            [[profile.default.overrides]]
            filter = "test(=my_test)"
            retries = 3

            [profile.ci]
        "#},
        BuildPlatform::Target,
        RetryPolicy::new_without_delay(2)

        ; "earlier config applied because it matches target cfg expr"
    )]
    #[test_case(
        indoc! {r#"
            [[profile.default.overrides]]
            platform = 'cfg(target_arch = "x86_64")'
            filter = "test(test)"
            retries = 2

            [[profile.default.overrides]]
            filter = "test(=my_test)"
            retries = 3

            [profile.ci]
        "#},
        BuildPlatform::Target,
        RetryPolicy::new_without_delay(3)

        ; "earlier config ignored because it doesn't match target cfg expr"
    )]
    fn overrides_retries(
        config_contents: &str,
        build_platform: BuildPlatform,
        retries: RetryPolicy,
    ) {
        let workspace_dir = tempdir().unwrap();

        let graph = temp_workspace(&workspace_dir, config_contents);
        let package_id = graph.workspace().iter().next().unwrap().id();
        let pcx = ParseContext::new(&graph);

        let config = NextestConfig::from_sources(
            graph.workspace().root(),
            &pcx,
            None,
            &[][..],
            &Default::default(),
        )
        .unwrap();
        let binary_query = binary_query(&graph, package_id, "lib", "my-binary", build_platform);
        let test_name = TestCaseName::new("my_test");
        let query = TestQuery {
            binary_query: binary_query.to_query(),
            test_name: &test_name,
        };
        let profile = config
            .profile("ci")
            .expect("ci profile is defined")
            .apply_build_platforms(&build_platforms());
        let settings_for = profile.settings_for(NextestRunMode::Test, &query);
        assert_eq!(
            settings_for.retries(),
            retries,
            "actual retries don't match expected retries"
        );
    }

    #[test]
    fn overrides_flaky_result() {
        let config_contents = indoc! {r#"
            [[profile.default.overrides]]
            filter = "test(=my_test)"
            retries = { backoff = "fixed", count = 3 }
            flaky-result = "fail"

            [[profile.default.overrides]]
            filter = "test(=other_test)"
            retries = 2

            [profile.ci]
        "#};
        let workspace_dir = tempdir().unwrap();

        let graph = temp_workspace(&workspace_dir, config_contents);
        let package_id = graph.workspace().iter().next().unwrap().id();
        let pcx = ParseContext::new(&graph);

        let config = NextestConfig::from_sources(
            graph.workspace().root(),
            &pcx,
            None,
            &[][..],
            &Default::default(),
        )
        .unwrap();

        let profile = config
            .profile("ci")
            .expect("ci profile is defined")
            .apply_build_platforms(&build_platforms());

        // my_test has flaky-result = "fail" set explicitly.
        let binary_query = binary_query(
            &graph,
            package_id,
            "lib",
            "my-binary",
            BuildPlatform::Target,
        );
        let test_name = TestCaseName::new("my_test");
        let query = TestQuery {
            binary_query: binary_query.to_query(),
            test_name: &test_name,
        };
        let settings = profile.settings_for(NextestRunMode::Test, &query);
        assert_eq!(
            settings.flaky_result(),
            FlakyResult::Fail,
            "my_test flaky_result is fail"
        );

        // other_test uses shorthand retries = 2, which does not set
        // flaky-result.
        let test_name = TestCaseName::new("other_test");
        let query = TestQuery {
            binary_query: binary_query.to_query(),
            test_name: &test_name,
        };
        let settings = profile.settings_for(NextestRunMode::Test, &query);
        assert_eq!(
            settings.flaky_result(),
            FlakyResult::Pass,
            "other_test flaky_result defaults to pass"
        );
    }

    /// Test that retries and flaky_result resolve independently through the
    /// override chain. An override that sets only retries should not override
    /// a flaky_result set by a later (lower-priority) override.
    #[test]
    fn overrides_flaky_result_independent_resolution() {
        let config_contents = indoc! {r#"
            # Override 1: sets retries count only.
            [[profile.default.overrides]]
            filter = "test(=my_test)"
            retries = 5

            # Override 2: sets retries with flaky-result = "fail".
            [[profile.default.overrides]]
            filter = "all()"
            retries = { backoff = "fixed", count = 2 }
            flaky-result = "fail"

            [profile.ci]
        "#};
        let workspace_dir = tempdir().unwrap();

        let graph = temp_workspace(&workspace_dir, config_contents);
        let package_id = graph.workspace().iter().next().unwrap().id();
        let pcx = ParseContext::new(&graph);

        let config = NextestConfig::from_sources(
            graph.workspace().root(),
            &pcx,
            None,
            &[][..],
            &Default::default(),
        )
        .unwrap();

        let profile = config
            .profile("ci")
            .expect("ci profile is defined")
            .apply_build_platforms(&build_platforms());

        let binary_query = binary_query(
            &graph,
            package_id,
            "lib",
            "my-binary",
            BuildPlatform::Target,
        );
        let test_name = TestCaseName::new("my_test");
        let query = TestQuery {
            binary_query: binary_query.to_query(),
            test_name: &test_name,
        };
        let settings = profile.settings_for(NextestRunMode::Test, &query);

        // Retries count comes from override 1 (higher priority).
        assert_eq!(
            settings.retries(),
            RetryPolicy::new_without_delay(5),
            "retries count from first override"
        );
        // Flaky result comes from override 2 (first override didn't set it).
        assert_eq!(
            settings.flaky_result(),
            FlakyResult::Fail,
            "flaky_result from second override"
        );
    }

    /// Test that `flaky-result = "fail"` (without retries) sets only the flaky
    /// result, with the retry policy inherited from a lower-priority override.
    #[test]
    fn overrides_flaky_result_only() {
        let config_contents = indoc! {r#"
            # Override 1: sets only flaky-result, no retry policy.
            [[profile.default.overrides]]
            filter = "test(=my_test)"
            flaky-result = "fail"

            # Override 2: sets retries count for all tests.
            [[profile.default.overrides]]
            filter = "all()"
            retries = 3

            [profile.ci]
        "#};
        let workspace_dir = tempdir().unwrap();

        let graph = temp_workspace(&workspace_dir, config_contents);
        let package_id = graph.workspace().iter().next().unwrap().id();
        let pcx = ParseContext::new(&graph);

        let config = NextestConfig::from_sources(
            graph.workspace().root(),
            &pcx,
            None,
            &[][..],
            &Default::default(),
        )
        .unwrap();

        let profile = config
            .profile("ci")
            .expect("ci profile is defined")
            .apply_build_platforms(&build_platforms());

        let binary_query = binary_query(
            &graph,
            package_id,
            "lib",
            "my-binary",
            BuildPlatform::Target,
        );
        let test_name = TestCaseName::new("my_test");
        let query = TestQuery {
            binary_query: binary_query.to_query(),
            test_name: &test_name,
        };
        let settings = profile.settings_for(NextestRunMode::Test, &query);

        // Retries come from override 2 (override 1 didn't set a policy).
        assert_eq!(
            settings.retries(),
            RetryPolicy::new_without_delay(3),
            "retries from second override"
        );
        // Flaky result comes from override 1.
        assert_eq!(
            settings.flaky_result(),
            FlakyResult::Fail,
            "flaky_result from first override"
        );

        // For a test that doesn't match override 1, flaky_result defaults to
        // pass.
        let test_name = TestCaseName::new("other_test");
        let query = TestQuery {
            binary_query: binary_query.to_query(),
            test_name: &test_name,
        };
        let settings = profile.settings_for(NextestRunMode::Test, &query);
        assert_eq!(
            settings.retries(),
            RetryPolicy::new_without_delay(3),
            "other_test retries from second override"
        );
        assert_eq!(
            settings.flaky_result(),
            FlakyResult::Pass,
            "other_test flaky_result defaults to pass"
        );
    }
}