kitest 0.5.0

A composable test harness toolkit with room to fly.
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
use std::{marker::PhantomData, ops::ControlFlow, sync::Arc, time::Instant};

use crate::{
    GroupedTestReport, TestListReport,
    filter::{FilteredTests, TestFilter},
    formatter::*,
    group::{TestGroupRunner, TestGrouper, TestGroups},
    harness::FmtErrors,
    ignore::{IgnoreStatus, TestIgnore},
    outcome::TestStatus,
    panic::TestPanicHandler,
    runner::TestRunner,
    test::Test,
    util::IteratorExt,
};

/// A test harness that executes tests in groups.
///
/// A [`GroupedTestHarness`] is created by promoting a [`TestHarness`](super::TestHarness) via
/// [`TestHarness::with_grouper`](super::TestHarness::with_grouper).
/// The promoted harness keeps the same overall execution model, but adds an explicit grouping
/// step before running tests.
///
/// Groups are executed in a similar way to how `TestHarness` executes individual tests:
/// tests are filtered and ignored the same way, each test is executed through the same panic
/// handling and runner logic, and the formatter receives the same test level events.
/// The main difference is that execution is structured around groups, and group level events are
/// emitted as well.
///
/// ## Grouping
///
/// In addition to `Extra` and the usual strategies, a grouped harness is generic over:
///
/// - `GroupKey`: a key used to assign tests to groups. This is expected to be fairly cheap, since
///   it is used as the identifier for grouping and reporting.
/// - `GroupCtx`: optional per-group context. This may be heavier and is often not required to be
///   [`Clone`].
///
/// Groups make it possible to run tests with shared resources and shared setup and teardown.
/// This is useful when tests depend on expensive or stateful resources that would be hard to manage
/// with unordered test execution.
///
/// Like [`TestHarness`](super::TestHarness), this harness is lazy.
/// Call [`run`](Self::run) to execute tests or [`list`](Self::list) to list them.
#[derive(Debug, Clone)]
#[must_use = "test harnesses are lazy, you have to call either `run` or `list` to do something"]
pub struct GroupedTestHarness<
    't,
    Extra,
    GroupKey,
    GroupCtx,
    Filter,
    Grouper,
    Groups,
    Ignore,
    GroupRunner,
    PanicHandler,
    Runner,
    Formatter,
> {
    pub(crate) tests: &'t [Test<Extra>],
    pub(crate) _group_key: PhantomData<GroupKey>,
    pub(crate) _group_ctx: PhantomData<GroupCtx>,
    pub(crate) filter: Filter,
    pub(crate) grouper: Grouper,
    pub(crate) groups: Groups,
    pub(crate) ignore: Ignore,
    pub(crate) group_runner: GroupRunner,
    pub(crate) panic_handler: PanicHandler,
    pub(crate) runner: Runner,
    pub(crate) formatter: Formatter,
}

impl<
    't,
    Extra: Sync,
    GroupKey: 't,
    GroupCtx: 't,
    Filter: TestFilter<Extra>,
    Grouper: TestGrouper<Extra, GroupKey, GroupCtx>,
    Groups: TestGroups<'t, Extra, GroupKey>,
    Ignore: TestIgnore<Extra> + Send + Sync + 't,
    GroupRunner: TestGroupRunner<'t, Extra, GroupKey, GroupCtx>,
    PanicHandler: TestPanicHandler<Extra> + Send + Sync + 't,
    Runner: TestRunner<'t, Extra>,
    Formatter: GroupedTestFormatter<'t, Extra, GroupKey, GroupCtx> + 't,
>
    GroupedTestHarness<
        't,
        Extra,
        GroupKey,
        GroupCtx,
        Filter,
        Grouper,
        Groups,
        Ignore,
        GroupRunner,
        PanicHandler,
        Runner,
        Formatter,
    >
{
    /// Execute the grouped test harness and produce a [`GroupedTestReport`].
    ///
    /// This runs the grouped test pipeline:
    /// - filters tests
    /// - assigns tests to groups via the configured grouper
    /// - executes groups via the group runner
    /// - executes tests inside each group through the runner
    /// - captures output and panics per test
    /// - forwards group and test events to the grouped formatter
    ///
    /// The harness is consumed by this call.
    /// After running, the result is returned as a [`GroupedTestReport`], which can be converted
    /// into an exit status.
    ///
    /// Formatting errors are collected and included in the report instead of
    /// aborting the run early.
    pub fn run(mut self) -> GroupedTestReport<'t, GroupKey, GroupCtx, Formatter::Error> {
        let now = Instant::now();

        let mut formatter = self.formatter;
        let mut fmt_errors = Vec::new();
        fmt_errors.push_on_error(
            FmtRunInit { tests: self.tests }.fmt(|data| formatter.fmt_run_init(data)),
        );

        let FilteredTests {
            tests,
            filtered_out: filtered,
        } = self.filter.filter(self.tests);
        tests.for_each(|test| self.groups.add(self.grouper.group(test), test));

        fmt_errors.push_on_error(
            FmtGroupedRunStart {
                tests: self.groups.len(),
                filtered,
            }
            .fmt(|data| formatter.fmt_grouped_run_start(data)),
        );
        let (grouped_outcomes, mut formatter, mut fmt_errors) = std::thread::scope(move |scope| {
            // TODO: prefer getting only the MAX value and not the total count of tests for the worker_count estimation
            let (ftx, frx) =
                crossbeam_channel::bounded(self.runner.worker_count(self.groups.len()).get());
            let fmt_thread = scope.spawn(move || {
                while let Ok(fmt_data) = frx.recv() {
                    fmt_errors.push_on_error(match fmt_data {
                        FmtGroupedTestData::Start(data) => formatter
                            .fmt_group_start(data)
                            .map_err(|err| (FormatError::GroupStart, err)),
                        FmtGroupedTestData::Test(FmtTestData::Ignored(data)) => formatter
                            .fmt_test_ignored(data)
                            .map_err(|err| (FormatError::TestIgnored, err)),
                        FmtGroupedTestData::Test(FmtTestData::Start(data)) => formatter
                            .fmt_test_start(data)
                            .map_err(|err| (FormatError::TestStart, err)),
                        FmtGroupedTestData::Test(FmtTestData::Outcome(data)) => formatter
                            .fmt_test_outcome(data)
                            .map_err(|err| (FormatError::TestOutcome, err)),
                        FmtGroupedTestData::Outcome(data) => formatter
                            .fmt_group_outcomes(data)
                            .map_err(|err| (FormatError::GroupOutcomes, err)),
                    });
                }
                (formatter, fmt_errors)
            });

            let ignore = Arc::new(self.ignore);
            let panic_handler = Arc::new(self.panic_handler);
            let runner = Arc::new(self.runner);

            let group_runs = self
                .groups
                .into_groups()
                .map_until_inclusive(|(key, tests)| {
                    let now = Instant::now();

                    let ignore = Arc::clone(&ignore);
                    let panic_handler = Arc::clone(&panic_handler);
                    let runner = Arc::clone(&runner);
                    let ftx = ftx.clone();
                    let ctx = self.grouper.group_ctx(&key);

                    let _ = ftx.send(FmtGroupedTestData::Start(
                        FmtGroupStart {
                            tests: tests.len(),
                            worker_count: runner.worker_count(tests.len()),
                            key: &key,
                            ctx: ctx.as_ref(),
                        }
                        .into(),
                    ));

                    let outcomes = self.group_runner.run_group(
                        move || {
                            let test_runs = tests.into_iter().map(|test| {
                                let meta = &test.meta;
                                let ignore = Arc::clone(&ignore);
                                let panic_handler = Arc::clone(&panic_handler);
                                let ftx = ftx.clone();

                                (
                                    move || {
                                        let reason = match ignore.ignore(meta) {
                                            IgnoreStatus::Run => {
                                                let _ = ftx.send(FmtGroupedTestData::Test(
                                                    FmtTestData::Start(
                                                        FmtTestStart { meta }.into(),
                                                    ),
                                                ));
                                                return panic_handler.handle(|| test.call(), meta);
                                            }
                                            IgnoreStatus::Ignore => None,
                                            IgnoreStatus::IgnoreWithReason(reason) => Some(reason),
                                        };
                                        let _ = ftx.send(FmtGroupedTestData::Test(
                                            FmtTestData::Ignored(
                                                FmtTestIgnored {
                                                    meta,
                                                    reason: reason.as_ref(),
                                                }
                                                .into(),
                                            ),
                                        ));
                                        TestStatus::Ignored { reason }
                                    },
                                    meta,
                                )
                            });

                            runner
                                .run(test_runs, scope)
                                .inspect(|(meta, outcome)| {
                                    let _ =
                                        ftx.send(FmtGroupedTestData::Test(FmtTestData::Outcome(
                                            FmtTestOutcome {
                                                meta: *meta,
                                                outcome,
                                            }
                                            .into(),
                                        )));
                                })
                                .map(|(meta, outcome)| (meta.name.as_ref(), outcome))
                                .collect()
                        },
                        &key,
                        ctx.as_ref(),
                    );

                    match outcomes {
                        ControlFlow::Continue(out) => {
                            ControlFlow::Continue((out, now.elapsed(), key, ctx))
                        }
                        ControlFlow::Break(out) => {
                            ControlFlow::Break((out, now.elapsed(), key, ctx))
                        }
                    }
                });

            let grouped_outcomes = group_runs
                .inspect(|(outcomes, duration, key, ctx)| {
                    let _ = ftx.send(FmtGroupedTestData::Outcome(
                        FmtGroupOutcomes {
                            outcomes,
                            duration: *duration,
                            key,
                            ctx: ctx.as_ref(),
                        }
                        .into(),
                    ));
                })
                .map(|(outcomes, _, key, ctx)| (key, outcomes, ctx))
                .collect();

            drop(ftx);
            let (formatter, fmt_errors) = fmt_thread
                .join()
                .expect("format thread should join without issues");

            (grouped_outcomes, formatter, fmt_errors)
        });

        let duration = now.elapsed();
        fmt_errors.push_on_error(
            FmtGroupedRunOutcomes {
                outcomes: &grouped_outcomes,
                duration,
            }
            .fmt(|data| formatter.fmt_grouped_run_outcomes(data)),
        );

        GroupedTestReport {
            outcomes: grouped_outcomes,
            duration,
            fmt_errors,
        }
    }
}

impl<
    't,
    Extra,
    GroupKey: 't,
    GroupCtx: 't,
    Filter: TestFilter<Extra>,
    Grouper: TestGrouper<Extra, GroupKey, GroupCtx>,
    Groups: TestGroups<'t, Extra, GroupKey>,
    Ignore: TestIgnore<Extra>,
    GroupRunner,
    PanicHandler,
    Runner,
    Formatter: GroupedTestListFormatter<'t, Extra, GroupKey, GroupCtx>,
>
    GroupedTestHarness<
        't,
        Extra,
        GroupKey,
        GroupCtx,
        Filter,
        Grouper,
        Groups,
        Ignore,
        GroupRunner,
        PanicHandler,
        Runner,
        Formatter,
    >
{
    /// List groups and tests without executing them.
    ///
    /// This runs the grouped harness in listing mode.
    /// Tests are filtered and grouped the same way as during a normal run, but test functions are
    /// never executed.
    ///
    /// The formatter is notified of listing events and may print a grouped overview
    /// similar to `cargo test -- --list`, but with group structure.
    ///
    /// The harness is consumed by this call.
    ///
    /// Formatting errors are returned instead of stopping early.
    pub fn list(mut self) -> TestListReport<Formatter::Error> {
        let mut formatter = self.formatter;
        let mut fmt_errors = Vec::new();
        fmt_errors.push_on_error(
            FmtInitListing { tests: self.tests }.fmt(|data| formatter.fmt_init_listing(data)),
        );

        let FilteredTests {
            tests,
            filtered_out: filtered,
        } = self.filter.filter(self.tests);
        fmt_errors.push_on_error(
            FmtBeginListing {
                tests: tests.len(),
                filtered,
            }
            .fmt(|data| formatter.fmt_begin_listing(data)),
        );

        tests.for_each(|test| self.groups.add(self.grouper.group(test), test));
        let groups = self.groups.into_groups();
        fmt_errors.push_on_error(
            FmtListGroups {
                groups: groups.len(),
            }
            .fmt(|data| formatter.fmt_list_groups(data)),
        );

        let mut active_count = 0;
        let mut ignore_count = 0;
        for (key, tests) in groups {
            let ctx = self.grouper.group_ctx(&key);
            let tests_len = tests.len();

            fmt_errors.push_on_error(
                FmtListGroupStart {
                    tests: tests_len,
                    key: &key,
                    ctx: ctx.as_ref(),
                }
                .fmt(|data| formatter.fmt_list_group_start(data)),
            );

            for test in tests {
                let ignored = self.ignore.ignore(test);
                match &ignored {
                    IgnoreStatus::Run => active_count += 1,
                    IgnoreStatus::Ignore | IgnoreStatus::IgnoreWithReason(_) => ignore_count += 1,
                }
                fmt_errors.push_on_error(
                    FmtListTest {
                        meta: test,
                        ignored,
                    }
                    .fmt(|data| formatter.fmt_list_test(data)),
                );
            }

            fmt_errors.push_on_error(
                FmtListGroupEnd {
                    tests: tests_len,
                    key: &key,
                    ctx: ctx.as_ref(),
                }
                .fmt(|data| formatter.fmt_list_group_end(data)),
            );
        }

        fmt_errors.push_on_error(
            FmtEndListing {
                active: active_count,
                ignored: ignore_count,
            }
            .fmt(|data| formatter.fmt_end_listing(data)),
        );

        TestListReport(fmt_errors)
    }
}

impl<
    't,
    Extra,
    GroupKey,
    GroupCtx,
    Filter,
    Grouper,
    Groups,
    Ignore,
    GroupRunner,
    PanicHandler,
    Runner,
    Formatter,
>
    GroupedTestHarness<
        't,
        Extra,
        GroupKey,
        GroupCtx,
        Filter,
        Grouper,
        Groups,
        Ignore,
        GroupRunner,
        PanicHandler,
        Runner,
        Formatter,
    >
{
    /// Replace the filter strategy.
    ///
    /// The filter strategy decides which tests participate at all. Filtering happens
    /// before grouping and before ignoring.
    pub fn with_filter<WithFilter: TestFilter<Extra>>(
        self,
        filter: WithFilter,
    ) -> GroupedTestHarness<
        't,
        Extra,
        GroupKey,
        GroupCtx,
        WithFilter,
        Grouper,
        Groups,
        Ignore,
        GroupRunner,
        PanicHandler,
        Runner,
        Formatter,
    > {
        GroupedTestHarness {
            tests: self.tests,
            _group_key: PhantomData,
            _group_ctx: PhantomData,
            filter,
            grouper: self.grouper,
            groups: self.groups,
            ignore: self.ignore,
            group_runner: self.group_runner,
            panic_handler: self.panic_handler,
            runner: self.runner,
            formatter: self.formatter,
        }
    }

    /// Replace the group storage strategy.
    ///
    /// This controls how groups are stored while building them.
    /// Different implementations can be used to control ordering or to use specialized storage.
    pub fn with_groups<WithGroups: TestGroups<'t, Extra, GroupKey>>(
        self,
        groups: WithGroups,
    ) -> GroupedTestHarness<
        't,
        Extra,
        GroupKey,
        GroupCtx,
        Filter,
        Grouper,
        WithGroups,
        Ignore,
        GroupRunner,
        PanicHandler,
        Runner,
        Formatter,
    > {
        GroupedTestHarness {
            tests: self.tests,
            _group_key: PhantomData,
            _group_ctx: PhantomData,
            filter: self.filter,
            grouper: self.grouper,
            groups,
            ignore: self.ignore,
            group_runner: self.group_runner,
            panic_handler: self.panic_handler,
            runner: self.runner,
            formatter: self.formatter,
        }
    }

    /// Replace the ignore strategy.
    ///
    /// The ignore strategy decides whether a test inside a group is executed or reported
    /// as ignored, optionally with a reason.
    pub fn with_ignore<WithIgnore: TestIgnore<Extra>>(
        self,
        ignore: WithIgnore,
    ) -> GroupedTestHarness<
        't,
        Extra,
        GroupKey,
        GroupCtx,
        Filter,
        Grouper,
        Groups,
        WithIgnore,
        GroupRunner,
        PanicHandler,
        Runner,
        Formatter,
    > {
        GroupedTestHarness {
            tests: self.tests,
            _group_key: PhantomData,
            _group_ctx: PhantomData,
            filter: self.filter,
            grouper: self.grouper,
            groups: self.groups,
            ignore,
            group_runner: self.group_runner,
            panic_handler: self.panic_handler,
            runner: self.runner,
            formatter: self.formatter,
        }
    }

    /// Replace the group runner strategy.
    ///
    /// The group runner decides how groups are executed and can control the flow between
    /// groups.
    /// For example, it may stop early once a group fails.
    pub fn with_group_runner<WithGroupRunner: TestGroupRunner<'t, Extra, GroupKey, GroupCtx>>(
        self,
        group_runner: WithGroupRunner,
    ) -> GroupedTestHarness<
        't,
        Extra,
        GroupKey,
        GroupCtx,
        Filter,
        Grouper,
        Groups,
        Ignore,
        WithGroupRunner,
        PanicHandler,
        Runner,
        Formatter,
    > {
        GroupedTestHarness {
            tests: self.tests,
            _group_key: PhantomData,
            _group_ctx: PhantomData,
            filter: self.filter,
            grouper: self.grouper,
            groups: self.groups,
            ignore: self.ignore,
            group_runner,
            panic_handler: self.panic_handler,
            runner: self.runner,
            formatter: self.formatter,
        }
    }

    /// Replace the panic handler.
    ///
    /// The panic handler is responsible for executing the test function and converting
    /// panics into a [`TestStatus`], taking metadata such as `should_panic` into account.
    pub fn with_panic_handler<WithPanicHandler: TestPanicHandler<Extra>>(
        self,
        panic_handler: WithPanicHandler,
    ) -> GroupedTestHarness<
        't,
        Extra,
        GroupKey,
        GroupCtx,
        Filter,
        Grouper,
        Groups,
        Ignore,
        GroupRunner,
        WithPanicHandler,
        Runner,
        Formatter,
    > {
        GroupedTestHarness {
            tests: self.tests,
            _group_key: PhantomData,
            _group_ctx: PhantomData,
            filter: self.filter,
            grouper: self.grouper,
            groups: self.groups,
            ignore: self.ignore,
            group_runner: self.group_runner,
            panic_handler,
            runner: self.runner,
            formatter: self.formatter,
        }
    }

    /// Replace the test runner.
    ///
    /// The runner controls how tests inside a group are scheduled and executed, for example
    /// sequentially or in parallel.
    pub fn with_runner<WithRunner: TestRunner<'t, Extra>>(
        self,
        runner: WithRunner,
    ) -> GroupedTestHarness<
        't,
        Extra,
        GroupKey,
        GroupCtx,
        Filter,
        Grouper,
        Groups,
        Ignore,
        GroupRunner,
        PanicHandler,
        WithRunner,
        Formatter,
    > {
        GroupedTestHarness {
            tests: self.tests,
            _group_key: PhantomData,
            _group_ctx: PhantomData,
            filter: self.filter,
            grouper: self.grouper,
            groups: self.groups,
            ignore: self.ignore,
            group_runner: self.group_runner,
            panic_handler: self.panic_handler,
            runner,
            formatter: self.formatter,
        }
    }

    /// Replace the grouped formatter.
    ///
    /// The formatter receives structured group and test events and is responsible for
    /// producing output.
    pub fn with_formatter<WithFormatter>(
        self,
        formatter: WithFormatter,
    ) -> GroupedTestHarness<
        't,
        Extra,
        GroupKey,
        GroupCtx,
        Filter,
        Grouper,
        Groups,
        Ignore,
        GroupRunner,
        PanicHandler,
        Runner,
        WithFormatter,
    > {
        GroupedTestHarness {
            tests: self.tests,
            _group_key: PhantomData,
            _group_ctx: PhantomData,
            filter: self.filter,
            grouper: self.grouper,
            groups: self.groups,
            ignore: self.ignore,
            group_runner: self.group_runner,
            panic_handler: self.panic_handler,
            runner: self.runner,
            formatter,
        }
    }
}