unittest参数化

 本文主要用来简单介绍unittest参数化的内容

本段话引自牛牛的博客(牛牛杂货铺-unittest参数化http://www.nnzhp.cn/archives/584):

我们在写case的时候,如果用例的操作是一样的,就是参数不同,比如说要测一个登陆的接口,要测正常登陆的、黑名单用户登陆的、账号密码错误的等等,在unittest里面就要写多个case来测试。

这样的情况只是调用接口的时候参数不一样而已,再写多个case的话就有点多余了,那怎么办呢,就得把这些参数都写到一个list里面, 然后循环去执行这个case。这样就可以省去写多个case了。

unittest:单元测试框架

ddt模块:数据驱动框架,用于将数据导入、传参。

测试用例的类需要导入参数,则需要在类前加@ddt.ddt来修饰该类。

  函数内若需传参,则在函数前加@ddt.data(******)用于传递数据。若函数有多个入参,则在函数前加@ddt.unpack;若函数入参只有一个参数,则只有一个@ddt.data(****)即可。

  函数传参为文件时,在函数前加@ddt.file_data('文件绝对路径/文件名')

BeautifulReport模块:生成测试报告

(1)下面代码中的解释:def test_interface(self,**test_data):使用"**"修饰参数名,表示传入的是字典的格式 key:value
(2)self._testMethodDoc = detail:这个变量self._testMethodDoc是用来指定用例描述的。


 unittest参数化.py的代码如下:

import unittest
import ddt
import requests
import BeautifulReport as br
def login(username,passwd):
    print(username,passwd)
    return True
@ddt.ddt
class Login(unittest.TestCase):

    #如果是一个数组,函数有多个入参,那就写上unpack
    # @ddt.data(['u1','p1',True],['u2','p2',False],['u3','p3',True])
    # @ddt.unpack
    # def test_login(self,username,passwd,check):
    #     res = login(username,passwd)
    #     self.assertEqual(check,res)
    #
    # #下面这样只有一个参数的,就不需要些unpack了
    # @ddt.data(1,2,3,4)
    # def test_query(self,key):
    #     print('run...',key)
    #

    @ddt.file_data('login.yaml')
    def test_interface(self,**test_data): #代表就是每一个用例数据的那个字典。
        url = test_data.get('url') #url
        method = test_data.get('method').upper() #method
        detail = test_data.get('detail','没写用例描述')#用例描述
        self._testMethodDoc = detail #这个变量就是指定用例描述的
        data  = test_data.get('data',{}) #请求数据
        headers = test_data.get('headers',{}) #请求头
        cookies = test_data.get('cookies',{}) #cookie
        is_json = test_data.get('is_json',0)#标识入参是否为json
        check = test_data.get('check') #断言
        if method=='POST':
            if is_json:
                res = requests.post(url, json=data, cookies=cookies, headers=headers).text
            else:
                res = requests.post(url,data=data,cookies=cookies,headers=headers).text
        elif method=='GET':
            res = requests.get(url,params=data,cookies=cookies,headers=headers).text
        for c in check:
            self.assertIn(c,res,'%s不在%s里面'%(c,res))


# unittest.main()
report = br.BeautifulReport(unittest.makeSuite(Login))
report.report('接口测试','login_report.html')

yaml文件内填写接口参数,如下:

-
  url : http://ip/api/user/login
  method : post
  detail : 登录接口
  data :
    username : niuhanyang
    passwd : aA123
  check :
     - sign
     - userId

-
  url : http://ip/api/user/all_stu
  method : get
  check :
    - sdfsdfs
  headers :
    Referer : http://api.nnzhp.cn/
  detail : 获取所有学生信息接口
原文地址:https://www.cnblogs.com/Noul/p/9932377.html