5835: Switch to expect_test from crates.io
 r=matklad a=matklad

bors r+
🤖

Co-authored-by: Aleksey Kladov <aleksey.kladov@gmail.com>
This commit is contained in:
bors[bot] 2020-08-21 11:21:05 +00:00 committed by GitHub
commit df54561a68
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
47 changed files with 54 additions and 425 deletions

19
Cargo.lock generated
View file

@ -345,12 +345,13 @@ dependencies = [
]
[[package]]
name = "expect"
version = "0.0.0"
name = "expect-test"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3e383741ea1982866572109d1a8c807bd36aad91fca701489fdca56ef92b3b8"
dependencies = [
"difference",
"once_cell",
"stdx",
]
[[package]]
@ -508,7 +509,7 @@ dependencies = [
"cfg",
"drop_bomb",
"either",
"expect",
"expect-test",
"fst",
"hir_expand",
"indexmap",
@ -553,7 +554,7 @@ dependencies = [
"chalk-recursive",
"chalk-solve",
"ena",
"expect",
"expect-test",
"hir_def",
"hir_expand",
"itertools",
@ -587,7 +588,7 @@ dependencies = [
"base_db",
"cfg",
"either",
"expect",
"expect-test",
"hir",
"ide_db",
"indexmap",
@ -1225,7 +1226,7 @@ dependencies = [
"cfg",
"crossbeam-channel",
"env_logger",
"expect",
"expect-test",
"flycheck",
"hir",
"hir_def",
@ -1452,7 +1453,7 @@ name = "ssr"
version = "0.0.0"
dependencies = [
"base_db",
"expect",
"expect-test",
"hir",
"ide_db",
"itertools",
@ -1494,7 +1495,7 @@ name = "syntax"
version = "0.0.0"
dependencies = [
"arrayvec",
"expect",
"expect-test",
"itertools",
"once_cell",
"parser",

View file

@ -1,15 +0,0 @@
[package]
name = "expect"
version = "0.0.0"
license = "MIT OR Apache-2.0"
authors = ["rust-analyzer developers"]
edition = "2018"
[lib]
doctest = false
[dependencies]
once_cell = "1"
difference = "2"
stdx = { path = "../stdx" }

View file

@ -1,356 +0,0 @@
//! Snapshot testing library, see
//! https://github.com/rust-analyzer/rust-analyzer/pull/5101
use std::{
collections::HashMap,
env, fmt, fs, mem,
ops::Range,
panic,
path::{Path, PathBuf},
sync::Mutex,
};
use difference::Changeset;
use once_cell::sync::Lazy;
use stdx::{lines_with_ends, trim_indent};
const HELP: &str = "
You can update all `expect![[]]` tests by running:
env UPDATE_EXPECT=1 cargo test
To update a single test, place the cursor on `expect` token and use `run` feature of rust-analyzer.
";
fn update_expect() -> bool {
env::var("UPDATE_EXPECT").is_ok()
}
/// expect![[r#"inline snapshot"#]]
#[macro_export]
macro_rules! expect {
[[$data:literal]] => {$crate::Expect {
position: $crate::Position {
file: file!(),
line: line!(),
column: column!(),
},
data: $data,
}};
[[]] => { $crate::expect![[""]] };
}
/// expect_file!["/crates/foo/test_data/bar.html"]
#[macro_export]
macro_rules! expect_file {
[$path:expr] => {$crate::ExpectFile {
path: std::path::PathBuf::from($path)
}};
}
#[derive(Debug)]
pub struct Expect {
pub position: Position,
pub data: &'static str,
}
#[derive(Debug)]
pub struct ExpectFile {
pub path: PathBuf,
}
#[derive(Debug)]
pub struct Position {
pub file: &'static str,
pub line: u32,
pub column: u32,
}
impl fmt::Display for Position {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}:{}", self.file, self.line, self.column)
}
}
impl Expect {
pub fn assert_eq(&self, actual: &str) {
let trimmed = self.trimmed();
if trimmed == actual {
return;
}
Runtime::fail_expect(self, &trimmed, actual);
}
pub fn assert_debug_eq(&self, actual: &impl fmt::Debug) {
let actual = format!("{:#?}\n", actual);
self.assert_eq(&actual)
}
fn trimmed(&self) -> String {
if !self.data.contains('\n') {
return self.data.to_string();
}
trim_indent(self.data)
}
fn locate(&self, file: &str) -> Location {
let mut target_line = None;
let mut line_start = 0;
for (i, line) in lines_with_ends(file).enumerate() {
if i == self.position.line as usize - 1 {
let pat = "expect![[";
let offset = line.find(pat).unwrap();
let literal_start = line_start + offset + pat.len();
let indent = line.chars().take_while(|&it| it == ' ').count();
target_line = Some((literal_start, indent));
break;
}
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;
Location { line_indent, literal_range }
}
}
impl ExpectFile {
pub fn assert_eq(&self, actual: &str) {
let expected = self.read();
if actual == expected {
return;
}
Runtime::fail_file(self, &expected, actual);
}
pub fn assert_debug_eq(&self, actual: &impl fmt::Debug) {
let actual = format!("{:#?}\n", actual);
self.assert_eq(&actual)
}
fn read(&self) -> String {
fs::read_to_string(self.abs_path()).unwrap_or_default().replace("\r\n", "\n")
}
fn write(&self, contents: &str) {
fs::write(self.abs_path(), contents).unwrap()
}
fn abs_path(&self) -> PathBuf {
WORKSPACE_ROOT.join(&self.path)
}
}
#[derive(Default)]
struct Runtime {
help_printed: bool,
per_file: HashMap<&'static str, FileRuntime>,
}
static RT: Lazy<Mutex<Runtime>> = Lazy::new(Default::default);
impl Runtime {
fn fail_expect(expect: &Expect, expected: &str, actual: &str) {
let mut rt = RT.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if update_expect() {
println!("\x1b[1m\x1b[92mupdating\x1b[0m: {}", expect.position);
rt.per_file
.entry(expect.position.file)
.or_insert_with(|| FileRuntime::new(expect))
.update(expect, actual);
return;
}
rt.panic(expect.position.to_string(), expected, actual);
}
fn fail_file(expect: &ExpectFile, expected: &str, actual: &str) {
let mut rt = RT.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if update_expect() {
println!("\x1b[1m\x1b[92mupdating\x1b[0m: {}", expect.path.display());
expect.write(actual);
return;
}
rt.panic(expect.path.display().to_string(), expected, actual);
}
fn panic(&mut self, position: String, expected: &str, actual: &str) {
let print_help = !mem::replace(&mut self.help_printed, true);
let help = if print_help { HELP } else { "" };
let diff = Changeset::new(actual, expected, "\n");
println!(
"\n
\x1b[1m\x1b[91merror\x1b[97m: expect test failed\x1b[0m
\x1b[1m\x1b[34m-->\x1b[0m {}
{}
\x1b[1mExpect\x1b[0m:
----
{}
----
\x1b[1mActual\x1b[0m:
----
{}
----
\x1b[1mDiff\x1b[0m:
----
{}
----
",
position, help, expected, actual, diff
);
// Use resume_unwind instead of panic!() to prevent a backtrace, which is unnecessary noise.
panic::resume_unwind(Box::new(()));
}
}
struct FileRuntime {
path: PathBuf,
original_text: String,
patchwork: Patchwork,
}
impl FileRuntime {
fn new(expect: &Expect) -> FileRuntime {
let path = WORKSPACE_ROOT.join(expect.position.file);
let original_text = fs::read_to_string(&path).unwrap();
let patchwork = Patchwork::new(original_text.clone());
FileRuntime { path, original_text, patchwork }
}
fn update(&mut self, expect: &Expect, actual: &str) {
let loc = expect.locate(&self.original_text);
let patch = format_patch(loc.line_indent.clone(), actual);
self.patchwork.patch(loc.literal_range, &patch);
fs::write(&self.path, &self.patchwork.text).unwrap()
}
}
#[derive(Debug)]
struct Location {
line_indent: usize,
literal_range: Range<usize>,
}
#[derive(Debug)]
struct Patchwork {
text: String,
indels: Vec<(Range<usize>, usize)>,
}
impl Patchwork {
fn new(text: String) -> Patchwork {
Patchwork { text, indels: Vec::new() }
}
fn patch(&mut self, mut range: Range<usize>, patch: &str) {
self.indels.push((range.clone(), patch.len()));
self.indels.sort_by_key(|(delete, _insert)| delete.start);
let (delete, insert) = self
.indels
.iter()
.take_while(|(delete, _)| delete.start < range.start)
.map(|(delete, insert)| (delete.end - delete.start, insert))
.fold((0usize, 0usize), |(x1, y1), (x2, y2)| (x1 + x2, y1 + y2));
for pos in &mut [&mut range.start, &mut range.end] {
**pos -= delete;
**pos += insert;
}
self.text.replace_range(range, &patch);
}
}
fn format_patch(line_indent: usize, patch: &str) -> String {
let mut max_hashes = 0;
let mut cur_hashes = 0;
for byte in patch.bytes() {
if byte != b'#' {
cur_hashes = 0;
continue;
}
cur_hashes += 1;
max_hashes = max_hashes.max(cur_hashes);
}
let hashes = &"#".repeat(max_hashes + 1);
let indent = &" ".repeat(line_indent);
let is_multiline = patch.contains('\n');
let mut buf = String::new();
buf.push('r');
buf.push_str(hashes);
buf.push('"');
if is_multiline {
buf.push('\n');
}
let mut final_newline = false;
for line in lines_with_ends(patch) {
if is_multiline && !line.trim().is_empty() {
buf.push_str(indent);
buf.push_str(" ");
}
buf.push_str(line);
final_newline = line.ends_with('\n');
}
if final_newline {
buf.push_str(indent);
}
buf.push('"');
buf.push_str(hashes);
buf
}
static WORKSPACE_ROOT: Lazy<PathBuf> = Lazy::new(|| {
let my_manifest =
env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| env!("CARGO_MANIFEST_DIR").to_owned());
// Heuristic, see https://github.com/rust-lang/cargo/issues/3946
Path::new(&my_manifest)
.ancestors()
.filter(|it| it.join("Cargo.toml").exists())
.last()
.unwrap()
.to_path_buf()
});
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_format_patch() {
let patch = format_patch(0, "hello\nworld\n");
expect![[r##"
r#"
hello
world
"#"##]]
.assert_eq(&patch);
let patch = format_patch(4, "single line");
expect![[r##"r#"single line"#"##]].assert_eq(&patch);
}
#[test]
fn test_patchwork() {
let mut patchwork = Patchwork::new("one two three".to_string());
patchwork.patch(4..7, "zwei");
patchwork.patch(0..3, "один");
patchwork.patch(8..13, "3");
expect![[r#"
Patchwork {
text: "один zwei 3",
indels: [
(
0..3,
8,
),
(
4..7,
4,
),
(
8..13,
1,
),
],
}
"#]]
.assert_debug_eq(&patchwork);
}
}

View file

@ -32,4 +32,4 @@ cfg = { path = "../cfg" }
tt = { path = "../tt" }
[dev-dependencies]
expect = { path = "../expect" }
expect-test = "0.1"

View file

@ -328,7 +328,7 @@ pub fn search_dependencies<'a>(
#[cfg(test)]
mod tests {
use base_db::{fixture::WithFixture, SourceDatabase, Upcast};
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use crate::{test_db::TestDB, AssocContainerId, Lookup};

View file

@ -1,5 +1,5 @@
use base_db::fixture::WithFixture;
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use hir_expand::{db::AstDatabase, HirFileId, InFile};
use rustc_hash::FxHashSet;
use std::sync::Arc;

View file

@ -7,7 +7,7 @@ mod primitives;
use std::sync::Arc;
use base_db::{fixture::WithFixture, SourceDatabase};
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use test_utils::mark;
use crate::{db::DefDatabase, nameres::*, test_db::TestDB};

View file

@ -30,8 +30,7 @@ syntax = { path = "../syntax" }
test_utils = { path = "../test_utils" }
[dev-dependencies]
expect-test = "0.1"
tracing = "0.1"
tracing-subscriber = { version = "0.2", default-features = false, features = ["env-filter", "registry"] }
tracing-tree = { version = "0.1.4" }
expect = { path = "../expect" }

View file

@ -11,7 +11,7 @@ mod display_source_code;
use std::{env, sync::Arc};
use base_db::{fixture::WithFixture, FileRange, SourceDatabase, SourceDatabaseExt};
use expect::Expect;
use expect_test::Expect;
use hir_def::{
body::{BodySourceMap, SyntheticSyntax},
child_by_source::ChildBySource,

View file

@ -1,4 +1,4 @@
use expect::expect;
use expect_test::expect;
use test_utils::mark;
use super::{check_infer, check_infer_with_mismatches};

View file

@ -1,6 +1,6 @@
use std::fs;
use expect::expect;
use expect_test::expect;
use test_utils::project_dir;
use super::{check_infer, check_types};

View file

@ -1,4 +1,4 @@
use expect::expect;
use expect_test::expect;
use super::{check_infer, check_types};

View file

@ -1,4 +1,4 @@
use expect::expect;
use expect_test::expect;
use super::{check_infer_with_mismatches, check_types};

View file

@ -1,4 +1,4 @@
use expect::expect;
use expect_test::expect;
use test_utils::mark;
use super::{check_infer, check_infer_with_mismatches};

View file

@ -1,4 +1,4 @@
use expect::expect;
use expect_test::expect;
use test_utils::mark;
use super::{check_infer, check_types};

View file

@ -1,4 +1,4 @@
use expect::expect;
use expect_test::expect;
use super::{check_infer, check_types};

View file

@ -1,4 +1,4 @@
use expect::expect;
use expect_test::expect;
use test_utils::mark;
use super::{check_infer, check_infer_with_mismatches, check_types};

View file

@ -32,4 +32,4 @@ ssr = { path = "../ssr" }
hir = { path = "../hir" }
[dev-dependencies]
expect = { path = "../expect" }
expect-test = "0.1"

View file

@ -229,7 +229,7 @@ impl FnCallNode {
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use test_utils::mark;
use crate::mock_analysis::analysis_and_position;

View file

@ -383,7 +383,7 @@ const DEFAULT_LINT_COMPLETIONS: &[LintCompletion] = &[
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use crate::completion::{test_utils::completion_list, CompletionKind};

View file

@ -61,7 +61,7 @@ fn complete_methods(acc: &mut Completions, ctx: &CompletionContext, receiver: &T
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use test_utils::mark;
use crate::completion::{test_utils::completion_list, CompletionKind};

View file

@ -66,7 +66,7 @@ pub(super) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext)
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use crate::completion::{test_utils::completion_list, CompletionKind};

View file

@ -174,7 +174,7 @@ fn complete_return(
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use crate::completion::{
test_utils::{check_edit, completion_list},

View file

@ -15,7 +15,7 @@ pub(super) fn complete_macro_in_item_position(acc: &mut Completions, ctx: &Compl
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use crate::completion::{test_utils::completion_list, CompletionKind};

View file

@ -33,7 +33,7 @@ pub(super) fn complete_pattern(acc: &mut Completions, ctx: &CompletionContext) {
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use crate::completion::{test_utils::completion_list, CompletionKind};

View file

@ -238,7 +238,7 @@ fn postfix_snippet(
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use crate::completion::{
test_utils::{check_edit, completion_list},

View file

@ -146,7 +146,7 @@ pub(super) fn complete_qualified_path(acc: &mut Completions, ctx: &CompletionCon
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use test_utils::mark;
use crate::completion::{

View file

@ -18,7 +18,7 @@ pub(super) fn complete_record(acc: &mut Completions, ctx: &CompletionContext) ->
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use crate::completion::{test_utils::completion_list, CompletionKind};

View file

@ -70,7 +70,7 @@ fn ${1:feature}() {
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use crate::completion::{test_utils::completion_list, CompletionKind};

View file

@ -225,7 +225,7 @@ fn make_const_compl_syntax(const_: &ast::Const) -> String {
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use crate::completion::{
test_utils::{check_edit, completion_list},

View file

@ -64,7 +64,7 @@ fn complete_enum_variants(acc: &mut Completions, ctx: &CompletionContext, ty: &T
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use test_utils::mark;
use crate::completion::{

View file

@ -464,7 +464,7 @@ fn guess_macro_braces(macro_name: &str, docs: &str) -> (&'static str, &'static s
mod tests {
use std::cmp::Reverse;
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use test_utils::mark;
use crate::{

View file

@ -214,7 +214,7 @@ fn check_struct_shorthand_initialization(
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use stdx::trim_indent;
use test_utils::assert_eq_text;

View file

@ -421,7 +421,7 @@ pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) ->
#[cfg(test)]
mod tests {
use expect::expect;
use expect_test::expect;
use crate::{mock_analysis::single_file, Query};

View file

@ -120,7 +120,7 @@ fn insert_whitespaces(syn: SyntaxNode) -> String {
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use crate::mock_analysis::analysis_and_position;

View file

@ -164,7 +164,7 @@ fn structure_node(node: &SyntaxNode) -> Option<StructureNode> {
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use super::*;

View file

@ -353,7 +353,7 @@ fn pick_best(tokens: TokenAtOffset<SyntaxToken>) -> Option<SyntaxToken> {
#[cfg(test)]
mod tests {
use base_db::FileLoader;
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use crate::mock_analysis::analysis_and_position;

View file

@ -336,7 +336,7 @@ fn get_callable(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<Call
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use test_utils::extract_annotations;
use crate::{inlay_hints::InlayHintsConfig, mock_analysis::single_file};

View file

@ -270,7 +270,7 @@ fn rename_reference(
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use stdx::trim_indent;
use test_utils::{assert_eq_text, mark};
use text_edit::TextEdit;

View file

@ -268,7 +268,7 @@ fn has_test_function_or_multiple_test_submodules(module: &ast::Module) -> bool {
#[cfg(test)]
mod tests {
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use crate::mock_analysis::analysis_and_position;

View file

@ -1,6 +1,6 @@
use std::fs;
use expect::{expect_file, ExpectFile};
use expect_test::{expect_file, ExpectFile};
use test_utils::project_dir;
use crate::{mock_analysis::single_file, FileRange, TextRange};

View file

@ -57,7 +57,7 @@ proc_macro_srv = { path = "../proc_macro_srv" }
winapi = "0.3.8"
[dev-dependencies]
expect = { path = "../expect" }
expect-test = "0.1"
test_utils = { path = "../test_utils" }
mbe = { path = "../mbe" }
tt = { path = "../tt" }

View file

@ -256,7 +256,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
mod tests {
use super::*;
use expect::{expect_file, ExpectFile};
use expect_test::{expect_file, ExpectFile};
fn check(diagnostics_json: &str, expect: ExpectFile) {
check_with_config(DiagnosticsMapConfig::default(), diagnostics_json, expect)

View file

@ -22,4 +22,4 @@ hir = { path = "../hir" }
test_utils = { path = "../test_utils" }
[dev-dependencies]
expect = { path = "../expect" }
expect-test = "0.1"

View file

@ -1,6 +1,6 @@
use crate::{MatchFinder, SsrRule};
use base_db::{salsa::Durability, FileId, FilePosition, FileRange, SourceDatabaseExt};
use expect::{expect, Expect};
use expect_test::{expect, Expect};
use rustc_hash::FxHashSet;
use std::sync::Arc;
use test_utils::{mark, RangeOrOffset};

View file

@ -30,6 +30,6 @@ parser = { path = "../parser" }
[dev-dependencies]
walkdir = "2.3.1"
rayon = "1"
expect-test = "0.1"
test_utils = { path = "../test_utils" }
expect = { path = "../expect" }

View file

@ -4,7 +4,7 @@ use std::{
path::{Path, PathBuf},
};
use expect::expect_file;
use expect_test::expect_file;
use rayon::prelude::*;
use test_utils::project_dir;