I’m trying to perform a unit test on each function of a python file using unittest.
Assuming the file I want to test is called X.py and the file containing the testing code is Y.py.
In file X there are some imports, some def of functions, and some executable commands.
My goal is to test each function in X.py in isolation, meaning that I want to mock all interactions with the outside, including variables used and functions called. I do not want any code in X.py that are outside of the target function to be tested to be executed (because they require a certain production environment to work and may have unwanted side effects). However, I find it impossible to avoid actually executing those codes outside the target function when importing X.py. What can I do to fix it? Or is it impossible to test a function in X.py completely separately from other codes in it? Or do I have to mock the imported modules by modifying sys.modules? Thanks! 🙂
I wrote a python function to only copy the functions in X.py to another .py file temp_X.py. I thought that I can get around the problem by importing temp_X.py instead. However, it ended up creating more trouble because the temp_X.py doesn’t recognize some stuff that should’ve been imported (but was not copied to temp_X.py from X.py). I think this is probably not the professional way of unit testing?
Yichen Zhang is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.