Locust性能-零基础入门系列(17)-简化Locust测试流程

之前在运行Locust测试时,一般步骤是这样的:

  • 创建好Locust脚本(locust file),模拟好场景

  • 在命令行运行Locust脚本,如下:
locust -f locust_file.py
  • 然后打开web UI,在UI上设置测试参数,比如用户数,ramp up rate等。
    如上你会发现,整体步骤还是有些繁琐的。其实Locust提供了比上述方式更简洁的方式,可以将性能测试相关的配置,运行等都集中在脚本中去实现。具体,可以参考如下脚本(Locust 版本1.1.1):
import gevent
from locust import HttpUser,task,between
from locust.env import Environment
from locust.stats import stats_printer
from locust.log import setup_logging

setup_logging("INFO",None)

class WebUser(HttpUser):
    wait_time = between(1,5)
    host = 'https://blog.51cto.com'
    @task
    def open_blog1(self):
        with self.client.get('/13734261/2538770',catch_response=True) as res:
            if res.status_code == 200:
                res.success()

    @task
    def open_blog2(self):
        with self.client.get('/13734261/2538745',catch_response=True) as res:
            if res.status_code == 200:
                res.success()

#创建环境和runner
env = Environment(user_classes=[WebUser,])
env.create_local_runner()

#start a WebUI instance
env.create_web_ui("127.0.0.1",8001)

#开启了协程,会定期打印runner状态
gevent.spawn(stats_printer(env.stats))

#开启测试,开启用户数为1
env.runner.start(1,hatch_rate=10)

# 设置100秒后,然后停止测试
gevent.spawn_later(100,lambda: env.runner.quit())
#等待greenlet结束
env.runner.greenlet.join()
#结束locust webUI
env.web_ui.stop()

测试输出结果如下,测试过程中,也会定期输出这样的测试结果表格,一般是隔几秒输出一次吧。

Name                                                          # reqs      # fails     Avg     Min     Max  |  Median   req/s failures/s
--------------------------------------------------------------------------------------------------------------------------------------------
 GET /13734261/2538745                                             13     0(0.00%)     300     183     542  |     280    0.10    0.00
 GET /13734261/2538770                                             17     0(0.00%)     376     199     931  |     270    0.20    0.00
--------------------------------------------------------------------------------------------------------------------------------------------
 Aggregated                                                        30     0(0.00%)     343     183     931  |     270    0.30    0.00

这样的测试步骤改进,可以省略如下步骤:

  • 在命令行运行测试脚本

  • 在浏览器中webUI上设置测试参数并监控测试运行过程。

Locust性能-零基础入门系列(17)-简化Locust测试流程

猜你喜欢

转载自blog.51cto.com/13734261/2571599