Debian Codegraph @

src/tests/integration_test_utils.rs

raw symbols SCIP
1 #![cfg(test)]
2
3 use std::borrow::Cow;
4 use std::fs::File;
5 use std::io::{BufReader, Write};
6 use std::path::Path;
7
8 use bytelines::ByteLines;
9 use itertools::Itertools;
10
11 use crate::ansi;
12 use crate::cli;
13 use crate::config;
14 use crate::delta::delta;
15 use crate::env::DeltaEnv;
16 use crate::git_config::GitConfig;
17 use crate::tests::test_utils;
18 use crate::utils::process::tests::FakeParentArgs;
19
20 pub fn make_options_from_args_and_git_config(
21 args: &[&str],
22 git_config_contents: Option<&[u8]>,
23 git_config_path: Option<&str>,
24 ) -> cli::Opt {
25 _make_options_from_args_and_git_config(
26 DeltaEnv::default(),
27 args,
28 git_config_contents,
29 git_config_path,
30 false,
31 )
32 }
33
34 pub fn make_options_from_args_and_git_config_with_custom_env(
35 env: DeltaEnv,
36 args: &[&str],
37 git_config_contents: Option<&[u8]>,
38 git_config_path: Option<&str>,
39 ) -> cli::Opt {
40 _make_options_from_args_and_git_config(env, args, git_config_contents, git_config_path, false)
41 }
42
43 pub fn make_options_from_args_and_git_config_honoring_env_var_with_custom_env(
44 env: DeltaEnv,
45 args: &[&str],
46 git_config_contents: Option<&[u8]>,
47 git_config_path: Option<&str>,
48 ) -> cli::Opt {
49 _make_options_from_args_and_git_config(env, args, git_config_contents, git_config_path, true)
50 }
51
52 fn _make_options_from_args_and_git_config(
53 env: DeltaEnv,
54 args: &[&str],
55 git_config_contents: Option<&[u8]>,
56 git_config_path: Option<&str>,
57 honor_env_var: bool,
58 ) -> cli::Opt {
59 let mut args: Vec<&str> = itertools::chain(&["/dev/null", "/dev/null"], args)
60 .copied()
61 .collect();
62 let git_config = match (git_config_contents, git_config_path) {
63 (Some(contents), Some(path)) => Some(make_git_config(&env, contents, path, honor_env_var)),
64 _ => {
65 args.push("--no-gitconfig");
66 None
67 }
68 };
69 cli::Opt::from_iter_and_git_config(&env, args, git_config)
70 }
71
72 pub fn make_options_from_args(args: &[&str]) -> cli::Opt {
73 make_options_from_args_and_git_config(args, None, None)
74 }
75
76 #[allow(dead_code)]
77 pub fn make_config_from_args_and_git_config(
78 args: &[&str],
79 git_config_contents: Option<&[u8]>,
80 git_config_path: Option<&str>,
81 ) -> config::Config {
82 config::Config::from(make_options_from_args_and_git_config(
83 args,
84 git_config_contents,
85 git_config_path,
86 ))
87 }
88
89 pub fn make_config_from_args(args: &[&str]) -> config::Config {
90 config::Config::from(make_options_from_args(args))
91 }
92
93 pub fn make_git_config(
94 env: &DeltaEnv,
95 contents: &[u8],
96 path: &str,
97 honor_env_var: bool,
98 ) -> GitConfig {
99 let path = Path::new(path);
100 let mut file = File::create(path).unwrap();
101 file.write_all(contents).unwrap();
102 GitConfig::from_path(env, path, honor_env_var)
103 }
104
105 pub fn get_line_of_code_from_delta(
106 input: &str,
107 line_number: usize,
108 expected_text: &str,
109 config: &config::Config,
110 ) -> String {
111 let output = run_delta(input, config);
112 let line_of_code = output.lines().nth(line_number).unwrap();
113 assert!(ansi::strip_ansi_codes(line_of_code) == expected_text);
114 line_of_code.to_string()
115 }
116
117 // Given an `expected` block as a raw string like: `r#"
118 // #indent_mark [optional]
119 // line1"#;` // line 2 etc.
120 // ignore the first newline and compare the following `lines()` to those produced
121 // by `have`, `skip`-ping the first few. The leading spaces of the first line
122 // to indicate the last line in the list). The leading spaces of the first line
123 // are stripped from every following line (and verified), unless the first line
124 // marks the indentation level with `#indent_mark`.
125 pub fn assert_lines_match_after_skip(skip: usize, expected: &str, have: &str) {
126 let mut exp = expected.lines().peekable();
127 let mut line1 = exp.next().unwrap();
128 let allow_partial = line1 == "#partial";
129 assert!(
130 allow_partial || line1.is_empty(),
131 "first line must be empty or \"#partial\""
132 );
133 line1 = exp.peek().unwrap();
134 let indentation = line1.find(|c| c != ' ').unwrap_or(0);
135 let ignore_indent = &line1[indentation..] == "#indent_mark";
136 if ignore_indent {
137 let _indent_mark = exp.next();
138 }
139
140 let mut it = have.lines().skip(skip);
141
142 for (i, expected) in exp.enumerate() {
143 if !ignore_indent {
144 let next_indentation = expected.find(|c| c != ' ').unwrap_or(0);
145 assert!(
146 indentation == next_indentation,
147 "The expected block has mixed indentation (use #indent_mark if that is on purpose)"
148 );
149 }
150 assert_eq!(
151 &expected[indentation..],
152 it.next().unwrap(),
153 "on line {} of input:\n{}",
154 i + 1,
155 delineated_string(have),
156 );
157 }
158 if !allow_partial {
159 assert_eq!(it.next(), None, "more input than expected");
160 }
161 }
162
163 pub fn assert_lines_match(expected: &str, have: &str) {
164 assert_lines_match_after_skip(0, expected, have)
165 }
166
167 pub fn delineated_string(txt: &str) -> String {
168 let top = "▼".repeat(100);
169 let btm = "▲".repeat(100);
170 let nl = "\n";
171 top + nl + txt + nl + &btm
172 }
173
174 pub struct DeltaTest<'a> {
175 config: Cow<'a, config::Config>,
176 calling_process: Option<String>,
177 explain_ansi_: bool,
178 }
179
180 impl<'a> DeltaTest<'a> {
181 pub fn with_args(args: &[&str]) -> Self {
182 Self {
183 config: Cow::Owned(make_config_from_args(args)),
184 calling_process: None,
185 explain_ansi_: false,
186 }
187 }
188
189 pub fn with_config(config: &'a config::Config) -> Self {
190 Self {
191 config: Cow::Borrowed(config),
192 calling_process: None,
193 explain_ansi_: false,
194 }
195 }
196
197 pub fn set_config<F>(mut self, f: F) -> Self
198 where
199 F: Fn(&mut config::Config),
200 {
201 let mut owned_config = self.config.into_owned();
202 f(&mut owned_config);
203 self.config = Cow::Owned(owned_config);
204 self
205 }
206
207 pub fn with_calling_process(mut self, command: &str) -> Self {
208 self.calling_process = Some(command.to_string());
209 self
210 }
211
212 pub fn explain_ansi(mut self) -> Self {
213 self.explain_ansi_ = true;
214 self
215 }
216
217 pub fn with_input(&self, input: &str) -> DeltaTestOutput {
218 let _args = FakeParentArgs::for_scope(self.calling_process.as_deref().unwrap_or(""));
219 let raw = run_delta(input, &self.config);
220 let cooked = if self.explain_ansi_ {
221 ansi::explain_ansi(&raw, false)
222 } else {
223 ansi::strip_ansi_codes(&raw)
224 };
225
226 DeltaTestOutput {
227 raw_output: raw,
228 output: cooked,
229 }
230 }
231 }
232
233 pub struct DeltaTestOutput {
234 pub raw_output: String,
235 pub output: String,
236 }
237
238 impl DeltaTestOutput {
239 /// Print output, either without ANSI escape sequences or, if explain_ansi() has been called,
240 /// with ASCII explanation of ANSI escape sequences.
241 #[allow(unused)]
242 pub fn inspect(self) -> Self {
243 eprintln!("{}", delineated_string(&self.output));
244 self
245 }
246
247 /// Print raw output, with any ANSI escape sequences.
248 #[allow(unused)]
249 pub fn inspect_raw(self) -> Self {
250 eprintln!("{}", delineated_string(&self.raw_output));
251 self
252 }
253
254 pub fn expect_after_skip(self, skip: usize, expected: &str) -> Self {
255 assert_lines_match_after_skip(skip, expected, &self.output);
256 self
257 }
258
259 pub fn expect(self, expected: &str) -> Self {
260 self.expect_after_skip(0, expected)
261 }
262
263 pub fn expect_after_header(self, expected: &str) -> Self {
264 self.expect_after_skip(crate::config::HEADER_LEN, expected)
265 }
266
267 pub fn skip_header(self) -> String {
268 self.output.lines().skip(config::HEADER_LEN).join("\n")
269 }
270
271 pub fn expect_contains(self, expected: &str) -> Self {
272 assert!(
273 self.output.contains(expected),
274 "Output does not contain \"{}\":\n{}\n",
275 expected,
276 delineated_string(&self.output)
277 );
278 self
279 }
280
281 pub fn expect_raw_contains(self, expected: &str) -> Self {
282 assert!(
283 self.raw_output.contains(expected),
284 "Raw output does not contain \"{}\":\n{}\n",
285 expected,
286 delineated_string(&self.raw_output)
287 );
288 self
289 }
290
291 pub fn expect_contains_once(self, expected: &str) -> Self {
292 assert!(
293 test_utils::contains_once(&self.output, expected),
294 "Output does not contain \"{}\" exactly once:\n{}\n",
295 expected,
296 delineated_string(&self.output)
297 );
298 self
299 }
300 }
301
302 pub fn run_delta(input: &str, config: &config::Config) -> String {
303 let mut writer: Vec<u8> = Vec::new();
304
305 delta(
306 ByteLines::new(BufReader::new(input.as_bytes())),
307 &mut writer,
308 config,
309 )
310 .unwrap();
311 String::from_utf8(writer).unwrap()
312 }
313
314 pub mod tests {
315 use super::*;
316
317 #[test]
318 fn test_lines_match_ok() {
319 let expected = r#"
320 one
321 two
322 three"#;
323 assert_lines_match(expected, "one\ntwo\nthree");
324
325 let expected = r#"
326 #indent_mark
327 one
328 2
329 three"#;
330 assert_lines_match(expected, "one\n 2\nthree");
331
332 let expected = r#"
333 #indent_mark
334 1
335 2
336 3"#;
337 assert_lines_match(expected, " 1 \n 2 \n 3");
338
339 let expected = r#"
340 #indent_mark
341 1
342 ignored! 2
343 3"#;
344 assert_lines_match(expected, " 1 \n 2 \n 3");
345 let expected = "\none\ntwo\nthree";
346 assert_lines_match(expected, "one\ntwo\nthree");
347 }
348
349 #[test]
350 #[should_panic]
351 fn test_lines_match_no_nl() {
352 let expected = r#"bad
353 lines"#;
354 assert_lines_match(expected, "bad\nlines");
355 }
356
357 #[test]
358 #[should_panic]
359 fn test_lines_match_iter_not_consumed() {
360 let expected = r#"
361 one
362 two
363 three"#;
364 assert_lines_match(expected, "one\ntwo\nthree\nFOUR");
365 }
366
367 #[test]
368 #[should_panic]
369 fn test_lines_match_no_indent_mark_1() {
370 let expected = r#"
371 ok
372 wrong_indent
373 "#;
374 assert_lines_match(expected, "ok");
375 }
376
377 #[test]
378 #[should_panic]
379 fn test_lines_match_no_indent_mark_2() {
380 let expected = r#"
381 ok
382 wrong_indent
383 "#;
384 assert_lines_match(expected, "ok");
385 }
386
387 #[test]
388 fn test_delta_test() {
389 let input = "@@ -1,1 +1,1 @@ fn foo() {\n-1\n+2\n";
390 DeltaTest::with_args(&["--raw"])
391 .set_config(|c| c.pager = None)
392 .set_config(|c| c.line_numbers = true)
393 .with_input(input)
394 .expect(
395 r#"
396 #indent_mark
397 @@ -1,1 +1,1 @@ fn foo() {
398 1 ⋮ │-1
399 ⋮ 1 │+2"#,
400 );
401
402 DeltaTest::with_args(&[])
403 .with_input(input)
404 .expect_after_skip(
405 4,
406 r#"
407 1
408 2"#,
409 );
410
411 DeltaTest::with_args(&["--raw"])
412 .explain_ansi()
413 .with_input(input)
414 .expect(
415 "\n\
416 (normal)@@ -1,1 +1,1 @@ fn foo() {\n\
417 (red)-1(normal)\n\
418 (green)+2(normal)",
419 );
420 }
421 }