我正在尝试使用 pytest 运行 Locust。我已经创建了这个 python 文件,但它没有显示任何输出。 pytest 不收集测试。我如何将 Locust 与 pytest 一起使用
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 只能看到并运行以某种方式命名的测试(类和函数都必须以“test”开头)。
您需要编写一个测试,然后使用 Locust 作为库以编程方式启动 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()
退出。
这个设置怎么样? 它肯定不会与 Locust 的统计数据和摘要交互,但会与 Locust HttpUser 同时执行测试
类 MyUser(HttpUser): 主机 =“MY_HOST_IP:端口”
@task
def run_pytest_tests(self):
result = subprocess.run(
["pytest", "-k", "MY_PYTEST"],
capture_output=True,
text=True,
)
if result.returncode != 0:
print(f"Test failed: {result.stdout}")
else:
print("Test passed")