【Locust】 Locust 高级用法

前言

前文说了locust的基础使用,本文介绍一些高阶的用法(注意Locust的基线版本是1.0以上。),主要有:  1. FastHttpUser ,HttpUser 的区别。 2. Locust里面如何使用集合点的概念 。 3. Locust 的非WEB运行 。 4. Locust的主从执行

快速执行模式-FastHttpUser

一直以来,locust方便快捷进行性能测试是它的优势, 但是它的压测能力一直是被质疑的,包括很多大佬使用go作为客户端去改写了Locust的内核施压client。

最新版本里面locust可以调用FastHttpUser模式,将极大提高Locust的并发能力(实测,能力不弱于go-client),如下几点是需要注意的:

1. Locust的施压原理是基于用户,主要是用到了CPU,而不是jmeter的多进程、线程的模式(用的是内存),所以比较机器的内存消耗、CPU消耗没意义。

2. 单机并发能力来看, Locust的快速模式,在我的window系统,i5的CPU机器上,实测最高并发能达到4800/秒,远高于jmeter (找一台高性能服务器,给jmeter配置8-16G内存,然后进程设置到3000一般就有压力,或者快拉满了)

用法[注意发请求要用path, 低速模式是url]:

class TestList(TaskSet):
   @task(5)
    def list_***(self):
        api = '/****/Get'
        params = '?Id=69810'
        url = api+params
        with self.client.get(path=url, headers=self.header, catch_response=True,
                             name="/****/Get") as res:
            # print(res)
            if res.status_code != 200:
                res.failure("Case Failed")

class WebsiteUser(FastHttpUser):
    def setup(self):
        print('locust setup')

    def teardown(self):
        print('locust teardown')

    tasks = [TestList]
    min_wait = 200  # 毫秒
    max_wait = 6000  # 毫秒
    # stop_timeout = 60  # 单位秒,运行时间
    host = 'https://****.cn'

Locust 集合点

使用Locust的时候,很多测试人员需要的一个功能是类似loadrunner里面的集合点概念,例如可以在施压之前能设置或者初始化一系列参数或者执行一些准备步骤。

setup只能满足当前文件,跨文件或者项目的时候不可用。那么在Locust里面如何设置呢?

用法【巧用Locust里面的spawned概念,设置集合点。】

all_locusts_spawned = Semaphore()
all_locusts_spawned.acquire()
from locust.exception import RescheduleTask

def on_hatch_complete(**kwargs):
     all_locusts_spawned.release()


events.hatch_complete += on_hatch_complete
env = get_env()
class TestList(TaskSet):
    def on_start(self):
        """ on_start is called when a Locust start before any task is scheduled
            所有压测的task执行之前等待登录完成
        """
     # 你的集合任务放在这里。 
all_locusts_spawned.wait() # 集合点等待,可以设置多个

Locust 执行阶梯式压测

阶梯式压测是Jmeter里面非常好用的一种功能,场景是: 从50并发开始,每过XX秒,自动增加50并发,一直到300并发量。 这样能很好的看出在不同施压过程中的被测项目能力并进行对比。

是一种非常常见的测试人员设计方案,那么用Locust如何实现呢?

用法:

run_time_list = [50, 100, 120, 180, 220, 300, 350, 430, 550]
    for run_time in run_time_list:
        if run_time < 600:
            user_count = round(run_time, -2)
            os.system('locust -f locustfile.py --headless --csv=example -u {} -r 20 -t 30s'.format(user_count))

Locust 一些常用的执行方式

由于某些原因,主从不能用Master-Slaver模式了,而是  master-worker

[locust 主从]
locust -f my_locustfile.py --worker --master-host=192.168.0.1 --master-port=5432
locust -f my_locustfile.py --master --master-bind-host=192.168.0.1 --master-bind-port=5432


NO WEB模式: locust -f collection.py --headless --csv=example -u 2 -r 2 -t 30s
原文地址:https://www.cnblogs.com/Ronaldo-HD/p/14569162.html