pytest_language_server/fixtures/
imports.rs1use super::FixtureDatabase;
11use once_cell::sync::Lazy;
12use rustpython_parser::ast::Stmt;
13use std::collections::HashSet;
14use std::path::{Path, PathBuf};
15use std::sync::Arc;
16use tracing::{debug, info};
17
18static STDLIB_MODULES: Lazy<HashSet<&'static str>> = Lazy::new(|| {
20 [
21 "os",
22 "sys",
23 "re",
24 "json",
25 "typing",
26 "collections",
27 "functools",
28 "itertools",
29 "pathlib",
30 "datetime",
31 "time",
32 "math",
33 "random",
34 "copy",
35 "io",
36 "abc",
37 "contextlib",
38 "dataclasses",
39 "enum",
40 "logging",
41 "unittest",
42 "asyncio",
43 "concurrent",
44 "multiprocessing",
45 "threading",
46 "subprocess",
47 "shutil",
48 "tempfile",
49 "glob",
50 "fnmatch",
51 "pickle",
52 "sqlite3",
53 "urllib",
54 "http",
55 "email",
56 "html",
57 "xml",
58 "socket",
59 "ssl",
60 "select",
61 "signal",
62 "struct",
63 "codecs",
64 "textwrap",
65 "string",
66 "difflib",
67 "inspect",
68 "dis",
69 "traceback",
70 "warnings",
71 "weakref",
72 "types",
73 "importlib",
74 "pkgutil",
75 "pprint",
76 "reprlib",
77 "numbers",
78 "decimal",
79 "fractions",
80 "statistics",
81 "hashlib",
82 "hmac",
83 "secrets",
84 "base64",
85 "binascii",
86 "zlib",
87 "gzip",
88 "bz2",
89 "lzma",
90 "zipfile",
91 "tarfile",
92 "csv",
93 "configparser",
94 "argparse",
95 "getopt",
96 "getpass",
97 "platform",
98 "errno",
99 "ctypes",
100 "__future__",
101 ]
102 .into_iter()
103 .collect()
104});
105
106#[derive(Debug, Clone)]
108#[allow(dead_code)] pub struct FixtureImport {
110 pub module_path: String,
112 pub is_star_import: bool,
114 pub imported_names: Vec<String>,
116 pub importing_file: PathBuf,
118 pub line: usize,
120}
121
122impl FixtureDatabase {
123 pub(crate) fn extract_fixture_imports(
126 &self,
127 stmts: &[Stmt],
128 file_path: &Path,
129 line_index: &[usize],
130 ) -> Vec<FixtureImport> {
131 let mut imports = Vec::new();
132
133 for stmt in stmts {
134 if let Stmt::ImportFrom(import_from) = stmt {
135 let mut module = import_from
137 .module
138 .as_ref()
139 .map(|m| m.to_string())
140 .unwrap_or_default();
141
142 if let Some(ref level) = import_from.level {
147 let dots = ".".repeat(level.to_usize());
148 module = dots + &module;
149 }
150
151 if self.is_standard_library_module(&module) {
153 continue;
154 }
155
156 let line =
157 self.get_line_from_offset(import_from.range.start().to_usize(), line_index);
158
159 let is_star = import_from
161 .names
162 .iter()
163 .any(|alias| alias.name.as_str() == "*");
164
165 if is_star {
166 imports.push(FixtureImport {
167 module_path: module,
168 is_star_import: true,
169 imported_names: Vec::new(),
170 importing_file: file_path.to_path_buf(),
171 line,
172 });
173 } else {
174 let names: Vec<String> = import_from
176 .names
177 .iter()
178 .map(|alias| alias.asname.as_ref().unwrap_or(&alias.name).to_string())
179 .collect();
180
181 if !names.is_empty() {
182 imports.push(FixtureImport {
183 module_path: module,
184 is_star_import: false,
185 imported_names: names,
186 importing_file: file_path.to_path_buf(),
187 line,
188 });
189 }
190 }
191 }
192 }
193
194 imports
195 }
196
197 fn is_standard_library_module(&self, module: &str) -> bool {
200 let first_part = module.split('.').next().unwrap_or(module);
201 STDLIB_MODULES.contains(first_part)
202 }
203
204 pub(crate) fn resolve_module_to_file(
207 &self,
208 module_path: &str,
209 importing_file: &Path,
210 ) -> Option<PathBuf> {
211 debug!(
212 "Resolving module '{}' from file {:?}",
213 module_path, importing_file
214 );
215
216 let parent_dir = importing_file.parent()?;
217
218 if module_path.starts_with('.') {
219 self.resolve_relative_import(module_path, parent_dir)
221 } else {
222 self.resolve_absolute_import(module_path, parent_dir)
224 }
225 }
226
227 fn resolve_relative_import(&self, module_path: &str, base_dir: &Path) -> Option<PathBuf> {
229 let mut current_dir = base_dir.to_path_buf();
230 let mut chars = module_path.chars().peekable();
231
232 while chars.peek() == Some(&'.') {
234 chars.next();
235 if chars.peek() != Some(&'.') {
236 break;
238 }
239 current_dir = current_dir.parent()?.to_path_buf();
241 }
242
243 let remaining: String = chars.collect();
244 if remaining.is_empty() {
245 let init_path = current_dir.join("__init__.py");
247 if init_path.exists() {
248 return Some(init_path);
249 }
250 return None;
251 }
252
253 self.find_module_file(&remaining, ¤t_dir)
254 }
255
256 fn resolve_absolute_import(&self, module_path: &str, start_dir: &Path) -> Option<PathBuf> {
258 let mut current_dir = start_dir.to_path_buf();
259
260 loop {
261 if let Some(path) = self.find_module_file(module_path, ¤t_dir) {
262 return Some(path);
263 }
264
265 match current_dir.parent() {
267 Some(parent) => current_dir = parent.to_path_buf(),
268 None => break,
269 }
270 }
271
272 None
273 }
274
275 fn find_module_file(&self, module_path: &str, base_dir: &Path) -> Option<PathBuf> {
277 let parts: Vec<&str> = module_path.split('.').collect();
278 let mut current_path = base_dir.to_path_buf();
279
280 for (i, part) in parts.iter().enumerate() {
281 let is_last = i == parts.len() - 1;
282
283 if is_last {
284 let py_file = current_path.join(format!("{}.py", part));
286 if py_file.exists() {
287 return Some(py_file);
288 }
289
290 let canonical_py_file = self.get_canonical_path(py_file.clone());
292 if self.file_cache.contains_key(&canonical_py_file) {
293 return Some(py_file);
294 }
295
296 let package_init = current_path.join(part).join("__init__.py");
298 if package_init.exists() {
299 return Some(package_init);
300 }
301
302 let canonical_package_init = self.get_canonical_path(package_init.clone());
304 if self.file_cache.contains_key(&canonical_package_init) {
305 return Some(package_init);
306 }
307 } else {
308 current_path = current_path.join(part);
310 if !current_path.is_dir() {
311 return None;
312 }
313 }
314 }
315
316 None
317 }
318
319 pub fn get_imported_fixtures(
325 &self,
326 file_path: &Path,
327 visited: &mut HashSet<PathBuf>,
328 ) -> HashSet<String> {
329 let canonical_path = self.get_canonical_path(file_path.to_path_buf());
330
331 if visited.contains(&canonical_path) {
333 debug!("Circular import detected for {:?}, skipping", file_path);
334 return HashSet::new();
335 }
336 visited.insert(canonical_path.clone());
337
338 let Some(content) = self.get_file_content(&canonical_path) else {
340 return HashSet::new();
341 };
342
343 let content_hash = Self::hash_content(&content);
344 let current_version = self
345 .definitions_version
346 .load(std::sync::atomic::Ordering::SeqCst);
347
348 if let Some(cached) = self.imported_fixtures_cache.get(&canonical_path) {
350 let (cached_content_hash, cached_version, cached_fixtures) = cached.value();
351 if *cached_content_hash == content_hash && *cached_version == current_version {
352 debug!("Cache hit for imported fixtures in {:?}", canonical_path);
353 return cached_fixtures.as_ref().clone();
354 }
355 }
356
357 let imported_fixtures = self.compute_imported_fixtures(&canonical_path, &content, visited);
359
360 self.imported_fixtures_cache.insert(
362 canonical_path.clone(),
363 (
364 content_hash,
365 current_version,
366 Arc::new(imported_fixtures.clone()),
367 ),
368 );
369
370 info!(
371 "Found {} imported fixtures for {:?}: {:?}",
372 imported_fixtures.len(),
373 file_path,
374 imported_fixtures
375 );
376
377 imported_fixtures
378 }
379
380 fn compute_imported_fixtures(
382 &self,
383 canonical_path: &Path,
384 content: &str,
385 visited: &mut HashSet<PathBuf>,
386 ) -> HashSet<String> {
387 let mut imported_fixtures = HashSet::new();
388
389 let Some(parsed) = self.get_parsed_ast(canonical_path, content) else {
390 return imported_fixtures;
391 };
392
393 let line_index = self.get_line_index(canonical_path, content);
394
395 if let rustpython_parser::ast::Mod::Module(module) = parsed.as_ref() {
396 let imports = self.extract_fixture_imports(&module.body, canonical_path, &line_index);
397
398 for import in imports {
399 let Some(resolved_path) =
401 self.resolve_module_to_file(&import.module_path, canonical_path)
402 else {
403 debug!(
404 "Could not resolve module '{}' from {:?}",
405 import.module_path, canonical_path
406 );
407 continue;
408 };
409
410 let resolved_canonical = self.get_canonical_path(resolved_path);
411
412 debug!(
413 "Resolved import '{}' to {:?}",
414 import.module_path, resolved_canonical
415 );
416
417 if import.is_star_import {
418 if let Some(file_fixtures) = self.file_definitions.get(&resolved_canonical) {
421 for fixture_name in file_fixtures.iter() {
422 imported_fixtures.insert(fixture_name.clone());
423 }
424 }
425
426 let transitive = self.get_imported_fixtures(&resolved_canonical, visited);
428 imported_fixtures.extend(transitive);
429 } else {
430 for name in &import.imported_names {
432 if self.definitions.contains_key(name) {
433 imported_fixtures.insert(name.clone());
434 }
435 }
436 }
437 }
438 }
439
440 imported_fixtures
441 }
442
443 pub fn is_fixture_imported_in_file(&self, fixture_name: &str, file_path: &Path) -> bool {
446 let mut visited = HashSet::new();
447 let imported = self.get_imported_fixtures(file_path, &mut visited);
448 imported.contains(fixture_name)
449 }
450}