locust性能测试的使用
工程目录放在test目录下:test>locusttest>locustfile.py
1.locust入口locustfile.py--------------------------
import os,sys,time sys.path.append(os.path.dirname(os.path.dirname(__file__))) import logging from locust import HttpUser, task, between, events from locusttest.workflowdir.workflow import run_get_account,run_get_hashrate,run_get_market_total class QuickstartUser(HttpUser): wait_time = between(1, 2.5) # 集合用户时间 @task def hello_world(self): start_time = int(time.time()) # 要跑的业务函数 # d = run_get_account() # d = run_get_hashrate() d = run_get_market_total() success = d.get("success") total_time = int((time.time() - start_time) * 1000) if success: events.request_success.fire( request_type= 'http', name= d.get("name"), response_time= total_time, response_length= d.get("response_length") ) else: events.request_failure.fire( request_type='http', name= d.get("name"), response_time=total_time, response_length=d.get("response_length"), exception = d.get("error_msg") ) def on_start(self): logging.info("----------前置操作---------") if __name__=="__main__": os.system("locust -f locusttest/locustfile.py --web-host=127.0.0.1") # 处理日志 # --skip-log-setup # --loglevel DEBUG/INFO/WARNING/ERROR/CRITICAL # --logfile # 命令行运行:locust -f locusttest/locustfile.py --headless -u 1000 -r 100 --host 111 --run-time 10 --stop-timeout 5 # 命令行参数解释: # -u 启动用户数 # -r 每秒创建用户数 # --host 111 配置host 目前用不到,但必填 # --run-time 运行时间 # --stop-timeout <seconds> 超时时间
2.自己组织场景测试流程workflow.py:
# # 随机选取 # colors = ['red','yellow','green','blue','gray','purple','orange'] # x = random.choice(colors) # # 数字随机 # random.randint(10,40) # 10-40之间随机整数 def rfunc(res): if res.status_code ==200: success = True error_msg="" else: success = False error_msg = res.status_code return { "name":"获取账号信息接口", "response_length":int(res.headers['content-length']), "success":success, "error_msg":error_msg } def run_get_account(): data = {'api_key': '80eda59a00ae35c0eb5981b2ce0b7016'} res = account_api.get_account(data) return rfunc(res)
3.requists接口调用,没有用到locust自身的client
get_account.py:
import requests import logging
url=""
param = ""
header = {}
res = send_get(url, param, header)
def send_get(url,param={},header={}): res = requests.get(url, params=param, headers=header) logging.info("*" * 100) logging.info("响应状态码: {0}".format(res.status_code)) logging.info("url地址:{0}".format(res.url)) logging.info("响应内容:{0}".format(res.json())) logging.info("*" * 100) return res
运行有两种方式:
(1)web页面运行:python直接运行locustfile.py这个文件
(2)test目录下命令行运行:locust -f locusttest/locustfile.py --headless -u 1000 -r 100 --host 111 --run-time 10 --stop-timeout 5
命令行参数解释:
-u 启动用户数
-r 每秒创建用户数
--host 111 配置host 目前用不到,但必填
--run-time 运行时间
--stop-timeout <seconds> 超时时间
鸡肉是我的最爱!