Skip to content

Commit

Permalink
Optionally disable all HTTP request mocks
Browse files Browse the repository at this point in the history
  • Loading branch information
tillprochaska committed Nov 17, 2024
1 parent eaf8fa5 commit b3f1927
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions backend/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
executed and rollback any changes after execution. In order to test API routes, we make use
of Flask’s built-in test client."""

import os

import pytest
import responses as responses_lib
from responses import FirstMatchRegistry, RequestsMock

from howtheyvote.db import Session, engine, migrate, session_factory
from howtheyvote.meili import configure_indexes, delete_indexes
Expand Down Expand Up @@ -55,8 +57,32 @@ def api(app):
yield app.test_client()


class DummyRegistry(FirstMatchRegistry):
"""A registry that ignores any requests that are added."""
def add(self, response):
return response


@pytest.fixture
def responses():
"""Allows mocking HTTP requests made with requests."""
with responses_lib.RequestsMock() as r:
yield r

mock_requests = os.environ.get("HTV_TEST_MOCK_REQUESTS", "true").lower() in ["true", "1"]

if not mock_requests:
# In most cases, we want HTTP requests in tests to be mocked. The `responses` package
# doesn’t seem to provide a global configuration option to disable all mocks and pass
# through the request.
#
# When calling `responses.get("http://...", body="Lorem ipsum")` in a test to register
# a mock response, the mock is stored in a registry. When the tested then tries to send
# a matching request, `responses` tries to find a matching mock in the registry. To
# disable all mocks, we simply pass a dummy registry that never actually registers any
# mocks and allow all unmatched requests to pass to the original source.
with RequestsMock(registry=DummyRegistry) as r:
r.add_passthru("http")
yield r
else:
# Return a "normal" requests mock that fails any request that isn’t explicitly mocked.
with RequestsMock() as r:
yield r

0 comments on commit b3f1927

Please sign in to comment.