test(宿主): 使用内置 Lua 解耦业务插件文件
将暂存事件与 HTTP 回调测试改为内置 Lua 源码,在临时目录生成插件;覆盖 HTTP 回调放行、拒绝和非成功状态。配置测试自行生成配置和插件,不再读取项目业务配置与模型目录。 在不包含业务 plugins、config.yaml 和模型目录的隔离目录中执行全量测试:132 项通过,1 项因缺少 LibreOffice 跳过。Ruff 静态检查、改动测试格式检查和差异检查通过。
This commit is contained in:
1 parent
8ad4b29e4c
commit
1b48d0146c
3 files changed
+80
-20
No files matched your search
@@ -95,4 +95,6 @@ Lua 标准库的文件、进程、模块加载、动态代码加载及 Python
|
||||
git diff --check
|
||||
```
|
||||
|
||||
宿主测试将 Lua 源码内置在用例中,运行时写入测试临时目录以验证实际加载流程;配置测试也自行生成配置,不依赖项目的业务 `plugins/`、`config.yaml` 或模型目录。
|
||||
|
||||
测试使用模拟 Agent,并包含真实 Uvicorn/TCP 流式接收、并发满载和客户端断开检查。网络授权测试验证 DNS 地址、白名单、TLS 默认设置及禁止代理/自动重定向;不会连接真实审核供应商、模型或 MCP。实际部署仍需使用甲方接口执行连通性验收。
|
||||
+13
-5
@@ -1,5 +1,3 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
@@ -7,10 +5,20 @@ from middleware.config import NetworkRule, PluginConfig, PluginMatch, Settings,
|
||||
|
||||
|
||||
def test_configuration_and_paths(tmp_path, monkeypatch):
|
||||
config_dir = tmp_path / "configuration"
|
||||
plugin = config_dir / "plugins" / "inline.lua"
|
||||
plugin.parent.mkdir(parents=True)
|
||||
plugin.write_text("return {}", encoding="utf-8")
|
||||
config = config_dir / "config.yaml"
|
||||
config.write_text(
|
||||
"upstream: http://agent:8000\nplugins:\n - id: inline\n file: plugins/inline.lua\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
(tmp_path / "models" / "guard_model").mkdir(parents=True)
|
||||
settings = load_settings(Path(__file__).parents[1] / "config.yaml")
|
||||
assert settings.plugins[0].file.is_absolute()
|
||||
|
||||
settings = load_settings(config)
|
||||
|
||||
assert settings.plugins[0].file == plugin.resolve()
|
||||
assert settings.limits.max_sessions == 4
|
||||
|
||||
|
||||
|
||||
+65
-15
@@ -1,5 +1,5 @@
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -234,14 +234,25 @@ async def test_close_failure_does_not_skip_other_plugins(tmp_path, caplog):
|
||||
assert "raw-secret" not in caplog.text
|
||||
|
||||
|
||||
async def test_example_redacts_cross_event_phone(tmp_path):
|
||||
source = (Path(__file__).parents[1] / "plugins/stream_redact.lua").read_text(encoding="utf-8")
|
||||
async def test_buffered_json_events_are_rewritten_on_end(tmp_path):
|
||||
source = """
|
||||
local parts={}
|
||||
return {
|
||||
on_event=function(ctx,event)
|
||||
parts[#parts+1]=host.json.decode(event.data).data.content
|
||||
return {action='hold'}
|
||||
end,
|
||||
on_end=function(ctx)
|
||||
return {action='replace',events={{
|
||||
data=host.json.encode({data={content=table.concat(parts),count=#parts}})
|
||||
}}}
|
||||
end,
|
||||
}
|
||||
"""
|
||||
manager = manager_for(tmp_path, [source])
|
||||
session = await manager.open(path="/chat/stream")
|
||||
try:
|
||||
for content in ["号码138", "1234", "5678"]:
|
||||
import json
|
||||
|
||||
for content in ["第一段", "中间段", "结束"]:
|
||||
assert (
|
||||
await session.apply(
|
||||
"on_event",
|
||||
@@ -253,8 +264,10 @@ async def test_example_redacts_cross_event_phone(tmp_path):
|
||||
== []
|
||||
)
|
||||
results = await session.end()
|
||||
text = "".join(json.loads(e["data"])["data"]["content"] for e in results)
|
||||
assert text == "号码***********"
|
||||
assert len(results) == 1
|
||||
assert json.loads(results[0]["data"]) == {
|
||||
"data": {"content": "第一段中间段结束", "count": 3}
|
||||
}
|
||||
finally:
|
||||
await session.aclose()
|
||||
|
||||
@@ -322,13 +335,40 @@ async def test_network_denial_and_cancellation_through_ipc(tmp_path):
|
||||
assert not session.process.is_alive()
|
||||
|
||||
|
||||
async def test_network_example_uses_configuration_and_http_result(tmp_path):
|
||||
@pytest.mark.parametrize(
|
||||
("status", "body", "allowed"),
|
||||
[
|
||||
(200, '{"allow":true}', True),
|
||||
(200, '{"allow":false}', False),
|
||||
(503, '{"allow":true}', False),
|
||||
],
|
||||
)
|
||||
async def test_http_callback_uses_plugin_configuration_and_result(tmp_path, status, body, allowed):
|
||||
from middleware.config import NetworkPolicy, NetworkRule
|
||||
|
||||
source = Path(__file__).parents[1] / "plugins/network_review.lua"
|
||||
source = """
|
||||
local settings
|
||||
return {
|
||||
init=function(ctx,config) settings=config end,
|
||||
on_request=function(ctx,request)
|
||||
local response=host.http.request({
|
||||
url=settings.url,
|
||||
method='POST',
|
||||
headers={['content-type']='application/json'},
|
||||
body=request.body,
|
||||
})
|
||||
if response.status ~= 200 or host.json.decode(response.body).allow ~= true then
|
||||
return {action='block'}
|
||||
end
|
||||
return {action='pass'}
|
||||
end,
|
||||
}
|
||||
"""
|
||||
file = tmp_path / "http_callback.lua"
|
||||
file.write_text(source, encoding="utf-8")
|
||||
plugin = PluginConfig(
|
||||
id="review",
|
||||
file=source,
|
||||
file=file,
|
||||
config={"url": "https://review.example.com/check"},
|
||||
network=NetworkPolicy(allow=[NetworkRule(domain="review.example.com")]),
|
||||
)
|
||||
@@ -339,15 +379,25 @@ async def test_network_example_uses_configuration_and_http_result(tmp_path):
|
||||
async def request(self, policy, request, maximum):
|
||||
calls.append(request)
|
||||
assert policy.allow[0].domain == "review.example.com"
|
||||
return {"status": 200, "headers": {}, "body": '{"allow":true}'}
|
||||
return {"status": status, "headers": {}, "body": body}
|
||||
|
||||
manager.broker = RecordingBroker()
|
||||
session = await manager.open(path="/chat/stream")
|
||||
try:
|
||||
original = {"body": '{"message":"test"}'}
|
||||
assert await session.apply("on_request", original) == [original]
|
||||
assert calls[0]["url"] == "https://review.example.com/check"
|
||||
assert calls[0]["body"] == original["body"]
|
||||
if allowed:
|
||||
assert await session.apply("on_request", original) == [original]
|
||||
else:
|
||||
with pytest.raises(PolicyBlocked):
|
||||
await session.apply("on_request", original)
|
||||
assert calls == [
|
||||
{
|
||||
"url": "https://review.example.com/check",
|
||||
"method": "POST",
|
||||
"headers": {"content-type": "application/json"},
|
||||
"body": original["body"],
|
||||
}
|
||||
]
|
||||
finally:
|
||||
await session.aclose()
|
||||
|
||||
|
||||
Reference in new issue
Block a user