德斯软件资讯7月7日消息,自动处理重复任务是系统管理员日常工作的核心部分。基于Web的API越来越需要这种自动化 ,为跨设备、云提供商或软件提供服务(SaaS)协调活动的工具。您需要彻底测试代码,无论是编写shell脚本还是与web服务互动的ansible剧本。
模拟API的能力是测试过程的重要组成部分。模仿真实的API,以便您开发和测试API交互。虽然一些工具和供应商提供实时沙箱环境,但在本地模仿API对高级测试场景非常有用,如修改响应文本或HTTP状态代码。如果您正处于开发API的初始阶段,您还需要在编写代码之前快速构建端点。
Mockoon是支持这样做的选择。Mockoon是一款用户界面丰富的优秀开源工具,可用于快速构建模拟API,并在本地机器上运行。
安装Mockon
您可以在Windows中使用官方软件包、Mockoon安装在MacOS和Linux上,包括AppImage和RPM格式。安装Mockoon后,官方文档为新用户提供了优秀的教程。
Mockoon拥有图形界面和命令行接口(CLI)本文重点介绍了如何使用图形界面。
创建环境
在Mockon中处理新项目的第一步是创造一个新的环境。环境允许您将API端点分为逻辑组。每个环境也可以在自己的端口上运行,这样您就可以在同一主机上模拟多个API。环境保存为JSON文件,可轻松导入、导出和与代码一起保存。
点击以下“新环境”图标创建环境。它将提示您选择保存环境JSON文件的位置。创建环境后,您可以开始添加路由。
通过添加基本的API路由
大多数API交互涉及一个简单的请求和响应循环,通常返回JSON对象。在开始使用Mockon之前,建立一个简单的API路由。单击界面中的内容 路由可以添加到环境中。
我在/api/v1/healthcheck添加返回2000 OK状态码的路由如下所示。该示例还返回JSON响应,包含健康状况检查信息:
一旦添加路由并启动服务器(或重新启动,如果已经在运行),端点可以访问:
生成随机响应数据
API响应文本中的静态值涵盖了许多基本的测试用例。Mockoon还可以在响应文本中生成更真实的测试的随机数据。Faker.js库用于生成随机数据。随机生成的值可以在响应文本中模板,并返回给请求者。
在下面的例子中,我添加了另一个端点:/api/v1/hosts/:id。:id表示这是一个URL参数。回应正文返回JSON对象,该对象包含多个字段附有随机生成数据。
使用此配置,API端点的每个调用都显示了一组不同的假数据:
注:MockoonFaker实现.js版本可能不是最新的,所以在编写模板时,一定要确保查看Faker文档的正确版本。
添加身份验证和规则
大多数API终端点需要身份验证,通常使用带有API令牌的HTTP标头。开发强大的自动化非常重要,以确保您的工具能够正确处理来自终端点的身份验证失败。Mockoon允许您定义可用于返回不同响应的规则,例如标题要求。
规则是在路由的“规则”选项卡上定义的。以下示例使用两个规则扩展/api/v1/hosts/:ID端点。第一条规则(响应1)返回HTTPP 401 Unauthorized。使用第一条规则,如果没有与请求匹配的其他规则。
第二条要求含有值等于40650a76的X规则(响应2)-Auth-Token HTTP标头。任何符合这一规则的请求都将收到200个 来自上一个例子的JSON响应OK。
这些规则导致任何X-Auth-请求失败不包含在Token标头中的正确值,并返回HTTP 401 Unauthorized。有正确令牌的请求将继续接收数据,如下所示:
这是使用规则根据要求属性控制响应行为的基本示例。
Mockon的规则引擎功能强大,可以创建非常先进的场景。
总结
今天就分享到这里吧,德斯软件资讯是一个软件分享基地,其中包括微信,红包辅助,支付宝,聊讯,微客优品,千喜惠,优乐购,淘卷淘,花惜,有趣超市,逗鱼时刻,惊喜淘,易凡,睛彩,坤米,达信酷,QQ,淘汇购,集市易选,泡泡易选,陌陌,钉钉,微信红包辅助,思语,百盛,苹果微信多开,微信分身,安卓微信多开等社交平台的功能有秒,避雷,埋雷软件,单透,扫尾,秒抢等一些红包强项外挂功能软件分享。喜欢的请关注收藏,谢谢。