在python中test case
,我想断言文件或文件夹的存在,并在断言失败的情况下提供有用的错误消息。我该怎么办?
当然可以执行以下操作,但不会在错误消息中产生路径/文件名:
import unittest
import pathlib as pl
class TestCase(unittest.TestCase):
def test(self):
# ...
path = pl.Path("a/b/c.txt")
self.assertTrue(path.is_file())
self.assertTrue(path.parent.is_dir())
if __name__ == "__main__":
unittest.main(verbosity=2)
======================================================================
FAIL: test (__main__.TestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "my_test.py", line 194, in test
self.assertTrue(path.is_file())
AssertionError: False is not true
在更大的测试中,乍一看断言对于哪个文件可能是有益的。如何扩展unittest.TestCase
以为此类测试打印更好的断言消息?
======================================================================
FAIL: test (__main__.TestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "my_test.py", line 194, in test
self.assertFileExists(path)
AssertionError: File does not exist: "a/b/c.txt"
扩展unittest.TestCase
附加断言对我来说是最好的。
class TestCaseBase(unittest.TestCase):
def assertIsFile(self, path):
if not pl.Path(path).resolve().is_file():
raise AssertionError("File does not exist: %s" % str(path))
class ActualTest(TestCaseBase):
def test(self):
path = pl.Path("a/b/c.txt")
self.assertIsFile(path)
这样产生:
======================================================================
FAIL: test (__main__.TestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "my_test.py", line 194, in test
raise AssertionError("File does not exist: %s" % str(path))
AssertionError: File does not exist: a/b/c.txt
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句