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

Best practice of using unittest kind asserts (like assertNotIn) in standalone pytest tests?

在独立的 pytest 测试用例中,我想使用像 unittest.TestCase.assertNotIn 这样的断言(和 unittests other asserts) without any dependency on the uniittest module. Is best practice to use libraries like python-assert?

最佳做法是使用语言 assert 语句,这会产生不必要的 unittestassert* 方法。比较

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

assert a not in b, 'element a is not found in sequence b'

后者更具 Python 风格。它也是 pytestdocs:

中命名的关键特征之一

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)

等等