-
Notifications
You must be signed in to change notification settings - Fork 0
/
subfun.py
executable file
·64 lines (50 loc) · 2.03 KB
/
subfun.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
import mock
import re
import subprocess
import unittest
def do_proc():
"""execute some external commands."""
call = subprocess.Popen(['ls'], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
out, err = call.communicate()
matched = re.search(r'foobar.txt', out, flags=re.MULTILINE)
if matched is not None:
try:
call = subprocess.Popen(['cat', 'foobar.txt'], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
out, err = call.communicate()
except OSError as err:
return False
return True
class TestDoProc(unittest.TestCase):
@mock.patch('subprocess.Popen')
def test_one(self, popen_mock):
pmock = mock.Mock()
pmock.communicate.return_value = ("foobar.txt", "")
popen_mock.return_value = pmock
calls = [
mock.call(['ls'], stderr=subprocess.STDOUT, stdout=subprocess.PIPE),
mock.call(['cat', 'foobar.txt'], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
]
do_proc()
popen_mock.assert_has_calls(calls)
@mock.patch('subprocess.Popen')
def test_two(self, popen_mock):
def proc_side_effect(*args, **kargs):
proc_cmd = args[0]
pmock = mock.Mock()
if proc_cmd[0] == 'ls':
pmock.communicate.return_value = ("foobar.txt", "")
elif proc_cmd[0] == 'cat':
pmock.communicate.return_value = ("go away", "")
else:
raise OSError
return pmock
popen_mock.configure_mock(side_effect=proc_side_effect)
calls = [
mock.call(['ls'], stderr=subprocess.STDOUT, stdout=subprocess.PIPE),
mock.call(['cat', 'foobar.txt'], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
]
do_proc()
popen_mock.assert_has_calls(calls)
if __name__ == "__main__":
unittest.main()