Locust實例
以下是一個簡單的locustfile.py的一個簡單例子
from locust import HttpLocust, TaskSet
def login(l):
l.client.post("/login", {"username":"ellen_key", "password":"education"})
def index(l):
l.client.get("/")
def profile(l):
l.client.get("/profile")
class UserBehavior(TaskSet):
tasks = {index: 2, profile: 1}
def on_start(self):
login(self)
class WebsiteUser(HttpLocust):
task_set = UserBehavior
min_wait = 5000
max_wait = 9000
這裏定義了一個Locust任務,裏面定義了兩個類,一個UserBehavior類,用於定義測試業務,一個WebsiteUser類,用於定義模擬用戶,我們定義一個模擬用戶在執行任務之間應該等待多長時間
另外一種簡單的方法,用@task 構造器。上面是隨機執行,下面這個是順序執行
from locust import HttpLocust, TaskSet, task
class UserBehavior(TaskSet):
def on_start(self):
""" on_start is called when a Locust start before any task is scheduled """
self.login()
def login(self):
self.client.post("/login", {"username":"ellen_key", "password":"education"})
@task(2)
def index(self):
self.client.get("/")
@task(1)
def profile(self):
self.client.get("/profile")
class WebsiteUser(HttpLocust):
task_set = UserBehavior
min_wait = 5000
max_wait = 9000
啓動Locust
如果locustfile.py位於當前工作目錄中,我們可以運行:
locust --host=http://example.com
如果Locust文件位於與locustfile.py不同的子目錄下,請使用-f以下命令指定:
locust -f locust_files/my_locust_file.py --host=http://example.com
分佈式啓動Locust
主進程:
locust -f locust_files/my_locust_file.py --master --host=http://example.com
子進程
locust -f locust_files/my_locust_file.py --slave --host=http://example.com
如果要在多臺機器上運行Locust,我們還需要在啓動從機時指定主機(在主機默認爲127.0.0.1時,在單臺機器上運行Locust時不需要):
locust -f locust_files/my_locust_file.py --slave --master-host=192.168.0.100 --host=http://example.com
打開Locust的Web界面
您使用上述命令行啓動了蝗蟲,您可以打開瀏覽器並輸入網址http://127.0.0.1:8089(如果您在本地運行Locust),如下界面:
第一行Number of users to simulate是模擬用戶的數量(虛擬用戶數),第二行Hatch rate (users spawned/second)表示產生模擬用戶的速度,填寫完成後點擊“Start swarming”即可開始測試