]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/tests.rs
7af8c903b3d4599da8610284bebc9de64eba9fd8
[rust.git] / crates / ide_completion / src / tests.rs
1 //! Tests and test utilities for completions.
2 //!
3 //! Most tests live in this module or its submodules unless for very specific completions like
4 //! `attributes` or `lifetimes` where the completed concept is a distinct thing.
5 //! Notable examples for completions that are being tested in this module's submodule are paths.
6
7 mod item_list;
8 mod use_tree;
9 mod items;
10 mod pattern;
11
12 use hir::{PrefixKind, Semantics};
13 use ide_db::{
14     base_db::{fixture::ChangeFixture, FileLoader, FilePosition},
15     helpers::{
16         insert_use::{ImportGranularity, InsertUseConfig},
17         SnippetCap,
18     },
19     RootDatabase,
20 };
21 use itertools::Itertools;
22 use stdx::{format_to, trim_indent};
23 use syntax::{AstNode, NodeOrToken, SyntaxElement};
24 use test_utils::assert_eq_text;
25
26 use crate::{item::CompletionKind, CompletionConfig, CompletionItem};
27
28 pub(crate) const TEST_CONFIG: CompletionConfig = CompletionConfig {
29     enable_postfix_completions: true,
30     enable_imports_on_the_fly: true,
31     enable_self_on_the_fly: true,
32     add_call_parenthesis: true,
33     add_call_argument_snippets: true,
34     snippet_cap: SnippetCap::new(true),
35     insert_use: InsertUseConfig {
36         granularity: ImportGranularity::Crate,
37         prefix_kind: PrefixKind::Plain,
38         enforce_granularity: true,
39         group: true,
40         skip_glob_imports: true,
41     },
42 };
43
44 pub(crate) fn completion_list(code: &str) -> String {
45     completion_list_with_config(TEST_CONFIG, code)
46 }
47
48 fn completion_list_with_config(config: CompletionConfig, code: &str) -> String {
49     render_completion_list(get_all_items(config, code))
50 }
51
52 /// Creates analysis from a multi-file fixture, returns positions marked with $0.
53 pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) {
54     let change_fixture = ChangeFixture::parse(ra_fixture);
55     let mut database = RootDatabase::default();
56     database.apply_change(change_fixture.change);
57     let (file_id, range_or_offset) = change_fixture.file_position.expect("expected a marker ($0)");
58     let offset = range_or_offset.expect_offset();
59     (database, FilePosition { file_id, offset })
60 }
61
62 pub(crate) fn do_completion(code: &str, kind: CompletionKind) -> Vec<CompletionItem> {
63     do_completion_with_config(TEST_CONFIG, code, kind)
64 }
65
66 pub(crate) fn do_completion_with_config(
67     config: CompletionConfig,
68     code: &str,
69     kind: CompletionKind,
70 ) -> Vec<CompletionItem> {
71     get_all_items(config, code)
72         .into_iter()
73         .filter(|c| c.completion_kind == kind)
74         .sorted_by(|l, r| l.label().cmp(r.label()))
75         .collect()
76 }
77
78 pub(crate) fn filtered_completion_list(code: &str, kind: CompletionKind) -> String {
79     filtered_completion_list_with_config(TEST_CONFIG, code, kind)
80 }
81
82 pub(crate) fn filtered_completion_list_with_config(
83     config: CompletionConfig,
84     code: &str,
85     kind: CompletionKind,
86 ) -> String {
87     let kind_completions: Vec<CompletionItem> =
88         get_all_items(config, code).into_iter().filter(|c| c.completion_kind == kind).collect();
89     render_completion_list(kind_completions)
90 }
91
92 fn render_completion_list(completions: Vec<CompletionItem>) -> String {
93     fn monospace_width(s: &str) -> usize {
94         s.chars().count()
95     }
96     let label_width =
97         completions.iter().map(|it| monospace_width(it.label())).max().unwrap_or_default().min(16);
98     completions
99         .into_iter()
100         .map(|it| {
101             let tag = it.kind().unwrap().tag();
102             let var_name = format!("{} {}", tag, it.label());
103             let mut buf = var_name;
104             if let Some(detail) = it.detail() {
105                 let width = label_width.saturating_sub(monospace_width(it.label()));
106                 format_to!(buf, "{:width$} {}", "", detail, width = width);
107             }
108             if it.deprecated() {
109                 format_to!(buf, " DEPRECATED");
110             }
111             format_to!(buf, "\n");
112             buf
113         })
114         .collect()
115 }
116
117 pub(crate) fn check_edit(what: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
118     check_edit_with_config(TEST_CONFIG, what, ra_fixture_before, ra_fixture_after)
119 }
120
121 pub(crate) fn check_edit_with_config(
122     config: CompletionConfig,
123     what: &str,
124     ra_fixture_before: &str,
125     ra_fixture_after: &str,
126 ) {
127     let ra_fixture_after = trim_indent(ra_fixture_after);
128     let (db, position) = position(ra_fixture_before);
129     let completions: Vec<CompletionItem> =
130         crate::completions(&db, &config, position).unwrap().into();
131     let (completion,) = completions
132         .iter()
133         .filter(|it| it.lookup() == what)
134         .collect_tuple()
135         .unwrap_or_else(|| panic!("can't find {:?} completion in {:#?}", what, completions));
136     let mut actual = db.file_text(position.file_id).to_string();
137
138     let mut combined_edit = completion.text_edit().to_owned();
139     if let Some(import_text_edit) =
140         completion.import_to_add().and_then(|edit| edit.to_text_edit(config.insert_use))
141     {
142         combined_edit.union(import_text_edit).expect(
143             "Failed to apply completion resolve changes: change ranges overlap, but should not",
144         )
145     }
146
147     combined_edit.apply(&mut actual);
148     assert_eq_text!(&ra_fixture_after, &actual)
149 }
150
151 pub(crate) fn check_pattern_is_applicable(code: &str, check: impl FnOnce(SyntaxElement) -> bool) {
152     let (db, pos) = position(code);
153
154     let sema = Semantics::new(&db);
155     let original_file = sema.parse(pos.file_id);
156     let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap();
157     assert!(check(NodeOrToken::Token(token)));
158 }
159
160 pub(crate) fn check_pattern_is_not_applicable(code: &str, check: fn(SyntaxElement) -> bool) {
161     let (db, pos) = position(code);
162     let sema = Semantics::new(&db);
163     let original_file = sema.parse(pos.file_id);
164     let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap();
165     assert!(!check(NodeOrToken::Token(token)));
166 }
167
168 pub(crate) fn get_all_items(config: CompletionConfig, code: &str) -> Vec<CompletionItem> {
169     let (db, position) = position(code);
170     crate::completions(&db, &config, position).unwrap().into()
171 }
172
173 fn check_no_completion(ra_fixture: &str) {
174     let (db, position) = position(ra_fixture);
175
176     assert!(
177         crate::completions(&db, &TEST_CONFIG, position).is_none(),
178         "Completions were generated, but weren't expected"
179     );
180 }
181
182 #[test]
183 fn test_no_completions_required() {
184     cov_mark::check!(no_completion_required);
185     check_no_completion(r#"fn foo() { for i i$0 }"#);
186 }