Locust简单使用

2019-10-09  本文已影响0人  mah93

简介

Locust 是一个开源负载测试工具。使用python代码定义用户行为,也可以仿真百万个用户。

Locust 是非常简单易用,分布式,用户负载测试工具。Locust 主要为网站或者其他系统进行负载测试,能测试出一个系统可以并发处理多少用户。

Locust 是完全基于时间的,因此单个机器支持几千个并发用户。相比其他许多事件驱动的应用,Locust 不使用回调,而是使用轻量级的处理方式gevent。

特点

安装

安装Python

安装Python2 或Python3,通过命令行或者是官网安装

安装Locust

通过pip命令安装

 pip  install --index https://pypi.mirrors.ustc.edu.cn/simple/ locust

安装完成后,命令行中验证

locust --help

使用

创建test.py

创建一个test.py,然后编辑

from locust import HttpLocust, TaskSet, task

class WebsiteTasks(TaskSet):
    def on_start(self):
        pass
        
    @task(1)
    def index(self):
        self.client.post("/login", {
            "username": "test_user",
            "password": ""
        })

    @task(1)
    def index(self):
        self.client.get("/")

    @task(1)
    def about(self):
        self.client.get("/about/")

class WebsiteUser(HttpLocust):
    task_set = WebsiteTasks
    min_wait = 5000
    max_wait = 15000

task_set:任务指定的方法

min_wait:最小等待时间(ms)

max_ wait:最大等待时间(ms)

on_start:会首先执行该方法

@task(1):单个任务(权重)

每次执行任务,会在最小等待时间到最大等待时间中随机执行,按照task的权重执行某一任务

自定义成功失败

locust会根据一次请求的状态码来确定该次请求是否成功,并表现在界面上。

当需要测试的接口,涉及到业务。就需要根据返回的数据来判断该次请求是否成功

需要将post请求改成以下方式:

with self.client.post("/login", {"username": "test_user","password": "123"}) as response:
        response.success('success')//成功
        response.failure('error')//失败

运行

编辑完test.py之后,在命令行中输入

locust -f ./test.py --host=你的服务器地址

没有报错之后,打开本地8089端口,即可看到locust的测试页面

locust.png

输入所需测试强度,即可开始测试。

上一篇 下一篇

猜你喜欢

热点阅读