一、locust 參數化很簡單,引入隊列的概念 queue ,實現方式是將參數推入隊列,測試時依次取出,全部取完后 locust 會自動停止。若是使用參數循環壓測,需要將取出的參數再推入隊尾。
二、斷言用 assert 直接判斷。(可能有些同學覺得 locust 腳本不好調試,並不能像普通 python 代碼一樣調試,這里提供個方法:調試腳本的時候可以在代碼中加入 exit(0) 來結束進程)
下面是一個簡單的例子
from locust import HttpLocust, TaskSet, task, between, events import time,os,queue from locust.exception import LocustError from geventhttpclient import HTTPClient from geventhttpclient.url import URL # 定義用戶行為 class UserTsak(TaskSet): def on_start(self): '''初始化數據''' url = URL('https://10.1.62.133') self.http = HTTPClient(url.host) @task def getHomeInfo(self): try: number = self.locust.q.get() # 推入隊尾 self.locust.q.put(number) start_time = time.time() res = self.http.get("/sz/api2/test/{}".format(number)) data = res.read() end_time = time.time() response_time =int((end_time - start_time)*1000) response_length = len(data) # 設置斷言 assert response_length == 30 if res.status_code == 200: events.request_success.fire(request_type="GET", name="test_success", response_time = response_time, response_length=response_length) except AssertionError: events.request_failure.fire(request_type="GET", name="test_failure", response_time=response_time,response_length=0, exception="斷言錯誤。status_code:{}。接口返回:{}。".format(res.status_code,json.loads(data))) except Exception as e: events.locust_error.fire(locust_instance=UserTsak, exception=e, tb =sys.exc_info()[2]) def on_stop(self): '''銷毀數據''' self.conn.close() class WebsiteUser(HttpLocust): host = 'https://10.1.62.133' task_set = UserTsak wait_time = between(0, 0) # 創建隊列 self.q = queue.Queue() # 將參數推入隊列 for i in range(10000): self.q.put(i)