Search code examples
pythonpython-unittest

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


In a python test case, I would like to assert the existence of a file or folder AND provide a useful error message in case the assertion fails. How could I do this?

The following of course works, but it does not yield the path/filename in the error message:

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

In a larger test it can be beneficial to see at a glance for which file the assertion failed. How to extend unittest.TestCase to print a better assertion message for such a test?

======================================================================
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"

Solution

  • Extending unittest.TestCase with an additional assertion worked best for me.

    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)
    

    This yields:

    ======================================================================
    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