Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading