一个基于Behave框架的http接口测试实例

来源:互联网 发布:怎样定投网络理财投资 编辑:程序博客网 时间:2024/05/17 03:28

前言:本人没怎么做过http接口测试,只是最近学习了一下,Behave框架也是最近学习的,如果有不对的请各位大神指点,感谢!

1.1       接口准备

本次get请求的接口用的是百度接口:wd=搜索关键词;rn=结果条数

https://www.baidu.com/s?wd=python&rn=3

post请求的接口是引用了虫师的实例资源,出处如下:

http://www.cnblogs.com/fnng/p/4853996.html

1.2       实例详解

项目目录结构如下:

.../APItest

.../APItest/HTTPAPI

.../APItest/HTTPAPI/http case.feature

.../APItest/HTTPAPI/steps

.../APItest/HTTPAPI/steps/httptest.py

 

http case.feature用Scenario Outline设计测试用例,测三个接口,分别是带参的get请求、不带参的get请求,和post请求,内容如下:

Feature: http api testing  Scenario Outline: for http api testing    Given request type is <request_type>    When I input HTTP api <url> and <parametes>    Then The status code is 200   Examples: all request type    |request_type|url                    |parametes|    |get         |https://www.baidu.com/s|{'wd':'python','rn':'3'}|    |get         |https://www.baidu.com/s|{}                      |    |post        |http://127.0.0.1:5000/login|{'username':'zhangsan','password':'123'}|

 

 

 

httptest.py,处理http请求的类,这里我只是简单地写了一下一般的get和post请求,以后可以优化。代码如下:

# coding:utf-8__author__ = 'helen'import requestsfrom behave import *@Given('request type is {request_type}')def step_impl(context,request_type):    context.request_type = request_type@When('I input HTTP api {url} and {parameters}')def step_impl(context,url,parameters):    context.url = url    context.parameters = parameters@Then('The status code is 200')def step_impl(context):    try:        if context.request_type=='get':            r = requests.get(url=context.url,params=context.parameters)        elif context.request_type == 'post':            r = requests.post(url=context.url,data=context.parameters)        assert r.status_code == 200    except requests.HTTPError,e:        e.strerror        e.args

 


 

1.3       执行测试

我的APItest项目已配置在jenkins,所以我在jenkins里面直接构建即可,我们可以在执行结果的控制台中查看到执行输出内容,如下图:

 

 

 

当然,你也可以在cmd命令行中直接执行,如下图所示:

 

 

 

你还可以把执行记录保存在文件中,如下图:

 

 

然后在D盘中我们就可以看到生成的test.txt文件,里面的内容与cmd的输出一至。

0 0
原创粉丝点击