-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.rs
216 lines (194 loc) · 6.49 KB
/
context.rs
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
use super::{results, suite, Test};
use crate::{
cli,
errors::{self, RuntError},
};
use futures::{
io::{AllowStdIo, AsyncWriteExt},
stream, StreamExt,
};
/// An executor manages the execution of a list of tests.
pub struct Executor {
/// Test configurations to be executed.
tests: Vec<Test>,
/// Maximum number of futures that can be created.
max_futures: usize,
}
impl Executor {
/// Execute the test suites and generate test results in any order.
/// It is the job of the consumer of this method to collect the results and
/// display them in the desired manner (grouped by test suite or order of
/// completion)
pub fn execute_all(
self,
) -> impl stream::Stream<Item = Result<results::Test, RuntError>> {
stream::iter(self.tests.into_iter().map(|test| test.execute_test()))
.buffer_unordered(self.max_futures)
}
}
/// Track the status of an executing test suite and print output to stdout.
pub struct Status {
pub miss: u64,
pub pass: u64,
pub remain: u64,
pub skip: u64,
pub fail: u64,
pub timeout: u64,
/// Handle to the output
handle: AllowStdIo<std::io::BufWriter<std::io::Stdout>>,
istty: bool,
}
impl Status {
/// Instantiate a test suite with total number of tests
pub fn new(total: u64) -> Self {
let handle =
AllowStdIo::new(std::io::BufWriter::new(std::io::stdout()));
let istty = atty::is(atty::Stream::Stdout);
Self {
remain: total,
miss: 0,
pass: 0,
skip: 0,
fail: 0,
timeout: 0,
handle,
istty,
}
}
/// Generate a summary string for the current state.
fn summary(&self) -> String {
use colored::*;
format!(
" {} {} / {} {} / {} {} / {} {} / {} {}",
self.pass.to_string().green().bold(),
&"passing".green().bold(),
(self.fail + self.timeout).to_string().red().bold(),
&"failing".red().bold(),
self.miss.to_string().yellow().bold(),
&"missing".yellow().bold(),
self.skip.to_string().yellow().dimmed().bold(),
&"skipped".yellow().dimmed().bold(),
self.remain.to_string().dimmed().bold(),
&"remaining".dimmed().bold(),
)
}
/// Stream out the current summary to the output if possible.
#[inline]
pub async fn stream_summary(&mut self) -> Result<(), errors::RuntError> {
if self.istty {
self.print_summary().await?;
}
Ok(())
}
/// Print the current status
#[inline]
pub async fn print_summary(&mut self) -> Result<(), errors::RuntError> {
self.handle.write_all(self.summary().as_bytes()).await?;
self.handle.flush().await?;
Ok(())
}
/// Clear the current output if possible.
#[inline]
pub async fn clear(&mut self) -> Result<(), errors::RuntError> {
if self.istty {
self.handle.write_all("\r\x1B[K".as_bytes()).await?;
}
Ok(())
}
/// Print a message to the output handler.
pub async fn print<S: AsRef<[u8]>>(
&mut self,
msg: S,
) -> Result<(), errors::RuntError> {
self.handle.write_all(msg.as_ref()).await?;
self.handle.write("\n".as_bytes()).await?;
self.handle.flush().await?;
Ok(())
}
/// Update the status given the [State] of a test.
pub fn update(&mut self, state: &results::State) {
match state {
results::State::Skip => {
self.skip += 1;
}
results::State::Correct => {
self.pass += 1;
}
results::State::Mismatch(..) => {
self.fail += 1;
}
results::State::Timeout => {
self.timeout += 1;
}
results::State::Missing(..) => {
self.miss += 1;
}
}
self.remain -= 1;
}
}
/// An execution context manage the mapping between test suites and test, asynchronously executes
/// tests, collects results, and streams out results as appropriate.
pub struct Context {
/// Configurations for suites to be executed.
configs: Vec<suite::Config>,
/// Test configurations to be executed.
pub exec: Executor,
}
impl Context {
/// Construct a new [Context] using suites and a maximum number of futures
/// allowed to run concurrently.
pub fn from(suites: Vec<suite::Suite>, max_futures: usize) -> Self {
let mut configs = Vec::with_capacity(suites.len());
let mut tests = Vec::with_capacity(suites.len());
for (idx, suite) in suites.into_iter().enumerate() {
let suite::Suite { config, paths } = suite;
tests.extend(paths.into_iter().map(|path| Test {
path,
cmd: config.cmd.clone(),
expect_dir: config.expect_dir.clone(),
test_suite: idx as u64,
timeout: config.timeout,
}));
configs.push(config);
}
Context {
exec: Executor { tests, max_futures },
configs,
}
}
/// Generates a streaming summary of the test results.
pub async fn execute_and_summarize(
self,
opts: &cli::Opts,
) -> Result<i32, errors::RuntError> {
let mut st = Status::new(self.exec.tests.len() as u64);
let mut tasks = self.exec.execute_all();
// Initial summary printing to give user feedback that runt has started.
st.stream_summary().await?;
while let Some(result) = tasks.next().await {
let mut res = result?;
// Save the result if needed
if res.should_save(opts) {
res.save_results().await?;
}
// Update summary
st.update(&res.state);
// Clear the current line to print the updating counter.
st.clear().await?;
// Print test information if needed.
if res.should_print(opts) {
let suite_name = &self.configs[res.test_suite as usize].name;
st.print(res.report_str(Some(suite_name), opts.diff))
.await?;
}
// Print out the current summary
st.stream_summary().await?;
}
// Print the final summary
st.clear().await?;
st.print_summary().await?;
println!();
Ok((st.timeout + st.fail) as i32)
}
}