test: real HTTP-over-TCP loopback domain test (#3) #15
No files matched your search
@@ -0,0 +1,48 @@
|
||||
# HTTP-over-TCP loopback 领域测试(issue #3)
|
||||
|
||||
Date: 2026-11-30. Branch: `codex/issue-3-loopback-domain`.
|
||||
Related: `marqdo-ext-http#3`(真实 loopback 领域测试)、`#13`(字节预算)、
|
||||
`marqdo-cli` 通用 TCP round-trip。
|
||||
|
||||
## 1. 交付
|
||||
|
||||
- `tests/loopback.mq.md`:真实消费者工程通过 `@http` 显式 Package 导入,使用
|
||||
CLI 通用资源能力(`resource.open("tcp","127.0.0.1:PORT",["read","write"])`、
|
||||
`resource.read/write/close`)完成**同一程序内两次真实 HTTP/1.1 交换**:
|
||||
GET `/one` 与 POST `/two`,请求由 `http.构建请求字节` 生成,响应由
|
||||
`http.解析响应字节` 解析,正文经 `http.字节文本` 解码(含非 ASCII 中文)。
|
||||
测试文档只读取端口环境变量(显式 `--allow-env HTTP_TEST_PORT`),网络仅
|
||||
`--allow-net 127.0.0.1`。
|
||||
- `scripts/loopback_server.py`:确定性 loopback HTTP 服务器,逐连接读取请求
|
||||
head + Content-Length body,按路径返回固定状态/正文并记录所有请求;
|
||||
测试结束由 runner 校验请求数、方法、路径与正文。
|
||||
- `scripts/run_cases.py`:新增 `kind: loopback` 支持(启动/回收服务器、
|
||||
端口注入、网络/环境 grant、请求记录断言),默认纯解析 case 行为不变。
|
||||
- `tests/cases/loopback.json`:断言 `GET /one → 200 第一个`、
|
||||
`POST /two → 201 第二个` 与请求记录 `method/path/body`。
|
||||
|
||||
## 2. 验证(真实执行,Linux x86_64 / glibc 2.43)
|
||||
|
||||
输入:CLI `3.0.0-rc.6`(candidate `afea4f9`,含通用资源能力)、Bundle
|
||||
`marqdo-stdlib 0.3.0`(tree `sha256:4e47b0ff…`)。
|
||||
|
||||
```text
|
||||
$ MARQDO_BIN=<cli> MARQDO_STDLIB_DIR=<bundle> sh scripts/test.sh
|
||||
PASS http
|
||||
PASS loopback
|
||||
2 cases passed
|
||||
```
|
||||
|
||||
组件 CI 镜像的 CLI 已提供通用 `resource.open/read/write` 与 `env.get`
|
||||
(该 loopback case 不依赖 `document.*`),因此默认 CI 可以直接运行;
|
||||
平台 Woodpecker 结果以 PR 记录为准。
|
||||
|
||||
## 3. 边界 / 未验证
|
||||
|
||||
- 覆盖:真实 TCP、两次请求、非 ASCII、请求/响应字节、请求记录、EOF 读取循环。
|
||||
- chunked/失败路径的纯解析负例继续由既有 `http` case 覆盖;真实 loopback 的
|
||||
超时/连接拒绝负例未加入(资源层错误不可作为 result 分支,属 Host 行为),
|
||||
保持 UNVERIFIED。
|
||||
- 根组合候选固定本提交后,`scripts/acceptance-stdlib.py` 的 explicit-package
|
||||
门禁需在根 PR 复跑(本仓单不冒充根验收)。
|
||||
- 未修改 CLI/Host/其他组件;未新增 Host 请求;未创建 release。
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deterministic loopback HTTP server for ext-http domain tests.
|
||||
|
||||
Accepts exactly N connections (one request each), reads the request head and a
|
||||
Content-Length body, records method/path/headers/body, answers with a fixed
|
||||
HTTP/1.1 response and closes the connection. Prints the ephemeral port on
|
||||
stdout as one line so the test runner can pass it to the program.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import socket
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
RESPONSES = {
|
||||
"/one": ("第一个", 200, "OK"),
|
||||
"/two": ("第二个", 201, "Created"),
|
||||
}
|
||||
|
||||
|
||||
def read_request(conn: socket.socket) -> dict:
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data:
|
||||
chunk = conn.recv(4096)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
head, _, rest = data.partition(b"\r\n\r\n")
|
||||
lines = head.decode("utf-8", errors="replace").split("\r\n")
|
||||
method, path, _ = (lines[0].split(" ") + ["", ""])[:3]
|
||||
headers = {}
|
||||
for line in lines[1:]:
|
||||
if ":" in line:
|
||||
name, value = line.split(":", 1)
|
||||
headers[name.strip().lower()] = value.strip()
|
||||
length = int(headers.get("content-length", "0"))
|
||||
body = rest
|
||||
while len(body) < length:
|
||||
chunk = conn.recv(4096)
|
||||
if not chunk:
|
||||
break
|
||||
body += chunk
|
||||
return {
|
||||
"method": method,
|
||||
"path": path,
|
||||
"headers": headers,
|
||||
"body": body.decode("utf-8", errors="replace"),
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 3:
|
||||
print("usage: loopback_server.py RECORD_PATH REQUEST_COUNT", file=sys.stderr)
|
||||
return 2
|
||||
record_path = Path(sys.argv[1])
|
||||
count = int(sys.argv[2])
|
||||
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
server.bind(("127.0.0.1", 0))
|
||||
server.listen(4)
|
||||
port = server.getsockname()[1]
|
||||
print(port, flush=True)
|
||||
records = []
|
||||
try:
|
||||
for _ in range(count):
|
||||
conn, _ = server.accept()
|
||||
with conn:
|
||||
request = read_request(conn)
|
||||
records.append(request)
|
||||
body, status, reason = RESPONSES.get(
|
||||
request["path"], ("unknown", 404, "Not Found")
|
||||
)
|
||||
payload = body.encode("utf-8")
|
||||
response = (
|
||||
f"HTTP/1.1 {status} {reason}\r\n"
|
||||
"Content-Type: text/plain; charset=utf-8\r\n"
|
||||
f"Content-Length: {len(payload)}\r\n"
|
||||
"Connection: close\r\n\r\n"
|
||||
).encode("utf-8") + payload
|
||||
conn.sendall(response)
|
||||
finally:
|
||||
server.close()
|
||||
record_path.write_text(json.dumps(records, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+61
-1
@@ -66,6 +66,52 @@ def consumer_manifest(alias: str) -> str:
|
||||
)
|
||||
|
||||
|
||||
class Loopback:
|
||||
"""One deterministic loopback HTTP server process for a domain case."""
|
||||
|
||||
def __init__(self, workdir: Path, requests: int):
|
||||
self.record = workdir / "loopback-records.json"
|
||||
self.record.unlink(missing_ok=True)
|
||||
self.process = subprocess.Popen(
|
||||
[
|
||||
sys.executable,
|
||||
str(REPO / "scripts" / "loopback_server.py"),
|
||||
str(self.record),
|
||||
str(requests),
|
||||
],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
line = self.process.stdout.readline().strip()
|
||||
if not line.isdigit():
|
||||
stderr = self.process.stderr.read()
|
||||
raise CaseError(f"loopback server did not report a port: {line!r} {stderr}")
|
||||
self.port = int(line)
|
||||
|
||||
def finish(self) -> list[dict]:
|
||||
try:
|
||||
self.process.wait(timeout=15)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.process.kill()
|
||||
raise CaseError("loopback server did not finish")
|
||||
if not self.record.is_file():
|
||||
raise CaseError("loopback server wrote no request record")
|
||||
return json.loads(self.record.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def check_loopback(case: dict, records: list[dict]) -> None:
|
||||
expected = case.get("request_asserts", {}).get("requests", [])
|
||||
if len(records) != len(expected):
|
||||
raise CaseError(f"loopback request count {len(records)} != {len(expected)}")
|
||||
for index, (actual, want) in enumerate(zip(records, expected)):
|
||||
for key in ("method", "path", "body"):
|
||||
if key in want and actual.get(key) != want[key]:
|
||||
raise CaseError(
|
||||
f"loopback request[{index}] {key} {actual.get(key)!r} != {want[key]!r}"
|
||||
)
|
||||
|
||||
|
||||
def run_case(case: dict, binary: str, bundle: Path) -> None:
|
||||
name = case["name"]
|
||||
alias = case["dep_alias"]
|
||||
@@ -77,7 +123,13 @@ def run_case(case: dict, binary: str, bundle: Path) -> None:
|
||||
if not source.is_file():
|
||||
raise CaseError(f"{name}: missing test source {source}")
|
||||
with tempfile.TemporaryDirectory(prefix="mq-package-test-") as tmp:
|
||||
consumer = Path(tmp) / "consumer"
|
||||
workdir = Path(tmp)
|
||||
loopback = (
|
||||
Loopback(workdir, int(case.get("requests", 2)))
|
||||
if case.get("kind") == "loopback"
|
||||
else None
|
||||
)
|
||||
consumer = workdir / "consumer"
|
||||
package = consumer / "deps" / alias
|
||||
package.mkdir(parents=True)
|
||||
shutil.copy2(REPO / "marqdo.yaml", package / "marqdo.yaml")
|
||||
@@ -89,6 +141,12 @@ def run_case(case: dict, binary: str, bundle: Path) -> None:
|
||||
if lock.returncode != 0:
|
||||
raise CaseError(f"{name}: marqdo lock failed: {lock.stderr.decode(errors='replace')}")
|
||||
args = [str(arg).replace("$MARQDO_BIN", binary) for arg in case.get("args", [])]
|
||||
if loopback is not None:
|
||||
env["HTTP_TEST_PORT"] = str(loopback.port)
|
||||
for host in case.get("grants", []):
|
||||
args += ["--allow-net", host]
|
||||
for name in case.get("allow_env", []):
|
||||
args += ["--allow-env", name]
|
||||
result = subprocess.run(
|
||||
[binary, "run", str(consumer / "tests" / case["file"]), *args, "--output", "json"],
|
||||
cwd=consumer, env=env, input=case.get("stdin", "").encode(), capture_output=True,
|
||||
@@ -111,6 +169,8 @@ def run_case(case: dict, binary: str, bundle: Path) -> None:
|
||||
stdout = channel_text(report["events"], "stdout.chunk")
|
||||
if stdout != case.get("expected_stdout", ""):
|
||||
raise CaseError(f"{name}: stdout changed: {stdout!r}")
|
||||
if loopback is not None:
|
||||
check_loopback(case, loopback.finish())
|
||||
|
||||
|
||||
def main() -> int:
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"schema": "marqdo.package-test-case",
|
||||
"schema_version": 1,
|
||||
"name": "loopback",
|
||||
"kind": "loopback",
|
||||
"file": "loopback.mq.md",
|
||||
"dep_alias": "http",
|
||||
"requests": 2,
|
||||
"grants": [
|
||||
"127.0.0.1"
|
||||
],
|
||||
"args": [],
|
||||
"stdin": "",
|
||||
"env": {},
|
||||
"expected_stdout": "",
|
||||
"expected_terminal": {
|
||||
"type": "list",
|
||||
"items": [
|
||||
{
|
||||
"type": "bool",
|
||||
"value": true
|
||||
},
|
||||
{
|
||||
"type": "int",
|
||||
"decimal": "200"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"value": "第一个"
|
||||
},
|
||||
{
|
||||
"type": "bool",
|
||||
"value": true
|
||||
},
|
||||
{
|
||||
"type": "int",
|
||||
"decimal": "201"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"value": "第二个"
|
||||
}
|
||||
]
|
||||
},
|
||||
"request_asserts": {
|
||||
"requests": [
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/one",
|
||||
"body": ""
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/two",
|
||||
"body": "ok"
|
||||
}
|
||||
]
|
||||
},
|
||||
"allow_env": [
|
||||
"HTTP_TEST_PORT"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
---
|
||||
import:
|
||||
http: "@http"
|
||||
---
|
||||
|
||||
# @exec 回环
|
||||
|
||||
## 写字节
|
||||
|
||||
`params(资源, 字节)`
|
||||
|
||||
**内存 = memory.new(1, 1)**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
`while 下标 < 长度(字节)`
|
||||
|
||||
**内存[下标] = 字节[下标]**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
`end`
|
||||
|
||||
`return resource.write(资源, 内存, 0, 长度(字节))`
|
||||
|
||||
## 读全部
|
||||
|
||||
`params(资源)`
|
||||
|
||||
**结果 = []**
|
||||
|
||||
**继续 = true**
|
||||
|
||||
`while 继续`
|
||||
|
||||
**内存 = memory.new(1, 1)**
|
||||
|
||||
**读 = resource.read(资源, 内存, 0, 65536)**
|
||||
|
||||
`if not 读.ok`
|
||||
|
||||
`return 读`
|
||||
|
||||
`end`
|
||||
|
||||
**数 = 读.value.count**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
`while 下标 < 数`
|
||||
|
||||
**结果 = list.append(结果, 内存[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
`end`
|
||||
|
||||
`if 读.value.eof or 数 == 0`
|
||||
|
||||
**继续 = false**
|
||||
|
||||
`else`
|
||||
`if true`
|
||||
|
||||
**忽略 = 0**
|
||||
|
||||
`end`
|
||||
`end`
|
||||
|
||||
`end`
|
||||
|
||||
`return {ok: true, value: 结果}`
|
||||
|
||||
## 交换
|
||||
|
||||
`params(端口, 方法, 路径, 头, 体)`
|
||||
|
||||
**请求字节 = http.构建请求字节(方法, 路径, 头, http.文本字节(体))**
|
||||
|
||||
**打开 = resource.open("tcp", "127.0.0.1:" + 文本(端口), ["read", "write"])**
|
||||
|
||||
**写 = 写字节(打开, 请求字节)**
|
||||
|
||||
`if not 写.ok`
|
||||
|
||||
`return 写`
|
||||
|
||||
`end`
|
||||
|
||||
**读 = 读全部(打开)**
|
||||
|
||||
**关闭 = resource.close(打开)**
|
||||
|
||||
`if not 读.ok`
|
||||
|
||||
`return 读`
|
||||
|
||||
`end`
|
||||
|
||||
**响应 = http.解析响应字节(读.value)**
|
||||
|
||||
`if not 响应.ok`
|
||||
|
||||
`return 响应`
|
||||
|
||||
`end`
|
||||
|
||||
**正文 = http.字节文本(响应.value.body)**
|
||||
|
||||
`if not 正文.ok`
|
||||
|
||||
`return 正文`
|
||||
|
||||
`end`
|
||||
|
||||
`return {ok: true, 状态: 响应.value.status, 正文: 正文.value}`
|
||||
|
||||
## main
|
||||
|
||||
`params()`
|
||||
|
||||
**端口读 = resource.request("env.get", ["HTTP_TEST_PORT"])**
|
||||
|
||||
`if not 端口读.ok`
|
||||
|
||||
`return [false, 0, "", false, 0, ""]`
|
||||
|
||||
`end`
|
||||
|
||||
**端口 = 整数(端口读.value)**
|
||||
|
||||
**一 = 交换(端口, "GET", "/one", [["Host", "example.test"]], "")**
|
||||
|
||||
**二 = 交换(端口, "POST", "/two", [["Host", "example.test"], ["Content-Length", "2"]], "ok")**
|
||||
|
||||
`return [一.ok, 一.状态, 一.正文, 二.ok, 二.状态, 二.正文]`
|
||||
Reference in new issue
Block a user