Locust 脚本练习
1、循环取数据,数据可重复使用
e.g. 模拟5个用户并发请求网页,总共有6个URL地址,每个虚拟用户都会依次循环加载这6个URL地址;
from locust import TaskSet, task, HttpLocust class UserBehavior(TaskSet): def on_start(self): self.index = 0 @task def test_visit(self): url = self.locust.share_data[self.index] print('visiting -- url: %s' % url) self.index = (self.index + 1) % len(self.locust.share_data) self.client.get(url,verify=False) class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait = 1000 max_wait = 3000 share_data = ['url1', 'url2', 'url3', 'url4', 'url5','url6'] host = 'https://172.1.1.1/'
2、保证并发测试数据唯一性,不循环取数据
e.g. 模拟5用户并发注册账号,总共有个100账号,要求注册账号不重复,注册完毕后结束测试;
from locust import TaskSet, task, HttpLocust from Queue import Queue class UserBehavior(TaskSet): @task def on_start(self): try: data = self.locust.user_data_queue.get() except Queue.Empty(): print('account data run out, test ended.') exit(0) print('register with user: {}, pwd: {}'.format(data['account'], data['password'])) payload = { 'account': data['account'], 'password': data['password'] } self.client.post('/register', data=payload,verify = False) class WebsiteUser(HttpLocust): task_set = UserBehavior user_data_queue = Queue() for index in range(100): data = { "account": "test%04d" % index, "password": "pwd%04d" % index, } user_data_queue.put_nowait(data) min_wait = 1000 max_wait = 3000
3、保证并发测试数据唯一性,循环取数据
e.g 模拟5用户并发登录账号,总共有100个账号,要求并发登录账号不相同,但数据可循环使用。
from locust import TaskSet, task, HttpLocust
from Queue import Queue class UserBehavior(TaskSet): @task def on_start(self): try: data = self.locust.user_data_queue.get() except Queue.Empty(): print('account data run out, test ended.') exit(0) print('register with user: {}, pwd: {}'.format(data['account'], data['password'])) payload = { 'account': data['account'], 'password': data['password'] } self.client.post('/register', data=payload,verify = False) self.locust.user_data_queue.put_nowait(data) class WebsiteUser(HttpLocust): task_set = UserBehavior user_data_queue = Queue() for index in range(100): data = { "account": "test%04d" % index, "password": "pwd%04d" % index, } user_data_queue.put_nowait(data) min_wait = 1000 max_wait = 3000
该种场景的实现方式与上一种场景基本相同,唯一的差异在于,每次使用完数据后,需要再将数据放入队列中。