Locust学习笔记(3) - 一个简单的出库demo
在做一个测试之前,首先需要分析请求的过程,请求参数的信息,返回的信息 完成分析之后,再着手脚本的编写 最后通过Locust并发请求 本文是简单的模拟商品出库的流程,分为3个步骤 1.根据商品的barCode查询商品 2.根据用户的手机号查询用户 3.商品出库 所以实现的过程如下: 1.实现查看商品的请求 2.实现查看会员的请求 3.将前面两个请求的响应里所需要的信息取回来 4.构造销售出库的请求
from locust import HttpLocust, TaskSet, task, between from random import randint import json ''' 步骤: 1.实现查看商品的请求 2.实现查看会员的请求 3.将前面两个请求的响应里所需要的信息取回来 4.构造销售出库的请求 ''' class TestLogin(TaskSet): # 每个虚拟用户都需要执行一次 def on_start(self): self.login_data = [{"username": "user1", "password": "pwd1"}, {"username": "user2", "password": "pwd2"}, {"username": "user3", "password": "pwd3"}] self.ranIndex = randint(0, len(self.login_data) - 1) self.barCodes = ['1001', '1002', '1003'] self.customers = ['22222222', '11111111'] self.doLogin() # 获取给定List中的随机值 def randomValue(self, myList): ranIndex = ranInt(1, 10000) % len(myList) return myList[ranIndex] # 登录 def doLogin(self): print(self.login_data[self.ranIndex]) response = self.client.post("/admin/", data=self.login_data[self.ranIndex], catch_response=Ture) print(response.text) # 断言 if "login-pass" in response.text: response.success() else: response.failure("Can not login!") # 返回随机商品的价格 def getGoods(self): # 请求地址:http://localhost:8080/WoniuSales/sell/barcode # 参数:barcode=1001 body = {'barcode': self.randomValue(self.barCodes)} # response为一个Json对象 response = self.client.post('/WoniuSales/sell/barcode', body) newText = json.loads(response.text) return newText[0]['unitprice'] # 获取会员的信息 def getCustomerInfo(self): # 请求地址:http://localhost:8080/WoniuSales/customer/query # 参数:customerphone=11111111 body = {"customerphone": self.randomValue(self.customers)} response = self.client.post('/WoniuSales/customer/query', body) newText = json.loads(response.text) # python 返回多个值 return newText[0]['customerphone'], newText[0]['credittotal'] # 销售出库的请求 @task def doSell(self): # 请求地址:http://localhost:8080/WoniuSales/sell/summary # 参数:customerphone,paymethod,totalprice,creditratio,creditsum # tickettype,ticketsum,oldcredit price = int(self.getGoods() * 0.78) phone, creditTotal = self.getCustomerInfo() body = { "customerphone": phone, "paymethod": "现金", "totalprice": price, "creditratio": "2.0", "creditsum": price * 2, "tickettype": "无", "ticketsum": "0", "oldcredit": creditTotal } response = self.client.post('/WoniuSales/sell/summary', body, catch_response=True) # 断言(简单断言) if response.text.isdigit(): response.success() else: response.failure("can not sell!!!!!!!!!") class WebSite(HttpLocust): task_set = TestLogin wait_time = between(3, 7)
总结:以上代码可以看出,重点还是在于分析请求的过程和处理response返回的信息。Locust只是提供一个并发的功能。
在调试过程中,可以一个请求一个请求的挨个调试
我走的很慢,但从不后退