locust 1.0V+ 批量添加任务

一.接口代码

import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel


class Item(BaseModel):
    a: int = None
    b: int = None


app = FastAPI()


@app.get("/hello1")
async def hello1():
    return 'hello1'


@app.get("/hello2")
async def hello2():
    return 'hello2'


@app.post("/hello3")
async def post_info1(request_data: Item):
    a = request_data.a
    b = request_data.b
    c = int(a) + int(b)
    result = {'a': a, 'b': b, 'a+b': c}
    return result


if __name__ == '__main__':
    uvicorn.run(app=app, host='127.0.0.1', port=8888)

二.locust代码

from locust import TaskSet, HttpUser

"""设置任务,此demo为使用project、environment参数"""
locust_data = {
    "project": "测试项目",
    "environment": "http://127.0.0.1:8888",
    "task_name": "locust_test",
    "task": [
        {"path": "/hello1", "method": "get", "header": {"Content-Type": "text/html"}, "task": 1, "data": ""},
        {"path": "/hello2", "method": "get", "header": {"Content-Type": "text/html"}, "task": 2, "data": ""},
        {"path": "/hello3", "method": "post",
         "header": {"Content-Type": "application/json; charset=utf-8"}, "task": 3,
         "data": {"a": 1, "b": 5}}
    ]
}


class Example:

    def __init__(self, path, method, header, data=None):
        """接口信息"""
        self.path = path
        self.method = method.upper()
        self.header = header
        self.data = data

    def example_test(self, obj):
        """任务模板"""
        if self.method == "GET":
            result = obj.client.get(url=self.path, headers=self.header, params=self.data)
            print(result.text)

        elif self.method == "POST":
            if 'json' in self.header['Content-Type']:
                result = obj.client.post(url=self.path, headers=self.header, json=self.data)
            else:
                result = obj.client.post(url=self.path, headers=self.header, data=self.data)
            print(result.text)
        else:
            print('目前仅支持GET、POST接口,其他接口还在开发中!')


class Task:
    """任务类"""
    pass


class UserBehavior(TaskSet):
    """设置任务"""
    task_name = locust_data['task_name']
    all_data = locust_data['task']
    """通过反射机制循环添加任务"""
    for i in locust_data['task']:
        setattr(Task, task_name + str(all_data.index(i)),
                Example(path=i['path'], method=i['method'], header=i['header'], data=i['data']).example_test)

    """循环设置task权重"""
    tasks = {}
    for i in all_data:
        tasks[getattr(Task, task_name + str(all_data.index(i)))] = i['task']


class WebUser(HttpUser):
    """运行"""
    host = locust_data['environment']
    tasks = [UserBehavior]
    min_wait = 1000
    max_wait = 1000

三.运行

locust -f locust_task.py

在这里插入图片描述
在这里插入图片描述

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页