Python Unittest-对象的数据驱动边缘案例测试?

Python Unittest-对象的数据驱动边缘案例测试?,python,unit-testing,data-driven-tests,data-driven,Python,Unit Testing,Data Driven Tests,Data Driven,考虑以下几点: import unittest class MyClass: def __init__(self, dict: {}): try: if self.validate_dict(dict): self.data = dict except Exception as e: raise Exception('Unable to create MyClass: {}'

考虑以下几点:

import unittest

class MyClass:
    def __init__(self, dict: {}):
        try:
            if self.validate_dict(dict):
                self.data = dict
        except Exception as e:
            raise Exception('Unable to create MyClass: {}'.format(str(e)))

    def validate_dict(self, dict: {}):
        if 'special_key' not in dict:
            raise Exception('Missing Key: special_key')

        # ... perhaps more complicated validation code...
        return True

class MyTests(unittest.TestCase):
    def test_bad_validation(self):
        with self.assertRaises(Exception) as context:
            test_dict = {}
            test_class = MyClass(test_dict)

        self.assertTrue('Unable to create' in str(context.exception))
。。。假设这对于单元测试这个函数来说不是一个糟糕的方法,那么除了
{}
之外,我如何向单元测试添加更多的测试用例呢

我觉得一眼就能看到一个特定测试的所有测试用例的列表,并快速添加新的测试用例是很有用的

我发现了一个专门用来解决这个问题的库,但似乎没有任何方法可以将整个对象(如dict)作为测试参数传递,而无需将其解包。在本例中,我想测试密钥的存在性(可能有很多),因此像DDT那样将它们分解成单独的参数似乎是一个糟糕的解决方案

unittest
是否支持这样的功能?我知道
pytest
可以,但我想先看看
unittest
有什么可能


单元测试此代码的其他方法也值得赞赏。

我相信您正在寻找
子测试方法(在3.4中添加)

在3.6中,对于通过验证检查失败的情况,打印:

======================================================================
FAIL: test_bad_validation (__main__.MyTests) (test_dict={'special_key': 4})
----------------------------------------------------------------------
Traceback (most recent call last):
  File "F:\Python\mypy\tem2.py", line 23, in test_bad_validation
    MyClass(test_dict)
AssertionError: Exception not raised

----------------------------------------------------------------------
Ran 1 test in 0.014s

FAILED (failures=1)
======================================================================
FAIL: test_bad_validation (__main__.MyTests) (test_dict={'special_key': 4})
----------------------------------------------------------------------
Traceback (most recent call last):
  File "F:\Python\mypy\tem2.py", line 23, in test_bad_validation
    MyClass(test_dict)
AssertionError: Exception not raised

----------------------------------------------------------------------
Ran 1 test in 0.014s

FAILED (failures=1)