import pytest from apps.users.services import google_oauth as google pytestmark = pytest.mark.unit def test_google_state_and_flow_are_single_use_or_expire(): state = google.create_google_state() google.consume_google_state(state) with pytest.raises(google.GoogleOAuthFlowError): google.consume_google_state(state) flow = google.create_google_flow({"status": "collect_profile", "email": "person@example.com", "google_profile": {"secret": True}}) assert google.get_google_flow(flow) == {"status": "collect_profile", "email": "person@example.com"} google.update_google_flow(flow, {"status": "authenticated", "access_token": "token"}) assert google.get_google_flow(flow)["access_token"] == "token" with pytest.raises(google.GoogleOAuthFlowError): google.get_google_flow("unknown") def test_google_authorization_url_requires_configured_client(settings): settings.GOOGLE_OAUTH_CLIENT_ID = "client-id" settings.GOOGLE_OAUTH_REDIRECT_URI = "https://example.test/callback" url = google.build_google_authorization_url() assert "client_id=client-id" in url assert "state=" in url def test_google_profile_exchange_checks_verified_email(settings, mocker): settings.GOOGLE_OAUTH_CLIENT_ID = "client-id" settings.GOOGLE_OAUTH_CLIENT_SECRET = "secret" settings.GOOGLE_OAUTH_REDIRECT_URI = "https://example.test/callback" token = mocker.patch("apps.users.services.google_oauth.requests.post") token.return_value.json.return_value = {"access_token": "access"} profile = mocker.patch("apps.users.services.google_oauth.requests.get") profile.return_value.json.return_value = {"sub": "google-1", "email": " PERSON@EXAMPLE.COM ", "email_verified": True} result = google.exchange_code_for_google_profile("code") assert result.provider_user_id == "google-1" assert result.email == "person@example.com" profile.return_value.json.return_value["email_verified"] = False with pytest.raises(google.GoogleOAuthFlowError): google.exchange_code_for_google_profile("code") def test_google_avatar_extension_uses_safe_suffix(): profile = google.GoogleProfile("id", "person@example.com", True, "", "", "https://example.test/a.png?size=1") assert google._avatar_file_extension(profile) == "png" profile.avatar_url = "https://example.test/a.exe" assert google._avatar_file_extension(profile) == "jpg"