python locust--HttpLocust

一、 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') 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值