Skip to content Skip to sidebar Skip to footer

How To Properly Unit Test Filenotfounderror

With the unittest module, how can I test FileNotFoundError is raised when opening a file as follows: func(filename): try: file = open(filename) except FileNotFoundE

Solution 1:

You are swallowing the exception inside your exception handler, so there is no way your calling code (the unit test) can know that the error has been raised, all it sees is that your code has run, and exited.

Consider re-raising as in :

func(filename):
    try:
        file = open(filename)
    except FileNotFoundError:
        # Whatever else you want to do raise

Better still, your unit test shouldn't really be depending on that file not existing - unit tests should be self contained by definition. Consider mocking the open method so you have more control.

Solution 2:

Use context manager for Exception

Changed in version 2.7: Added the ability to use assertRaises() as a context manager.

If only the exception argument is given, returns a context manager so that the code under test can be written inline rather than as a function:

with self.assertRaises(SomeException):
    do_something()

Post a Comment for "How To Properly Unit Test Filenotfounderror"