# -*- coding: utf-8 -*-## file: test_fasthttp# Author: ShunZhe# Date: 2021/7/24import osimport queuefrom locust import TaskSet, constant, task, eventsfrom locust.contrib.fasthttp import FastHttpUserfrom locust.runners import MasterRunner"""1、test_start:开始新的负载测试时在每个节点上触发。如果在测试期间用户数量发生变化,则不会再次触发2、init事件:在初始化 locust,发生在解析locust文件之后,但在测试接口开始之前,分布式执行则每个slave初始化一次3、test_start:当负载测试停止时在每个节点上触发"""ids = queue.Queue()@events.test_start.add_listenerdef on_test_start(**kwargs): print(f'A new test is starting')@events.test_stop.add_listenerdef on_test_stop(**kwargs): print('A new test is ending')@events.init_command_line_parser.add_listenerdef add_user_parser(parser, **kwargs): """自定义locust命令参数""" parser.add_argument( "-fi", "--first_index", help="获取截取列表首索引" "[fc:]", default=0, type=str ) parser.add_argument( "-li", "--last_index", help="获取截取列表末索引" "[:li]", default=0, type=str ) args = parser.parse_args() if args.first_index: os.environ['first_index'] = args.first_index if args.last_index: os.environ['last_index'] = args.last_index@events.init.add_listenerdef on_locust_init(environment, **kwargs): print("当前环境变量first_index为: %s" % os.environ.get('first_index')) print("当前环境变量last_index为: %s" % os.environ.get('last_index')) for i in range(10000)[int(os.environ.get('first_index')): int(os.environ.get('last_index'))]: ids.put_nowait(i) print('初始化测试数据完毕') if isinstance(environment.runner, MasterRunner): print("master节点执行") else: print("worker节点执行")class ApiUser(TaskSet): def on_start(self): """每个虚拟用户运行时触发""" print("---------------测试开始了---------------") def on_stop(self): """每个虚拟用户退出时触发""" print("---------------测试结束了----------------") @task(1) def test_visit_baidu(self): print(f'当前id的值为:{ids.get()}') with self.client.get("/web/users/details", catch_response=True, name='users/details') as response: # print(response) if response.status_code == 401: response.success() else: response.failure('not 401 code')# class UserTest(HttpUser):# host = "https://backend-test.cn"# wait_time = constant(1)## tasks = {ApiUser}class UserTest(FastHttpUser): host = "https://backend-test.cn" wait_time = constant(1) tasks = {ApiUser}if __name__ == "__main__": file_name = os.path.abspath(__file__) os.system("locust -f %s --first_index 10 --last_index 20" % file_name)