在独立的pytest测试中使用unittest类断言(比如assertNotIn)的最佳实践?

2024-09-29 23:26:53 发布

您现在位置:Python中文网/ 问答频道 /正文

在独立的pytest测试用例中,我希望使用unittest.TestCase.assertNotIn(和^{}s other asserts)这样的断言,而不依赖于uniittest模块。使用python-assert这样的库是最佳实践吗?在


Tags: 模块pytest测试用例assert断言unittesttestcaseother
1条回答
网友
1楼 · 发布于 2024-09-29 23:26:53

最佳实践是使用语言assert语句,它产生不必要的unittest的{}方法。比较

self.assertNotIn(a, b, 'element a is not found in sequence b')

^{pr2}$

后者更像Python。它也是docspytest名称的关键特性之一:

Detailed info on failing assert statements (no need to remember self.assert* names)

如果您缺少任何unittest方法,pytest旨在为它们提供替换:

with self.assertRaises(Exception):
    spam()

变成

with pytest.raises(Exception):
    spam()

你说

self.assertAlmostEqual(a, b)

变成

assert a == pytest.approx(b)

等等

相关问题 更多 >

    热门问题