# The Grinder 3.4 # HTTP script recorded by TCPProxy at Jan 24, 2011 1:53:12 PM from net.grinder.script import Test from net.grinder.script.Grinder import grinder from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest from HTTPClient import NVPair connectionDefaults = HTTPPluginControl.getConnectionDefaults() httpUtilities = HTTPPluginControl.getHTTPUtilities() # 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 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13'), ] headers0= \ [ NVPair('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'), ] headers1= \ [ NVPair('Accept', 'image/png,image/*;q=0.8,*/*;q=0.5'), NVPair('Referer', 'http://localhost:8000/oib/login'), ] headers2= \ [ NVPair('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
# -*- coding:utf-8 -*- # A simple example using the HTTP plugin that shows the retrieval of a # single page via HTTP. # # This script is automatically generated by ngrinder. # # @author admin from net.grinder.script.Grinder import grinder from net.grinder.script import Test from net.grinder.plugin.http import HTTPRequest from net.grinder.plugin.http import HTTPPluginControl from HTTPClient import Cookie, CookieModule, CookiePolicyHandler, NVPair import PTS #自定义的库,后续大家可扩充。 control = HTTPPluginControl.getConnectionDefaults() # if you don't want that HTTPRequest follows the redirection, please modify the following option 0. # control.followRedirects = 1 # if you want to increase the timeout, please modify the following option. control.timeout = 600000 #超时时间10分钟 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
# Portions created by the Initial Developer are Copyright (C) 2009 # the Initial Developer. All Rights Reserved. # # Contributor(s): # # The Grinder 3.4 # HTTP script originally recorded by TCPProxy, but then hacked... from net.grinder.script import Test from net.grinder.script.Grinder import grinder from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest from HTTPClient import NVPair from HTTPClient import Cookie, CookieModule, CookiePolicyHandler connectionDefaults = HTTPPluginControl.getConnectionDefaults() httpUtilities = HTTPPluginControl.getHTTPUtilities() log = grinder.logger.output # 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):
# HTTP digest authentication # # Basically delegates to HTTPClient's support for digest # authentication. # # Copyright (C) 2008 Matt Moran # Copyright (C) 2008 Philip Aston # Distributed under the terms of The Grinder license. from net.grinder.plugin.http import HTTPPluginControl from HTTPClient import AuthorizationInfo # Enable HTTPClient's authorisation module. HTTPPluginControl.getConnectionDefaults().useAuthorizationModule = 1 test1 = Test(1, "Request resource") request1 = HTTPRequest() test1.record(request1) class TestRunner: def __call__(self): threadContextObject = HTTPPluginControl.getThreadHTTPClientContext() # Set the authorisation details for this worker thread. AuthorizationInfo.addDigestAuthorization("www.my.com", 80, "myrealm", "myuserid", "mypw", threadContextObject) result = request1.GET('http://www.my.com/resource')
from javax.net.ssl import SSLProtocolException from java.util import Random from java.util.zip import InflaterOutputStream from net.grinder.script.Grinder import grinder from net.grinder.script import Test from net.grinder.plugin.http import HTTPRequest, HTTPPluginControl, TimeoutException from org.apache.commons.codec.binary import Base64 from org.json.simple import JSONValue from time import time from collections import deque from threading import Lock from HTTPClient import NVPair log = grinder.logger.info HTTPPluginControl.getConnectionDefaults().setFollowRedirects(2) HTTPPluginControl.getConnectionDefaults().setTimeout(10000) CookieHandler.setDefault(CookieManager(None, CookiePolicy.ACCEPT_ALL)) # require for LS load balancing baseUrl = grinder.properties.getProperty("web.baseUrl") isLogEnabled = grinder.properties.getBoolean("log.isEnabled", False) useRabbitForGameMessages = grinder.properties.getBoolean("yazino.useRabbitForGameMessages", False) class PlayerSource: def __init__(self): sessionDuration = grinder.properties.getInt("player.sessionDurationInSeconds", 0) self.password = grinder.properties.getProperty("player.password") players_url = grinder.properties.getProperty("player.source-url") passwordHash = URLEncoder.encode(grinder.properties.getProperty("player.passwordHash"), "UTF-8") workers = grinder.properties.getInt("grinder.processes", 0) threads = grinder.properties.getInt("grinder.threads", 0)
# Portions created by the Initial Developer are Copyright (C) 2009 # the Initial Developer. All Rights Reserved. # # Contributor(s): # # The Grinder 3.4 # HTTP script originally recorded by TCPProxy, but then hacked... from net.grinder.script import Test from net.grinder.script.Grinder import grinder from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest from HTTPClient import NVPair from HTTPClient import Cookie, CookieModule, CookiePolicyHandler connectionDefaults = HTTPPluginControl.getConnectionDefaults() # Decode gzipped responses connectionDefaults.useContentEncoding = 1 # in ms connectionDefaults.setTimeout(60000) httpUtilities = HTTPPluginControl.getHTTPUtilities() log = grinder.logger.output # Properties read from the grinder .properties file. # After how many 'send' requests should we perform oauth? This is to # simulate cookie expiry or session timeouts. sends_per_oauth = grinder.getProperties().getInt("linkdrop.sends_per_oauth", 0)
# HTTP digest authentication # # Basically delegates to HTTPClient's support for digest # authentication. # # Copyright (C) 2008 Matt Moran # Copyright (C) 2008 Philip Aston # Distributed under the terms of The Grinder license. from net.grinder.plugin.http import HTTPPluginControl from HTTPClient import AuthorizationInfo # Enable HTTPClient's authorisation module. HTTPPluginControl.getConnectionDefaults().useAuthorizationModule = 1 test1 = Test(1, "Request resource") request1 = test1.wrap(HTTPRequest()) class TestRunner: def __call__(self): threadContextObject = HTTPPluginControl.getThreadHTTPClientContext() # Set the authorisation details for this worker thread. AuthorizationInfo.addDigestAuthorization( "www.my.com", 80, "myrealm", "myuserid", "mypw", threadContextObject) result = request1.GET('http://www.my.com/resource')
def sendData(self, **args): ''' should get all inputs from step/scenario and generate request0 and response0 keys in data just like when we have templates but without templates ''' use_reporter=False if 'reporter' in args and args['reporter']: use_reporter=True logger.debug("Rest implementation, sendData called.") # consider we are in legacy mode with something like "request0.uri= ...." if isinstance(args['data'], basestring): if logger.isDebugEnabled(): logger.debug("Rest implementation, sendData called with legacy request data in string format [%s]" % (args['data'])) if logger.isInfoEnabled(): logger.info("%s data sent is [%s]" % (self.__class__.__name__, args['data'])) li_resp = self.sendHTTP(args['data']) if logger.isInfoEnabled(): logger.info("%s li_resp returned is [%s]" % (self.__class__.__name__, li_resp)) return self.processJSONResponse(li_resp) # ------------------------------------------- logger.debug("Rest implementation, sendData called without legacy request data in string format.") data=args['data'] if 'rest_request_uri' not in data: logger.error('%s.sendData - missing parameter "rest_request_uri"' % self.__class__.__name__) raise NotImplementedError('%s.sendData - missing parameter "rest_request_uri"' % self.__class__.__name__) if 'rest_request_body' not in data: logger.error('%s.sendData - missing parameter "rest_request_body"' % self.__class__.__name__) raise NotImplementedError('%s.sendData - missing parameter "rest_request_body"' % self.__class__.__name__) rest_request_uri=data.get('rest_request_uri') rest_request_body=data.get('rest_request_body') ### Headers rest_request_headers=data.get('rest_request_headers', 'Content-Type:application/json') # Transform the headers list into the headers string format ( "|" delimiter ) if isinstance(rest_request_headers, list): rest_request_headers='|'.join(rest_request_headers) ### Basic authentication Header basicAuthentStr='' if 'rest_basic_auth_user' in data and 'rest_basic_auth_password' in data: basicAuthentStr = 'Authorization: Basic %s' % (base64.b64encode('%s:%s' % (data['rest_basic_auth_user'],data['rest_basic_auth_password'])))+'|' HTTPPluginControl.getConnectionDefaults().setUseCookies(0) rest_request_headers+= '|%s' % basicAuthentStr if basicAuthentStr else '' logger.debug("Rest implementation, sendData formatting request data for http implementation.") send_http_str2send = ('request0.headers=%s\nrequest0.uri=%s\nrequest0.body=%s\nrequest0.method=%s\nresponse0.statuscode=%s') % (rest_request_headers, rest_request_uri,rest_request_body, data.get('rest_request_method','POST' ), data.get('rest_response_status_code', '200' )) logger.debug("Rest implementation, sendData sending http [%s]" % (send_http_str2send)) # check reporter if 'reporter' in args and args['reporter']: # Low overhead call (minimum processing) start_time = System.currentTimeMillis() try: li_resp=self.sendHTTP(send_http_str2send) finally: try: delta_time = System.currentTimeMillis() - start_time args['reporter'].setTime2(delta_time, args['testname']) if logger.isTraceEnabled(): logger.trace('Test "%s" execution time : %d' % (args['testname'], delta_time)) li_resp['grindertool.step.executionTime'] = delta_time finally: logger.warn('%s - Measurement error on sendHTTP call' % self.__class__.__name__) else: li_resp=self.sendHTTP(send_http_str2send) HTTPPluginControl.getConnectionDefaults().setUseCookies(1) logger.debug("Rest implementation, sendData processing response [%s]" % (li_resp)) li_resp=self.processJSONResponse(li_resp) logger.debug("Rest implementation, sendData return response [%s]" % (li_resp)) return li_resp
from java.net import URL, URLEncoder, CookieHandler, CookieManager, CookiePolicy, SocketTimeoutException from javax.net.ssl import SSLProtocolException from java.util import Random from java.util.zip import InflaterOutputStream from net.grinder.script.Grinder import grinder from net.grinder.script import Test from net.grinder.plugin.http import HTTPRequest, HTTPPluginControl, TimeoutException from org.apache.commons.codec.binary import Base64 from org.json.simple import JSONValue from time import time from collections import deque from threading import Lock from HTTPClient import NVPair log = grinder.logger.info HTTPPluginControl.getConnectionDefaults().setFollowRedirects(2) HTTPPluginControl.getConnectionDefaults().setTimeout(10000) CookieHandler.setDefault(CookieManager( None, CookiePolicy.ACCEPT_ALL)) # require for LS load balancing baseUrl = grinder.properties.getProperty("web.baseUrl") isLogEnabled = grinder.properties.getBoolean("log.isEnabled", False) useRabbitForGameMessages = grinder.properties.getBoolean( "yazino.useRabbitForGameMessages", False) class PlayerSource: def __init__(self): sessionDuration = grinder.properties.getInt( "player.sessionDurationInSeconds", 0) self.password = grinder.properties.getProperty("player.password") players_url = grinder.properties.getProperty("player.source-url")