test_db_errors.py
2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""数据库相关的失败路径,全部是实跑时真炸出来过的问题。
共同的要求:**失败必须带可操作的指引**,而不是把底层异常原样吐出去。
"""
from __future__ import annotations
import httpx
import pytest
from sqlalchemy.exc import ProgrammingError
from mcp_hive.core.config import credentials as creds
from mcp_hive.core.errors import ConfigError
from mcp_hive.core.http.client import decode_body
def _missing_table_error() -> ProgrammingError:
"""构造一个和 MySQL 真实报法一致的「表不存在」异常。"""
return ProgrammingError(
"SELECT base_url, app_key, secret, enabled FROM mcph_service_config WHERE service_key = %s",
{},
Exception("(1146, \"Table 'ai_multi_agentic_dev.mcph_service_config' doesn't exist\")"),
)
# ------------------------------------------------------------ 表没建时的报错
def test_missing_table_tells_you_to_run_db_init():
"""回归用:表没建时,AI Agent 原先收到的是一坨 pymysql 异常 + 一行 SQL,
既看不出该干什么,又把内部库名表名漏了出去。"""
with pytest.raises(ConfigError) as exc, creds._translate_db_errors("读取上游凭证"):
raise _missing_table_error()
message = str(exc.value)
assert "mcp-hive-admin db init" in message, "必须告诉用户该执行什么"
assert "pymysql" not in message
assert "SELECT" not in message
assert "mcph_service_config" not in message, "不要把内部表名漏给调用方"
def test_other_db_errors_do_not_claim_the_table_is_missing():
"""连不上库和表没建是两回事,指引不能串。"""
with pytest.raises(ConfigError) as exc, creds._translate_db_errors("读取上游凭证"):
raise ProgrammingError("SELECT 1", {}, Exception("Access denied for user"))
assert "db init" not in str(exc.value)
assert "数据库不可用" in str(exc.value)
def test_unconfigured_db_points_at_the_env_file():
with pytest.raises(ConfigError, match=r"\.env"):
creds._require_db("读取上游凭证")
# ---------------------------------------------------------------- 响应体编码
def test_upstream_chinese_error_is_decoded_as_utf8():
"""回归用:上游返回不带 charset 的 text/plain,httpx 猜编码会把
「缺少必要参数」解成带代理码点的乱码 —— 而这句话是当前联调阻塞项唯一的线索。"""
response = httpx.Response(
400,
content="缺少必要参数".encode(),
headers={"content-type": "text/plain"}, # 故意不带 charset
)
assert decode_body(response) == "缺少必要参数"
def test_undecodable_bytes_degrade_instead_of_raising():
"""解不出来也不能抛异常,否则错误处理路径自己先炸了。"""
response = httpx.Response(400, content=b"\xff\xfe bad bytes")
assert isinstance(decode_body(response), str)