本篇文章,从局部出发,利用一个简单的测试,来讲明场景模拟的wait_time属性的用法。wait_time为何要单独拎出来说,是由于它主要有两种模式,而初学者对这两种模式,容易混淆。python
1)
app
wait_time = constant(3) wait_time = between(5,15)
第一种模式,能够使用以上2种模式,他们的用法都是一致的,都是当任务完成以后,停顿3秒或者是5-15秒之间选择一个停顿的时间做为停顿的时间。其两种方式的源码以下:dom
def between(min_wait, max_wait): """ Returns a function that will return a random number between min_wait and max_wait. Example:: class MyUser(User): # wait between 3.0 and 10.5 seconds after each task wait_time = between(3.0, 10.5) """ return lambda instance: min_wait + random.random() * (max_wait - min_wait)
def constant(wait_time): """ Returns a function that just returns the number specified by the wait_time argument Example:: class MyUser(User): wait_time = constant(3) """ return lambda instance: wait_time
第二种模式,以下:ide
wait_time = constant_pacing(1)
和第一种模式就有很大的不一样了。它是计时性的,也就是每1秒钟触发执行一次任务,而无论任务有没有执行完。源码以下:性能
def constant_pacing(wait_time): """ Returns a function that will track the run time of the tasks, and for each time it's called it will return a wait time that will try to make the total time between task execution equal to the time specified by the wait_time argument. In the following example the task will always be executed once every second, no matter the task execution time:: class MyUser(User): wait_time = constant_pacing(1) @task def my_task(self): time.sleep(random.random()) If a task execution exceeds the specified wait_time, the wait will be 0 before starting the next task. """因此你们能够在实际的工做中根据需求来自行选择。可是前提是你们要对这些选项和用法掌握,避免不清楚而致使工做失误。
下面是一个简单的locust file 代码讲解,算是一个很基础的一个入门。
测试
from locust import User, task,between,constant,constant_pacing class MyUser(User): @task def my_task(self): print("executing my_task") #wait_time = between(5,15) #wait_time = constant(3) wait_time = constant_pacing(1)
说明:spa
line 1: 导入相关的包。code
line 3: 定义一个用户类MyUser,这个类要继承Locust User类继承
line 5: 定义一个任务方法ci
line 4: 添加@task 修饰符, 若是不添加,那么任务方法就不会被执行。
line 7/8/9:是上面已经讲过的,关于wait_time属性的设置,有2大类方式,这里就再也不赘述。
若是安装以上的场景定义,那么执行的结果就是,每隔1秒钟就会执行1次my_task任务。
你们也能够扫描并关注以下公众号“TimTest”,会有更多性能测试相关内容分享。