-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.rs
284 lines (247 loc) · 8.3 KB
/
build.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
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
use serde::Deserialize;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::fs::DirEntry;
use std::path::Path;
use std::{env, fs};
const MD_CASES_PATH: &str = "tests/md_cases/";
const CASES_WRITE: &str = "tests/integ_test_cases.rs";
fn main() -> Result<(), String> {
println!("cargo::rerun-if-changed={MD_CASES_PATH}");
let out_dir = env::var("OUT_DIR").unwrap();
generate_integ_test_cases(&out_dir)?;
Ok(())
}
fn generate_integ_test_cases(out_dir: &String) -> Result<(), String> {
let mut out = Writer::new();
for md_case in fs::read_dir(MD_CASES_PATH).map_err(|e| e.to_string())? {
let spec_file = DirEntryHelper::new(md_case.map_err(|e| e.to_string())?);
if !spec_file.run(DirEntry::file_type)?.is_file() {
return Err(spec_file.err_string::<&str, _>("not a regular file"));
}
out.writes(&["mod ", &spec_file.mod_name(), " {"]).nl();
out.with_indent(|out| {
out.write("use super::*;").nl().nl();
let contents = spec_file.run(|f| fs::read_to_string(f.path())).unwrap();
let spec_file_parsed: TestSpecFile =
toml::from_str(&contents).map_err(|e| spec_file.err_string(e)).unwrap();
let chained_needed = spec_file_parsed.chained.map(|ch| ch.needed).unwrap_or(true);
out.write("const MD: &str = indoc::indoc! {r#\"");
out.with_indent(|out| {
let mut iter = spec_file_parsed.given.md.trim().split('\n').peekable();
while let Some(line) = iter.next() {
out.nl().write(line);
if iter.peek().is_none() {
out.writeln("\"#};");
}
}
});
let mut found_chained_case = false;
for case in spec_file_parsed.get_cases() {
found_chained_case |= case.case_name.eq("chained");
case.write_test_fn_to(out);
}
match (chained_needed, found_chained_case) {
(true, false) => Case::write_failing_test(out, "chained", "missing 'chained' test case"),
(false, true) => Case::write_failing_test(
out,
"chained__extra",
"provided 'chained' test case even though it was marked as not needed",
),
_ => {}
}
if !found_chained_case {}
});
out.writeln("}");
}
let out_path = Path::new(&out_dir).join(CASES_WRITE);
fs::create_dir_all(out_path.parent().expect("no parent dir found"))
.map_err(|e| format!("mkdirs on {}: {}", out_path.to_string_lossy(), e.to_string()))?;
fs::write(&out_path, out.get())
.map_err(|e| format!("writing to {}: {}", out_path.to_string_lossy(), e.to_string()))?;
Ok(())
}
struct DirEntryHelper {
dir_entry: DirEntry,
path_lossy: String,
}
impl DirEntryHelper {
fn new(dir_entry: DirEntry) -> Self {
let path_lossy = dir_entry.path().to_string_lossy().to_string();
Self { dir_entry, path_lossy }
}
fn mod_name(&self) -> String {
let file_name = self.dir_entry.file_name();
let p = Path::new(file_name.as_os_str());
let stem = p
.file_stem()
.expect(&format!("no file stem for {}", self.dir_entry.path().to_string_lossy()));
stem.to_string_lossy().to_string()
}
fn run<F, E: ToString, R>(&self, action: F) -> Result<R, String>
where
E: ToString,
F: FnOnce(&DirEntry) -> Result<R, E>,
{
action(&self.dir_entry).map_err(|e| self.err_string(e))
}
fn path(&self) -> &str {
&self.path_lossy
}
fn err_string<E: ToString, B: Borrow<E>>(&self, e: B) -> String {
format!("{}: {}", self.path(), e.borrow().to_string())
}
}
#[derive(Deserialize)]
struct TestSpecFile {
given: TestGiven,
expect: HashMap<String, TestExpect>,
chained: Option<Chained>,
}
#[derive(Deserialize)]
struct TestGiven {
md: String,
}
#[derive(Deserialize)]
struct TestExpect {
cli_args: Vec<String>,
output: String,
output_json: Option<bool>,
expect_success: Option<bool>,
ignore: Option<String>,
}
#[derive(Deserialize, Copy, Clone)]
struct Chained {
needed: bool,
}
impl TestSpecFile {
fn get_cases(self) -> Vec<Case> {
let mut results = Vec::with_capacity(self.expect.len());
for (case_name, test_expect) in self.expect {
results.push(Case {
case_name,
cli_args: test_expect.cli_args,
expect_output: test_expect.output,
output_json: test_expect.output_json.unwrap_or(false),
expect_success: test_expect.expect_success.unwrap_or(true),
ignored: test_expect.ignore.is_some(),
})
}
results
}
}
#[derive(Debug)]
struct Case {
case_name: String,
ignored: bool,
cli_args: Vec<String>,
expect_output: String,
output_json: bool,
expect_success: bool,
}
impl Case {
fn write_failing_test(out: &mut Writer, name: &str, err_msg: &str) {
out.writeln("#[test]");
out.writes(&["fn ", name, "() {"]);
out.with_indent(|out| {
out.writes(&["panic!(\"", err_msg, "\");"]);
});
out.writeln("}");
}
fn write_test_fn_to(&self, out: &mut Writer) {
let fn_name = self
.case_name
.replace(|ch: char| !(ch.is_alphanumeric() || ch.is_whitespace()), "")
.replace(|ch: char| ch.is_whitespace(), "_");
if self.ignored {
// separate out ign-ore to two lines, so that it doesn't trigger the CI check for ignored tests
out.write("#[ign");
out.writeln("ore]");
}
out.writeln("#[test]");
out.writes(&["fn ", &fn_name, "() {"]);
out.with_indent(|out| {
out.write("Case {");
out.with_indent(|out| {
out.writeln(&format!("cli_args: {:?},", &self.cli_args));
out.writeln(&format!("expect_output_json: {},", self.output_json));
if self.expect_output.is_empty() {
out.write("expect_output: \"\",");
} else {
out.write("expect_output: indoc::indoc! {r#\"");
out.with_indent(|out| {
let mut iter = self.expect_output.split('\n').peekable();
while let Some(line) = iter.next() {
out.write(line);
if iter.peek().is_some() {
out.nl();
} else {
out.write("\"#},");
}
}
});
}
out.write("expect_success: ")
.write(&self.expect_success.to_string())
.writeln(",");
out.write("md: MD,");
});
out.write("}.check();");
});
out.write("}").nl().nl();
}
}
struct Writer {
out: String,
indent_level: usize,
}
impl Writer {
fn new() -> Self {
Self {
out: String::with_capacity(512),
indent_level: 0,
}
}
fn with_indent<F>(&mut self, block: F)
where
F: FnOnce(&mut Self),
{
self.indent_level += 1;
self.write("\n");
block(self);
self.indent_level -= 1;
self.write("\n");
}
fn write(&mut self, text: &str) -> &mut Self {
let mut iter = text.split('\n').peekable();
while let Some(line) = iter.next() {
if !line.is_empty() {
self.out.push_str(line);
}
if iter.peek().is_some() {
self.out.push('\n');
for _ in 0..self.indent_level {
self.out.push_str(" ");
}
}
}
self
}
fn writes(&mut self, items: &[&str]) -> &mut Self {
for item in items {
self.write(item);
}
self
}
fn writeln(&mut self, text: &str) {
self.write(text);
self.write("\n");
}
fn nl(&mut self) -> &mut Self {
self.write("\n");
self
}
fn get(&self) -> &str {
&self.out
}
}