test: bypass Turnstile network calls in test env
Some checks failed
CI / lint (push) Successful in 9s
CI / type-check (push) Successful in 16s
CI / test (push) Failing after 2m17s

This commit is contained in:
Bu5hm4nn
2026-04-08 16:53:40 +02:00
parent eb262189cf
commit e45c935eb6
2 changed files with 27 additions and 1 deletions

View File

@@ -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,

View File

@@ -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