Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions bedrock/firefox/tests/test_redirects.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
from unittest.mock import patch

from django.conf import settings
from django.test import RequestFactory, override_settings
from django.test import RequestFactory

import pytest

from bedrock.firefox.redirects import mobile_app, validate_param_value
from tests.utils import enable_fxc_redirects


@pytest.mark.parametrize(
Expand Down Expand Up @@ -93,7 +94,7 @@ def test_mobile_app():
EXPECTED_REDIRECT_QS = "?redirect_source=mozilla-org"


@override_settings(ENABLE_FIREFOX_COM_REDIRECTS=True)
@enable_fxc_redirects()
@pytest.mark.django_db
@pytest.mark.parametrize(
"path,expected_location,expected_status,follow_redirects",
Expand Down Expand Up @@ -467,7 +468,7 @@ def test_springfield_redirect_patterns(
assert response.headers["Location"] == expected_location


@override_settings(ENABLE_FIREFOX_COM_REDIRECTS=True)
@enable_fxc_redirects()
@pytest.mark.django_db
@pytest.mark.parametrize(
"path,expected_location,expected_status,follow_redirects",
Expand Down Expand Up @@ -504,7 +505,7 @@ def test_springfield_redirects_carry_over_querystrings_and_add_redirect_source(
assert response.headers["Location"] == expected_location


@override_settings(ENABLE_FIREFOX_COM_REDIRECTS=True)
@enable_fxc_redirects()
@pytest.mark.django_db
@pytest.mark.parametrize(
"path",
Expand All @@ -528,6 +529,7 @@ def test_mobile_app_redirector_does_not_go_to_springfield(client):
assert resp.headers["Location"] == "https://apps.apple.com/app/apple-store/id989804926"


@enable_fxc_redirects()
@pytest.mark.django_db
@pytest.mark.parametrize(
"path",
Expand All @@ -541,7 +543,6 @@ def test_mobile_app_redirector_does_not_go_to_springfield(client):
"/firefox/releases/",
),
)
@override_settings(ENABLE_FIREFOX_COM_REDIRECTS=True)
def test_releasenotes_generic_urls_not_rediected_to_springfield(client, path):
resp = client.get(path)
assert resp.status_code == 302
Expand All @@ -561,7 +562,7 @@ def test_releasenotes_generic_urls_not_rediected_to_springfield(client, path):
("/en-US/firefox/installer-help/", f"{settings.FXC_BASE_URL}/en-US/download/installer-help/{EXPECTED_REDIRECT_QS}"),
),
)
@override_settings(ENABLE_FIREFOX_COM_REDIRECTS=True)
@enable_fxc_redirects()
def test_subsequent_redirects_do_not_carry_querystrings_from_earlier_requests(
client,
path,
Expand All @@ -584,6 +585,7 @@ def test_subsequent_redirects_do_not_carry_querystrings_from_earlier_requests(
("/firefox/browsers/incognito-browser/", f"{settings.FXC_BASE_URL}/more/incognito-browser/{EXPECTED_REDIRECT_QS}"),
),
)
@enable_fxc_redirects()
def test_offsite_redirects_still_work_when_locale_not_in_source_path(
client,
path,
Expand Down
3 changes: 3 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
109 changes: 109 additions & 0 deletions tests/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

import functools
import importlib
from collections.abc import Callable
from typing import Any

from django.test import override_settings


def reload_redirects_with_settings(redirects_module_path: str, middleware_module_path: str, **settings_kwargs):
"""
Generic decorator that enables dynamic redirect reloading for testing.

This decorator:
1. Stores the original setting values before any changes
2. Overrides specified settings using the same pattern as @override_settings
3. Reloads the specified redirects module to pick up new patterns
4. Patches the specified middleware module to use the reloaded patterns
5. Restores original settings and reloads module again after the test

This is needed because Django loads redirects once at startup and doesn't
reload them when @override_settings is used.

Args:
redirects_module_path: The redirects module path to reload
middleware_module_path: The middleware module path to patch
**settings_kwargs: Settings to override

Usage:
@reload_redirects_with_settings(
'bedrock.firefox.redirects',
'bedrock.redirects.middleware',
ENABLE_FIREFOX_COM_REDIRECTS=True
)
def test_my_redirect():
# Your test code here
pass
"""

def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
from django.conf import settings

original_settings = {}
for setting_name in settings_kwargs.keys():
original_settings[setting_name] = getattr(settings, setting_name, None)

with override_settings(**settings_kwargs):
original_get_resolver = _reload_module_and_patch_middleware(redirects_module_path, middleware_module_path)
try:
return func(*args, **kwargs)
finally:
restore_settings = {name: value for name, value in original_settings.items()}
with override_settings(**restore_settings):
_reload_module_and_patch_middleware(redirects_module_path, middleware_module_path)
middleware_module = importlib.import_module(middleware_module_path)
middleware_module.get_resolver = original_get_resolver

return wrapper

return decorator


def _reload_module_and_patch_middleware(redirects_module_path: str, middleware_module_path: str) -> Any:
"""
Import, reload the specified module, and patch the redirects middleware.

Args:
redirects_module_path: The redirects module path to reload
middleware_module_path: The middleware module path to patch

Returns:
The original get_resolver function for restoration
"""
middleware_module = importlib.import_module(middleware_module_path)

redirects_module = importlib.import_module(redirects_module_path)
importlib.reload(redirects_module) # type: ignore
original_get_resolver = middleware_module.get_resolver

def patched_get_resolver(patterns=None):
if patterns is None:
patterns = redirects_module.redirectpatterns # type: ignore
return original_get_resolver(patterns)

middleware_module.get_resolver = patched_get_resolver

return original_get_resolver


def enable_fxc_redirects():
"""
Convenience decorator for Firefox.com redirect testing.

This is a wrapper around reload_redirects_with_settings that enables
Firefox.com redirects for the duration of the test regardless of the
ENABLE_FIREFOX_COM_REDIRECTS environment variable.

Usage:
@enable_fxc_redirects()
def test_my_redirect():
# Your test code here
pass
"""
return reload_redirects_with_settings("bedrock.firefox.redirects", "bedrock.redirects.middleware", ENABLE_FIREFOX_COM_REDIRECTS=True)