Skip to content

Fixture Creates Second Mock, Cleans up Only One #22

Open

Description

@martinLE

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.

Activity

  1. filbranden commented on Sep 13, 2024

    @filbranden

    Indeed that's the case.

    I think a much cleaner solution actually is to drop the pytest_runtest_setup(), pytest_runtest_teardown() and the @pytest.mark.withoutresponses altogether and simply provide the responses fixture, so a test that wants to enable responses simply has to include the fixture, and any test that doesn't will not be affected by it.

    That makes the code almost trivial, just a 3-liner, in fact basically what's suggested under https://github.com/getsentry/responses/blob/master/README.rst#responses-as-a-pytest-fixture

    Though it would be nice to still have a standard pytest fixture exported under the responses name, without having to define it ad hoc on any pytest script that wants to use it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions