locust工具学习笔记(二)-Events事件、test_start和test_stop

1,351 阅读2分钟

 Events事件

locust包含了一个事件类,为不同的事件提供hook,事件处理函数注册该hook,基于event触发处理函数实现事件驱动。

test_start和test_stop事件

如果需要在负载测试开始或者结束后运行一段代码,则可使用test_start和test_stop事件,test_start和test_stop事件只在locust主节点中触发执行。

from locust import events, task, constant, HttpUser
from locust.runners import MasterRunner
​
@events.test_start.add_listener
def on_test_start(**kwargs):
    print("A new test is starting")
​
@events.test_stop.add_listener
def on_test_stop(**kwargs):
    print("A new test is ending")
​
class MyUser(HttpUser):
    wait_time = constant(1)
​
    @events.init.add_listener
    def on_locust_init(environment,**kwargs):
        if isinstance(environment.runner,MasterRunner):  #判断是主节点还是其他工作节点
            print("如果是主节点执行!")
        else:
            print("工作节点或独立节点执行")
    @task
    def task_1(self):
        self.client.get("/")
        print("my task1")

​

init事件的用法

init事件是在每一个 Locust进程开始的时候触发。这个事件机制特别是对分布式的测试需求特别有用。可以针对每个worker 进程设置init事件,比如在测试开始触发时,我们需要对每个worker进程拉取全局变量等状态值,类似这种需求使用init事件就很适合用。

from locust import HttpLocust,events,TaskSet, User, task, constant
from locust.runners import MasterRunner
​
class MyUser(User):
    wait_time = constant(2)
​
    @events.init.add_listener
    def on_locust_init(environment,**kwargs):
        if isinstance(environment.runner,MasterRunner):  #判断是主节点还是其他工作节点
            print("如果是主节点执行!")
        else:
            print("工作节点或独立节点执行")
    @task
    def task_1(self):
        print("my task1")
    @task
    def task_2(self):
        print("my task2")
​
#1、控制台运行输出
E:\PyProject\Learning>locust -f E:\PyProject\Learning\locusti\locustfile_dome5.py
[2021-01-17 15:14:48,348] 910lanmingyong/INFO/locust.main: Starting web interface at http://0.0.0.0:8089 (accepting connections from all network interfaces)
工作节点或独立节点执行
[2021-01-17 15:14:48,367] 910lanmingyong/INFO/locust.main: Starting Locust 1.3.1
[2021-01-17 15:15:41,836] 910lanmingyong/INFO/locust.runners: Spawning 2 users at the rate 1 users/s (0 users already running)...
my task2
[2021-01-17 15:15:42,838] 910lanmingyong/INFO/locust.runners: All users spawned: MyUser: 2 (0 already running)
my task1
my task2
my task2
my task2
my task1
......
#2、控制台运行输出
E:\PyProject\Learning>locust -f E:\PyProject\Learning\locusti\locustfile_dome5.py --master
[2021-01-17 15:18:38,303] 910lanmingyong/INFO/locust.main: Starting web interface at http://0.0.0.0:8089 (accepting connections from all network interfaces)
如果是主节点执行!
[2021-01-17 15:18:38,309] 910lanmingyong/INFO/locust.main: Starting Locust 1.3.1
[2021-01-17 15:18:50,638] 910lanmingyong/WARNING/locust.runners: You are running in distributed mode but have no worker servers connected. Please connect worker
s prior to swarming.
[2021-01-17 15:19:06,476] 910lanmingyong/WARNING/locust.runners: You are running in distributed mode but have no worker servers connected. Please connect worker
s prior to swarming.

HttpUser类

HttpUser是最常用的User。HttpUser类包含一个client属性,用于发出HTTP请求。

from locust import HttpUser, task, between
​
class MyUser(HttpUser):
    wait_time = between(5, 15)
    @task(4)
    def index(self):
        self.client.get("/")
    @task(1)
    def about(self):
        self.client.get("/about/")

client属性/HttpSession

client是HttpSession的一个实例,HttpSession是requests的子类/包装器requests.Session

HttpSession主要是将请求结果报告到Locust中(成功/失败,响应时间,响应长度,名称)。

response = self.client.post("/login", {"username":"testuser", "password":"secret"})
print("Response status code:", response.status_code)
print("Response text:", response.text)
response = self.client.get("/my-profile")

responses

如果HTTP响应代码正常(<400),则请求被视为成功,可以自定义响应结果验证

使用catch_response参数,带有-statement和对response.failure() 将请求标记为失败。

with self.client.get("/", catch_response=True) as response:
    if response.text != "Success":
        response.failure("Got wrong response")
    elif response.elapsed.total_seconds() > 0.5:
        response.failure("Request took too long")

将请求标记为成功,即使响应代码是不正确的

with self.client.get("/does_not_exist/", catch_response=True) as response:
    if response.status_code == 404:
        response.success()

通过引发异常然后将其捕获到with块之外来完全避免记录请求

from locust.exception import RescheduleTask
...
with self.client.get("/does_not_exist/", catch_response=True) as response:
    if response.status_code == 404:
        raise RescheduleTask()

TaskSets(任务集)

TaskSets是一种结构测试等级的网站/系统的方法。

配置文件

可以通过命令行参数设置的任何选项也可以由配置文件格式的配置文件设置。

默认情况下locust会查找~/.locust.conf./locust.conf 文件

也可以通过--confg指定配置文件

$ locust --config=master.conf

master.conf文件

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 = 10m

配置选项列表

命令行环境配置文件描述
-f--locustfileLOCUST_LOCUSTFILElocustfile要导入的Python模块文件,例如'../other.py'。默认值:locustfile
-H--hostLOCUST_HOSThost主机以以下格式加载测试:http : //10.21.32.33
-u--usersLOCUST_USERSusers并发蝗虫用户数。主要与–headless一起使用。可以在测试期间通过输入w,W(生成1,10个用户)和s,S(停止1,10个用户)来更改
-r--spawn-rateLOCUST_SPAWN_RATEspawn-rate产生用户的每秒速率。主要与–headless一起使用
--hatch-rateLOCUST_HATCH_RATEhatch-rate==抑制==
-t--run-timeLOCUST_RUN_TIMErun-time在指定的时间段后停止,例如(300s,20m,3h,1h30m等)。仅与–headless一起使用。默认为永久运行。
--web-hostLOCUST_WEB_HOSTweb-host将Web界面绑定到的主机。默认为“ *”(所有接口)
--web-port-PLOCUST_WEB_PORTweb-port运行虚拟主机的端口
--headlessLOCUST_HEADLESSheadless禁用Web界面,而是立即开始负载测试。需要指定-u和-t。
--headfulLOCUST_HEADFULheadful==抑制==
--web-authLOCUST_WEB_AUTHweb-auth打开Web界面的基本身份验证。应以以下格式提供:username:password
--tls-certLOCUST_TLS_CERTtls-cert用于通过HTTPS服务的TLS证书的可选路径
--tls-keyLOCUST_TLS_KEYtls-key用于通过HTTPS服务的TLS私钥的可选路径
--masterLOCUST_MODE_MASTERmaster将蝗虫设置为以该进程为主机以分布式模式运行
--master-bind-hostLOCUST_MASTER_BIND_HOSTmaster-bind-host蝗虫主机应绑定的接口(主机名,ip)。仅在与–master一起运行时使用。默认为*(所有可用接口)。
--master-bind-portLOCUST_MASTER_BIND_PORTmaster-bind-port蝗虫主应该绑定的端口。仅在与–master一起运行时使用。默认为5557
--expect-workersLOCUST_EXPECT_WORKERSexpect-workers主机在开始测试之前应该期望连接多少工人(仅当使用–headless时)。
--workerLOCUST_MODE_WORKERworker将蝗虫设置为以分布式模式运行,并将此进程作为工作进程
--master-hostLOCUST_MASTER_NODE_HOSTmaster-host用于分布式负载测试的蝗虫主服务器的主机或IP地址。仅在与–worker一起运行时使用。默认为127.0.0.1。
--master-portLOCUST_MASTER_NODE_PORTmaster-port蝗虫主服务器使用与之连接的端口进行分布式负载测试。仅在与–worker一起运行时使用。默认为5557
-T--tagsLOCUST_TAGStags测试中要包含的标签列表,因此仅执行具有任何匹配标签的任务
-E--exclude-tagsLOCUST_EXCLUDE_TAGSexclude-tags要从测试中排除的标签列表,因此仅执行没有匹配标签的任务
--csvLOCUST_CSVcsv将当前请求统计信息以CSV格式存储到文件中。设置此选项将生成三个文件:[CSV_PREFIX] _stats.csv,[CSV_PREFIX] _stats_history.csv和[CSV_PREFIX] _failures.csv
--csv-full-historyLOCUST_CSV_FULL_HISTORYcsv-full-history将每个统计信息条目以CSV格式存储到_stats_history.csv文件中。您还必须指定“ –csv”参数以启用此功能。
--print-statsLOCUST_PRINT_STATSprint-stats在控制台中打印统计信息
--only-summaryLOCUST_ONLY_SUMMARYonly-summary仅打印摘要统计信息
--reset-statsLOCUST_RESET_STATSreset-stats产卵完成后重置统计信息。在分布式模式下运行时,应同时在master和worker上设置
--skip-log-setupLOCUST_SKIP_LOG_SETUPskip-log-setup禁用蝗虫的日志记录设置。而是由Locust测试或Python默认设置提供配置。
--loglevel-LLOCUST_LOGLEVELloglevel在调试/信息/警告/错误/严重之间选择。默认值为INFO。
--logfileLOCUST_LOGFILElogfile日志文件的路径。如果未设置,日志将转到stdout / stderr
--exit-code-on-errorLOCUST_EXIT_CODE_ON_ERRORexit-code-on-error设置流程退出代码以在测试结果包含任何失败或错误时使用
-s--stop-timeoutLOCUST_STOP_TIMEOUTstop-timeout退出之前等待模拟用户完成任何正在执行的任务的秒数。默认为立即终止。运行Locust分布式时,仅需要为主进程指定此参数。

欢迎大家关注我的订阅号,会定期分享一些关于测试相关的文章,有问题也欢迎一起讨论学习!订阅号每一条留言都会回复!