如何使用 PyTest 使用 Locust 执行负载测试? [英] How can I perform Load testing with Locust using PyTest?

查看:111
本文介绍了如何使用 PyTest 使用 Locust 执行负载测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您认为可以使用 PyTest 执行负载测试吗?例如:

What do you think is it possible to perform Load testing using PyTest? For example:

import locust

class UsersTest(locust.TaskSet):

    @locust.seq_task(1)
    def api_get_task(self):
        self.client.get("/api", name="GET /api") # Самое действие

    @locust.seq_task(2)
    def api_post_task(self):
        payload = {"username": "user1", "password": "123456"}
        self.client.post("/api", data=payload, name="POST /api")

class SituationTest(locust.HttpLocust):

    task_set = UsersTest 
    min_wait = 1000 
    max_wait = 2000
    host = "http://127.0.0.1:3000"

这里是 2 个 url 的 2 个简单任务的示例.进入类 UsersTest 我有我的测试用例本身.进入类 SituationTest 我有我的参数.

So here is example of 2 simple tasks for 2 urls. Into class UsersTest I have my test cases itself. Into class SituationTest I have my params.

那么问题是如何将这 2 个类集成到 pytest fixtures 装饰器中并在 test_file.py 和 conftest.py 之间拆分?

So question is how to integrate this 2 classes into pytest fixtures decorators and split it between test_file.py and conftest.py?

推荐答案

一种可能的方法是将单独的 pytest 测试添加为 locust 任务.

One possible way to do this by adding individual pytest tests as a locust task.

如果你的测试很简单并且不使用pytest fixtures,你可以导入所有测试函数(或类)并将它们添加为任务.

If you tests are simple and don't use pytest fixtures, you can import all test functions(or classes) and add them as tasks.

此处介绍了如何以编程方式添加任务.

Here is how you can add a task programmatically.

结果代码就是这种效果.

Resulting code would be something of this effect.

from test_module import test_a
from locust import TaskSet, HttpLocust


class TestTaskSet(TaskSet):
     @task
     def test_task(self):
         self.schedule_task(test_a)


class WebsiteUser(HttpLocust):
    task_set = TestTaskSet

如果您的测试代码使用了 pytest 功能,例如装置、参数化等,您可以使用 pytest.main() 来收集所有测试并将单个测试添加为任务并作为 pytest 测试执行它们.

If your test code uses pytest features like fixtures, parameterization etc., you can use pytest.main() to collect all the tests and add individual tests as tasks and execute them as pytest tests.

例如

import pytest
from locust import TaskSet, HttpLocust, between


class TestCollector:

    def __init__(self):
        self.collected = []

    def pytest_collection_modifyitems(self, items):
        for item in items:
            self.collected.append(item.nodeid)


test_collector = TestCollector()

pytest.main(['tests_dir', '--collect-only'], plugins=[test_collector])


class TestTaskSet(TaskSet):

    @task
    def task_gen(self):
        for test in test_collector.collected:
            self.schedule_task(pytest.main, args=[test])


class WebsiteUser(HttpLocust):
    task_set = TestTaskSet
    wait_time = between(1, 5)

此代码将使单个测试成为蝗虫任务.

This code will make individual tests a locust task.

这篇关于如何使用 PyTest 使用 Locust 执行负载测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆