python学习笔记-day11-02【单元测试框架unittest -之数据驱动ddt】

接着聊聊单元测试框架unittest -之数据驱动ddt, 如何使用数据驱动。

一、安装依赖模块

pip install ddt

二、如何使用ddt模块

1、数据驱动模块ddt使用方式

@ddt.ddt   #在类的这里写上,表明使用的ddt,数据驱动方式
class Login(unittest.TestCase):
   
    @ddt.file_data('login01.yaml')  #这里写上@ddt.file_data('login01.yaml') 表明数据驱动的文件是login01.yaml文件,
这是测试用你的请求参数与数据,执行用例时,每次只能读一个文件,
  def test_request(self, **kwargs):
pass

2、使用示例:

数据驱动测试有例文件,以yaml格式文件进行测试用例的方式:

login01.yaml文件:

-  #表明下面的数据是一个列表
  url: /api/user/login
  method: post
  detail: 正常登录
  data:
    username: test
    passwd: 111111
  check:
    - userId   #这里也是一个列表,结果检测
    - sign

-
  url: /api/user/login
  method: post
  detail: 密码错误
  data:
    username: test
    passwd: 2222222
  check:
    - 密码错误

-
  url: /api/user/login
  method: post
  detail: 不传密码
  data:
    username: test
  check:
    - 必填参数未填

测试执行代码 :

testlogin.py:

import unittest
import ddt
from BeautifulReport import  BeautifulReport as bf
import requests
from urllib import parse


@ddt.ddt
class Login(unittest.TestCase):
    base_url = 'http://xxxx.xxxx.xxxx'
    @ddt.file_data('login01.yaml')
    def test_request(self, **kwargs):  #**kwargs可变参数,参数不固定,当参数较多时,可以使用这种方式,没有参数的时候,不会报错,只是取不到数据而已
        detail = kwargs.get('detail', '没写用例描述')
        self._testMethodDoc = detail  #动态的用例描述
        url = kwargs.get('url')
        url = parse.urljoin(self.base_url, url) #拼接好url
        method = kwargs.get('method', 'get')
        data = kwargs.get('data', {}) #请求参数
        header = kwargs.get('header', {}) #请求头
        cookie = kwargs.get('cookie') #cookie
        check = kwargs.get('check')
        method = method.lower() #便于处理

        try:
            if method == 'get':
                res = requests.get(url, params=data, cookies=cookie, headers=header).text
            else:
                res = requests.post(url, data=data, cookies=cookie, headers=header).text
        except Exception as e:
            print('接口请求出错')
            res = e

        for c in check:
            self.assertIn(c, res, msg='预期结果不符, 预期结果【%s】,实际结果【%s】' %(c, res))

        # userid = check.get('userId')
        # # error_code = check.get('error_code')
        # # if userid:
        # #     real_userid = res.get('login_info').get('userId')
        # #     self.assertEqual(userid, real_userid, '校验userid是否一样')
        # #
        # # real_code = res.get('error_code')
        # # self.assertEqual(error_code, real_code, '校验接口返回码是否一致')

#不要使用这样方式,校验结果没有通用化
suite = unittest.TestSuite() #测试套件 suite.addTest(unittest.makeSuite(Login)) #将所有的测试用例加到测试套件里去 run = bf(suite) run.report('login_test', '登录测试用例') print(run.success_count) #通过的次数 print(run.failure_count) #失败的次数 #1、运行的用例条数是不是和你的用例数一样 #2、看看有没有其他不对的地方

三、执行

直接在测试用例文件即要执行,或是python testlogin.py也可以

猜你喜欢

转载自www.cnblogs.com/shmily2018/p/9131285.html