nGrinder学习笔记 — post请求

Post请求:

带json格式内容:

Groovy :

import HTTPClient.HTTPResponse
import HTTPClient.NVPair
import ch.qos.logback.classic.Level
import net.grinder.plugin.http.HTTPPluginControl
import net.grinder.plugin.http.HTTPRequest
import net.grinder.script.GTest
import net.grinder.scriptengine.groovy.junit.GrinderRunner
import net.grinder.scriptengine.groovy.junit.annotation.BeforeProcess
import net.grinder.scriptengine.groovy.junit.annotation.BeforeThread
import org.junit.Test
import org.junit.runner.RunWith
import org.slf4j.LoggerFactory

import static net.grinder.script.Grinder.grinder
import static org.hamcrest.Matchers.is
import static org.junit.Assert.assertThat

/**
 * Created by nd-xm-mac5 on 15/12/24.
 */
@RunWith(GrinderRunner)
class LoginDemo {
    public static GTest test
    public static HTTPRequest request

    @BeforeProcess
    public static void beforeProcess() {
        HTTPPluginControl.getConnectionDefaults().timeout = 6000
        test = new GTest(1, "192.168.70.206")
        request = new HTTPRequest()
        test.record(request);
        grinder.logger.info("before process.");
    }

    @BeforeThread
    public void beforeThread() {
//        只打印错误的log
        LoggerFactory.getLogger("worker").setLevel(Level.ERROR)

        grinder.statistics.delayReports = true;
        grinder.logger.info("before thread.");
    }

    private NVPair[] headers() {
        return [
                new NVPair("Content-type", "application/json;charset=UTF-8")
        ];
    }

    @Test
    public void test1() {
        // json字符串
        def json = '{"tenant_code":"XXX","user_name":"XX","password":"X","skip_duplicate_entries":true,"type":"0"}';
        // 发起请求
        HTTPResponse result = request.POST("http://192.XXX.XX.XXX:XXXX/XXX/XX/login", json.getBytes(), headers());
        grinder.logger.info(result.getText());
        grinder.logger.info(result.getHeader("Content-type"));

        if (result.statusCode == 301 || result.statusCode == 302) {
            grinder.logger.warn("Warning. The response may not be correct. The response code was {}.", result.statusCode);
        } else {
            assertThat(result.statusCode, is(200));
        }
    }
}


Python:

# -*- coding:utf-8 -*-
#
# 一个简单的HTTP请求脚本示例
#
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
#导入对JSON格式返回值的处理函数
from org.json import JSONObject


control = HTTPPluginControl.getConnectionDefaults()
#请求重定向开关
# control.followRedirects = 1
#超时时间设置
control.timeout = 6000

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

# Make any method call on request1 increase TPS
test1.record(request1)

class TestRunner:
    #初始化,仅执行一次
    def __init__(self):
        grinder.statistics.delayReports=True
        pass


    #类似LR的action,压测时会多次执行
    # test method       
    def __call__(self):

                #url地址
        url = 'http://www.xxx.com/v0.93/login'
        #headers信息
        headers = [NVPair("Content-Type","application/json"),
                   NVPair("Authorization","123")
                   ]
        #JSON格式的请求内容
        submitdata = '{"login_name":"156599@ND","password":"80fba977d063a6f7262a8a9c95f61140"}'
        #URL请求
        result = request1.POST(url,submitdata,headers)

        #打印输出URL请求返回内容
        #grinder.logger.info(result.getText())

        #返回结果检查,有返回特定字符,则判断请求成功
        if result.getText().find("检查内容") != -1 :
            grinder.statistics.forLastTest.success = 1
        else :
            grinder.statistics.forLastTest.success = 0
            #请求失败,则输出失败时服务器返回的值
            grinder.logger.info(result.getText()) 


带表单格式内容:

python:

# -*- coding:utf-8 -*-
#
# 一个简单的HTTP请求脚本示例
#
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
#导入对JSON格式返回值的处理函数
from org.json import JSONObject


control = HTTPPluginControl.getConnectionDefaults()
#请求重定向开关
# control.followRedirects = 1
#超时时间设置
control.timeout = 6000

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

# Make any method call on request1 increase TPS
test1.record(request1)

class TestRunner:
    #初始化,仅执行一次
    def __init__(self):
        grinder.statistics.delayReports=True
        pass


    #类似LR的action,压测时会多次执行
    # test method       
    def __call__(self):

                #url地址
        url = 'http://101uccenter.qa.web.sdp.101.com'
        #headers信息
        headers = [NVPair("Content-Type","application/json"),NVPair("Authorization","123")]
        #JSON格式的请求内容
        submitdata = [NVPair("a","1"),NVPair("b","2"),NVPair("c","3")]
        #URL请求
        result = request1.POST(url,submitdata,headers)

        #打印输出URL请求返回内容
        #grinder.logger.info(result.getText())

        #返回结果检查,有返回特定字符,则判断请求成功
        if result.getText().find("检查内容") != -1 :
            grinder.statistics.forLastTest.success = 1
        else :
            grinder.statistics.forLastTest.success = 0
            #请求失败,则输出失败时服务器返回的值
            grinder.logger.info(result.getText()) 


Groovy:

import HTTPClient.HTTPResponse
import HTTPClient.NVPair
import ch.qos.logback.classic.Level
import groovy.json.JsonSlurper
import net.grinder.plugin.http.HTTPPluginControl
import net.grinder.plugin.http.HTTPRequest
import net.grinder.script.GTest
import net.grinder.scriptengine.groovy.junit.GrinderRunner
import net.grinder.scriptengine.groovy.junit.annotation.BeforeProcess
import net.grinder.scriptengine.groovy.junit.annotation.BeforeThread
import org.apache.http.impl.client.DefaultHttpClient
import org.junit.Test
import org.junit.runner.RunWith
import org.slf4j.LoggerFactory

import static net.grinder.script.Grinder.grinder
import static org.hamcrest.Matchers.is
import static org.junit.Assert.assertThat

/**
 * Created by nd-xm-mac5 on 15/12/24.
 */
@RunWith(GrinderRunner)
class PostDemo {
    public static GTest test
    public static HTTPRequest request

    @BeforeProcess
    public static void beforeProcess() {
        HTTPPluginControl.getConnectionDefaults().timeout = 6000
        test = new GTest(1, "192.168.70.206")
        request = new HTTPRequest()
        test.record(request);
        grinder.logger.info("before process.");
    }

    @BeforeThread
    public void beforeThread() {
//        只打印错误的log
        LoggerFactory.getLogger("worker").setLevel(Level.ERROR)
        grinder.statistics.delayReports = true;
        grinder.logger.info("before thread.");
    }

    private NVPair[] headers() {

        return [
                new NVPair("Content-type", "application/json;charset=UTF-8")
        ];
    }

    private NVPair[] jsons() {

        return [
                new NVPair("A", "1"),
                new NVPair("B", "2")
        ];
    }

    @Test
    public void test1() {

        HTTPResponse result = request.POST("URL", jsons(), headers());

        grinder.logger.info(result.getText());
        grinder.logger.info(result.getHeader("Content-type"));

        if (result.statusCode == 301 || result.statusCode == 302) {
            grinder.logger.warn("Warning. The response may not be correct. The response code was {}.", result.statusCode);
        } else {
            assertThat(result.statusCode, is(200));
        }
    }
}


  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值