af_core/test/
context.rs

1// Copyright © 2021 Alexandra Frydl
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use super::{Output, OutputStream, Path};
8use crate::channel;
9use crate::prelude::*;
10use crate::string::SharedString;
11use crate::task::{self, Task};
12use std::collections::BTreeMap;
13
14/// A test context that groups related tests together.
15#[derive(Default)]
16pub struct Context {
17  children: BTreeMap<SharedString, Child>,
18  len: usize,
19  path: Path,
20}
21
22/// A child of a [`Context`].
23enum Child {
24  Context(Context),
25  Test(Box<dyn FnOnce() -> Task<Result<(), fail::Error>> + Send>),
26}
27
28impl Context {
29  /// Creates a new, empty test context.
30  pub fn new() -> Self {
31    default()
32  }
33
34  /// Creates a new child context with a given scope name.
35  pub fn scope(&mut self, name: impl Into<SharedString>, build: impl FnOnce(&mut Context)) {
36    let name = name.into();
37
38    assert!(!name.is_empty(), "A test context cannot be named \"\".");
39    assert!(!self.children.contains_key(&name), "Duplicate name {:?}.", name);
40
41    let mut ctx = Self::new();
42
43    build(&mut ctx);
44
45    ctx.path = self.path.clone();
46    ctx.path.components.push_back(name.clone());
47
48    self.len += ctx.len;
49    self.children.insert(name, Child::Context(ctx));
50  }
51
52  /// Adds a test to the context.
53  pub fn test(
54    &mut self,
55    name: impl Into<SharedString>,
56    test: impl task::Start<Result> + Send + 'static,
57  ) {
58    let name = name.into();
59
60    assert!(!name.is_empty(), "A test cannot be named \"\".");
61    assert!(!self.children.contains_key(&name), "Duplicate name {:?}.", name);
62
63    let start = Box::new(move || task::start(test));
64
65    self.len += 1;
66    self.children.insert(name, Child::Test(start));
67  }
68
69  /// Starts the tests in this context, returning an [`OutputStream`] for
70  /// receiving the results.
71  pub fn start(self) -> OutputStream {
72    let remaining = self.len;
73    let (tx, rx) = channel::unbounded();
74    let _task = task::start(self.run(default(), tx));
75
76    OutputStream { remaining, rx, _task }
77  }
78
79  /// Runs the tests in this context and its child contexts in separate tasks.
80  #[future::boxed]
81  async fn run(self, path: Path, output: channel::Sender<Output>) {
82    let mut tasks = task::Join::new();
83
84    for (name, child) in self.children {
85      let output = output.clone();
86      let mut path = path.clone();
87
88      path.components.push_back(name);
89
90      match child {
91        Child::Context(ctx) => tasks.add(ctx.run(path, output)),
92
93        Child::Test(start) => tasks.add(async move {
94          let result = start().try_join().await;
95
96          output.send(Output { path, result }).await.unwrap();
97        }),
98      };
99    }
100
101    while let Some(task) = tasks.next().await {
102      if task.result.is_err() {
103        error!("Internal test runner panic.");
104      }
105    }
106  }
107}