普贤教程 › 包参考
mock 包
HTTP 桩服务器 / 测试请求客户端
⚠️ 含并发(spawn)—— 服务器需编译模式运行(px build);
| 项 | 值 |
|---|---|
| 包名 | mock |
| 版本 | 0.2.0 |
| 可用版本 | 0.1.0 / 0.2.0 |
| 入口 | mock.px |
| 分类 | Web 与 HTTP |
| 文件数 / 行数 | 1 / 236 |
安装与引入
bash
pxpkg init # 首次 pxpkg add mock@0.2.0 pxpkg install
px
import mock所属分类教程:Web 与 HTTP
公开接口
| 函数 | 参数 |
|---|---|
mk_route | method, path, status, body, ctype = "text/plain" |
mk_status_text | code |
mk_start_server | port, routes, reqlog, max_conns = 100 |
mk_parse_response | resp |
mk_request | port, method, path, body = "" |
mk_clock | secs |
mk_clock_next | clk |
其余 9 个 def(内部与辅助,可直接调用但不属稳定接口)
| 函数 | 参数 |
|---|---|
mk_parse_req | raw |
mk_build_resp | status, body, ctype |
mk_route_resp | req, routes |
mk_server_loop | port, routes, reqlog, max_conns, ready = null |
mk_is_success | code |
mk_is_redirect | code |
mk_is_error | code |
mk_format_url | host, port, path |
mk_method_name | method |
包内说明(源码头注释)
text
============================================================ 普贤生态库:registry/mock —— HTTP 桩服务器 / 测试请求客户端 ------------------------------------------------------------ ⚠️ 含并发(spawn)—— 服务器需编译模式运行(px build); 解释器 px run 是 Mini 子集,无并发原语(PX-DEF-006)。 var routes = [mk_route("GET", "/hello", 200, "hi")] var log = [] mk_start_server(19080, routes, log, 10) var r = mk_request(19080, "GET", "/hello") r.unwrap()["status"] == 200, ["body"] == "hi" API: mk_route(method, path, status, body[, ctype]) → 路由 dict mk_start_server(port, routes, reqlog, max_conns) → 启动桩服务器(spawn) mk_request(port, method, path[, body]) → Ok({status, status_text, headers, body}) mk_parse_response(resp_text) → Ok(dict) | Err(客户端响应解析) mk_status_text(code) → 状态短语 时间桩(注入式):mk_clock(secs) / mk_clock_next(clock) 行为: - 路由按 method+path 精确匹配;路径存在但方法不符 → 405;否则 404 - Content-Length 按 UTF-8 字节数计算(中文 body 正确) - reqlog 为 list 引用,服务器每收一个请求 append {method, path, headers, body} - 服务器处理满 max_conns 个连接后退出(spawn 协程自然结束) 说明:监听地址由 native tcp_listen 决定(任意地址);测试请指向 127.0.0.1 ============================================================ ---- 路由与状态 ---- 构造路由:method/path 精确匹配