assert-text 0.3.0

the testing macro tools.
Documentation
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/*!
the testing macro tools.

This checks that strings are equal.
You will see different characters if that is different.

# Features

- assert_text_eq!(txt1, txt2)
- assert_text_contains!(txt1, txt2)
- assert_text_starts_with!(txt1, txt2)
- assert_text_ends_with!(txt1, txt2)
- assert_text_match!(txt1, regex_text2)
- supports custom panic messages
- minimum support rustc 1.65.0 (897e37553 2022-11-02)

*/

/// Asserts that two text expressions are equal.
///
/// If the texts are not equal, it prints a GitHub-style diff and panics.
///
/// # Arguments
///
/// * `$left` - The first text expression.
/// * `$right` - The second text expression.
///
/// # Examples
///
/// ```
/// use assert_text::assert_text_eq;
/// assert_text_eq!("hello", "hello");
/// ```
///
/// ```should_panic
/// use assert_text::assert_text_eq;
/// assert_text_eq!("hello", "world");
/// ```
///
/// ```should_panic
/// use assert_text::assert_text_eq;
/// assert_text_eq!("hello", "world", "custom message: {}", "foo");
/// ```
#[macro_export]
macro_rules! assert_text_eq {
    ($left: expr, $right: expr $(,)?) => {
        $crate::assert_text_eq!($left, $right, "assertion failed")
    };
    ($left: expr, $right: expr, $($arg:tt)+) => {
        match (&$left, &$right) {
            (left_val, right_val) => {
                let left_val: &str = left_val.as_ref();
                let right_val: &str = right_val.as_ref();
                if left_val != right_val {
                    $crate::print_diff_github_style(right_val, left_val);
                    panic!($($arg)+)
                }
            }
        }
    };
}

/// Asserts that the first text expression starts with the second text expression.
///
/// If the first text does not start with the second, it prints a GitHub-style diff
/// of the differing prefix and panics.
///
/// # Arguments
///
/// * `$left` - The text expression to check.
/// * `$right` - The prefix to check against.
///
/// # Examples
///
/// ```
/// use assert_text::assert_text_starts_with;
/// assert_text_starts_with!("hello world", "hello ");
/// ```
///
/// ```should_panic
/// use assert_text::assert_text_starts_with;
/// assert_text_starts_with!("hello world", "goodbye");
/// ```
///
/// ```should_panic
/// use assert_text::assert_text_starts_with;
/// assert_text_starts_with!("hello world", "goodbye", "custom message: {}", "foo");
/// ```
#[macro_export]
macro_rules! assert_text_starts_with {
    ($left: expr, $right: expr $(,)?) => {
        $crate::assert_text_starts_with!($left, $right, "assertion failed")
    };
    ($left: expr, $right: expr, $($arg:tt)+) => {
        match (&$left, &$right) {
            (left_val, right_val) => {
                let left_val: &str = left_val.as_ref();
                let right_val: &str = right_val.as_ref();
                if !left_val.starts_with(right_val) {
                    let right_chars = right_val.chars().count();
                    let limit = left_val
                        .char_indices()
                        .nth(right_chars)
                        .map(|(idx, _)| idx)
                        .unwrap_or_else(|| left_val.len());
                    let edit = &left_val[..limit];
                    $crate::print_diff_github_style(right_val, edit);
                    panic!($($arg)+)
                }
            }
        }
    };
}

/// Asserts that the first text expression ends with the second text expression.
///
/// If the first text does not end with the second, it prints a GitHub-style diff
/// of the differing suffix and panics.
///
/// # Arguments
///
/// * `$left` - The text expression to check.
/// * `$right` - The suffix to check against.
///
/// # Examples
///
/// ```
/// use assert_text::assert_text_ends_with;
/// assert_text_ends_with!("hello world", " world");
/// ```
///
/// ```should_panic
/// use assert_text::assert_text_ends_with;
/// assert_text_ends_with!("hello world", "goodbye");
/// ```
///
/// ```should_panic
/// use assert_text::assert_text_ends_with;
/// assert_text_ends_with!("hello world", "goodbye", "custom message: {}", "foo");
/// ```
#[macro_export]
macro_rules! assert_text_ends_with {
    ($left: expr, $right: expr $(,)?) => {
        $crate::assert_text_ends_with!($left, $right, "assertion failed")
    };
    ($left: expr, $right: expr, $($arg:tt)+) => {
        match (&$left, &$right) {
            (left_val, right_val) => {
                let left_val: &str = left_val.as_ref();
                let right_val: &str = right_val.as_ref();
                if !left_val.ends_with(right_val) {
                    let right_chars = right_val.chars().count();
                    let total_chars = left_val.chars().count();
                    let skip_chars = total_chars.saturating_sub(right_chars);
                    let limit = left_val
                        .char_indices()
                        .nth(skip_chars)
                        .map(|(idx, _)| idx)
                        .unwrap_or(0);
                    let edit = &left_val[limit..];
                    $crate::print_diff_github_style(right_val, edit);
                    panic!($($arg)+)
                }
            }
        }
    };
}

/// Asserts that the first text contains the given second text.
///
/// If the text does not contains second text, it panics.
///
/// # Arguments
///
/// * `$left` - The text expression to check.
/// * `$right` - The second text expression.
///
/// # Examples
///
/// ```
/// use assert_text::assert_text_contains;
/// assert_text_contains!("hello world", "o w");
/// ```
///
/// ```should_panic
/// use assert_text::assert_text_contains;
/// assert_text_contains!("hello world", "apple");
/// ```
///
/// ```should_panic
/// use assert_text::assert_text_contains;
/// assert_text_contains!("hello world", "apple", "custom message: {}", "foo");
/// ```
#[macro_export]
macro_rules! assert_text_contains {
    ($left: expr, $right: expr $(,)?) => {
        match (&$left, &$right) {
            (left_val, right_val) => {
                let left_val: &str = left_val.as_ref();
                let right_val: &str = right_val.as_ref();
                if !left_val.contains(right_val) {
                    $crate::assert_text_contains!(
                        left_val,
                        right_val,
                        concat!("assertion failed\n", "  left: \"{}\"\n", " right: \"{}\""),
                        left_val.escape_debug(),
                        right_val.escape_debug(),
                    )
                }
            }
        }
    };
    ($left: expr, $right: expr, $($arg:tt)+) => {
        match (&$left, &$right) {
            (left_val, right_val) => {
                let left_val: &str = left_val.as_ref();
                let right_val: &str = right_val.as_ref();
                if !left_val.contains(right_val) {
                    panic!($($arg)+);
                }
            }
        }
    };
}

/// Asserts that the first text expression matches the given regular expression.
///
/// If the text does not match the regex, it panics.
///
/// # Arguments
///
/// * `$left` - The text expression to check.
/// * `$right` - The regular expression string.
///
/// # Panics
///
/// Panics if the `$right` string is not a valid regular expression.
///
/// # Examples
///
/// ```
/// use assert_text::assert_text_match;
/// assert_text_match!("hello world", r"^h.+d$");
/// ```
///
/// ```should_panic
/// use assert_text::assert_text_match;
/// assert_text_match!("hello world", r"^goodbye.*");
/// ```
///
/// ```should_panic
/// use assert_text::assert_text_match;
/// assert_text_match!("hello world", r"^goodbye.*", "custom message: {}", "foo");
/// ```
#[macro_export]
macro_rules! assert_text_match {
    ($left: expr, $right: expr $(,)?) => {
        match (&$left, &$right) {
            (left_val, right_val) => {
                let left_val: &str = left_val.as_ref();
                let right_val: &str = right_val.as_ref();
                let re = regex::Regex::new(right_val).unwrap();
                if !re.is_match(left_val) {
                    $crate::assert_text_match!(
                        left_val,
                        right_val,
                        concat!("assertion failed\n", "  left: \"{}\"\n", " regex: \"{}\""),
                        left_val.escape_debug(),
                        right_val.escape_debug(),
                    )
                }
            }
        }
    };
    ($left: expr, $right: expr, $($arg:tt)+) => {
        match (&$left, &$right) {
            (left_val, right_val) => {
                let left_val: &str = left_val.as_ref();
                let right_val: &str = right_val.as_ref();
                let re = regex::Regex::new(right_val).unwrap();
                if !re.is_match(left_val) {
                    panic!($($arg)+);
                }
            }
        }
    };
}

use difference::{Changeset, Difference};

/// Prints a GitHub-style diff between two text slices to stdout.
///
/// This function highlights additions in green and removals in red.
///
/// # Arguments
///
/// * `text1` - The original text.
/// * `text2` - The modified text.
///
/// # Examples
///
/// ```
/// use assert_text::print_diff_github_style;
/// print_diff_github_style("hello world", "Hello orld");
/// ```
pub fn print_diff_github_style(text1: &str, text2: &str) {
    //
    let use_color = std::env::var("NO_COLOR").is_err();
    let color_green = if use_color { "\x1b[32m" } else { "" };
    let color_red = if use_color { "\x1b[31m" } else { "" };
    let color_bright_green = if use_color { "\x1b[1;32m" } else { "" };
    let color_reverse_red = if use_color { "\x1b[31;7m" } else { "" };
    let color_reverse_green = if use_color { "\x1b[32;7m" } else { "" };
    let color_end = if use_color { "\x1b[0m" } else { "" };
    //
    let mut out_s = String::new();
    //
    let Changeset { diffs, .. } = Changeset::new(text1, text2, "\n");
    //
    for i in 0..diffs.len() {
        let s = match diffs[i] {
            Difference::Same(ref y) => format_diff_line_same(y),
            Difference::Add(ref y) => {
                let opt = if i > 0 {
                    if let Difference::Rem(ref x) = diffs[i - 1] {
                        Some(format_diff_add_rem(
                            "+",
                            x,
                            y,
                            color_green,
                            color_reverse_green,
                            color_end,
                        ))
                    } else {
                        None
                    }
                } else {
                    None
                };
                match opt {
                    Some(a) => a,
                    None => format_diff_line_mark("+", y, color_bright_green, color_end),
                }
            }
            Difference::Rem(ref y) => {
                let opt = if i < diffs.len() - 1 {
                    if let Difference::Add(ref x) = diffs[i + 1] {
                        Some(format_diff_add_rem(
                            "-",
                            x,
                            y,
                            color_red,
                            color_reverse_red,
                            color_end,
                        ))
                    } else {
                        None
                    }
                } else {
                    None
                };
                match opt {
                    Some(a) => a,
                    None => format_diff_line_mark("-", y, color_red, color_end),
                }
            }
        };
        out_s.push_str(s.as_str());
    }
    //
    print!("{}", out_s.as_str());
}

/// Formats a line that is the same in both texts for diff output.
/// Prepends a space to the line.
#[inline(never)]
fn format_diff_line_same(y: &str) -> String {
    let mut s = String::with_capacity(y.len() + 2);
    for line in y.split_terminator('\n') {
        s.reserve(line.len() + 2);
        s.push(' ');
        s.push_str(line);
        s.push('\n');
    }
    s
}

/// Formats a line that is either added or removed, with a specific mark and color.
#[inline(never)]
fn format_diff_line_mark(
    mark: &str, // "+" or "-"
    y: &str,
    color_start: &str,
    color_end: &str,
) -> String {
    let line_count = y.split_terminator('\n').count();
    let extra_per_line = color_start.len() + mark.len() + color_end.len() + 1;
    let mut s = String::with_capacity(y.len() + (line_count * extra_per_line));
    for line in y.split_terminator('\n') {
        s.push_str(color_start);
        s.push_str(mark);
        s.push_str(line);
        s.push_str(color_end);
        s.push('\n');
    }
    s
}

/// Formats a line that has been changed (both added and removed parts) for diff output.
#[inline(never)]
fn format_diff_add_rem(
    mark: &str, // "+" or "-"
    x: &str,
    y: &str,
    color_fore: &str,
    color_reverse: &str,
    color_end: &str,
) -> String {
    //
    #[derive(PartialEq, Copy, Clone)]
    enum Cattr {
        None,
        Fore,
        Reve,
    }
    //
    let mut ca_v: Vec<(Cattr, &str)> = vec![(Cattr::Fore, mark)];
    //
    let changeset = Changeset::new(x, y, " ");
    for c in &changeset.diffs {
        match c {
            Difference::Same(ref z) => {
                for line in z.split_terminator('\n') {
                    ca_v.push((Cattr::Fore, line));
                    ca_v.push((Cattr::None, "\n"));
                    ca_v.push((Cattr::Fore, mark));
                }
                let bytes = z.as_bytes();
                let len = bytes.len();
                if len >= 1 && bytes[len - 1] != b'\n' {
                    ca_v.pop();
                    ca_v.pop();
                }
                ca_v.push((Cattr::Fore, " "));
            }
            Difference::Add(ref z) => {
                for line in z.split_terminator('\n') {
                    ca_v.push((Cattr::Reve, line));
                    ca_v.push((Cattr::None, "\n"));
                    ca_v.push((Cattr::Fore, mark));
                }
                let bytes = z.as_bytes();
                let len = bytes.len();
                if len >= 1 && bytes[len - 1] != b'\n' {
                    ca_v.pop();
                    ca_v.pop();
                }
                ca_v.push((Cattr::Fore, " "));
            }
            _ => {}
        };
    }
    //
    let mut out_s = String::with_capacity(x.len().max(y.len()) * 2);
    let mut prev_a: Cattr = Cattr::None;
    for (cat, st) in &ca_v {
        //
        if prev_a != *cat {
            if prev_a != Cattr::None {
                out_s.push_str(color_end)
            }
            if *cat == Cattr::Fore {
                out_s.push_str(color_fore);
            } else if *cat == Cattr::Reve {
                out_s.push_str(color_reverse);
            }
            prev_a = *cat;
        }
        out_s.push_str(st);
    }
    if prev_a != Cattr::None {
        out_s.push_str(color_end);
    }
    out_s.push('\n');
    //
    out_s
}