单接口的locust压测
接口场景:
get接口api地址为/j/review/1431235,传3个参数bookid,number,count.bookid需要通过csv文件获取,number为3位随机数中取,count为从一个递增序列中取值。
脚本实现:
#-*-coding:utf-8-*- from locust import task,HttpLocust,TaskSet import json,random,csv class Userbehave(TaskSet): #计数器 def counter(self,growth,min,max,count): count+=growth if count > max: count=min else: pass return count #读取csv文件 def get_csvdata(self,csv_name): datas=[] with open(csv_name,'r') as csv_file: csv_datas=csv.reader(csv_file) for i in csv_datas: datas.append(i) return datas #读取行 def get_line(self): try: self.data=self.datas[self.csv_line] self.csv_line+=1 except: self.csv_line=0 self.data=self.datas[self.csv_line] #得到headers和parmas def Get_headersAndParams(self): self.params={"bookid":self.data[0],"number":self.number,"count":self.count} self.headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"} def on_start(self): self.number=123 self.count=1 self.min=1 self.max=10 self.growth=2 csv_name="E:\csv_name.csv" self.csv_line=0 self.datas=self.get_csvdata(csv_name) self.get_line() self.Get_headersAndParams() @task def Get(self): with self.client.get('/j/review/1431235',headers=self.headers,params=self.params) as response: self.count=self.counter(self.growth,self.min,self.max,self.count) self.number=random.randint(100,999) self.get_line() self.Get_headersAndParams() if "true" in response.content: response.success() else: response.failure("failed!") class WebsiteUser(HttpLocust): task_set=Userbehave min_wait=0 max_wait=0 host="https://read.douban.com"
数据准备:
bookid借助csv的库去读取存取到数组中,在逐行解析,解析到最后在从头开始;number借助random的randint方法从100,到999中随机取值;count为1到10每次递增2的循环。
脚本编写:
locust依赖requests的包去访问接口,把数据准备好,以字典的方式传入client.get方法的headers和params两个参数。
监听:
借助response.content,判断需要断言的部分是否在响应文本里就可以了.