将参数传递给python unittests函数

将参数传递给python unittests函数,python,python-unittest,Python,Python Unittest,C#的NUnit能够使用不同的参数多次运行相同的测试: [TestCase(12,2,6)] [TestCase(12,4,3)] public void DivideTest(int n, int d, int q) { Assert.AreEqual( q, n / d ); } 在Python的unittest模块中也可以这样做吗 我有点喜欢 def test_divide(self): for n, d, q in [(12, 2, 6), (12, 4, 3)]:

C#的NUnit能够使用不同的参数多次运行相同的测试:

[TestCase(12,2,6)]
[TestCase(12,4,3)]
public void DivideTest(int n, int d, int q) {
  Assert.AreEqual( q, n / d ); 
} 
在Python的
unittest
模块中也可以这样做吗

我有点喜欢

def test_divide(self):
   for n, d, q in [(12, 2, 6), (12, 4, 3)]:
     self.assertEqual(q, n / d)
但是它

  • 错误时不打印n、d、q的值
  • 第一个失败会中断整个测试,NUnit将选择其他参数并继续测试

Python没有用于添加此类测试的快捷语法,但可以将测试动态添加到unittest类中

根据您提供的示例,您可以按如下方式执行此操作:

import os
import unittest


class TestMath(unittest.TestCase):
    pass


def add_method(cls, method_name, test_method):
    """
    Add a method to a class.
    """
    # pylint warns about re-defining the method name, I do want to re-define
    # the name in this case.
    # pylint: disable=W0622
    test_method.__name__ = method_name
    if not hasattr(cls, test_method.__name__):
        setattr(cls, test_method.__name__, test_method)


def add_divide_test(n, d, q):
    """
    Adds a test method called test_divide_n_by_d to the TestMath class that
    checks the result of the division operation.
    """

    def test_method(self):
        self.assertEqual(q, n / d)

    add_method(
        TestMath, "test_divide_%d_by_%d" % (n, d), test_method
    )

# Adding an entry to this list will generate a new unittest in the TestMath
# class
value_list = [
    [12, 2, 6],
    [12, 4, 3],
]

for values in value_list:
    add_divide_test(values[0], values[1], values[2])
如果您想基于目录中的文件列表生成单元测试,这将变得非常有用。例如,您可以在
test\u资源
中收集数据文件,并实现类似的功能

for file_name in os.listdir("test_resources"):
    add_test_for_file(file_name)
一旦设置为添加新的单元测试,您只需在
test\u resources
目录中添加新文件即可添加新测试