Файли
openidea/crates/ide-host/tests/python_signature_ops.rs
T
LU XIANGRUIтаwildcatDownstairs e35ba7d805 feat(python): Change Signature through rope (#7622)
Refactor > Change Signature works on Python functions, methods and classes (their __init__). pylsp-rope has no such command, so the IDE runs an embedded helper with the pylsp-rope environment's Python: rope finds the function, its overrides and calls and renames parameters scope-aware; the parameter list and arguments are rewritten from the ast so annotations, defaults, the * and / markers and keyword arguments survive. Unsaved buffers are read through an overlay, calls rope can't resolve come from the type checker's references, and calls that can't be rewritten or likely mistakes are listed in a confirmation first. The result is a normal workspace edit (Preview, Refactor, one undo). The dialog is the Java one reduced to Name and Default value. The rope tests are ignored by default.

Refs #901

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 17:36:01 +08:00

119 рядки
6.0 KiB
Rust

//! Python Change Signature through the commands the app calls: the dialog's signature, the
//! edit it computes from the open (unsaved) buffers, applying it and undoing it. `#[ignore]`d:
//! it needs `pylsp` with rope on `PATH` (`pip install python-lsp-server pylsp-rope`).
mod common;
use ide_core::{ChangeSet, IdeEvent, Pos, RequestId, SharedSink, TextChange, error::ErrorKind};
use ide_host::{Host, HostConfig, ops};
use ide_lsp::types::SignatureParameter;
use parking_lot::Mutex;
use std::sync::Arc;
fn row(name: &str, default: &str, index: i32) -> SignatureParameter {
SignatureParameter {
type_name: String::new(),
name: name.into(),
default_value: default.into(),
original_index: index,
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs pylsp with rope on PATH"]
async fn changes_a_signature_from_unsaved_buffers_then_undoes_it() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("app");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"app\"\n").unwrap();
std::fs::write(root.join("lib.py"), "def f(a, b=2):\n return a\n").unwrap();
std::fs::write(root.join("use.py"), "from lib import f\n\nf(1, 2)\n").unwrap();
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
let sink: SharedSink = {
let events = events.clone();
Arc::new(move |event| events.lock().push(event))
};
let host =
Host::new(HostConfig { sink_for: Box::new(move |_| sink.clone()), ..common::host_config(&root.join(".app")) });
host.set_project_trust(&root, true, false).await.unwrap();
host.open_project("main", &root).unwrap();
let lib = ops::doc::doc_open(&host, "main", root.join("lib.py")).await.unwrap();
let usage = ops::doc::doc_open(&host, "main", root.join("use.py")).await.unwrap();
// An unsaved call that exists only in the editor.
let append = ChangeSet { changes: vec![TextChange { from: 27, to: 27, insert: "f(3, 4)\n".into() }] };
ops::doc::doc_edit(&host, "main", usage.id, usage.version, append).await.unwrap();
let caret = Pos::new(0, 5);
let info = ops::lsp::lsp_signature_info(&host, "main", RequestId(1), lib.id, caret).await.unwrap();
let names: Vec<_> = info.parameters.iter().map(|p| (p.name.as_str(), p.default_value.as_str())).collect();
assert_eq!((info.method_name.as_str(), names), ("f", vec![("a", ""), ("b", "2")]));
let mut changed = info.clone();
changed.parameters = vec![row("b", "2", 1), row("a", "", 0)];
let swapped =
ops::lsp::lsp_change_signature(&host, "main", RequestId(2), lib.id, caret, changed.clone(), false, None).await;
assert!(swapped.is_err(), "a default before a parameter without one is refused");
changed.parameters = vec![row("a", "", 0), row("b", "2", 1), row("c", "None", -1)];
changed.method_name = "g".into();
let answer =
ops::lsp::lsp_change_signature(&host, "main", RequestId(3), lib.id, caret, changed, false, None).await.unwrap();
let edit = answer.edit.expect("an edit");
ops::lsp::apply_workspace_edit(&host, "main", edit).await.unwrap();
assert_eq!(
ops::doc::doc_snapshot(&host, "main", lib.id).await.unwrap().text,
"def g(a, b=2, c=None):\n return a\n"
);
assert_eq!(
ops::doc::doc_snapshot(&host, "main", usage.id).await.unwrap().text,
"from lib import g\n\ng(1, 2)\ng(3, 4)\n"
);
let id = events
.lock()
.iter()
.find_map(|event| match event {
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
_ => None,
})
.unwrap();
ops::lsp::undo_workspace_edit(&host, "main", id).await.unwrap();
assert_eq!(ops::doc::doc_snapshot(&host, "main", lib.id).await.unwrap().text, "def f(a, b=2):\n return a\n");
assert_eq!(
ops::doc::doc_snapshot(&host, "main", usage.id).await.unwrap().text,
"from lib import f\n\nf(1, 2)\nf(3, 4)\n"
);
// A refusal comes back as an invalid-input error with rope's reason.
let mut bad = info;
bad.parameters = vec![row("b", "2", 1), row("a", "", 0), row("a", "", -1)];
let error =
ops::lsp::lsp_change_signature(&host, "main", RequestId(4), lib.id, caret, bad, false, None).await.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains("Duplicate"), "{}", error.message);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs pylsp with rope on PATH"]
async fn a_closed_file_with_a_byte_order_mark_keeps_its_first_character() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("app");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("lib.py"), "def f(a, b):\n return a\n").unwrap();
std::fs::write(root.join("use.py"), "\u{feff}from lib import f\n\nf(1, 2)\n").unwrap();
let host =
Host::new(HostConfig { sink_for: Box::new(|_| Arc::new(|_| {})), ..common::host_config(&root.join(".app")) });
host.set_project_trust(&root, true, false).await.unwrap();
host.open_project("main", &root).unwrap();
let lib = ops::doc::doc_open(&host, "main", root.join("lib.py")).await.unwrap();
let caret = Pos::new(0, 4);
let mut changed = ops::lsp::lsp_signature_info(&host, "main", RequestId(1), lib.id, caret).await.unwrap();
changed.parameters = vec![row("b", "", 1), row("a", "", 0)];
let answer =
ops::lsp::lsp_change_signature(&host, "main", RequestId(2), lib.id, caret, changed, false, None).await.unwrap();
ops::lsp::apply_workspace_edit(&host, "main", answer.edit.expect("an edit")).await.unwrap();
let usage = ops::doc::doc_open(&host, "main", root.join("use.py")).await.unwrap();
assert_eq!(usage.text, "from lib import f\n\nf(2, 1)\n");
let bytes = std::fs::read(root.join("use.py")).unwrap();
assert!(bytes.starts_with("\u{feff}from lib".as_bytes()), "{bytes:?}");
}