getsentry / pytest-responses

py.test integration for responses

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Fixture Creates Second Mock, Cleans up Only One

martinLE opened this issue · comments

Environment

python = "3.8.8"
pytest = "6.2.2"
pytest-responses = "0.5.0"

Steps to Reproduce

  1. Create a test that uses the responses fixture.
  2. In a second test, use @pytest.mark.withoutresponses and create a request.

Minimal example:

import pytest
import requests


def test_enabled(responses):
    url = 'http://responses.valid'
    responses.add(responses.GET, url, status=200)
    requests.get(url)

    assert len(responses.calls) == 1


@pytest.mark.withoutresponses
def test_disabled():
    requests.get('https://github.com')

    assert True

Expected Result

Responses is not active in the second test. Both tests pass.

Actual Result

Responses is still active and raises requests.exceptions.ConnectionError: Connection refused by Responses - the call doesn't match any registered mock.

Possible Explanation

Responses already creates a default RequestsMock. The fixture creates another mock, but the teardown will only cleanup one mock.
Instead of creating a second mock, the fixture could just return the already created default mock, like this:

@pytest.fixture
def responses():
    return responses_._default_mock

With this change, both tests will pass.