1 //! Tests and test utilities for completions.
3 //! Most tests live in this module or its submodules. The tests in these submodules are "location"
4 //! oriented, that is they try to check completions for something like type position, param position
6 //! Tests that are more orientated towards specific completion types like visibility checks of path
7 //! completions or `check_edit` tests usually live in their respective completion modules instead.
8 //! This gives this test module and its submodules here the main purpose of giving the developer an
9 //! overview of whats being completed where, not how.
26 use hir::{db::DefDatabase, PrefixKind, Semantics};
28 base_db::{fixture::ChangeFixture, FileLoader, FilePosition},
30 insert_use::{ImportGranularity, InsertUseConfig},
35 use itertools::Itertools;
36 use stdx::{format_to, trim_indent};
37 use syntax::{AstNode, NodeOrToken, SyntaxElement};
38 use test_utils::assert_eq_text;
40 use crate::{item::CompletionKind, CompletionConfig, CompletionItem};
42 /// Lots of basic item definitions
43 const BASE_ITEMS_FIXTURE: &str = r#"
44 enum Enum { TupleV(u32), RecordV { field: u32 }, UnitV }
45 use self::Enum::TupleV;
49 static STATIC: Unit = Unit;
50 const CONST: Unit = Unit;
51 struct Record { field: u32 }
56 #[rustc_builtin_macro]
59 union Union { field: i32 }
62 pub(crate) const TEST_CONFIG: CompletionConfig = CompletionConfig {
63 enable_postfix_completions: true,
64 enable_imports_on_the_fly: true,
65 enable_self_on_the_fly: true,
66 add_call_parenthesis: true,
67 add_call_argument_snippets: true,
68 snippet_cap: SnippetCap::new(true),
69 insert_use: InsertUseConfig {
70 granularity: ImportGranularity::Crate,
71 prefix_kind: PrefixKind::Plain,
72 enforce_granularity: true,
74 skip_glob_imports: true,
79 pub(crate) fn completion_list(ra_fixture: &str) -> String {
80 completion_list_with_config(TEST_CONFIG, ra_fixture)
83 fn completion_list_with_config(config: CompletionConfig, ra_fixture: &str) -> String {
84 // filter out all but one builtintype completion for smaller test outputs
85 let items = get_all_items(config, ra_fixture);
86 let mut bt_seen = false;
90 it.completion_kind != CompletionKind::BuiltinType || !mem::replace(&mut bt_seen, true)
93 render_completion_list(items)
96 /// Creates analysis from a multi-file fixture, returns positions marked with $0.
97 pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) {
98 let change_fixture = ChangeFixture::parse(ra_fixture);
99 let mut database = RootDatabase::default();
100 database.set_enable_proc_attr_macros(true);
101 database.apply_change(change_fixture.change);
102 let (file_id, range_or_offset) = change_fixture.file_position.expect("expected a marker ($0)");
103 let offset = range_or_offset.expect_offset();
104 (database, FilePosition { file_id, offset })
107 pub(crate) fn do_completion(code: &str, kind: CompletionKind) -> Vec<CompletionItem> {
108 do_completion_with_config(TEST_CONFIG, code, kind)
111 pub(crate) fn do_completion_with_config(
112 config: CompletionConfig,
114 kind: CompletionKind,
115 ) -> Vec<CompletionItem> {
116 get_all_items(config, code)
118 .filter(|c| c.completion_kind == kind)
119 .sorted_by(|l, r| l.label().cmp(r.label()))
123 pub(crate) fn filtered_completion_list(code: &str, kind: CompletionKind) -> String {
124 filtered_completion_list_with_config(TEST_CONFIG, code, kind)
127 pub(crate) fn filtered_completion_list_with_config(
128 config: CompletionConfig,
130 kind: CompletionKind,
132 let kind_completions: Vec<CompletionItem> =
133 get_all_items(config, code).into_iter().filter(|c| c.completion_kind == kind).collect();
134 render_completion_list(kind_completions)
137 fn render_completion_list(completions: Vec<CompletionItem>) -> String {
138 fn monospace_width(s: &str) -> usize {
142 completions.iter().map(|it| monospace_width(it.label())).max().unwrap_or_default().min(22);
146 let tag = it.kind().unwrap().tag();
147 let var_name = format!("{} {}", tag, it.label());
148 let mut buf = var_name;
149 if let Some(detail) = it.detail() {
150 let width = label_width.saturating_sub(monospace_width(it.label()));
151 format_to!(buf, "{:width$} {}", "", detail, width = width);
154 format_to!(buf, " DEPRECATED");
156 format_to!(buf, "\n");
162 pub(crate) fn check_edit(what: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
163 check_edit_with_config(TEST_CONFIG, what, ra_fixture_before, ra_fixture_after)
166 pub(crate) fn check_edit_with_config(
167 config: CompletionConfig,
169 ra_fixture_before: &str,
170 ra_fixture_after: &str,
172 let ra_fixture_after = trim_indent(ra_fixture_after);
173 let (db, position) = position(ra_fixture_before);
174 let completions: Vec<CompletionItem> =
175 crate::completions(&db, &config, position).unwrap().into();
176 let (completion,) = completions
178 .filter(|it| it.lookup() == what)
180 .unwrap_or_else(|| panic!("can't find {:?} completion in {:#?}", what, completions));
181 let mut actual = db.file_text(position.file_id).to_string();
183 let mut combined_edit = completion.text_edit().to_owned();
187 .filter_map(|edit| edit.to_text_edit(config.insert_use))
188 .for_each(|text_edit| {
189 combined_edit.union(text_edit).expect(
190 "Failed to apply completion resolve changes: change ranges overlap, but should not",
194 combined_edit.apply(&mut actual);
195 assert_eq_text!(&ra_fixture_after, &actual)
198 pub(crate) fn check_pattern_is_applicable(code: &str, check: impl FnOnce(SyntaxElement) -> bool) {
199 let (db, pos) = position(code);
201 let sema = Semantics::new(&db);
202 let original_file = sema.parse(pos.file_id);
203 let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap();
204 assert!(check(NodeOrToken::Token(token)));
207 pub(crate) fn check_pattern_is_not_applicable(code: &str, check: fn(SyntaxElement) -> bool) {
208 let (db, pos) = position(code);
209 let sema = Semantics::new(&db);
210 let original_file = sema.parse(pos.file_id);
211 let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap();
212 assert!(!check(NodeOrToken::Token(token)));
215 pub(crate) fn get_all_items(config: CompletionConfig, code: &str) -> Vec<CompletionItem> {
216 let (db, position) = position(code);
217 crate::completions(&db, &config, position).map_or_else(Vec::default, Into::into)
220 fn check_no_completion(ra_fixture: &str) {
221 let (db, position) = position(ra_fixture);
224 crate::completions(&db, &TEST_CONFIG, position).is_none(),
225 "Completions were generated, but weren't expected"
230 fn test_no_completions_required() {
231 cov_mark::check!(no_completion_required);
232 check_no_completion(r#"fn foo() { for i i$0 }"#);
236 fn regression_10042() {
239 macro_rules! preset {
240 ($($x:ident)&&*) => {
242 let mut v = Vec::new();