79 lines
2.6 KiB
Python
79 lines
2.6 KiB
Python
from unittest.mock import patch
|
|
|
|
import pytest
|
|
from django.test import override_settings
|
|
from django.urls import reverse
|
|
|
|
from apps.accounts.models import PhoneOTP, User
|
|
|
|
|
|
@pytest.mark.django_db
|
|
@override_settings(OTP_PROVIDER="console")
|
|
def test_phone_auth_creates_user_and_issues_tokens(client):
|
|
# Deterministic OTP so we can verify the flow without external providers.
|
|
with patch("apps.accounts.services.otp.generate_code", return_value="123456"):
|
|
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"]
|
|
|
|
otp = PhoneOTP.objects.filter(phone_number="+966512345678").order_by("-created_at").first()
|
|
assert otp is not None
|
|
assert str(otp.id) == 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
|
|
data = good.json()
|
|
assert "access" in data
|
|
assert "refresh" in data
|
|
|
|
user = User.objects.filter(phone_number="+966512345678").first()
|
|
assert user is not None
|
|
assert user.is_phone_verified is True
|
|
|
|
|
|
@pytest.mark.django_db
|
|
@override_settings(OTP_PROVIDER="console")
|
|
def test_phone_auth_refresh_endpoint_still_works(client):
|
|
with patch("apps.accounts.services.otp.generate_code", return_value="123456"):
|
|
request_response = client.post(
|
|
reverse("phone_auth_request"),
|
|
{"phone_number": "0512345678", "channel": "sms"},
|
|
content_type="application/json",
|
|
)
|
|
request_id = request_response.json()["request_id"]
|
|
|
|
verify_response = client.post(
|
|
reverse("phone_auth_verify"),
|
|
{"request_id": request_id, "code": "123456"},
|
|
content_type="application/json",
|
|
)
|
|
|
|
assert verify_response.status_code == 200
|
|
refresh = verify_response.json()["refresh"]
|
|
|
|
refresh_response = client.post(
|
|
reverse("token_refresh"),
|
|
{"refresh": refresh},
|
|
content_type="application/json",
|
|
)
|
|
assert refresh_response.status_code == 200
|
|
assert "access" in refresh_response.json()
|