How to unit test a function using Popen?

I am writing a program that contains many files. Some operations are performed by calling subprocess.Popen , for example, split -l 50000 ${filename} , gzip -d -f ${filename} ${filename}. .

Now I want unit test program functionality. But how could unit test perform these functions?

Any suggestions?

+8
python subprocess unit-testing
source share
1 answer

The canonical way is to chop the Popen call and replace the results with some test data. See the mock library documentation . one

You would 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 verification or whatever you want to verify ...

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

+8
source share

All Articles