python性能测试工具Locust学习笔记

环境安装:

  • 安装locust:pip install locustio
  • 如果python是较低版本,比如2.7,建议再安装pip install requests[security]

脚本编写:

from locust import HttpLocust, TaskSet, task

class UserOne(TaskSet):

@task(1)
def baidu1(self):
self.client.get("/")
print "get one request is operation"

@task(2)
def baidu2(self):
requestParam = "key=value"
response = self.client.get("/test?"+requestParam)
code = response.json().get("code") 
print response.json()

class UserTwo(TaskSet):
tasks = {UserOne:2}
@task(1)
def leave(self):
print "get three request is operation"


class WebsiteUser(HttpLocust):
task_set = UserOne
min_wait = 100
max_wait = 600
host = "http://test"

参数解析:

  • locust中的所有测试场景都是在taskset和locust两个类的继承子类中进行描述的,其中locust类相当于定义的用户,taskset类相当于用户的具体行为
  • task后的参数表示执行的频率占比,例如本脚本例子中的baidu1占比1/3,baidu2占比2/3

如果想要获取http请求的返回,需要在get请求时增加参数catch_response=True,但是增加后locust不会做任何校验甚至不记录请求事件


 

如果需要自己进行数据校验和请求记录需要自己实现events.request_success.fire和events.request_failure.fire

例如

            code = response.json().get("code")  
            if code == "200":  
                events.request_success.fire(  
                    request_type=response.locust_request_meta["method"],  
                    name=response.locust_request_meta["name"],  
                    response_time=response.locust_request_meta["response_time"],  
                    response_length=response.locust_request_meta["content_size"],  
                )  
            else:  
                events.request_failure.fire(  
                    request_type=response.locust_request_meta["method"],  
                    name=response.locust_request_meta["name"],  
                    response_time=response.locust_request_meta["response_time"],  
                    response_length=response.locust_request_meta["content_size"],  
                    exception="Response Code Error! Code:{0}".format(code)  
                ) 

 


遇到的坑

  • locust里面的client是继承自requests,默认直接重定向,如果对请求返回的cookie有需要解析需求的,需要在请求时增加allow_redirects=False
  • locust里面的同一个def里面的client是循环使用的,类似于cookies是重复使用的,如果想要每次清除cookies进行测试,需要新增cookies.clear()
  • 自己进行结果校验时,获取响应结果,不能用json,因为json数据结构为字典,不能与sting进行转换,不能使用正则校验,只能字段校验,需要进行整包正则校验时,需要使用text

 

转载于:https://www.cnblogs.com/Hawthorn-Garden/p/8428054.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值