你面临的问题是你在定义它的地方模拟,你应该修补它在哪里使用。
模拟一个项目的使用位置,而不是它的来源。
我给你留下一些示例代码,这样你就可以理解这个想法。
project1/constants.py
INPUT_DIRECTORY="/input_folder"
project1/module1.py
from project1.constants import INPUT_DIRECTORY
import os
def clean_directories():
for filename in os.listdir(INPUT_DIRECTORY):
filepath = os.path.join(directory, filename)
os.remove(filepath)
project1/tests/test_module1.py
import mock, pytest
def test_clean_directories(tmpdir_factory):
"""Test that folders supposed to be emptied, are effectively emptied"""
# Mock folder and one file in it
in_folder = tmpdir_factory.mktemp("in")
in_file = in_folder.join("name2.json")
in_file.write("{'asd': 3}")
# Check there is one file in the folder
assert len([name for name in os.listdir(in_folder.strpath) if os.path.isfile(os.path.join(path, name))]) == 1
# As this folder is not a parameter of the function, mock it.
with mock.patch('project1.module1.INPUT_DIRECTORY', in_folder.strpath):
clean_directories()
# Check there is no file in the folder
assert len([name for name in os.listdir(in_folder.strpath) if os.path.isfile(os.path.join(path, name))]) == 0
所以重要的一行是这一行:
with mock.patch('project1.module1.INPUT_DIRECTORY', in_folder.strpath):
看,值是在 在哪里使用被模拟的,而不是在 constants.py 中(在哪里定义)