Debian Codegraph @

tests/test_instantiating_module.py

raw symbols SCIP
1 """Test that _instantiating_module correctly captures the module that created the App.
2
3 This feature was introduced in PR #495 to improve automatic version detection.
4 The instantiating module is used to detect the version when --version is called.
5 """
6
7 import subprocess
8 import sys
9
10
11 def test_instantiating_module_is_captured(tmp_path):
12 """Test that App._instantiating_module captures the module that created it.
13
14 This is critical for automatic version detection from the app's package.
15 """
16 # Create a test script
17 test_script = tmp_path / "test_app.py"
18 test_script.write_text("""
19 import cyclopts
20
21 app = cyclopts.App()
22
23 # Verify the module was captured
24 if app._instantiating_module is not None:
25 print(f"SUCCESS: {app._instantiating_module.__name__}")
26 else:
27 print("FAIL: Module was not captured")
28 exit(1)
29 """)
30
31 result = subprocess.run(
32 [sys.executable, str(test_script)],
33 capture_output=True,
34 text=True,
35 )
36
37 assert result.returncode == 0, f"Module capture failed:\n{result.stdout}\n{result.stderr}"
38 assert "SUCCESS" in result.stdout
39 # When run as a script, it should be __main__
40 assert "__main__" in result.stdout
41
42
43 def test_instantiating_module_lazy_property():
44 """Test that _instantiating_module behaves as a lazy property."""
45 import cyclopts
46
47 app = cyclopts.App()
48
49 # The module name should be captured at init - this is the KEY test
50 # If this fails, the optimization broke the feature
51 assert app._instantiating_module_name is not None, (
52 "Module name was not captured during App initialization. This breaks version detection!"
53 )
54 assert app._instantiating_module_name == __name__, (
55 f"Expected module name '{__name__}', got '{app._instantiating_module_name}'"
56 )
57
58 # The module object should be lazy (uses UNSET sentinel before first access)
59 from cyclopts.utils import UNSET
60
61 assert app._instantiating_module_cache is UNSET
62
63 # First access should resolve it
64 module = app._instantiating_module
65 assert module is not None
66 assert app._instantiating_module_cache is not UNSET
67
68 # Subsequent accesses should return cached value
69 module2 = app._instantiating_module
70 assert module is module2
71
72
73 def test_instantiating_module_used_for_version():
74 """Test that _instantiating_module is correctly used for version detection."""
75 import cyclopts
76
77 app = cyclopts.App()
78
79 # The app should have captured the test module
80 assert app._instantiating_module is not None
81
82 # When we call _get_fallback_version_string, it should try to use the instantiating module
83 # (though it may fall back to other methods if the module doesn't have version metadata)
84 version = app._get_fallback_version_string()
85 assert isinstance(version, str)
86 # Should return something (either actual version or default "0.0.0")
87 assert version != ""