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
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

use crate::time::far_future_duration;
use serde::{Deserialize, Serialize, de::IntoDeserializer};
use std::{fmt, num::NonZeroUsize, time::Duration};

/// Type for the slow-timeout config key.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub struct SlowTimeout {
    #[serde(with = "humantime_serde")]
    pub(crate) period: Duration,
    #[serde(default)]
    pub(crate) terminate_after: Option<NonZeroUsize>,
    #[serde(with = "humantime_serde", default = "default_grace_period")]
    pub(crate) grace_period: Duration,
    #[serde(default)]
    pub(crate) on_timeout: SlowTimeoutResult,
}

impl SlowTimeout {
    /// A reasonable value for "maximum slow timeout".
    pub(crate) const VERY_LARGE: Self = Self {
        // See far_future() in pausable_sleep.rs for why this is roughly 30 years.
        period: far_future_duration(),
        terminate_after: None,
        grace_period: Duration::from_secs(10),
        on_timeout: SlowTimeoutResult::Fail,
    };
}

fn default_grace_period() -> Duration {
    Duration::from_secs(10)
}

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

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

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            write!(
                formatter,
                "a table ({{ period = \"60s\", terminate-after = 2 }}) or a string (\"60s\")"
            )
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            if v.is_empty() {
                Ok(None)
            } else {
                let period = humantime_serde::deserialize(v.into_deserializer())?;
                Ok(Some(SlowTimeout {
                    period,
                    terminate_after: None,
                    grace_period: default_grace_period(),
                    on_timeout: SlowTimeoutResult::Fail,
                }))
            }
        }

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

    deserializer.deserialize_any(V)
}

/// The result of controlling slow timeout behavior.
///
/// In most situations a timed out test should be marked failing. However, there are certain
/// classes of tests which are expected to run indefinitely long, like fuzzing, which explores a
/// huge state space. For these tests it's nice to be able to treat a timeout as a success since
/// they generally check for invariants and other properties of the code under test during their
/// execution. A timeout in this context doesn't mean that there are no failing inputs, it just
/// means that they weren't found up until that moment, which is still valuable information.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Default, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(test, derive(test_strategy::Arbitrary))]
pub enum SlowTimeoutResult {
    #[default]
    /// The test is marked as failed.
    Fail,

    /// The test is marked as passed.
    Pass,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        config::{core::NextestConfig, utils::test_helpers::*},
        run_mode::NextestRunMode,
    };
    use camino_tempfile::tempdir;
    use indoc::indoc;
    use nextest_filtering::ParseContext;
    use test_case::test_case;

    #[test_case(
        "",
        Ok(SlowTimeout {
            period: Duration::from_secs(60),
            terminate_after: None,
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        }),
        None
        ; "empty config is expected to use the hardcoded values"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            slow-timeout = "30s"
        "#},
        Ok(SlowTimeout {
            period: Duration::from_secs(30),
            terminate_after: None,
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        }),
        None
        ; "overrides the default profile"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            slow-timeout = "30s"

            [profile.ci]
            slow-timeout = { period = "60s", terminate-after = 3 }
        "#},
        Ok(SlowTimeout {
            period: Duration::from_secs(30),
            terminate_after: None,
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        }),
        Some(SlowTimeout {
            period: Duration::from_secs(60),
            terminate_after: Some(NonZeroUsize::new(3).unwrap()),
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        })
        ; "adds a custom profile 'ci'"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            slow-timeout = { period = "60s", terminate-after = 3 }

            [profile.ci]
            slow-timeout = "30s"
        "#},
        Ok(SlowTimeout {
            period: Duration::from_secs(60),
            terminate_after: Some(NonZeroUsize::new(3).unwrap()),
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        }),
        Some(SlowTimeout {
            period: Duration::from_secs(30),
            terminate_after: None,
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        })
        ; "ci profile uses string notation"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            slow-timeout = { period = "60s", terminate-after = 3, grace-period = "1s" }

            [profile.ci]
            slow-timeout = "30s"
        "#},
        Ok(SlowTimeout {
            period: Duration::from_secs(60),
            terminate_after: Some(NonZeroUsize::new(3).unwrap()),
            grace_period: Duration::from_secs(1),
            on_timeout: SlowTimeoutResult::Fail,
        }),
        Some(SlowTimeout {
            period: Duration::from_secs(30),
            terminate_after: None,
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        })
        ; "timeout grace period"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            slow-timeout = { period = "60s" }
        "#},
        Ok(SlowTimeout {
            period: Duration::from_secs(60),
            terminate_after: None,
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        }),
        None
        ; "partial table"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            slow-timeout = { period = "60s", terminate-after = 0 }
        "#},
        Err("original: invalid value: integer `0`, expected a nonzero usize"),
        None
        ; "zero terminate-after should fail"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            slow-timeout = { period = "60s", on-timeout = "pass" }
        "#},
        Ok(SlowTimeout {
            period: Duration::from_secs(60),
            terminate_after: None,
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Pass,
        }),
        None
        ; "timeout result success"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            slow-timeout = { period = "60s", on-timeout = "fail" }
        "#},
        Ok(SlowTimeout {
            period: Duration::from_secs(60),
            terminate_after: None,
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        }),
        None
        ; "timeout result failure"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            slow-timeout = { period = "60s", on-timeout = "pass" }

            [profile.ci]
            slow-timeout = { period = "30s", on-timeout = "fail" }
        "#},
        Ok(SlowTimeout {
            period: Duration::from_secs(60),
            terminate_after: None,
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Pass,
        }),
        Some(SlowTimeout {
            period: Duration::from_secs(30),
            terminate_after: None,
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        })
        ; "override on-timeout option"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            slow-timeout = "60s"

            [profile.ci]
            slow-timeout = { terminate-after = 3 }
        "#},
        Err("original: missing configuration field \"profile.ci.slow-timeout.period\""),
        None

        ; "partial slow-timeout table should error"
    )]
    fn slowtimeout_adheres_to_hierarchy(
        config_contents: &str,
        expected_default: Result<SlowTimeout, &str>,
        maybe_expected_ci: Option<SlowTimeout>,
    ) {
        let workspace_dir = tempdir().unwrap();

        let graph = temp_workspace(&workspace_dir, config_contents);

        let pcx = ParseContext::new(&graph);

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

        match expected_default {
            Ok(expected_default) => {
                let nextest_config = nextest_config_result.expect("config file should parse");

                assert_eq!(
                    nextest_config
                        .profile("default")
                        .expect("default profile should exist")
                        .apply_build_platforms(&build_platforms())
                        .slow_timeout(NextestRunMode::Test),
                    expected_default,
                );

                if let Some(expected_ci) = maybe_expected_ci {
                    assert_eq!(
                        nextest_config
                            .profile("ci")
                            .expect("ci profile should exist")
                            .apply_build_platforms(&build_platforms())
                            .slow_timeout(NextestRunMode::Test),
                        expected_ci,
                    );
                }
            }

            Err(expected_err_str) => {
                let err_str = format!("{:?}", nextest_config_result.unwrap_err());

                assert!(
                    err_str.contains(expected_err_str),
                    "expected error string not found: {err_str}",
                )
            }
        }
    }

    // Default test slow-timeout is 60 seconds.
    const DEFAULT_TEST_SLOW_TIMEOUT: SlowTimeout = SlowTimeout {
        period: Duration::from_secs(60),
        terminate_after: None,
        grace_period: Duration::from_secs(10),
        on_timeout: SlowTimeoutResult::Fail,
    };

    /// Expected bench timeout: either a specific value or "very large" (default).
    #[derive(Debug)]
    enum ExpectedBenchTimeout {
        /// Expect a specific timeout value.
        Exact(SlowTimeout),
        /// Expect the default very large timeout (>= VERY_LARGE, accounting for
        /// leap years in humantime parsing).
        VeryLarge,
    }

    #[test_case(
        "",
        DEFAULT_TEST_SLOW_TIMEOUT,
        ExpectedBenchTimeout::VeryLarge
        ; "empty config uses defaults for both modes"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            slow-timeout = { period = "10s", terminate-after = 2 }
        "#},
        SlowTimeout {
            period: Duration::from_secs(10),
            terminate_after: Some(NonZeroUsize::new(2).unwrap()),
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        },
        // bench.slow-timeout should still be 30 years (default).
        ExpectedBenchTimeout::VeryLarge
        ; "slow-timeout does not affect bench.slow-timeout"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            bench.slow-timeout = { period = "20s", terminate-after = 3 }
        "#},
        // slow-timeout should still be 60s (default).
        DEFAULT_TEST_SLOW_TIMEOUT,
        ExpectedBenchTimeout::Exact(SlowTimeout {
            period: Duration::from_secs(20),
            terminate_after: Some(NonZeroUsize::new(3).unwrap()),
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        })
        ; "bench.slow-timeout does not affect slow-timeout"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            slow-timeout = { period = "10s", terminate-after = 2 }
            bench.slow-timeout = { period = "20s", terminate-after = 3 }
        "#},
        SlowTimeout {
            period: Duration::from_secs(10),
            terminate_after: Some(NonZeroUsize::new(2).unwrap()),
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        },
        ExpectedBenchTimeout::Exact(SlowTimeout {
            period: Duration::from_secs(20),
            terminate_after: Some(NonZeroUsize::new(3).unwrap()),
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        })
        ; "both slow-timeout and bench.slow-timeout can be set independently"
    )]
    #[test_case(
        indoc! {r#"
            [profile.default]
            bench.slow-timeout = "30s"
        "#},
        DEFAULT_TEST_SLOW_TIMEOUT,
        ExpectedBenchTimeout::Exact(SlowTimeout {
            period: Duration::from_secs(30),
            terminate_after: None,
            grace_period: Duration::from_secs(10),
            on_timeout: SlowTimeoutResult::Fail,
        })
        ; "bench.slow-timeout string notation"
    )]
    fn bench_slowtimeout_is_independent(
        config_contents: &str,
        expected_test_timeout: SlowTimeout,
        expected_bench_timeout: ExpectedBenchTimeout,
    ) {
        let workspace_dir = tempdir().unwrap();

        let graph = temp_workspace(&workspace_dir, config_contents);

        let pcx = ParseContext::new(&graph);

        let nextest_config = NextestConfig::from_sources(
            graph.workspace().root(),
            &pcx,
            None,
            &[][..],
            &Default::default(),
        )
        .expect("config file should parse");

        let profile = nextest_config
            .profile("default")
            .expect("default profile should exist")
            .apply_build_platforms(&build_platforms());

        assert_eq!(
            profile.slow_timeout(NextestRunMode::Test),
            expected_test_timeout,
            "Test mode slow-timeout mismatch"
        );

        let actual_bench_timeout = profile.slow_timeout(NextestRunMode::Benchmark);
        match expected_bench_timeout {
            ExpectedBenchTimeout::Exact(expected) => {
                assert_eq!(
                    actual_bench_timeout, expected,
                    "Benchmark mode slow-timeout mismatch"
                );
            }
            ExpectedBenchTimeout::VeryLarge => {
                // The default is "30y" which humantime parses accounting for
                // leap years, so it is slightly larger than VERY_LARGE.
                assert!(
                    actual_bench_timeout.period >= SlowTimeout::VERY_LARGE.period,
                    "Benchmark mode slow-timeout should be >= VERY_LARGE, got {:?}",
                    actual_bench_timeout.period
                );
                assert_eq!(
                    actual_bench_timeout.terminate_after, None,
                    "Benchmark mode terminate_after should be None"
                );
            }
        }
    }
}