]> git.lizzy.rs Git - rust.git/blob - crates/assists/src/tests.rs
Add initial_contents field for CreateFile
[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 target_dst = dst.path;
127                         format_to!(buf, "//- {}\n", target_dst);
128                         buf.push_str(&initial_contents);
129                     }
130                     _ => (),
131                 }
132             }
133
134             assert_eq_text!(after, &buf);
135         }
136         (Some(assist), ExpectedResult::Target(target)) => {
137             let range = assist.assist.target;
138             assert_eq_text!(&text_without_caret[range], target);
139         }
140         (Some(_), ExpectedResult::NotApplicable) => panic!("assist should not be applicable!"),
141         (None, ExpectedResult::After(_)) | (None, ExpectedResult::Target(_)) => {
142             panic!("code action is not applicable")
143         }
144         (None, ExpectedResult::NotApplicable) => (),
145     };
146 }
147
148 #[test]
149 fn assist_order_field_struct() {
150     let before = "struct Foo { <|>bar: u32 }";
151     let (before_cursor_pos, before) = extract_offset(before);
152     let (db, file_id) = with_single_file(&before);
153     let frange = FileRange { file_id, range: TextRange::empty(before_cursor_pos) };
154     let assists = Assist::resolved(&db, &AssistConfig::default(), frange);
155     let mut assists = assists.iter();
156
157     assert_eq!(
158         assists.next().expect("expected assist").assist.label,
159         "Change visibility to pub(crate)"
160     );
161     assert_eq!(assists.next().expect("expected assist").assist.label, "Add `#[derive]`");
162 }
163
164 #[test]
165 fn assist_order_if_expr() {
166     let before = "
167     pub fn test_some_range(a: int) -> bool {
168         if let 2..6 = <|>5<|> {
169             true
170         } else {
171             false
172         }
173     }";
174     let (range, before) = extract_range(before);
175     let (db, file_id) = with_single_file(&before);
176     let frange = FileRange { file_id, range };
177     let assists = Assist::resolved(&db, &AssistConfig::default(), frange);
178     let mut assists = assists.iter();
179
180     assert_eq!(assists.next().expect("expected assist").assist.label, "Extract into variable");
181     assert_eq!(assists.next().expect("expected assist").assist.label, "Replace with match");
182 }
183
184 #[test]
185 fn assist_filter_works() {
186     let before = "
187     pub fn test_some_range(a: int) -> bool {
188         if let 2..6 = <|>5<|> {
189             true
190         } else {
191             false
192         }
193     }";
194     let (range, before) = extract_range(before);
195     let (db, file_id) = with_single_file(&before);
196     let frange = FileRange { file_id, range };
197
198     {
199         let mut cfg = AssistConfig::default();
200         cfg.allowed = Some(vec![AssistKind::Refactor]);
201
202         let assists = Assist::resolved(&db, &cfg, frange);
203         let mut assists = assists.iter();
204
205         assert_eq!(assists.next().expect("expected assist").assist.label, "Extract into variable");
206         assert_eq!(assists.next().expect("expected assist").assist.label, "Replace with match");
207     }
208
209     {
210         let mut cfg = AssistConfig::default();
211         cfg.allowed = Some(vec![AssistKind::RefactorExtract]);
212         let assists = Assist::resolved(&db, &cfg, frange);
213         assert_eq!(assists.len(), 1);
214
215         let mut assists = assists.iter();
216         assert_eq!(assists.next().expect("expected assist").assist.label, "Extract into variable");
217     }
218
219     {
220         let mut cfg = AssistConfig::default();
221         cfg.allowed = Some(vec![AssistKind::QuickFix]);
222         let assists = Assist::resolved(&db, &cfg, frange);
223         assert!(assists.is_empty(), "All asserts but quickfixes should be filtered out");
224     }
225 }