Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a function that uses Popen?

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?

like image 464
shihpeng Avatar asked Jun 25 '14 02:06

shihpeng


People also ask

Do you need to close Popen?

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.

What is subprocess popen ()?

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.

What is the difference between subprocess call and Popen?

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.

What does Popen return Python?

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.


1 Answers

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.

like image 82
mgilson Avatar answered Oct 05 '22 05:10

mgilson