Authentica OTP tests
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
"""Mocked end-to-end phone auth flow using Authentica OTP provider."""
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from django.test import override_settings
|
||||
from django.urls import reverse
|
||||
|
||||
from apps.accounts.models import User
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@override_settings(OTP_PROVIDER="authentica")
|
||||
@patch("requests.post")
|
||||
def test_phone_auth_flow_with_authentica_mock(mock_post, client):
|
||||
def make_response(payload, ok=True):
|
||||
response = MagicMock()
|
||||
response.ok = ok
|
||||
response.json.return_value = payload
|
||||
response.text = ""
|
||||
return response
|
||||
|
||||
def side_effect(url, headers=None, json=None, timeout=None):
|
||||
assert headers and headers.get("X-Authorization") == "api-key"
|
||||
assert timeout == 7.0
|
||||
if url.endswith("/api/v2/send-otp"):
|
||||
assert json == {"method": "sms", "phone": "+966512345678"}
|
||||
return make_response({"success": True})
|
||||
if url.endswith("/api/v2/verify-otp"):
|
||||
if json == {"phone": "+966512345678", "otp": "123456"}:
|
||||
return make_response({"verified": True})
|
||||
return make_response({"verified": False})
|
||||
raise AssertionError(f"Unexpected URL {url}")
|
||||
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"AUTHENTICA_API_KEY": "api-key",
|
||||
"AUTHENTICA_TIMEOUT_SECONDS": "7",
|
||||
},
|
||||
):
|
||||
mock_post.side_effect = side_effect
|
||||
|
||||
request_url = reverse("phone_auth_request")
|
||||
verify_url = reverse("phone_auth_verify")
|
||||
|
||||
response = client.post(
|
||||
request_url,
|
||||
{"phone_number": "0512345678", "channel": "sms", "first_name": "Sara"},
|
||||
content_type="application/json",
|
||||
)
|
||||
assert response.status_code == 201
|
||||
request_id = response.json()["request_id"]
|
||||
|
||||
bad = client.post(
|
||||
verify_url,
|
||||
{"request_id": request_id, "code": "000000"},
|
||||
content_type="application/json",
|
||||
)
|
||||
assert bad.status_code == 400
|
||||
|
||||
good = client.post(
|
||||
verify_url,
|
||||
{"request_id": request_id, "code": "123456"},
|
||||
content_type="application/json",
|
||||
)
|
||||
assert good.status_code == 200
|
||||
|
||||
user = User.objects.filter(phone_number="+966512345678").first()
|
||||
assert user is not None
|
||||
assert user.is_phone_verified is True
|
||||
Reference in New Issue
Block a user