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
#![doc = include_str!("../README.md")]
// !!START_LINTS
// Wick lints
// Do not change anything between the START_LINTS and END_LINTS line.
// This is automatically generated. Add exceptions after this section.
#![allow(unknown_lints)]
#![deny(
  clippy::expect_used,
  clippy::explicit_deref_methods,
  clippy::option_if_let_else,
  clippy::await_holding_lock,
  clippy::cloned_instead_of_copied,
  clippy::explicit_into_iter_loop,
  clippy::flat_map_option,
  clippy::fn_params_excessive_bools,
  clippy::implicit_clone,
  clippy::inefficient_to_string,
  clippy::large_types_passed_by_value,
  clippy::manual_ok_or,
  clippy::map_flatten,
  clippy::map_unwrap_or,
  clippy::must_use_candidate,
  clippy::needless_for_each,
  clippy::needless_pass_by_value,
  clippy::option_option,
  clippy::redundant_else,
  clippy::semicolon_if_nothing_returned,
  clippy::too_many_lines,
  clippy::trivially_copy_pass_by_ref,
  clippy::unnested_or_patterns,
  clippy::future_not_send,
  clippy::useless_let_if_seq,
  clippy::str_to_string,
  clippy::inherent_to_string,
  clippy::let_and_return,
  clippy::string_to_string,
  clippy::try_err,
  clippy::unused_async,
  clippy::missing_enforced_import_renames,
  clippy::nonstandard_macro_braces,
  clippy::rc_mutex,
  clippy::unwrap_or_else_default,
  clippy::manual_split_once,
  clippy::derivable_impls,
  clippy::needless_option_as_deref,
  clippy::iter_not_returning_iterator,
  clippy::same_name_method,
  clippy::manual_assert,
  clippy::non_send_fields_in_send_ty,
  clippy::equatable_if_let,
  bad_style,
  clashing_extern_declarations,
  dead_code,
  deprecated,
  explicit_outlives_requirements,
  improper_ctypes,
  invalid_value,
  missing_copy_implementations,
  missing_debug_implementations,
  mutable_transmutes,
  no_mangle_generic_items,
  non_shorthand_field_patterns,
  overflowing_literals,
  path_statements,
  patterns_in_fns_without_body,
  private_in_public,
  trivial_bounds,
  trivial_casts,
  trivial_numeric_casts,
  type_alias_bounds,
  unconditional_recursion,
  unreachable_pub,
  unsafe_code,
  unstable_features,
  unused,
  unused_allocation,
  unused_comparisons,
  unused_import_braces,
  unused_parens,
  unused_qualifications,
  while_true,
  missing_docs
)]
#![allow(unused_attributes, clippy::derive_partial_eq_without_eq, clippy::box_default)]
// !!END_LINTS
// Add exceptions here
#![allow()]

use testanything::tap_test::TapTest;
use testanything::tap_test_builder::TapTestBuilder;

#[derive(Default, Debug)]
/// [TestRunner] is the main way you'll interact with TAP tests.
pub struct TestRunner {
  desc: Option<String>,
  blocks: Vec<TestBlock>,
  output: Vec<String>,
}

impl TestRunner {
  /// Create a new [TestRunner]
  pub fn new<T: AsRef<str>>(desc: Option<T>) -> Self {
    Self {
      desc: desc.map(|v| v.as_ref().to_owned()),
      blocks: vec![],
      output: vec![],
    }
  }

  /// Add a [TestBlock] to the runner.
  pub fn add_block(&mut self, block: TestBlock) {
    self.blocks.push(block);
  }

  #[must_use]
  /// Get the TAP output.
  pub fn get_tap_lines(&self) -> &Vec<String> {
    &self.output
  }

  /// Execute the tests.
  pub fn run(&mut self) {
    let description = self
      .desc
      .as_ref()
      .map_or_else(|| "TAP Stream".to_owned(), |v| v.clone());

    let mut total_tests = 0;
    for block in &self.blocks {
      total_tests += block.num_tests();
    }

    let plan_line = format!("1..{} # {}", total_tests, description);
    let mut all_lines = vec![plan_line];

    let mut test_num = 0;
    for block in self.blocks.iter_mut() {
      if let Some(desc) = block.desc.as_ref() {
        all_lines.push(format!("# {}", desc));
      }
      let mut block_passed = true;
      for result in block.run() {
        test_num += 1;
        let tap = result.status_line(test_num);
        all_lines.push(tap);
        block_passed = block_passed && result.passed;
        if !result.passed {
          let mut formatted_diagnostics = format_diagnostics(&result.diagnostics);
          all_lines.append(&mut formatted_diagnostics);
        }
      }
      if !block_passed {
        all_lines.append(&mut format_diagnostics(&block.diagnostics));
      }
    }
    self.output = all_lines;
  }

  /// Print the TAP output.
  pub fn print(&self) {
    let lines = self.get_tap_lines();
    for line in lines {
      println!("{}", line);
    }
  }

  #[must_use]
  /// Get the number of failed tests.
  pub fn num_failed(&self) -> u32 {
    let lines = self.get_tap_lines();
    let mut num_failed: u32 = 0;

    for line in lines {
      if line.starts_with("not ok") {
        num_failed += 1;
      }
    }
    num_failed
  }
}

fn format_diagnostic_line<T: AsRef<str>>(line: T) -> String {
  format!("# {}", line.as_ref())
}

fn format_diagnostics<T>(lines: &[T]) -> Vec<String>
where
  T: AsRef<str>,
{
  lines.iter().map(format_diagnostic_line).collect()
}

#[derive(Default, Debug)]
/// A [TestBlock] organizes [TestCase] under one description.
pub struct TestBlock {
  desc: Option<String>,
  tests: Vec<TestCase>,
  diagnostics: Vec<String>,
}

impl TestBlock {
  /// Create a new [TestBlock].
  pub fn new<T: AsRef<str>>(desc: Option<T>) -> Self {
    Self {
      desc: desc.map(|v| v.as_ref().to_owned()),
      tests: vec![],
      diagnostics: vec![],
    }
  }

  /// Add a new test case.
  pub fn add_test<T: AsRef<str>>(
    &mut self,
    test: impl FnOnce() -> bool + Sync + Send + 'static,
    description: T,
    diagnostics: Option<Vec<String>>,
  ) {
    self.tests.push(TestCase {
      test: Some(Box::new(test)),
      result: Some(false),
      description: description.as_ref().to_owned(),
      diagnostics: diagnostics.unwrap_or_default(),
    });
  }

  /// Add diagnostic messages to this test block.
  pub fn add_diagnostic_messages(&mut self, messages: Vec<String>) {
    self.diagnostics = messages;
  }

  fn num_tests(&self) -> usize {
    self.tests.len()
  }

  /// Execute the [TestBlock]'s [TestCase]s.
  pub fn run(&mut self) -> Vec<TapTest> {
    let mut tests = vec![];
    for test_case in self.tests.iter_mut() {
      let diags: Vec<&str> = test_case.diagnostics.iter().map(|s| s.as_str()).collect();
      let tap_test = TapTestBuilder::new()
        .name(test_case.description.clone())
        .diagnostics(&diags)
        .passed(test_case.exec())
        .finalize();
      tests.push(tap_test);
    }
    tests
  }
}

#[derive()]
struct TestCase {
  test: Option<Box<dyn FnOnce() -> bool + Sync + Send>>,
  result: Option<bool>,
  description: String,
  diagnostics: Vec<String>,
}

impl std::fmt::Debug for TestCase {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.debug_struct("TestCase")
      .field("result", &self.result)
      .field("description", &self.description)
      .field("diagnostics", &self.diagnostics)
      .finish()
  }
}

impl TestCase {
  fn exec(&mut self) -> bool {
    match self.test.take() {
      Some(test) => {
        let result = (test)();
        self.result = Some(result);
        result
      }
      #[allow(clippy::expect_used)]
      None => self.result.expect("Attempted to execute a test without a test case"),
    }
  }
}