Файли
openidea/crates/ide-host/tests/python_move.rs
T
LU XIANGRUIтаwildcatDownstairs fc60719d4b feat(python): move top-level functions, classes and variables to another module (#7680)
Refactor > Move (F6) in a .py file moves top-level functions, classes and variables to another module. The dialog has From file, To file (a .py path in the project, new or existing) and Elements to Move. An embedded ast-based helper, run with the pylsp-rope environment's Python, moves the code with its decorators and attached comments, places it by import-time dependencies, writes the imports both modules need and rewrites module.name uses; from ... import statements across the project go through the existing module-move rewriter. Unsaved buffers are read, a file changed meanwhile is refused, and every changed file is parsed again before the edit is returned. A name already defined at the destination is refused; risky cases are confirmed first. The tests needing pylsp are ignored by default.

Refs #901

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

401 рядки
17 KiB
Rust

//! Python Move through the commands the app calls, on real files: each moved project is run with
//! Python before and after, and must print the same. `#[ignore]`d: it needs `pylsp` on `PATH`
//! (the helper runs with that environment's Python).
mod common;
use ide_core::{ChangeSet, IdeEvent, RequestId, SharedSink, TextChange};
use ide_host::{Host, HostConfig, ops};
use ide_lsp::types::ServerRefactored;
use parking_lot::Mutex;
use serde_json::json;
use std::path::PathBuf;
use std::sync::Arc;
struct Project {
_tmp: tempfile::TempDir,
root: PathBuf,
host: Host,
events: Arc<Mutex<Vec<IdeEvent>>>,
}
impl Project {
async fn new(files: &[(&str, &str)]) -> Self {
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();
for (name, text) in files {
let path = root.join(name);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).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();
Self { _tmp: tmp, root, host, events }
}
/// Moves `names` of `source` to `dest`, accepting any warnings, and applies the edit.
async fn try_move(&self, source: &str, names: &[&str], dest: &str) -> Result<Vec<String>, String> {
let doc = ops::doc::doc_open(&self.host, "main", self.root.join(source)).await.unwrap();
let args = json!({ "names": names, "file": dest }).to_string();
let send = |confirmation| {
ops::lsp::lsp_java_move(
&self.host,
"main",
RequestId(1),
doc.id,
"python".into(),
args.clone(),
confirmation,
)
};
let mut answer: ServerRefactored = send(None).await.map_err(|e| e.message)?;
let mut warnings = Vec::new();
if answer.confirmation.is_some() {
assert!(answer.edit.is_none(), "nothing before the confirmation");
warnings = answer.problems.iter().map(|p| p.message.clone()).collect();
answer = send(answer.confirmation).await.map_err(|e| e.message)?;
}
ops::lsp::apply_workspace_edit(&self.host, "main", answer.edit.expect("an edit")).await.unwrap();
Ok(warnings)
}
async fn text(&self, file: &str) -> String {
let doc = ops::doc::doc_open(&self.host, "main", self.root.join(file)).await.unwrap();
ops::doc::doc_snapshot(&self.host, "main", doc.id).await.unwrap().text
}
/// Writes the editors' texts out and runs `main.py`.
async fn output(&self) -> String {
self.output_without(&[]).await
}
async fn output_without(&self, skipped: &[&str]) -> String {
for file in walk(&self.root).into_iter().filter(|f| !skipped.contains(&f.as_str())) {
let text = self.text(&file).await;
std::fs::write(self.root.join(file), text).unwrap();
}
let out = std::process::Command::new(if cfg!(windows) { "python" } else { "python3" })
.args(["-B", "main.py"])
.current_dir(&self.root)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n")
}
}
fn walk(root: &std::path::Path) -> Vec<String> {
let mut found = Vec::new();
let mut folders = vec![root.to_path_buf()];
while let Some(folder) = folders.pop() {
for entry in std::fs::read_dir(folder).unwrap().flatten() {
let path = entry.path();
if path.is_dir() && !entry.file_name().to_string_lossy().starts_with('.') {
folders.push(path);
} else if path.extension().is_some_and(|e| e == "py") {
found.push(path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/"));
}
}
}
found
}
const LIB: &str = r#""""Library."""
import os
from math import floor
SEP = os.sep
LIMIT: int = 3
def helper(x):
return floor(x) + LIMIT
# The thing to move.
# 中文注释 🎉
@staticmethod
def double(x) -> "int":
return helper(x) * 2
class Box:
def __init__(self, v=LIMIT):
self.v = double(v)
def keep():
return Box().v
"#;
const MAIN: &str = r#"import pkg.lib
import pkg.lib as aliased
from pkg import lib
from pkg.lib import Box, double as twice, keep
from pkg import Box as Exported
print(pkg.lib.Box(1).v, aliased.double(1), lib.double(2))
print(Box(2).v, twice(3), keep(), Exported().v)
"#;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs pylsp on PATH"]
async fn moves_into_a_new_module_and_updates_every_spelling_then_undoes_it() {
let p = Project::new(&[
("pkg/__init__.py", "from .lib import Box\n"),
("pkg/lib.py", LIB),
("pkg/rel.py", "from . import lib\nfrom .lib import Box\n\n\ndef f():\n return lib.Box().v + Box().v\n"),
("main.py", &format!("{MAIN}from pkg.rel import f\nprint(f())\n")),
])
.await;
let before = p.output().await;
let warnings = p.try_move("pkg/lib.py", &["double", "Box"], "pkg/shapes/box.py").await.unwrap();
assert!(warnings.iter().any(|w| w.contains("import each other")), "{warnings:?}");
let lib = p.text("pkg/lib.py").await;
assert!(lib.contains("from pkg.shapes.box import Box\n"), "{lib}");
assert!(!lib.contains("def double") && !lib.contains("class Box") && !lib.contains("中文"), "{lib}");
let moved = p.text("pkg/shapes/box.py").await;
assert!(moved.contains("# The thing to move.\n# 中文注释 🎉\n@staticmethod\ndef double"), "{moved}");
assert!(moved.contains("from pkg.lib import LIMIT\n") && moved.contains("from pkg.lib import helper\n"), "{moved}");
assert_eq!(p.text("pkg/__init__.py").await, "from .shapes.box import Box\n");
// The two modules now import each other, which is the one warning.
assert_eq!(warnings.len(), 1, "{warnings:?}");
let id = p
.events
.lock()
.iter()
.find_map(|e| match e {
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
_ => None,
})
.unwrap();
ops::lsp::undo_workspace_edit(&p.host, "main", id).await.unwrap();
assert!(!p.root.join("pkg/shapes").join("box.py").exists(), "the new module is removed again");
assert_eq!(p.text("pkg/lib.py").await, LIB);
assert_eq!(p.output().await, before);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs pylsp on PATH"]
async fn the_moved_project_runs_the_same() {
let p = Project::new(&[
("pkg/__init__.py", "from .lib import Box\n"),
(
"pkg/lib.py",
"from __future__ import annotations\n\nimport json\nfrom . import consts\nfrom .consts import N as COUNT\n\n\nclass Box:\n v: int = COUNT + consts.N\n\n def dump(self) -> str:\n return json.dumps(self.v)\n\n\ndef make():\n return Box()\n\n\nprint(make().dump())\n",
),
("pkg/consts.py", "N = 2\n"),
("pkg/other.py", "\"\"\"Doc.\"\"\"\nimport sys\n\nHAVE = sys.maxsize > 0\n"),
(
"main.py",
"import pkg.lib\nfrom pkg.lib import *\nfrom pkg import lib as l\nfrom pkg import Box as B\n\nprint(Box().dump(), l.make().v, pkg.lib.Box.v, B.v, make().v)\n",
),
])
.await;
let before = p.output().await;
let warnings = p.try_move("pkg/lib.py", &["Box"], "pkg/other.py").await.unwrap();
assert!(warnings.iter().any(|w| w.contains("import *")), "{warnings:?}");
let other = p.text("pkg/other.py").await;
assert!(other.starts_with("\"\"\"Doc.\"\"\"\nfrom __future__ import annotations\n"), "{other}");
assert!(other.contains("from pkg.consts import N as COUNT\n") && other.contains("import json\n"), "{other}");
assert_eq!(p.output().await, before);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs pylsp on PATH"]
async fn a_destination_that_uses_the_name_gets_it_defined_first() {
let p = Project::new(&[
("a.py", "def f():\n return 1\n\n\ndef g():\n return 2\n"),
("b.py", "import a\nfrom a import f, g\n\nX = f() + a.f() + g()\n"),
("main.py", "import b\nprint(b.X, b.f())\n"),
])
.await;
let before = p.output().await;
// unsaved: a use that exists only in the editor
let doc = ops::doc::doc_open(&p.host, "main", p.root.join("main.py")).await.unwrap();
let at = doc.text.len() as u32;
let change =
ChangeSet { changes: vec![TextChange { from: at, to: at, insert: "import a\nprint(a.f())\n".into() }] };
ops::doc::doc_edit(&p.host, "main", doc.id, doc.version, change).await.unwrap();
p.try_move("a.py", &["f"], "b.py").await.unwrap();
let b = p.text("b.py").await;
assert!(b.find("def f").unwrap() < b.find("X = ").unwrap(), "{b}");
assert!(b.contains("X = f() + f() + g()"), "{b}");
assert!(p.text("main.py").await.contains("print(b.f())"), "{}", p.text("main.py").await);
assert_eq!(p.output().await, format!("{before}1\n"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs pylsp on PATH"]
async fn refuses_what_it_cannot_move_safely_and_changes_nothing() {
let source = "import os\n\nA = 1\nA = 2\n\n\ndef f():\n return os.sep\n\n\ndef g():\n global C\n C = 1\n\n\nC = 0\nD = 1; E = 2\n";
let p = Project::new(&[
("a.py", source),
("taken.py", "def f():\n pass\n"),
("os_is_mine.py", "os = 1\n"),
("alias.py", "from a import f as h\n"),
("broken.py", "def (:\n"),
])
.await;
for (names, dest, reason) in [
(vec!["f"], "taken.py", "already defined"),
(vec!["f"], "os_is_mine.py", "means something else"),
(vec!["f"], "alias.py", "another name"),
(vec!["f"], "broken.py", "Syntax error"),
(vec!["f"], "a.py", "itself"),
(vec!["f"], "new.txt", ".py file"),
(vec!["f"], "../out.py", ".py file"),
(vec!["f"], "1bad.py", "Python module"),
(vec!["A"], "new.py", "several places"),
(vec!["g"], "new.py", "global"),
(vec!["C"], "new.py", "global"),
(vec!["D"], "new.py", "shares its line"),
(vec!["missing"], "new.py", "not a top-level"),
(vec![], "new.py", "Select"),
] {
let error = p.try_move("a.py", &names, dest).await.unwrap_err();
assert!(error.contains(reason), "{names:?} -> {dest}: {error}");
}
assert_eq!(p.text("a.py").await, source);
assert!(!p.root.join("new.py").exists());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs pylsp on PATH"]
async fn reports_what_it_leaves_alone() {
let p = Project::new(&[
("a.py", "def f():\n return __name__\n"),
("use.py", "import a\n\nTARGET = 'a.f'\n\n\ndef g(a):\n return a.f\n"),
("broken.py", "import a\ndef (:\n"),
])
.await;
let warnings = p.try_move("a.py", &["f"], "b.py").await.unwrap();
for part in ["__name__", "the string 'a.f'", "local name", "syntax error"] {
assert!(warnings.iter().any(|w| w.contains(part)), "{part}: {warnings:?}");
}
assert!(p.text("use.py").await.ends_with("def g(a):\n return a.f\n"));
assert_eq!(p.text("a.py").await, "");
assert_eq!(p.text("b.py").await, "def f():\n return __name__\n");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs pylsp on PATH"]
async fn lists_the_movable_names_and_marks_the_one_at_the_caret() {
let p = Project::new(&[("lib.py", LIB)]).await;
let doc = ops::doc::doc_open(&p.host, "main", p.root.join("lib.py")).await.unwrap();
let line = LIB.lines().position(|l| l == "@staticmethod").unwrap();
let args = json!({ "line": line }).to_string();
let found = ops::lsp::lsp_java_move_destinations(&p.host, "main", RequestId(1), doc.id, "python".into(), args)
.await
.unwrap();
let found: Vec<serde_json::Value> = found.iter().map(|s| serde_json::from_str(s).unwrap()).collect();
let names: Vec<_> = found.iter().map(|s| s["name"].as_str().unwrap()).collect();
assert_eq!(names, ["SEP", "LIMIT", "helper", "double", "Box", "keep"]);
let selected: Vec<_> = found.iter().filter(|s| s["selected"] == true).map(|s| &s["name"]).collect();
assert_eq!(selected, ["double"]);
}
/// Order at import time: moved code goes after what it needs and before what needs it.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs pylsp on PATH"]
async fn places_the_code_where_the_destination_still_runs() {
let p = Project::new(&[
("a.py", "def f():\n return 1\n # end of f\n\n\nclass C(__import__('b').Base):\n pass\n"),
(
"b.py",
"class Base:\n pass\n\n\ndef main():\n print(f())\n\n\nif __name__ == '__main__':\n main()\n\n\ndef lazy():\n from a import f\n return f()\n",
),
("main.py", "import runpy\n\nimport b\n\nrunpy.run_path('b.py', run_name='__main__')\nprint(b.lazy())\n"),
])
.await;
p.try_move("a.py", &["f"], "b.py").await.unwrap();
let b = p.text("b.py").await;
assert!(b.find("def f").unwrap() < b.find("if __name__").unwrap(), "{b}");
assert!(b.contains("# end of f") && !p.text("a.py").await.contains("end of f"), "{b}");
assert_eq!(p.output().await, "1\n1\n");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs pylsp on PATH"]
async fn every_import_of_the_module_gets_the_new_one() {
let p = Project::new(&[
("a.py", "import urllib.parse\nimport urllib.request\n\n\ndef f():\n return urllib.parse.quote(' '), urllib.request.__name__\n"),
(
"main.py",
"def g():\n import a\n return a.f()\n\n\ndef h():\n import a\n return a.f()\n\n\nimport a; print(a.f())\ntry: import a\nexcept ImportError: pass\nprint(g(), h(), a.f())\n",
),
])
.await;
let before = p.output().await;
p.try_move("a.py", &["f"], "b.py").await.unwrap();
assert_eq!(p.output().await, before);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs pylsp on PATH"]
async fn refuses_shadowed_names_and_shadowed_destinations() {
let source = "def f():\n pass\n";
let p = Project::new(&[
("a.py", source),
("use.py", "import a\n\n\ndef g(b):\n return a.f(), b\n"),
("utils/__init__.py", ""),
("pkg.py", ""),
("early.py", "X = f()\n\n\nclass Base:\n pass\n"),
("c.py", "from early import Base\n\n\nclass D(Base):\n pass\n"),
])
.await;
for (dest, reason) in [("b.py", "already uses the name 'b'"), ("utils.py", "same name"), ("pkg/x.py", "same name")]
{
let error = p.try_move("a.py", &["f"], dest).await.unwrap_err();
assert!(error.contains(reason), "{dest}: {error}");
}
p.try_move("c.py", &["D"], "early.py").await.unwrap();
assert!(p.text("early.py").await.find("class Base").unwrap() < p.text("early.py").await.find("class D").unwrap());
assert_eq!(p.text("a.py").await, source);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs pylsp on PATH"]
async fn refuses_a_destination_behind_a_link_out_of_the_project() {
let p = Project::new(&[("a.py", "def f():\n pass\n")]).await;
let outside = tempfile::tempdir().unwrap();
std::os::unix::fs::symlink(outside.path(), p.root.join("linked")).unwrap();
let error = p.try_move("a.py", &["f"], "linked/b.py").await.unwrap_err();
assert!(error.contains("inside the project"), "{error}");
}
/// Closed files keep their byte order mark and encoding; a package's `from . import name` follows.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "needs pylsp on PATH"]
async fn closed_files_in_other_encodings_and_package_imports() {
let p = Project::new(&[
("pkg/__init__.py", "# Copyright ACME\ndef helper():\n return 1\n"),
("pkg/rel.py", "from . import helper\n\nX = helper()\n"),
("bom.py", "\u{feff}import os\nfrom pkg import helper\nprint(helper(), os.sep != '')\n"),
("main.py", "import bom\nfrom pkg.rel import X\nprint(X)\n"),
])
.await;
// GBK, not UTF-8
std::fs::write(p.root.join("gbk.py"), b"# -*- coding: gbk -*-\n# \xd6\xd0\nimport os\n").unwrap();
let before = p.output_without(&["gbk.py"]).await;
p.try_move("pkg/__init__.py", &["helper"], "pkg/tools.py").await.unwrap();
assert!(std::fs::read(p.root.join("bom.py")).unwrap().starts_with("\u{feff}import os\n".as_bytes()));
assert!(p.text("pkg/__init__.py").await.starts_with("# Copyright ACME"));
assert!(p.text("pkg/rel.py").await.contains("tools import helper"), "{}", p.text("pkg/rel.py").await);
assert_eq!(p.output_without(&["gbk.py"]).await, before);
}