簡體   English   中英

Python unittest:如何斷言文件或文件夾的存在並在失敗時打印路徑?

[英]Python unittest: How to assert the existence of a file or folder and print the path on failure?

在 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最適合我。

import unittest
import pathlib as pl

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

您可以編寫測試,以便斷言包含路徑名:

import unittest
import pathlib as pl

class TestCase(unittest.TestCase):
    def test(self):
        # ...
        path = pl.Path("a/b/c.txt")
        self.assertEquals((str(path), path.is_file()), (str(path), True))

if __name__ == "__main__":
    unittest.main(verbosity=2)

這會給你這樣的輸出:

======================================================================
FAIL: test_something (__main__.TextExample)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "testfoo.py", line 8, in test_something
    self.assertEqual((path, path.is_file()), (path, True))
AssertionError: Tuples differ: (PosixPath('path/to/file'), False) != (PosixPath('path/to/file'), True)

First differing element 1:
False
True

- (PosixPath('path/to/file'), False)
?                                     ^^^^

+ (PosixPath('path/to/file'), True)
?                                     ^^^

但您也可以決定改用pytest ,並像這樣編寫測試:

from pathlib import Path


def test_something():
    path = Path('path/to/file')
    assert path.is_file()

使用pytest運行它會自動將路徑包含在你的失敗中:

============================= test session starts ==============================
platform linux -- Python 3.7.5, pytest-4.6.6, py-1.8.0, pluggy-0.13.0
rootdir: /home/lars/tmp
collected 1 item

testfoo.py F                                                             [100%]

=================================== FAILURES ===================================
________________________________ test_something ________________________________

    def test_something():
        path = Path('path/to/file')
>       assert path.is_file()
E       AssertionError: assert False
E        +  where False = <bound method Path.is_file of PosixPath('path/to/file')>()
E        +    where <bound method Path.is_file of PosixPath('path/to/file')> = PosixPath('path/to/file').is_file

testfoo.py:6: AssertionError
=========================== 1 failed in 0.01 seconds ===========================

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM