Skip to main content

Posts

Showing posts from November, 2018

Unit testing CLI scripts

I've been building tests for my scripts for some time now; however, I've avoiding testing the interaction with CLI scripts simply because I didn't know how to mock user input and test the script's output. This past week I decided overcome this hurdle and look further into mocking user input. I was surprised by how not difficult it actually was. Of course there is unittest.mock, but that didn't give me the control I wanted when running a script and testing it end to end. After a bit of digging I found that the key to solving this problem was overloads, specifically overloading input, getpass(if you prompt for it), and print. I found an article called Mocking input and output for Python testing on code-maven covering this. I then expanded on it to make it work for my application. I guess it's best to demonstrate and then go back and explain the code. So here's an app, and it's test.py: cli_app.py: from __future__ import print_function from getpass i...