9 use crossbeam_channel::{after, select, Receiver};
10 use lsp_server::{Connection, Message, Notification, Request};
12 notification::Exit, request::Shutdown, TextDocumentIdentifier, Url, WorkDoneProgress,
14 use lsp_types::{ProgressParams, ProgressParamsValue};
15 use project_model::{CargoConfig, ProjectManifest};
17 config::{ClientCapsConfig, Config, FilesConfig, FilesWatcher, LinkedProject},
21 use serde_json::{to_string_pretty, Value};
22 use test_utils::{find_mismatch, Fixture};
25 use crate::testdir::TestDir;
27 pub(crate) struct Project<'a> {
30 tmp_dir: Option<TestDir>,
32 config: Option<Box<dyn Fn(&mut Config)>>,
35 impl<'a> Project<'a> {
36 pub(crate) fn with_fixture(fixture: &str) -> Project {
37 Project { fixture, tmp_dir: None, roots: vec![], with_sysroot: false, config: None }
40 pub(crate) fn tmp_dir(mut self, tmp_dir: TestDir) -> Project<'a> {
41 self.tmp_dir = Some(tmp_dir);
45 pub(crate) fn root(mut self, path: &str) -> Project<'a> {
46 self.roots.push(path.into());
50 pub(crate) fn with_sysroot(mut self, yes: bool) -> Project<'a> {
51 self.with_sysroot = yes;
55 pub(crate) fn with_config(mut self, config: impl Fn(&mut Config) + 'static) -> Project<'a> {
56 self.config = Some(Box::new(config));
60 pub(crate) fn server(self) -> Server {
61 let tmp_dir = self.tmp_dir.unwrap_or_else(|| TestDir::new());
62 static INIT: Once = Once::new();
64 env_logger::builder().is_test(true).try_init().unwrap();
65 profile::init_from(crate::PROFILE);
68 for entry in Fixture::parse(self.fixture) {
69 let path = tmp_dir.path().join(&entry.path['/'.len_utf8()..]);
70 fs::create_dir_all(path.parent().unwrap()).unwrap();
71 fs::write(path.as_path(), entry.text.as_bytes()).unwrap();
74 let tmp_dir_path = AbsPathBuf::assert(tmp_dir.path().to_path_buf());
76 self.roots.into_iter().map(|root| tmp_dir_path.join(root)).collect::<Vec<_>>();
78 roots.push(tmp_dir_path.clone());
80 let linked_projects = roots
82 .map(|it| ProjectManifest::discover_single(&it).unwrap())
83 .map(LinkedProject::from)
86 let mut config = Config {
87 client_caps: ClientCapsConfig {
89 code_action_literals: true,
90 work_done_progress: true,
93 cargo: CargoConfig { no_sysroot: !self.with_sysroot, ..Default::default() },
95 files: FilesConfig { watcher: FilesWatcher::Client, exclude: Vec::new() },
96 ..Config::new(tmp_dir_path)
98 if let Some(f) = &self.config {
102 Server::new(tmp_dir, config)
106 pub(crate) fn project(fixture: &str) -> Server {
107 Project::with_fixture(fixture).server()
110 pub(crate) struct Server {
112 messages: RefCell<Vec<Message>>,
113 _thread: jod_thread::JoinHandle<()>,
115 /// XXX: remove the tempdir last
120 fn new(dir: TestDir, config: Config) -> Server {
121 let (connection, client) = Connection::memory();
123 let _thread = jod_thread::Builder::new()
124 .name("test server".to_string())
125 .spawn(move || main_loop(config, connection).unwrap())
126 .expect("failed to spawn a thread");
128 Server { req_id: Cell::new(1), dir, messages: Default::default(), client, _thread }
131 pub(crate) fn doc_id(&self, rel_path: &str) -> TextDocumentIdentifier {
132 let path = self.dir.path().join(rel_path);
133 TextDocumentIdentifier { uri: Url::from_file_path(path).unwrap() }
136 pub(crate) fn notification<N>(&self, params: N::Params)
138 N: lsp_types::notification::Notification,
139 N::Params: Serialize,
141 let r = Notification::new(N::METHOD.to_string(), params);
142 self.send_notification(r)
145 pub(crate) fn request<R>(&self, params: R::Params, expected_resp: Value)
147 R: lsp_types::request::Request,
148 R::Params: Serialize,
150 let actual = self.send_request::<R>(params);
151 if let Some((expected_part, actual_part)) = find_mismatch(&expected_resp, &actual) {
153 "JSON mismatch\nExpected:\n{}\nWas:\n{}\nExpected part:\n{}\nActual part:\n{}\n",
154 to_string_pretty(&expected_resp).unwrap(),
155 to_string_pretty(&actual).unwrap(),
156 to_string_pretty(expected_part).unwrap(),
157 to_string_pretty(actual_part).unwrap(),
162 pub(crate) fn send_request<R>(&self, params: R::Params) -> Value
164 R: lsp_types::request::Request,
165 R::Params: Serialize,
167 let id = self.req_id.get();
168 self.req_id.set(id.wrapping_add(1));
170 let r = Request::new(id.into(), R::METHOD.to_string(), params);
171 self.send_request_(r)
173 fn send_request_(&self, r: Request) -> Value {
174 let id = r.id.clone();
175 self.client.sender.send(r.into()).unwrap();
176 while let Some(msg) = self.recv() {
178 Message::Request(req) => {
179 if req.method == "window/workDoneProgress/create" {
182 if req.method == "client/registerCapability" {
183 let params = req.params.to_string();
184 if ["workspace/didChangeWatchedFiles", "textDocument/didSave"]
186 .any(|&it| params.contains(it))
191 panic!("unexpected request: {:?}", req)
193 Message::Notification(_) => (),
194 Message::Response(res) => {
195 assert_eq!(res.id, id);
196 if let Some(err) = res.error {
197 panic!("error response: {:#?}", err);
199 return res.result.unwrap();
203 panic!("no response");
205 pub(crate) fn wait_until_workspace_is_loaded(self) -> Server {
206 self.wait_for_message_cond(1, &|msg: &Message| match msg {
207 Message::Notification(n) if n.method == "$/progress" => {
208 match n.clone().extract::<ProgressParams>("$/progress").unwrap() {
210 token: lsp_types::ProgressToken::String(ref token),
211 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(_)),
212 } if token == "rustAnalyzer/roots scanned" => true,
220 fn wait_for_message_cond(&self, n: usize, cond: &dyn Fn(&Message) -> bool) {
222 for msg in self.messages.borrow().iter() {
228 let msg = self.recv().expect("no response");
234 fn recv(&self) -> Option<Message> {
235 recv_timeout(&self.client.receiver).map(|msg| {
236 self.messages.borrow_mut().push(msg.clone());
240 fn send_notification(&self, not: Notification) {
241 self.client.sender.send(Message::Notification(not)).unwrap();
244 pub(crate) fn path(&self) -> &Path {
249 impl Drop for Server {
251 self.request::<Shutdown>((), Value::Null);
252 self.notification::<Exit>(());
256 fn recv_timeout(receiver: &Receiver<Message>) -> Option<Message> {
258 if cfg!(target_os = "macos") { Duration::from_secs(300) } else { Duration::from_secs(120) };
260 recv(receiver) -> msg => msg.ok(),
261 recv(after(timeout)) -> _ => panic!("timed out"),