1、關(guān)聯(lián)session
在某些請求中,需要攜帶之前response中提取的參數(shù),常見場景就是session_id。Python中可用通過re正則匹配,對(duì)于返回的html頁面,可用采用lxml庫來定位獲取需要的參數(shù);
from locust import HttpLocust, TaskSet, task
from lxml import etree
class WebsiteTasks(TaskSet):
def get_session(self,html): #關(guān)聯(lián)例子
tages = etree.HTML(html)
return tages.xpath("http://div[@class='btnbox']/input[@name='session']/@value")[0]
2、參數(shù)化
保證并發(fā)測試數(shù)據(jù)唯一性,不循環(huán)取數(shù)據(jù);采用隊(duì)列
from locust import TaskSet, task, HttpLocust
import queue
class UserBehavior(TaskSet):
@task
def test_register(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['username'], data['password']))
payload = {
'username': data['username'],
'password': data['password']
}
self.client.post('/register', data=payload)
class WebsiteUser(HttpLocust):
host = 'http://debugtalk.com'
task_set = UserBehavior
user_data_queue = queue.Queue()
for index in range(100):
data = {
"username": "test%04d" % index,
"password": "pwd%04d" % index,
"email": "test%04d@debugtalk.test" % index,
"phone": "186%08d" % index,
}
user_data_queue.put_nowait(data)
min_wait = 1000
max_wait = 3000
保證并發(fā)測試數(shù)據(jù)唯一性,循環(huán)取數(shù)據(jù);
所有并發(fā)虛擬用戶共享同一份測試數(shù)據(jù),保證并發(fā)虛擬用戶使用的數(shù)據(jù)不重復(fù),并且數(shù)據(jù)可循環(huán)重復(fù)使用;
from locust import TaskSet, task, HttpLocust
import queue
class UserBehavior(TaskSet):
@task
def test_register(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: {0}, pwd: {1}' .format(data['username'], data['password']))
payload = {
'username': data['username'],
'password': data['password']
}
self.client.post('/register', data=payload)
self.locust.user_data_queue.put_nowait(data)
class WebsiteUser(HttpLocust):
host = 'http://debugtalk.com'
task_set = UserBehavior
user_data_queue = queue.Queue()
for index in range(100):
data = {
"username": "test%04d" % index,
"password": "pwd%04d" % index,
"email": "test%04d@debugtalk.test" % index,
"phone": "186%08d" % index,
}
user_data_queue.put_nowait(data)
min_wait = 1000
max_wait = 3000
3、斷言
@task
def all_interface(self):
#豆瓣圖書api為例子
with self.client.get("https://api.douban.com/v2/book/1220562",name="/LhcActivity/GetActConfig",catch_response=True) as response:
assert response.json()['rating']['max']==10 #python斷言對(duì)接口返回值中的max字段進(jìn)行斷言
if response.status_code ==200: #對(duì)http響應(yīng)碼是否200進(jìn)行判斷
response.success()
else:
response.failure("GetActConfig[Failed!]")