Fastman
fastman 是一个restful api 测试的辅助库,可以快速建立api测试,并完成openapi的文档编写;
并将测试用例导出为postman的格式文件,以便共享测试用例。
目前只支持 OpenApi 3.0 版本的文档格式
测试的runner使用 newman
Current Version: 0.0.3
Use
Install
For yarn
yarn add fastman
For npm
npm i fastman --save
Demo
Clone 仓库
yarn
yarn test
yarn demo-server
测试前文档
http://localhost:3000/doc
测试后文档
http://localhost:3000/doc/tested
编写API文档
编写需要测试的openapi文档,如 example.yaml
新建一个测试文件
example.test.js
引入并初始化fastman
const Fastman = require("fastman").default;
const fastman = new Fastman();
可以使用任何测试框架,本例使用mocha
测试前需要做一些准备工作
before(function () {
const spec = yaml.safeLoad(fs.readFileSync(specPath).toString("utf8"));
fastman
.openApiVersion(3)
.load(spec)
.globalHeaders({
post: {
"Content-Type": "application/json",
},
put: {
"Content-Type": "application/json",
},
})
.resource("Users");
});
写测试code
it("Test Create User", async function () {
await fastman
.path("/users")
.operation("get")
.response("200")
.testCase({
name: "ListUserOK",
save: true,
query: {
offset: 0,
limit: 10,
},
})
.except((resp) => {
let body = resp.json();
assert(body.length === 10);
const xTotal = resp.headers.get("X-Total");
assert(xTotal !== 0);
})
.run()
});
另一种写法
it('Test Create User ', async function () {
let resp = await fastman
.path("/users")
.operation("post")
.response("200")
.testCase({
name: "CreateUerOK",
save: true,
body: {
name: "Shao Chen",
},
}).run();
const body = resp.json();
assert.exists(body.id);
user = body.id;
assert(body["name"] === "Shao Chen");
});
同一api的多个TestCase测试
it("Test get User", async function () {
let resp = await fastman
.path("/users/{userId}")
.operation("get")
.response("200")
.testCase({
name: "GetUserOK",
save: true,
params: [user],
}).run();
let body = resp.json();
assert(body.name === "MagicCaptain");
assert(body.id === user);
resp = await fastman
.response("404")
.testCase({
name: "GetUserNotFound",
save: true,
params: ["fdfdfder3"],
})
.run();
body = resp.json();
assert(body.name === "NotFound");
})
输出测试结果
after(function () {
fs.writeFileSync(testedSpecPath, fastman.writeSpec());
fastman.exportPostman(postmanPath);
});
测试用例配置
export interface TestCase {
name: string,
save?: boolean,
saveRequest?: boolean
excludePostman?: boolean,
params?: string[]
query?: object,
body?: object,
header?: object
}
Roadmap