简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM