Files
agent-safe-middleware/tests/test_scenario_runner.py
starrrLight fa937803c7 fix(场景): 默认输出插件运行日志
场景命令直接输出插件消息并保留各日志级别,详细模式继续显示生命周期。保持标准输出为场景结果 JSON,补充默认和详细模式的命令行回归测试并简化文档。
2026-10-16 14:40:45 +08:00

210 lines
7.3 KiB
Python

import json
import subprocess
import sys
import pytest
from middleware.scenario_runner import ScenarioError, build_request, load_scenarios, run_scenarios
def write_config(tmp_path):
plugin = tmp_path / "marker.lua"
plugin.write_text(
"return {on_request=function(ctx,r) r.headers['x-marker']='matched'; "
"return {action='replace',value=r} end}",
encoding="utf-8",
)
config = tmp_path / "config.yaml"
config.write_text(
"upstream: http://unused\nplugins:\n"
" - id: marker\n file: marker.lua\n match:\n paths: [/stream]\n",
encoding="utf-8",
)
return config
def write_scenarios(tmp_path):
fixture = tmp_path / "sample.txt"
fixture.write_text("附件正文", encoding="utf-8")
scenario = tmp_path / "scenarios.json"
scenario.write_text(
json.dumps(
{
"scenarios": [
{
"id": "sse",
"kind": "sse",
"path": "/stream?token=a%2Fb",
"headers": {"content-type": "application/json"},
"body": {"message": "hello"},
"response": {
"status": 200,
"headers": {"content-type": "text/event-stream"},
"events": [
{"event": "run_started", "data": {"data": {"ok": True}}},
{"event": "run_completed", "data": {"data": {"ok": True}}},
],
},
"expect": {
"status": 200,
"events": ["run_started", "run_completed"],
"upstream_path": "/stream?token=a%2Fb",
},
},
{
"id": "post",
"kind": "post",
"path": "/other/",
"headers": {"content-type": "application/json"},
"body": {"hello": "普通 POST"},
"response": {"status": 201, "body": {"created": True}},
"expect": {
"status": 201,
"body": {"created": True},
"upstream_path": "/other/",
},
},
{
"id": "file",
"kind": "file",
"path": "/upload?source=test",
"file": {"path": "sample.txt", "field": "file", "mime": "text/plain"},
"response": {"status": 200, "body": {"stored": True}},
"expect": {
"status": 200,
"body": {"stored": True},
"upstream_path": "/upload?source=test",
"file_forwarded": True,
},
},
]
},
ensure_ascii=False,
),
encoding="utf-8",
)
return scenario
async def test_runner_executes_sse_post_and_file_with_real_matching(tmp_path, capsys):
reports = await run_scenarios(write_config(tmp_path), write_scenarios(tmp_path))
assert [report["id"] for report in reports] == ["sse", "post", "file"]
assert reports[0]["plugins"] == ["marker"]
assert reports[1]["plugins"] == []
assert reports[2]["plugins"] == []
assert reports[2]["upstream_path"] == "/upload?source=test"
assert reports[2]["assertions"]["file_forwarded"] is True
assert len(capsys.readouterr().out.splitlines()) == 3
@pytest.mark.parametrize(
("hook", "expected"),
[
("return {action='block'}", r"status 403 != 200 \(PolicyBlocked\)"),
("error('private-plugin-message')", r"status 502 != 200 \(MiddlewareFailure\)"),
],
)
async def test_sse_rejection_reports_http_status_before_decoding(tmp_path, hook, expected):
config = write_config(tmp_path)
(tmp_path / "marker.lua").write_text(
f"return {{on_request=function(ctx,r) {hook} end}}", encoding="utf-8"
)
with pytest.raises(ScenarioError, match=expected) as failure:
await run_scenarios(config, write_scenarios(tmp_path))
assert "scenario sse:" in str(failure.value)
assert "private-plugin-message" not in str(failure.value)
def test_scenario_schema_and_file_path_safety(tmp_path):
scenario = tmp_path / "scenario.json"
scenario.write_text(json.dumps({"scenarios": []}), encoding="utf-8")
with pytest.raises(ScenarioError, match="must not be empty"):
load_scenarios(scenario)
scenario.write_text(
json.dumps(
{
"scenarios": [
{
"id": "fragment",
"kind": "post",
"path": "/upload#fragment",
"response": {"body": {}},
}
]
}
),
encoding="utf-8",
)
with pytest.raises(ScenarioError, match="fragment"):
load_scenarios(scenario)
with pytest.raises(ScenarioError, match="below the scenario directory"):
build_request(
{
"id": "escape",
"kind": "file",
"path": "/upload",
"file": {"path": "../secret.txt"},
},
tmp_path,
)
def test_file_request_generates_multipart_headers(tmp_path):
source = tmp_path / "input.txt"
source.write_text("内容", encoding="utf-8")
parsed, headers, body, info = build_request(
{
"id": "file",
"kind": "file",
"path": "/upload",
"headers": {"x-test": "yes"},
"file": {"path": "input.txt", "field": "attachment"},
},
tmp_path,
)
assert parsed.path == "/upload"
assert headers["x-test"] == "yes"
assert headers["content-type"].startswith("multipart/form-data; boundary=")
assert info["file_bytes"] in body
@pytest.mark.parametrize("verbose", [False, True])
def test_cli_displays_plugin_logs_without_verbose(tmp_path, verbose):
config = write_config(tmp_path)
(tmp_path / "marker.lua").write_text(
"return {on_request=function() host.log.info('测试插件正文'); "
"host.log.warning('测试警告'); host.log.error('测试错误') end}",
encoding="utf-8",
)
command = [
sys.executable,
"-X",
"utf8",
"-m",
"middleware.scenario_runner",
"--config",
str(config),
"--scenarios",
str(write_scenarios(tmp_path)),
]
if verbose:
command.append("--verbose")
result = subprocess.run(command, capture_output=True, encoding="utf-8", timeout=30)
assert result.returncode == 0, result.stderr
assert 'message="测试插件正文"' in result.stderr
assert 'message="测试警告"' in result.stderr
assert 'message="测试错误"' in result.stderr
assert "plugin=marker" in result.stderr
assert ("plugin_hook " in result.stderr) is verbose
assert [json.loads(line)["id"] for line in result.stdout.splitlines()] == [
"sse",
"post",
"file",
]