Created
October 2, 2015 14:01
-
-
Save manuelzs/720d3a5cf4bf9e09c7e7 to your computer and use it in GitHub Desktop.
Mock subprocess.Popen with context manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import subprocess | |
| from contextlib import contextmanager | |
| from mock import Mock, MagicMock | |
| @contextmanager | |
| def popen_mock(): | |
| """ | |
| Context manager to mock subprocess calls. | |
| Example: | |
| ``` | |
| with popen_mock() as process_mock: | |
| call_some_fn_that_uses_popen() | |
| assert process_mock.communicate.called | |
| ``` | |
| """ | |
| orig_popen = subprocess.Popen | |
| subprocess.Popen = MagicMock() | |
| process_mock = Mock() | |
| process_mock.configure_mock(**{ | |
| 'communicate.return_value': ('ouput', 0), | |
| 'wait.return_value': 0, | |
| 'returncode': 0, | |
| }) | |
| subprocess.Popen.return_value = process_mock | |
| yield process_mock | |
| subprocess.Popen = orig_popen | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment