說明:目前locust已經升級到1.0,腳本及安裝方式已經發生變化,本文主要以1.0作爲實踐
1、安裝(前提是已經裝了python3)
通用方式:pip install locust
檢查安裝是否成功:locust -h
2、寫腳本(文件名爲:locusttest.py)
其中v1.0版本中不同的點:
1)、HttpLocust 類已經被替換爲 HttpUser,正確的導入:from locust import HttpUser,task,TaskSet
2)、task_set=GetResume 的方式已經被替換,正確的寫法爲:tasks = [GetResume]
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from locust import HttpUser,task,TaskSet
import os
class GetResume(TaskSet):
@task(1) #設置權重值,默認爲1,值越大,優先執行
def get_resume(self):
#如果後臺需要的是json格式,需要加header,否則報415
header = {"Content-Type": "application/json"}
self.client.headers.update(header)
url1 = "/api/resume/getAllResume"
json = {'currPage': '1', 'pageSize': '10', 'mark':'0'}
# 網上是直接把Json的格式填進去,但是在本項目中報400,無法識別數據格式,查看系統報錯才明白需要轉成json對象
req = self.client.post(url1,json = json)
if req.status_code == 200:
print("success")
else:
print("fail")
@task(12)
def get_schedule(self):
header = {"Content-Type": "application/json"}
url2 = "/test/demo.html"
#json = {"currPage": "1", "pageSize": "10"}
self.client.headers.update(header)
req = self.client.get(url2)
print("Response status code:", req.status_code)
assert req.status_code == 200
class websitUser(HttpUser):
tasks = [GetResume]
min_wait = 3000 # 單位爲毫秒
max_wait = 6000 # 單位爲毫秒
if __name__ == "__main__":
os.system("locust -f locusttest.py --web-host=127.0.0.1 --host=http://baidu.com")
3、執行腳本
在cmd中通過:python locusttest.py,啓動後瀏覽器中輸入:http://1270.0.01:8089,訪問圖形界面
可這併發數和啓動時間,點擊啓動執行即可
4、其它配置
1)、啓動方式可以通過--web-host參數啓動多種方式:
--web-host=127.0.0.1
--web-host=localhost
--web-host=XXX.XXX.XXX.XXX(具體的IP地址)
2)、如不通過上述啓動方式,也可以通過命令直接啓動:
locust -f locusttest.py --web-host=127.0.0.1 --host=http://baidu.com
3)、非ui下執行方式:
說明:v1.0版本執行的命令已經有所變化,--no-web -c等命令已經不再使用
locust -f locusttest.py --host=http://baidu.com -u 10 -t 5 --headless