1. # -*- coding: utf-8 -*-
2. # @Time : 2021/4/19
3. # @Author : 大海
4.
5. import os
6. from locust import TaskSet, task, events, HttpUser
7. from gevent._semaphore import BoundedSemaphore
8.
9. all_locusts_spawned = BoundedSemaphore()
10. all_locusts_spawned.acquire()
11.
12.
13. def on_hatch_complete(**kwargs):
14. # 创建钩子方法
15. all_locusts_spawned.release()
16.
17.
18. # 挂在到locust钩子函数(所有的Locust示例产生完成时触发)
19. # events.hatch_complete += on_hatch_complete # 1.0之前的写法
20. events.spawning_complete.add_listener(on_hatch_complete) # 1.0之后的写法
21.
22.
23. class TestTask(TaskSet):
24. def on_start(self):
25. """所有任务启动前执行"""
26. all_locusts_spawned.wait()
27. print('所有任务启动前执行')
28.
29. @task(1)
30. def index(self):
31. all_locusts_spawned.wait()
32.
33. url = 'https://www.baidu.com'
34. self.client.get(url)
35. print('index task')
36.
37. @task(1)
38. def login(self):
39. all_locusts_spawned.wait()
40. self.client.get("http://www.baidu.com")
41. print('login task')
42.
43.
44. # class MyUser(HttpLocust): 这是1.0之前写法
45. class MyUser(HttpUser):
46. # task_set = TestTask 这是1.0之前写法
47. tasks = [TestTask]
48. host = "http://www.baidu.com"
49. min_wait = 1000
50. max_wait = 3000
51.
52.
53. if __name__ == '__main__':
54. file_path = os.path.abspath(__file__)
55. os.system(f'locust -f {file_path} --web-host=127.0.0.1')