Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ exclude = [".github/", "bors.toml", "rustfmt.toml"]
[dependencies]
once_cell = "1"
dissimilar = "1"
regex = "1.5.4"
48 changes: 45 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ use std::{
};

use once_cell::sync::Lazy;
use regex::Regex;

const HELP: &str = "
You can update all `expect![[]]` tests by running:
Expand Down Expand Up @@ -274,13 +275,30 @@ impl Expect {
line_start += line.len();
}
let (literal_start, line_indent) = target_line.unwrap();
let literal_length =
file[literal_start..].find("]]").expect("Couldn't find matching `]]` for `expect![[`.");
let literal_range = literal_start..literal_start + literal_length;

let literal_end = locate_end(&file[literal_start..])
.expect("Couldn't find matching `]]` for `expect![[`.");

let literal_range = literal_start..literal_start + literal_end;
Location { line_indent, literal_range }
}
}

/// Returns the index of the end of the literal passed to `expect` in the input string.
fn locate_end(expect_invocation_to_eof: &str) -> Option<usize> {
static TRAILER: Lazy<Regex> = Lazy::new(|| Regex::new(r##""#*(\s*]])"##).unwrap());

// First, check for `expect![[]]` (no literal).
let mut chars = expect_invocation_to_eof.chars().skip_while(|c| c.is_whitespace());
if (']', ']') == (chars.next()?, chars.next()?) {
return Some(0);
}

let trailer = TRAILER.captures(expect_invocation_to_eof)?;
let literal_end = trailer.get(0).unwrap().end() - trailer[1].len();
Some(literal_end)
}

impl ExpectFile {
/// Checks if file contents is equal to `actual`.
pub fn assert_eq(&self, actual: &str) {
Expand Down Expand Up @@ -661,4 +679,28 @@ line1
"#]],
);
}

#[test]
fn test_locate() {
macro_rules! check_locate {
($( [[$s:literal]] ),* $(,)?) => {$({
let lit = stringify!($s);
let with_trailer = format!("{} \t]]\n", lit);
assert_eq!(locate_end(&with_trailer), Some(lit.len()));
})*};
}

// Check that we handle string literals containing "]]" correctly.
check_locate!(
[[r#"{ arr: [[1, 2], [3, 4]], other: "foo" } "#]],

// We don't actually parse string literals, so these cases fail.
// [["]]"]],
// [["\"]]"]],
// [[r#""]]"#]],
);

// Check `expect![[ ]]` as well.
assert_eq!(locate_end(" ]]"), Some(0));
}
}