init事件是在每一个 Locust进程开始的时候触发。这个事件机制特别是对分布式的测试需求特别有用。我们可以针对每个worker 进程设置init事件,比如在测试开始触发时,我们需要对每个worker进程拉取全局变量等状态值,类似这种需求使用init事件就比较恰当。以下为根据官方案例改写的。
from locust import events,between,User,task
from locust.runners import MasterRunner
class MyUser(User):
wait_time = between(5,8)
@events.init.add_listener
def on_locust_init(environment,**kwargs):
if isinstance(environment.runner,MasterRunner):
print("I‘m on master node")
else:
print("I‘m on a worker or standalone node")
@task
def task_1(self):
print("it is task1")
@task
def task_2(self):
print("it is task2")
执行以上代码,发现控制台输出信息如下,可以发现我们在本地执行的locust进程时一个worker/standalone node,这是正确的。因为首先肯定不是master node,原因是:
1)我们这里不是分布式测试,你可以理解为单机测试,所以不是master node.
2)Master node是不会模拟任何的虚拟用户的。master node主要是用来展示测试开始时的实时数据展示,承接locust的web interface.
后续系列课程也会详细讲解分布式测试的内容,敬请期待。
[2020-11-26 09:06:41,135] jasondeMacBook-Pro.local/INFO/locust.main: Starting web interface at http://:8089
I‘m on a worker or standalone node
[2020-11-26 09:06:41,144] jasondeMacBook-Pro.local/INFO/locust.main: Starting Locust 1.1.1
[2020-11-26 09:06:47,454] jasondeMacBook-Pro.local/INFO/locust.runners: Hatching and swarming 1 users at the rate 1 users/s (0 users already running)...
[2020-11-26 09:06:47,454] jasondeMacBook-Pro.local/INFO/locust.runners: All users hatched: MyUser: 1 (0 already running)
it is task1
it is task2
it is task1
it is task1
it is task2
it is task1
...
原文:https://blog.51cto.com/13734261/2571559