I have 1 file which loads a particular resource ( from a file ) that takes a while to load.
I have a function in another file which uses that resource by importing it first. When that resource is first imported, it loads and takes a bit.
However, when I’m testing that function that requires that resource, I wanna pass it another smaller resource.
Unfortunately, there aren’t any major refactors I’m able to do to either file1.py
or file2.py
. Is there a solution using pytest
? I haven’t been able to get it working.
file1.py
def load_resource():
print("Loading big resource...")
return {"key": "big resource"}
resource = load_resource()
file2.py
from file1 import resource
def my_func():
return resource["key"]
test.py
import pytest
@pytest.fixture(autouse=True)
def mock_load_resource(monkeypatch):
def mock_resource():
return {'key': 'mocked_value'}
monkeypatch.setattr('file1', 'load_resource', mock_resource)
monkeypatch.setattr('file1', 'resource', mock_resource())
def test_my_function():
from file2 import my_func
result = my_func()
assert result == 'mocked_value'