编写nGrinder脚本时,如何保持接口的登录状态

在编写压测的脚本时,有两种情况:
1.没有登陆状态,直接压目标接口
2.有登陆状态,需要先登陆
这里主要说一下第二种情况。

脚本

# -*- 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(itsm_id):
    statusCode = [0L, 0L, 0L, 0L]

    result = HTTPRequest().GET('http://x.x.x.x/b/api/v3/circle/circles/query?t=1509618442404')
    PTS.addHttpCode(result.getStatusCode(), statusCode)
    return statusCode


# Make any method call on request1 increase TPS
Test(1,'test').record(tenant)

class TestRunner:
    # initlialize a thread
    def __init__(self):
        grinder.statistics.delayReports=True
        self.login_list = []
        self.threadContext = HTTPPluginControl.getThreadHTTPClientContext()
        self.login_cookies = CookieModule.listAllCookies(self.threadContext)

    # test method
    def __call__(self):
        sumStatusCode = [0L,0L,0L,0L]
        it_id = PTS.random_int(10)
        grinder.logger.info(str(itsm_id))
        headers = [NVPair('Content-Type', 'application/json'),NVPair('Accept', 'application/json'),]
        data = '{"email": "admin","passwd": "admin","code":"uyun","authCode":"h"}'
        result = HTTPRequest().POST('http://x.x.x.x/tenant/api/v1/user/login', data, headers)
        #因为每次执行测试cookie会被清空,所以这里需要每次重新设置cookie
        for c in self.login_cookies:
           CookieModule.addCookie(c, self.threadContext)        
        PTS.sumHttpCode(tenant(it_id),sumStatusCode)

        # if you want to print out log.. Don't use print keyword. Instead, use following.
        #grinder.logger.info(str(sumStatusCode))

        # statusCode[0]代表http code < 300 个数,    statusCode[1] 代表 300<=http code<400 个数
        # statusCode[2]代表400<=http code<500个数,  statusCode[3] 代表 http code >=500个数
        # 如果http code 300 到 400 之间是正常的
        # 那么判断事务失败,请将statusCode[1:4] 改为   statusCode[2:4] 即可
        if sum(sumStatusCode[1:4]) > 0:
            grinder.statistics.forLastTest.success = 0
            grinder.logger.error(u'事务请求中http 返回状态大于300,请检查请求是否正确!')
        else:
            grinder.statistics.forLastTest.success = 1

单个用户和多个用户

多用户

上面的脚本中是多个用户登陆的写法,压测的时候每次跑到测试主体这里,都会随机选择用户重新登录(这里的登陆信息,可以使用resources文件,或者在自定义的脚本里写死)。

单用户

如果只使用一个用户登陆,可以将测试主体里面的登录操作放到上面脚本的构造函数中。这样在压测的时候,只会在初始化的时候登陆一次。

结束

压测新手,如果有问题,轻喷。

推荐阅读更多精彩内容