shihpeng
shihpeng

Reputation: 5381

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?

Upvotes: 11

Views: 3596

Answers (1)

mgilson
mgilson

Reputation: 310147

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.

Upvotes: 10

Related Questions