pytestpython-responses

How can I de-duplicate responses for pytest?


The responses library provides mocks for requests. In my case, it looks typically like this:

import responses

@responses.activate
def test_foo():
    # Add mocks for service A
    responses.add(responses.POST, 'http://service-A/foo', json={'bar': 'baz'}, status=200)
    responses.add(responses.POST, 'http://service-A/abc', json={'de': 'fg'}, status=200)


@responses.activate
def test_another_foo():
    # Add mocks for service A
    responses.add(responses.POST, 'http://service-A/foo', json={'bar': 'baz'}, status=200)
    responses.add(responses.POST, 'http://service-A/abc', json={'de': 'fg'}, status=200)


How can I avoid this code duplication?

I would love to have a mock_service_a fixture or something similar.


Solution

  • Just as you suggest, creating a fixture solves these issues.

    import pytest
    import responses
    import requests
    
    
    @pytest.fixture(scope="module", autouse=True)
    def mocked_responses():
        with responses.RequestsMock() as rsps:
            rsps.add(
                responses.POST, "http://service-a/foo", json={"bar": "baz"}, status=200
            )
            rsps.add(
                responses.POST, "http://service-a/abc", json={"de": "fg"}, status=200
            )
            yield rsps
    
    
    def test_foo():
        resp = requests.post("http://service-a/foo", json={"bar": "baz"})
        assert resp.status_code == 200
    
    
    def test_another_foo():
        resp = requests.post("http://service-a/abc", json={"de": "fg"})
        assert resp.status_code == 200
    
    
    

    Running it returns:

    ==================================== test session starts =====================================
    platform darwin -- Python 3.9.1, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
    rootdir: **
    collected 2 items                                                                            
    
    tests/test_grab.py ..                                                                  [100%]
    
    ===================================== 2 passed in 0.21s ======================================