• python自动化测试学习笔记-unittest参数化


    做接口测试的时候,当一个参数需要输入多个值的时候,就可以使用参数来实现;

    python中unittest单元测试,可以使用nose_parameterized来实现;

    首先需要安装:pip  install nose-parameterized,导入该模块;

    看下面的例子,一般我们写测试用例的时候会追条定义一个test*()的方法,然后执行所有测试用例,如下:

    import unittest
    def calc(a,b):
    res=a+b
    return res

    class MyTest(unittest.TestCase):

    def test1(self):
    res=calc(1,2)
    self.assertEqual(res,3)

    def test2(self):
    res=calc(0,0)
    self.assertEqual(0,0)

    if __name__ == '__main__':
    unittest.main()

    执行查看结果:

    当传入的值类型相同,我们可以用读取list的方式,进行参数化,自动调用执行,如下:

    import unittest
    import nose_parameterized
    def calc(a,b):
    res=a+b
    return res
    data=[
    [1,2,3],
    [0,0,0],
    [9999,0,9999]
    ]
    class MyTest(unittest.TestCase):
      
      #参数化,自动的运行list里边的数据
    @nose_parameterized.parameterized.expand(data)
    def test1(self,a,b,e):
    res=calc(a,b)
    self.assertEqual(res,e)

    if __name__ == '__main__':
    unittest.main()

    上述我们只需要定义一个测试用例方法,使用parameterized方法自动运行data里边的数据,查看执行结果,看到执行了三次:

    还可以通过调用文件的方式来进行unittest参数化;如果测试数据存在于文件中,首先我们需要定义一个将文件转化成list的方法,我们可以根据文件的不同类型使用不同的方法,封装一个tool模块,定义DataToParam

    import os
    import xlrd

    class DataToParam(object):
    def file_exist(self,filename):
    if os.path.isfile(filename):
    return True
    else:
    raise Exception('参数化文件不存在')

    def text(self,filename):
    if self.file_exist(filename):
    with open(filename,'r',encoding='utf-8') as f:
    list=[]
    for line in f :
    list.append(line.strip().split(','))
    return list


    def excel(self,filename):
    if self.file_exist(filename):
    book=xlrd.open_workbook(filename)
    sheet=book.sheet_by_index(0)
    rows=sheet.nrows
    list=[]
    for row in range(rows):
    list.append(sheet.row_values(row))
    return list

    调用DataToParam中的函数,将文件转化成list

    文件:


    import unittest
    from tool import DateToParam
    import nose_parameterized
    def calc(a,b):
    res=a+b
    return res
    class MyTest(unittest.TestCase):

    #参数化,自动的运行list里边的数
    @nose_parameterized.parameterized.expand(DateToParam.excel(r'C: est est.xlsx'))

    def test_func(self,a,b,e):
    e=float(e)
    res=calc(a,b)
    self.assertEqual(res,e)


    if __name__ == '__main__':
    unittest.main()

    执行查看结果:

  • 相关阅读:
    【LeetCode】3. Longest Substring Without Repeating Characters
    【LeetCode】65. Valid Number
    【LeetCode】8. String to Integer (atoi)
    【Java】 大话数据结构(18) 排序算法(5) (直接插入排序)
    【LeetCode】557. Reverse Words in a String III
    【LeetCode】151. Reverse Words in a String
    【LeetCode】28. Implement strStr()
    【LeetCode】125. Valid Palindrome
    【Java】 遍历HashMap
    【LeetCode】170. Two Sum III – Data structure design
  • 原文地址:https://www.cnblogs.com/phoebes/p/8611394.html
Copyright © 2020-2023  润新知