responses icon indicating copy to clipboard operation
responses copied to clipboard

How to combine multiple RequestMock contexts (pytest fixture)?

Open Kilo59 opened this issue 3 months ago • 0 comments

How can I combine multiple RequestsMock contexts so that they don't overwrite each other? In my specific case I'm using RequestsMock as pytest fixtures.

If there isn't a supported way to do this, what's the easiest way to programmatically copy the registered mocks from 2 different RequestsMock into a 3rd one?

from typing import Generator

import pytest
import requests
import responses

@pytest.fixture
def mock_foo_api() -> Generator[responses.RequestsMock, None, None]:
    with responses.RequestsMock() as rsps:
        rsps.add(
            responses.GET,
            "https://example.foo",
            status=200,
            body="{'msg': 'foo'}"
            content_type="application/json",
        )
        yield rsps

@pytest.fixture
def mock_bar_api() -> Generator[responses.RequestsMock, None, None]:
    with responses.RequestsMock() as rsps:
        rsps.add(
            responses.GET,
            "https://example.bar",
            status=200,
            body="{'msg': 'bar'}"
            content_type="application/json",
        )
        yield rsps

def test_api(mock_foo_api: responses.RequestsMock, mock_bar_api: responses.RequestsMock):
    # this test fails    
    bar_req = requests.get("https://example.bar")
    assert bar_req.status_code == 200

    foo_req = requests.get("https://example.foo")
    assert foo_req.status_code == 200

# can I do something like this?? 👇 

@pytest.fixture
def hypothetical_combined_api_mocks(
    mock_foo_api: responses.RequestsMock,
    mock_bar_api: responses.RequestsMock
):
    with responses.RequestsMock() as rsps:
        for registered_mock in [*mock_foo_api.<SOMETHING>, *mock_bar_api.<SOMETHING>]
            rsps.add(registered_mock)
         yield rsps


def test_api2(hypothetical_combined_api_mocks: responses.RequestsMock):
    bar_req = requests.get("https://example.bar")
    assert bar_req.status_code == 200

    foo_req = requests.get("https://example.foo")
    assert foo_req.status_code == 200

  • This seems somewhat related to #https://github.com/getsentry/responses/issues/542

Kilo59 avatar Sep 17 '25 15:09 Kilo59