test_wx_qr_api.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """web wx-qr create/status API。"""
  2. from types import SimpleNamespace
  3. from unittest.mock import AsyncMock, patch
  4. from fastapi.testclient import TestClient
  5. from app.main import app
  6. from app.services import wx_qr_session
  7. client = TestClient(app)
  8. def setup_function():
  9. wx_qr_session._memory_clear_for_tests()
  10. def test_wx_qr_create_and_poll_pending():
  11. with patch("app.services.wx_qr_session._redis", return_value=None), patch(
  12. "app.api.public.get_unlimited_wxacode",
  13. return_value=b"\x89PNG\r\n\x1a\n",
  14. ):
  15. r = client.post("/api/web/auth/wx-qr/create")
  16. assert r.status_code == 200
  17. body = r.json()
  18. assert body.get("code") == 200
  19. data = body["data"]
  20. sid = data["sessionId"]
  21. assert data["qrImageBase64"].startswith("data:image/")
  22. st = client.get("/api/web/auth/wx-qr/status", params={"sessionId": sid})
  23. assert st.status_code == 200
  24. assert st.json()["data"]["status"] == "pending"
  25. def test_web_qr_confirm_success_sets_session():
  26. fake_user = SimpleNamespace(
  27. id="u1", phone_no="13800138000", wx_openid=None, wx_unionid=None, status="1"
  28. )
  29. tokens = {
  30. "token": "access",
  31. "refreshToken": "refresh",
  32. "expiresIn": 3600,
  33. "userInfo": {"id": "u1"},
  34. }
  35. with patch("app.services.wx_qr_session._redis", return_value=None):
  36. wx_qr_session._memory_clear_for_tests()
  37. sid, _short = wx_qr_session.create_session(ttl_sec=60)
  38. with patch("app.api.mini_auth.code2session", return_value={"openid": "oid1", "unionid": ""}), \
  39. patch("app.api.mini_auth.get_phone_number", return_value="13800138000"), \
  40. patch("app.api.mini_auth.resolve_wechat_login_user", return_value=(fake_user, None, None)), \
  41. patch("app.api.mini_auth.issue_tokens_for_user", new=AsyncMock(return_value=tokens)):
  42. r = client.post(
  43. "/api/mini/auth/web-qr-confirm",
  44. json={"sessionId": sid, "loginCode": "lc", "phoneCode": "pc"},
  45. )
  46. assert r.status_code == 200
  47. body = r.json()
  48. assert body.get("code") == 200
  49. assert body["data"].get("ok") is True
  50. assert "token" not in (body.get("data") or {})
  51. consumed = wx_qr_session.consume_success(sid)
  52. assert consumed and consumed["token"] == "access"