Exemple #1
0
    def __call__(self):

        c = HTTPPluginControl.getThreadConnection(url)

        for baud in rates:
            c.setBandwidthLimit(baud)
            requests[baud].GET(url)
Exemple #2
0
    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")
Exemple #3
0
    def __call__(self):

        c = HTTPPluginControl.getThreadConnection(url)
        
        for baud in rates:
            c.setBandwidthLimit(baud)
            requests[baud].GET(url)
Exemple #4
0
    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):
        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')
Exemple #6
0
 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)
Exemple #7
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)
Exemple #8
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)
Exemple #9
0
    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
Exemple #10
0
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
Exemple #11
0
    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)
Exemple #12
0
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
Exemple #13
0
    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
Exemple #14
0
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")
Exemple #15
0
 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)
Exemple #16
0
    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)
Exemple #17
0
    def doTest(self, iteration):

        if self.basicAuthentication:
            connection = HTTPPluginControl.getThreadConnection(self.url)

            connection.addBasicAuthorization(self.basicAuthentication[0],
                                             self.basicAuthentication[1],
                                             self.basicAuthentication[2])

        grinder.statistics.delayReports = 1

        if self.postData:
            page = self.request.POST(self.url, self.postData).text
        else:
            page = self.request.GET(self.url).text

        if not page:
            error = self.okString
        else:
            error = self.okString and page.find(self.okString) == -1

            if error or logHTML:
                if self.test.description:
                    description = "_%s" % self.test.description
                else:
                    description = ""

                filename = grinder.filenameFactory.createFilename(
                    "page",
                    "_%d_%.3d%s" % (iteration, self.test.number, description))

                file = open(filename, "w")
                print >> file, page
                file.close()

                if error:
                    grinder.logger.error(
                        "The 'ok' string ('%s') was not found in the page "
                        "received. The output has been written to '%s'." %
                        (self.okString, filename))

        if error:
            grinder.statistics.forLastTest.success = 0

        if self.sleepTime:
            grinder.sleep(long(self.sleepTime))
Exemple #18
0
    def doTest(self, iteration):

        if self.basicAuthentication:
            connection = HTTPPluginControl.getThreadConnection(self.url)

            connection.addBasicAuthorization(self.basicAuthentication[0],
                                             self.basicAuthentication[1],
                                             self.basicAuthentication[2])

        grinder.statistics.delayReports = 1

        if self.postData:
            page = self.request.POST(self.url, self.postData).text
        else:
            page = self.request.GET(self.url).text

        if not page:
            error = self.okString
        else:
            error = self.okString and page.find(self.okString) == -1

            if error or logHTML:
                if self.test.description:
                    description = "_%s" % self.test.description
                else:
                    description = ""

                filename = grinder.filenameFactory.createFilename(
                    "page",
                    "_%d_%.3d%s" % (iteration, self.test.number, description))

                file = open(filename, "w")
                print >> file, page
                file.close()

                if error:
                    grinder.logger.error(
                        "The 'ok' string ('%s') was not found in the page "
                        "received. The output has been written to '%s'." %
                        (self.okString, filename))

        if error:
            grinder.statistics.forLastTest.success = 0

        if self.sleepTime:
            grinder.sleep(long(self.sleepTime))
Exemple #19
0
    def __call__(self):
        # 加cookie
        threadContext = HTTPPluginControl.getThreadHTTPClientContext()
        expiryDate = Date()
        expiryDate.year += 10
        grinder.logger.info(hostlist[2][:-5])
        # url地址
        url2 = 'http://%s/goldbeta-service/bkt/api' % (hostlist[2])
        result = test('api.system.simulation.trade.stock.list',
                      '{"uid":"527","betaId":"1020491295"}', 527, '1.0', url2)

        # 返回结果检查,有返回特定字符,则判断请求成功
        if result.getText().find("success") != -1:
            grinder.statistics.forLastTest.success = 1
            grinder.logger.info(result.getText())
        else:
            grinder.statistics.forLastTest.success = 0
            # 请求失败,则输出失败时服务器返回的值
            grinder.logger.info(result.getText())
Exemple #20
0
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'),
     ]
     #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)
Exemple #22
0
    def __call__(self):
        #metronom.getToken()
        httpUtilities = HTTPPluginControl.getHTTPUtilities()
        currentTestData = TestRunner.randomTestData()
        #testUrl = 'https://robertsrg--tileserver.leidoslabs.com/tileserver/%s?skipcache' % currentTestData[TestRunner.TESTDATA_FILENAME_INDEX]
        testUrl = 'https://robertsrg--tileserver.leidoslabs.com/tileserver/%s' % currentTestData[
            TestRunner.TESTDATA_FILENAME_INDEX]
        # grinder.logger.info("testUrl = %s" % testUrl)
        expectedSize = long(
            currentTestData[TestRunner.TESTDATA_FILESIZE_INDEX])

        result = request1.GET(testUrl, (),
                              (httpUtilities.basicAuthorizationHeader(
                                  'tileservertest', 'T1leserver!!'), ))

        resultData = result.getData()

        # grinder.logger.info('result.getStatusCode() = %d len(resultData) = %d expectedSize = %d' % (result.getStatusCode(), len(resultData), expectedSize))
        # print 'result.getStatusCode() = %d len(resultData) = %d expectedSize = %d' % (result.getStatusCode(), len(resultData), expectedSize)

        if ((result.getStatusCode() != 200) or (resultData is None)
                or (len(resultData) != expectedSize)):
            grinder.statistics.forLastTest.setSuccess(0)
Exemple #23
0
    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
Exemple #24
0
# -*- coding:  latin-1 -*-
# The Grinder 3.11
# HTTP script recorded by TCPProxy at Dec 18, 2015 2:50:19 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("supercars-tomcat:8080", 8001)

def createRequest(test, url, headers=None):
    """Create an instrumented HTTPRequest."""
    request = HTTPRequest(url=url)
    if headers: request.headers=headers
    test.record(request, HTTPRequest.getHttpMethodFilter())
    return request

# These definitions at the top level of the file are evaluated once,
# when the worker process is started.

connectionDefaults.defaultHeaders = \
  [ NVPair('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9'),
    NVPair('Accept-Encoding', 'gzip, deflate'),
    NVPair('Accept-Language', 'en-us'), ]

headers0= \
  [ NVPair('Accept', '*/*'),
Exemple #25
0
def parseJsonString(json, element):
    for x in json.split(","):
        pc = x.replace('"', '').split(":")
        if pc[0].replace("{", "") == element:
            ele = pc[1].replace("}", "")
            return ele
        else:
            return ""


test1 = Test(1, "Request resource")
request1 = HTTPRequest()
headers = \
( NVPair('Content-Type', 'application/json'), )
request1.setHeaders(headers)
utilities = HTTPPluginControl.getHTTPUtilities()
test1.record(request1)
random = java.util.Random()


class TestRunner:
    def __call__(self):

        customerId = str(random.nextInt())

        result = request1.POST(
            "http://localhost:8080/transactions/add", "{"
            '"customerRewardsId"'
            ":null,"
            '"customerId"'
            ":" + customerId + ","
Exemple #26
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()
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):
Exemple #27
0
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")
PIDPREFIX = grinder.getProperties().getProperty('pidprefix')

log = grinder.logger.output # alias


testCycle = Test(0,"Full Cycle")

test1 = Test(1, "RetrieveDC")
test2 = Test(2, "Ingest")
test3 = Test(3, "modifyRELSEXT")
test4 = Test(4, "RetrieveRELSEXT")



utilities = HTTPPluginControl.getHTTPUtilities()
auth = utilities.basicAuthorizationHeader(grinder.getProperties().getProperty('fcrepo.userName'),grinder.getProperties().getProperty('fcrepo.password'))
contenttype = NVPair('Content-Type','text/xml')
dedupobject = FileInputStream('fcagent-file-store/current/DataWellDeDup.xml')


requestDCHTTP = test1.wrap(HTTPRequest())
ingestHTTP = test2.wrap(HTTPRequest())

requestRELSEXT = test4.wrap(HTTPRequest())


            
def establishFirstFromFedora():
    global auth
    log("establish First")
Exemple #29
0
# -*- 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

# 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')
Exemple #31
0
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)
Exemple #32
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)
Exemple #33
0
		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)
# 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'),
Exemple #35
0
 def before(self):
     request1.setHeaders(headers)
     for c in cookies:
         CookieModule.addCookie(
             c, HTTPPluginControl.getThreadHTTPClientContext())
Exemple #36
0
# TODO:
# What to do about errors
# Control M's in logged data
# Timing vs G2


from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest
from HTTPClient import NVPair

pluginParameters = grinder.properties.getPropertySubset("grinder.plugin.parameter.")

# Parse global parameters.
control = HTTPPluginControl.getConnectionDefaults()
control.followRedirects = pluginParameters.getBoolean("followRedirects", 0)
control.useCookies = pluginParameters.getBoolean("useCookies", 1)
logHTML = pluginParameters.getBoolean("logHTML", 0)

if pluginParameters["disablePersistentConnections"]:
    control.defaultHeaders = ( NVPair("Connection", "close"), )


class G2HTTPTest:
    """Parses parameters for an individual test and records the test
    invocation using a G3 Test."""

    def __init__(self, testNumber, properties):
        self.sleepTime = properties["sleepTime"]
# 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')