test_wechat_login_silent.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """微信登录:openid 已绑定可无 phoneCode 静默换票。"""
  2. from types import SimpleNamespace
  3. from unittest.mock import AsyncMock, MagicMock, patch
  4. import pytest
  5. from app.services.wechat_login_service import resolve_wechat_login_by_openid_only
  6. def test_resolve_openid_bound_ok_without_phone():
  7. bound = SimpleNamespace(
  8. id="u1",
  9. wx_openid="oid-1",
  10. status="1",
  11. )
  12. db = MagicMock()
  13. with patch(
  14. "app.services.wechat_login_service.user_crud.get_by_wx_openid",
  15. return_value=bound,
  16. ):
  17. user, err, code = resolve_wechat_login_by_openid_only(db, openid="oid-1")
  18. assert err is None and code is None
  19. assert user is bound
  20. def test_resolve_openid_not_bound_asks_phone():
  21. db = MagicMock()
  22. with patch(
  23. "app.services.wechat_login_service.user_crud.get_by_wx_openid",
  24. return_value=None,
  25. ):
  26. user, err, code = resolve_wechat_login_by_openid_only(db, openid="oid-x")
  27. assert user is None
  28. assert code == 400
  29. assert "请授权手机号" in err
  30. def test_resolve_openid_bound_but_disabled():
  31. bound = SimpleNamespace(
  32. id="u2",
  33. wx_openid="oid-2",
  34. status="0",
  35. )
  36. db = MagicMock()
  37. with patch(
  38. "app.services.wechat_login_service.user_crud.get_by_wx_openid",
  39. return_value=bound,
  40. ):
  41. user, err, code = resolve_wechat_login_by_openid_only(db, openid="oid-2")
  42. assert user is None
  43. assert code == 403
  44. assert "停用" in err
  45. @pytest.mark.asyncio
  46. async def test_wechat_login_api_silent_when_openid_bound():
  47. bound = SimpleNamespace(
  48. id="u1",
  49. wx_openid="oid-1",
  50. status="1",
  51. wx_unionid=None,
  52. )
  53. with (
  54. patch(
  55. "app.api.mini_auth.code2session",
  56. return_value={"openid": "oid-1", "unionid": None},
  57. ),
  58. patch(
  59. "app.api.mini_auth.resolve_wechat_login_by_openid_only",
  60. return_value=(bound, None, None),
  61. ) as resolve_silent,
  62. patch(
  63. "app.api.mini_auth.issue_tokens_for_user",
  64. new_callable=AsyncMock,
  65. return_value={"accessToken": "t"},
  66. ),
  67. ):
  68. from app.api.mini_auth import wechat_login
  69. resp = await wechat_login({"loginCode": "lc"}, db=MagicMock())
  70. resolve_silent.assert_called_once()
  71. assert resp["code"] == 200
  72. assert resp["data"]["accessToken"] == "t"