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?
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.