I have a weird problem with pytest and mock patching.
My django app calls currency exchanges' APIs when receiving a request.
I want to patch them while testing, but it doesn't work.
The command below succeeds. It doesn't send any request to real exchange servers.
pipenv run pytest --reuse-db myapp
But, the command below fails because it sends requests to real exchange API servers. Seems patching is not working.
pipenv run pytest --reuse-db
The project structure looks like this.
django_proj/
django_proj/
myapp/
views.py
urls.py
backends/
backend1.py
backend2.py
tests/
test_views.py
test_views.py
class MockBackend1:
# Some mock methods
# They returns mock values instead of sending requests to real servers.
class MockBackend2:
# Some mock methods
# They returns mock values instead of sending requests to real servers.
@patch('myapp.backends.backend1.Backend1', MockBackend1)
@patch('myapp.backends.backend2.Backend2', MockBackend2)
class TestListAPIView:
@pytest.fixture
...
def test_list(self, client, params):
"""Test list."""
response = client.get(
reverse("myapp:list"),
data=params
)
content = response.json()
# sample assertion
asset content == mocked_content
What causes the difference above?
And how can you make patching work properly in both cases?
Thanks in advance.