I have a python module/script which does a few of these
- At various nested levels inside the script I take command line inputs, validate them, apply sensible defaults
- I also check if a few directories exist
The above are just two examples. I am trying to find out what is the best "strategy" to test this. What I have done is that I have constructed wrapper functions around raw_input
and os.path.exists
in my module and then in my test I override these two functions to take input from my array list or do some mocked behaviour. This approach has the following disadvantages
- Wrapper functions just exist for the sake of testing and this pollutes the code
- I have to remember to use the wrapper function in the code everytime and not just call
os.path.exists
orraw_input
Any brilliant suggestions?
Johnnysweb is spot on with what you need to do, but instead of rolling your own, you can import and use mock. Mock is specifically designed for unit testing, and makes it extremely simple to do what you're trying to do. It's built-in to Python 3.3.
For example, if want to run a unit test that replaces os.path.isfile and always returns True:
This can save you a LOT of boilerplate code, and it's quite readable.
If you need something a bit more complex, for example, replacing supbroccess.check_output, you can create a simple helper function:
The short answer is to monkey patch these system calls.
There are some good examples in the answer to How to display the redirected stdin in Python?
Here is a simple example for
raw_input()
using alambda
that throws away the prompt and returns what we want.System Under Test
Test case:
Solution1: I would do something like this beacuse it works:
It is not so nice.
Solution2: Restructuring your code was not an option as you said, right? It would make it worse to understand and unintuitive.