Example #1
0
 def __call__(self):
     grinder.statistics.delayReports = 1
     error = grinder.logger.error
     log = grinder.logger.output
         
     twitterTest = Test(201, "REST twittersoek")
     twitterRequest = twitterTest.wrap(HTTPRequest(url=baseUrl))
     
     profilbildeTest = Test(202, "REST profilbilder")
     profilbildeRequest = profilbildeTest.wrap(HTTPRequest())
     
     try:
         log("Soek etter 'Grinder' paa twitter og henter JSON-resultater")
         twitterJson = twitterRequest.GET("search.json?q=" + sokeord).text
         twitterObjekt = JSONObject(twitterJson)
         twitterResultater = twitterObjekt.getJSONArray("results")
         for i in range(0,twitterResultater.length()):
             enkeltTweet = twitterResultater.getJSONObject(i)
             brukerID = enkeltTweet.getString("from_user_id_str")
             log("Henter profilbilde for bruker:" + brukerID)
             profilbildeUrl = enkeltTweet.getString("profile_image_url")
             profilbildeRequest.GET(profilbildeUrl)
     except JSONException, ex:
         grinder.statistics.forLastTest.setSuccess(0)
         error("EXCEPTION HENDTE:")
         error(str(ex))
Example #2
0
 def __init__(self):
     url_file = open(url_file_path)
     self.tests = []
     for num, url in enumerate(url_file):
         url = url.strip()
         test = Test(num, url)
         request = test.wrap(HTTPRequest())
         self.tests.append((request, url))
     url_file.close()
Example #3
0
 def __init__(self):
     url_file = open(url_file_path)
     self.requests = []
     for num, line in enumerate(url_file):
         url, description = line.split(' ', 1)
         test = Test(num, description.strip())
         request_fn = request_factory(url)
         wrapped_request_fn = test.wrap(request_fn)
         self.requests.append(wrapped_request_fn)
     url_file.close()
Example #4
0
 def __init__(self):
     url_file = open(url_file_path)
     self.tests = []
     for num, url in enumerate(url_file):
         url = url.strip()
         test = Test(num, url)
         request = test.wrap(HTTPRequest())
         self.tests.append((request, url))
     url_file.close()
     grinder.statistics.setDelayReports(True)
 def __init__(self):
     url_file = open(url_file_path, "rb")
     self.tests = []
     for num, line in enumerate(url_file):
         line = [val.strip() for val in line.split("|")]
         url, description, checks = line[0], line[1], line[2:]
         test = Test(num, description)
         request = test.wrap(HTTPRequest())
         self.tests.append((request, url, checks))
     url_file.close()
     grinder.statistics.setDelayReports(True)
Example #6
0
 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
Example #7
0
 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 __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):
        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))
Example #10
0
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)
        total += ret

    return total


streamed_get = test1.wrap(streamed_get)


class TestRunner:
    def __call__(self):
        grinder.logger.output('Selecting dataset from %s' % dataset_list)
        dataset_url = random.choice(data_urls.load_dataset_list(dataset_list))
        grinder.logger.output('Downloading %s' % dataset_url)
        result = streamed_get(dataset_url)
        grinder.logger.output('Transfered %d bytes' % result)
# Hello World, with functions
#
# The Hello World example re-written using functions.
#
# In previous examples we've defined TestRunner as a class; calling
# the class creates an instance and calling that instance invokes its
# __call__ method. This script is for the Luddites amongst you and
# shows how The Grinder engine is quite happy as long as the script
# creates a callable thing called TestRunner that can be called to
# create another callable thing.

from net.grinder.script.Grinder import grinder
from net.grinder.script import Test

test1 = Test(1, "Log method")
logTest = test1.wrap(grinder.logger.info)

def doRun():
    logTest("Hello World")

def TestRunner():
    return doRun
Example #12
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):
Example #13
0
def createTestFunction(description, testFunction):
    global testCounter
    testCounter += 1
    test = Test(testCounter, description)
    return test.wrap(testFunction())
Example #14
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):
Example #15
0
import time
import random
import urllib2
import logging, logging.config
import config
from core.user import User 
from core.session import Session
from core.admin import Admin
from core.exceptions import RequestFailedError
from core.exceptions import ConnectionError
from core.exceptions import InvalidArgumentError
import java
 
log = grinder.logger.info
test2 = Test(2, 'Game step test')
logWrapper = test2.wrap(log)


 #   Тест: Игра случайного игрока. Игрок пытается сделать ход в каждой сессии из его списка сессий
   
class TestRunner:
       
    def __init__(self):
        """
            TestRunner constructor
            do nothing 
        """
        pass
      #  grinder.logger.info('Thread #%d started' % grinder.threadNumber )
    
    def __call__(self):
# This script shows the recommended style for scripts, with a
# TestRunner class. The script is executed just once by each worker
# process and defines the TestRunner class. The Grinder creates an
# instance of TestRunner for each worker thread, and repeatedly calls
# the instance for each run of that thread.

from net.grinder.script.Grinder import grinder
from net.grinder.script import Test

# A shorter alias for the grinder.logger.output() method.
log = grinder.logger.output

# Create a Test with a test number and a description. The test will be
# automatically registered with The Grinder console if you are using
# it.
test1 = Test(1, "Log method")

# Wrap the log() method with our Test and call the result logWrapper.
# Calls to logWrapper() will be recorded and forwarded on to the real
# log() method.
logWrapper = test1.wrap(log)


# A TestRunner instance is created for each thread. It can be used to
# store thread-specific data.
class TestRunner:

    # This method is called for every run.
    def __call__(self):
        logWrapper("Hello World")
Example #17
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 *

# assemble Test object
bet_test = Test(1, "bet:Commit bet request.")
# assemble http proxy object
request = bet_test.wrap(HTTPRequest())

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

# define the message body of request
request_msgbody = """
<Ticket multipleDraws="1" totalAmount="20" PIN="123456-a">
    <GameDraw number="20090724" gameId="GAME-113"/>
    <Entry selectedNumber="2,3,5,6,13,1" betOption="1" isQuickPick="0"/>
    <Entry selectedNumber="2,3,5,6,13,7" betOption="1" isQuickPick="0"/>
</Ticket>
"""

# --------------------------------------------------#
# Grinder specified test runner                    #
# --------------------------------------------------#
Example #18
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)),
		)
Example #19
0
# Client Properties
SERVER     = "localhost"
PORT       = 4321

# A shorter alias for the grinder.logger.output() method.
log = grinder.logger.output

# Create a Test with a test number and a description. The test will be
# automatically registered with The Grinder console if you are using
# it.
test1 = Test(1, "RegisterTest")

# Wrap the log() method with our Test and call the result logWrapper.
# Calls to logWrapper() will be recorded and forwarded on to the real
# log() method.
logWrapper = test1.wrap(log)

# A TestRunner instance is created for each thread. It can be used to
# store thread-specific data.
class TestRunner:
    
    # This method is called for every run.
    def __call__(self):
        System.setSecurityManager(RMISecurityManager());
        managerEngine = ManagerEngine()
        remoteController = RemoteController(managerEngine,SERVER)
        registry = LocateRegistry.getRegistry(SERVER,PORT)
        centralController = registry.lookup("CentralController")
        centralController.register(remoteController)
        if centralController is None:
            grinder.statistics.setSuccess(0)
Example #20
0
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)
        total += ret

    return total
streamed_get = test1.wrap(streamed_get)

class TestRunner:
    def __call__(self):
        grinder.logger.output('Selecting dataset from %s' % dataset_list)
        dataset_url = random.choice(data_urls.load_dataset_list(dataset_list))
        grinder.logger.output('Downloading %s' % dataset_url)
        result = streamed_get(dataset_url)
        grinder.logger.output('Transfered %d bytes' % result)
    
Example #21
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")
class TestRunner:
	 
    # There's a runsForThread variable for each worker thread. This
    # statement specifies a class-wide initial value.
    runsForThread = 0
 
    # The __init__ method is called once for each thread.
    def __init__(self):
        self.barrier = grinder.barrier("initialization")
    
        global rayolock
        rayolock.lock()
        try:
            global testNumber        
            testNumber += 1
    
            # There's an initialisationTime variable for each worker thread.
            self.initialisationTime = System.currentTimeMillis()
            self.loadTest = LoadTest()
            self.loadTest.loadTest(testNumber)
        
            self.test = Test(testNumber, "Load Test")
            self.wrapper = self.test.wrap(self.loadTest) 
        
            grinder.logger.output("New thread started at time %s" %
                              self.initialisationTime)
        finally:
            rayolock.unlock()
        grinder.logger.output("Waiting for other threads to initialize")                  
        self.barrier.await()
 
    # The __call__ method is called once for each test run performed by
    # a worker thread.
    def __call__(self):
 
        # Turn off automatic reporting for the current worker thread.
        # Having done this, the script can modify or set the statistics
        # before they are sent to the log and the console.
        grinder.statistics.delayReports = 1    
        
        # We really should synchronise this access to the shared
        # totalNumberOfRuns variable. See JMS receiver example for how
        # to use the Python Condition class.
        global totalNumberOfRuns
        totalNumberOfRuns += 1
 
        self.runsForThread += 1
 
        grinder.logger.output(
            "runsForThread=%d, totalNumberOfRuns=%d, initialisationTime=%d" %
            (self.runsForThread, totalNumberOfRuns, self.initialisationTime))
 		
        try:
            self.wrapper.testLoadScenario2()
        except:
            grinder.statistics.forLastTest.success = 0
 		
        # You can also vary behaviour based on thread ID.
        if grinder.threadNumber % 2 == 0:
            grinder.logger.output("I have an even thread ID.")
 
    # Scripts can optionally define a __del__ method. The Grinder
    # guarantees this will be called at shutdown once for each thread
    # It is useful for closing resources (e.g. database connections)
    # that were created in __init__.
    def __del__(self):
        grinder.logger.output("Thread shutting down") 
Example #23
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)
Example #24
0
applicationProperties = grinderUtil.getApplicationProperties()

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

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

# The default command should be "foobar"
testCommand = applicationProperties.getProperty("test.command")

# The default should be "http://www.example.com/" set in the pom.xml
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()
        elif testCommand == "foobar":
# Hello World, with functions
#
# The Hello World example re-written using functions.
#
# In previous examples we've defined TestRunner as a class; calling
# the class creates an instance and calling that instance invokes its
# __call__ method. This script is for the Luddites amongst you and
# shows how The Grinder engine is quite happy as long as the script
# creates a callable thing called TestRunner that can be called to
# create another callable thing.

from net.grinder.script.Grinder import grinder
from net.grinder.script import Test

test1 = Test(1, "Log method")
logTest = test1.wrap(grinder.logger.output)


def doRun():
    logTest("Hello World")


def TestRunner():
    return doRun
Example #26
0
    def __init__(self):
        test1 = Test(1, "GET some JSON")
        self.request1 = test1.wrap(HTTPRequest())

        test2 = Test(2, "GET profilepicture")
        self.request2 = test2.wrap(HTTPRequest())
Example #27
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
Example #28
0
# A simple example using the MQ plugin that sends a mq message
# and gets a response
#
# 

from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from com.ibm.mq import *      
from org.rextency.mq import MQMsg                 
from org.rextency.mq import MQConnector

mqTest = Test(1,"MQSend Test")
mqex = mqTest.wrap(MQConnector())
mqmessage1 = MQMsg()
log = grinder.logger.output

class TestRunner:
    def __call__(self):
    	mqmessage1.setReplyQueue("REPLYQ")
    	mqmessage1.setReplyToQueue("REPLYQ")
    	mqmessage1.setRequestQueue("REQUEST_Q")
    	mqmessage1.setQueueManager("QueueManager")
    	mqmessage1.setReplyToQueueManager("ReplyToQueueManager")
    	mqmessage1.setMessage("MyMessage MyData 010101")	    	
        mqex.init("myserver.com", "9050", "CHANNEL1", mqmessage1)   
        mqex.SendMessage(mqmessage1)
        log(">>>")
        log(mqex.GetMessage(mqmessage1))
        log(">>>")
        mqex.finish() 
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")
    contenttype = NVPair('Content-Type','text/xml')
    target =  SERVER + '/objects/nextPID?format=xml'

    
    result = HTTPRequest().POST(target,None,[contenttype,auth])
    text =  str(result.getText())
Example #30
0
# A server should be running on the localhost. This script uses the
# example from
# http://xmlrpc-c.sourceforge.net/xmlrpc-howto/xmlrpc-howto-java-server.html
#
# Copyright (C) 2004 Sebasti�n Fontana
# Distributed under the terms of The Grinder license.

from java.util import Vector
from java.lang import Integer
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test

from org.apache.xmlrpc import XmlRpcClient

test1 = Test(1, "XML-RPC example test")
server_url = "http://localhost:8080/RPC2"

serverWrapper = test1.wrap(XmlRpcClient(server_url))


class TestRunner:
    def __call__(self):
        params = Vector()
        params.addElement(Integer(6))
        params.addElement(Integer(3))

        result = serverWrapper.execute("sample.sumAndDifference", params)
        sum = result.get("sum")

        grinder.logger.info("SUM %d" % sum)
Example #31
0
def createTestFunction(description, testFunction):
    global testCounter
    testCounter += 1
    test = Test(testCounter, description)
    return test.wrap(testFunction())
Example #32
0
#
# A server should be running on the localhost. This script uses the
# example from
# http://xmlrpc-c.sourceforge.net/xmlrpc-howto/xmlrpc-howto-java-server.html
#
# Copyright (C) 2004 Sebastián Fontana
# Distributed under the terms of The Grinder license.

from java.util import Vector
from java.lang import Integer
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test

from org.apache.xmlrpc import XmlRpcClient

test1 = Test(1, "XML-RPC example test")
server_url = "http://localhost:8080/RPC2"

serverWrapper = test1.wrap(XmlRpcClient(server_url))

class TestRunner:
    def __call__(self):
        params = Vector()
        params.addElement(Integer(6))
        params.addElement(Integer(3))

        result = serverWrapper.execute("sample.sumAndDifference", params)
        sum = result.get("sum")

        grinder.logger.output("SUM %d" % sum)
Example #33
0
class G2HTTPTest:
    """Parses parameters for an individual test and wraps the test
    invocation in 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."

        request = HTTPRequest(headers=headers)
        self.test = Test(testNumber, properties["description"])
        self.request = self.test.wrap(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))
Example #34
0
"""



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

# constants
TOMCAT_HOST = "qa-perftest001"
TOMCAT_PORT = 8080
THINK_TIME = 400

test1 = Test(1, "Tomcat home")
request1 = test1.wrap(HTTPRequest())
# http://localhost:8080
url1 = "http://%s:%d" % (TOMCAT_HOST, TOMCAT_PORT)

test2 = Test(2, "Tomcat relnotes")
request2 = test2.wrap(HTTPRequest())
# http://localhost:8080/RELEASE-NOTES.txt
url2 = "http://%s:%d/RELEASE-NOTES.txt" % (TOMCAT_HOST, TOMCAT_PORT)

test3 = Test(3, "Tomcat documentation")
request3 = test3.wrap(HTTPRequest())
# http://localhost:8080/docs/
url3 = "http://%s:%d/docs/" % (TOMCAT_HOST, TOMCAT_PORT)

test4 = Test(4, "Tomcat servlets")
request4 = test4.wrap(HTTPRequest())
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Grinder Analyzer; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA



"""
Based on the simple HTTP script in the Grinder script gallery.

Classes:

    TestRunner:     main entry point for the grinder

"""

from net.grinder.script import Test
from net.grinder.script.Grinder import grinder
 
test1 = Test(1, "Log method")
 
# Wrap the info() method with our Test and call the result logWrapper.
logWrapper = test1.wrap(grinder.logger.info)
 
class TestRunner:
    def __call__(self):
        logWrapper("Hello World")
        grinder.sleep(250)

Example #36
0
 def __call__(self):
     kontoTest = Test(101, "Laste vg.no")
     kontoRequest = kontoTest.wrap(HTTPRequest())   
     kontoRequest.GET("http://www.vg.no")
Example #37
0
import time
import random
import urllib2
import logging, logging.config
import config
from core.user import User 
from core.session import Session
from core.admin import Admin
from core.exceptions import RequestFailedError
from core.exceptions import ConnectionError
from core.exceptions import InvalidArgumentError
import java
 
log = grinder.logger.info
test3 = Test(3, 'all users are playing ')
logWrapper = test3.wrap(log)

 #   Тест: Создание по 10 сессий для каждого игрока
   
class TestRunner:
       
    def __init__(self):
        pass
      #  grinder.logger.info('Thread #%d started' % grinder.threadNumber )
    
    def __call__(self):
       # logging.basicConfig(level=logging.DEBUG)
       # log = logging.getLogger('main')
        curThreadInfo = java.lang.Thread.currentThread().toString()
        try:
            logging.debug("******* Staring task %s" % curThreadInfo)
    def __call__(self):
        grinder.statistics.delayReports = 1
        error = grinder.logger.error
        log = grinder.logger.output
        
		randomTall = randomGenerator.nextInt(400000)

        brukerNummer = TestDataGenerator.hentTilfeldigBrukerKontoNummer(randomTall)
        log("Behandler bruker med brukernummer: " + brukerNummer)

		backdoorAktiveringsHeader = ( NVPair("brukerNummer", brukerNummer ), NVPair("brukerType", "49" ) )
        
        httpUtilities = HTTPPluginControl.getHTTPUtilities()

        twitterTest = Test(301, "REST twittersoek")
        twitterRequest = twitterTest.wrap(HTTPRequest(url=baseUrl, headers=backdoorAktiveringsHeader))
        
        profilbildeTest = Test(302, "REST profilbilder")
        profilbildeRequest = profilbildeTest.wrap(HTTPRequest(), headers=backdoorAktiveringsHeader)
        
        try:
            log("Soek etter 'Grinder' paa twitter og henter JSON-resultater")
            twitterJson = twitterRequest.GET("search.json?q=" + sokeord, (), ( httpUtilities.basicAuthorizationHeader(basicAuthBrukernavn, basicAutoPassord), )).text
            twitterObjekt = JSONObject(twitterJson)
            twitterResultater = twitterObjekt.getJSONArray("results")
            for i in range(0,twitterResultater.length()):
                enkeltTweet = twitterResultater.getJSONObject(i)
                brukerID = enkeltTweet.getString("from_user_id_str")
                log("Henter profilbilde for bruker:" + brukerID)
                profilbildeUrl = enkeltTweet.getString("profile_image_url")
                profilbildeRequest.GET(profilbildeUrl, (), ( httpUtilities.basicAuthorizationHeader(basicAuthBrukernavn, basicAutoPassord), ))
Example #39
0
 def __init__(self):
     test = Test(1, "GETing some webpage")
     self.request = test.wrap(HTTPRequest())
Example #40
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):
Example #41
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()
# Hello World, with functions
#
# The Hello World example re-written using functions.
#
# In previous examples we've defined TestRunner as a class; calling
# the class creates an instance and calling that instance invokes its
# __call__ method. This script is for the Luddites amongst you and
# shows how The Grinder engine is quite happy as long as the script
# creates a callable thing called TestRunner that can be called to
# create another callable thing.

from net.grinder.script.Grinder import grinder
from net.grinder.script import Test

test1 = Test(1, "Log method")
logTest = test1.wrap(grinder.logger.output)

def doRun():
    logTest("Hello World")

def TestRunner():
    return doRun
Example #43
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")
        
Example #44
0
# Hello World, with functions
#
# The Hello World example re-written using functions.
#
# In previous examples we've defined TestRunner as a class; calling
# the class creates an instance and calling that instance invokes its
# __call__ method. This script is for the Luddites amongst you and
# shows how The Grinder engine is quite happy as long as the script
# creates a callable thing called TestRunner that can be called to
# create another callable thing.

from net.grinder.script.Grinder import grinder
from net.grinder.script import Test

test1 = Test(1, "Log method")
logTest = test1.wrap(grinder.logger.info)


def doRun():
    logTest("Hello World")


def TestRunner():
    return doRun