locust性能测试

109 阅读2分钟
from locust import HttpUser, TaskSet, task, between
from locust.runners import MasterRunner
import time

debug = False


class WebsiteTasks(TaskSet):
    # 定义用户行为
    # def on_start(self):
    #     # 压测任务执行前执行一次 完成一些初始化的工作,例如压测搜索接口必须先登录就把登录逻辑写在这个方法下.
    #     # self.client.post("/login", { "username": "test", "password": "123456" })
    #     self.client.get("/login?key=00d91e8e0cca2b76f515926a36db68f5&phone=13594347817&passwd=123456")
    #
    # # @task(2)
    # def videoCategory(self):
    #     self.client.get("/videoCategory")
    #
    # # @task(1)
    # def videoRecommend(self):
    #     self.client.get("/videoRecommend?id=127398")
    #
    # def todayVideo(self):
    #     self.client.get("/todayVideo")
    #
    # def getJoke(self):
    #     self.client.get("/getJoke?page=1&count=2&type=video")
    #
    # def novelSearchApi(self):
    #     self.client.get("/searchPoetry?name=古风二首%20二")
    #
    # tasks = {videoCategory: 2, videoRecommend: 1, todayVideo: 2, getJoke: 3, novelSearchApi: 2}  # 与装饰器效果一致
    @task(1)
    def index(self):
        res = self.client.get("/index")

        # if res.status_code == 200:
        #     print("index ok "*10)
        # else:
        #     print("index fails*fails " * 10)

    @task(3)
    def about(self):
        res = self.client.get("/about")

        # if res.status_code == 200:
        #     print("about ok"*10)
        # else:
        #     print("about fails" * 10)
        # print(dir(res))
        # print(res.status_code)
        # print(res.text)
        # print(res.url)  # http://127.0.0.1:9876/about


class WebsiteUser(HttpUser):
    # 设置性能测试的参数
    tasks = [WebsiteTasks]
    wait_time = between(1, 3)
    host = "http://127.0.0.1:9876"


"""
启动脚本:
locust -f http_demo.py  (web控制台启动)
locust -f ./load_test.py  --host=https://www.baidu.com
locust 网络监控器的默认端口是 8089
Number of users to simulate 设置模拟用户数。
Hatch rate(users spawned/second) 每秒产生(启动)的虚拟用户数。
Median:中间值,单位毫秒,一半的服务器响应时间低于该值,而另一半高于该值。
RPS=QPS=TPS(多数情况下这三者是一回事 每秒事务数)
noweb 模式启动脚本:
locust -f load_test.py --host=https://www.baidu.com --no-web -c 10 -r 2 -t 1m
-c 设置虚拟用户数。
-r 设置每秒启动虚拟用户数。
-t 设置设置运行时间。
参数解析: reqs/sec:RPS每秒事务数.(大多数时候等同于QPS/TPS)

优点:
LoadRunner 和 Jmeter 这类采用进程和线程的测试工具,都很难在单机上模拟出较高的并发压力。Locust 的并发机制摒弃了进程和线程,采用协程(gevent)的机制。
协程避免了系统级资源调度,由此可以大幅提高单机的并发能力。
"""