]> git.lizzy.rs Git - rust.git/blob - crates/test_utils/src/fixture.rs
Merge #8415
[rust.git] / crates / test_utils / src / fixture.rs
1 //! Defines `Fixture` -- a convenient way to describe the initial state of
2 //! rust-analyzer database from a single string.
3 //!
4 //! Fixtures are strings containing rust source code with optional metadata.
5 //! A fixture without metadata is parsed into a single source file.
6 //! Use this to test functionality local to one file.
7 //!
8 //! Simple Example:
9 //! ```
10 //! r#"
11 //! fn main() {
12 //!     println!("Hello World")
13 //! }
14 //! "#
15 //! ```
16 //!
17 //! Metadata can be added to a fixture after a `//-` comment.
18 //! The basic form is specifying filenames,
19 //! which is also how to define multiple files in a single test fixture
20 //!
21 //! Example using two files in the same crate:
22 //! ```
23 //! "
24 //! //- /main.rs
25 //! mod foo;
26 //! fn main() {
27 //!     foo::bar();
28 //! }
29 //!
30 //! //- /foo.rs
31 //! pub fn bar() {}
32 //! "
33 //! ```
34 //!
35 //! Example using two crates with one file each, with one crate depending on the other:
36 //! ```
37 //! r#"
38 //! //- /main.rs crate:a deps:b
39 //! fn main() {
40 //!     b::foo();
41 //! }
42 //! //- /lib.rs crate:b
43 //! pub fn b() {
44 //!     println!("Hello World")
45 //! }
46 //! "#
47 //! ```
48 //!
49 //! Metadata allows specifying all settings and variables
50 //! that are available in a real rust project:
51 //! - crate names via `crate:cratename`
52 //! - dependencies via `deps:dep1,dep2`
53 //! - configuration settings via `cfg:dbg=false,opt_level=2`
54 //! - environment variables via `env:PATH=/bin,RUST_LOG=debug`
55 //!
56 //! Example using all available metadata:
57 //! ```
58 //! "
59 //! //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
60 //! fn insert_source_code_here() {}
61 //! "
62 //! ```
63
64 use rustc_hash::FxHashMap;
65 use stdx::{lines_with_ends, split_once, trim_indent};
66
67 #[derive(Debug, Eq, PartialEq)]
68 pub struct Fixture {
69     pub path: String,
70     pub text: String,
71     pub krate: Option<String>,
72     pub deps: Vec<String>,
73     pub cfg_atoms: Vec<String>,
74     pub cfg_key_values: Vec<(String, String)>,
75     pub edition: Option<String>,
76     pub env: FxHashMap<String, String>,
77     pub introduce_new_source_root: bool,
78 }
79
80 impl Fixture {
81     /// Parses text which looks like this:
82     ///
83     ///  ```not_rust
84     ///  //- some meta
85     ///  line 1
86     ///  line 2
87     ///  //- other meta
88     ///  ```
89     pub fn parse(ra_fixture: &str) -> Vec<Fixture> {
90         let fixture = trim_indent(ra_fixture);
91
92         let mut res: Vec<Fixture> = Vec::new();
93
94         let default = if ra_fixture.contains("//-") { None } else { Some("//- /main.rs") };
95
96         for (ix, line) in default.into_iter().chain(lines_with_ends(&fixture)).enumerate() {
97             if line.contains("//-") {
98                 assert!(
99                     line.starts_with("//-"),
100                     "Metadata line {} has invalid indentation. \
101                      All metadata lines need to have the same indentation.\n\
102                      The offending line: {:?}",
103                     ix,
104                     line
105                 );
106             }
107
108             if line.starts_with("//-") {
109                 let meta = Fixture::parse_meta_line(line);
110                 res.push(meta)
111             } else if let Some(entry) = res.last_mut() {
112                 entry.text.push_str(line);
113             }
114         }
115
116         res
117     }
118
119     //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b env:OUTDIR=path/to,OTHER=foo
120     fn parse_meta_line(meta: &str) -> Fixture {
121         assert!(meta.starts_with("//-"));
122         let meta = meta["//-".len()..].trim();
123         let components = meta.split_ascii_whitespace().collect::<Vec<_>>();
124
125         let path = components[0].to_string();
126         assert!(path.starts_with('/'));
127
128         let mut krate = None;
129         let mut deps = Vec::new();
130         let mut edition = None;
131         let mut cfg_atoms = Vec::new();
132         let mut cfg_key_values = Vec::new();
133         let mut env = FxHashMap::default();
134         let mut introduce_new_source_root = false;
135         for component in components[1..].iter() {
136             let (key, value) = split_once(component, ':').unwrap();
137             match key {
138                 "crate" => krate = Some(value.to_string()),
139                 "deps" => deps = value.split(',').map(|it| it.to_string()).collect(),
140                 "edition" => edition = Some(value.to_string()),
141                 "cfg" => {
142                     for entry in value.split(',') {
143                         match split_once(entry, '=') {
144                             Some((k, v)) => cfg_key_values.push((k.to_string(), v.to_string())),
145                             None => cfg_atoms.push(entry.to_string()),
146                         }
147                     }
148                 }
149                 "env" => {
150                     for key in value.split(',') {
151                         if let Some((k, v)) = split_once(key, '=') {
152                             env.insert(k.into(), v.into());
153                         }
154                     }
155                 }
156                 "new_source_root" => introduce_new_source_root = true,
157                 _ => panic!("bad component: {:?}", component),
158             }
159         }
160
161         Fixture {
162             path,
163             text: String::new(),
164             krate,
165             deps,
166             cfg_atoms,
167             cfg_key_values,
168             edition,
169             env,
170             introduce_new_source_root,
171         }
172     }
173 }
174
175 #[test]
176 #[should_panic]
177 fn parse_fixture_checks_further_indented_metadata() {
178     Fixture::parse(
179         r"
180         //- /lib.rs
181           mod bar;
182
183           fn foo() {}
184           //- /bar.rs
185           pub fn baz() {}
186           ",
187     );
188 }
189
190 #[test]
191 fn parse_fixture_gets_full_meta() {
192     let parsed = Fixture::parse(
193         r"
194     //- /lib.rs crate:foo deps:bar,baz cfg:foo=a,bar=b,atom env:OUTDIR=path/to,OTHER=foo
195     mod m;
196     ",
197     );
198     assert_eq!(1, parsed.len());
199
200     let meta = &parsed[0];
201     assert_eq!("mod m;\n", meta.text);
202
203     assert_eq!("foo", meta.krate.as_ref().unwrap());
204     assert_eq!("/lib.rs", meta.path);
205     assert_eq!(2, meta.env.len());
206 }