nGrinder脚本-Jython实现Post请求

2015-06-08  籽藤 

nGrinder是一款超级好用的压力测试工具。自从用了它,我就再也不想回到JMeter。本来嘛,分布式压测环境容易部署,执行界面也简单,开发同事都很喜欢。

nGrinder脚本支持Groovy和Jython两种语言,而且都有脚本模板。稍作修改就可以做API并发测试,简直是神器。以下是用Jython实现Post请求的nGrinder脚本,涉及到:

[参考]Jython语言官方学习指南:http://www.jython.org/jythonbook/en/1.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 applewu 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 NVPair from jarray import zeros from org.json import JSONObject import random import string import datetime 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, "******") request1 = HTTPRequest(url = "https://api.******.com") # Make any method call on request1 increase TPS test1.record(request1) class TestRunner: # initlialize a thread def __init__(self): grinder.statistics.delayReports=True pass # test method def __call__(self): try: headers = ( NVPair("Content-type", "application/json"), NVPair("Authorization", "Bearer ******")) b = '''{ "subject": "%(subject)s", "body": "gaDXstiHQnyMAYtFpBGJhZvlkxRVa测试123omiITHmUmfSSlQsAsZyLTSjFLjyeUkyxBKCCUdWdwJMcZYE", "amount": "10", "order_no": "%(order_no)s", "channel": "jdpay_wap", "currency": "cny", "client_ip": "127.0.0.1", "app": { "id": "******" }, "extra":{ "success_url":"baidu.com", "fail_url":"diandian.com" } }''' now = datetime.datetime.now() subject = now.strftime("%Y%m%d-%H%M%S") # Generate the random string for order number seq = string.letters + string.digits order_no = ''.join(random.choice(seq) for _ in xrange(12)) body = b%{'subject':str(subject),'order_no':str(order_no)} result = request1.POST('/v1/charges',body,headers) # You get the message body using the getText() method. # if result.getText().find("HELLO WORLD") != -1 : # grinder.statistics.forLastTest.success = 1 # else : # grinder.statistics.forLastTest.success = 0 # if you want to print out log.. Don't use print keyword. Instead, use following. # grinder.logger.info("Hello World") if result.getStatusCode() == 200 : grinder.statistics.forLastTest.success = 1 elif result.getStatusCode() in (301, 302) : grinder.logger.warn("Warning. The response may not be correct. The response code was %d." % result.getStatusCode()) grinder.statistics.forLastTest.success = 1 else : grinder.statistics.forLastTest.success = 0 except Exception, e: print e
791°/7912 人阅读/0 条评论 发表评论

登录 后发表评论