def __call__(self): sheets = 10 random = Random() worksheet = str(40 + random.nextInt(sheets)) base_url = 'http://localhost:8080/home/admin/%s' % worksheet request = newCellTest.wrap(HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id","0"),)) new_cell = result.text.split()[0].rstrip('___S_A_G_E___') request = evaluationTest.wrap(HTTPRequest(url=base_url + "/eval")) a = random.nextInt(2**30) b = random.nextInt(2**30) evalData = ( NVPair("id", new_cell), NVPair("input", "factor(%s%s)"% (a,b)), NVPair("newcell", "0"),) result = request.POST(evalData) count = 0 while (True): request = updateTest.wrap(HTTPRequest(url=base_url + "/cell_update")) getData = ( NVPair("id", new_cell),) result = request.POST(getData) count += 1 if result.text.find('pre') != -1: print 'wait %s test factor %s%s = %s' % (count, a, b, strip_answer(result.text)) break request = deleteCellTest.wrap(HTTPRequest(url=base_url + "/delete_cell")) getData = ( NVPair("id", new_cell),) result = request.POST(getData)
def __call__(self): random = Random() worksheet = random.nextInt(10) base_url = 'http://localhost:8080/home/admin/%s' % worksheet request = newCellTest.wrap( HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id", "0"), )) new_cell = result.text.split()[0].rstrip('___S_A_G_E___') request = evaluationTest.wrap(HTTPRequest(url=base_url + "/eval")) a, b = random.nextInt(10**1), random.nextInt(10**1) evalData = ( NVPair("id", new_cell), NVPair("input", "%s * %s" % (a, b)), NVPair("newcell", "0"), ) result = request.POST(evalData) count = 0 while (True): request = updateTest.wrap( HTTPRequest(url=base_url + "/cell_update")) getData = (NVPair("id", new_cell), ) result = request.POST(getData) count += 1 if result.text.find('pre') != -1: print 'wait', count, 'test', a, '*', b, '=', strip_answer( result.text) break request = deleteCellTest.wrap( HTTPRequest(url=base_url + "/delete_cell")) getData = (NVPair("id", new_cell), ) result = request.POST(getData)
def __call__(self): worksheet = '1' request = protectedResourceTest.wrap( HTTPRequest(url="http://localhost:8000/")) result = request.GET() result = maybeAuthenticate(result) result = request.GET('/home/%s/%s/' % (user, worksheet)) #print 'test sheet seen: ', (result.text.find('test') != -1) #print result.text base_url = 'http://localhost:8000/home/%s/%s' % (user, worksheet) request = newCellTest.wrap( HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id", "0"), )) new_cell = result.text.split()[0].rstrip('___S_A_G_E___') #print 'new cell number', new_cell request = evaluationTest.wrap(HTTPRequest(url=base_url + "/eval")) random = Random() a, b = random.nextInt(10**1), random.nextInt(10**1) # print 'random test',a,b, evalData = ( NVPair("id", new_cell), NVPair("input", "%s * %s" % (a, b)), NVPair("newcell", "0"), ) result = request.POST(evalData) #print 'input', result.text count = 0 while (True): #grinder.sleep(5000) request = updateTest.wrap( HTTPRequest(url=base_url + "/cell_update")) getData = (NVPair("id", new_cell), ) result = request.POST(getData) #print 'full result:', result.text count += 1 if result.text.find('pre') != -1: #print 'full result:', result.text print 'wait', count, 'test', a, '*', b, '=', strip_answer( result.text) break request = deleteCellTest.wrap( HTTPRequest(url=base_url + "/delete_cell")) getData = (NVPair("id", new_cell), ) result = request.POST(getData)
def __call__(self): if grinder.runNumber > 0 or grinder.threadNumber > 0: raise RuntimeError("Use limited to one thread, one run; " "see Amazon Web Services terms and conditions") request = HTTPRequest(url="http://xml.amazon.com/onca/xml") bookDetailsTest.record(request) parameters = ( NVPair("v", "1.0"), NVPair("f", "xml"), NVPair("t", "webservices-20"), NVPair("dev-t", "<insert license key here>"), NVPair("type", "heavy"), NVPair("AsinSearch", "1904284000"), ) bytes = request.POST(parameters).inputStream # Parse results document = parser.buildDocumentUrl(InputSource(bytes)) result = {} for details in document.getElementsByTagName("Details"): for detailName in ("ProductName", "SalesRank", "ListPrice"): result[detailName] = details.getElementsByTagName( detailName)[0].firstChild.nodeValue grinder.logger.info(str(result))
def __call__(self): request = Test(1, "Basic request").wrap( HTTPRequest(url = "http://localhost:7001")) # Example 1. You can get the time of the last test as follows. result = request.GET("index.html") grinder.logger.info("The last test took %d milliseconds" % grinder.statistics.forLastTest.time) # Example 2. Normally test results are reported automatically # when the test returns. If you want to alter the statistics # after a test has completed, you must set delayReports = 1 to # delay the reporting before performing the test. This only # affects the current worker thread. grinder.statistics.delayReports = 1 result = request.GET("index.html") if grinder.statistics.forLastTest.time > 5: # We set success = 0 to mark the test as a failure. The test # time will be reported to the data log, but not included # in the aggregate statistics sent to the console or the # summary table. grinder.statistics.forLastTest.success = 0 # With delayReports = 1 you can call report() to explicitly. grinder.statistics.report() # You can also turn the automatic reporting back on. grinder.statistics.delayReports = 0 # Example 3. # getForCurrentTest() accesses statistics for the current test. # getForLastTest() accesses statistics for the last completed test. def page(self): resourceRequest = Test(2, "Request resource").wrap( HTTPRequest(url = "http://localhost:7001")) resourceRequest.GET("index.html"); resourceRequest.GET("foo.css"); grinder.logger.info("GET foo.css returned a %d byte body" % grinder.statistics.forLastTest.getLong( "httpplugin.responseLength")) grinder.logger.info("Page has taken %d ms so far" % grinder.statistics.forCurrentTest.time) if grinder.statistics.forLastTest.time > 10: grinder.statistics.forCurrentTest.success = 0 resourceRequest.GET("image.gif"); instrumentedPage = Test(3, "Page").wrap(page) instrumentedPage(self)
def tenant(): statusCode = [0L, 0L, 0L, 0L] result7 = HTTPRequest().GET( 'https://cmdb.uyuntest.cn/crab/api/v1/cis?classCode=Y_Router') PTS.addHttpCode(result7.getStatusCode(), statusCode) return statusCode
def tenant(): statusCode = [0L, 0L, 0L, 0L] result7 = HTTPRequest().GET( 'https://cmdb.uyuntest.cn/crab/api/v1/cis/578f1f65cdd390000beb0991') PTS.addHttpCode(result7.getStatusCode(), statusCode) return statusCode
def send(self, data): request = HTTPRequest() result = request.POST(self._url, data) if not result.statusCode == 204: raise Exception("Unexpected HTTP response; " + result.getText()) return result
def __call__(self): request = protectedResourceTest.wrap( HTTPRequest(url="http://localhost:7001/console")) result = request.GET() result = maybeAuthenticate(result) result = request.GET()
def __call__(self): worksheet = '1' request = protectedResourceTest.wrap( HTTPRequest(url="http://localhost:8080/")) result = request.GET() result = maybeAuthenticate(result) result = request.GET('/home/%s/%s/' % (user, worksheet)) base_url = 'http://localhost:8080/home/%s/%s' % (user, worksheet) request = newCellTest.wrap( HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id", "0"), )) new_cell = result.text.split()[0].rstrip('___S_A_G_E___') request = evaluationTest.wrap(HTTPRequest(url=base_url + "/eval")) random = Random() a, b = random.nextInt(10**1), random.nextInt(10**1) evalData = ( NVPair("id", new_cell), NVPair("input", "%s * %s" % (a, b)), NVPair("newcell", "0"), ) result = request.POST(evalData) count = 0 while (True): #grinder.sleep(5000) request = updateTest.wrap( HTTPRequest(url=base_url + "/cell_update")) getData = (NVPair("id", new_cell), ) result = request.POST(getData) count += 1 if result.text.find('pre') != -1: txt = 'wait {} test {} * {} = {}' print(txt.format(count, a, b, strip_answer(result.text))) break request = deleteCellTest.wrap( HTTPRequest(url=base_url + "/delete_cell")) getData = (NVPair("id", new_cell), ) result = request.POST(getData)
def httpPost(url, params=None): try: request = HTTPRequest() if params is not None: return request.POST(url, params) else: return request.POST(url) except SSLProtocolException, e: log("SSL error for %s: %s" % (url, e)) return None
def tenant(): statusCode = [0L, 0L, 0L, 0L] 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) return statusCode
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 uploadFile(): fileId = UUID.randomUUID() body = "foobar test" headers = () putUrl = "%s/v1/file/%s" % (url, fileId) grinder.statistics.delayReports = 1 putWrap = tests["/v1/file"].wrap(HTTPRequest()) result = putWrap.PUT(putUrl, body, headers) if (result.statusCode != 200): grinder.statistics.forLastTest.setSuccess(0)
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 tenant(): statusCode = [0L, 0L, 0L, 0L] result7 = HTTPRequest().GET( 'http://10.1.11.254/itsm/api/v2/ticket/getTicketList?filterType=all') a = result7.getStatusCode() data = result7.getText() status = data[11:14] if status != '200': a = 300 PTS.addHttpCode(a, statusCode) return statusCode
def tenant(): statusCode = [0L, 0L, 0L, 0L] headers = [ NVPair('Content-Type', 'application/json'), NVPair('Accept', 'application/json'), ] number = PTS.random_num(4) ip = PTS.random_num(8) name = '路由器' + number data = '{"Y_name": "%s","classCode": "Y_Router","Y_ip": "%s"}' % (name, ip) result = HTTPRequest().POST('https://cmdb.uyuntest.cn/crab/api/v1/cis', data, headers) PTS.addHttpCode(result.getStatusCode(), statusCode) content = result.getText() data2 = '["%s"]' % content result2 = HTTPRequest().POST( 'https://cmdb.uyuntest.cn/crab/api/v1/cis/delete', data2, headers) PTS.addHttpCode(result2.getStatusCode(), statusCode) return statusCode
def __call__(self): result = request1.GET("http://*****:*****@liferay.com&password=test") result = request1.GET("http://*****:*****@liferay.com&password=test") result = request1.GET("http://*****:*****@liferay.com&password=test") writeToFile(result.text); authenticationFormData = ( NVPair("j_username", "*****@*****.**"), NVPair("j_password", "test"),) request = authenticationTest.wrap(HTTPRequest(url="%s/j_security_check" % result.originalURI)) request.POST(authenticationFormData) writeToFile(result.text);
def maybeAuthenticate(lastResult): if lastResult.statusCode == 401 \ or lastResult.text.find("password") != -1: authenticationFormData = ( NVPair("email", user), NVPair("password", password), ) request = authenticationTest.wrap( HTTPRequest(url="%s/login" % lastResult.originalURI)) return request.POST(authenticationFormData)
def create_metrics(cls, agent_number): #divide the total number of each query type into the ones need by this worker total_queries = default_config[cls.query_interval_name] start_job, end_job = generate_job_range(total_queries, default_config['num_nodes'], agent_number) cls.num_queries_for_current_node = end_job - start_job # Grinder test infrastructure test = Test(cls.test_number, cls.query_name) cls.query_request = HTTPRequest() test.record(cls.query_request) return [cls] * cls.num_queries_for_current_node
def tenant(): statusCode = [0L, 0L, 0L, 0L] result7 = HTTPRequest().GET('http://10.1.11.254/itsm/api/v2/ticket/getTicketList?filterType=all') code = result7.getStatusCode() data = result7.getText() json = JSONObject(data) grinder.logger.info(json.getString("errCode")) status = json.getString("errCode") if status == 'null': code = 300 if status != 'null': code = int(status) PTS.addHttpCode(code, statusCode) return statusCode
def maybeAuthenticate(lastResult): if lastResult.statusCode == 401 \ or lastResult.text.find("j_security_check") != -1: grinder.logger.output("Challenged, authenticating") authenticationFormData = ( NVPair("j_username", "weblogic"), NVPair("j_password", "weblogic"), ) request = authenticationTest.wrap( HTTPRequest(url="%s/j_security_check" % lastResult.originalURI)) return request.POST(authenticationFormData)
def tenant(): statusCode = [0L, 0L, 0L, 0L] headers = [NVPair('Content-Type', 'application/json'),NVPair('Accept', 'application/json'),NVPair('Origin', '10.1.11.254')] data = '{"message": {"toUserList": [5],"content": "同意"},"executor": {"957c8fa1cfda44b596ed3b4e29d6e27e": ["bdfe0b48fe7741b395dc599bdc80835e", "e10adc3949ba59abbe56e057f20f88dd"]},"form": {"title": "测试0010","urgentLevel": "5"}}' result7 = HTTPRequest().POST('http://10.1.11.254/itsm/api/v2/ticket/createTicket/5dbb00bb124c4d0e86f8cd0d15da0749', data, headers) code = result7.getStatusCode() data = result7.getText() json = JSONObject(data) grinder.logger.info(json.getString("errCode")) status = json.getString("errCode") if status == 'null': code = 300 if status != 'null': code = int(status) PTS.addHttpCode(code, statusCode) return statusCode
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 _add_webtest_file(cls, filename): """Add all requests in the given ``.webtest`` filename to the class. """ # Parse the Webtest file webtest = parser.Webtest(filename) # Create an HTTPRequest and Test wrapper for each request, # numbered sequentially test_requests = [] for index, request in enumerate(webtest.requests): # First request is test_number+1, then test_number+2 etc. test = Test(cls.test_number + index + 1, str(request)) wrapper = test.wrap(HTTPRequest()) test_requests.append((test, wrapper, request)) # Add the (test, request) list to class for this filename cls.webtest_requests[filename] = test_requests # Skip ahead to the next test_number cls.test_number += cls.test_number_skip
def __init__(self, testNumber, properties): self.sleepTime = properties["sleepTime"] headers = [] seenContentType = 0 for e in properties.getPropertySubset("parameter.header.").entrySet(): headers.append(NVPair(e.key, e.value)) if not seenContentType and e.key.lower() == "content-type": seenContentType = 1 postDataFilename = properties["parameter.post"] if postDataFilename: file = open(postDataFilename) self.postData = file.read() file.close() if not seenContentType: headers.append( NVPair("Content-type", "application/x-www-form-urlencoded")) else: self.postData = None self.okString = properties["parameter.ok"] self.url = properties["parameter.url"] realm = properties["basicAuthenticationRealm"] user = properties["basicAuthenticationUser"] password = properties["basicAuthenticationPassword"] if realm and user and password: self.basicAuthentication = (realm, user, password) elif not realm and not user and not password: self.basicAuthentication = None else: raise "If you specify one of { basicAuthenticationUser, basicAuthenticationRealm, basicAuthenticationPassword } you must specify all three." self.request = HTTPRequest(headers=headers) self.test = Test(testNumber, properties["description"]) self.test.record(self.request)
def page(self): resourceRequest = Test(2, "Request resource").wrap( HTTPRequest(url = "http://localhost:7001")) resourceRequest.GET("index.html"); resourceRequest.GET("foo.css"); grinder.logger.info("GET foo.css returned a %d byte body" % grinder.statistics.forLastTest.getLong( "httpplugin.responseLength")) grinder.logger.info("Page has taken %d ms so far" % grinder.statistics.forCurrentTest.time) if grinder.statistics.forLastTest.time > 10: grinder.statistics.forCurrentTest.success = 0 resourceRequest.GET("image.gif");
def create_request_obj(test_num, test_name, tgroup_name=None, auth_user=None): grinder.logger.debug('Creating %s request object' % test_name) test = Test(test_num, test_name) request = HTTPRequest() request = ResponseCheckingRequest(request) test.record(request) request = ExceptionHandlingRequest(request) request = ErrorLoggingRequest(request, grinder.logger.info) if auth_user: grinder.logger.debug('%s request object will authenticate with ' 'username "%s".' % (test_name, auth_user.username)) request = AuthenticatingRequest(request, auth_user) if tgroup_name: grinder.logger.debug('%s request object will throttle with group ' '"%s".' % (test_name, tgroup_name)) tgroup = throttling_groups[tgroup_name] request = ThrottlingRequest(tgroup, request) return request
def __call__(self): t1 = System.currentTimeMillis() test = Test(1, "HTTP post") request = test.wrap(HTTPRequest()) timestamp = "<foo>|timestamp=" + str(System.currentTimeMillis()) + "|" padding = 'X' * (MSG_SIZE - len(timestamp) - len("</foo>")) data = timestamp + padding + "</foo>" result = request.POST(URL, data) if not result.statusCode == 204: raise Exception("Unexpected HTTP response; " + result.getText()) if sleepTime > 0: # Adjust sleep time based on test time adjustedSleeptime = sleepTime - (System.currentTimeMillis() - t1) grinder.sleep(long(adjustedSleeptime))
def __call__(self): grinder.SSLControl.setKeyStoreFile("mykeystore.jks", "123456") for index in range(len(vo_keys)): vo = vo_keys[index] test = Test(index, "VOMS AC for VO " + vo) request = HTTPRequest() test.record(request) port = list_vo[vo] url = "https://" + host + ":" + str(port) + resource grinder.statistics.delayReports = 1 result = str(request.GET(url)) if not '200 OK' in result: grinder.statistics.forLastTest.success = 0 grinder.statistics.report() grinder.statistics.delayReports = 0