Skip to content

Commit 6fd2965

Browse files
bors[bot]Veetaha
andauthored
Merge #2931
2931: Added documentation to test_utils r=matklad a=Veetaha Added some doc comments to test_utils functions while studying this crate. They should be all stable enough to document them. Also some minor code relocation in `parse_fixture()` closer to its usage according to the advice of @matklad. Co-authored-by: Veetaha <gerzoh1@gmail.com>
2 parents 7a2b87d + 5e1ae1d commit 6fd2965

File tree

2 files changed

+56
-24
lines changed

2 files changed

+56
-24
lines changed

crates/test_utils/src/lib.rs

Lines changed: 55 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ pub use difference::Changeset as __Changeset;
2121

2222
pub const CURSOR_MARKER: &str = "<|>";
2323

24+
/// Asserts that two strings are equal, otherwise displays a rich diff between them.
25+
///
26+
/// The diff shows changes from the "original" left string to the "actual" right string.
27+
///
28+
/// All arguments starting from and including the 3rd one are passed to
29+
/// `eprintln!()` macro in case of text inequality.
2430
#[macro_export]
2531
macro_rules! assert_eq_text {
2632
($left:expr, $right:expr) => {
@@ -42,13 +48,16 @@ macro_rules! assert_eq_text {
4248
}};
4349
}
4450

51+
/// Infallible version of `try_extract_offset()`.
4552
pub fn extract_offset(text: &str) -> (TextUnit, String) {
4653
match try_extract_offset(text) {
4754
None => panic!("text should contain cursor marker"),
4855
Some(result) => result,
4956
}
5057
}
5158

59+
/// Returns the offset of the first occurence of `<|>` marker and the copy of `text`
60+
/// without the marker.
5261
fn try_extract_offset(text: &str) -> Option<(TextUnit, String)> {
5362
let cursor_pos = text.find(CURSOR_MARKER)?;
5463
let mut new_text = String::with_capacity(text.len() - CURSOR_MARKER.len());
@@ -58,13 +67,16 @@ fn try_extract_offset(text: &str) -> Option<(TextUnit, String)> {
5867
Some((cursor_pos, new_text))
5968
}
6069

70+
/// Infallible version of `try_extract_range()`.
6171
pub fn extract_range(text: &str) -> (TextRange, String) {
6272
match try_extract_range(text) {
6373
None => panic!("text should contain cursor marker"),
6474
Some(result) => result,
6575
}
6676
}
6777

78+
/// Returns `TextRange` between the first two markers `<|>...<|>` and the copy
79+
/// of `text` without both of these markers.
6880
fn try_extract_range(text: &str) -> Option<(TextRange, String)> {
6981
let (start, text) = try_extract_offset(text)?;
7082
let (end, text) = try_extract_offset(&text)?;
@@ -85,6 +97,11 @@ impl From<RangeOrOffset> for TextRange {
8597
}
8698
}
8799

100+
/// Extracts `TextRange` or `TextUnit` depending on the amount of `<|>` markers
101+
/// found in `text`.
102+
///
103+
/// # Panics
104+
/// Panics if no `<|>` marker is present in the `text`.
88105
pub fn extract_range_or_offset(text: &str) -> (RangeOrOffset, String) {
89106
if let Some((range, text)) = try_extract_range(text) {
90107
return (RangeOrOffset::Range(range), text);
@@ -93,7 +110,7 @@ pub fn extract_range_or_offset(text: &str) -> (RangeOrOffset, String) {
93110
(RangeOrOffset::Offset(offset), text)
94111
}
95112

96-
/// Extracts ranges, marked with `<tag> </tag>` paris from the `text`
113+
/// Extracts ranges, marked with `<tag> </tag>` pairs from the `text`
97114
pub fn extract_ranges(mut text: &str, tag: &str) -> (Vec<TextRange>, String) {
98115
let open = format!("<{}>", tag);
99116
let close = format!("</{}>", tag);
@@ -127,9 +144,9 @@ pub fn extract_ranges(mut text: &str, tag: &str) -> (Vec<TextRange>, String) {
127144
(ranges, res)
128145
}
129146

147+
/// Inserts `<|>` marker into the `text` at `offset`.
130148
pub fn add_cursor(text: &str, offset: TextUnit) -> String {
131-
let offset: u32 = offset.into();
132-
let offset: usize = offset as usize;
149+
let offset: usize = offset.to_usize();
133150
let mut res = String::new();
134151
res.push_str(&text[..offset]);
135152
res.push_str("<|>");
@@ -152,19 +169,6 @@ pub struct FixtureEntry {
152169
/// // - other meta
153170
/// ```
154171
pub fn parse_fixture(fixture: &str) -> Vec<FixtureEntry> {
155-
let mut res = Vec::new();
156-
let mut buf = String::new();
157-
let mut meta: Option<&str> = None;
158-
159-
macro_rules! flush {
160-
() => {
161-
if let Some(meta) = meta {
162-
res.push(FixtureEntry { meta: meta.to_string(), text: buf.clone() });
163-
buf.clear();
164-
}
165-
};
166-
};
167-
168172
let margin = fixture
169173
.lines()
170174
.filter(|it| it.trim_start().starts_with("//-"))
@@ -184,6 +188,19 @@ pub fn parse_fixture(fixture: &str) -> Vec<FixtureEntry> {
184188
}
185189
});
186190

191+
let mut res = Vec::new();
192+
let mut buf = String::new();
193+
let mut meta: Option<&str> = None;
194+
195+
macro_rules! flush {
196+
() => {
197+
if let Some(meta) = meta {
198+
res.push(FixtureEntry { meta: meta.to_string(), text: buf.clone() });
199+
buf.clear();
200+
}
201+
};
202+
};
203+
187204
for line in lines {
188205
if line.starts_with("//-") {
189206
flush!();
@@ -236,11 +253,10 @@ fn lines_match_works() {
236253
assert!(!lines_match("b", "cb"));
237254
}
238255

239-
// Compares JSON object for approximate equality.
240-
// You can use `[..]` wildcard in strings (useful for OS dependent things such
241-
// as paths). You can use a `"{...}"` string literal as a wildcard for
242-
// arbitrary nested JSON (useful for parts of object emitted by other programs
243-
// (e.g. rustc) rather than Cargo itself). Arrays are sorted before comparison.
256+
/// Compares JSON object for approximate equality.
257+
/// You can use `[..]` wildcard in strings (useful for OS dependent things such
258+
/// as paths). You can use a `"{...}"` string literal as a wildcard for
259+
/// arbitrary nested JSON. Arrays are sorted before comparison.
244260
pub fn find_mismatch<'a>(expected: &'a Value, actual: &'a Value) -> Option<(&'a Value, &'a Value)> {
245261
use serde_json::Value::*;
246262
match (expected, actual) {
@@ -286,6 +302,14 @@ pub fn find_mismatch<'a>(expected: &'a Value, actual: &'a Value) -> Option<(&'a
286302
}
287303
}
288304

305+
/// Calls callback `f` with input code and file paths of all `.rs` files from `test_data_dir`
306+
/// subdirectories defined by `paths`.
307+
///
308+
/// If the content of the matching `.txt` file differs from the output of `f()`
309+
/// the test will fail.
310+
///
311+
/// If there is no matching `.txt` file it will be created and filled with the
312+
/// output of `f()`, but the test will fail.
289313
pub fn dir_tests<F>(test_data_dir: &Path, paths: &[&str], f: F)
290314
where
291315
F: Fn(&str, &Path) -> String,
@@ -307,6 +331,7 @@ where
307331
}
308332
}
309333

334+
/// Collects all `.rs` files from `test_data_dir` subdirectories defined by `paths`.
310335
pub fn collect_tests(test_data_dir: &Path, paths: &[&str]) -> Vec<(PathBuf, String)> {
311336
paths
312337
.iter()
@@ -321,6 +346,7 @@ pub fn collect_tests(test_data_dir: &Path, paths: &[&str]) -> Vec<(PathBuf, Stri
321346
.collect()
322347
}
323348

349+
/// Collects paths to all `.rs` files from `dir` in a sorted `Vec<PathBuf>`.
324350
fn test_from_dir(dir: &Path) -> Vec<PathBuf> {
325351
let mut acc = Vec::new();
326352
for file in fs::read_dir(&dir).unwrap() {
@@ -334,6 +360,7 @@ fn test_from_dir(dir: &Path) -> Vec<PathBuf> {
334360
acc
335361
}
336362

363+
/// Returns the path to the root directory of `rust-analyzer` project.
337364
pub fn project_dir() -> PathBuf {
338365
let dir = env!("CARGO_MANIFEST_DIR");
339366
PathBuf::from(dir).parent().unwrap().parent().unwrap().to_owned()
@@ -356,6 +383,9 @@ pub fn read_text(path: &Path) -> String {
356383
.replace("\r\n", "\n")
357384
}
358385

386+
/// Returns `false` if slow tests should not run, otherwise returns `true` and
387+
/// also creates a file at `./target/.slow_tests_cookie` which serves as a flag
388+
/// that slow tests did run.
359389
pub fn skip_slow_tests() -> bool {
360390
let should_skip = std::env::var("CI").is_err() && std::env::var("RUN_SLOW_TESTS").is_err();
361391
if should_skip {
@@ -367,8 +397,9 @@ pub fn skip_slow_tests() -> bool {
367397
should_skip
368398
}
369399

370-
const REWRITE: bool = false;
371-
400+
/// Asserts that `expected` and `actual` strings are equal. If they differ only
401+
/// in trailing or leading whitespace the test won't fail and
402+
/// the contents of `actual` will be written to the file located at `path`.
372403
fn assert_equal_text(expected: &str, actual: &str, path: &Path) {
373404
if expected == actual {
374405
return;
@@ -381,6 +412,7 @@ fn assert_equal_text(expected: &str, actual: &str, path: &Path) {
381412
fs::write(path, actual).unwrap();
382413
return;
383414
}
415+
const REWRITE: bool = false;
384416
if REWRITE {
385417
println!("rewriting {}", pretty_path.display());
386418
fs::write(path, actual).unwrap();

crates/test_utils/src/marks.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//! This module implements manually tracked test coverage, which useful for
1+
//! This module implements manually tracked test coverage, which is useful for
22
//! quickly finding a test responsible for testing a particular bit of code.
33
//!
44
//! See <https://matklad.github.io/2018/06/18/a-trick-for-test-maintenance.html>

0 commit comments

Comments
 (0)