pytest
(2.8.3) 是否与 self.subTest()
等效(如 Python 3 的 unittest
中所示)?
这是我尝试转换的代码的简化版本:
class MyUnittestTest(TestCase):
def test_permutations(self):
on_off = True, False
for prefix, params, suffix in product(on_off, on_off, on_off):
expected_prefix = 'something' if prefix else ''
expected_params = ('something',) if params else ()
expected_suffix = b'something' if suffix else b''
with self.subTest(prefix=prefix, params=params, suffix=suffix):
result = do_magic(prefix=prefix, params=params, suffix=suffix)
self.assertEqual(result.prefix, expected_prefix)
self.assertEqual(result.params, expected_params)
self.assertEqual(result.suffix, expected_suffix)
目前,我所拥有的只是为每个排列定义一个测试。一定有比这更好的方法:
class MyPytestTest:
def test_on_on_on(self):
expected_prefix = ...
result = do_magic(...)
assert ...
def test_on_on_off(self):
...
pytest-subtests
插件添加。
要使用它,请将
subtests
夹具注入测试中:
def test_permutations(subtests):
on_off = True, False
for prefix, params, suffix in product(on_off, on_off, on_off):
with subtests.test(prefix=prefix, params=params, suffix=suffix):
result = do_magic(prefix=prefix, params=params, suffix=suffix)
assert ...
pytest.mark.parametrize
可能是更好的选择,尽管它的工作方式不同。