Search code examples
pythonunit-testingpython-importassert

Is there a pythonic unit testing way to assert that a function has been imported successfully?


Let's say we have the following simple file structure:

- some_file.py
- tests.py

The file some_file.py should contain the function foo, but how do I confirm that using the unittest framework?

I could see doing something like this within tests.py:

try:
   from some_file import foo
except ImportError as error:
   print('Error! Could not find foo.)

... but I am curious if there is a way to do this with assertions instead of a try-except block.

This question is pretty comprehensive about testing the imports on modules themselves, but I don't actually see anything about functions within the file, unless I'm overlooking something.


Solution

  • You can use several approaches:

    • Just import the function without try-except. If it doesn't raise an exception it counts as a passed test. However, if it does, it counts as an error and not as a failure.
    • Change the import from from some_file import foo to import some_file and add an assertion assertTrue(hasattr(some_file, 'foo')). This has the benefit that you are now explicitly testing that something called foo exists in some_file and not that you can import some_file.