1 //! Tests and test utilities for completions.
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.
12 use hir::{PrefixKind, Semantics};
14 base_db::{fixture::ChangeFixture, FileLoader, FilePosition},
16 insert_use::{ImportGranularity, InsertUseConfig},
21 use itertools::Itertools;
22 use stdx::{format_to, trim_indent};
23 use syntax::{AstNode, NodeOrToken, SyntaxElement};
24 use test_utils::assert_eq_text;
26 use crate::{item::CompletionKind, CompletionConfig, CompletionItem};
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,
40 skip_glob_imports: true,
44 pub(crate) fn completion_list(code: &str) -> String {
45 completion_list_with_config(TEST_CONFIG, code)
48 fn completion_list_with_config(config: CompletionConfig, code: &str) -> String {
49 render_completion_list(get_all_items(config, code))
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 })
62 pub(crate) fn do_completion(code: &str, kind: CompletionKind) -> Vec<CompletionItem> {
63 do_completion_with_config(TEST_CONFIG, code, kind)
66 pub(crate) fn do_completion_with_config(
67 config: CompletionConfig,
70 ) -> Vec<CompletionItem> {
71 get_all_items(config, code)
73 .filter(|c| c.completion_kind == kind)
74 .sorted_by(|l, r| l.label().cmp(r.label()))
78 pub(crate) fn filtered_completion_list(code: &str, kind: CompletionKind) -> String {
79 filtered_completion_list_with_config(TEST_CONFIG, code, kind)
82 pub(crate) fn filtered_completion_list_with_config(
83 config: CompletionConfig,
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)
92 fn render_completion_list(completions: Vec<CompletionItem>) -> String {
93 fn monospace_width(s: &str) -> usize {
97 completions.iter().map(|it| monospace_width(it.label())).max().unwrap_or_default().min(16);
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);
109 format_to!(buf, " DEPRECATED");
111 format_to!(buf, "\n");
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)
121 pub(crate) fn check_edit_with_config(
122 config: CompletionConfig,
124 ra_fixture_before: &str,
125 ra_fixture_after: &str,
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
133 .filter(|it| it.lookup() == what)
135 .unwrap_or_else(|| panic!("can't find {:?} completion in {:#?}", what, completions));
136 let mut actual = db.file_text(position.file_id).to_string();
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))
142 combined_edit.union(import_text_edit).expect(
143 "Failed to apply completion resolve changes: change ranges overlap, but should not",
147 combined_edit.apply(&mut actual);
148 assert_eq_text!(&ra_fixture_after, &actual)
151 pub(crate) fn check_pattern_is_applicable(code: &str, check: impl FnOnce(SyntaxElement) -> bool) {
152 let (db, pos) = position(code);
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)));
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)));
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()
173 fn check_no_completion(ra_fixture: &str) {
174 let (db, position) = position(ra_fixture);
177 crate::completions(&db, &TEST_CONFIG, position).is_none(),
178 "Completions were generated, but weren't expected"
183 fn test_no_completions_required() {
184 cov_mark::check!(no_completion_required);
185 check_no_completion(r#"fn foo() { for i i$0 }"#);