| 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 |
|
| 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 |
|
| 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 |
|
| 50 |
|
| 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 |
|
| 59 |
from cyclopts.utils import UNSET |
| 60 |
|
| 61 |
assert app._instantiating_module_cache is UNSET |
| 62 |
|
| 63 |
|
| 64 |
module = app._instantiating_module |
| 65 |
assert module is not None |
| 66 |
assert app._instantiating_module_cache is not UNSET |
| 67 |
|
| 68 |
|
| 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 |
|
| 80 |
assert app._instantiating_module is not None |
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
version = app._get_fallback_version_string() |
| 85 |
assert isinstance(version, str) |
| 86 |
|
| 87 |
assert version != "" |