1use 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#[derive(Default)]
16pub struct Context {
17 children: BTreeMap<SharedString, Child>,
18 len: usize,
19 path: Path,
20}
21
22enum Child {
24 Context(Context),
25 Test(Box<dyn FnOnce() -> Task<Result<(), fail::Error>> + Send>),
26}
27
28impl Context {
29 pub fn new() -> Self {
31 default()
32 }
33
34 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 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 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 #[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}