性能工具之 locust 工具 Get 与 Post 请求

举报
zuozewei 发表于 2022/01/07 00:36:02 2022/01/07
【摘要】 最近在学习 Locust 性能工具,发现 Locust 性能工具脚本需要 python 基础才能写脚本,但是对于性能测试人员来说 python 是基本功夫。

前言

最近在学习 Locust 性能工具,发现 Locust 性能工具脚本需要 python 基础才能写脚本,但是对于性能测试人员来说 python 是基本功夫。

脚本示例

在 Locust 中 get 脚本怎么写,为了方便直接在代码运行调试,采用关闭 web 模式,通过参考官方文档自己实验 get/post 代码,参考代码如:

	@task(1)
    def get_7dTest(self):
        # 定义请求头
        header = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"}
        response = self.client.get("/7d/", headers=header, verify=False)
        # print("Response status code:", response.status_code)
        if response.status_code == 200:
            print("successful")
            # print("Response text:", response.json())
        else:
            print('failure')

Post请求写法如下:

 	# 登陆
    @task(1)
    def get_login(self):
        response = self.client.post("/login", {"userName": "7d", "passWord": "123456"})
        print("Response json:", response.json())

结果:

# 结果:
[2021-04-24 21:36:49,495] liwen.local/INFO/locust.main: Run time limit set to 1 seconds
[2021-04-24 21:36:49,495] liwen.local/INFO/locust.main: Starting Locust 1.4.4
[2021-04-24 21:36:49,496] liwen.local/INFO/locust.runners: Spawning 1 users at the rate 1 users/s (0 users already running)...
[2021-04-24 21:36:49,496] liwen.local/INFO/locust.runners: All users spawned: webTestDunShan: 1 (1 total running)
[2021-04-24 21:36:49,496] liwen.local/INFO/root: Terminal was not a tty. Keyboard input disabled
 Name                                                          # reqs      # fails  |     Avg     Min     Max  Median  |   req/s failures/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
 Aggregated                                                         0     0(0.00%)  |       0       0       0       0  |    0.00    0.00

Response json: {'msg': 'success', 'code': 0, 'data': '登陆成功'}
successful
Response json: {'msg': 'success', 'code': 0, 'data': '登陆成功'}
Response json: {'msg': 'success', 'code': 0, 'data': '登陆成功'}
Response json: {'msg': 'success', 'code': 0, 'data': '登陆成功'}
Response json: {'msg': 'success', 'code': 0, 'data': '登陆成功'}

post 请求 json 请求写法:

	@task(1)
    def get_login_json(self):
        jsonData = {"userName": "7d", "passWord": "123456"}
        response = self.client.post("/login/json", json=json.dumps(jsonData))
        print("Response json:", response.json())
        
		# 结果
		Response json: {'msg': 'success', 'code': 0, 'data': '登陆成功'}

实验请求资源代码:


	@GetMapping("/7d")
    @ResponseBody
    public R indexPage() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("success", "欢迎来到性能实战课堂");
        map.put("Data", new Date());
        return R.ok().put("data", map);
    }


	/**
     * 登陆
     *
     * @param memberEntity
     * @return
     */
     
    @PostMapping("/login")
    @ResponseBody
    public R login(MemberEntity memberEntity) {

        if ("7d".equals(memberEntity.getUserName()) && "123456".equals(memberEntity.getPassWord())) {
            return R.ok().put("data", "登陆成功");
        }
        return R.error().put("data", "用户名或者密码失败");
    }


    /**
     * 登陆
     *
     * @param requestBody
     * @return
     */
     
    @PostMapping(value = "/login/json", produces = "application/json")
    @ResponseBody
    public R login_json(@RequestBody String requestBody) {
        log.info("json数据:{}", requestBody);
        Object parse = JSON.parse(requestBody);
        MemberEntity memberEntity = JSON.parseObject(parse.toString(), MemberEntity.class);
        if ("7d".equals(memberEntity.getUserName()) && "123456".equals(memberEntity.getPassWord())) {
            return R.ok().put("data", "登陆成功");
        }
        return R.error().put("data", "用户名或者密码失败");
    }

Locust 直接在 Python 代码调试代码关闭web页面,这样调试很方便,参考如下命令:

os.system("locust -f demoLcou.py --host=http://127.0.0.1:8080 --headless -u 1 -r 1 -t 1s")
# –no-web 表示不使用Web界面运行测试。
# -c 设置虚拟用户数。
# -r 设置每秒启动虚拟用户数。
# -t 设置设置运行时间。

# 结果参考:
[2021-04-24 22:23:59,688] liwen.local/INFO/locust.main: Run time limit set to 1 seconds
[2021-04-24 22:23:59,688] liwen.local/INFO/locust.main: Starting Locust 1.4.4
[2021-04-24 22:23:59,688] liwen.local/INFO/locust.runners: Spawning 1 users at the rate 1 users/s (0 users already running)...
[2021-04-24 22:23:59,688] liwen.local/INFO/locust.runners: All users spawned: webTestDunShan: 1 (1 total running)
[2021-04-24 22:23:59,689] liwen.local/INFO/root: Terminal was not a tty. Keyboard input disabled
 Name                                                          # reqs      # fails  |     Avg     Min     Max  Median  |   req/s failures/s
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
 Aggregated                                                         0     0(0.00%)  |       0       0       0       0  |    0.00    0.00

successful
Response json: {'msg': '未知异常,请联系管理员', 'code': 500, 'data': '用户名或者密码失败'}
。。。。。中间省略。。。。
successful
[2021-04-24 22:24:00,454] liwen.local/INFO/locust.main: Time limit reached. Stopping Locust.
[2021-04-24 22:24:00,454] liwen.local/INFO/locust.runners: Stopping 1 users
[2021-04-24 22:24:00,455] liwen.local/INFO/locust.runners: 1 Users have been stopped, 0 still running
[2021-04-24 22:24:00,455] liwen.local/INFO/locust.main: Running teardowns...
[2021-04-24 22:24:00,455] liwen.local/INFO/locust.main: Shutting down (exit code 0), bye.
[2021-04-24 22:24:00,455] liwen.local/INFO/locust.main: Cleaning up runner...
 Name                                                          # reqs      # fails  |     Avg     Min     Max  Median  |   req/s failures/s
--------------------------------------------------------------------------------------------------------------------------------------------
 GET /                                                            166     0(0.00%)  |       1       1       5       2  |  216.65    0.00
 GET /7d/                                                          89     0(0.00%)  |       1       1      12       1  |  116.16    0.00
 POST /login                                                       98     0(0.00%)  |       1       1       2       1  |  127.90    0.00
 POST /login/json                                                  87     0(0.00%)  |       1       1       2       2  |  113.55    0.00
--------------------------------------------------------------------------------------------------------------------------------------------
 Aggregated                                                       440     0(0.00%)  |       1       1      12       2  |  574.26    0.00

Response time percentiles (approximated)
 Type     Name                                                              50%    66%    75%    80%    90%    95%    98%    99%  99.9% 99.99%   100% # reqs
--------|------------------------------------------------------------|---------|------|------|------|------|------|------|------|------|------|------|------|
 GET      /                                                                   2      2      2      2      2      3      3      5      6      6      6    166
 GET      /7d/                                                                1      1      1      1      2      2      2     12     12     12     12     89
 POST     /login                                                              1      1      1      1      2      2      2      2      2      2      2     98
 POST     /login/json                                                         2      2      2      2      2      2      2      3      3      3      3     87
--------|------------------------------------------------------------|---------|------|------|------|------|------|------|------|------|------|------|------|
 None     Aggregated                                                          2      2      2      2      2      2      3      3     12     12     12    440


Process finished with exit code 0

总结

Locust 官方文档还是比较详细,只要慢慢看就能掌握 Locust 工具怎么操作,但是在老师性能工程中,工具只要能发压就行。

参考资料:

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。