feat(avatar): add BOXIM chat takeover
This commit is contained in:
@@ -1,134 +1,118 @@
|
||||
"""Tests for the Box IM client (Netease Yunxin gateway wrapper)."""
|
||||
import pytest
|
||||
"""Contract tests for the self-hosted BOXIM client."""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from services.boxim_client import BoxIMClient, BoxIMError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config():
|
||||
def config():
|
||||
return {
|
||||
"HUIHUI_IM_BASE_URL": "http://192.168.1.200:60040",
|
||||
"HUIHUI_PLATFORM_BASE_URL": "https://open.example/api",
|
||||
"BOXIM_API_BASE_URL": "https://im.example/api",
|
||||
"HUIHUI_APP_ID": "test_app",
|
||||
"HUIHUI_ACCESS_ID": "test_access",
|
||||
"HUIHUI_ACCESS_SECRET": "test_secret",
|
||||
}
|
||||
|
||||
|
||||
def _make_mock_response(json_data: dict):
|
||||
"""Create a properly configured mock for httpx.Response."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.json.return_value = json_data
|
||||
return mock_response
|
||||
def _response(payload: dict, status_code: int = 200):
|
||||
response = MagicMock()
|
||||
response.status_code = status_code
|
||||
response.json.return_value = payload
|
||||
return response
|
||||
|
||||
|
||||
def _patch_httpx_client(json_data: dict):
|
||||
"""Patch httpx.AsyncClient so that `async with httpx.AsyncClient() as c: await c.post(...)` returns json_data."""
|
||||
mock_client = AsyncMock()
|
||||
mock_client.post.return_value = _make_mock_response(json_data)
|
||||
|
||||
mock_cm = AsyncMock()
|
||||
mock_cm.__aenter__.return_value = mock_client
|
||||
mock_cm.__aexit__.return_value = None
|
||||
|
||||
return patch("httpx.AsyncClient", return_value=mock_cm)
|
||||
def _client_patch(*, post_payload=None, request_payload=None, status_code=200):
|
||||
client = AsyncMock()
|
||||
if post_payload is not None:
|
||||
client.post.return_value = _response(post_payload, status_code)
|
||||
if request_payload is not None:
|
||||
client.request.return_value = _response(request_payload, status_code)
|
||||
context = AsyncMock()
|
||||
context.__aenter__.return_value = client
|
||||
context.__aexit__.return_value = None
|
||||
return patch("services.boxim_client.httpx.AsyncClient", return_value=context), client
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_credentials(mock_config):
|
||||
"""get_credentials should return accid and token from the gateway response."""
|
||||
with _patch_httpx_client({"code": 200, "data": {"accid": "user123", "token": "tok_xyz"}}):
|
||||
from services.boxim_client import BoxIMClient
|
||||
async def test_exchange_access_token_uses_huihui_bearer_and_signed_form(config):
|
||||
mocked, client = _client_patch(
|
||||
post_payload={"code": 0, "data": {"accessToken": "box-token", "accessTokenExpiresIn": 3600}}
|
||||
)
|
||||
with mocked:
|
||||
result = await BoxIMClient(config).exchange_access_token("huihui-token")
|
||||
|
||||
client = BoxIMClient(mock_config)
|
||||
result = await client.get_credentials("user123")
|
||||
|
||||
assert result["accid"] == "user123"
|
||||
assert result["token"] == "tok_xyz"
|
||||
assert result["accessToken"] == "box-token"
|
||||
call = client.post.await_args
|
||||
assert call.args[0] == "https://open.example/api/im/box/netease"
|
||||
assert call.kwargs["headers"]["Authorization"] == "Bearer huihui-token"
|
||||
assert call.kwargs["data"]["appId"] == "test_app"
|
||||
assert len(call.kwargs["data"]["signature"]) == 32
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_p2p_message_success(mock_config):
|
||||
"""send_p2p_message should return True when the gateway responds with code 200."""
|
||||
with _patch_httpx_client({"code": 200}):
|
||||
from services.boxim_client import BoxIMClient
|
||||
async def test_get_self_and_incremental_private_messages_use_boxim_header(config):
|
||||
client_instance = BoxIMClient(config)
|
||||
mocked, client = _client_patch(
|
||||
request_payload={"code": 200, "data": {"id": 42, "nickName": "Owner"}}
|
||||
)
|
||||
with mocked:
|
||||
profile = await client_instance.get_self("box-token")
|
||||
assert profile["id"] == 42
|
||||
assert client.request.await_args.kwargs["headers"] == {"accessToken": "box-token"}
|
||||
|
||||
client = BoxIMClient(mock_config)
|
||||
result = await client.send_p2p_message("owner_acc", "target_acc", "Hello")
|
||||
|
||||
assert result is True
|
||||
mocked, client = _client_patch(
|
||||
request_payload={"code": 200, "data": [{"id": 101, "sendId": 7, "recvId": 42}]}
|
||||
)
|
||||
with mocked:
|
||||
messages = await client_instance.fetch_private_messages("box-token", "100")
|
||||
assert messages[0]["id"] == 101
|
||||
assert client.request.await_args.kwargs["params"] == {"minId": "100"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_p2p_message_failure(mock_config):
|
||||
"""send_p2p_message should return False when the gateway responds with a non-200 code."""
|
||||
with _patch_httpx_client({"code": 500, "message": "error"}):
|
||||
from services.boxim_client import BoxIMClient
|
||||
async def test_send_private_message_matches_boxim_payload(config):
|
||||
mocked, client = _client_patch(
|
||||
request_payload={"code": 200, "data": {"id": 88, "localId": 12345}}
|
||||
)
|
||||
with mocked:
|
||||
result = await BoxIMClient(config).send_private_message(
|
||||
"box-token", "77", "你好", local_id="12345"
|
||||
)
|
||||
|
||||
client = BoxIMClient(mock_config)
|
||||
result = await client.send_p2p_message("owner_acc", "target_acc", "Hello")
|
||||
|
||||
assert result is False
|
||||
assert result["id"] == 88
|
||||
call = client.request.await_args
|
||||
assert call.args[:2] == ("POST", "https://im.example/api/message/private/send")
|
||||
assert call.kwargs["json"] == {
|
||||
"localId": 12345,
|
||||
"recvId": 77,
|
||||
"content": "你好",
|
||||
"type": 0,
|
||||
"receipt": False,
|
||||
"atUserIds": [],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_credentials_returns_none_on_error(mock_config):
|
||||
"""get_credentials should return None when the gateway responds with an error code."""
|
||||
with _patch_httpx_client({"code": 500, "message": "user not found"}):
|
||||
from services.boxim_client import BoxIMClient
|
||||
|
||||
client = BoxIMClient(mock_config)
|
||||
result = await client.get_credentials("nonexistent")
|
||||
|
||||
assert result is None
|
||||
async def test_boxim_auth_error_is_explicit(config):
|
||||
mocked, _ = _client_patch(
|
||||
request_payload={"code": 400, "message": "未登录"}, status_code=200
|
||||
)
|
||||
with mocked, pytest.raises(BoxIMError) as exc_info:
|
||||
await BoxIMClient(config).get_self("expired")
|
||||
assert exc_info.value.auth_error is True
|
||||
|
||||
|
||||
def test_build_sign_params_contains_required_fields(mock_config):
|
||||
"""_build_sign_params should produce appId, accessId, nonce, timestamp, signature, signType, signVersion."""
|
||||
from services.boxim_client import BoxIMClient
|
||||
|
||||
client = BoxIMClient(mock_config)
|
||||
params = client._build_sign_params({"userId": "u1"})
|
||||
|
||||
assert "appId" in params
|
||||
assert "accessId" in params
|
||||
assert "nonce" in params
|
||||
assert "timestamp" in params
|
||||
assert "signature" in params
|
||||
def test_sign_params_include_production_required_fields(config):
|
||||
params = BoxIMClient(config)._build_sign_params()
|
||||
assert params["appId"] == "test_app"
|
||||
assert params["accessId"] == "test_access"
|
||||
assert params["signType"] == "MD5"
|
||||
assert params["signVersion"] == "1.0"
|
||||
assert len(params["nonce"]) == 12
|
||||
|
||||
|
||||
def test_build_sign_params_excludes_signature_and_accessSecret_from_signing_string(mock_config):
|
||||
"""signature and accessSecret must be excluded from the signing string to match news_service.py."""
|
||||
from services.boxim_client import BoxIMClient
|
||||
|
||||
client = BoxIMClient(mock_config)
|
||||
|
||||
# Pass params that already contain a stale "signature" value
|
||||
params_with_stale_sig = client._build_sign_params({
|
||||
"userId": "u1",
|
||||
"signature": "OLD_STALE_SIG",
|
||||
})
|
||||
|
||||
# The returned signature must be freshly computed (32-char MD5 uppercase),
|
||||
# NOT the stale value we passed in.
|
||||
assert params_with_stale_sig["signature"] != "OLD_STALE_SIG"
|
||||
assert len(params_with_stale_sig["signature"]) == 32
|
||||
|
||||
# Calling with the same extra params but no stale signature should also work.
|
||||
params_clean = client._build_sign_params({"userId": "u1"})
|
||||
assert len(params_clean["signature"]) == 32
|
||||
|
||||
|
||||
def test_build_sign_params_signature_is_deterministic(mock_config):
|
||||
"""Same inputs should produce valid MD5 signatures."""
|
||||
from services.boxim_client import BoxIMClient
|
||||
|
||||
client = BoxIMClient(mock_config)
|
||||
|
||||
params1 = client._build_sign_params({"userId": "u1"})
|
||||
params2 = client._build_sign_params({"userId": "u1"})
|
||||
|
||||
assert params1["signature"] is not None
|
||||
assert params2["signature"] is not None
|
||||
assert len(params1["signature"]) == 32 # MD5 hex length
|
||||
assert len(params["timestamp"]) == 14
|
||||
assert len(params["signature"]) == 32
|
||||
assert "accessSecret" not in params
|
||||
|
||||
Reference in New Issue
Block a user