【问题标题】:Using locust with pytest将 locust 与 pytest 一起使用
【发布时间】:2021-06-15 10:06:40
【问题描述】:

我正在尝试使用 pytest 运行 locust。我已经创建了这个 python 文件,但它没有显示任何输出。 pytest 不收集测试。如何在 pytest 中使用 locust

from locust import HttpUser, TaskSet, task
class WebsiteTasks(TaskSet):
    def on_start(self):
        self.index()

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

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


class WebsiteUser(HttpUser):
    task = WebsiteTasks
    host = "localhost:5000"
    min_wait = 1000
    max_wait = 5000

当我运行 pytest locust_test.py 这是输出:

================================================================ test session starts ================================================================
platform linux -- Python 3.8.5, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: /home/user/Desktop/testing
collected 0 items                                                                                                                                   

【问题讨论】:

  • 如果您想使用 pytest 驱动 locust 负载测试,我的建议是根本不要这样做。 pytest 用于短期测试。蝗虫用于负载测试。他们不会在一起玩得很好。

标签: python python-3.x testing pytest locust


【解决方案1】:

Pytest 只能查看和运行以某种方式命名的测试(类和函数都必须以“test”开头)。

您要做的是编写一个测试,然后使用Locust as a library 以编程方式启动您的 Locust 测试。

import gevent
from locustfile import WebsiteUser
from locust.env import Environment
from locust.stats import stats_printer, stats_history


def test_locust():
    # setup Environment and Runner
    env = Environment(user_classes=[WebsiteUser])
    env.create_local_runner()

    # start a greenlet that periodically outputs the current stats
    gevent.spawn(stats_printer(env.stats))

    # start a greenlet that save current stats to history
    gevent.spawn(stats_history, env.runner)

    # start the test
    env.runner.start(1, spawn_rate=10)

    # in 60 seconds stop the runner
    gevent.spawn_later(60, lambda: env.runner.quit())

    # wait for the greenlets
    env.runner.greenlet.join()

您可以在退出运行程序之前根据您的通过/失败标准编写测试断言。也许为 lambda 编写一个不同的函数来调用,首先检查 env.stats 的故障和响应时间,然后调用 env.runner.quit() 退出。

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2018-10-13
    • 2016-05-04
    • 1970-01-01
    • 2023-03-02
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    相关资源
    最近更新 更多