locust详解
目录
一、命令行选项
locust主要通过命令行参数配置
locust --help
Usage: locust [OPTIONS] [UserClass ...]
Common options:
  -h, --help            show this help message and exit
  -f LOCUSTFILE, --locustfile LOCUSTFILE
                        Python module to import, e.g. '../other_test.py'.
                        Either a .py file or a package directory. Defaults to
                        'locustfile'
  --config CONFIG       Config file path
  -H HOST, --host HOST  Host to load test in the following format:
                        http://10.21.32.33
  -u NUM_USERS, --users NUM_USERS
                        Peak number of concurrent Locust users. Primarily used
                        together with --headless or --autostart. Can be
                        changed during a test by keyboard inputs w, W (spawn
                        1, 10 users) and s, S (stop 1, 10 users)
  -r SPAWN_RATE, --spawn-rate SPAWN_RATE
                        Rate to spawn users at (users per second). Primarily
                        used together with --headless or --autostart
  -t RUN_TIME, --run-time RUN_TIME
                        Stop after the specified amount of time, e.g. (300s,
                        20m, 3h, 1h30m, etc.). Only used together with
                        --headless or --autostart. Defaults to run forever.
  -l, --list            Show list of possible User classes and exit二、配置文件
配置文件默认为:locust.conf
可使用--config指定附加的配置文件
# locust.conf in current directory
locustfile = locust_files/my_locust_file.py
headless = true
master = true
expect-workers = 5
host = http://target-system
users = 100
spawn-rate = 10
run-time = 10mlocust --config=master.conf
当多个地方均有配置时,配置信息按以下顺序取值
~/locust.conf -> ./locust.conf -> (file specified using --conf) -> env vars -> cmd args三、自定义统计设置
Locust 统计的默认配置在 stats.py 文件的常量中设置,它可以通过覆盖这些值来调整到特定要求。
import locust.stats
locust.stats.CONSOLE_STATS_INTERVAL_SEC = 15可以修改的统计参数列表是:
| 参数名称 | 目的 | 
|---|---|
| STATS_NAME_WIDTH | 控制台输出中请求名称的列宽 | 
| STATS_TYPE_WIDTH | 控制台输出中请求类型的列宽 | 
| CSV_STATS_INTERVAL_SEC | 如果配置了此选项,则写入 CSV 文件的频率间隔 | 
| CONSOLE_STATS_INTERVAL_SEC | 结果写入控制台的频率间隔 | 
| CURRENT_RESPONSE_TIME_PERCENTILE_WINDOW | 窗口大小/分辨率 - 以秒为单位 - 计算当前响应时间百分位时 | 
| PERCENTILES_TO_REPORT | 要计算和报告的响应时间百分位数列表 | 
四、分布式负载生成
4.1、同一台机器
- 启动主进程:locust -f 被执行的文件.py --master
- 启动助攻进程:cmd进入到脚本目录下,输入命令:locust -f 被执行的文件.py --worker 注:同一台机器的分布式,机器是几核的,就启动几个;主控进程和助攻进程的启动,没有先后顺序报错解决方法:执行 locust -f 被执行的文件.py --master 报错:AttributeError: module 'zmq.green' has no attribute 'ROUTER'查看是否安装pyzmq,得知系统已安装pyzmq 
怀疑可能是版本不正确,卸载当前版本,安装最新版本pyzmq


再次执行 locust -f 被执行的文件.py --master 又报错:

原因:版本不匹配,解决办法如下: 先卸载现有版本的pyzmq,再下载更低版本的pyzmq
pip3 install pyzmq==19.0.2
再次运行,可正常启动
4.2、不同机器
- 启动主进程:locust -f 被执行的文件.py --master
- 启动助攻进程:locust -f 被执行的文件.py --worker --master-host=主控机器ip --master-port=5557(默认的端口,如果主控没有修改的话,可以不用写)
五、在调试器中运行测试
调试器中运行 Locust 在开发测试时非常有用,可以检查特定响应或检查一些用户实例变量。
但是调试器有时会遇到像 Locust 这样复杂的 gevent 应用程序的问题,并且框架本身发生了很多你可能不感兴趣的事情。为了简化这一点,Locust 提供了一个名为的方法run_single_use
from locust import HttpUser, task, run_single_user
class QuickstartUser(HttpUser):
    host = "http://www.baidu.com"
    @task
    def hello_world(self):
        with self.client.get("/", catch_response=True) as resp:
            pass  # maybe set a breakpoint here to analyze the resp object?
if __name__ == "__main__":
    run_single_user(QuickstartUser)运行结果:

六、在没有 Web UI 的情况下运行
在没有 Web UI 的情况下运行 locust ,例如想在某些自动化流程中运行它,如CI 服务器, - 通过将--headless标志与-u和-r一起使用
locust -f locust_files/my_locust_file.py --headless -u 1000 -r 100-u指定要生成的用户数,并-r指定生成率(每秒启动的用户数)。
6.1、设置测试时间限制
如果要指定测试的运行时间,可以使用--run-time或-t:
$ locust -f --headless -u 1000 -r 100 --run-time 1h30m6.2、允许任务在关闭时完成迭代
默认情况下,locust 在运行时间结束时,会立刻结束任务,如果你想让所有任务都完成,可以使用.--stop-timeout <seconds>
6.3、控制locust的退出码
当在CI中运行locust时,可能需要控制locust退出码(我们可以根据exit_code来判断本次构建是否成功),可以在测试脚本中设置 Environment 实例的 process_exit_code
下面的例子演示,如果满足以下任何条件,就退出测试并将退出码设置为非0:
- 超过 1% 的请求失败
- 平均响应时间大于 200 ms
- 95%的响应时间大于 800 毫秒
import logging
from locust import events
@events.quitting.add_listener
def _(environment, **kw):
    if environment.stats.total.fail_ratio > 0.01:
        logging.error("Test failed due to failure ratio > 1%")
        environment.process_exit_code = 1
    elif environment.stats.total.avg_response_time > 200:
        logging.error("Test failed due to average response time ratio > 200 ms")
        environment.process_exit_code = 1
    elif environment.stats.total.get_response_time_percentile(0.95) > 800:
        logging.error("Test failed due to 95th percentile response time > 800 ms")
        environment.process_exit_code = 1
    else:
        environment.process_exit_code = 0(此代码可以进入 locustfile.py 或写在其他文件中导入到 locustfile.py)
构造符合上述三种情况之一的脚本,运行结果如下:

运行完成后,可根据exit code 来判定每次压测结果是否通过
