def __call__(self): # The cache of cookies for each worker thread will be reset at # the start of each run. result = request1.GET("http://localhost:7001/console/?request1") # If the first response set any cookies for the domain, # they willl be sent back with this request. result2 = request1.GET("http://localhost:7001/console/?request2") # Now let's add a new cookie. threadContext = HTTPPluginControl.getThreadHTTPClientContext() expiryDate = Date() expiryDate.year += 10 cookie = Cookie("key", "value","localhost", "/", expiryDate, 0) CookieModule.addCookie(cookie, threadContext) result = request1.GET("http://localhost:7001/console/?request3") # Get all cookies for the current thread and write them to the log cookies = CookieModule.listAllCookies(threadContext) for c in cookies: log("retrieved cookie: %s" % c) # Remove any cookie that isn't ours. for c in cookies: if c != cookie: CookieModule.removeCookie(c, threadContext) result = request1.GET("http://localhost:7001/console/?request4")
def __call__(self): # The cache of cookies for each worker thread will be reset at # the start of each run. result = request1.GET("http://localhost:7001/console/?request1") # If the first response set any cookies for the domain, # they willl be sent back with this request. result2 = request1.GET("http://localhost:7001/console/?request2") # Now let's add a new cookie. threadContext = HTTPPluginControl.getThreadHTTPClientContext() expiryDate = Date() expiryDate.year += 10 cookie = Cookie("key", "value", "localhost", "/", expiryDate, 0) CookieModule.addCookie(cookie, threadContext) result = request1.GET("http://localhost:7001/console/?request3") # Get all cookies for the current thread and write them to the log cookies = CookieModule.listAllCookies(threadContext) for c in cookies: log("retrieved cookie: %s" % c) # Remove any cookie that isn't ours. for c in cookies: if c != cookie: CookieModule.removeCookie(c, threadContext) result = request1.GET("http://localhost:7001/console/?request4")
def __call__(self): sumStatusCode = [0L, 0L, 0L, 0L] for c in self.login_cookies: CookieModule.addCookie(c, self.threadContext) PTS.sumHttpCode(tenant(), sumStatusCode) if sum(sumStatusCode[1:4]) > 0: grinder.statistics.forLastTest.success = 0 grinder.logger.error(u'事务请求中http 返回状态大于300,请检查请求是否正确!') else: grinder.statistics.forLastTest.success = 1
def __init__(self): # Login URL request = HTTPRequest(url="https://login.site.com") ##### reset to the all cookies ##### threadContext = HTTPPluginControl.getThreadHTTPClientContext() self.cookies = CookieModule.listAllCookies(threadContext) for c in self.cookies: CookieModule.removeCookie(c, threadContext) # do login request.POST("/login/do", ( NVPair("id", "my_id"),NVPair("pw", "my_passwd"))); ##### save to the login info in cookies ##### self.cookies = CookieModule.listAllCookies(threadContext)
def getCSRF(): threadContext = HTTPPluginControl.getThreadHTTPClientContext() CookieModule.discardAllCookies(threadContext) result = request1.GET(linkdrop_host + '/api/account/get') assert result.getStatusCode()==200, result csrf = linkdrop = None for cookie in CookieModule.listAllCookies(threadContext): if cookie.name == "linkdrop": linkdrop = cookie if cookie.name == "csrf": csrf = cookie.value assert csrf and linkdrop return csrf, linkdrop
def doit(self): if linkdrop_static_per_send: for i in range(0,linkdrop_static_per_send): getStatic(linkdrop_static_url) if self.csrf is None or \ (sends_per_oauth and grinder.getRunNumber() % sends_per_oauth==0): self.csrf, self.linkdrop_cookie = getCSRF() self.userid = authService(self.csrf) # cookies are reset by the grinder each test run - re-inject the # linkdrop session cookie. threadContext = HTTPPluginControl.getThreadHTTPClientContext() CookieModule.addCookie(self.linkdrop_cookie, threadContext) send(self.userid, self.csrf)
def getCSRF(): threadContext = HTTPPluginControl.getThreadHTTPClientContext() CookieModule.discardAllCookies(threadContext) result = request1.GET(url0 + '/api/account/get') assert result.getStatusCode() == 200, result csrf = linkdrop = None for cookie in CookieModule.listAllCookies(threadContext): if cookie.name == "linkdrop": linkdrop = cookie if cookie.name == "csrf": csrf = cookie.value assert csrf and linkdrop return csrf, linkdrop
def __call__(self): grinder.statistics.delayReports = 1 ##### Set to the cookies for login ##### threadContext = HTTPPluginControl.getThreadHTTPClientContext() for c in self.cookies: CookieModule.addCookie(c,threadContext) ##### Request with login ##### result = request1.GET("/mypage") if result.text.count("only my content data") < 0: grinder.statistics.forLastTest.success = 0 else : grinder.statistics.forLastTest.success = 1
def setStubbornAuthToken(): threadContext = HTTPPluginControl.getThreadHTTPClientContext() cookies = CookieModule.listAllCookies(threadContext) for cookie in cookies: if cookie.getName() == 'sso.auth_token': CookieModule.removeCookie(cookie, threadContext) expiryDate = Date() expiryDate.year += 10 stubbornAuthToken = StubbornCookie('sso.auth_token', cookie.getValue(), '.wgenhq.net', '/', expiryDate, False) CookieModule.addCookie(stubbornAuthToken, threadContext) grinder.logger.output("Replaced sso.auth_token with a stubborn version of itself")
def doit(self): if linkdrop_static_per_send: for i in range(0,linkdrop_static_per_send): getStatic(linkdrop_static_url) if (sends_per_oauth and grinder.getRunNumber() % sends_per_oauth==0): self.linkdrop_cookie = None self.userid = None if self.userid is None: self.userid, self.linkdrop_cookie = authService() # cookies are reset by the grinder each test run - re-inject the # linkdrop session cookie. threadContext = HTTPPluginControl.getThreadHTTPClientContext() CookieModule.addCookie(self.linkdrop_cookie, threadContext) send(self.userid)
def __call__(self): PTS.Data.delayReports = 1 for c in self.init_cookies: CookieModule.addCookie(c, self.threadContext) # DealUser注册 result = self.registerDealUser() PTS.Framework.setExtraData(result["statusCode"]) dealUserId = result["dealUserId"] accessToken = result["accessToken"] # 开始访问网站 result = self.startAccessSite(dealUserId, accessToken) PTS.Framework.setExtraData(result["statusCode"]) logId = result["logId"] # 循环控制器 for i in range(1, 5): pageNum = str(i) # 开始访问页面 result = self.startViewPage(dealUserId, logId, pageNum, accessToken) PTS.Framework.setExtraData(result["statusCode"]) viewLogId = result["viewLogId"] for j in range(5): # 线程睡眠1秒 PTS.Thread.sleep(5000) # 定时更新页面访问结束时间 statusCode = self.updateViewPageEndTime( dealUserId, logId, pageNum, viewLogId, accessToken) PTS.Framework.setExtraData(statusCode) # 提交关键行为 statusCode = self.submitKeyBehaviour(dealUserId, logId, pageNum, viewLogId, accessToken) PTS.Framework.setExtraData(statusCode) PTS.Data.report() PTS.Data.delayReports = 0
def __call__(self): sumStatusCode = [0L, 0L, 0L, 0L] #因为每次执行测试cookie会被清空,所以这里需要每次重新设置cookie for c in self.login_cookies: CookieModule.addCookie(c, self.threadContext) PTS.sumHttpCode(tenant(), sumStatusCode) # if you want to print out log.. Don't use print keyword. Instead, use following. #grinder.logger.info(str(sumStatusCode)) # statusCode[0]代表http code < 300 个数, statusCode[1] 代表 300<=http code<400 个数 # statusCode[2]代表400<=http code<500个数, statusCode[3] 代表 http code >=500个数 # 如果http code 300 到 400 之间是正常的 # 那么判断事务失败,请将statusCode[1:4] 改为 statusCode[2:4] 即可 if sum(sumStatusCode[1:4]) > 0: grinder.statistics.forLastTest.success = 0 grinder.logger.error(u'事务请求中http 返回状态大于300,请检查请求是否正确!') else: grinder.statistics.forLastTest.success = 1
def __init__(self): grinder.statistics.delayReports = True headers = [ NVPair('Content-Type', 'application/json'), NVPair('Accept', 'application/json'), ] data = '{"email": "*****@*****.**","passwd": "e10adc3949ba59abbe56e057f20f883e"}' result = HTTPRequest().POST( 'https://cmdb.uyuntest.cn/tenant/api/v1/user/login', data, headers) self.threadContext = HTTPPluginControl.getThreadHTTPClientContext() self.login_cookies = CookieModule.listAllCookies(self.threadContext)
def authService(): threadContext = HTTPPluginControl.getThreadHTTPClientContext() CookieModule.discardAllCookies(threadContext) # Call authorize requesting we land back on /account/get - after # a couple of redirects for auth, we should wind up with the data from # account/get - which should now include our account info. result = request1.POST(linkdrop_host + '/api/account/authorize', ( NVPair('domain', linkdrop_service), NVPair('end_point_success', '/api/account/get'), NVPair('end_point_auth_failure', '/current/send/auth.html#oauth_failure'), ), ( NVPair('Content-Type', 'application/x-www-form-urlencoded'), )) assert result.getStatusCode()==200, result data = json_loads(result.getText()) assert data, 'account/get failed to return data' userid = data[0]['accounts'][0]['userid'] for cookie in CookieModule.listAllCookies(threadContext): if cookie.name == "linkdrop": linkdrop_cookie = cookie assert linkdrop_cookie return userid, linkdrop_cookie
def __init__(self): grinder.statistics.delayReports=True headers = [NVPair('Content-Type', 'application/json'),NVPair('Accept', 'application/json'),] login_msg=PTS.get_tenant() lenth=len(login_msg) i=0 grinder.logger.info(login_msg[i][0]) grinder.logger.info(login_msg[i][1]) data= '{"email": "%s", "passwd": "%s", "code": "uyun", "authCode": "YQTxa8TT6tnQ23IOt23YSAqotUw9KgItxqq4gem+n+f4KB5cINEWr4nMMLeTPBaZobmLzsm1nz9wjVm31fFjrQ=="}' % (login_msg[i][0], login_msg[i][1]) grinder.logger.info(data) if i >= lenth-1: i=0 i+=1 result = HTTPRequest().POST('http://10.1.11.254/tenant/api/v1/user/login', data, headers) self.threadContext = HTTPPluginControl.getThreadHTTPClientContext() self.login_cookies = CookieModule.listAllCookies(self.threadContext)
def __init__(self): grinder.statistics.delayReports = True headers = [ NVPair('Content-Type', 'application/json'), NVPair('Accept', 'application/json'), ] #data = '{"email": "*****@*****.**","passwd": "0e7517141fb53f21ee439b355b5a1d0a"}' login_msg = PTS.get_tenant() lenth = len(login_msg) i = 0 #grinder.logger.info(login_msg[i][0]) #grinder.logger.info(login_msg[i][1]) data = '{"email": "%s", "passwd": "%s", "code": "uyun", "authCode": "fd9552d74e7113c7970226443dd4efd4181dd5aa068a8917c6357b6606b6994b"}' % ( login_msg[i][0], login_msg[i][1]) #grinder.logger.info(data) if i >= lenth - 1: i = 0 i += 1 result = HTTPRequest().POST( 'http://10.1.11.254/tenant/api/v1/user/login', data, headers) self.threadContext = HTTPPluginControl.getThreadHTTPClientContext() self.login_cookies = CookieModule.listAllCookies(self.threadContext)
#connection options domain = 'http://test.constellation.tv' screening = 'Wx5rFpEf4S5KLks' time_to_run = 60 films = [ 87 ] film = str(random.choice( films )) # Set up a cookie handler to log all cookies that are sent and received. class MyCookiePolicyHandler(CookiePolicyHandler): def acceptCookie(self, cookie, request, response): return 1 def sendCookie(self, cookie, request): return 1 CookieModule.setCookiePolicyHandler(MyCookiePolicyHandler()) class TestRunner: #decide whether this is a reader or writing thread def __init__(self): tid = grinder.threadNumber #self.testRunnter = self.writer if tid % 4 == 2: self.testRunnter = self.reader else: self.testRunnter = self.writer
# _*_ coding: utf8 _*_ from HTTPClient import NVPair, Cookie, CookieModule, CookiePolicyHandler from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest from net.grinder.script import Test from net.grinder.script.Grinder import grinder from java.util import Date # Set up a cookie handler to log all cookies that are sent and received. class MyCookiePolicyHandler(CookiePolicyHandler): def acceptCookie(self, cookie, request, response): return 1 def sendCookie(self, cookie, request): return 1 CookieModule.setCookiePolicyHandler(MyCookiePolicyHandler()) test1 = Test(1, "checkout home") request1 = test1.wrap(HTTPRequest(url="http://my.site.com")) class TestRunner: def __init__(self): # Login URL request = HTTPRequest(url="https://login.site.com") ##### reset to the all cookies ##### threadContext = HTTPPluginControl.getThreadHTTPClientContext() self.cookies = CookieModule.listAllCookies(threadContext) for c in self.cookies: CookieModule.removeCookie(c, threadContext) # do login request.POST("/login/do", ( NVPair("id", "my_id"),NVPair("pw", "my_passwd"))); ##### save to the login info in cookies ##### self.cookies = CookieModule.listAllCookies(threadContext)
def enableCookieLogging(): CookieModule.setCookiePolicyHandler(MyCookiePolicyHandler())
# The URL of the server we want to hit. url0 = 'http://127.0.0.1:5000' # *sob* - failed to get json packages working. Using 're' is an option, # although it requires you install jython2.5 (which still doesn't have # json builtin) - so to avoid all that complication, hack 'eval' into # working for us... _json_ns = {'null': None} def json_loads(val): return eval(val, _json_ns) CookieModule.setCookiePolicyHandler(None) from net.grinder.plugin.http import HTTPPluginControl HTTPPluginControl.getConnectionDefaults().followRedirects = 1 # To use a proxy server, uncomment the next line and set the host and port. # connectionDefaults.setProxyServer("localhost", 8001) # These definitions at the top level of the file are evaluated once, # when the worker process is started. connectionDefaults.defaultHeaders = \ [ NVPair('Accept-Language', 'en-us,en;q=0.5'), NVPair('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'), NVPair('Accept-Encoding', 'gzip, deflate'), NVPair('User-Agent', 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:2.0b6) Gecko/20100101 Firefox/4.0b6'), ] request1 = HTTPRequest()
def listAllCookies(): cookies = CookieModule.listAllCookies() grinder.logger.output("CURRENT COOKIES:") for cookie in cookies: grinder.logger.output(cookie.getName() + ": " + cookie.getValue())
# Static URL we want to hit linkdrop_static_url = grinder.getProperties().getProperty("linkdrop.static_url", '/share/') # How often we want to hit the static page per send linkdrop_static_per_send = grinder.getProperties().getInt("linkdrop.static_per_send", 0) # *sob* - failed to get json packages working. Using 're' is an option, # although it requires you install jython2.5 (which still doesn't have # json builtin) - so to avoid all that complication, hack 'eval' into # working for us... _json_ns = {'null': None} def json_loads(val): return eval(val, _json_ns) CookieModule.setCookiePolicyHandler(None) from net.grinder.plugin.http import HTTPPluginControl HTTPPluginControl.getConnectionDefaults().followRedirects = 1 # To use a proxy server, uncomment the next line and set the host and port. # connectionDefaults.setProxyServer("localhost", 8001) # These definitions at the top level of the file are evaluated once, # when the worker process is started. connectionDefaults.defaultHeaders = \ [ NVPair('Accept-Language', 'en-us,en;q=0.5'), NVPair('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'), NVPair('Accept-Encoding', 'gzip, deflate'), NVPair('User-Agent', 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:2.0b6) Gecko/20100101 Firefox/4.0b6'), ] request1 = HTTPRequest()
def before(self): request1.setHeaders(headers) for c in cookies: CookieModule.addCookie( c, HTTPPluginControl.getThreadHTTPClientContext())
def __del__(self): for c in self.init_cookies: CookieModule.addCookie(c, self.threadContext)
def __call__(self): domain = 'http://test.constellation.tv' screening = 'thevowevent' films = [ 87 ] film = str(random.choice( films )) # start signup service pwd = '123456' for i in range(10): numba = random.randint(48,122) if ((numba != 96) and (numba != 94) and (numba != 92) and (numba != 69) and (numba != 60) and (numba != 62) and (numba != 58) and (numba != 59)): pwd += chr(numba) signupRequest = test1.wrap(HTTPRequest(url=domain + "/services/Join")) parameters = ( NVPair("username", str(random.randint(0,255))), NVPair("email", "grind-" + pwd + "@constellation.tv"), NVPair("password", pwd), NVPair("password2", pwd) ) signupRequest.POST(parameters) viewRequest = test2.wrap(HTTPRequest(url=domain + '/theater/'+screening)) viewRequest.GET() purchaseRequest = test3.wrap(HTTPRequest(url=domain + '/screening/'+film+'/purchase/'+screening)) post_body=( NVPair("b_address1", str('1 main street')), NVPair("b_address2", str('Apt 3')), NVPair("b_city", str('San Jose')), NVPair("b_country", str('US')), NVPair("b_state", str('CA')), NVPair("b_zipcode", str('95131')), NVPair("card_verification_number", str('962')), NVPair("confirm_email", str('grind-'+pwd+'@constellation.tv')), NVPair("credit_card_number", str('4286546374372331')), NVPair("dohbr", str('false')), NVPair("email", str('grind-'+pwd+'@constellation.tv')), NVPair("expiration_date_month", str("6")), NVPair("expiration_date_year", str("2012")), NVPair("first_name", str('First')), NVPair("invite_count", str('0')), NVPair("last_name", str('Last')), NVPair("promo_code", str('0')), NVPair("ticket_code", str('false')), NVPair("ticket_price", str('0.00')), NVPair("username", str('User ' + pwd)) ) result = purchaseRequest.POST(post_body) enterRequest = test4.wrap(HTTPRequest(url=domain + '/theater/'+screening)) result = enterRequest.GET() html = result.getText() the_user = re.search('<span class="reqs" id="mechanize_userId">([^<].*)</span>', html) log("USER IS: " + str(the_user.group(1))) user = str(the_user.group(1)) the_cmo = re.search('<span class="reqs" id="mechanize_cmo">([^<].*)</span>', html) log("CMO IS: " + str(the_cmo.group(1))) cmo = str(the_cmo.group(1)) threadContext = HTTPPluginControl.getThreadHTTPClientContext() cookies = CookieModule.listAllCookies(threadContext) for c in cookies: if c.getName() == "constellation_frontend": log("retrieved cookie: %s" % c.getValue()) thacook = c.getValue() the_film = re.search('<span class="reqs" id="mechanize_filmId">([^<].*)</span>', html) log("FILM IS: " + str(the_film.group(1))) film = str(the_film.group(1)) the_instance = re.search('<span class="reqs" id="mechanize_instance">([^<].*)</span>', html) log("THE INSTANCE IS: " + str(the_instance.group(1))) instance = str(the_instance.group(1)) is_host = re.search('<span class="reqs" id="mechanize_ishost">([^<].*)</span>', html) log("THE HOST IS: " + str(is_host.group(1))) host = str(is_host.group(1)) the_mdt = re.search('<span class="reqs" id="mechanize_mdt">([^<].*)</span>', html) log("THE MDT IS: " + str(the_mdt.group(1))) mdt = str(the_mdt.group(1)) the_image = re.search('<span class="reqs" id="mechanize_userImage">([^<].*)</span>', html) log("THE IMAGE IS: " + str(the_image.group(1))) image = str(the_image.group(1)) the_port = re.search('<span class="reqs" id="mechanize_port">([^<].*)</span>', html) log("THE PORT IS: " + str(the_port.group(1))) aport = str(the_port.group(1)) time_to_stop = time.time() + time_to_run #chatRequest = test5.wrap(HTTPRequest(url='http://www.google.com/')) #chatRequest.GET() myRandom = random.random() if myRandom > .5: #READ CHANNEL while time.time() < time_to_stop: read_chatRequest = test5.wrap(HTTPRequest(url=domain + '/services/chat/update')) read_chat_body=( NVPair("cmo", str(cmo)), NVPair("cookie", str(thacook)), NVPair("instance", str(instance)), NVPair("ishost", str(host)), NVPair("mdt", str(mdt)), NVPair("room", str(screening)), NVPair("s", "0"), NVPair("a", "0"), NVPair("c", "6"), NVPair("t", time.time()), NVPair("p", str(aport)), NVPair("u", str(user)) ) read_chatRequest.POST(read_chat_body) else: #WRITE CHANNEL while time.time() < time_to_stop: chatRequest = test6.wrap(HTTPRequest(url=domain + '/services/chat/post')) chat_body=( NVPair("author", str(user)), NVPair("body", str(user + datetime.now().strftime("%H:%M %s"))), NVPair("cmo", str(cmo)), NVPair("cookie", str(thacook)), NVPair("film", str(film)), NVPair("instance", str(instance)), NVPair("ishost", str(host)), NVPair("mdt", str(mdt)), NVPair("room", str(screening)), NVPair("type", str('chat')), NVPair("user_image", str(image)), NVPair("p", str(aport)) ) chatRequest.POST(chat_body)
def __init__(self): self.threadContext = PTS.Context.getThreadContext() self.init_cookies = CookieModule.listAllCookies(self.threadContext) self.dealApiURL = "https://deal-api.kuick.cn"