Debian Codegraph @

tests/test_nested_package_relative_import.py

raw symbols SCIP
1 # tests/test_nested_package_imports.py
2 import os
3 import subprocess
4 import sys
5 import textwrap
6 from pathlib import Path
7
8
9 def test_nested_package_relative_import(tmp_path):
10 """
11 Scalene should profile a module inside a sub‑package without breaking
12 its relative imports. Regression test for PR #903
13 (commit bb8b753b7…).
14 """
15 # ------------------------------------------------------------------
16 # 1. Create the package pkg.subpkg with a helper and a module.
17 # ------------------------------------------------------------------
18 pkg: Path = tmp_path / "pkg"
19 subpkg: Path = pkg / "subpkg"
20 subpkg.mkdir(parents=True)
21
22 # mark both directories as packages
23 (pkg / "__init__.py").write_text("")
24 (subpkg / "__init__.py").write_text("")
25
26 # helper that the target module will import relatively
27 (subpkg / "helper.py").write_text("def foo():\n" " return 42\n")
28
29 # target module that depends on the relative import
30 (subpkg / "mod.py").write_text(
31 textwrap.dedent(
32 """
33 from .helper import foo
34
35 if __name__ == "__main__":
36 print(foo()) # prints 42 on success
37 """
38 )
39 )
40
41 # ------------------------------------------------------------------
42 # 2. Invoke Scalene as a separate process on that module.
43 # ------------------------------------------------------------------
44 env = os.environ.copy()
45 env["PYTHONPATH"] = str(tmp_path) # make package discoverable
46
47 result = subprocess.run(
48 [
49 sys.executable,
50 "-m",
51 "scalene",
52 "-m",
53 "pkg.subpkg.mod",
54 "--cli", # plain‑text output, no browser
55 "--cpu-only", # keep the run fast
56 ],
57 cwd=tmp_path,
58 env=env,
59 capture_output=True,
60 text=True,
61 check=False,
62 )
63
64 # ------------------------------------------------------------------
65 # 3. Assertions: process exited cleanly and the helper ran.
66 # ------------------------------------------------------------------
67 assert result.returncode == 0, result.stderr
68 assert "42" in result.stdout