10

I am writing a program which contains a lot of file operation. Some operations are done by calling subprocess.Popen, eg, split -l 50000 ${filename}, gzip -d -f ${filename} ${filename}..

Now I want to unit test the functionality of the program. But how could I unit test these functions?

Any suggestions?

juliomalegria
  • 24,229
  • 14
  • 73
  • 89
shihpeng
  • 5,283
  • 6
  • 37
  • 63
  • Use [`mock`](http://www.voidspace.org.uk/python/mock/) library, see [this example](http://stackoverflow.com/questions/19179795/how-to-mock-subprocess-call-in-a-unittest). – alecxe Jun 25 '14 at 02:57
  • @shihpeng Do you want to get rid of OS tool dependency (to run given test e.g. on Windows) or you want to find effective way how to wrap the call to something, what will use the command in OS, but allows you to evaluate, if all went well? – Jan Vlcinsky Jun 25 '14 at 05:46

1 Answers1

10

The canonical way is to mock out the call to Popen and replace the results with some test data. Have a look at the mock library documentation.1

You'd do something like this:

with mock.patch.object(subprocess, 'Popen') as mocked_popen:
    mocked_popen.return_value.communicate.return_value = some_fake_result
    function_which_uses_popen_communicate()

Now you can do some checking or whatever you want to test...

1Note that this was included in the standard library as unittest.mock in python3.3.

mgilson
  • 300,191
  • 65
  • 633
  • 696