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?
Popen do we need to close the connection or subprocess automatically closes the connection? Usually, the examples in the official documentation are complete. There the connection is not closed. So you do not need to close most probably.
The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.
Popen is more general than subprocess. call . Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.
The popen() function executes the command specified by the string command. It creates a pipe between the calling program and the executed command, and returns a pointer to a stream that can be used to either read from or write to the pipe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With