Locust 官方文檔 10:將 Locust 作爲庫來使用 3# Full example 完整示例

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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章