如何在Chakram中断言Keep-Alive响应头的timeout值符合范围要求?
完成Postman中Keep-Alive Timeout的断言逻辑
我来帮你补全Postman BDD里针对Keep-Alive头timeout值的断言代码,结合你已经写的部分,完整逻辑如下:
// 获取响应头中的Keep-Alive字段 let keepAlive = response.getHeader("Keep-Alive"); // 提取timeout数值的正则表达式 let timeoutMatch = /timeout=(\d+)/.exec(keepAlive); // 断言匹配结果存在且不为空 expect(timeoutMatch).to.be.an("array").and.not.empty; // 将匹配到的字符串转为整数 let timeout = parseInt(timeoutMatch[1]); // 断言timeout值在10到100之间(包含两个边界值) expect(timeout).to.be.within(10, 100);
逻辑说明:
- 用正则表达式
/timeout=(\d+)/精准匹配Keep-Alive字段中的timeout=xx部分,捕获组(\d+)会提取出纯数字部分 expect(timeout).to.be.within(10, 100)是Chai BDD风格的断言,直接验证数值是否在指定区间内(包含10和100)- 如果你同时需要验证max值的话,也可以沿用你原来的逻辑,把timeout的验证和max的验证放在一起:
// 同时验证timeout和max的完整代码 let keepAlive = response.getHeader("Keep-Alive"); // 验证timeout let timeoutMatch = /timeout=(\d+)/.exec(keepAlive); expect(timeoutMatch).to.be.an("array").and.not.empty; let timeout = parseInt(timeoutMatch[1]); expect(timeout).to.be.within(10, 100); // 验证max(沿用你原来的逻辑) let maxMatch = /max=(\d+)/.exec(keepAlive); expect(maxMatch).to.be.an("array").and.not.empty; let max = parseInt(maxMatch[1]); expect(max).to.be.within(98, 100);
这样就能同时完成timeout和max值的双重断言啦~
内容的提问来源于stack exchange,提问作者demouser123
相关产品推荐
相关产品推荐

