def establishFirstFromFedora():
    global auth
    log("establish First")
    contenttype = NVPair('Content-Type','text/xml')
    target =  SERVER + '/objects/nextPID?format=xml'

    
    result = HTTPRequest().POST(target,None,[contenttype,auth])
    text =  str(result.getText())
    log(text)
    pidstart = text.index("<pid>")
    pidend = text.index("</pid>")
    pid = text[pidstart+5:pidend]
    log(pid)
    return pid
def modifyDefensively(targetIN,rdf,auth):
    attempts = 0
    log("modifying object defensively")
    while (attempts<5):
        result = HTTPRequest().PUT(targetIN,rdf,[auth])
        status = result.getStatusCode()
        if status >= 200 and status < 300:
            break
        else:
            log("failed attempt "+str(attempts))
            grinder.sleep(1000)
            attempts = attempts+1
            #todo sleep a while
    stats = grinder.getStatistics().getForCurrentTest()
    status = result.getStatusCode()
    if status >= 200 and status < 300:
        stats.setSuccess(True)
    else:
        log("failed to modifyDefensively, ended with status "+str(status))
        stats.setSuccess(False)
Ejemplo n.º 3
0
    def http_open(self, req):
        greq = HTTPRequest()

        url = req.get_full_url()
        payload = req.get_data()
        headers = []
        for k, v in req.headers.items():
            headers.append(NVPair(k, v))

        if req.get_method() == 'GET':
            gresp = greq.GET(url, payload, headers)
        elif req.get_method() == 'POST':
            gresp = greq.POST(url, payload, headers)
        elif req.get_method() == 'PUT':
            gresp = greq.PUT(url, payload, headers)
        elif req.get_method() == 'DELETE':
            gresp = greq.DELETE(url, payload, headers)
        else:
            raise ValueError("HTTP method " + req.get_method() +
                             " isn't supported")

        return self.GrinderHTTPResponse(gresp)
Ejemplo n.º 4
0
# A simple example using the HTTP plugin that shows the retrieval of a
# single page via HTTP. The resulting page is written to a file.
#
# More complex HTTP scripts are best created with the TCPProxy.
#
# This script is auto generated by ngrinder.
#
# @author ${user.userName}
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest

test1 = Test(1, "Request resource")
request1 = test1.wrap(HTTPRequest())
log = grinder.logger.info


class TestRunner:
    def __call__(self):
        grinder.sleep(1000)
        while True:
            log("WOW")
Ejemplo n.º 5
0
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
Ejemplo n.º 6
0
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
Ejemplo n.º 7
0
#out = grinder.logger.LOG

grinderUtil = GrinderUtil.getSingleton()
applicationProperties = grinderUtil.getApplicationProperties()

testCommand = applicationProperties.getProperty("test.command")
url = applicationProperties.getProperty("test.url")

grinderUtil = GrinderUtil.getSingleton()
applicationProperties = grinderUtil.getApplicationProperties()

testCommand = applicationProperties.getProperty("test.command")
url = applicationProperties.getProperty("test.url")

testWrap = Test(1, "General Tests")
wrappedRequest = testWrap.wrap(HTTPRequest())

tests = {"Example": Test(1, "Index Page")}

execCounter = 0


class TestRunner:
    def __call__(self):
        print "testCommand=%s" % (testCommand)
        if testCommand == "example-get":
            getRequest()
        elif testCommand == "my-test-1":
            test1()
        elif testCommand == "my-test-2":
            test1()
Ejemplo n.º 8
0
grinder.statistics.registerSummaryExpression("Batches Per Second",
                                             "(* (/ userLong1 period) 1000)")

url = grinder.properties.get('server.url')

log.info('The server url to use is %s' % url)

serverPath = grinder.properties.get('server.path')

log.info('The server path is %s' % serverPath)

helper = SymmetricProtocolHelper(grinder)

log.info('The variable replacer was created')

httpRequest = HTTPRequest(url=url)

log.info('The HTTP request object was created')


def pull():
    ts = current_millis()
    token_nodeId = helper.nodeId
    token_securityToken = grinder.properties.getProperty(
        'server.auth.token', 'test')

    result = httpRequest.GET(serverPath + '/pull' + '?nodeId=' + token_nodeId +
                             '&securityToken=' + token_securityToken)

    if result.statusCode == 200:
        ackData = helper.generateAck(String(result.data))
Ejemplo n.º 9
0
param_file = "http_get_test.txt"
infile = open(param_file, 'r')
keyword_list = []
for line in infile.readlines():
    keyword_list.append(line.strip())
infile.close()

# 可能需要修改url和headers等值
url = 'https://www.baidu.com'
headers = [
    NVPair(
        'User-Agent',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
    )
]
request = HTTPRequest(url=url, headers=headers)


class TestRunner:
    """A TestRunner instance is created for each worker thread."""

    # 构造方法
    def __init__(self):
        pass

    # 获取参数
    def getParam(self, keyword):
        param = "/baidu?wd=" + keyword
        return param

    # 发送请求
Ejemplo n.º 10
0
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest
from HTTPClient import NVPair

# We declare a default URL for the HTTPRequest.
request = HTTPRequest(url="http://localhost:8000")


def page1():
    request.GET('/')
    #request.GET('/console/login/LoginForm.jsp')
    #request.GET('/console/login/bea_logo.gif')


page1Test = Test(1, "First page").wrap(page1)


class TestRunner:
    def __call__(self):
        page1Test()
Ejemplo n.º 11
0
class IngestThread(AbstractThread):
  # The list of metric numbers for all threads in this worker
  metrics = []
  
  # Grinder test reporting infrastructure
  test1 = Test(1, "Ingest test")
  request = HTTPRequest()
  test1.record(request)


  @classmethod
  def create_metrics(cls, agent_number):
    """ Generate all the metrics for this worker

    The metrics are a list of batches.  Each batch is a list of metrics processed by
    a single metrics ingest request.
    """
    metrics =  generate_metrics_tenants(default_config['num_tenants'],
                                            default_config['metrics_per_tenant'], agent_number, 
                                            default_config['num_nodes'], 
                                            cls.generate_metrics_for_tenant)

    cls.metrics = cls.divide_metrics_into_batches(metrics, default_config['batch_size'])

  @classmethod
  def num_threads(cls):
    return default_config['ingest_concurrency']

  @classmethod
  def generate_metrics_for_tenant(cls, tenant_id, metrics_per_tenant):
    l = [];
    for x in range(metrics_per_tenant):
      l.append([tenant_id, x])
    return l

  @classmethod
  def divide_metrics_into_batches(cls, metrics, batch_size):
    b = []
    for i in range(0, len(metrics), batch_size):
      b.append(metrics[i:i+batch_size])
    return b

  def __init__(self, thread_num):
    AbstractThread.__init__(self, thread_num)
    # Initialize the "slice" of the metrics to be sent by this thread
    start, end = generate_job_range(len(self.metrics), 
                                    self.num_threads(), thread_num)
    self.slice = self.metrics[start:end]

  def generate_metric(self, time, tenant_id, metric_id):
    ingest_delay_millis = default_config['ingest_delay_millis']

    collection_time = time
    # all even tenants have possible delayed metrics
    if len(ingest_delay_millis) > 0 and tenant_id % 2 == 0:
        collection_times = [time - long(delay) for delay in ingest_delay_millis.split(",")]
        collection_time = random.choice(collection_times)

    return {'tenantId': str(tenant_id),
            'metricName': generate_metric_name(metric_id),
            'unit': self.generate_unit(tenant_id),
            'metricValue': random.randint(0, RAND_MAX),
            'ttlInSeconds': (2 * 24 * 60 * 60),
            'collectionTime': collection_time}

  def generate_payload(self, time, batch):
    payload = map(lambda x:self.generate_metric(time,*x), batch)
    return json.dumps(payload)

  def ingest_url(self):
    return "%s/v2.0/tenantId/ingest/multi" % default_config['url']


  def make_request(self, logger):
    if len(self.slice) == 0:
      logger("Warning: no work for current thread")
      self.sleep(1000000)
      return None
    self.check_position(logger, len(self.slice))
    payload = self.generate_payload(int(self.time()),
                                           self.slice[self.position])
    self.position += 1
    result = self.request.POST(self.ingest_url(), payload)
    return result
Ejemplo n.º 12
0
#
# The J2EE Servlet specification defines a common model for form based
# authentication. When unauthenticated users try to access a protected
# resource, they are challenged with a logon page. The logon page
# contains a form that POSTs username and password fields to a special
# j_security_check page.

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

protectedResourceTest = Test(1, "Request resource")
authenticationTest = Test(2, "POST to j_security_check")

request = HTTPRequest(url="http://localhost:7001/console")
protectedResourceTest.record(request)


class TestRunner:
    def __call__(self):
        result = request.GET()
        result = maybeAuthenticate(result)

        result = request.GET()


# Function that checks the passed HTTPResult to see whether
# authentication is necessary. If it is, perform the authentication
# and record performance information against Test 2.
def maybeAuthenticate(lastResult):
Ejemplo n.º 13
0
headers2= \
  [ NVPair('Accept', '*/*'),
    NVPair('Referer', 'http://test.sagenb.org/pub/'), ]

headers3= \
  [ NVPair('Accept', 'image/png,image/*;q=0.8,*/*;q=0.5'),
    NVPair('Referer', 'http://test.sagenb.org/pub/'), ]

url0 = 'http://test.sagenb.org:80'
url1 = 'http://www.google-analytics.com:80'

# Create an HTTPRequest for each request, then replace the
# reference to the HTTPRequest with an instrumented version.
# You can access the unadorned instance using request101.__target__.
request101 = HTTPRequest(url=url0, headers=headers0)
request101 = Test(101, 'GET /').wrap(request101)

request102 = HTTPRequest(url=url0, headers=headers1)
request102 = Test(102, 'GET main.css').wrap(request102)

request103 = HTTPRequest(url=url0, headers=headers2)
request103 = Test(103, 'GET localization.js').wrap(request103)

request201 = HTTPRequest(url=url1, headers=headers3)
request201 = Test(201, 'GET __utm.gif').wrap(request201)


class TestRunner:
    """A TestRunner instance is created for each worker thread."""
Ejemplo n.º 14
0
# HTTP multipart form submission
#
# This script uses the HTTPClient.Codecs class to post itself to the
# server as a multi-part form. Thanks to Marc Gemis.

from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest
from HTTPClient import Codecs, NVPair
from jarray import zeros

test1 = Test(1, "Upload Image")
request1 = HTTPRequest(url="http://localhost:7001/")
test1.record(request1)

class TestRunner:
    def __call__(self):

        files = ( NVPair("self", "form.py"), )
        parameters = ( NVPair("run number", str(grinder.runNumber)), )

        # This is the Jython way of creating an NVPair[] Java array
        # with one element.
        headers = zeros(1, NVPair)

        # Create a multi-part form encoded byte array.
        data = Codecs.mpFormDataEncode(parameters, files, headers)
        grinder.logger.output("Content type set to %s" % headers[0].value)

        # Call the version of POST that takes a byte array.
        result = request1.POST("/upload", data, headers)
Ejemplo n.º 15
0
#
# A simple example using the HTTP plugin that shows the retrieval of a
# single page via HTTP. The resulting page is written to a file.
#
# More complex HTTP scripts are best created with the TCPProxy.

from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest

import data_urls
import jarray
import random

test1 = Test(1, "Request random dataset")
req = HTTPRequest()
req.setReadResponseBody(False)
chunk = 1024*512

properties = grinder.properties.getPropertySubset('dapbench.')

dataset_list = properties['datasets']

def streamed_get(url):
    buf = jarray.zeros(chunk, 'b')
    total = 0
    resp = req.GET(url)
    stream = resp.getInputStream()
    ret = 0
    while ret != -1:
        ret = stream.read(buf)
Ejemplo n.º 16
0
	67651,
	1218937829,
	981,
	8711
]

def rndIndex():
    return VALUES[randomizer.nextInt() % len(VALUES)]

# Logging
log = grinder.logger.output
out = grinder.logger.TERMINAL

test1 = Test(1, "enqueue")
test2 = Test(2, "dequeue")
request1 = test1.wrap(HTTPRequest())
request2 = test2.wrap(HTTPRequest())

# Test Interface
class TestRunner:
	def __call__(self):
                post_data={}
                for pt in ['1', '2', '3', '4', '5', 'X', 'K', 'Y', 'W', 'Z']:
                    post_data['FAKENAME'+pt]=rndIndex()

		log("Sending data (enqueuing): %s" % post_data )

		post_parameters = (
			NVPair("queue", QUEUENAME),
			NVPair("value", str(post_data)),
		)
Ejemplo n.º 17
0
        date = str(int(time.time()))
        initial_sleep(thread_rampup)
        import re
        p = re.compile(r'piqid":[ ]*"([^"]*)"')
        co = 0
        ts = '&TS=' + date
        while True:
            for data1, data2 in dataset:
        	co += 1
                res = GET1(data1, None)
                res = res.getText()
                pars = p.search(res)
                if not co & 1:
            	    t = ts
            	else: 
            	    t = '' 
		if pars:
            	    id = pars.group(1)
        	    GET("/dataex/data/?" + data2 + '&DI=' + id  + t)


def TestRunner():
    return do_test

test = Test(1, appname)
request = HTTPRequest()
request.setUrl(base_url)
request1 = HTTPRequest()
request.setHeaders(headers)
test.record(request, HTTPRequest.getHttpMethodFilter())
Ejemplo n.º 18
0
import string
import time
import random

from java.io import FileOutputStream
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest
from net.grinder.common import GrinderException
from HTTPClient import NVPair

test1 = Test(1, "MyCravings - Load test")
testId = "MyCravingsLoadTest"

# REVIEW: Ensure URL is available
request1 = HTTPRequest(url="https://stagehub.p2c.com/node/19")
test1.record(request1)

# Current timestamp to uniquely identify the contacts
baseId = time.time()

class TestRunner:
    def __call__(self):
        tid = grinder.threadNumber

        nameSuffix = random.randint(1, 9999999999)
        firstName = "Grinder"
        lastName = "GrinderLast-%d-%d" % (baseId, nameSuffix)
        phone = "%d" % (random.randint(1111111111, 9999999999))
        email = "%s@%s.net" % (firstName, lastName)
Ejemplo n.º 19
0
"""
Test the throughput of Tomcat running on different jvm(sun,ibm,jrocket).
"""

from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest
#from HTTPClient import NVPair
from net.grinder.script.Grinder import grinder
from net.grinder.common import Logger

# assemble Test object
jvm_test = Test(1, "Test tomcat based on different JVM.")
# assemble http proxy object
request = jvm_test.wrap(HTTPRequest())

# initialize a grinder log.
log = grinder.logger.output


#--------------------------------------------------#
# Grinder specified test runner                    #
#--------------------------------------------------#
class TestRunner:
    def __init__(self):
        pass

    def __call__(self):
        """
        A Python object is callable if it defines a __call__ method. Each worker thread performs a
        number of runs of the test script, as configured by the property grinder.runs. For each run,
        the worker thread calls its TestRunner; thus the __call__ method can be thought of as the
Ejemplo n.º 20
0
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest
 
test = Test(1, "BZT Requests")
request = HTTPRequest()
test.record(request)
 
class TestRunner(object):
    def __call__(self):
        request.GET("http://demo.blazemeter.com/")
 
Ejemplo n.º 21
0
class EnumIngestThread(AbstractThread):
    # The list of metric numbers for all threads in this worker
    metrics = []

    # Grinder test reporting infrastructure
    test1 = Test(7, "Enum Ingest test")
    request = HTTPRequest()
    test1.record(request)

    @classmethod
    def create_metrics(cls, agent_number):
        """ Generate all the metrics for this worker

        The metrics are a list of batches.  Each batch is a list of metrics
        processed by a single metrics ingest request.
        """
        metrics = generate_metrics_tenants(
            default_config['enum_num_tenants'],
            default_config['enum_metrics_per_tenant'], agent_number,
            default_config['num_nodes'], cls.generate_metrics_for_tenant)

        cls.metrics = cls.divide_metrics_into_batches(
            metrics, default_config['batch_size'])

    @classmethod
    def num_threads(cls):
        return default_config['enum_ingest_concurrency']

    @classmethod
    def generate_metrics_for_tenant(cls, tenant_id, metrics_per_tenant):
        l = []
        for x in range(metrics_per_tenant):
            l.append([tenant_id, x])
        return l

    @classmethod
    def divide_metrics_into_batches(cls, metrics, batch_size):
        b = []
        for i in range(0, len(metrics), batch_size):
            b.append(metrics[i:i + batch_size])
        return b

    def __init__(self, thread_num):
        AbstractThread.__init__(self, thread_num)
        # Initialize the "slice" of the metrics to be sent by this thread
        start, end = generate_job_range(len(self.metrics), self.num_threads(),
                                        thread_num)
        self.slice = self.metrics[start:end]

    def generate_enum_suffix(self):
        return "_" + str(random.randint(0, default_config['enum_num_values']))

    def generate_enum_metric(self, time, tenant_id, metric_id):
        return {
            'tenantId':
            str(tenant_id),
            'timestamp':
            time,
            'enums': [{
                'name':
                generate_enum_metric_name(metric_id),
                'value':
                'e_g_' + str(metric_id) + self.generate_enum_suffix()
            }]
        }

    def generate_payload(self, time, batch):
        payload = map(lambda x: self.generate_enum_metric(time, *x), batch)
        return json.dumps(payload)

    def ingest_url(self):
        return "%s/v2.0/tenantId/ingest/aggregated/multi" % default_config[
            'url']

    def make_request(self, logger):
        if len(self.slice) == 0:
            logger("Warning: no work for current thread")
            self.sleep(1000000)
            return None
        self.check_position(logger, len(self.slice))
        payload = self.generate_payload(int(self.time()),
                                        self.slice[self.position])
        self.position += 1
        result = self.request.POST(self.ingest_url(), payload)
        return result
Ejemplo n.º 22
0
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 __call__(self):
Ejemplo n.º 23
0
    NVPair('Accept-Encoding', 'gzip,deflate'),
    NVPair('Accept-Language', 'en-us,en;q=0.5'),
    NVPair('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'), )

headers0= \
  ( NVPair('Accept', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'), )

headers1= \
  ( NVPair('Accept', 'image/png,*/*;q=0.5'), )

url0 = 'http://localhost:8080'

# Create an HTTPRequest for each request, then replace the
# reference to the HTTPRequest with an instrumented version.
# You can access the unadorned instance using request101.__target__.
request101 = HTTPRequest(url=url0, headers=headers0)
#request101 = Test(101, 'GET MotorPlus').wrap(request101)

request201 = HTTPRequest(url=url0, headers=headers0)
#request201 = Test(201, 'POST QuoteWindow').wrap(request201)

request202 = HTTPRequest(url=url0, headers=headers0)
#request202 = Test(202, 'GET QuoteWindow').wrap(request202)

request301 = HTTPRequest(url=url0, headers=headers0)
#request301 = Test(301, 'POST QuoteWindow').wrap(request301)

request302 = HTTPRequest(url=url0, headers=headers0)
#request302 = Test(302, 'GET QuoteWindow').wrap(request302)

request401 = HTTPRequest(url=url0, headers=headers0)
Ejemplo n.º 24
0
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest
from HTTPClient import NVPair
from net.grinder.script.Grinder import grinder

from java.lang import String

import te_message
from te_conf import *
from te_testdata import *

# assemble Test object
bet_test = Test(2, "active: active multiple books.")
# assemble http proxy object
request = bet_test.wrap(HTTPRequest())

# initialize a grinder log.
log = grinder.logger.output
out = grinder.logger.TERMINAL

request_msgbody = batch_validate()


#--------------------------------------------------#
# Grinder specified test runner                    #
#--------------------------------------------------#
class TestRunner:
    def __init__(self):
        pass

    def __call__(self):
Ejemplo n.º 25
0
# Recording many HTTP interactions as one test
#
# This example shows how many HTTP interactions can be grouped as a
# single test by wrapping them in a function.

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

# We declare a default URL for the HTTPRequest.
request = HTTPRequest(url = "http://localhost:7001")

def page1():
    request.GET('/console')
    request.GET('/console/login/LoginForm.jsp')
    request.GET('/console/login/bea_logo.gif')

Test(1, "First page").record(page1)

class TestRunner:
    def __call__(self):
        page1()
Ejemplo n.º 26
0
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"]

        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 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))
Ejemplo n.º 27
0
#
# A simple example using the HTTP plugin that shows the retrieval of a
# single page via HTTP. The resulting page is written to a file.
#
# More complex HTTP scripts are best created with the TCPProxy.

from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest

import data_urls
import jarray
import random

test1 = Test(1, "Request random dataset")
req = HTTPRequest()
req.setReadResponseBody(False)
chunk = 1024 * 512

properties = grinder.properties.getPropertySubset('dapbench.')

dataset_list = properties['datasets']


def streamed_get(url):
    buf = jarray.zeros(chunk, 'b')
    total = 0
    resp = req.GET(url)
    stream = resp.getInputStream()
    ret = 0
    while ret != -1:
Ejemplo n.º 28
0
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

requests = {}

rates = (-1, 10000000, 1000000, 100000, 56000, 9600, 2400)

i = 0

for baud in rates:
    requests[baud] = Test(i, "%d baud" % baud).wrap(HTTPRequest())
    i = i + 1

url = "http://slashdot.org/"

grinder.statistics.registerDataLogExpression(
    "BPS",
    "(* 8000 (/ httpplugin.responseLength (+ (sum timedTests) (* -1 httpplugin.firstByteTime))))"
)
grinder.statistics.registerSummaryExpression(
    "BPS",
    "(* 8000 (/ httpplugin.responseLength (+ (sum timedTests) (* -1 httpplugin.firstByteTime))))"
)


class TestRunner:
    def __call__(self):

        c = HTTPPluginControl.getThreadConnection(url)
Ejemplo n.º 29
0
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest
from HTTPClient import NVPair
from java.util import Random

# We declare a default URL for the HTTPRequest.
request = HTTPRequest(url="http://www.google.com")
#request = HTTPRequest(url = "http://aleph.sagemath.org")


def evalss():
    wait = 250
    input = 'from+sage.all+import+*;factor(ZZ.random_element(10**40))'
    result = request.GET('/execute?input=%s' % input)
    id = result.text
    count = 0
    while True:
        grinder.sleep(wait)
        result = request.GET('/get?id=%s' % id)
        count += 1
        if result.text.find('wait') == -1:
            break
    ans = eval(result.text)
    print('test waited%s ans = %s' % (count, ans['output']))


evalssTest = Test(1, "Exec testpage").wrap(evalss)


def homess():
Ejemplo n.º 30
0
# HTTP multipart form submission
#
# This script uses the HTTPClient.Codecs class to post itself to the
# server as a multi-part form. Thanks to Marc Gemis.

from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest
from HTTPClient import Codecs, NVPair
from jarray import zeros

test1 = Test(1, "Upload Image")
request1 = test1.wrap(HTTPRequest(url="http://localhost:7001/"))


class TestRunner:
    def __call__(self):

        files = (NVPair("self", "form.py"), )
        parameters = (NVPair("run number", str(grinder.runNumber)), )

        # This is the Jython way of creating an NVPair[] Java array
        # with one element.
        headers = zeros(1, NVPair)

        # Create a multi-part form encoded byte array.
        data = Codecs.mpFormDataEncode(parameters, files, headers)
        grinder.logger.output("Content type set to %s" % headers[0].value)

        # Call the version of POST that takes a byte array.
        result = request1.POST("/upload", data, headers)
Ejemplo n.º 31
0
def getRequest():
    grinder.statistics.delayReports = 1
    result = tests["Example"].wrap(HTTPRequest()).GET(url)

    if (result.statusCode != 200):
        grinder.statistics.forLastTest.setSuccess(0)
Ejemplo n.º 32
0
agentID = int(grinder.properties["grinder.agentID"])
processID = int(grinder.processName.split("-").pop())
host = '192.168.1.200'
domain = 'openf.ath.cx'
boshUrl = 'http://' + host + ':7070/http-bind/'
boshWait = 1
userPrefix = 'user'
numThreads = 1

# Create an HTTPRequest for each request, then replace the
# reference to the HTTPRequest with an instrumented version.
# You can access the unadorned instance using request101.__target__.

request101 = Test(101,
                  'Initiate a BOSH session').wrap(HTTPRequest(url=boshUrl))
request201 = Test(201, 'Authenticate').wrap(HTTPRequest(url=boshUrl))
request301 = Test(301, 'Bind resource').wrap(HTTPRequest(url=boshUrl))
request401 = Test(401, 'Request a session from the server').wrap(
    HTTPRequest(url=boshUrl))
request501 = Test(501, 'Get roster').wrap(HTTPRequest(url=boshUrl))
request601 = Test(601, 'Change presence').wrap(HTTPRequest(url=boshUrl))
request701 = Test(701,
                  'Send one to one message').wrap(HTTPRequest(url=boshUrl))
request801 = Test(801, 'Make an empty request to the server').wrap(
    HTTPRequest(url=boshUrl))
request901 = Test(901, 'Terminate the session').wrap(HTTPRequest(url=boshUrl))


class TestRunner:
    """A TestRunner instance is created for each worker thread."""
Ejemplo n.º 33
0
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 java.util import Date
from HTTPClient import NVPair, Cookie, CookieModule
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 = 6000

test1 = Test(1, "Test1")
request1 = HTTPRequest()

# Set header datas
headers = []  # Array of NVPair
# Set param datas
params = []  # Array of NVPair
# Set cookie datas
cookies = []  # Array of Cookie


def tenant():
    statusCode = [0L, 0L, 0L, 0L]

    headers = [
        NVPair('Content-Type', 'application/json'),
        NVPair('Accept', 'application/json'),
Ejemplo n.º 34
0
def post(url, context, logString, template):
    return HTTPRequest().POST(url, render(context, logString, template))
Ejemplo n.º 35
0
class AnnotationsIngestThread(AbstractThread):
    # The list of metric numbers for all threads in this worker
    annotations = []

    # Grinder test reporting infrastructure
    test1 = Test(2, "Annotations Ingest test")
    request = HTTPRequest()
    test1.record(request)

    @classmethod
    def create_metrics(cls, agent_number):
        """ Generate all the annotations for this worker

    """
        cls.annotations = generate_metrics_tenants(
            default_config['annotations_num_tenants'],
            default_config['annotations_per_tenant'], agent_number,
            default_config['num_nodes'], cls.generate_annotations_for_tenant)

    @classmethod
    def num_threads(cls):
        return default_config['annotations_concurrency']

    @classmethod
    def generate_annotations_for_tenant(cls, tenant_id,
                                        annotations_per_tenant):
        l = []
        for x in range(annotations_per_tenant):
            l.append([tenant_id, x])
        return l

    def __init__(self, thread_num):
        AbstractThread.__init__(self, thread_num)
        # Initialize the "slice" of the metrics to be sent by this thread
        start, end = generate_job_range(len(self.annotations),
                                        self.num_threads(), thread_num)
        self.slice = self.annotations[start:end]

    def generate_annotation(self, time, metric_id):
        metric_name = generate_metric_name(metric_id)
        return {
            'what': 'annotation ' + metric_name,
            'when': time,
            'tags': 'tag',
            'data': 'data'
        }

    def generate_payload(self, time, metric_id):
        payload = self.generate_annotation(time, metric_id)
        return json.dumps(payload)

    def ingest_url(self, tenant_id):
        return "%s/v2.0/%s/events" % (default_config['url'], tenant_id)

    def make_request(self, logger):
        if len(self.slice) == 0:
            logger("Warning: no work for current thread")
            self.sleep(1000000)
            return None
        self.check_position(logger, len(self.slice))
        batch = self.slice[self.position]
        tenant_id = batch[0]
        metric_id = batch[1]
        payload = self.generate_payload(int(self.time()), metric_id)

        self.position += 1
        result = self.request.POST(self.ingest_url(tenant_id), payload)
        return result
Ejemplo n.º 36
0
from net.grinder.script import Test
from net.grinder.script.Grinder import grinder
from net.grinder.plugin.http import HTTPRequest, HTTPPluginControl, HTTPUtilities
from HTTPClient import NVPair

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 + ","'"transactionDate"'":null}")
        txnId = parseJsonString(result.getText(), "id")

        result = request1.GET("http://localhost:8080/rewards/find/"+ customerId)