Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: restrict external HTTP calls in tests #3866

Merged
merged 3 commits into from
May 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ repos:
exclude: migrations

- repo: https://github.com/pycqa/flake8
rev: 6.0.0
rev: 7.0.0
hooks:
- id: flake8
name: flake8
Expand Down
33 changes: 33 additions & 0 deletions api/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from pytest_django.plugin import blocking_manager_key
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
from urllib3.connectionpool import HTTPConnectionPool
from xdist import get_xdist_worker_id

from api_keys.models import MasterAPIKey
Expand Down Expand Up @@ -120,6 +121,38 @@ def django_db_setup(request: pytest.FixtureRequest) -> None:
db_settings["NAME"] = test_db_name


@pytest.fixture(autouse=True)
def restrict_http_requests(monkeypatch: pytest.MonkeyPatch) -> None:
matthewelwell marked this conversation as resolved.
Show resolved Hide resolved
"""
This fixture prevents all tests from performing HTTP requests to
any host than `localhost`.

Any external request attempt leads to `RuntimeError` with a helpful message
pointing developers to the `responses` fixture.
"""
allowed_hosts = {"localhost"}
original_urlopen = HTTPConnectionPool.urlopen

def urlopen_mock(
self,
method: str,
url: str,
*args,
**kwargs,
) -> HTTPConnectionPool.ResponseCls:
if self.host in allowed_hosts:
return original_urlopen(self, method, url, *args, **kwargs)

raise RuntimeError(
f"Blocked {method} request to {self.scheme}://{self.host}{url}. "
"Use `responses` fixture to mock the response!"
)

monkeypatch.setattr(
"urllib3.connectionpool.HTTPConnectionPool.urlopen", urlopen_mock
)


trait_key = "key1"
trait_value = "value1"

Expand Down
2 changes: 1 addition & 1 deletion api/tests/unit/users/utils/test_unit_users_mailer_lite.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def test_batch_subscribe__subscribe_populates_batch_correctly(mocker):
)
users = [user1, user2]
# When
with BatchSubscribe() as batch:
with BatchSubscribe(mocker.MagicMock()) as batch:
for user in users:
batch.subscribe(user)
# Then
Expand Down