//! Python Change Signature against real rope: the matrix of `python_signature.py`. `#[ignore]`d //! because it needs rope: `cargo test -p ide-host --test python_signature -- --ignored`. //! The interpreter is `$ROPE_PYTHON`, //! else `python3` / `python`. use serde_json::{Value, json}; use std::collections::BTreeMap; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; /// Relative to the crate directory, where `cargo test` and the smoke job run the binary. const HELPER: &str = "src/python_signature.py"; fn python() -> String { if let Ok(python) = std::env::var("ROPE_PYTHON") { return python; } ["python3", "python"] .into_iter() .find(|p| Command::new(p).args(["-c", "import rope"]).output().is_ok_and(|o| o.status.success())) .expect("python with rope (pip install rope) on PATH, or ROPE_PYTHON") .to_owned() } /// A parameter row: name, default, index in the current parameter list (-1: new). type Row = (&'static str, &'static str, i32); struct Project { dir: tempfile::TempDir, } impl Project { fn new(files: &[(&str, &str)]) -> Self { let dir = tempfile::tempdir().unwrap(); for (name, text) in files { let path = dir.path().join(name); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(path, text).unwrap(); } Self { dir } } fn root(&self) -> PathBuf { std::fs::canonicalize(self.dir.path()).unwrap() } fn run(&self, request: Value) -> Value { let mut child = Command::new(python()) .arg(HELPER) // what a Windows console would decode stdin with .env("PYTHONIOENCODING", "cp1252") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .unwrap(); child.stdin.take().unwrap().write_all(request.to_string().as_bytes()).unwrap(); let out = child.wait_with_output().unwrap(); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); serde_json::from_slice(&out.stdout).unwrap() } /// `word` on the first line of `file` containing `line`, as an LSP position. fn at(&self, file: &str, line: &str, word: &str) -> (usize, usize) { let text = std::fs::read_to_string(self.root().join(file)).unwrap(); let (i, l) = text.lines().enumerate().find(|(_, l)| l.contains(line)).expect("line"); (i, l[..l.find(line).unwrap() + line.find(word).unwrap()].encode_utf16().count()) } fn request(&self, op: &str, file: &str, at: (usize, usize), overlay: &BTreeMap) -> Value { let overlay: BTreeMap = overlay.iter().map(|(k, v)| (self.root().join(k).to_string_lossy().into_owned(), v)).collect(); json!({ "op": op, "root": self.root(), "file": self.root().join(file), "line": at.0, "col": at.1, "overlay": overlay, }) } /// The parameter rows rope reads at `at`. fn info(&self, file: &str, line: &str, word: &str) -> Result, String> { let at = self.at(file, line, word); let answer = self.run(self.request("info", file, at, &BTreeMap::new())); if answer["ok"] != true { return Err(answer["error"].as_str().unwrap().to_owned()); } Ok(answer["result"]["params"] .as_array() .unwrap() .iter() .map(|p| p["name"].as_str().unwrap().to_owned()) .collect()) } fn change(&self, c: &Change) -> Result<(BTreeMap, Vec), String> { let at = self.at(c.file, c.line, c.word); let mut request = self.request("change", c.file, at, &c.overlay()); let rows: Vec = c .rows .iter() .map(|(n, d, i)| json!({ "name": n, "defaultValue": d, "originalIndex": i, "type": "" })) .collect(); request["change"] = json!({ "name": c.name, "params": rows, "hierarchy": true }); request["sites"] = c .sites .iter() .map(|(file, line, word)| { let (l, col) = self.at(file, line, word); json!({ "path": self.root().join(file), "line": l, "col": col, "len": word.trim_end_matches('(').len() }) }) .collect(); let answer = self.run(request); if answer["ok"] != true { return Err(answer["error"].as_str().unwrap().to_owned()); } let root = self.root(); let files = answer["result"]["files"] .as_object() .unwrap() .iter() .map(|(k, v)| { ( Path::new(k).strip_prefix(&root).unwrap().to_string_lossy().into_owned(), v.as_str().unwrap().to_owned(), ) }) .collect(); let warnings = answer["result"]["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_owned()).collect(); Ok((files, warnings)) } } struct Change { file: &'static str, line: &'static str, word: &'static str, name: &'static str, rows: Vec, unsaved: Vec<(&'static str, &'static str)>, /// Calls a type-aware server reports: file, a line, and the word on it that names the function. sites: Vec<(&'static str, &'static str, &'static str)>, } impl Change { fn overlay(&self) -> BTreeMap { self.unsaved.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect() } } fn change(file: &'static str, line: &'static str, word: &'static str, name: &'static str, rows: Vec) -> Change { Change { file, line, word, name, rows, unsaved: Vec::new(), sites: Vec::new() } } /// Runs `c` on `files` and compares every changed file; `expect` lists exactly the files that change. #[track_caller] fn check(files: &[(&str, &str)], c: Change, expect: &[(&str, &str)]) -> Vec { let project = Project::new(files); let (changed, warnings) = project.change(&c).unwrap_or_else(|e| panic!("refused: {e}")); let want: BTreeMap = expect.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(); assert_eq!(changed, want); warnings } #[track_caller] fn refused(files: &[(&str, &str)], c: Change) -> String { Project::new(files).change(&c).expect_err("should be refused") } const LIB: &str = "def f(a, b=2, *args, key=1, **kw):\n return a\n"; #[test] #[ignore = "needs rope"] fn reads_the_parameter_list_from_a_call_a_header_or_the_class() { let files = [( "lib.py", "class C:\n def __init__(self, a, /, b=1, *, c):\n pass\n\n def m(self, x):\n pass\n\n\ndef f(a, b=2, *args, key=1, **kw):\n return a\n\n\nf(1)\nC(1, c=2).m(3)\n", )]; let p = Project::new(&files); let rows = |r: Result, String>| r.unwrap().join(" "); assert_eq!(rows(p.info("lib.py", "def f(", "f(")), "a b *args key **kw"); assert_eq!(rows(p.info("lib.py", "def f(a, b=2", "b=2")), "a b *args key **kw", "caret inside the header"); assert_eq!(rows(p.info("lib.py", "f(1)", "f(")), "a b *args key **kw", "caret on a call"); assert_eq!(rows(p.info("lib.py", "def __init__", "__init__")), "self a / b * c"); assert_eq!(rows(p.info("lib.py", "class C", "C")), "self a / b * c", "the class stands for __init__"); assert_eq!(rows(p.info("lib.py", "C(1, c=2).m(3)", "m(")), "self x", "caret on a method call"); assert!(p.info("lib.py", " return a", "return").is_err(), "caret in a body is not a function"); } #[test] #[ignore = "needs rope"] fn reorders_positional_arguments_in_every_file_through_re_exports_and_relative_imports() { // A call through an alias (`import f as g`) is a reference the language server reports. let mut c = change("pkg/core.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]); c.sites = vec![("top.py", "g(5, 6)", "g")]; check( &[ ("pkg/__init__.py", "from .core import f\n"), ("pkg/core.py", "def f(a, b):\n return a - b\n"), ("pkg/sub/use.py", "from .. import f\n\nf(1, 2)\nf(b=2, a=1)\n"), ("top.py", "import pkg\nfrom pkg.core import f as g\n\npkg.f(3, 4)\ng(5, 6)\n"), ], c, &[ ("pkg/core.py", "def f(b, a):\n return a - b\n"), ("pkg/sub/use.py", "from .. import f\n\nf(2, 1)\nf(b=2, a=1)\n"), ("top.py", "import pkg\nfrom pkg.core import f as g\n\npkg.f(4, 3)\ng(6, 5)\n"), ], ); } #[test] #[ignore = "needs rope"] fn keeps_annotations_defaults_decorators_and_the_return_type() { check( &[( "m.py", "import functools\n\n\n@functools.cache\ndef f(a: int, b: str = \"x\", *, flag: bool = False, n: int = 0) -> dict[str, int]: # note\n return {}\n\n\nf(1, \"y\", flag=True)\n", )], change( "m.py", "def f(", "f(", "f", vec![("a", "", 0), ("b", "\"x\"", 1), ("*", "", 2), ("n", "0", 4), ("flag", "False", 3)], ), &[( "m.py", "import functools\n\n\n@functools.cache\ndef f(a: int, b: str = \"x\", *, n: int = 0, flag: bool = False) -> dict[str, int]: # note\n return {}\n\n\nf(1, \"y\", flag=True)\n", )], ); } #[test] #[ignore = "needs rope"] fn refuses_a_default_before_a_parameter_without_one() { let e = refused(&[("m.py", LIB)], change("m.py", "def f(", "f(", "f", vec![("b", "2", 1), ("a", "", 0)])); assert!(e.contains("follows a parameter with a default"), "{e}"); } #[test] #[ignore = "needs rope"] fn moves_a_defaulted_parameter_to_keyword_style_calls_when_it_is_skipped() { // `f(1, 2)` binds a=1, b=2; with `b` moved after `c=0` the call keeps meaning by naming it. check( &[("m.py", "def f(a, b=2, c=0):\n pass\n\n\nf(1, 5)\nf(1, c=3)\n")], change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("c", "0", 2), ("b", "2", 1)]), &[("m.py", "def f(a, c=0, b=2):\n pass\n\n\nf(1, b=5)\nf(1, c=3)\n")], ); } #[test] #[ignore = "needs rope"] fn adds_a_parameter_with_a_default_and_calls_stay_valid() { check( &[("m.py", "def f(a, b):\n pass\n\n\nf(1, 2)\n")], change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("b", "", 1), ("c", "None", -1)]), &[("m.py", "def f(a, b, c=None):\n pass\n\n\nf(1, 2)\n")], ); } #[test] #[ignore = "needs rope"] fn an_added_default_stands_in_while_a_later_argument_stays_positional() { check( &[("m.py", "def f(a, b=2):\n pass\n\n\nf(1, 5)\nf(1)\n")], change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("c", "0", -1), ("b", "2", 1)]), &[("m.py", "def f(a, c=0, b=2):\n pass\n\n\nf(1, 0, 5)\nf(1)\n")], ); } #[test] #[ignore = "needs rope"] fn refuses_a_new_parameter_without_a_default() { let e = refused(&[("m.py", LIB)], change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("z", "", -1)])); assert!(e.contains("Default value"), "{e}"); } #[test] #[ignore = "needs rope"] fn removes_a_parameter_from_positional_and_keyword_calls() { let warnings = check( &[("m.py", "def f(a, b, c=3):\n return a + c\n\n\nf(1, 2)\nf(1, 2, 4)\nf(1, c=4, b=2)\n")], change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("c", "3", 2)]), &[("m.py", "def f(a, c=3):\n return a + c\n\n\nf(1)\nf(1, 4)\nf(1, c=4)\n")], ); assert!(warnings.is_empty(), "{warnings:?}"); } #[test] #[ignore = "needs rope"] fn warns_when_a_removed_parameter_is_still_used() { let warnings = check( &[("m.py", "def f(a, b):\n return a + b\n\n\nf(1, 2)\n")], change("m.py", "def f(", "f(", "f", vec![("a", "", 0)]), &[("m.py", "def f(a):\n return a + b\n\n\nf(1)\n")], ); assert!(warnings[0].contains("'b' is removed but still used"), "{warnings:?}"); } #[test] #[ignore = "needs rope"] fn renames_parameters_in_the_body_and_in_keyword_arguments_but_not_in_other_scopes() { check( &[ ( "m.py", "def f(a, b=2):\n xs = [a for a in range(3)]\n\n def g(a):\n return a\n\n return a + b\n", ), ("u.py", "from m import f\n\nf(a=1)\nf(1, b=3)\n"), ], change("m.py", "def f(", "f(", "f", vec![("first", "", 0), ("b", "2", 1)]), &[ ( "m.py", "def f(first, b=2):\n xs = [a for a in range(3)]\n\n def g(a):\n return a\n\n return first + b\n", ), ("u.py", "from m import f\n\nf(first=1)\nf(1, b=3)\n"), ], ); } #[test] #[ignore = "needs rope"] fn renames_the_function_everywhere() { check( &[("m.py", "def f(a):\n pass\n"), ("u.py", "from m import f\n\nf(1)\n")], change("m.py", "def f(", "f(", "run", vec![("a", "", 0)]), &[("m.py", "def run(a):\n pass\n"), ("u.py", "from m import run\n\nrun(1)\n")], ); } #[test] #[ignore = "needs rope"] fn variadic_parameters_move_with_their_arguments() { check( &[("m.py", "def f(a, *args, **kw):\n pass\n\n\nf(1, 2, 3, x=4)\n")], change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("sep", "None", -1), ("*args", "", 1), ("**kw", "", 2)]), &[("m.py", "def f(a, sep=None, *args, **kw):\n pass\n\n\nf(1, None, 2, 3, x=4)\n")], ); } #[test] #[ignore = "needs rope"] fn dropping_args_drops_the_extra_positional_arguments() { let warnings = check( &[("m.py", "def f(a, *args):\n pass\n\n\nf(1, 2, 3)\n")], change("m.py", "def f(", "f(", "f", vec![("a", "", 0)]), &[("m.py", "def f(a):\n pass\n\n\nf(1)\n")], ); assert!(warnings[0].contains("removed '*' parameter"), "{warnings:?}"); } #[test] #[ignore = "needs rope"] fn keyword_only_and_positional_only_markers_follow_their_parameters() { check( &[("m.py", "def f(a, b, /, c, *, d):\n pass\n\n\nf(1, 2, 3, d=4)\nf(1, 2, c=3, d=4)\n")], change( "m.py", "def f(", "f(", "f", vec![("a", "", 0), ("b", "", 1), ("/", "", 2), ("*", "", 4), ("c", "", 3), ("d", "", 5)], ), &[("m.py", "def f(a, b, /, *, c, d):\n pass\n\n\nf(1, 2, c=3, d=4)\nf(1, 2, c=3, d=4)\n")], ); } #[test] #[ignore = "needs rope"] fn refuses_what_python_rejects() { let at = |rows: Vec| refused(&[("m.py", "def f(a, b, c):\n pass\n")], change("m.py", "def f(", "f(", "f", rows)); assert!(at(vec![("a", "", 0), ("a", "", 1)]).contains("Duplicate parameter name")); assert!(at(vec![("a", "", 0), ("class", "1", -1)]).contains("not a valid parameter name")); assert!(at(vec![("a", "", 0), ("*", "", -1)]).contains("keyword-only")); assert!(at(vec![("**kw", "", -1), ("a", "", 0)]).contains("must be last")); assert!(at(vec![("a", "", 0), ("*x", "", -1), ("*y", "", -1)]).contains("Only one")); assert!(at(vec![("a", "", 0), ("b", "1+", -1)]).contains("not a valid expression")); let e = refused( &[("m.py", "def f(a, b):\n pass\n")], change("m.py", "def f(", "f(", "class", vec![("a", "", 0), ("b", "", 1)]), ); assert!(e.contains("Cannot rename"), "{e}"); } #[test] #[ignore = "needs rope"] fn refuses_renaming_a_parameter_to_the_name_of_another() { let e = refused( &[("m.py", "def f(a, b):\n pass\n")], change("m.py", "def f(", "f(", "f", vec![("b", "", 0), ("a", "", 1)]), ); assert!(e.contains("another parameter has that name"), "{e}"); } #[test] #[ignore = "needs rope"] fn methods_change_with_their_overrides_and_every_kind_of_call() { let files = [ ( "m.py", "class Base:\n def run(self, x, y):\n return x\n\n\nclass Child(Base):\n def run(self, x, y):\n return super().run(x, y)\n\n\ndef use(o: Base):\n o.run(1, 2)\n Base.run(o, 1, 2)\n Child().run(y=2, x=1)\n", ), ("n.py", "from m import Base\n\nBase().run(\n 1,\n 2,\n)\n"), ]; let mut c = change("m.py", "def run(self, x, y)", "run(", "run", vec![("self", "", 0), ("y", "", 2), ("x", "", 1)]); // rope resolves neither an annotated parameter nor `super()`; the language server does. c.sites = vec![("m.py", "o.run(1, 2)", "run("), ("m.py", "super().run(", "run(")]; check( &files, c, &[ ( "m.py", "class Base:\n def run(self, y, x):\n return x\n\n\nclass Child(Base):\n def run(self, y, x):\n return super().run(y, x)\n\n\ndef use(o: Base):\n o.run(2, 1)\n Base.run(o, 2, 1)\n Child().run(y=2, x=1)\n", ), ("n.py", "from m import Base\n\nBase().run(\n 2,\n 1,\n)\n"), ], ); } #[test] #[ignore = "needs rope"] fn refuses_to_change_the_self_parameter_of_a_method() { let e = refused( &[("m.py", "class C:\n def m(self, x):\n pass\n")], change("m.py", "def m(", "m(", "m", vec![("x", "", 1), ("self", "", 0)]), ); assert!(e.contains("cannot be changed"), "{e}"); } #[test] #[ignore = "needs rope"] fn static_and_class_methods_bind_like_their_decorators() { check( &[( "m.py", "class C:\n @staticmethod\n def s(p, q):\n pass\n\n @classmethod\n def c(cls, p, q):\n pass\n\n\nC.s(1, 2)\nC().s(1, 2)\nC.c(1, 2)\nC().c(1, 2)\n", )], change("m.py", "def s(", "s(", "s", vec![("q", "", 1), ("p", "", 0)]), &[( "m.py", "class C:\n @staticmethod\n def s(q, p):\n pass\n\n @classmethod\n def c(cls, p, q):\n pass\n\n\nC.s(2, 1)\nC().s(2, 1)\nC.c(1, 2)\nC().c(1, 2)\n", )], ); check( &[("m.py", "class C:\n @classmethod\n def c(cls, p, q):\n pass\n\n\nC.c(1, 2)\nC().c(1, 2)\n")], change("m.py", "def c(", "c(", "c", vec![("cls", "", 0), ("q", "", 2), ("p", "", 1)]), &[("m.py", "class C:\n @classmethod\n def c(cls, q, p):\n pass\n\n\nC.c(2, 1)\nC().c(2, 1)\n")], ); } #[test] #[ignore = "needs rope"] fn constructors_are_changed_from_the_class_or_the_init_and_subclasses_through_super() { let files = [ ( "m.py", "class Base:\n def __init__(self, a, b=1):\n self.a = a\n\n\nclass Child(Base):\n def __init__(self, a, b=1):\n super().__init__(a, b)\n\n\nBase(1, b=2)\nBase(3)\n", ), ("__init__.py", "from m import Base\n"), ("u.py", "from . import Base\n\nBase(5, 6)\n"), ]; let expect: &[(&str, &str)] = &[ ( "m.py", "class Base:\n def __init__(self, b=1, a=0):\n self.a = a\n\n\nclass Child(Base):\n def __init__(self, b=1, a=0):\n super().__init__(b, a)\n\n\nBase(b=2, a=1)\nBase(a=3)\n", ), ("u.py", "from . import Base\n\nBase(6, 5)\n"), ]; let rows = vec![("self", "", 0), ("b", "1", 2), ("a", "0", 1)]; let mut c = change("m.py", "def __init__(self, a, b=1):", "__init__", "__init__", rows); c.sites = vec![("m.py", "super().__init__(a, b)", "__init__(")]; // rope doesn't resolve `super()` check(&files, c, expect); } #[test] #[ignore = "needs rope"] fn refuses_renaming_init() { let e = refused( &[("m.py", "class C:\n def __init__(self, a):\n pass\n")], change("m.py", "def __init__", "__init__", "make", vec![("self", "", 0), ("a", "", 1)]), ); assert!(e.contains("Cannot rename"), "{e}"); } #[test] #[ignore = "needs rope"] fn an_override_with_another_parameter_list_is_left_with_a_warning() { let warnings = check( &[( "m.py", "class A:\n def m(self, x, y):\n pass\n\n\nclass B(A):\n def m(self, x, y, z=0):\n pass\n", )], change("m.py", "def m(self, x, y):", "m(", "m", vec![("self", "", 0), ("y", "", 2), ("x", "", 1)]), &[( "m.py", "class A:\n def m(self, y, x):\n pass\n\n\nclass B(A):\n def m(self, x, y, z=0):\n pass\n", )], ); assert!(warnings[0].contains("m.py:7") && warnings[0].contains("override"), "{warnings:?}"); } #[test] #[ignore = "needs rope"] fn calls_with_unpacking_or_comments_are_listed_and_left_alone() { let warnings = check( &[( "m.py", "def f(a, b):\n pass\n\n\nargs = (1, 2)\nf(*args)\nf(1, # first\n 2)\nf(**{'a': 1, 'b': 2})\nf(1, 2)\n", )], change("m.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]), &[( "m.py", "def f(b, a):\n pass\n\n\nargs = (1, 2)\nf(*args)\nf(1, # first\n 2)\nf(**{'a': 1, 'b': 2})\nf(2, 1)\n", )], ); assert_eq!(warnings.len(), 3, "{warnings:?}"); assert!(warnings.iter().any(|w| w.contains("unpacking"))); assert!(warnings.iter().any(|w| w.contains("comments"))); } #[test] #[ignore = "needs rope"] fn an_unrecognised_decorator_warns() { let warnings = check( &[("m.py", "import deco\n\n\n@deco.wrap\ndef f(a, b):\n pass\n\n\nf(1, 2)\n")], change("m.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]), &[("m.py", "import deco\n\n\n@deco.wrap\ndef f(b, a):\n pass\n\n\nf(2, 1)\n")], ); assert!(warnings[0].contains("@deco.wrap"), "{warnings:?}"); } #[test] #[ignore = "needs rope"] fn properties_are_refused() { let p = Project::new(&[("m.py", "class C:\n @property\n def p(self):\n return 1\n")]); assert!(p.info("m.py", "def p(", "p(").unwrap_err().contains("property")); } #[test] #[ignore = "needs rope"] fn multi_line_parameter_lists_and_calls_keep_one_item_per_line() { check( &[("m.py", "def f(\n a,\n b=2,\n c=3,\n):\n pass\n\n\nf(\n 1,\n 2,\n 3,\n)\n")], change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("c", "3", 2), ("b", "2", 1)]), &[("m.py", "def f(\n a,\n c=3,\n b=2,\n):\n pass\n\n\nf(\n 1,\n 3,\n 2,\n)\n")], ); } #[test] #[ignore = "needs rope"] fn unsaved_buffers_are_what_rope_reads() { let project = Project::new(&[("m.py", "def f(a, b):\n pass\n"), ("u.py", "from m import f\n\nf(1, 2)\n")]); let mut c = change("m.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]); c.unsaved = vec![("u.py", "from m import f\n\nf(1, 2)\nf(3, 4)\n")]; let (changed, _) = project.change(&c).unwrap(); assert_eq!(changed["u.py"], "from m import f\n\nf(2, 1)\nf(4, 3)\n"); assert_eq!( std::fs::read_to_string(project.root().join("u.py")).unwrap(), "from m import f\n\nf(1, 2)\n", "disk untouched" ); } #[test] #[ignore = "needs rope"] fn call_sites_from_a_type_aware_server_are_updated_too() { let project = Project::new(&[( "m.py", "class A:\n def m(self, x, y):\n pass\n\n\ndef make():\n return get().m(1, 2)\n", )]); let at = project.at("m.py", "def m(", "m("); let mut request = project.request("change", "m.py", at, &BTreeMap::new()); let (line, col) = project.at("m.py", "get().m(", "m("); request["sites"] = json!([{ "path": project.root().join("m.py"), "line": line, "col": col, "len": 1 }]); request["change"] = json!({ "name": "m", "hierarchy": true, "params": [ { "name": "self", "defaultValue": "", "originalIndex": 0, "type": "" }, { "name": "y", "defaultValue": "", "originalIndex": 2, "type": "" }, { "name": "x", "defaultValue": "", "originalIndex": 1, "type": "" }, ]}); let answer = project.run(request); let text = answer["result"]["files"].as_object().unwrap().values().next().unwrap().as_str().unwrap().to_owned(); assert!(text.contains("get().m(2, 1)"), "{text}"); } #[test] #[ignore = "needs rope"] fn unicode_text_and_crlf_files() { check( &[("m.py", "def f(a, b):\n return 'é😀'\n\n\nf('é', '😀')\n")], change("m.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]), &[("m.py", "def f(b, a):\n return 'é😀'\n\n\nf('😀', 'é')\n")], ); } #[test] #[ignore = "needs rope"] fn syntax_errors_in_other_files_do_not_stop_the_change() { check( &[ ("m.py", "def f(a, b):\n pass\n"), ("broken.py", "def (:\nf(1, 2)\n"), ("u.py", "from m import f\nf(1, 2)\n"), ], change("m.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]), &[("m.py", "def f(b, a):\n pass\n"), ("u.py", "from m import f\nf(2, 1)\n")], ); } #[test] #[ignore = "needs rope"] fn refuses_a_function_name_that_the_scope_already_has() { let module = "def f(a):\n pass\n\n\ndef run():\n pass\n"; let e = refused(&[("m.py", module)], change("m.py", "def f(", "f(", "run", vec![("a", "", 0)])); assert!(e.contains("already defined"), "{e}"); let class = "class C:\n def f(self):\n pass\n\n run = 1\n"; let e = refused(&[("m.py", class)], change("m.py", "def f(", "f(", "run", vec![("self", "", 0)])); assert!(e.contains("already defined"), "{e}"); } #[test] #[ignore = "needs rope"] fn warns_when_a_new_parameter_name_is_used_in_the_body() { let warnings = check( &[("m.py", "def f(a):\n total = a\n return total\n")], change("m.py", "def f(", "f(", "f", vec![("total", "", 0)]), &[("m.py", "def f(total):\n total = total\n return total\n")], ); assert!(warnings[0].contains("'total' is already used"), "{warnings:?}"); } #[test] #[ignore = "needs rope"] fn async_functions_lambdas_and_nested_functions() { check( &[( "m.py", "async def f(a, b):\n def inner(x, y):\n return x\n\n return inner(a, b)\n\n\nasync def main():\n await f(1, 2)\n g = lambda p, q: p\n return g(1, 2)\n", )], change("m.py", "def f(", "f(", "f", vec![("b", "", 1), ("a", "", 0)]), &[( "m.py", "async def f(b, a):\n def inner(x, y):\n return x\n\n return inner(a, b)\n\n\nasync def main():\n await f(2, 1)\n g = lambda p, q: p\n return g(1, 2)\n", )], ); check( &[("m.py", "def outer():\n def inner(x, y):\n return x\n\n return inner(1, 2)\n")], change("m.py", "def inner(", "inner(", "inner", vec![("y", "", 1), ("x", "", 0)]), &[("m.py", "def outer():\n def inner(y, x):\n return x\n\n return inner(2, 1)\n")], ); } #[test] #[ignore = "needs rope"] fn unchanged_signatures_change_nothing() { check( &[("m.py", "def f(a, b=2, *args, k=1, **kw):\n pass\n\n\nf(1, 2, 3, k=4, z=5)\n")], change( "m.py", "def f(", "f(", "f", vec![("a", "", 0), ("b", "2", 1), ("*args", "", 2), ("k", "1", 3), ("**kw", "", 4)], ), &[], ); } #[test] #[ignore = "needs rope"] fn a_function_defined_in_a_file_with_a_syntax_error_is_refused_with_the_reason() { let e = refused(&[("m.py", "def f(a:\n pass\n")], change("m.py", "def f(", "f(", "f", vec![("a", "", 0)])); assert!(!e.is_empty()); } const AB: &str = "def f(a, b):\n return a\n\n\n"; fn swap() -> Vec { vec![("b", "", 1), ("a", "", 0)] } /// `AB` plus `calls` becomes the new header plus `after`. #[track_caller] fn check_calls(calls: &str, rows: Vec, header: &str, after: &str) -> Vec { let before = format!("{AB}{calls}\n"); let want = format!("def f({header}):\n return a\n\n\n{after}\n"); check(&[("m.py", &before)], change("m.py", "def f(", "f(", "f", rows), &[("m.py", &want)]) } #[test] #[ignore = "needs rope"] fn nested_calls_are_rewritten_inside_out() { check_calls("f(f(1, 2), 3)", swap(), "b, a", "f(3, f(2, 1))"); check_calls("f(f(1, 22), 3)", vec![("a", "", 0)], "a", "f(f(1))"); } #[test] #[ignore = "needs rope"] fn parentheses_around_arguments_and_defaults_stay_with_them() { check_calls("f((x), (y))", swap(), "b, a", "f((y), (x))"); check_calls("f((p + q), c)", swap(), "b, a", "f(c, (p + q))"); check( &[("m.py", "def f(a, b=(1+2)):\n pass\n")], change("m.py", "def f(", "f(", "f", vec![("a", "", 0), ("b", "(1+2)", 1), ("c", "3", -1)]), &[("m.py", "def f(a, b=(1+2), c=3):\n pass\n")], ); } #[test] #[ignore = "needs rope"] fn removing_every_argument_removes_the_trailing_comma() { check_calls("f(1, 2,)", vec![], "", "f()"); } #[test] #[ignore = "needs rope"] fn references_of_something_else_are_not_rewritten() { // the caret on `fn`: a server reports the references of the parameter, not of `apply` let mut c = change("m.py", "def apply(fn", "fn", "apply", vec![("x", "", 1), ("fn", "", 0)]); c.sites = vec![("m.py", "return fn(x)", "fn")]; check( &[("m.py", "def apply(fn, x):\n return fn(x)\n\n\napply(print, 1)\n")], c, &[("m.py", "def apply(x, fn):\n return fn(x)\n\n\napply(1, print)\n")], ); } #[test] #[ignore = "needs rope"] fn renaming_the_function_renames_the_calls_only_a_server_finds() { let text = "class B:\n def run(self):\n pass\n\n\nclass C(B):\n def go(self):\n super().run()\n\n\ndef g(o: B):\n o.run()\n"; let mut c = change("m.py", "def run", "run", "walk", vec![("self", "", 0)]); c.sites = vec![("m.py", "super().run()", "run"), ("m.py", " o.run()", "run")]; check(&[("m.py", text)], c, &[("m.py", &text.replace("run", "walk"))]); } #[test] #[ignore = "needs rope"] fn overrides_keep_their_defaults_and_follow_parameter_renames() { let text = "class B:\n def m(self, a, b=1):\n return a\n\n\nclass C(B):\n def m(self, a, b=2):\n return a\n\n\nC().m(a=0)\n"; check( &[("m.py", text)], change("m.py", "def m(self, a, b=1", "m", "m", vec![("self", "", 0), ("y", "", 1), ("b", "1", 2)]), &[("m.py", &text.replace("a, b=", "y, b=").replace("return a", "return y").replace("a=0", "y=0"))], ); } #[test] #[ignore = "needs rope"] fn star_parameters_are_renamed_by_their_names() { check( &[("m.py", "def f(*args, **kw):\n return args, kw\n")], change("m.py", "def f(", "f(", "f", vec![("*xs", "", 0), ("**opts", "", 1)]), &[("m.py", "def f(*xs, **opts):\n return xs, opts\n")], ); } #[test] #[ignore = "needs rope"] fn a_changed_parameter_kind_never_loses_arguments_silently() { let warnings = check( &[("m.py", "def f(*args):\n pass\n\n\nf(1, 2)\n")], change("m.py", "def f(", "f(", "f", vec![("args", "", 0)]), &[("m.py", "def f(args):\n pass\n\n\nf(1, 2)\n")], ); assert!(warnings[0].contains("after its kind changes"), "{warnings:?}"); let warnings = check_calls("f(1, 2)", vec![("a", "", 0), ("*b", "", 1)], "a, *b", "f(1, 2)"); assert!(warnings[0].contains("after its kind changes"), "{warnings:?}"); } #[test] #[ignore = "needs rope"] fn rows_that_would_not_parse_are_refused_or_cleaned() { let files = [("m.py", "def f(a, b=1):\n pass\n")]; let at = |rows| change("m.py", "def f(", "f(", "f", rows); for default in ["1, 3", "1 # x", "x=1", "*y"] { let why = refused(&files, at(vec![("a", "", 0), ("b", default, 1)])); assert!(why.contains("not a valid expression"), "{default}: {why}"); } let why = refused(&files, at(vec![("a", "", 0), ("*", "", -1), ("/", "", -1), ("b", "1", 1)])); assert!(why.contains("'/' must come before '*'"), "{why}"); // the dialog hides the default of a star row, so the old one is dropped check(&files, at(vec![("a", "", 0), ("*b", "1", 1)]), &[("m.py", "def f(a, *b):\n pass\n")]); } #[test] #[ignore = "needs rope"] fn keyword_only_parameters_without_positional_ones_can_change() { check( &[("m.py", "def f(*, a, b):\n pass\n\n\nf(a=1, b=2)\n")], change("m.py", "def f(", "f(", "f", vec![("*", "", 0), ("b", "", 2), ("a", "", 1)]), &[("m.py", "def f(*, b, a):\n pass\n\n\nf(b=2, a=1)\n")], ); } #[test] #[ignore = "needs rope"] fn calls_through_type_self_and_stored_methods_are_not_misaligned() { let text = "class C:\n def run(self, a, b):\n pass\n\n def go(self):\n type(self).run(self, 1, 2)\n\n\nm = C().run\nm(1, 2)\n"; let mut c = change("m.py", "def run", "run", "run", vec![("self", "", 0), ("b", "", 2), ("a", "", 1)]); c.sites = vec![("m.py", "type(self).run(", "run("), ("m.py", "m(1, 2)", "m(")]; let warnings = check( &[("m.py", text)], c, &[("m.py", &text.replace("self, a, b", "self, b, a").replace("self, 1, 2", "self, 2, 1"))], ); assert!(warnings.iter().any(|w| w.contains("used as a value")), "{warnings:?}"); }