diff options
Diffstat (limited to 'crates/test_utils/src/fixture.rs')
-rw-r--r-- | crates/test_utils/src/fixture.rs | 288 |
1 files changed, 288 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..d0a732031 --- /dev/null +++ b/crates/test_utils/src/fixture.rs | |||
@@ -0,0 +1,288 @@ | |||
1 | use ra_cfg::CfgOptions; | ||
2 | use rustc_hash::FxHashMap; | ||
3 | use stdx::split1; | ||
4 | |||
5 | #[derive(Debug, Eq, PartialEq)] | ||
6 | pub struct FixtureEntry { | ||
7 | pub meta: FixtureMeta, | ||
8 | pub text: String, | ||
9 | } | ||
10 | |||
11 | #[derive(Debug, Eq, PartialEq)] | ||
12 | pub enum FixtureMeta { | ||
13 | Root { path: String }, | ||
14 | File(FileMeta), | ||
15 | } | ||
16 | |||
17 | #[derive(Debug, Eq, PartialEq)] | ||
18 | pub struct FileMeta { | ||
19 | pub path: String, | ||
20 | pub crate_name: Option<String>, | ||
21 | pub deps: Vec<String>, | ||
22 | pub cfg: CfgOptions, | ||
23 | pub edition: Option<String>, | ||
24 | pub env: FxHashMap<String, String>, | ||
25 | } | ||
26 | |||
27 | impl FixtureMeta { | ||
28 | pub fn path(&self) -> &str { | ||
29 | match self { | ||
30 | FixtureMeta::Root { path } => &path, | ||
31 | FixtureMeta::File(f) => &f.path, | ||
32 | } | ||
33 | } | ||
34 | |||
35 | pub fn crate_name(&self) -> Option<&String> { | ||
36 | match self { | ||
37 | FixtureMeta::File(f) => f.crate_name.as_ref(), | ||
38 | _ => None, | ||
39 | } | ||
40 | } | ||
41 | |||
42 | pub fn cfg_options(&self) -> Option<&CfgOptions> { | ||
43 | match self { | ||
44 | FixtureMeta::File(f) => Some(&f.cfg), | ||
45 | _ => None, | ||
46 | } | ||
47 | } | ||
48 | |||
49 | pub fn edition(&self) -> Option<&String> { | ||
50 | match self { | ||
51 | FixtureMeta::File(f) => f.edition.as_ref(), | ||
52 | _ => None, | ||
53 | } | ||
54 | } | ||
55 | |||
56 | pub fn env(&self) -> impl Iterator<Item = (&String, &String)> { | ||
57 | struct EnvIter<'a> { | ||
58 | iter: Option<std::collections::hash_map::Iter<'a, String, String>>, | ||
59 | } | ||
60 | |||
61 | impl<'a> EnvIter<'a> { | ||
62 | fn new(meta: &'a FixtureMeta) -> Self { | ||
63 | Self { | ||
64 | iter: match meta { | ||
65 | FixtureMeta::File(f) => Some(f.env.iter()), | ||
66 | _ => None, | ||
67 | }, | ||
68 | } | ||
69 | } | ||
70 | } | ||
71 | |||
72 | impl<'a> Iterator for EnvIter<'a> { | ||
73 | type Item = (&'a String, &'a String); | ||
74 | fn next(&mut self) -> Option<Self::Item> { | ||
75 | self.iter.as_mut().and_then(|i| i.next()) | ||
76 | } | ||
77 | } | ||
78 | |||
79 | EnvIter::new(self) | ||
80 | } | ||
81 | } | ||
82 | |||
83 | /// Same as `parse_fixture`, except it allow empty fixture | ||
84 | pub fn parse_single_fixture(ra_fixture: &str) -> Option<FixtureEntry> { | ||
85 | if !ra_fixture.lines().any(|it| it.trim_start().starts_with("//-")) { | ||
86 | return None; | ||
87 | } | ||
88 | |||
89 | let fixtures = parse_fixture(ra_fixture); | ||
90 | if fixtures.len() > 1 { | ||
91 | panic!("too many fixtures"); | ||
92 | } | ||
93 | fixtures.into_iter().nth(0) | ||
94 | } | ||
95 | |||
96 | /// Parses text which looks like this: | ||
97 | /// | ||
98 | /// ```not_rust | ||
99 | /// //- some meta | ||
100 | /// line 1 | ||
101 | /// line 2 | ||
102 | /// // - other meta | ||
103 | /// ``` | ||
104 | pub fn parse_fixture(ra_fixture: &str) -> Vec<FixtureEntry> { | ||
105 | let fixture = indent_first_line(ra_fixture); | ||
106 | let margin = fixture_margin(&fixture); | ||
107 | |||
108 | let mut lines = fixture | ||
109 | .split('\n') // don't use `.lines` to not drop `\r\n` | ||
110 | .enumerate() | ||
111 | .filter_map(|(ix, line)| { | ||
112 | if line.len() >= margin { | ||
113 | assert!(line[..margin].trim().is_empty()); | ||
114 | let line_content = &line[margin..]; | ||
115 | if !line_content.starts_with("//-") { | ||
116 | assert!( | ||
117 | !line_content.contains("//-"), | ||
118 | r#"Metadata line {} has invalid indentation. All metadata lines need to have the same indentation. | ||
119 | The offending line: {:?}"#, | ||
120 | ix, | ||
121 | line | ||
122 | ); | ||
123 | } | ||
124 | Some(line_content) | ||
125 | } else { | ||
126 | assert!(line.trim().is_empty()); | ||
127 | None | ||
128 | } | ||
129 | }); | ||
130 | |||
131 | let mut res: Vec<FixtureEntry> = Vec::new(); | ||
132 | for line in lines.by_ref() { | ||
133 | if line.starts_with("//-") { | ||
134 | let meta = line["//-".len()..].trim().to_string(); | ||
135 | let meta = parse_meta(&meta); | ||
136 | res.push(FixtureEntry { meta, text: String::new() }) | ||
137 | } else if let Some(entry) = res.last_mut() { | ||
138 | entry.text.push_str(line); | ||
139 | entry.text.push('\n'); | ||
140 | } | ||
141 | } | ||
142 | res | ||
143 | } | ||
144 | |||
145 | //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo | ||
146 | fn parse_meta(meta: &str) -> FixtureMeta { | ||
147 | let components = meta.split_ascii_whitespace().collect::<Vec<_>>(); | ||
148 | |||
149 | if components[0] == "root" { | ||
150 | let path = components[1].to_string(); | ||
151 | assert!(path.starts_with("/") && path.ends_with("/")); | ||
152 | return FixtureMeta::Root { path }; | ||
153 | } | ||
154 | |||
155 | let path = components[0].to_string(); | ||
156 | assert!(path.starts_with("/")); | ||
157 | |||
158 | let mut krate = None; | ||
159 | let mut deps = Vec::new(); | ||
160 | let mut edition = None; | ||
161 | let mut cfg = CfgOptions::default(); | ||
162 | let mut env = FxHashMap::default(); | ||
163 | for component in components[1..].iter() { | ||
164 | let (key, value) = split1(component, ':').unwrap(); | ||
165 | match key { | ||
166 | "crate" => krate = Some(value.to_string()), | ||
167 | "deps" => deps = value.split(',').map(|it| it.to_string()).collect(), | ||
168 | "edition" => edition = Some(value.to_string()), | ||
169 | "cfg" => { | ||
170 | for key in value.split(',') { | ||
171 | match split1(key, '=') { | ||
172 | None => cfg.insert_atom(key.into()), | ||
173 | Some((k, v)) => cfg.insert_key_value(k.into(), v.into()), | ||
174 | } | ||
175 | } | ||
176 | } | ||
177 | "env" => { | ||
178 | for key in value.split(',') { | ||
179 | if let Some((k, v)) = split1(key, '=') { | ||
180 | env.insert(k.into(), v.into()); | ||
181 | } | ||
182 | } | ||
183 | } | ||
184 | _ => panic!("bad component: {:?}", component), | ||
185 | } | ||
186 | } | ||
187 | |||
188 | FixtureMeta::File(FileMeta { path, crate_name: krate, deps, edition, cfg, env }) | ||
189 | } | ||
190 | |||
191 | /// Adjusts the indentation of the first line to the minimum indentation of the rest of the lines. | ||
192 | /// This allows fixtures to start off in a different indentation, e.g. to align the first line with | ||
193 | /// the other lines visually: | ||
194 | /// ``` | ||
195 | /// let fixture = "//- /lib.rs | ||
196 | /// mod foo; | ||
197 | /// //- /foo.rs | ||
198 | /// fn bar() {} | ||
199 | /// "; | ||
200 | /// assert_eq!(fixture_margin(fixture), | ||
201 | /// " //- /lib.rs | ||
202 | /// mod foo; | ||
203 | /// //- /foo.rs | ||
204 | /// fn bar() {} | ||
205 | /// ") | ||
206 | /// ``` | ||
207 | fn indent_first_line(fixture: &str) -> String { | ||
208 | if fixture.is_empty() { | ||
209 | return String::new(); | ||
210 | } | ||
211 | let mut lines = fixture.lines(); | ||
212 | let first_line = lines.next().unwrap(); | ||
213 | if first_line.contains("//-") { | ||
214 | let rest = lines.collect::<Vec<_>>().join("\n"); | ||
215 | let fixed_margin = fixture_margin(&rest); | ||
216 | let fixed_indent = fixed_margin - indent_len(first_line); | ||
217 | format!("\n{}{}\n{}", " ".repeat(fixed_indent), first_line, rest) | ||
218 | } else { | ||
219 | fixture.to_owned() | ||
220 | } | ||
221 | } | ||
222 | |||
223 | fn fixture_margin(fixture: &str) -> usize { | ||
224 | fixture | ||
225 | .lines() | ||
226 | .filter(|it| it.trim_start().starts_with("//-")) | ||
227 | .map(indent_len) | ||
228 | .next() | ||
229 | .expect("empty fixture") | ||
230 | } | ||
231 | |||
232 | fn indent_len(s: &str) -> usize { | ||
233 | s.len() - s.trim_start().len() | ||
234 | } | ||
235 | |||
236 | #[test] | ||
237 | #[should_panic] | ||
238 | fn parse_fixture_checks_further_indented_metadata() { | ||
239 | parse_fixture( | ||
240 | r" | ||
241 | //- /lib.rs | ||
242 | mod bar; | ||
243 | |||
244 | fn foo() {} | ||
245 | //- /bar.rs | ||
246 | pub fn baz() {} | ||
247 | ", | ||
248 | ); | ||
249 | } | ||
250 | |||
251 | #[test] | ||
252 | fn parse_fixture_can_handle_dedented_first_line() { | ||
253 | let fixture = "//- /lib.rs | ||
254 | mod foo; | ||
255 | //- /foo.rs | ||
256 | struct Bar; | ||
257 | "; | ||
258 | assert_eq!( | ||
259 | parse_fixture(fixture), | ||
260 | parse_fixture( | ||
261 | "//- /lib.rs | ||
262 | mod foo; | ||
263 | //- /foo.rs | ||
264 | struct Bar; | ||
265 | " | ||
266 | ) | ||
267 | ) | ||
268 | } | ||
269 | |||
270 | #[test] | ||
271 | fn parse_fixture_gets_full_meta() { | ||
272 | let parsed = parse_fixture( | ||
273 | r" | ||
274 | //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo | ||
275 | mod m; | ||
276 | ", | ||
277 | ); | ||
278 | assert_eq!(1, parsed.len()); | ||
279 | |||
280 | let parsed = &parsed[0]; | ||
281 | assert_eq!("mod m;\n\n", parsed.text); | ||
282 | |||
283 | let meta = &parsed.meta; | ||
284 | assert_eq!("foo", meta.crate_name().unwrap()); | ||
285 | assert_eq!("/lib.rs", meta.path()); | ||
286 | assert!(meta.cfg_options().is_some()); | ||
287 | assert_eq!(2, meta.env().count()); | ||
288 | } | ||