The problem you are facing is that you are mocking where it is defined, and you should patch where is it used.
Mock an item where it is used, not where it came from.
I leave you some example code, so you can catch the idea.
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
So the important line would be this one:
with mock.patch('project1.module1.INPUT_DIRECTORY', in_folder.strpath):
See, value is mocked where it is used, and not in constants.py (where it is defined)
from mock import patch @patch("location.of.file.and.CONSTANT", mockValue)
– Halfandhalf