0

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.

Shunx
  • 11
  • 1
  • 1
    Please provide an [MCVE](https://stackoverflow.com/help/mcve). – Klaus D. Mar 02 '19 at 04:59
  • 1
    Thank you for your advice. I figured out the condition while I was looking for the minimal code that produces the problem. In the project, other apps' tests also use `client` fixture (I think this is django.test.Client). And if any of the tests is executed before myapp test, myapp test always fails. If myapp test is executed first, it always succeeds. The execution order matters. But I'm not sure what causes this behaviour yet. – Shunx Mar 03 '19 at 17:19

0 Answers0