test: cover LSP protocol workflows

This commit is contained in:
Dandaedre 2026-09-29 17:11:22 +02:00
parent 883fb13c12
commit dcae1b1b06
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
4 changed files with 319 additions and 1 deletions

2
Cargo.lock generated
View File

@ -695,6 +695,7 @@ dependencies = [
"clap",
"directories",
"figment",
"futures",
"globset",
"insta",
"miette",
@ -706,6 +707,7 @@ dependencies = [
"thiserror",
"tokio",
"toml 1.1.6+spec-1.1.0",
"tower",
"tower-lsp-server",
"walkdir",
"zip",

View File

@ -42,4 +42,6 @@ walkdir = "2.5.0"
zip = "8.6.0"
[dev-dependencies]
futures = { version = "0.3.34", default-features = false, features = ["std"] }
insta = { version = "1.48.0", default-features = false }
tower = { version = "0.5.3", default-features = false, features = ["util"] }

View File

@ -203,7 +203,7 @@ first formatter milestone tag.
publishing obsolete results when analysis overlaps newer edits.
- [x] Keep all protocol bytes on stdout and diagnostics/logging on stderr. Add
opt-in structured logging without document contents.
- [ ] Add in-process protocol tests for lifecycle, versions, Unicode positions,
- [x] Add in-process protocol tests for lifecycle, versions, Unicode positions,
config reload, close cleanup, invalid URI, malformed messages, concurrent
documents, and formatter/LSP output equivalence.

314
tests/lsp.rs Normal file
View File

@ -0,0 +1,314 @@
use std::{fs, ops::Range as ByteRange, path::PathBuf};
use futures::{FutureExt, StreamExt};
use john_slop::{
Config, ConfigLoader, ConfigPaths, apply_replacements, lsp::LspBackend, plan_replacements,
};
use serde_json::{Value, json};
use tempfile::TempDir;
use tower::{Service, ServiceExt};
use tower_lsp_server::{
LspService,
jsonrpc::{ErrorCode, Request, Response},
};
struct Harness {
service: LspService<LspBackend>,
socket: tower_lsp_server::ClientSocket,
_directory: TempDir,
explicit: Option<PathBuf>,
}
impl Harness {
async fn new(explicit_config: Option<&str>) -> Self {
let directory = tempfile::tempdir().unwrap();
let explicit = explicit_config.map(|contents| {
let path = directory.path().join("lsp.toml");
fs::write(&path, contents).unwrap();
path
});
let paths = ConfigPaths {
directory: directory.path().to_owned(),
base: directory.path().join("missing-base.toml"),
named: None,
explicit: explicit.clone(),
};
let loader = ConfigLoader::from_paths(paths);
let config = loader.load().unwrap();
let (service, socket) = LspService::new(|client| LspBackend::new(client, loader, config));
let mut harness = Self {
service,
socket,
_directory: directory,
explicit,
};
let response = harness
.request("initialize", json!({ "capabilities": {} }), 1)
.await;
assert!(response.is_ok());
assert_eq!(
response.result().unwrap()["capabilities"]["textDocumentSync"],
1
);
harness.notify("initialized", json!({})).await;
harness
}
async fn request(&mut self, method: &'static str, params: Value, id: i64) -> Response {
let request = Request::build(method).params(params).id(id).finish();
self.service
.ready()
.await
.unwrap()
.call(request)
.await
.unwrap()
.unwrap()
}
async fn notify(&mut self, method: &'static str, params: Value) {
let request = Request::build(method).params(params).finish();
assert!(
self.service
.ready()
.await
.unwrap()
.call(request)
.await
.unwrap()
.is_none()
);
}
async fn notification(&mut self, method: &str) -> Value {
loop {
let request = self
.socket
.next()
.now_or_never()
.expect("server notification should already be queued")
.unwrap();
if request.method() == method {
return request.params().cloned().unwrap_or(Value::Null);
}
}
}
fn explicit_path(&self) -> &std::path::Path {
self.explicit.as_deref().unwrap()
}
}
fn open_params(uri: &str, version: i32, text: &str) -> Value {
json!({
"textDocument": {
"uri": uri,
"languageId": "plaintext",
"version": version,
"text": text,
}
})
}
fn utf16_position_to_byte(source: &str, position: &Value) -> usize {
let target_line = position["line"].as_u64().unwrap() as usize;
let target_units = position["character"].as_u64().unwrap() as usize;
let line_start = if target_line == 0 {
0
} else {
source
.match_indices('\n')
.nth(target_line - 1)
.map(|(offset, _)| offset + 1)
.unwrap()
};
let line = &source[line_start..];
let mut units = 0;
for (relative, character) in line.char_indices() {
if units == target_units {
return line_start + relative;
}
units += character.len_utf16();
assert!(units <= target_units, "position splits a UTF-16 scalar");
}
line_start + line.len()
}
#[tokio::test]
async fn lifecycle_versions_unicode_quick_fixes_and_formatter_equivalence() {
let mut harness = Harness::new(None).await;
let uri = "file:///tmp/unicode.txt";
let source = "😀—one\r\ntwo−";
harness
.notify("textDocument/didOpen", open_params(uri, 1, source))
.await;
let published = harness
.notification("textDocument/publishDiagnostics")
.await;
assert_eq!(published["version"], 1);
assert_eq!(published["diagnostics"].as_array().unwrap().len(), 2);
assert_eq!(
published["diagnostics"][0]["range"]["start"],
json!({"line": 0, "character": 2})
);
let response = harness
.request(
"textDocument/codeAction",
json!({
"textDocument": { "uri": uri },
"range": {
"start": { "line": 0, "character": 0 },
"end": { "line": 1, "character": 4 }
},
"context": { "diagnostics": published["diagnostics"] }
}),
2,
)
.await;
let actions = response.result().unwrap().as_array().unwrap();
assert_eq!(actions.len(), 2);
let mut edits = actions
.iter()
.map(|action| {
let edit = &action["edit"]["documentChanges"][0]["edits"][0];
let start = utf16_position_to_byte(source, &edit["range"]["start"]);
let end = utf16_position_to_byte(source, &edit["range"]["end"]);
john_slop::TextEdit {
byte_span: ByteRange { start, end },
replacement: edit["newText"].as_str().unwrap().to_owned(),
}
})
.collect::<Vec<_>>();
edits.sort_by_key(|edit| edit.byte_span.start);
let lsp_output = apply_replacements(source, &edits).unwrap();
let formatter_output =
apply_replacements(source, &plan_replacements(&Config::embedded(), source)).unwrap();
assert_eq!(lsp_output, formatter_output);
harness
.notify(
"textDocument/didChange",
json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "plain ASCII" }]
}),
)
.await;
let cleared = harness
.notification("textDocument/publishDiagnostics")
.await;
assert_eq!(cleared["version"], 2);
assert!(cleared["diagnostics"].as_array().unwrap().is_empty());
let stale = harness
.request(
"textDocument/codeAction",
json!({
"textDocument": { "uri": uri },
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 1 } },
"context": { "diagnostics": published["diagnostics"] }
}),
3,
)
.await;
assert_eq!(stale.error().unwrap().code, ErrorCode::InvalidParams);
harness
.notify(
"textDocument/didClose",
json!({ "textDocument": { "uri": uri } }),
)
.await;
let closed = harness
.notification("textDocument/publishDiagnostics")
.await;
assert!(closed["diagnostics"].as_array().unwrap().is_empty());
assert!(closed["version"].is_null());
}
#[tokio::test]
async fn configuration_reload_and_concurrent_documents_remain_independent() {
let disabled = r#"
[[replacements]]
id = "em-dash"
enabled = false
"#;
let mut harness = Harness::new(Some(disabled)).await;
let first = "file:///tmp/first.txt";
let second = "untitled:second";
harness
.notify("textDocument/didOpen", open_params(first, 1, "first—doc"))
.await;
let one = harness
.notification("textDocument/publishDiagnostics")
.await;
harness
.notify("textDocument/didOpen", open_params(second, 3, "second−doc"))
.await;
let two = harness
.notification("textDocument/publishDiagnostics")
.await;
let by_uri = [one, two]
.into_iter()
.map(|params| (params["uri"].as_str().unwrap().to_owned(), params))
.collect::<std::collections::HashMap<_, _>>();
assert!(by_uri[first]["diagnostics"].as_array().unwrap().is_empty());
assert_eq!(by_uri[second]["diagnostics"].as_array().unwrap().len(), 1);
fs::write(
harness.explicit_path(),
r#"
[[replacements]]
id = "em-dash"
enabled = true
"#,
)
.unwrap();
let reload = Request::build("workspace/didChangeConfiguration")
.params(json!({ "settings": {} }))
.finish();
let service = &mut harness.service;
let socket = &mut harness.socket;
let reload_future = async { service.ready().await.unwrap().call(reload).await.unwrap() };
let notifications = async {
let first = socket.next().await.unwrap();
let second = socket.next().await.unwrap();
[first, second].map(|request| request.params().cloned().unwrap())
};
let (reload_response, [refreshed_one, refreshed_two]) =
tokio::join!(reload_future, notifications);
assert!(reload_response.is_none());
let refreshed = [refreshed_one, refreshed_two]
.into_iter()
.map(|params| (params["uri"].as_str().unwrap().to_owned(), params))
.collect::<std::collections::HashMap<_, _>>();
assert_eq!(refreshed[first]["diagnostics"].as_array().unwrap().len(), 1);
assert_eq!(
refreshed[second]["diagnostics"].as_array().unwrap().len(),
1
);
}
#[tokio::test]
async fn malformed_messages_and_invalid_uris_are_rejected_without_panics() {
assert!("not JSON".parse::<Request>().is_err());
let mut harness = Harness::new(None).await;
let malformed = harness
.request("textDocument/codeAction", json!({ "textDocument": {} }), 7)
.await;
assert_eq!(malformed.error().unwrap().code, ErrorCode::InvalidParams);
let invalid_uri = harness
.request(
"textDocument/codeAction",
json!({
"textDocument": { "uri": "http://[invalid" },
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } },
"context": { "diagnostics": [] }
}),
8,
)
.await;
assert_eq!(invalid_uri.error().unwrap().code, ErrorCode::InvalidParams);
}