485 lines
17 KiB
Python
485 lines
17 KiB
Python
"""Phase 1 集成测试:启动真实 uvicorn 服务器(随机端口),模拟设备 + 前端接入验证。"""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
import pytest_asyncio
|
|
import websockets
|
|
from httpx import AsyncClient
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent.parent))
|
|
os.environ.setdefault("DB_PATH", str(Path(tempfile.gettempdir()) / f"cp_agent_test_{uuid.uuid4().hex[:8]}.db"))
|
|
|
|
import uvicorn # noqa: E402
|
|
|
|
from main import app # noqa: E402
|
|
from main import validate_download_relative_path # noqa: E402
|
|
from core.device import redact_transfer_payload # noqa: E402
|
|
|
|
|
|
class Server:
|
|
def __init__(self):
|
|
self.port = 18700 + (uuid.uuid4().int % 1000)
|
|
config = uvicorn.Config(app, host="127.0.0.1", port=self.port, log_level="warning")
|
|
self.server = uvicorn.Server(config)
|
|
self.task: asyncio.Task | None = None
|
|
|
|
@property
|
|
def device_ws(self) -> str:
|
|
return f"ws://127.0.0.1:{self.port}/ws/device"
|
|
|
|
@property
|
|
def ui_ws(self) -> str:
|
|
return f"ws://127.0.0.1:{self.port}/ws/ui"
|
|
|
|
@property
|
|
def http_url(self) -> str:
|
|
return f"http://127.0.0.1:{self.port}"
|
|
|
|
async def start(self):
|
|
self.task = asyncio.get_running_loop().create_task(self.server.serve())
|
|
for _ in range(100):
|
|
if self.server.started:
|
|
return
|
|
await asyncio.sleep(0.05)
|
|
raise RuntimeError("服务器启动超时")
|
|
|
|
async def stop(self):
|
|
self.server.should_exit = True
|
|
if self.task is not None:
|
|
await asyncio.wait_for(self.task, timeout=10)
|
|
|
|
|
|
@pytest_asyncio.fixture(scope="session")
|
|
async def server():
|
|
s = Server()
|
|
await s.start()
|
|
yield s
|
|
await s.stop()
|
|
|
|
|
|
class MockDevice:
|
|
def __init__(self, server: Server, device_id: str, name: str = "Mock Phone"):
|
|
self.server = server
|
|
self.device_id = device_id
|
|
self.name = name
|
|
|
|
async def connect(self):
|
|
ws = await websockets.connect(self.server.device_ws)
|
|
await ws.send(json.dumps({
|
|
"type": "register",
|
|
"deviceId": self.device_id,
|
|
"deviceName": self.name,
|
|
"osVersion": "Android 14",
|
|
"sdkVersion": 34,
|
|
"token": "",
|
|
}))
|
|
# 等待服务器完成注册处理
|
|
await asyncio.sleep(0.3)
|
|
return ws
|
|
|
|
async def serve_command(self, ws, handler=None):
|
|
"""接收一条 command 并按 handler 回复。"""
|
|
raw = await asyncio.wait_for(ws.recv(), timeout=5)
|
|
msg = json.loads(raw)
|
|
assert msg["type"] == "command"
|
|
if handler:
|
|
result = handler(msg)
|
|
payload = await result if hasattr(result, "__await__") else result
|
|
else:
|
|
payload = {"exitCode": 0, "output": "ok"}
|
|
await ws.send(json.dumps({
|
|
"id": msg["id"], "type": "response", "action": msg["action"],
|
|
"status": "success", "payload": payload,
|
|
}))
|
|
return msg
|
|
|
|
|
|
class UiClient:
|
|
def __init__(self, server: Server, ws):
|
|
self.ws = ws
|
|
self.seq = 0
|
|
|
|
async def request(self, action: str, payload: dict, device_id: str = "", timeout: float = 10):
|
|
self.seq += 1
|
|
rid = f"test-{self.seq}"
|
|
await self.ws.send(json.dumps({
|
|
"id": rid, "type": "command", "action": action,
|
|
"deviceId": device_id, "payload": payload,
|
|
}))
|
|
while True:
|
|
raw = await asyncio.wait_for(self.ws.recv(), timeout=timeout)
|
|
msg = json.loads(raw)
|
|
if msg.get("id") == rid and msg.get("type") == "response":
|
|
return msg
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def ui(server):
|
|
async with websockets.connect(server.ui_ws) as ws:
|
|
raw = await asyncio.wait_for(ws.recv(), timeout=5)
|
|
assert json.loads(raw)["action"] == "device.list"
|
|
yield UiClient(server, ws)
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def http(server):
|
|
async with AsyncClient(base_url=server.http_url) as client:
|
|
yield client
|
|
|
|
|
|
# ---------- 测试 ----------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("logger_name", ["", "cp_agent.integration", "uvicorn", "uvicorn.error", "uvicorn.access"])
|
|
async def test_log_list_returns_server_log_schema(ui, logger_name):
|
|
marker = f"list-marker-{uuid.uuid4().hex}"
|
|
log = logging.getLogger(logger_name)
|
|
expected_message = f"server record {marker}"
|
|
if logger_name == "uvicorn.access":
|
|
# Uvicorn's console access formatter requires its five HTTP arguments.
|
|
log.warning('%s - "%s %s HTTP/%s" %d', "127.0.0.1:12345", "GET", f"/{marker}", "1.1", 200)
|
|
expected_message = f'127.0.0.1:12345 - "GET /{marker} HTTP/1.1" 200'
|
|
else:
|
|
log.warning("server record %s", marker)
|
|
|
|
response = await ui.request("log.list", {})
|
|
|
|
assert response["status"] == "success"
|
|
matching = [entry for entry in response["payload"]["logs"] if marker in entry["message"]]
|
|
assert len(matching) == 1
|
|
entry = matching[0]
|
|
assert set(entry) == {"ts", "level", "logger", "message"}
|
|
assert isinstance(entry["ts"], (int, float))
|
|
assert entry["level"] == "WARNING"
|
|
assert entry["logger"] == (logger_name or "root")
|
|
assert entry["message"] == expected_message
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("from_thread", [False, True])
|
|
async def test_server_log_is_pushed_to_ui(ui, from_thread):
|
|
marker = f"push-marker-{uuid.uuid4().hex}"
|
|
log = logging.getLogger("cp_agent.integration")
|
|
if from_thread:
|
|
await asyncio.to_thread(log.error, "server record %s", marker)
|
|
else:
|
|
log.error("server record %s", marker)
|
|
|
|
async def receive_log():
|
|
while True:
|
|
message = json.loads(await ui.ws.recv())
|
|
if message.get("action") == "event.log" and marker in message["payload"]["message"]:
|
|
return message
|
|
|
|
message = await asyncio.wait_for(receive_log(), timeout=2)
|
|
assert message["type"] == "event"
|
|
entry = message["payload"]
|
|
assert set(entry) == {"ts", "level", "logger", "message"}
|
|
assert isinstance(entry["ts"], (int, float))
|
|
assert entry["level"] == "ERROR"
|
|
assert entry["logger"] == "cp_agent.integration"
|
|
assert entry["message"] == f"server record {marker}"
|
|
response = await ui.request("log.list", {})
|
|
assert [item for item in response["payload"]["logs"] if marker in item["message"]] == [entry]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ui_reply_does_not_create_synthetic_log(ui):
|
|
marker = f"unknown.action.{uuid.uuid4().hex}"
|
|
response = await ui.request(marker, {}, "not-connected")
|
|
assert response["status"] == "error"
|
|
|
|
response = await ui.request("log.list", {})
|
|
assert not any(
|
|
marker in entry["message"] or entry["level"] == "command"
|
|
for entry in response["payload"]["logs"]
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("offline_delay", [0, 0.5])
|
|
async def test_device_logs_are_real_hub_records(server, ui, caplog, monkeypatch, offline_delay):
|
|
import main
|
|
|
|
device_id = f"log-device-{uuid.uuid4().hex}"
|
|
offline_done = asyncio.Event()
|
|
unregister = main.hub.unregister_device
|
|
|
|
async def delayed_unregister(target_id):
|
|
if target_id != device_id:
|
|
return await unregister(target_id)
|
|
try:
|
|
# Reproduce a slow disconnect without relying on machine load.
|
|
await asyncio.sleep(offline_delay)
|
|
await unregister(target_id)
|
|
finally:
|
|
offline_done.set()
|
|
|
|
monkeypatch.setattr(main.hub, "unregister_device", delayed_unregister)
|
|
with caplog.at_level(logging.INFO, logger="core.hub"):
|
|
ws = await MockDevice(server, device_id).connect()
|
|
try:
|
|
await ws.close()
|
|
|
|
async def wait_for_offline_log():
|
|
while not any(
|
|
record.name == "core.hub"
|
|
and record.getMessage() == f"设备离线: {device_id}"
|
|
for record in caplog.records
|
|
):
|
|
await asyncio.sleep(0.01)
|
|
|
|
await asyncio.wait_for(wait_for_offline_log(), timeout=2)
|
|
response = await ui.request("log.list", {})
|
|
entries = response["payload"]["logs"]
|
|
matching = [entry for entry in entries if device_id in entry["message"]]
|
|
assert len(matching) == 2
|
|
assert all(entry["logger"] == "core.hub" and entry["level"] == "INFO" for entry in matching)
|
|
assert all(entry["level"] != "device" for entry in entries)
|
|
finally:
|
|
await ws.close()
|
|
await asyncio.wait_for(offline_done.wait(), timeout=2)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_index_page(http):
|
|
resp = await http.get("/")
|
|
assert resp.status_code == 200
|
|
assert "CP Bridge · ATX 设备列表平台" in resp.text
|
|
|
|
|
|
@pytest.mark.parametrize("path,expected", [
|
|
("", ""),
|
|
("notes/a.txt", "notes/a.txt"),
|
|
("中文 文件.apk", "中文 文件.apk"),
|
|
])
|
|
def test_download_path_accepts_only_relative_paths_inside_root(path, expected):
|
|
assert validate_download_relative_path(path) == expected
|
|
|
|
|
|
@pytest.mark.parametrize("path", [
|
|
"../secret", "notes/../../secret", "/sdcard/Download/a.txt", "\\sdcard\\Download\\a.txt",
|
|
"notes\\a.txt", "./a.txt", "notes//a.txt", "a\x00b", "a\nb",
|
|
])
|
|
def test_download_path_rejects_escape_and_ambiguous_segments(path):
|
|
with pytest.raises(ValueError):
|
|
validate_download_relative_path(path)
|
|
|
|
|
|
def test_transfer_payloads_are_redacted_from_command_audit():
|
|
outgoing = redact_transfer_payload("file.upload.chunk", {
|
|
"transferId": "t1", "offset": 0, "data": "private-file-content",
|
|
})
|
|
incoming = redact_transfer_payload("file.download.chunk", {
|
|
"transferId": "t1", "offset": 0, "data": "private-file-content",
|
|
})
|
|
assert "private-file-content" not in json.dumps(outgoing)
|
|
assert "private-file-content" not in json.dumps(incoming)
|
|
assert outgoing["encodedLength"] == len("private-file-content")
|
|
assert incoming["encodedLength"] == len("private-file-content")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_register_and_device_list(server, ui):
|
|
device = MockDevice(server, "test-device-001", "Pixel Mock")
|
|
ws = await device.connect()
|
|
try:
|
|
await asyncio.sleep(0.3)
|
|
resp = await ui.request("device.list", {})
|
|
assert resp["status"] == "success"
|
|
devices = resp["payload"]["devices"]
|
|
target = [d for d in devices if d["deviceId"] == "test-device-001"]
|
|
assert target and target[0]["online"] is True
|
|
assert target[0]["deviceName"] == "Pixel Mock"
|
|
finally:
|
|
await ws.close()
|
|
await asyncio.sleep(0.3)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_shell_exec_roundtrip(server, ui):
|
|
device = MockDevice(server, "test-device-002")
|
|
ws = await device.connect()
|
|
try:
|
|
async def device_loop():
|
|
while True:
|
|
try:
|
|
await device.serve_command(ws, handler=lambda m: {"exitCode": 0, "output": "hello from device"})
|
|
except asyncio.TimeoutError:
|
|
continue
|
|
except websockets.exceptions.ConnectionClosed:
|
|
return
|
|
|
|
loop_task = asyncio.create_task(device_loop())
|
|
resp = await ui.request("shell.exec", {"cmd": "echo hi", "timeout": 5}, "test-device-002")
|
|
assert resp["status"] == "success"
|
|
assert resp["payload"]["output"] == "hello from device"
|
|
assert resp["payload"]["exitCode"] == 0
|
|
loop_task.cancel()
|
|
finally:
|
|
await ws.close()
|
|
await asyncio.sleep(0.3)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_device_info(server, ui):
|
|
device = MockDevice(server, "test-device-003")
|
|
ws = await device.connect()
|
|
try:
|
|
async def device_loop():
|
|
while True:
|
|
try:
|
|
async def handler(m):
|
|
assert m["action"] == "device.info"
|
|
return {"deviceId": "test-device-003", "battery": 88}
|
|
await device.serve_command(ws, handler=handler)
|
|
except asyncio.TimeoutError:
|
|
continue
|
|
except websockets.exceptions.ConnectionClosed:
|
|
return
|
|
|
|
loop_task = asyncio.create_task(device_loop())
|
|
resp = await ui.request("device.info", {}, "test-device-003")
|
|
assert resp["status"] == "success"
|
|
assert resp["payload"]["battery"] == 88
|
|
loop_task.cancel()
|
|
finally:
|
|
await ws.close()
|
|
await asyncio.sleep(0.3)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_management_actions_forward_to_device(server, ui):
|
|
device = MockDevice(server, "management-device-001")
|
|
ws = await device.connect()
|
|
seen = []
|
|
|
|
async def device_loop():
|
|
for _ in range(2):
|
|
msg = await device.serve_command(ws)
|
|
seen.append(msg)
|
|
|
|
loop_task = asyncio.create_task(device_loop())
|
|
try:
|
|
list_response = await ui.request("file.list", {"path": ""}, device.device_id)
|
|
install_response = await ui.request("app.install", {"path": "demo.apk"}, device.device_id)
|
|
await asyncio.wait_for(loop_task, timeout=5)
|
|
assert list_response["status"] == "success"
|
|
assert install_response["status"] == "success"
|
|
assert [(item["action"], item["payload"]) for item in seen] == [
|
|
("file.list", {"path": ""}),
|
|
("app.install", {"path": "demo.apk"}),
|
|
]
|
|
finally:
|
|
if not loop_task.done():
|
|
loop_task.cancel()
|
|
await ws.close()
|
|
await asyncio.sleep(0.3)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_management_path_rejection_does_not_reach_device(server, ui):
|
|
device = MockDevice(server, "management-device-002")
|
|
ws = await device.connect()
|
|
try:
|
|
response = await ui.request("file.list", {"path": "../outside"}, device.device_id)
|
|
assert response["status"] == "error"
|
|
with pytest.raises(asyncio.TimeoutError):
|
|
await asyncio.wait_for(ws.recv(), timeout=0.3)
|
|
finally:
|
|
await ws.close()
|
|
await asyncio.sleep(0.3)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_command_timeout(server, ui):
|
|
device = MockDevice(server, "test-device-004")
|
|
ws = await device.connect()
|
|
try:
|
|
# 设备收到 command 但不回复
|
|
req_task = asyncio.create_task(
|
|
ui.request("shell.exec", {"cmd": "sleep 999", "timeout": 1}, "test-device-004", timeout=15)
|
|
)
|
|
raw = await asyncio.wait_for(ws.recv(), timeout=5)
|
|
msg = json.loads(raw)
|
|
assert msg["type"] == "command"
|
|
|
|
resp = await req_task
|
|
assert resp["status"] == "error"
|
|
assert resp["payload"]["code"] == 1002 # COMMAND_TIMEOUT
|
|
finally:
|
|
await ws.close()
|
|
await asyncio.sleep(0.3)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_offline_after_disconnect(server, ui):
|
|
device = MockDevice(server, "test-device-005")
|
|
ws = await device.connect()
|
|
await asyncio.sleep(0.2)
|
|
resp = await ui.request("device.list", {})
|
|
assert [d for d in resp["payload"]["devices"] if d["deviceId"] == "test-device-005"][0]["online"] is True
|
|
|
|
await ws.close()
|
|
await asyncio.sleep(0.5)
|
|
|
|
resp = await ui.request("device.list", {})
|
|
assert [d for d in resp["payload"]["devices"] if d["deviceId"] == "test-device-005"][0]["online"] is False
|
|
|
|
# 离线设备下发指令应失败
|
|
resp = await ui.request("shell.exec", {"cmd": "ls"}, "test-device-005")
|
|
assert resp["status"] == "error"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_heartbeat_updates_state(server, ui):
|
|
device = MockDevice(server, "test-device-006")
|
|
ws = await device.connect()
|
|
try:
|
|
await ws.send(json.dumps({
|
|
"id": uuid.uuid4().hex, "type": "event", "action": "event.heartbeat",
|
|
"deviceId": "test-device-006", "payload": {"battery": 42, "cpu": 10},
|
|
}))
|
|
await asyncio.sleep(0.3)
|
|
resp = await ui.request("device.list", {})
|
|
target = [d for d in resp["payload"]["devices"] if d["deviceId"] == "test-device-006"][0]
|
|
assert target["heartbeat"]["battery"] == 42
|
|
finally:
|
|
await ws.close()
|
|
await asyncio.sleep(0.3)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_invalid_register_rejected(server):
|
|
ws = await websockets.connect(server.device_ws)
|
|
try:
|
|
await ws.send(json.dumps({"type": "not-register", "deviceId": "x"}))
|
|
raw = await asyncio.wait_for(ws.recv(), timeout=5)
|
|
resp = json.loads(raw)
|
|
assert resp["status"] == "error"
|
|
assert resp["payload"]["code"] == 1001
|
|
finally:
|
|
await ws.close()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unknown_action(server, ui):
|
|
device = MockDevice(server, "test-device-007")
|
|
ws = await device.connect()
|
|
try:
|
|
resp = await ui.request("bad.action", {}, "test-device-007")
|
|
assert resp["status"] == "error"
|
|
finally:
|
|
await ws.close()
|
|
await asyncio.sleep(0.3)
|