aboutsummaryrefslogtreecommitdiff
path: root/crates/test_utils/src/fixture.rs
diff options
context:
space:
mode:
authorbors[bot] <26634292+bors[bot]@users.noreply.github.com>2020-06-23 19:39:58 +0100
committerGitHub <[email protected]>2020-06-23 19:39:58 +0100
commit9caf810129589327cc614936a97a10cedc6f03a9 (patch)
treea3fc00ca2a19fa1294cf93030ff0d4a8d80f647f /crates/test_utils/src/fixture.rs
parent0c12c4f9609ee72487af9b55a558b01af73ffe3e (diff)
parent295c8d4f7f9ce9d3dc67e8a988914d90424c1b7e (diff)
Merge #5011
5011: Simplify fixtures r=matklad a=matklad bors r+ 🤖 Co-authored-by: Aleksey Kladov <[email protected]>
Diffstat (limited to 'crates/test_utils/src/fixture.rs')
-rw-r--r--crates/test_utils/src/fixture.rs216
1 files changed, 216 insertions, 0 deletions
diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs
new file mode 100644
index 000000000..9108e49d9
--- /dev/null
+++ b/crates/test_utils/src/fixture.rs
@@ -0,0 +1,216 @@
1//! Defines `Fixture` -- a convenient way to describe the initial state of
2//! rust-analyzer database from a single string.
3
4use rustc_hash::FxHashMap;
5use stdx::split1;
6
7#[derive(Debug, Eq, PartialEq)]
8pub struct Fixture {
9 pub path: String,
10 pub text: String,
11 pub crate_name: Option<String>,
12 pub deps: Vec<String>,
13 pub cfg_atoms: Vec<String>,
14 pub cfg_key_values: Vec<(String, String)>,
15 pub edition: Option<String>,
16 pub env: FxHashMap<String, String>,
17}
18
19impl Fixture {
20 /// Parses text which looks like this:
21 ///
22 /// ```not_rust
23 /// //- some meta
24 /// line 1
25 /// line 2
26 /// // - other meta
27 /// ```
28 pub fn parse(ra_fixture: &str) -> Vec<Fixture> {
29 let fixture = indent_first_line(ra_fixture);
30 let margin = fixture_margin(&fixture);
31
32 let mut lines = fixture
33 .split('\n') // don't use `.lines` to not drop `\r\n`
34 .enumerate()
35 .filter_map(|(ix, line)| {
36 if line.len() >= margin {
37 assert!(line[..margin].trim().is_empty());
38 let line_content = &line[margin..];
39 if !line_content.starts_with("//-") {
40 assert!(
41 !line_content.contains("//-"),
42 r#"Metadata line {} has invalid indentation. All metadata lines need to have the same indentation.
43The offending line: {:?}"#,
44 ix,
45 line
46 );
47 }
48 Some(line_content)
49 } else {
50 assert!(line.trim().is_empty());
51 None
52 }
53 });
54
55 let mut res: Vec<Fixture> = Vec::new();
56 for line in lines.by_ref() {
57 if line.starts_with("//-") {
58 let meta = Fixture::parse_single(line);
59 res.push(meta)
60 } else if let Some(entry) = res.last_mut() {
61 entry.text.push_str(line);
62 entry.text.push('\n');
63 }
64 }
65 res
66 }
67
68 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
69 pub fn parse_single(meta: &str) -> Fixture {
70 assert!(meta.starts_with("//-"));
71 let meta = meta["//-".len()..].trim();
72 let components = meta.split_ascii_whitespace().collect::<Vec<_>>();
73
74 let path = components[0].to_string();
75 assert!(path.starts_with("/"));
76
77 let mut krate = None;
78 let mut deps = Vec::new();
79 let mut edition = None;
80 let mut cfg_atoms = Vec::new();
81 let mut cfg_key_values = Vec::new();
82 let mut env = FxHashMap::default();
83 for component in components[1..].iter() {
84 let (key, value) = split1(component, ':').unwrap();
85 match key {
86 "crate" => krate = Some(value.to_string()),
87 "deps" => deps = value.split(',').map(|it| it.to_string()).collect(),
88 "edition" => edition = Some(value.to_string()),
89 "cfg" => {
90 for entry in value.split(',') {
91 match split1(entry, '=') {
92 Some((k, v)) => cfg_key_values.push((k.to_string(), v.to_string())),
93 None => cfg_atoms.push(entry.to_string()),
94 }
95 }
96 }
97 "env" => {
98 for key in value.split(',') {
99 if let Some((k, v)) = split1(key, '=') {
100 env.insert(k.into(), v.into());
101 }
102 }
103 }
104 _ => panic!("bad component: {:?}", component),
105 }
106 }
107
108 Fixture {
109 path,
110 text: String::new(),
111 crate_name: krate,
112 deps,
113 cfg_atoms,
114 cfg_key_values,
115 edition,
116 env,
117 }
118 }
119}
120
121/// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines.
122/// This allows fixtures to start off in a different indentation, e.g. to align the first line with
123/// the other lines visually:
124/// ```
125/// let fixture = "//- /lib.rs
126/// mod foo;
127/// //- /foo.rs
128/// fn bar() {}
129/// ";
130/// assert_eq!(fixture_margin(fixture),
131/// " //- /lib.rs
132/// mod foo;
133/// //- /foo.rs
134/// fn bar() {}
135/// ")
136/// ```
137fn indent_first_line(fixture: &str) -> String {
138 if fixture.is_empty() {
139 return String::new();
140 }
141 let mut lines = fixture.lines();
142 let first_line = lines.next().unwrap();
143 if first_line.contains("//-") {
144 let rest = lines.collect::<Vec<_>>().join("\n");
145 let fixed_margin = fixture_margin(&rest);
146 let fixed_indent = fixed_margin - indent_len(first_line);
147 format!("\n{}{}\n{}", " ".repeat(fixed_indent), first_line, rest)
148 } else {
149 fixture.to_owned()
150 }
151}
152
153fn fixture_margin(fixture: &str) -> usize {
154 fixture
155 .lines()
156 .filter(|it| it.trim_start().starts_with("//-"))
157 .map(indent_len)
158 .next()
159 .expect("empty fixture")
160}
161
162fn indent_len(s: &str) -> usize {
163 s.len() - s.trim_start().len()
164}
165
166#[test]
167#[should_panic]
168fn parse_fixture_checks_further_indented_metadata() {
169 Fixture::parse(
170 r"
171 //- /lib.rs
172 mod bar;
173
174 fn foo() {}
175 //- /bar.rs
176 pub fn baz() {}
177 ",
178 );
179}
180
181#[test]
182fn parse_fixture_can_handle_dedented_first_line() {
183 let fixture = "//- /lib.rs
184 mod foo;
185 //- /foo.rs
186 struct Bar;
187";
188 assert_eq!(
189 Fixture::parse(fixture),
190 Fixture::parse(
191 "//- /lib.rs
192mod foo;
193//- /foo.rs
194struct Bar;
195"
196 )
197 )
198}
199
200#[test]
201fn parse_fixture_gets_full_meta() {
202 let parsed = Fixture::parse(
203 r"
204 //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo
205 mod m;
206 ",
207 );
208 assert_eq!(1, parsed.len());
209
210 let meta = &parsed[0];
211 assert_eq!("mod m;\n\n", meta.text);
212
213 assert_eq!("foo", meta.crate_name.as_ref().unwrap());
214 assert_eq!("/lib.rs", meta.path);
215 assert_eq!(2, meta.env.len());
216}