getsentry / getsentry/responses

How to combine multiple RequestMock contexts (pytest fixture)?

Open
#779 0 comments 0 reactions 0 assignees View on GitHub
question
Dominant language
Python
Stars
4.3k
Forks
378
Avg merge
4d 1h
Merged PRs (30d)
1

Description

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?

```python
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., *mock_bar_api.]
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

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.