python单元测试中的模拟常量不起作用
我正在尝试在python单元测试中模拟常量。
我有一个名为 settings.py 的模块,其中包含一组常量,特别是我有一个:
REL_PATH = "my/path/{}/file.csv"
然后在另一个模块中,我有一个使用REL_PATH变量的函数,如下所示:
from path.for.REL_PATH.setting import REL_PATH
def create_csv(missing_path_here):
columns = ["col_a", "col_b", ...]
empty_df = pd.DataFrame(columns=columns)
Writer(empty_df, REL_PATH.format(missing_path_here)).write_csv()
在我的单元测试中,我有以下代码:
class TestCreateAnomaliesRepositoryCsv(unittest.TestCase):
@patch("path.for.setting.REL_PATH", "another/custom/path/file.csv")
def test_create_anomalies_repository_csv(self):
create_csv(missing_path_here="test")
我希望通过这种方式将在“另一个/自定义/路径/”路径下创建csv文件,但仍在原始目录中创建csv文件。
我也试图这样做:
def test_create_anomalies_repository_csv(self):
with path("path.for.setting.REL_PATH", "another/custom/path/file.csv")
create_csv(missing_path_here="test")
但最终结果是相同的。
我究竟做错了什么?
-
如果要修补对象,则必须始终修补模块中使用的对象,例如,如果您以以下形式导入对象:
from x import y
在模块中module
,必须修补module.y
而不是x.y
。这是在描述文档,并且有一个很好的博客文章由斯内德尔德在详细描述问题。在您的情况下,您需要:@patch("path.to.using_module.REL_PATH", "another/custom/path/file.csv") def test_create_anomalies_repository_csv(self): create_csv(missing_path_here="test")
只要
path.to.using_module.py
输入这样的常量:from path.for.setting import REL_PATH
您尝试过的另一个变体是等效的,也可以使用:
def test_create_anomalies_repository_csv(self): with path("path.to.using_module.REL_PATH", "another/custom/path/file.csv") create_csv(missing_path_here="test")
总而言之,您始终必须检查如何导入要使用的对象。基本上有两种情况:
- 该对象是在进口
sut.py
像import module
或import module.object
在这种情况下,它可以被修补为-module.object
- 该对象的导入方式
sut.py
类似from module import object
-在这种情况下,sut.py
使用本地引用来引用该对象,并且应为sut.object
- 该对象是在进口