Python测试场景下替换BASE_PATH常量并联动更新关联路径的解决方案咨询
The core issue here is that your FOLDER_1_PATH and FOLDER_2_PATH are calculated once at module import time using the original BASE_PATH value. Patching BASE_PATH later doesn't trigger a recalculation because those variables are already statically set. Here's a clean solution that avoids classes and keeps your constants approach intact:
Solution: Use Module-Level __getattr__ for Dynamic Path Calculation
Modify your constants.py to generate the folder paths dynamically whenever they're accessed, instead of setting them as static variables. This way, every time you reference the folder paths, they'll use the current value of BASE_PATH:
# constants.py import os BASE_PATH = "/base/" def __getattr__(name): """Dynamically generate path attributes when accessed.""" if name == "FOLDER_1_PATH": return os.path.join(BASE_PATH, "folder1") elif name == "FOLDER_2_PATH": return os.path.join(BASE_PATH, "folder2") # Raise standard AttributeError for unknown attributes raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
Key Notes for Other Scripts
Make sure any script that uses these paths references them through the constants module, rather than importing them directly as top-level variables. For example:
❌ Avoid this (it caches the static value at import):
from constants import FOLDER_1_PATH
✅ Do this (accesses the dynamic value every time):
import constants # Use constants.FOLDER_1_PATH wherever you need it print(constants.FOLDER_1_PATH)
Test Implementation Example
Now when you patch BASE_PATH in your tests, the folder paths will automatically reflect the new value:
from unittest.mock import patch import constants import your_script_that_uses_paths # Import the script under test def test_updated_base_path(): with patch('constants.BASE_PATH', "A://"): # Verify the dynamic path calculation works assert constants.FOLDER_1_PATH == "A://folder1" assert constants.FOLDER_2_PATH == "A://folder2" # Any function in your_script_that_uses_paths that references # constants.FOLDER_1_PATH will now use the patched value your_script_that_uses_paths.some_function() # Uses "A://folder1"
Why This Works
The __getattr__ function in a module is called whenever an attribute is accessed that doesn't exist as a static variable. By defining your folder paths here, you ensure they're recalculated on every access, using the current BASE_PATH value. This keeps your constants pattern intact while adding the dynamic behavior needed for testing.
内容的提问来源于stack exchange,提问作者Waqar Ahmed

