aboutsummaryrefslogtreecommitdiff
path: root/crates/ide_assists/src/tests.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ide_assists/src/tests.rs')
-rw-r--r--crates/ide_assists/src/tests.rs275
1 files changed, 275 insertions, 0 deletions
diff --git a/crates/ide_assists/src/tests.rs b/crates/ide_assists/src/tests.rs
new file mode 100644
index 000000000..384eb7eee
--- /dev/null
+++ b/crates/ide_assists/src/tests.rs
@@ -0,0 +1,275 @@
1mod generated;
2
3use expect_test::expect;
4use hir::Semantics;
5use ide_db::{
6 base_db::{fixture::WithFixture, FileId, FileRange, SourceDatabaseExt},
7 helpers::{
8 insert_use::{InsertUseConfig, MergeBehavior},
9 SnippetCap,
10 },
11 source_change::FileSystemEdit,
12 RootDatabase,
13};
14use stdx::{format_to, trim_indent};
15use syntax::TextRange;
16use test_utils::{assert_eq_text, extract_offset};
17
18use crate::{handlers::Handler, Assist, AssistConfig, AssistContext, AssistKind, Assists};
19
20pub(crate) const TEST_CONFIG: AssistConfig = AssistConfig {
21 snippet_cap: SnippetCap::new(true),
22 allowed: None,
23 insert_use: InsertUseConfig {
24 merge: Some(MergeBehavior::Full),
25 prefix_kind: hir::PrefixKind::Plain,
26 },
27};
28
29pub(crate) fn with_single_file(text: &str) -> (RootDatabase, FileId) {
30 RootDatabase::with_single_file(text)
31}
32
33pub(crate) fn check_assist(assist: Handler, ra_fixture_before: &str, ra_fixture_after: &str) {
34 let ra_fixture_after = trim_indent(ra_fixture_after);
35 check(assist, ra_fixture_before, ExpectedResult::After(&ra_fixture_after), None);
36}
37
38// There is no way to choose what assist within a group you want to test against,
39// so this is here to allow you choose.
40pub(crate) fn check_assist_by_label(
41 assist: Handler,
42 ra_fixture_before: &str,
43 ra_fixture_after: &str,
44 label: &str,
45) {
46 let ra_fixture_after = trim_indent(ra_fixture_after);
47 check(assist, ra_fixture_before, ExpectedResult::After(&ra_fixture_after), Some(label));
48}
49
50// FIXME: instead of having a separate function here, maybe use
51// `extract_ranges` and mark the target as `<target> </target>` in the
52// fixture?
53#[track_caller]
54pub(crate) fn check_assist_target(assist: Handler, ra_fixture: &str, target: &str) {
55 check(assist, ra_fixture, ExpectedResult::Target(target), None);
56}
57
58#[track_caller]
59pub(crate) fn check_assist_not_applicable(assist: Handler, ra_fixture: &str) {
60 check(assist, ra_fixture, ExpectedResult::NotApplicable, None);
61}
62
63#[track_caller]
64fn check_doc_test(assist_id: &str, before: &str, after: &str) {
65 let after = trim_indent(after);
66 let (db, file_id, selection) = RootDatabase::with_range_or_offset(&before);
67 let before = db.file_text(file_id).to_string();
68 let frange = FileRange { file_id, range: selection.into() };
69
70 let assist = Assist::get(&db, &TEST_CONFIG, true, frange)
71 .into_iter()
72 .find(|assist| assist.id.0 == assist_id)
73 .unwrap_or_else(|| {
74 panic!(
75 "\n\nAssist is not applicable: {}\nAvailable assists: {}",
76 assist_id,
77 Assist::get(&db, &TEST_CONFIG, false, frange)
78 .into_iter()
79 .map(|assist| assist.id.0)
80 .collect::<Vec<_>>()
81 .join(", ")
82 )
83 });
84
85 let actual = {
86 let source_change = assist.source_change.unwrap();
87 let mut actual = before;
88 if let Some(source_file_edit) = source_change.get_source_edit(file_id) {
89 source_file_edit.apply(&mut actual);
90 }
91 actual
92 };
93 assert_eq_text!(&after, &actual);
94}
95
96enum ExpectedResult<'a> {
97 NotApplicable,
98 After(&'a str),
99 Target(&'a str),
100}
101
102#[track_caller]
103fn check(handler: Handler, before: &str, expected: ExpectedResult, assist_label: Option<&str>) {
104 let (db, file_with_caret_id, range_or_offset) = RootDatabase::with_range_or_offset(before);
105 let text_without_caret = db.file_text(file_with_caret_id).to_string();
106
107 let frange = FileRange { file_id: file_with_caret_id, range: range_or_offset.into() };
108
109 let sema = Semantics::new(&db);
110 let config = TEST_CONFIG;
111 let ctx = AssistContext::new(sema, &config, frange);
112 let mut acc = Assists::new(&ctx, true);
113 handler(&mut acc, &ctx);
114 let mut res = acc.finish();
115
116 let assist = match assist_label {
117 Some(label) => res.into_iter().find(|resolved| resolved.label == label),
118 None => res.pop(),
119 };
120
121 match (assist, expected) {
122 (Some(assist), ExpectedResult::After(after)) => {
123 let source_change = assist.source_change.unwrap();
124 assert!(!source_change.source_file_edits.is_empty());
125 let skip_header = source_change.source_file_edits.len() == 1
126 && source_change.file_system_edits.len() == 0;
127
128 let mut buf = String::new();
129 for (file_id, edit) in source_change.source_file_edits {
130 let mut text = db.file_text(file_id).as_ref().to_owned();
131 edit.apply(&mut text);
132 if !skip_header {
133 let sr = db.file_source_root(file_id);
134 let sr = db.source_root(sr);
135 let path = sr.path_for_file(&file_id).unwrap();
136 format_to!(buf, "//- {}\n", path)
137 }
138 buf.push_str(&text);
139 }
140
141 for file_system_edit in source_change.file_system_edits {
142 if let FileSystemEdit::CreateFile { dst, initial_contents } = file_system_edit {
143 let sr = db.file_source_root(dst.anchor);
144 let sr = db.source_root(sr);
145 let mut base = sr.path_for_file(&dst.anchor).unwrap().clone();
146 base.pop();
147 let created_file_path = format!("{}{}", base.to_string(), &dst.path[1..]);
148 format_to!(buf, "//- {}\n", created_file_path);
149 buf.push_str(&initial_contents);
150 }
151 }
152
153 assert_eq_text!(after, &buf);
154 }
155 (Some(assist), ExpectedResult::Target(target)) => {
156 let range = assist.target;
157 assert_eq_text!(&text_without_caret[range], target);
158 }
159 (Some(_), ExpectedResult::NotApplicable) => panic!("assist should not be applicable!"),
160 (None, ExpectedResult::After(_)) | (None, ExpectedResult::Target(_)) => {
161 panic!("code action is not applicable")
162 }
163 (None, ExpectedResult::NotApplicable) => (),
164 };
165}
166
167fn labels(assists: &[Assist]) -> String {
168 let mut labels = assists
169 .iter()
170 .map(|assist| {
171 let mut label = match &assist.group {
172 Some(g) => g.0.clone(),
173 None => assist.label.to_string(),
174 };
175 label.push('\n');
176 label
177 })
178 .collect::<Vec<_>>();
179 labels.dedup();
180 labels.into_iter().collect::<String>()
181}
182
183#[test]
184fn assist_order_field_struct() {
185 let before = "struct Foo { $0bar: u32 }";
186 let (before_cursor_pos, before) = extract_offset(before);
187 let (db, file_id) = with_single_file(&before);
188 let frange = FileRange { file_id, range: TextRange::empty(before_cursor_pos) };
189 let assists = Assist::get(&db, &TEST_CONFIG, false, frange);
190 let mut assists = assists.iter();
191
192 assert_eq!(assists.next().expect("expected assist").label, "Change visibility to pub(crate)");
193 assert_eq!(assists.next().expect("expected assist").label, "Generate a getter method");
194 assert_eq!(assists.next().expect("expected assist").label, "Generate a mut getter method");
195 assert_eq!(assists.next().expect("expected assist").label, "Generate a setter method");
196 assert_eq!(assists.next().expect("expected assist").label, "Add `#[derive]`");
197}
198
199#[test]
200fn assist_order_if_expr() {
201 let (db, frange) = RootDatabase::with_range(
202 r#"
203pub fn test_some_range(a: int) -> bool {
204 if let 2..6 = $05$0 {
205 true
206 } else {
207 false
208 }
209}
210"#,
211 );
212
213 let assists = Assist::get(&db, &TEST_CONFIG, false, frange);
214 let expected = labels(&assists);
215
216 expect![[r#"
217 Convert integer base
218 Extract into variable
219 Extract into function
220 Replace with match
221 "#]]
222 .assert_eq(&expected);
223}
224
225#[test]
226fn assist_filter_works() {
227 let (db, frange) = RootDatabase::with_range(
228 r#"
229pub fn test_some_range(a: int) -> bool {
230 if let 2..6 = $05$0 {
231 true
232 } else {
233 false
234 }
235}
236"#,
237 );
238 {
239 let mut cfg = TEST_CONFIG;
240 cfg.allowed = Some(vec![AssistKind::Refactor]);
241
242 let assists = Assist::get(&db, &cfg, false, frange);
243 let expected = labels(&assists);
244
245 expect![[r#"
246 Convert integer base
247 Extract into variable
248 Extract into function
249 Replace with match
250 "#]]
251 .assert_eq(&expected);
252 }
253
254 {
255 let mut cfg = TEST_CONFIG;
256 cfg.allowed = Some(vec![AssistKind::RefactorExtract]);
257 let assists = Assist::get(&db, &cfg, false, frange);
258 let expected = labels(&assists);
259
260 expect![[r#"
261 Extract into variable
262 Extract into function
263 "#]]
264 .assert_eq(&expected);
265 }
266
267 {
268 let mut cfg = TEST_CONFIG;
269 cfg.allowed = Some(vec![AssistKind::QuickFix]);
270 let assists = Assist::get(&db, &cfg, false, frange);
271 let expected = labels(&assists);
272
273 expect![[r#""#]].assert_eq(&expected);
274 }
275}