Locust 官方文档 10:将 Locust 作为库来使用

2021-02-02  本文已影响0人  猫与测试

It’s possible to use Locust as a library, instead of running Locust using the locust command.

将 Locust 作为 Python 的一个三方库,通过 Python 代码运行,代替命令行的方式。

To run Locust as a library you need to create an Environment instance:

通过 Python 代码来运行,你需要创建 Environment 的实例:

from locust.env import Environment

env = Environment(user_classes=[MyTestUser])

The Environment instance’s create_local_runner, create_master_runner or create_worker_runner can then be used to start a Runner instance, which can be used to start a load test:

Environment 实例中的 Runner 用来使用不同的方式启动负载测试,分别为 create_local_runner, create_master_runnercreate_worker_runner

env.create_local_runner()
env.runner.start(5000, hatch_rate=20)
env.runner.greenlet.join()

We could also use the Environment instance’s create_web_ui method to start a Web UI that can be used to view the stats, and to control the runner (e.g. start and stop load tests):

也可以使用 Environment 实例中的 create_web_ui 方法来启动 web UI 以便控制运行(启动或停止负载测试)和查看统计信息:

env.create_local_runner()
env.create_web_ui()
env.web_ui.greenlet.join()

3# Full example 完整示例

import gevent
from locust import HttpUser, task, between
from locust.env import Environment
from locust.stats import stats_printer
from locust.log import setup_logging

setup_logging("INFO", None)


class User(HttpUser):
    wait_time = between(1, 3)
    host = "https://docs.locust.io"

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

    @task
    def task_404(self):
        self.client.get("/non-existing-path")

# setup Environment and Runner
# 设置 Environment 和 Runner
env = Environment(user_classes=[User])
env.create_local_runner()

# start a WebUI instance
# 启动 WebUI 实例
env.create_web_ui("127.0.0.1", 8089)

# start a greenlet that periodically outputs the current stats
# 启动 greenlet 定期输出当前的统计信息
gevent.spawn(stats_printer(env.stats))

# start the test
# 启动负载测试
env.runner.start(1, hatch_rate=10)

# in 60 seconds stop the runner
# 运行 60s 后停止运行
gevent.spawn_later(60, lambda: env.runner.quit())

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

# stop the web server for good measures
# 采取良好的措施停止 web server
env.web_ui.stop()
上一篇下一篇

猜你喜欢

热点阅读