一、 HttpLocust简介
为了方便http请求,我们可以使用HttpLocust,该类继承Locust,具有client类属性,client发送请求时可以带上session。如下源代码可以看出client是HttpSession的实例化对象。
class HttpLocust(Locust):
"""
Represents an HTTP "user" which is to be hatched and attack the system that is to be load tested.
The behaviour of this user is defined by the task_set attribute, which should point to a
:py:class:`TaskSet <locust.core.TaskSet>` class.
This class creates a *client* attribute on instantiation which is an HTTP client with support
for keeping a user session between requests.
"""
client = None
"""
Instance of HttpSession that is created upon instantiation of Locust.
The client support cookies, and therefore keeps the session between HTTP requests.
"""
def __init__(self):
super(HttpLocust, self).__init__()
if self.host is None:
raise LocustError("You must specify the base host. Either in the host attribute in the Locust class, or on the command line using the --host option.")
self.client = HttpSession(base_url=self.host)
HttpSession继承requests.Session,所有我们可以使用client发送GET、POST等请求。
二、使用HttpLocust
from locust import TaskSet, task, HttpLocust
class MyTaskSet(TaskSet):
@task
def index(self):
res = self.client.get('/')
print(res.status_code)
print(res.text)
pass
class MyHttpLocust(HttpLocust):
task_set = MyTaskSet
max_wait = 10000
min_wait = 5000
注意:
1、在TaskSet中可以直接使用self.client,因为TaskSet有client属性,返回的是Locust.client。
2、client运行时是safe mode,将不会抛出异常,如果http请求超时、错误等时,将会返回一个None的Response且status code=0,locust在统计结果时该请求会统计到失败中。
三、手动判断返回结果
大多数情况下我们判断请求成功的status code都是2XX,但是有些情况下在发生我们需要手动判断请求时成功还是失败,比如访问404页面、或者干脆有些请求在发生错误的情况下返回200。如下所示:
from locust import TaskSet, task, HttpLocust
class MyTaskSet(TaskSet):
@task
def index(self):
with self.client.get("/", catch_response=True) as response:
if response.content != b"Success":
response.failure("Got wrong response")
@task
def not_exist(self):
with self.client.get('/not_exsit_page', catch_response=True) as res:
if res.status_code == 404:
res.sucess()
class MyHttpLocust(HttpLocust):
task_set = MyTaskSet
max_wait = 10000
min_wait = 5000
四、动态参数
在我们日常测试过程中,很多请求的参数都是动态的,我们可以使用locust发送动态参数的请求,我们可以使用name参数统计该接口的请求结果,如下:
@task
def search(self):
"""统计的时候搜索的页码请求都将在search中"""
for num in range(1, 10):
self.client.get('/search?page=%s' % num, name='search')