From e45c935eb6ad7b5f15bf181613959758e2f56b9d Mon Sep 17 00:00:00 2001 From: Bu5hm4nn Date: Wed, 8 Apr 2026 16:53:40 +0200 Subject: [PATCH] test: bypass Turnstile network calls in test env --- app/services/turnstile.py | 8 ++++++++ tests/test_turnstile.py | 20 +++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/app/services/turnstile.py b/app/services/turnstile.py index 1745f8a..f6e0ee1 100644 --- a/app/services/turnstile.py +++ b/app/services/turnstile.py @@ -66,6 +66,14 @@ def verify_turnstile_token(token: str, remote_ip: str | None = None) -> bool: return True if not token.strip(): return False + if _environment() == "test": + if ( + settings.site_key == ALWAYS_FAIL_TURNSTILE_TEST_SITE_KEY + and settings.secret_key == ALWAYS_FAIL_TURNSTILE_TEST_SECRET_KEY + ): + return False + if settings.uses_test_keys: + return True try: response = requests.post( TURNSTILE_VERIFY_URL, diff --git a/tests/test_turnstile.py b/tests/test_turnstile.py index f5d47ad..e399ef2 100644 --- a/tests/test_turnstile.py +++ b/tests/test_turnstile.py @@ -104,7 +104,9 @@ def test_turnstile_settings_fail_loudly_without_keys_outside_dev(monkeypatch) -> def test_turnstile_verification_returns_false_on_transport_error(monkeypatch) -> None: from app.services import turnstile as turnstile_module - monkeypatch.setenv("APP_ENV", "test") + monkeypatch.setenv("APP_ENV", "production") + monkeypatch.setenv("TURNSTILE_SITE_KEY", "real-site-key") + monkeypatch.setenv("TURNSTILE_SECRET_KEY", "real-secret-key") def raise_error(*args, **kwargs): raise requests.RequestException("boom") @@ -114,6 +116,22 @@ def test_turnstile_verification_returns_false_on_transport_error(monkeypatch) -> assert turnstile_module.verify_turnstile_token("token") is False +def test_turnstile_verification_short_circuits_default_test_keys(monkeypatch) -> None: + from app.services import turnstile as turnstile_module + + monkeypatch.setenv("APP_ENV", "test") + monkeypatch.setenv("TURNSTILE_SITE_KEY", turnstile_module.DEFAULT_TURNSTILE_TEST_SITE_KEY) + monkeypatch.setenv("TURNSTILE_SECRET_KEY", turnstile_module.DEFAULT_TURNSTILE_TEST_SECRET_KEY) + + def raise_error(*args, **kwargs): + raise AssertionError("network should not be called for default test keys") + + monkeypatch.setattr(turnstile_module.requests, "post", raise_error) + + assert turnstile_module.verify_turnstile_token("token") is True + assert turnstile_module.verify_turnstile_token("") is False + + def test_turnstile_settings_ignore_real_credentials_in_test_environment(monkeypatch) -> None: from app.services import turnstile as turnstile_module