当前位置: 首页 > 工具软件 > Locust > 使用案例 >

Locust (一)性能测试为什么要用 locust ?为什么 locust 的教程用不了?

元昊苍
2023-12-01

一、什么是locust?

引用官网文案:Define user behaviour with Python code, and swarm your system with millions of simultaneous users.

即,用Python代码定义用户行为,让数百万并发用户涌入您的系统。

 

二、为什么用locust?

相较于loadrunner、jmeter,locust的优势主要在于:

1、基于协程,避免了系统级资源调度,大幅提高了单机并发能力

2、开源免费,功能简单,学习成本低

3、基于python,且 HTTP 请求完全基于 Requests 库,也可支持其他协议或者自定义请求,可拓展性强,理论可测一切系统

当然,locust 缺点也很明显,也就是一直为人所诟病的极简风的报告与分析,以及不支持资源监控

所以,locust的优缺点都很明显,如何取舍就看个人需求了。

具体对比如下:

 LRJmeterLocust
开发语言C/JAVAJAVAPYTHON
脚本形式C/JAVAGUIPYTHON
授权方式商业收费开源免费开源免费
并发机制进程/线程线程协程
单机并发能力
资源消耗
分布式支持支持支持
报告与分析全面简单简单
资源监控支持不支持不支持
二次开发不支持支持支持


三、为什么网上搜到的 locust 教程大都不能用了?

其实不能用的原因很简单,因为时代变了,网上的教程大都是'0.n'版本,而 locust 在2020locust 进入了  '1.n' 版本时代。

而网上的教程大都还停留在0版本,版本不一致自然不能用。

那么0到1的版本变更都有哪些呢?

1、安装

安装命令统一为:pip install locust

如果使用 pip install locustio,就必须指定以前0开头的版本

2、参数

可以直接拉出帮助文档

C:\Users\Administrator>locust --help

Usage: locust [OPTIONS] [UserClass ...]

Common options:
  -h, --help            show this help message and exit
  -f LOCUSTFILE, --locustfile LOCUSTFILE
                        Python module file to import, e.g. '../other.py'.
                        Default: 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
                        Number of concurrent Locust users. Only used together
                        with --headless
  -r HATCH_RATE, --hatch-rate HATCH_RATE
                        The rate per second in which users are spawned. Only
                        used together with --headless
  -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
  -l, --list            Show list of possible User classes and exit

Web UI options:
  --web-host WEB_HOST   Host to bind the web interface to. Defaults to '*'
                        (all interfaces)
  --web-port WEB_PORT, -P WEB_PORT
                        Port on which to run web host
  --headless            Disable the web interface, and instead start the load
                        test immediately. Requires -u and -t to be specified.
  --web-auth WEB_AUTH   Turn on Basic Auth for the web interface. Should be
                        supplied in the following format: username:password
  --tls-cert TLS_CERT   Optional path to TLS certificate to use to serve over
                        HTTPS
  --tls-key TLS_KEY     Optional path to TLS private key to use to serve over
                        HTTPS

Master options:
  Options for running a Locust Master node when running Locust distributed. A Master node need Worker nodes that connect to it before it can run load tests.

  --master              Set locust to run in distributed mode with this
                        process as master
  --master-bind-host MASTER_BIND_HOST
                        Interfaces (hostname, ip) that locust master should
                        bind to. Only used when running with --master.
                        Defaults to * (all available interfaces).
  --master-bind-port MASTER_BIND_PORT
                        Port that locust master should bind to. Only used when
                        running with --master. Defaults to 5557.
  --expect-workers EXPECT_WORKERS
                        How many workers master should expect to connect
                        before starting the test (only when --headless used).

Worker options:

  Options for running a Locust Worker node when running Locust distributed.
  Only the LOCUSTFILE (-f option) need to be specified when starting a Worker, since other options such as -u, -r, -t are specified on the Master node.

  --worker              Set locust to run in distributed mode with this
                        process as worker
  --master-host MASTER_NODE_HOST
                        Host or IP address of locust master for distributed
                        load testing. Only used when running with --worker.
                        Defaults to 127.0.0.1.
  --master-port MASTER_NODE_PORT
                        The port to connect to that is used by the locust
                        master for distributed load testing. Only used when
                        running with --worker. Defaults to 5557.

Tag options:
  Locust tasks can be tagged using the @tag decorator. These options let specify which tasks to include or exclude during a test.

  -T [TAG [TAG ...]], --tags [TAG [TAG ...]]
                        List of tags to include in the test, so only tasks
                        with any matching tags will be executed
  -E [TAG [TAG ...]], --exclude-tags [TAG [TAG ...]]
                        List of tags to exclude from the test, so only tasks
                        with no matching tags will be executed

Request statistics options:
  --csv CSV_PREFIX      Store current request stats to files in CSV format.
                        Setting this option will generate three files:
                        [CSV_PREFIX]_stats.csv, [CSV_PREFIX]_stats_history.csv
                        and [CSV_PREFIX]_failures.csv
  --csv-full-history    Store each stats entry in CSV format to
                        _stats_history.csv file
  --print-stats         Print stats in the console
  --only-summary        Only print the summary stats
  --reset-stats         Reset statistics once hatching has been completed.
                        Should be set on both master and workers when running
                        in distributed mode

Logging options:
  --skip-log-setup      Disable Locust's logging setup. Instead, the
                        configuration is provided by the Locust test or Python
                        defaults.
  --loglevel LOGLEVEL, -L LOGLEVEL
                        Choose between DEBUG/INFO/WARNING/ERROR/CRITICAL.
                        Default is INFO.
  --logfile LOGFILE     Path to log file. If not set, log will go to
                        stdout/stderr

Step load options:
  --step-load           Enable Step Load mode to monitor how performance
                        metrics varies when user load increases. Requires
                        --step-users and --step-time to be specified.
  --step-users STEP_USERS
                        User count to increase by step in Step Load mode. Only
                        used together with --step-load
  --step-time STEP_TIME
                        Step duration in Step Load mode, e.g. (300s, 20m, 3h,
                        1h30m, etc.). Only used together with --step-load

Other options:
  --show-task-ratio     Print table of the User classes' task execution ratio
  --show-task-ratio-json
                        Print json data of the User classes' task execution
                        ratio
  --version, -V         Show program's version number and exit
  --exit-code-on-error EXIT_CODE_ON_ERROR
                        Sets the process exit code to use when a test result
                        contain any failure or error
  -s STOP_TIMEOUT, --stop-timeout STOP_TIMEOUT
                        Number of seconds to wait for a simulated user to
                        complete any executing task before exiting. Default is
                        to terminate immediately. This parameter only needs to
                        be specified for the master process when running
                        Locust distributed.

User classes:
  UserClass             Optionally specify which User classes that should be
                        used (available User classes can be listed with -l or
                        --list)

3、代码

(1)  将 Locust 类,重命名为 User, HttpLocust 类,重命名为 HttpUser, TaskSet 类属性 locust 重命名为 user

(2) 移除 Locust 类中的 task_set属性,改用User类中的tasks属性,并且tasks只能是列表,或字典

(3) 增加tag标签,在执行时,可以用 -T  --tags 指定标签执行、-E --exclude-tags排除指定标签执行

(4)可以在继承User类下,直接使用@task装饰器

(5)环境变量

· LOCUST_MASTER 重命名为 LOCUST_MODE_MASTER

· LOCUST_SLAVE 重命名为 LOCUST_MODE_WORKER

· LOCUST_MASTER_PORT 重命名为 LOCUST_MASTER_NODE_PORT

· LOCSUT_MASTER_HOST 重命名为 LOCUST_MASTER_NODE_HOST

· CSVFILEBASE 重命名为 LOCUST_CSV

(6)  分布式中,助攻进程的参数,由 --slave \ expect-slaves 更改为 --worker \ --expect-workers

(7)  移除 Locust.setup、 Locust.teardown、 TaskSet.setup、 TaskSet.teardown,改用 on_test_start、on_test_stop

(8) 顺利类 TaskSequence 和 顺序装饰器@seq_task 全包变更为 SequentialTaskSet。

(9) 无图形模式启动参数,由 --no-web 更改为 --headless

(10)运行数据记录,csv文件,表头发生变化,增加统计,使表头意思更清晰明了

(11)结果写入csv文件的参数 --csv-base-name 被移除

(12)控制台日志,不在用标准输出stdout(或标准错误输出stderr),要输出日志,可以直接用print()进行输出,也可以用logging模块,定义日志

 

 类似资料: