在压测HTTP服务时常常需要在请求前设置headers字段,其中Cookie虽然是Header字段但是在Grinder里面必须要单独由CookieModule来设置,直接在Header里设置Cookie是不会生效的。需要指出的是Cookie的域名必须和GET的url中的域名完全相同,否则Cookie设置不会生效。以下是一个完整的示例。Grinder的配置可参考分布式压测工具Grinder的Hello World示例教程
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest, HTTPPluginControl
from HTTPClient import Cookie, CookieModule, CookiePolicyHandler
from HTTPClient import NVPair
from java.util import Date
import random
import string
log = grinder.logger.info
test1 = Test(1, "GET with headers")
request1 = HTTPRequest()
test1.record(request1)
class TestRunner:
def __call__(self):
domain = 'test.pengpengzhou.com'
port = '8080'
cookieValue = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(15)])
# Now let's add a new cookie.
threadContext = HTTPPluginControl.getThreadHTTPClientContext()
expiryDate = Date()
expiryDate.year += 10
cookie = Cookie("ckid", cookieValue , domain , "/", expiryDate, 0)
CookieModule.addCookie(cookie, threadContext)
uid = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(12)])
url = ''.join(["http://", domain , ":", port, "/htest?uid=",uid])
headersGet = ( NVPair('Accept-Language', 'en-us,en;q=0.5'), NVPair('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0'), )
request1.setHeaders(headersGet)
result = request1.GET(url)