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.
CodePudding user response:
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
toimport some_file
and add an assertionassertTrue(hasattr(some_file, 'foo'))
. This has the benefit that you are now explicitly testing that something calledfoo
exists insome_file
and not that you can importsome_file
.