Python nose单元测试框架结合requests库进行web接口测试

简介: [本文出自天外归云的博客园] 之前写过一篇关于nose使用方法的博客。最近在做一元乐购产品的接口测试,结合着python的requests库可以很方便的进行web接口测试并生成测试结果。接口测试脚本示例如下(脚本路径为“E:\forPytest\test_new_product_detail.

[本文出自天外归云的博客园]

之前写过一篇关于nose使用方法的博客。最近在做一元乐购产品的接口测试,结合着python的requests库可以很方便的进行web接口测试并生成测试结果。接口测试脚本示例如下(脚本路径为“E:\forPytest\test_new_product_detail.py”):

# -*- coding: utf-8 -*-
from nose.tools import nottest,istest,assert_equal,assert_in
from nose_ittr import IttrMultiplier, ittr
import requests,json

'''
    用户信息配置
'''
user1 = ""
user2 = ""
pwd = ""

class TestNewProductDetail(object):
    __metaclass__ = IttrMultiplier

    '''
        非进行中商品
    '''
    @nottest
    @ittr(productId=["2016101716PT022944258","2016101411PT022935002"],accountId=[user1,user2]) 
    def test_new_product_detail_1(self):
        s = requests.Session()
        url = "https://api.winyylg.com/new_product_detail.html"
        periodId = "1"
        data = {
            "productId":self.productId,
            "accountId":self.accountId,
            "sessionId":getSessionId(s,self.accountId,pwd),
            "periodId":periodId
        }
        r = json.loads(s.get(url=url,params=data).text)
        if self.productId == "":
            assert_equal(r["result"],-1,msg="productId is null or not exists.")
        else:
            assert_equal(r["result"],100,msg="result not 100")
        basic_asserts(r)

    '''
        没有sessionId
        没有accountId
        非进行中商品
    '''
    @nottest
    @ittr(productId=["2016101716PT022944258"]) 
    def test_new_product_detail_2(self):
        s = requests.Session()
        url = "https://api.winyylg.com/new_product_detail.html"
        periodId = "1"
        data = {
            "productId":self.productId,
            "periodId":periodId
        }
        r = json.loads(s.get(url=url,params=data).text)
        assert_equal(r["result"],100,msg="result not 100")
        basic_asserts(r)

    '''
        进行中商品
    '''
    @istest
    @ittr(productId=["2016102016PT023048118"],accountId=[user1,user2])
    def test_new_product_detail_3(self):
        s = requests.Session()
        url = "https://api.winyylg.com/new_product_detail.html"
        periodId = "1"
        data = {
            "productId":self.productId,
            "accountId":self.accountId,
            "sessionId":getSessionId(s,self.accountId,pwd),
            "periodId":periodId
        }
        r = json.loads(s.get(url=url,params=data).text)
        if self.productId == "":
            assert_equal(r["result"],-1,msg="productId is null or not exists.")
        else:
            assert_equal(r["result"],100,msg="result not 100")
        basic_asserts(r)
        for coupon in r["participateInfo"]["couponList"]:
            assert_coupon_fields(coupon)
            print coupon

@nottest
def basic_asserts(result):
    print "\n"
    tylan_assert_in("resultDesc",result)
    tylan_assert_in("product",result)
    tylan_assert_in("participateInfo",result)
    tylan_assert_in("prizeUser",result)
    tylan_assert_in("calculationDetailUrl",result)
    tylan_assert_in("imageTextUrl",result)
    tylan_assert_in("additionalModel",result)
    tylan_assert_in("userParticipateRecords",result)
    tylan_assert_in("pastDetails",result)
    #print result["participateInfo"]
    tylan_assert_in("couponList",result["participateInfo"])
    #print result["participateInfo"]["couponList"]

@nottest
def assert_coupon_fields(result):
    tylan_assert_in("couponId",result)
    tylan_assert_in("couponSchemeId",result)
    tylan_assert_in("couponType",result)
    tylan_assert_in("status",result)
    tylan_assert_in("threshold",result)
    tylan_assert_in("couponAmount",result)
    tylan_assert_in("remainAmount",result)
    tylan_assert_in("accountId",result)
    tylan_assert_in("takenId",result)
    tylan_assert_in("createTime",result)
    tylan_assert_in("updateTime",result)
    tylan_assert_in("activeTime",result)
    tylan_assert_in("expireTime",result)
    tylan_assert_in("expireDay",result)
    tylan_assert_in("couponName",result)
    tylan_assert_in("couponDesc",result)
    tylan_assert_in("couponApply",result)
    tylan_assert_in("couponApplyDesc",result)

@nottest
def tylan_assert_in(a,b):
    assert_in(a,b,msg=a+" not include in "+str(b))

@nottest
def getSessionId(session,accountId,pwd):
    url = "https://hygtest.ms.netease.com/winyyg/scripts"
    data = {
        "username":accountId,
        "password":pwd,
        "tag":"winyylg_login"
    }
    r = json.loads(session.post(url,data).text)
    return r[0][1]

'''
    新的奖品详情页接口,将原来的奖品详情页的两个接口合成了一个接口:
    1. https://api.winyylg.com/product_detail.html
    2. https://api.winyylg.com/participate_records.html
    新的接口为:https://api.winyylg.com/new_product_detail.html
    接口类型为:GET
    改动:去掉historyAwardUrl
    请求参数:
        productId
        accountId
        sessionId
        periodId
    返回参数:
        result
        resultDesc
        product
            ...
        participateInfo
            ...
            couponList
                ...
        prizeUser
            ...
        calculationDetailUrl
        imageTextUrl
        additionalModel
            ...
        userParticipateRecords
        pastDetails
'''

在命令行中用例所在的目录下执行命令“nosetests --with-html-output --html-out-file=test_result.html -v”(若想查看脚本中的输出需要在命令结尾再加一个“-s”):

生成的结果文件:

利用nose框架的assert方法、@istest和@nottest装饰器、@ittr装饰器(需安装传参插件)等封装可以很方便的进行测试,再结合python的requests库就可以进行web接口测试了,非常好用。

相关文章
|
3天前
|
JSON JavaScript 测试技术
Postman接口测试工具详解
Postman接口测试工具详解
13 1
|
5天前
|
测试技术 Go Python
在python中测试应用
【6月更文挑战第29天】本文介绍Python的unittest是内置的单元测试框架,适合线性控制流的代码测试。并举实例说明,如何组织测试代码,如何构造脚手架和测试套件。
18 6
在python中测试应用
|
2天前
|
测试技术 API 持续交付
【Python自动化测试】文章探讨了Python在测试领域的关键作用,分为三部分
【7月更文挑战第2天】【Python自动化测试】文章探讨了Python在测试领域的关键作用,分为三部分:1) 自动化测试的重要性与Python的易用性、库支持、跨平台和社区优势;2) Unittest作为标准测试框架的基础用法,及Pytest的灵活性与强大功能;3) 实践中包括Selenium的Web UI测试、Requests的API测试,强调测试隔离、持续集成等最佳实践。Python助力高效稳定的软件测试。
9 2
|
1天前
|
测试技术 Python
|
1天前
|
JSON 数据格式
postman 实用教程(含带 token 访问需登录权限的接口、测试文件上传接口、测试文件下载接口)
postman 实用教程(含带 token 访问需登录权限的接口、测试文件上传接口、测试文件下载接口)
4 0
后端测试,编写好了一个接口,怎样用postman测试
后端测试,编写好了一个接口,怎样用postman测试
|
1天前
|
API 开发工具
支付系统23-------使用沙箱账号进行支付测试,统一收单并支付页面接口的调用
支付系统23-------使用沙箱账号进行支付测试,统一收单并支付页面接口的调用
|
2天前
一款测试接口的好插件
一款测试接口的好插件
5 0
|
6天前
|
消息中间件 缓存 中间件
【赠书活动 - 第1期】- 测试工程师Python开发实战(异步图书出品)| 文末送书
【赠书活动 - 第1期】- 测试工程师Python开发实战(异步图书出品)| 文末送书
|
6天前
|
JSON 前端开发 测试技术
从零开始:学习使用 Postman 进行接口测试
在当前,API(应用程序接口)的使用变得越来越普遍。其中,HTTP/HTTPS API 是最常见的一种。无论是开发前端还是后端,测试 API 都是一个关键环节。Postman 是一种流行且强大的 API 测试工具,能够帮助开发人员轻松地进行接口测试和调试。