最近一直在使用Locust進行壓力測試,因此想總結一下學習和實踐的一些成果。Locust官方文檔
版本:
python: 3.*
locust: 0.9.0
1.TaskSet的屬性
按照官方的說法,在TaskSet類中也可以設置min_wait、max_wait等屬性,但是我實驗的時候發(fā)現(xiàn)未起效,所以不建議這種做法。
2.setup和teardown函數(shù)
Locust類和TaskSet類都可以定義setup函數(shù)和teardown函數(shù),用setup和teardown可以做一些準備(如創(chuàng)建一個數(shù)據(jù)庫)和清理環(huán)境(如刪除一個數(shù)據(jù)庫)等等。不同與每次開始任務集都會執(zhí)行的on_start,和每次運行結束時會被被調用的on_stop,setup函數(shù)與teardown函數(shù)都僅執(zhí)行一次,執(zhí)行順序如下:
Locust setup # 第一次啟動Locust的時候執(zhí)行
TaskSet setup # 第一次實例化任務集時執(zhí)行
TaskSet on_start # 每一次開始一個任務時執(zhí)行
TaskSet tasks…
TaskSet on_stop # 點擊頁面stop時,當前所有在執(zhí)行中的TaskSet執(zhí)行
TaskSet teardown # 停止locust運行時執(zhí)行
Locust teardown # 停止locust運行時執(zhí)行
示例如下:
class MyTaskSet(TaskSet):
def setup(self):
print("task set_up")
def on_start(self):
print("start")
@task
def one(self):
print("one")
@task(3)
def two(self):
print("two")
def on_stop(self):
print("stop")
def teardown(self):
print("task tear_down")
class WebSiteUser(HttpLocust):
task_set = MyTaskSet
host = "http://www.baidu.com"
min_wait = 10000
max_wait = 10000
def setup(self):
print("locust set_up")
def teardown(self):
print("locust tear_down")
3.TaskSequence:順序執(zhí)行的TaskSet
如果我們需要執(zhí)行的任務是按照一定順序執(zhí)行的,那么就可以繼承TaskSequence類來實現(xiàn)。示例如下:
class PlayGameTaskSet(TaskSequence):
tasks = [play_one, play_two]
@seq_task(1)
def login(self):
print("login")
@seq_task(2)
@task(5)
def play_game(self):
print("the player is playing game")
@seq_task(3)
@task
def end_game(self):
print("game end")
tips:
- 使用@seq_task指定執(zhí)行順序,如果沒有該注解,默認順序是1;相同的order,會根據(jù)字母順序排序
- 使用@task指定執(zhí)行次數(shù)(?。。。?/strong>,由于不再是隨機選擇任務執(zhí)行,框架會直接使用task的權重作為執(zhí)行次數(shù),如果沒有該注解,默認執(zhí)行1次
- 當順序執(zhí)行完一輪任務后,會重頭開始新一輪的執(zhí)行任務
- 如果方法即沒有@task也沒有@seq_task,那么這個方法就不會被認為是一個task,不會出現(xiàn)在執(zhí)行序列當中
上述示例執(zhí)行情況如下:
