1. # -*- coding: utf-8 -*-#
    2. # file: test_fasthttp
    3. # Author: ShunZhe
    4. # Date: 2021/7/24
    5. import os
    6. import queue
    7. from locust import TaskSet, constant, task, events
    8. from locust.contrib.fasthttp import FastHttpUser
    9. from locust.runners import MasterRunner
    10. """
    11. 1、test_start:开始新的负载测试时在每个节点上触发。如果在测试期间用户数量发生变化,则不会再次触发
    12. 2、init事件:在初始化 locust,发生在解析locust文件之后,但在测试接口开始之前,分布式执行则每个slave初始化一次
    13. 3、test_start:当负载测试停止时在每个节点上触发
    14. """
    15. ids = queue.Queue()
    16. @events.test_start.add_listener
    17. def on_test_start(**kwargs):
    18. print(f'A new test is starting')
    19. @events.test_stop.add_listener
    20. def on_test_stop(**kwargs):
    21. print('A new test is ending')
    22. @events.init_command_line_parser.add_listener
    23. def add_user_parser(parser, **kwargs):
    24. """自定义locust命令参数"""
    25. parser.add_argument(
    26. "-fi",
    27. "--first_index",
    28. help="获取截取列表首索引"
    29. "[fc:]",
    30. default=0,
    31. type=str
    32. )
    33. parser.add_argument(
    34. "-li",
    35. "--last_index",
    36. help="获取截取列表末索引"
    37. "[:li]",
    38. default=0,
    39. type=str
    40. )
    41. args = parser.parse_args()
    42. if args.first_index:
    43. os.environ['first_index'] = args.first_index
    44. if args.last_index:
    45. os.environ['last_index'] = args.last_index
    46. @events.init.add_listener
    47. def on_locust_init(environment, **kwargs):
    48. print("当前环境变量first_index为: %s" % os.environ.get('first_index'))
    49. print("当前环境变量last_index为: %s" % os.environ.get('last_index'))
    50. for i in range(10000)[int(os.environ.get('first_index')): int(os.environ.get('last_index'))]:
    51. ids.put_nowait(i)
    52. print('初始化测试数据完毕')
    53. if isinstance(environment.runner, MasterRunner):
    54. print("master节点执行")
    55. else:
    56. print("worker节点执行")
    57. class ApiUser(TaskSet):
    58. def on_start(self):
    59. """每个虚拟用户运行时触发"""
    60. print("---------------测试开始了---------------")
    61. def on_stop(self):
    62. """每个虚拟用户退出时触发"""
    63. print("---------------测试结束了----------------")
    64. @task(1)
    65. def test_visit_baidu(self):
    66. print(f'当前id的值为:{ids.get()}')
    67. with self.client.get("/web/users/details", catch_response=True, name='users/details') as response:
    68. # print(response)
    69. if response.status_code == 401:
    70. response.success()
    71. else:
    72. response.failure('not 401 code')
    73. # class UserTest(HttpUser):
    74. # host = "https://backend-test.cn"
    75. # wait_time = constant(1)
    76. #
    77. # tasks = {ApiUser}
    78. class UserTest(FastHttpUser):
    79. host = "https://backend-test.cn"
    80. wait_time = constant(1)
    81. tasks = {ApiUser}
    82. if __name__ == "__main__":
    83. file_name = os.path.abspath(__file__)
    84. os.system("locust -f %s --first_index 10 --last_index 20" % file_name)