From bc64188c389e0934fcfe1f3228451f28180207cc Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Fri, 27 Nov 2026 23:12:59 +0900 Subject: [PATCH] feat(python): go to definition and completion for pytest fixtures (#6510) A fixture parameter of a test or fixture now resolves to the fixture that pytest would inject: the nearest definition in the same class or module, then the conftest.py chain up to the root, pytest_plugins modules, pytest11 entry points and the _pytest builtins. Go to Declaration opens it, and completion in a test's parameter list offers the fixtures in scope with their source file. Named fixtures (name=...) and usefixtures("...") strings are covered; the fixture layers are cached by file mtime. Closes #6490 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-host/src/ops/mod.rs | 1 + crates/ide-host/src/ops/nav.rs | 19 + crates/ide-host/src/ops/pytest_fixtures.rs | 255 +++++++++ crates/ide-language/src/lib.rs | 4 +- crates/ide-language/src/syntax/mod.rs | 5 + .../src/syntax/python_fixtures.rs | 517 ++++++++++++++++++ fixtures/python-app/tests/conftest.py | 15 + fixtures/python-app/tests/test_fixtures.py | 21 + smoke/run.test.ts | 2 +- src-tauri/tests/commands.snap | 1 + src/bindings.ts | 29 + src/features/index.ts | 2 + src/features/pytest/index.test.ts | 10 + src/features/pytest/index.ts | 98 ++++ 14 files changed, 977 insertions(+), 2 deletions(-) create mode 100644 crates/ide-host/src/ops/pytest_fixtures.rs create mode 100644 crates/ide-language/src/syntax/python_fixtures.rs create mode 100644 fixtures/python-app/tests/conftest.py create mode 100644 fixtures/python-app/tests/test_fixtures.py create mode 100644 src/features/pytest/index.test.ts create mode 100644 src/features/pytest/index.ts diff --git a/crates/ide-host/src/ops/mod.rs b/crates/ide-host/src/ops/mod.rs index 8650a555a5..9996dfa5cd 100644 --- a/crates/ide-host/src/ops/mod.rs +++ b/crates/ide-host/src/ops/mod.rs @@ -27,6 +27,7 @@ pub mod maven_placeholder; pub mod nav; pub mod notebook; pub mod project; +pub mod pytest_fixtures; mod python; pub mod python_stubs; pub mod refactor; diff --git a/crates/ide-host/src/ops/nav.rs b/crates/ide-host/src/ops/nav.rs index c110d842f8..13fcc0002e 100644 --- a/crates/ide-host/src/ops/nav.rs +++ b/crates/ide-host/src/ops/nav.rs @@ -1,4 +1,5 @@ use super::blocking; +use super::pytest_fixtures::{PytestFixtureAt, fixture_at}; use super::python_stubs::{ PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path, }; @@ -478,6 +479,23 @@ pub async fn nav_python_stubs(host: &Host, window: &str, doc: DocId) -> IdeResul .await } +/// pytest fixtures at `pos` of a Python document: the definition pytest uses for the fixture +/// named there (a test's parameter, a `usefixtures` / `getfixturevalue` string), and the +/// fixtures visible where a fixture name goes, for completion. +#[command(trust = always)] +pub async fn nav_pytest_fixtures(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult { + let project = host.project(window)?; + let syntax = host.syntax(); + blocking(move || { + let snap = project.documents.snapshot(doc)?; + if snap.large || snap.language.as_str() != "python" { + return Ok(Default::default()); + } + Ok(fixture_at(&project, &syntax, &snap.path, &snap.text, pos)) + }) + .await +} + ide_command::domain!( nav: find_dirs, @@ -491,6 +509,7 @@ ide_command::domain!( mark_recent, nav_index_definitions, nav_inheritance, + nav_pytest_fixtures, nav_python_stubs, nav_resolve_module, path_completions, diff --git a/crates/ide-host/src/ops/pytest_fixtures.rs b/crates/ide-host/src/ops/pytest_fixtures.rs new file mode 100644 index 0000000000..68a7c77d3f --- /dev/null +++ b/crates/ide-host/src/ops/pytest_fixtures.rs @@ -0,0 +1,255 @@ +//! pytest fixtures across files: the modules a test file sees, nearest first (the file, its +//! `conftest.py` files up to the project root, the modules `pytest_plugins` names, installed +//! plugins' `pytest11` entry points, pytest's own `_pytest` package), for Go to Declaration +//! and completion of fixture names. + +use super::python_stubs::site_packages; +use crate::Project; +use ide_core::{IpcPath, LanguageId, Location, Pos, Range}; +use ide_language::{PytestModule, Syntax, resolve_fixture, visible_fixtures}; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, LazyLock, Mutex}; +use std::time::SystemTime; + +#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PytestFixtureAt { + /// The fixture name at the position, and the definition pytest uses for it. + pub reference: Option, + /// At a place a fixture name goes (a test's parameters, a `usefixtures` string): the + /// fixtures visible there, nearest first. + pub completions: Option>, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PytestFixtureReference { + pub name: String, + pub range: Range, + /// None when no visible module defines it (`request`, a fixture from a hook). + pub definition: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PytestFixtureItem { + pub name: String, + /// The file defining it. + pub path: IpcPath, +} + +/// Fixtures at `pos` of the Python document `path` / `text`. +pub(crate) fn fixture_at(project: &Project, syntax: &Syntax, path: &Path, text: &str, pos: Pos) -> PytestFixtureAt { + let own = syntax.pytest_module(&python(), text); + let usage = own.use_at(pos).cloned(); + let slot = own.slot_at(pos).cloned(); + if usage.is_none() && slot.is_none() { + return PytestFixtureAt::default(); + } + let layers = layers(project, syntax, path, Arc::new(own)); + let modules: Vec<&PytestModule> = layers.iter().map(|(_, m)| m.as_ref()).collect(); + let reference = usage.map(|u| { + let found = resolve_fixture(&modules, &u.name, u.class.as_deref(), u.in_fixture.as_deref() == Some(&u.name)); + PytestFixtureReference { + definition: found.map(|(l, f)| Location { + path: IpcPath::from(layers[l].0.clone()), + range: modules[l].fixtures[f].selection, + uri: None, + }), + name: u.name, + range: u.range, + } + }); + let completions = slot.map(|s| { + visible_fixtures(&modules, s.class.as_deref()) + .into_iter() + // `_name` fixtures are internal, as `pytest --fixtures` hides them. + .filter(|&(l, f)| !modules[l].fixtures[f].name.starts_with('_')) + .map(|(l, f)| PytestFixtureItem { + name: modules[l].fixtures[f].name.clone(), + path: IpcPath::from(layers[l].0.clone()), + }) + .collect() + }); + PytestFixtureAt { reference, completions } +} + +fn python() -> LanguageId { + LanguageId::new("python") +} + +type Layer = (PathBuf, Arc); + +/// The modules `path` sees, nearest first, `own` being its own. +fn layers(project: &Project, syntax: &Syntax, path: &Path, own: Arc) -> Vec { + let mut out: Vec = vec![(path.to_path_buf(), own)]; + // conftest.py files from the file's folder up to the project root. + let mut dir = path.parent(); + while let Some(d) = dir.filter(|d| d.starts_with(&project.root)) { + let conftest = d.join("conftest.py"); + if conftest != path + && let Some(m) = module_of(project, syntax, &conftest) + { + out.push((conftest, m)); + } + dir = d.parent(); + } + let packages = interpreter_site_packages(project); + let mut search = super::python::paths(project); + search.extend(packages.iter().cloned()); + // `pytest_plugins = ["pytester"]` names pytest's own optional plugins by their short name. + search.extend(packages.iter().map(|p| p.join("_pytest"))); + // Modules named by `pytest_plugins` in those files. + let named: Vec = out.iter().flat_map(|(_, m)| m.plugins.clone()).collect(); + let mut extra: Vec = named.iter().filter_map(|module| module_file(module, &search)).collect(); + // Installed plugins, then pytest's own fixtures. + for packages in &packages { + extra.extend( + entry_point_modules(packages).iter().filter_map(|m| module_file(m, std::slice::from_ref(packages))), + ); + } + for packages in &packages { + extra.extend(builtin_modules(&packages.join("_pytest"))); + } + for file in extra { + if !out.iter().any(|(p, _)| *p == file) + && let Some(m) = module_of(project, syntax, &file) + { + out.push((file, m)); + } + } + out +} + +/// The `site-packages` of the project's interpreter: its virtualenv's, else its install prefix's. +fn interpreter_site_packages(project: &Project) -> Vec { + let settings = project.settings.effective(); + let Some(python) = ide_sdk::apply::python_interpreter(&project.root, &settings) else { return Vec::new() }; + let prefix = ide_sdk::venv_of(&python).or_else(|| python.parent()?.parent().map(Path::to_path_buf)); + prefix.map(|p| site_packages(&p)).unwrap_or_default() +} + +/// `pkg.mod` → `pkg/mod.py` or `pkg/mod/__init__.py` in the first folder that has it. +fn module_file(module: &str, search: &[PathBuf]) -> Option { + let rel: PathBuf = module.split('.').collect(); + search.iter().find_map(|base| { + let file = base.join(&rel).with_extension("py"); + let package = base.join(&rel).join("__init__.py"); + [file, package].into_iter().find(|p| p.is_file()) + }) +} + +/// The modules of the `[pytest11]` entry points of the distributions in `site_packages`. +fn entry_point_modules(site_packages: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(site_packages) else { return Vec::new() }; + let mut out = Vec::new(); + for entry in entries.flatten() { + if !entry.file_name().to_string_lossy().ends_with(".dist-info") { + continue; + } + let Ok(text) = std::fs::read_to_string(entry.path().join("entry_points.txt")) else { continue }; + out.extend(pytest11_modules(&text)); + } + out.sort(); + out +} + +/// The modules of the `[pytest11]` section of an `entry_points.txt` (`name = module:attr`). +fn pytest11_modules(text: &str) -> Vec { + let mut section = ""; + let mut out = Vec::new(); + for line in text.lines().map(str::trim) { + if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + section = name; + } else if section == "pytest11" + && let Some((_, value)) = line.split_once('=') + { + let module = value.trim().split(':').next().unwrap_or_default().trim(); + if !module.is_empty() { + out.push(module.to_owned()); + } + } + } + out +} + +/// pytest's own plugins that are off unless `pytest_plugins` names them. +const OPTIONAL_BUILTINS: [&str; 2] = ["pytester.py", "pytester_assertions.py"]; + +/// pytest's own modules that may define fixtures: `_pytest/*.py`, one level of subpackages. +fn builtin_modules(dir: &Path) -> Vec { + let mut out = Vec::new(); + let Ok(entries) = std::fs::read_dir(dir) else { return out }; + for entry in entries.flatten() { + let path = entry.path(); + if OPTIONAL_BUILTINS.iter().any(|name| entry.file_name() == *name) { + continue; + } + if path.extension().is_some_and(|e| e == "py") { + out.push(path); + } else if path.is_dir() { + out.extend( + std::fs::read_dir(&path) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "py")), + ); + } + } + out.sort(); + out +} + +/// A parsed file and the modification time and length it was read at. +type Cached = (SystemTime, u64, Arc); + +/// The fixtures of a file: from its open editor, else from disk, parsed once per modification. +fn module_of(project: &Project, syntax: &Syntax, path: &Path) -> Option> { + if let Some(text) = project.documents.text_of(path) { + return Some(Arc::new(syntax.pytest_module(&python(), &text))); + } + static CACHE: LazyLock>> = LazyLock::new(Default::default); + let meta = std::fs::metadata(path).ok().filter(|m| m.is_file())?; + if meta.len() > ide_vfs::LARGE_FILE_THRESHOLD { + return None; + } + let stamp = (meta.modified().ok()?, meta.len()); + if let Some((time, len, m)) = CACHE.lock().ok()?.get(path) + && (*time, *len) == stamp + { + return Some(m.clone()); + } + let text = std::fs::read_to_string(path).ok()?; + let module = Arc::new(syntax.pytest_module(&python(), &ide_text::normalize_line_endings(&text))); + CACHE.lock().ok()?.insert(path.to_path_buf(), (stamp.0, stamp.1, module.clone())); + Some(module) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_pytest11_entry_points() { + let text = + "[console_scripts]\nx = a:b\n\n[pytest11]\nmock = pytest_mock\nasyncio = pytest_asyncio.plugin:main\n"; + assert_eq!(pytest11_modules(text), ["pytest_mock", "pytest_asyncio.plugin"]); + } + + #[test] + fn finds_module_files_and_packages() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(dir.path().join("pkg/sub")).unwrap(); + std::fs::write(dir.path().join("pkg/fixtures.py"), "").unwrap(); + std::fs::write(dir.path().join("pkg/sub/__init__.py"), "").unwrap(); + let search = [dir.path().to_path_buf()]; + assert_eq!(module_file("pkg.fixtures", &search), Some(dir.path().join("pkg/fixtures.py"))); + assert_eq!(module_file("pkg.sub", &search), Some(dir.path().join("pkg/sub/__init__.py"))); + assert_eq!(module_file("pkg.none", &search), None); + } +} diff --git a/crates/ide-language/src/lib.rs b/crates/ide-language/src/lib.rs index 380450f642..a9cb31614f 100644 --- a/crates/ide-language/src/lib.rs +++ b/crates/ide-language/src/lib.rs @@ -29,7 +29,9 @@ pub use syntax::{ set_external_syntax, shift_pos, shift_range, }; pub use syntax::{ - MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases, + MethodBody, PhpAlignment, PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestModule, + PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases, resolve_fixture, + visible_fixtures, }; /// Parsed form of `languages/.toml`. Backend-only; the UI gets [`LanguageInfo`]. diff --git a/crates/ide-language/src/syntax/mod.rs b/crates/ide-language/src/syntax/mod.rs index 5dff200a54..1f4dd85fa9 100644 --- a/crates/ide-language/src/syntax/mod.rs +++ b/crates/ide-language/src/syntax/mod.rs @@ -13,6 +13,7 @@ mod literals; mod outline; mod php_align; mod python_facts; +mod python_fixtures; mod python_imports; mod rearrange; mod rst; @@ -35,6 +36,10 @@ pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion}; pub use outline::{merge_kinds, merge_visibility}; pub use php_align::PhpAlignment; pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression}; +pub use python_fixtures::{ + PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestModule, resolve_fixture, + visible_fixtures, +}; use std::cell::RefCell; use std::collections::HashMap; use std::sync::OnceLock; diff --git a/crates/ide-language/src/syntax/python_fixtures.rs b/crates/ide-language/src/syntax/python_fixtures.rs new file mode 100644 index 0000000000..8b046e266d --- /dev/null +++ b/crates/ide-language/src/syntax/python_fixtures.rs @@ -0,0 +1,517 @@ +//! pytest fixtures in one Python module: the fixtures it defines (`@pytest.fixture`), the +//! places it names one (a test's or fixture's parameters, `usefixtures("x")`, +//! `getfixturevalue("x")`) and the plugin modules it loads (`pytest_plugins`). From the +//! syntax tree only; [`resolve_fixture`] then picks the definition pytest uses, given the +//! modules a test sees, nearest first. + +use super::lines::LineIndex; +use crate::{LanguageId, Syntax}; +use ide_core::{Pos, Range}; +use tree_sitter::{Node, Tree}; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PytestModule { + pub fixtures: Vec, + pub uses: Vec, + /// Where a fixture name may be typed: completion offers the visible fixtures there. + pub slots: Vec, + /// Modules named by a module-level `pytest_plugins`, as written (`pkg.fixtures`). + pub plugins: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PytestFixture { + /// The name tests ask for: the `name=` argument, else the function's name. + pub name: String, + /// That name in the source: the function name, or the `name=` string's content. + pub selection: Range, + /// The class whose method it is; only that class's tests see it. + pub class: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PytestFixtureUseKind { + Parameter, + UseFixtures, + GetFixtureValue, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PytestFixtureUse { + pub name: String, + pub range: Range, + pub kind: PytestFixtureUseKind, + pub class: Option, + /// The fixture whose parameter this is: `def tasks(tasks)` asks for the next `tasks` outward. + pub in_fixture: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PytestFixtureSlot { + /// A test's or fixture's parameter list, or the content of a `usefixtures` / + /// `getfixturevalue` string (empty strings included). + pub range: Range, + pub class: Option, +} + +impl PytestModule { + /// The use whose name covers `pos` (its end included, where a caret after the name sits). + pub fn use_at(&self, pos: Pos) -> Option<&PytestFixtureUse> { + self.uses.iter().find(|u| u.range.start <= pos && pos <= u.range.end) + } + + /// The slot holding `pos`. + pub fn slot_at(&self, pos: Pos) -> Option<&PytestFixtureSlot> { + self.slots.iter().filter(|s| s.range.start <= pos && pos <= s.range.end).min_by_key(|s| s.range.end) + } +} + +impl Syntax { + /// The pytest fixtures a Python `text` defines and names; empty for other languages. + pub fn pytest_module(&self, lang: &LanguageId, text: &str) -> PytestModule { + self.analyze(lang, text, |g, tree, text| (g.spec.name == "python").then(|| extract(tree, text))) + .unwrap_or_default() + } +} + +/// The fixture pytest uses for a name asked in `layers[0]` (the module), `class` being the +/// asking test's class, the later layers being the `conftest.py` files from the module's +/// folder upward, then plugins and pytest's own modules. `overriding`: the asker is a fixture +/// of that same name, which gets the next definition outward. Returns (layer, fixture) indexes. +pub fn resolve_fixture( + layers: &[&PytestModule], + name: &str, + class: Option<&str>, + overriding: bool, +) -> Option<(usize, usize)> { + visible(layers, class).filter(|&(l, f)| layers[l].fixtures[f].name == name).nth(usize::from(overriding)) +} + +/// The fixtures a test of `class` in `layers[0]` sees, nearest first, one per name. +pub fn visible_fixtures(layers: &[&PytestModule], class: Option<&str>) -> Vec<(usize, usize)> { + let mut seen = std::collections::HashSet::new(); + visible(layers, class).filter(|&(l, f)| seen.insert(layers[l].fixtures[f].name.as_str())).collect() +} + +/// Every fixture visible from `class` in `layers[0]`, nearest first: the class's own, then +/// the module's, then each later layer's module-level ones. Within one scope the last +/// definition of a name wins, as Python rebinds it. +fn visible<'a>(layers: &'a [&'a PytestModule], class: Option<&'a str>) -> impl Iterator + 'a { + let scopes = layers.iter().enumerate().flat_map(move |(l, m)| { + let own = (l == 0).then_some(class).flatten().map(|c| (l, m, Some(c))); + own.into_iter().chain(std::iter::once((l, m, None))) + }); + scopes.flat_map(|(l, m, scope)| { + let mut picked: Vec<(usize, usize)> = Vec::new(); + for (f, fixture) in m.fixtures.iter().enumerate().rev() { + if fixture.class.as_deref() == scope && !picked.iter().any(|&(_, p)| m.fixtures[p].name == fixture.name) { + picked.push((l, f)); + } + } + picked.reverse(); + picked + }) +} + +fn extract(tree: &Tree, text: &str) -> PytestModule { + let idx = LineIndex::new(text); + let mut out = PytestModule::default(); + let root = tree.root_node(); + let mut cursor = root.walk(); + for node in root.named_children(&mut cursor) { + statement(node, None, text, &idx, &mut out); + } + // `usefixtures` / `getfixturevalue` calls wherever they are. + let mut walker = root.walk(); + visit(&mut walker, &mut |node| { + if node.kind() == "call" { + fixture_call(node, text, &idx, &mut out); + } + }); + out +} + +/// A top-level statement, or one in a class body (`class` set). +fn statement(node: Node, class: Option<&str>, text: &str, idx: &LineIndex, out: &mut PytestModule) { + let (definition, decorators) = match node.kind() { + "decorated_definition" => { + let mut c = node.walk(); + let decorators: Vec = node.children(&mut c).filter(|n| n.kind() == "decorator").collect(); + let Some(definition) = node.child_by_field_name("definition") else { return }; + (definition, decorators) + } + _ => (node, Vec::new()), + }; + match definition.kind() { + "function_definition" => function(definition, &decorators, class, &[], text, idx, out), + "class_definition" if class.is_none() => { + let Some(name) = definition.child_by_field_name("name") else { return }; + let name = text_of(name, text); + let Some(body) = definition.child_by_field_name("body") else { return }; + // `@pytest.mark.parametrize` on the class names arguments of every test in it. + let class_args = parametrized(&decorators, text, idx); + let mut c = body.walk(); + for child in body.named_children(&mut c) { + let (def, decs) = match child.kind() { + "decorated_definition" => { + let mut c2 = child.walk(); + let decs: Vec = child.children(&mut c2).filter(|n| n.kind() == "decorator").collect(); + match child.child_by_field_name("definition") { + Some(d) => (d, decs), + None => continue, + } + } + _ => (child, Vec::new()), + }; + if def.kind() == "function_definition" { + function(def, &decs, Some(&name), &class_args, text, idx, out); + } + } + } + "expression_statement" if class.is_none() => plugins(definition, text, idx, &mut out.plugins), + _ => {} + } +} + +fn function( + def: Node, + decorators: &[Node], + class: Option<&str>, + class_args: &[String], + text: &str, + idx: &LineIndex, + out: &mut PytestModule, +) { + let Some(name_node) = def.child_by_field_name("name") else { return }; + let name = text_of(name_node, text); + let fixture = decorators.iter().find_map(|d| fixture_decorator(*d, text, idx)); + let is_test = name.starts_with("test") && class.is_none_or(|c| c.starts_with("Test")); + if fixture.is_none() && !is_test { + return; + } + let fixture_name = fixture.as_ref().and_then(|f| f.as_ref().map(|(n, _)| n.clone())).unwrap_or(name.clone()); + if let Some(f) = &fixture { + let selection = match f { + Some((_, string)) => *string, + None => idx.range(name_node.start_byte(), name_node.end_byte()), + }; + out.fixtures.push(PytestFixture { name: fixture_name.clone(), selection, class: class.map(str::to_owned) }); + } + let Some(params) = def.child_by_field_name("parameters") else { return }; + out.slots.push(PytestFixtureSlot { + range: idx.range(params.start_byte(), params.end_byte()), + class: class.map(str::to_owned), + }); + // Arguments `parametrize` supplies are no fixtures (unless indirect). + let mut skip: Vec = parametrized(decorators, text, idx); + skip.extend_from_slice(class_args); + let mut c = params.walk(); + for (i, param) in params.named_children(&mut c).enumerate() { + let ident = match param.kind() { + "identifier" => param, + "typed_parameter" => match param.named_child(0) { + Some(n) if n.kind() == "identifier" => n, + _ => continue, + }, + // Defaulted parameters, `*args`, `**kwargs`: no fixtures. + _ => continue, + }; + let param_name = text_of(ident, text); + if (i == 0 && class.is_some() && (param_name == "self" || param_name == "cls")) || skip.contains(¶m_name) { + continue; + } + out.uses.push(PytestFixtureUse { + name: param_name, + range: idx.range(ident.start_byte(), ident.end_byte()), + kind: PytestFixtureUseKind::Parameter, + class: class.map(str::to_owned), + in_fixture: fixture.is_some().then(|| fixture_name.clone()), + }); + } +} + +/// `Some(None)` for `@pytest.fixture` / `@fixture(...)`, `Some(Some((name, range)))` with a +/// `name="…"` argument, `None` for any other decorator. +fn fixture_decorator(decorator: Node, text: &str, idx: &LineIndex) -> Option> { + let expr = decorator.named_child(0)?; + let (callee, args) = match expr.kind() { + "call" => (expr.child_by_field_name("function")?, expr.child_by_field_name("arguments")), + _ => (expr, None), + }; + let callee = text_of(callee, text); + if callee != "fixture" && !callee.ends_with(".fixture") { + return None; + } + let named = args.and_then(|args| { + let mut c = args.walk(); + args.named_children(&mut c).find_map(|a| { + if a.kind() != "keyword_argument" || a.child_by_field_name("name").map(|n| text_of(n, text))? != "name" { + return None; + } + string_content(a.child_by_field_name("value")?, text, idx) + }) + }); + Some(named) +} + +/// The argument names of `@pytest.mark.parametrize("a, b", …)` decorators that are passed +/// directly (no `indirect=`). +fn parametrized(decorators: &[Node], text: &str, idx: &LineIndex) -> Vec { + let mut out = Vec::new(); + for d in decorators { + let Some(call) = d.named_child(0).filter(|n| n.kind() == "call") else { continue }; + let Some(callee) = call.child_by_field_name("function") else { continue }; + if !text_of(callee, text).ends_with("parametrize") { + continue; + } + let Some(args) = call.child_by_field_name("arguments") else { continue }; + let mut c = args.walk(); + let all: Vec = args.named_children(&mut c).collect(); + let indirect = all.iter().any(|a| { + a.kind() == "keyword_argument" + && a.child_by_field_name("name").is_some_and(|n| text_of(n, text) == "indirect") + && a.child_by_field_name("value").is_some_and(|v| text_of(v, text) != "False") + }); + if indirect { + continue; + } + let first = all.iter().find(|a| a.kind() != "keyword_argument"); + let names: Vec = match first { + Some(n) if n.kind() == "string" => string_content(*n, text, idx) + .map(|(s, _)| s.split(',').map(|p| p.trim().to_owned()).collect()) + .unwrap_or_default(), + Some(n) if matches!(n.kind(), "list" | "tuple") => { + let mut c = n.walk(); + n.named_children(&mut c).filter_map(|e| string_content(e, text, idx).map(|(s, _)| s)).collect() + } + _ => Vec::new(), + }; + out.extend(names.into_iter().filter(|n| !n.is_empty())); + } + out +} + +/// `usefixtures("a", "b")` and `request.getfixturevalue("a")`. +fn fixture_call(call: Node, text: &str, idx: &LineIndex, out: &mut PytestModule) { + let Some(callee) = call.child_by_field_name("function") else { return }; + let callee_text = text_of(callee, text); + let kind = if callee_text == "usefixtures" || callee_text.ends_with(".usefixtures") { + PytestFixtureUseKind::UseFixtures + } else if callee.kind() == "attribute" + && callee.child_by_field_name("attribute").is_some_and(|a| text_of(a, text) == "getfixturevalue") + { + PytestFixtureUseKind::GetFixtureValue + } else { + return; + }; + let Some(args) = call.child_by_field_name("arguments") else { return }; + let class = enclosing_class(call, text); + let mut c = args.walk(); + for (i, arg) in args.named_children(&mut c).enumerate() { + if kind == PytestFixtureUseKind::GetFixtureValue && i > 0 { + break; + } + let Some((name, range)) = string_content(arg, text, idx) else { continue }; + out.slots.push(PytestFixtureSlot { range, class: class.clone() }); + if !name.is_empty() { + out.uses.push(PytestFixtureUse { name, range, kind, class: class.clone(), in_fixture: None }); + } + } +} + +/// The top-level class a node is in, if any. +fn enclosing_class(node: Node, text: &str) -> Option { + let mut at = node.parent(); + let mut class = None; + while let Some(n) = at { + if n.kind() == "class_definition" { + class = n.child_by_field_name("name").map(|c| text_of(c, text)); + } + at = n.parent(); + } + class +} + +/// `pytest_plugins = "a"`, `= ["a", "b"]` or `= ("a",)`. +fn plugins(statement: Node, text: &str, idx: &LineIndex, out: &mut Vec) { + let Some(assign) = statement.named_child(0).filter(|n| n.kind() == "assignment") else { return }; + if assign.child_by_field_name("left").map(|l| text_of(l, text)).as_deref() != Some("pytest_plugins") { + return; + } + let Some(right) = assign.child_by_field_name("right") else { return }; + match right.kind() { + "string" => out.extend(string_content(right, text, idx).map(|(s, _)| s)), + "list" | "tuple" => { + let mut c = right.walk(); + out.extend(right.named_children(&mut c).filter_map(|e| string_content(e, text, idx).map(|(s, _)| s))); + } + _ => {} + } +} + +/// The content of a plain string literal and its range (between the quotes); none for +/// f-strings, byte strings and concatenations. +fn string_content(node: Node, text: &str, idx: &LineIndex) -> Option<(String, Range)> { + if node.kind() != "string" { + return None; + } + let mut c = node.walk(); + let parts: Vec = node.children(&mut c).collect(); + let start = parts.iter().find(|p| p.kind() == "string_start")?; + let end = parts.iter().find(|p| p.kind() == "string_end")?; + if text_of(*start, text).chars().any(|ch| matches!(ch, 'f' | 'F' | 'b' | 'B')) { + return None; + } + if parts.iter().any(|p| p.kind() == "interpolation" || p.kind() == "escape_sequence") { + return None; + } + let (from, to) = (start.end_byte(), end.start_byte()); + Some((text.get(from..to)?.to_owned(), idx.range(from, to))) +} + +fn text_of(node: Node, text: &str) -> String { + text.get(node.byte_range()).unwrap_or_default().to_owned() +} + +fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) { + loop { + f(cursor.node()); + if cursor.goto_first_child() { + continue; + } + loop { + if cursor.goto_next_sibling() { + break; + } + if !cursor.goto_parent() { + return; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn module(src: &str) -> PytestModule { + static S: std::sync::OnceLock = std::sync::OnceLock::new(); + S.get_or_init(Syntax::new).pytest_module(&LanguageId::new("python"), src) + } + + fn names(m: &PytestModule) -> Vec { + m.fixtures + .iter() + .map(|f| format!("{}{}", f.class.as_deref().map(|c| format!("{c}.")).unwrap_or_default(), f.name)) + .collect() + } + + fn uses(m: &PytestModule) -> Vec { + m.uses.iter().map(|u| format!("{:?} {}", u.kind, u.name)).collect() + } + + const TEST_MODULE: &str = r#"import pytest +from pytest import fixture + +pytest_plugins = ["pkg.fixtures", "other"] +pytestmark = pytest.mark.usefixtures("db") + + +@pytest.fixture +def tasks(tmp_path): + return [] + + +@fixture(scope="module", name="client") +def make_client(tasks, request): + return request.getfixturevalue("server") + + +@pytest.mark.parametrize("title, expected", [("a", "a")]) +def test_add(tasks, title, expected, monkeypatch, flag=False, *args): + pass + + +def helper(tasks): + pass + + +@pytest.mark.usefixtures("client", "") +class TestTasks: + @pytest.fixture + def tasks(self, tasks): + return tasks + + def test_one(self, tasks: list, capsys): + pass +"#; + + #[test] + fn reads_definitions_uses_and_plugins() { + let m = module(TEST_MODULE); + assert_eq!(names(&m), ["tasks", "client", "TestTasks.tasks"]); + assert_eq!(m.plugins, ["pkg.fixtures", "other"]); + assert_eq!( + uses(&m), + [ + "Parameter tmp_path", + "Parameter tasks", + "Parameter request", + "Parameter tasks", + "Parameter monkeypatch", + "Parameter tasks", + "Parameter tasks", + "Parameter capsys", + "UseFixtures db", + "GetFixtureValue server", + "UseFixtures client", + ] + ); + // `name=` is found by its string; the overriding class fixture knows it overrides. + let client = &m.fixtures[1]; + assert_eq!((client.selection.start.line, client.selection.start.col), (12, 31)); + let own = m.uses.iter().find(|u| u.class.as_deref() == Some("TestTasks") && u.in_fixture.is_some()).unwrap(); + assert_eq!(own.in_fixture.as_deref(), Some("tasks")); + // The empty `usefixtures` string is still a place to complete. + assert!(m.slots.iter().any(|s| s.range.start == s.range.end)); + } + + #[test] + fn resolves_nearest_first_and_overrides_outward() { + let m = module(TEST_MODULE); + let conftest = module( + "import pytest\n\n@pytest.fixture\ndef tasks():\n return [1]\n\n@pytest.fixture\ndef db():\n pass\n", + ); + let builtins = module("from _pytest.fixtures import fixture\n\n@fixture\ndef tmp_path():\n pass\n"); + let layers = [&m, &conftest, &builtins]; + // In the class: its own `tasks`; at module level: the module's. + assert_eq!(resolve_fixture(&layers, "tasks", Some("TestTasks"), false), Some((0, 2))); + assert_eq!(resolve_fixture(&layers, "tasks", None, false), Some((0, 0))); + // The class fixture's `tasks` parameter: the module's; the module's own: conftest's. + assert_eq!(resolve_fixture(&layers, "tasks", Some("TestTasks"), true), Some((0, 0))); + assert_eq!(resolve_fixture(&layers, "tasks", None, true), Some((1, 0))); + assert_eq!(resolve_fixture(&layers, "db", None, false), Some((1, 1))); + assert_eq!(resolve_fixture(&layers, "tmp_path", None, false), Some((2, 0))); + assert_eq!(resolve_fixture(&layers, "missing", None, false), None); + // Completion: one entry per name, nearest first; another class's fixtures are hidden. + let visible: Vec<&str> = + visible_fixtures(&layers, None).iter().map(|&(l, f)| layers[l].fixtures[f].name.as_str()).collect(); + assert_eq!(visible, ["tasks", "client", "db", "tmp_path"]); + } + + #[test] + fn a_later_definition_replaces_an_earlier_one() { + let m = module("import pytest\n\n@pytest.fixture\ndef a():\n pass\n\n@pytest.fixture\ndef a():\n pass\n"); + assert_eq!(resolve_fixture(&[&m], "a", None, false), Some((0, 1))); + } + + #[test] + fn finds_the_use_and_slot_at_a_position() { + let m = module(TEST_MODULE); + // `def test_add(tasks, …` is on line 18; the caret right after `tasks`. + let at = m.use_at(Pos::new(18, 18)).unwrap(); + assert_eq!(at.name, "tasks"); + assert!(m.slot_at(Pos::new(18, 13)).is_some()); + assert!(m.use_at(Pos::new(22, 11)).is_none(), "a plain function's parameters are no fixtures"); + } +} diff --git a/fixtures/python-app/tests/conftest.py b/fixtures/python-app/tests/conftest.py new file mode 100644 index 0000000000..197bf8282d --- /dev/null +++ b/fixtures/python-app/tests/conftest.py @@ -0,0 +1,15 @@ +import pytest + +from tasks import Priority, TaskList + + +@pytest.fixture +def tasks(): + return TaskList() + + +@pytest.fixture(name="sample") +def sample_tasks(tasks): + tasks.add("write docs", Priority.HIGH) + tasks.add("tidy up", Priority.LOW) + return tasks diff --git a/fixtures/python-app/tests/test_fixtures.py b/fixtures/python-app/tests/test_fixtures.py new file mode 100644 index 0000000000..cc3677e4f3 --- /dev/null +++ b/fixtures/python-app/tests/test_fixtures.py @@ -0,0 +1,21 @@ +import pytest + +from tasks import Priority + + +class TestPending: + @pytest.fixture + def tasks(self, tasks): + # Overrides the conftest.py fixture of the same name. + tasks.add("review", Priority.NORMAL) + return tasks + + def test_counts_the_extra_task(self, tasks): + assert len(tasks.pending()) == 1 + + +@pytest.mark.usefixtures("sample") +def test_sample_is_sorted(sample, request, tmp_path): + assert [t.title for t in sample.pending()] == ["write docs", "tidy up"] + assert request.getfixturevalue("tasks") is sample + assert tmp_path.is_dir() diff --git a/smoke/run.test.ts b/smoke/run.test.ts index cd2c0342b9..2f5ecc38ba 100644 --- a/smoke/run.test.ts +++ b/smoke/run.test.ts @@ -123,7 +123,7 @@ const CASES: Record = { tests: { config: "pytest", failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), - passed: 7, + passed: 9, failed: "test_intentionally_failing", file: "tests/test_models.py", }, diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index dd317c80a4..4f095c5d49 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -445,6 +445,7 @@ menu_set_disabled always desktop bin menu_set_remote_recent always desktop bindings sync nav_index_definitions always project_host bindings async nav_inheritance always project_host bindings async +nav_pytest_fixtures always project_host bindings async nav_python_stubs always project_host bindings async nav_resolve_module always project_host bindings async notebook_cell_docs trusted project_host bindings sync diff --git a/src/bindings.ts b/src/bindings.ts index d2395a640f..cc29d9e42d 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1211,6 +1211,12 @@ export const commands = { * for native inheritance gutter markers. */ navInheritance: () => typedError(__TAURI_INVOKE("nav_inheritance")), + /** + * pytest fixtures at `pos` of a Python document: the definition pytest uses for the fixture + * named there (a test's parameter, a `usefixtures` / `getfixturevalue` string), and the + * fixtures visible where a fixture name goes, for completion. + */ + navPytestFixtures: (doc: DocId, pos: Pos) => typedError(__TAURI_INVOKE("nav_pytest_fixtures", { doc, pos })), /** * The stub (`.pyi`) of a Python document, or the implementation of a stub, and the * functions and classes declared in both: PyCharm's stub gutter markers. @@ -12137,6 +12143,29 @@ export type PypiPackage = { versions: string[], }; +export type PytestFixtureAt = { + /** The fixture name at the position, and the definition pytest uses for it. */ + reference: PytestFixtureReference | null, + /** + * At a place a fixture name goes (a test's parameters, a `usefixtures` string): the + * fixtures visible there, nearest first. + */ + completions: PytestFixtureItem[] | null, +}; + +export type PytestFixtureItem = { + name: string, + /** The file defining it. */ + path: IpcPath, +}; + +export type PytestFixtureReference = { + name: string, + range: Range, + /** None when no visible module defines it (`request`, a fixture from a hook). */ + definition: Location | null, +}; + /** A class definition and the methods it declares. */ export type PythonClassFacts = { name: string, diff --git a/src/features/index.ts b/src/features/index.ts index f490a393cc..6af88cb7a2 100644 --- a/src/features/index.ts +++ b/src/features/index.ts @@ -45,6 +45,7 @@ import { activate as services } from "./services"; import { activate as github } from "./github"; import { activate as httpClient } from "./http-client"; import { activate as cucumber } from "./cucumber"; +import { activate as pytest } from "./pytest"; import { activate as rails } from "./rails"; import { activate as thymeleaf } from "./thymeleaf"; import { activate as database } from "./database"; @@ -102,6 +103,7 @@ const features: Array<[string, Activate]> = [ ["github", github], ["http-client", httpClient], ["cucumber", cucumber], + ["pytest", pytest], ["rails", rails], ["thymeleaf", thymeleaf], ["database", database], diff --git a/src/features/pytest/index.test.ts b/src/features/pytest/index.test.ts new file mode 100644 index 0000000000..c82ea9a332 --- /dev/null +++ b/src/features/pytest/index.test.ts @@ -0,0 +1,10 @@ +import { describe, expect, it } from "vitest"; +import { where } from "./index"; + +describe("where", () => { + it("shows installed fixtures below site-packages and the project's relative to it", () => { + expect(where("/p/.venv/lib/python3.12/site-packages/_pytest/tmpdir.py", "/p")).toBe("_pytest/tmpdir.py"); + expect(where("/p/tests/conftest.py", "/p")).toBe("tests/conftest.py"); + expect(where("/elsewhere/conftest.py", "/p")).toBe("/elsewhere/conftest.py"); + }); +}); diff --git a/src/features/pytest/index.ts b/src/features/pytest/index.ts new file mode 100644 index 0000000000..0f89a17d58 --- /dev/null +++ b/src/features/pytest/index.ts @@ -0,0 +1,98 @@ +/** + * pytest fixtures: Go to Declaration on a fixture name (a test's or fixture's parameter, a + * `usefixtures` / `getfixturevalue` string) opens the fixture pytest uses, and completion + * offers the visible fixtures there. Resolution (conftest.py files, plugins, pytest's own + * fixtures) is the backend's (`navPytestFixtures`); the language server knows none of it. + */ +import type { CompletionContext, CompletionResult } from "@codemirror/autocomplete"; +import { EditorState } from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; +import { + registerEditorContribution, + registerNavigationProvider, + whenSynced, + type EditorDocContext, +} from "@/editor/api"; +import { docOf } from "@/editor/lsp/lsp"; +import { offsetToPos, posToOffset } from "@/editor/lsp/positions"; +import { call, commands, isTauri, type PytestFixtureAt } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; + +/** The fixtures at `offset`, once the backend has the editor's text; null when the text changed meanwhile. */ +async function fixturesAt(view: EditorView, doc: number, offset: number): Promise { + const text = view.state.doc; + await whenSynced(view); + if (view.state.doc !== text) return null; + const at = await call(commands.navPytestFixtures(doc, offsetToPos(text, offset))); + return view.state.doc === text ? at : null; +} + +/** Text before the caret that may be inside a parameter list or a `usefixtures` / `getfixturevalue` string. */ +const MAYBE_SLOT = /\bdef\s+\w+\s*\([^)]*$|\b(?:usefixtures|getfixturevalue)\s*\([^)]*["'][\w]*$/; + +/** A fixture's file as the lookup shows it: below `site-packages/` for installed ones, else project-relative. */ +export function where(path: string, root: string | null | undefined): string { + const installed = path.lastIndexOf("/site-packages/"); + if (installed >= 0) return path.slice(installed + "/site-packages/".length); + return root && path.startsWith(`${root}/`) ? path.slice(root.length + 1) : path; +} + +function completion(doc: EditorDocContext) { + return async (ctx: CompletionContext): Promise => { + const view = ctx.view; + if (!view || !isTauri()) return null; + if (!MAYBE_SLOT.test(ctx.state.sliceDoc(Math.max(0, ctx.pos - 2000), ctx.pos))) return null; + const word = ctx.matchBefore(/\w*/); + // Typing a name, or right after `(`, `,` or a quote. + if (!word || (word.from === word.to && !ctx.explicit && !/[(,"'\s]/.test(ctx.state.sliceDoc(ctx.pos - 1, ctx.pos)))) + return null; + try { + const at = await fixturesAt(view, doc.doc, ctx.pos); + if (ctx.aborted || !at?.completions?.length) return null; + const root = useProject.getState().project?.root; + const n = at.completions.length; + return { + from: word.from, + to: word.to, + validFor: /^\w*$/, + options: at.completions.map((item, i) => ({ + label: item.name, + type: "variable", + icon: "symbol-function", + typeText: where(item.path, root), + // Nearest first, as pytest picks them. + boost: n - i, + })), + }; + } catch { + return null; + } + }; +} + +export function activate(): () => void { + const offNavigation = registerNavigationProvider(async (view, offset) => { + const doc = docOf(view); + if (!doc || doc.virtual || doc.language !== "python" || !isTauri()) return null; + const at = await fixturesAt(view, doc.doc, offset).catch(() => null); + const ref = at?.reference; + if (!ref?.definition) return null; + const text = view.state.doc; + return { + from: posToOffset(text, ref.range.start), + to: posToOffset(text, ref.range.end), + targets: [{ ...ref.definition, name: ref.name }], + }; + }); + const offCompletion = registerEditorContribution({ + id: "pytest-fixtures", + extensions: (doc) => + doc.language === "python" && !doc.virtual && !doc.readOnly + ? EditorState.languageData.of(() => [{ openideaCompletion: completion(doc) }]) + : [], + }); + return () => { + offNavigation(); + offCompletion(); + }; +}