]> git.lizzy.rs Git - rust.git/blob - crates/assists/src/tests.rs
Merge #6989
[rust.git] / crates / assists / src / tests.rs
1 mod generated;
2
3 use hir::Semantics;
4 use ide_db::base_db::{fixture::WithFixture, FileId, FileRange, SourceDatabaseExt};
5 use ide_db::source_change::FileSystemEdit;
6 use ide_db::RootDatabase;
7 use syntax::TextRange;
8 use test_utils::{assert_eq_text, extract_offset, extract_range};
9
10 use crate::{handlers::Handler, Assist, AssistConfig, AssistContext, AssistKind, Assists};
11 use stdx::{format_to, trim_indent};
12
13 pub(crate) fn with_single_file(text: &str) -> (RootDatabase, FileId) {
14     RootDatabase::with_single_file(text)
15 }
16
17 pub(crate) fn check_assist(assist: Handler, ra_fixture_before: &str, ra_fixture_after: &str) {
18     let ra_fixture_after = trim_indent(ra_fixture_after);
19     check(assist, ra_fixture_before, ExpectedResult::After(&ra_fixture_after), None);
20 }
21
22 // There is no way to choose what assist within a group you want to test against,
23 // so this is here to allow you choose.
24 pub(crate) fn check_assist_by_label(
25     assist: Handler,
26     ra_fixture_before: &str,
27     ra_fixture_after: &str,
28     label: &str,
29 ) {
30     let ra_fixture_after = trim_indent(ra_fixture_after);
31     check(assist, ra_fixture_before, ExpectedResult::After(&ra_fixture_after), Some(label));
32 }
33
34 // FIXME: instead of having a separate function here, maybe use
35 // `extract_ranges` and mark the target as `<target> </target>` in the
36 // fixture?
37 pub(crate) fn check_assist_target(assist: Handler, ra_fixture: &str, target: &str) {
38     check(assist, ra_fixture, ExpectedResult::Target(target), None);
39 }
40
41 pub(crate) fn check_assist_not_applicable(assist: Handler, ra_fixture: &str) {
42     check(assist, ra_fixture, ExpectedResult::NotApplicable, None);
43 }
44
45 fn check_doc_test(assist_id: &str, before: &str, after: &str) {
46     let after = trim_indent(after);
47     let (db, file_id, selection) = RootDatabase::with_range_or_offset(&before);
48     let before = db.file_text(file_id).to_string();
49     let frange = FileRange { file_id, range: selection.into() };
50
51     let assist = Assist::resolved(&db, &AssistConfig::default(), frange)
52         .into_iter()
53         .find(|assist| assist.assist.id.0 == assist_id)
54         .unwrap_or_else(|| {
55             panic!(
56                 "\n\nAssist is not applicable: {}\nAvailable assists: {}",
57                 assist_id,
58                 Assist::resolved(&db, &AssistConfig::default(), frange)
59                     .into_iter()
60                     .map(|assist| assist.assist.id.0)
61                     .collect::<Vec<_>>()
62                     .join(", ")
63             )
64         });
65
66     let actual = {
67         let mut actual = before;
68         for source_file_edit in assist.source_change.source_file_edits {
69             if source_file_edit.file_id == file_id {
70                 source_file_edit.edit.apply(&mut actual)
71             }
72         }
73         actual
74     };
75     assert_eq_text!(&after, &actual);
76 }
77
78 enum ExpectedResult<'a> {
79     NotApplicable,
80     After(&'a str),
81     Target(&'a str),
82 }
83
84 fn check(handler: Handler, before: &str, expected: ExpectedResult, assist_label: Option<&str>) {
85     let (db, file_with_caret_id, range_or_offset) = RootDatabase::with_range_or_offset(before);
86     let text_without_caret = db.file_text(file_with_caret_id).to_string();
87
88     let frange = FileRange { file_id: file_with_caret_id, range: range_or_offset.into() };
89
90     let sema = Semantics::new(&db);
91     let config = AssistConfig::default();
92     let ctx = AssistContext::new(sema, &config, frange);
93     let mut acc = Assists::new_resolved(&ctx);
94     handler(&mut acc, &ctx);
95     let mut res = acc.finish_resolved();
96
97     let assist = match assist_label {
98         Some(label) => res.into_iter().find(|resolved| resolved.assist.label == label),
99         None => res.pop(),
100     };
101
102     match (assist, expected) {
103         (Some(assist), ExpectedResult::After(after)) => {
104             let mut source_change = assist.source_change;
105             assert!(!source_change.source_file_edits.is_empty());
106             let skip_header = source_change.source_file_edits.len() == 1
107                 && source_change.file_system_edits.len() == 0;
108             source_change.source_file_edits.sort_by_key(|it| it.file_id);
109
110             let mut buf = String::new();
111             for source_file_edit in source_change.source_file_edits {
112                 let mut text = db.file_text(source_file_edit.file_id).as_ref().to_owned();
113                 source_file_edit.edit.apply(&mut text);
114                 if !skip_header {
115                     let sr = db.file_source_root(source_file_edit.file_id);
116                     let sr = db.source_root(sr);
117                     let path = sr.path_for_file(&source_file_edit.file_id).unwrap();
118                     format_to!(buf, "//- {}\n", path)
119                 }
120                 buf.push_str(&text);
121             }
122
123             for file_system_edit in source_change.file_system_edits.clone() {
124                 match file_system_edit {
125                     FileSystemEdit::CreateFile { dst, initial_contents } => {
126                         let sr = db.file_source_root(dst.anchor);
127                         let sr = db.source_root(sr);
128                         let mut base = sr.path_for_file(&dst.anchor).unwrap().clone();
129                         base.pop();
130                         let created_file_path = format!("{}{}", base.to_string(), &dst.path[1..]);
131                         format_to!(buf, "//- {}\n", created_file_path);
132                         buf.push_str(&initial_contents);
133                     }
134                     _ => (),
135                 }
136             }
137
138             assert_eq_text!(after, &buf);
139         }
140         (Some(assist), ExpectedResult::Target(target)) => {
141             let range = assist.assist.target;
142             assert_eq_text!(&text_without_caret[range], target);
143         }
144         (Some(_), ExpectedResult::NotApplicable) => panic!("assist should not be applicable!"),
145         (None, ExpectedResult::After(_)) | (None, ExpectedResult::Target(_)) => {
146             panic!("code action is not applicable")
147         }
148         (None, ExpectedResult::NotApplicable) => (),
149     };
150 }
151
152 #[test]
153 fn assist_order_field_struct() {
154     let before = "struct Foo { <|>bar: u32 }";
155     let (before_cursor_pos, before) = extract_offset(before);
156     let (db, file_id) = with_single_file(&before);
157     let frange = FileRange { file_id, range: TextRange::empty(before_cursor_pos) };
158     let assists = Assist::resolved(&db, &AssistConfig::default(), frange);
159     let mut assists = assists.iter();
160
161     assert_eq!(
162         assists.next().expect("expected assist").assist.label,
163         "Change visibility to pub(crate)"
164     );
165     assert_eq!(assists.next().expect("expected assist").assist.label, "Add `#[derive]`");
166 }
167
168 #[test]
169 fn assist_order_if_expr() {
170     let before = "
171     pub fn test_some_range(a: int) -> bool {
172         if let 2..6 = <|>5<|> {
173             true
174         } else {
175             false
176         }
177     }";
178     let (range, before) = extract_range(before);
179     let (db, file_id) = with_single_file(&before);
180     let frange = FileRange { file_id, range };
181     let assists = Assist::resolved(&db, &AssistConfig::default(), frange);
182     let mut assists = assists.iter();
183
184     assert_eq!(assists.next().expect("expected assist").assist.label, "Extract into variable");
185     assert_eq!(assists.next().expect("expected assist").assist.label, "Replace with match");
186 }
187
188 #[test]
189 fn assist_filter_works() {
190     let before = "
191     pub fn test_some_range(a: int) -> bool {
192         if let 2..6 = <|>5<|> {
193             true
194         } else {
195             false
196         }
197     }";
198     let (range, before) = extract_range(before);
199     let (db, file_id) = with_single_file(&before);
200     let frange = FileRange { file_id, range };
201
202     {
203         let mut cfg = AssistConfig::default();
204         cfg.allowed = Some(vec![AssistKind::Refactor]);
205
206         let assists = Assist::resolved(&db, &cfg, frange);
207         let mut assists = assists.iter();
208
209         assert_eq!(assists.next().expect("expected assist").assist.label, "Extract into variable");
210         assert_eq!(assists.next().expect("expected assist").assist.label, "Replace with match");
211     }
212
213     {
214         let mut cfg = AssistConfig::default();
215         cfg.allowed = Some(vec![AssistKind::RefactorExtract]);
216         let assists = Assist::resolved(&db, &cfg, frange);
217         assert_eq!(assists.len(), 1);
218
219         let mut assists = assists.iter();
220         assert_eq!(assists.next().expect("expected assist").assist.label, "Extract into variable");
221     }
222
223     {
224         let mut cfg = AssistConfig::default();
225         cfg.allowed = Some(vec![AssistKind::QuickFix]);
226         let assists = Assist::resolved(&db, &cfg, frange);
227         assert!(assists.is_empty(), "All asserts but quickfixes should be filtered out");
228     }
229 }