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接口测试了,非常好用。

相关文章
|
11天前
|
存储 缓存 JavaScript
python实战篇:利用request库打造自己的翻译接口
python实战篇:利用request库打造自己的翻译接口
26 1
python实战篇:利用request库打造自己的翻译接口
|
22天前
|
Web App开发 Python
在ModelScope中,你可以使用Python的浏览器自动化库
在ModelScope中,你可以使用Python的浏览器自动化库
15 2
|
1天前
|
JSON API 数据格式
python的request库如何拿到json的返回值
python的request库如何拿到json的返回值
4 0
|
4天前
|
监控 测试技术 API
深入理解自动化测试框架Selenium的设计与实现
【4月更文挑战第14天】在软件开发过程中,自动化测试是确保代码质量、减少人工重复劳动的关键步骤。Selenium作为一款广泛使用的自动化测试工具,提供了对多种浏览器和操作系统的支持。本文将探讨Selenium的核心组件及其架构设计,分析其如何通过WebDriver与浏览器交互,以及它如何支持多种编程语言进行脚本编写。同时,我们还将讨论Selenium Grid的作用以及它如何实现并行测试,以缩短测试周期并提高测试效率。
164 58
|
4天前
|
Web App开发 测试技术 网络安全
|
6天前
|
Web App开发 前端开发 Java
框架分析(11)-测试框架
框架分析(11)-测试框架
|
9天前
|
JSON 测试技术 持续交付
自动化测试与脚本编写:Python实践指南
【4月更文挑战第9天】本文探讨了Python在自动化测试中的应用,强调其作为热门选择的原因。Python拥有丰富的测试框架(如unittest、pytest、nose)以支持自动化测试,简化测试用例的编写与维护。示例展示了使用unittest进行单元测试的基本步骤。此外,Python还适用于集成测试、系统测试等,提供模拟外部系统行为的工具。在脚本编写实践中,Python的灵活语法和强大库(如os、shutil、sqlite3、json)助力执行复杂测试任务。同时,Python支持并发、分布式执行及与Jenkins、Travis CI等持续集成工具的集成,提升测试效率和质量。
|
11天前
|
监控 物联网 Linux
python测试串口最大通信速率
【4月更文挑战第5天】
|
13天前
|
jenkins 测试技术 持续交付
软件测试|docker搭建Jenkins+Python+allure自动化测试环境
通过以上步骤,你可以在Docker中搭建起Jenkins自动化测试环境,实现Python测试的自动化执行和Allure报告生成。 买CN2云服务器,免备案服务器,高防服务器,就选蓝易云。百度搜索:蓝易云
32 6
|
14天前
|
数据采集 网络协议 API
python中其他网络相关的模块和库简介
【4月更文挑战第4天】Python网络编程有多个流行模块和库,如requests提供简洁的HTTP客户端API,支持多种HTTP方法和自动处理复杂功能;Scrapy是高效的网络爬虫框架,适用于数据挖掘和自动化测试;aiohttp基于asyncio的异步HTTP库,用于构建高性能Web应用;Twisted是事件驱动的网络引擎,支持多种协议和异步编程;Flask和Django分别是轻量级和全栈Web框架,方便构建不同规模的Web应用。这些工具使网络编程更简单和高效。