如何Mock模块局部变量?测试遇UnboundLocalError问题求助
如何Mock模块局部变量并解决UnboundLocalError错误?
问题场景
script.py
import os my_var = os.getenv("my_variable") def my_func(): my_var = my_var + "_new" print(my_var) return my_var
script_test.py
from unittest.mock import patch from utils.script import my_func @patch('utils.script.my_var', "this_is_a_test_variable") def test_get_duration_paths_v1(path): x = my_func() print("variable is", x)
运行测试用例时抛出错误:
UnboundLocalError: local variable 'my_var' referenced before assignment
解决方案
1. 修复原函数的UnboundLocalError
在my_func中,你试图修改同名变量,但Python会将函数内赋值的my_var视为局部变量,导致在赋值前引用它时报错。解决方式有两种:
使用
global声明:明确告诉Python使用全局作用域的my_vardef my_func(): global my_var my_var = my_var + "_new" print(my_var) return my_var通过模块名引用全局变量:如果
script.py是作为模块导入,直接用模块名访问全局变量,避免局部变量混淆import script def my_func(): script.my_var = script.my_var + "_new" print(script.my_var) return script.my_var
2. 正确Mock模块全局变量
你的@patch路径是正确的,但需要调整测试函数的参数(移除未使用的path),确保测试逻辑正常执行:
修正后的script_test.py示例:
from unittest.mock import patch from utils.script import my_func @patch('utils.script.my_var', "this_is_a_test_variable") def test_get_duration_paths_v1(): x = my_func() print("variable is", x) # 可选:添加断言验证结果 assert x == "this_is_a_test_variable_new"
原理说明
UnboundLocalError的核心原因是Python的变量作用域规则:函数内如果对变量赋值,该变量会被默认视为局部变量,即使全局作用域有同名变量。unittest.mock.patch通过替换模块中的目标变量实现Mock,只要路径正确,就能在测试期间覆盖原全局变量的值。
内容的提问来源于stack exchange,提问作者Exorcismus
相关产品推荐
相关产品推荐

