我正在考虑将我的多线程python脚本移动到蝗虫。
我的脚本的简单解释是:
当我开始研究蝗虫时,我注意到以自己的特定间隔执行每个任务的唯一方法,我需要为每个任务创建一个任务集。
这提出了如何在任务集之间共享给定生成用户的auth cookie的问题?从长远来看,我还需要在给定的衍生用户的任务集之间共享响应数据,因为它在产生的用户之间不同。
在下面的示例代码中,所有由蝗虫产生的用户共享相同的" storage.cookie"。有没有办法让每个用户保持storage.cookie唯一性,通过蝗虫与给定的衍生用户的所有任务集共享?蝗虫是否报告当前正在执行任务的用户?
from __future__ import print_function
from locust import Locust, TaskSet, task, HttpLocust
import json
def auth(l):
payload = {"username":"some_username","password":"some_password"}
resp = l.client.post('/auth', data = json.dumps(payload))
storage.cookie = # get auth cookie from resp
def do_i_auth(l):
if len(storage.cookie) == 0:
auth(l)
class storage(object):
cookie == ''
class first_call(TaskSet):
def on_start(self):
do_i_auth(self)
@task
def get_api_a(self):
headers = {"Cookie":storage.cookie}
self.client.get('/api_a', headers)
class second_call(TaskSet):
def on_start(self):
do_i_auth(self)
@task
def get_api_b(self):
headers = {"Cookie":storage.cookie}
self.client.get('/api_b', headers)
class api_A(HttpLocust):
task_set = first_call
min_wait = 5000
max_wait = 5000
class api_B(HttpLocust):
task_set = second_call
min_wait = 10000
max_wait = 10000
答案 0 :(得分:1)
您可以尝试让您的授权功能返回cookie并将其分别存储在每个类中。像这样:
from __future__ import print_function
from locust import Locust, TaskSet, task, HttpLocust
import json
def auth(l):
payload = {"username":"some_username","password":"some_password"}
resp = l.client.post('/auth', data = json.dumps(payload))
cookie = # get auth cookie from resp
return cookie
class first_call(TaskSet):
cookie = ""
def on_start(self):
self.cookie = auth(self)
@task
def get_api_a(self):
headers = {"Cookie":self.cookie}
self.client.get('/api_a', headers)
答案 1 :(得分:0)
我认为这里的解决方案是对于每个调用 not 不具有单独的类,而是将这些调用作为方法放在单个类上。这样,您可以将Cookie存储在对象上(通过wrapString
进行引用)。
这对我有用:
https://gist.github.com/MatrixManAtYrService/1d83abd54adc9d4181f9ebb98b9799f7
答案 2 :(得分:0)
我最近在DotNet应用程序负载测试脚本中实现了cookie。
应该使用字典对象传递Cookie。
cookiedict={}
cookiedict['Key1'] = 'Value1'
cookiedict['Key2'] = 'Value2'
#Auth API
self.auth_response = self.gettoken(cookiedict)
self.token = self.auth_response.cookies['RequestVerificationToken']
self.cookies = self.auth_response.cookies
#Login API
cookiedict['RequestVerificationToken'] = self.token
`
self.login_response=self.login(self.user_name,self.password,self.token,cookiedict)
还请注意,您还需要使用HttpSession
from locust.clients import HttpSession
self.requests = HttpSession(consumer_cfg.rest_api_url)
executor = self.requests.post
if method == 'PUT':
executor = self.requests.put
elif method == 'GET':
executor = self.requests.get
self._request_proceed(method='GET', url=url, data=formdata,catch_response=catch_response, cookies = CookiesSent,allow_redirects = True)