subprocess2_test.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. #!/usr/bin/env vpython3
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Unit tests for subprocess2.py."""
  6. import os
  7. import sys
  8. import unittest
  9. from unittest import mock
  10. DEPOT_TOOLS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  11. sys.path.insert(0, DEPOT_TOOLS)
  12. import subprocess
  13. import subprocess2
  14. TEST_FILENAME = 'subprocess2_test_script.py'
  15. TEST_COMMAND = [
  16. sys.executable,
  17. os.path.join(DEPOT_TOOLS, 'testing_support', TEST_FILENAME),
  18. ]
  19. class DefaultsTest(unittest.TestCase):
  20. @mock.patch('subprocess2.communicate')
  21. def test_check_call_defaults(self, mockCommunicate):
  22. mockCommunicate.return_value = (('stdout', 'stderr'), 0)
  23. self.assertEqual(('stdout', 'stderr'),
  24. subprocess2.check_call_out(['foo'], a=True))
  25. mockCommunicate.assert_called_with(['foo'], a=True)
  26. @mock.patch('subprocess2.communicate')
  27. def test_capture_defaults(self, mockCommunicate):
  28. mockCommunicate.return_value = (('stdout', 'stderr'), 0)
  29. self.assertEqual('stdout', subprocess2.capture(['foo'], a=True))
  30. mockCommunicate.assert_called_with(['foo'],
  31. a=True,
  32. stdin=subprocess2.DEVNULL,
  33. stdout=subprocess2.PIPE)
  34. @mock.patch('subprocess2.Popen')
  35. def test_communicate_defaults(self, mockPopen):
  36. mockPopen().communicate.return_value = ('bar', 'baz')
  37. mockPopen().returncode = -8
  38. self.assertEqual((('bar', 'baz'), -8),
  39. subprocess2.communicate(['foo'], a=True))
  40. mockPopen.assert_called_with(['foo'], a=True)
  41. @mock.patch('os.environ', {})
  42. @mock.patch('subprocess.Popen.__init__')
  43. def test_Popen_defaults(self, mockPopen):
  44. with mock.patch('sys.platform', 'win32'):
  45. subprocess2.Popen(['foo'], a=True)
  46. mockPopen.assert_called_with(['foo'], a=True, shell=True)
  47. with mock.patch('sys.platform', 'non-win32'):
  48. subprocess2.Popen(['foo'], a=True)
  49. mockPopen.assert_called_with(['foo'], a=True, shell=False)
  50. def test_get_english_env(self):
  51. with mock.patch('sys.platform', 'win32'):
  52. self.assertIsNone(subprocess2.get_english_env({}))
  53. with mock.patch('sys.platform', 'non-win32'):
  54. self.assertIsNone(subprocess2.get_english_env({}))
  55. self.assertIsNone(
  56. subprocess2.get_english_env({
  57. 'LANG': 'en_XX',
  58. 'LANGUAGE': 'en_YY'
  59. }))
  60. self.assertEqual({
  61. 'LANG': 'en_US.UTF-8',
  62. 'LANGUAGE': 'en_US.UTF-8'
  63. }, subprocess2.get_english_env({
  64. 'LANG': 'bar',
  65. 'LANGUAGE': 'baz'
  66. }))
  67. @mock.patch('subprocess2.communicate')
  68. def test_check_output_defaults(self, mockCommunicate):
  69. mockCommunicate.return_value = (('stdout', 'stderr'), 0)
  70. self.assertEqual('stdout', subprocess2.check_output(['foo'], a=True))
  71. mockCommunicate.assert_called_with(['foo'],
  72. a=True,
  73. stdin=subprocess2.DEVNULL,
  74. stdout=subprocess2.PIPE)
  75. @mock.patch('subprocess.Popen.__init__')
  76. def test_env_type(self, mockPopen):
  77. subprocess2.Popen(['foo'], env={b'key': b'value'})
  78. mockPopen.assert_called_with(['foo'],
  79. env={'key': 'value'},
  80. shell=mock.ANY)
  81. def _run_test(with_subprocess=True):
  82. """Runs a tests in 12 combinations:
  83. - With universal_newlines=True and False.
  84. - With LF, CR, and CRLF output.
  85. - With subprocess and subprocess2.
  86. """
  87. subps = (subprocess2, subprocess) if with_subprocess else (subprocess2, )
  88. no_op = lambda s: s
  89. to_bytes = lambda s: s.encode()
  90. to_cr_bytes = lambda s: s.replace('\n', '\r').encode()
  91. to_crlf_bytes = lambda s: s.replace('\n', '\r\n').encode()
  92. def wrapper(test):
  93. def inner(self):
  94. for subp in subps:
  95. # universal_newlines = False
  96. test(self, to_bytes, TEST_COMMAND, False, subp)
  97. test(self, to_cr_bytes, TEST_COMMAND + ['--cr'], False, subp)
  98. test(self, to_crlf_bytes, TEST_COMMAND + ['--crlf'], False,
  99. subp)
  100. # universal_newlines = True
  101. test(self, no_op, TEST_COMMAND, True, subp)
  102. test(self, no_op, TEST_COMMAND + ['--cr'], True, subp)
  103. test(self, no_op, TEST_COMMAND + ['--crlf'], True, subp)
  104. return inner
  105. return wrapper
  106. class SmokeTests(unittest.TestCase):
  107. # Regression tests to ensure that subprocess and subprocess2 have the same
  108. # behavior.
  109. def _check_res(self, res, stdout, stderr, returncode):
  110. (out, err), code = res
  111. self.assertEqual(stdout, out)
  112. self.assertEqual(stderr, err)
  113. self.assertEqual(returncode, code)
  114. def _check_exception(self, subp, e, stdout, stderr, returncode):
  115. """On exception, look if the exception members are set correctly."""
  116. self.assertEqual(returncode, e.returncode)
  117. self.assertEqual(stdout, e.stdout)
  118. self.assertEqual(stderr, e.stderr)
  119. def test_check_output_no_stdout(self):
  120. for subp in (subprocess, subprocess2):
  121. with self.assertRaises(ValueError):
  122. # pylint: disable=unexpected-keyword-arg
  123. subp.check_output(TEST_COMMAND, stdout=subp.PIPE)
  124. def test_print_exception(self):
  125. with self.assertRaises(subprocess2.CalledProcessError) as e:
  126. subprocess2.check_output(TEST_COMMAND + ['--fail', '--stdout'])
  127. exception_str = str(e.exception)
  128. # Windows escapes backslashes so check only filename
  129. self.assertIn(TEST_FILENAME + ' --fail --stdout', exception_str)
  130. self.assertIn(str(e.exception.returncode), exception_str)
  131. self.assertIn(e.exception.stdout.decode('utf-8', 'ignore'),
  132. exception_str)
  133. @_run_test()
  134. def test_check_output_throw_stdout(self, c, cmd, un, subp):
  135. with self.assertRaises(subp.CalledProcessError) as e:
  136. subp.check_output(cmd + ['--fail', '--stdout'],
  137. universal_newlines=un)
  138. self._check_exception(subp, e.exception, c('A\nBB\nCCC\n'), None, 64)
  139. @_run_test()
  140. def test_check_output_throw_no_stderr(self, c, cmd, un, subp):
  141. with self.assertRaises(subp.CalledProcessError) as e:
  142. subp.check_output(cmd + ['--fail', '--stderr'],
  143. universal_newlines=un)
  144. self._check_exception(subp, e.exception, c(''), None, 64)
  145. @_run_test()
  146. def test_check_output_throw_stderr(self, c, cmd, un, subp):
  147. with self.assertRaises(subp.CalledProcessError) as e:
  148. subp.check_output(cmd + ['--fail', '--stderr'],
  149. stderr=subp.PIPE,
  150. universal_newlines=un)
  151. self._check_exception(subp, e.exception, c(''), c('a\nbb\nccc\n'), 64)
  152. @_run_test()
  153. def test_check_output_throw_stderr_stdout(self, c, cmd, un, subp):
  154. with self.assertRaises(subp.CalledProcessError) as e:
  155. subp.check_output(cmd + ['--fail', '--stderr'],
  156. stderr=subp.STDOUT,
  157. universal_newlines=un)
  158. self._check_exception(subp, e.exception, c('a\nbb\nccc\n'), None, 64)
  159. def test_check_call_throw(self):
  160. for subp in (subprocess, subprocess2):
  161. with self.assertRaises(subp.CalledProcessError) as e:
  162. subp.check_call(TEST_COMMAND + ['--fail', '--stderr'])
  163. self._check_exception(subp, e.exception, None, None, 64)
  164. @_run_test()
  165. def test_redirect_stderr_to_stdout_pipe(self, c, cmd, un, subp):
  166. # stderr output into stdout.
  167. proc = subp.Popen(cmd + ['--stderr'],
  168. stdout=subp.PIPE,
  169. stderr=subp.STDOUT,
  170. universal_newlines=un)
  171. res = proc.communicate(), proc.returncode
  172. self._check_res(res, c('a\nbb\nccc\n'), None, 0)
  173. @_run_test()
  174. def test_redirect_stderr_to_stdout(self, c, cmd, un, subp):
  175. # stderr output into stdout but stdout is not piped.
  176. proc = subp.Popen(cmd + ['--stderr'],
  177. stderr=subprocess2.STDOUT,
  178. universal_newlines=un)
  179. res = proc.communicate(), proc.returncode
  180. self._check_res(res, None, None, 0)
  181. @_run_test()
  182. def test_stderr(self, c, cmd, un, subp):
  183. cmd = ['expr', '1', '/', '0']
  184. if sys.platform == 'win32':
  185. cmd = ['cmd.exe', '/c', 'exit', '1']
  186. p1 = subprocess.Popen(cmd, stderr=subprocess.PIPE, shell=False)
  187. p2 = subprocess2.Popen(cmd, stderr=subprocess.PIPE, shell=False)
  188. r1 = p1.communicate()
  189. r2 = p2.communicate()
  190. self.assertEqual(r1, r2)
  191. @_run_test(with_subprocess=False)
  192. def test_stdin(self, c, cmd, un, subp):
  193. stdin = c('0123456789')
  194. res = subprocess2.communicate(cmd + ['--read'],
  195. stdin=stdin,
  196. universal_newlines=un)
  197. self._check_res(res, None, None, 10)
  198. @_run_test(with_subprocess=False)
  199. def test_stdin_empty(self, c, cmd, un, subp):
  200. stdin = c('')
  201. res = subprocess2.communicate(cmd + ['--read'],
  202. stdin=stdin,
  203. universal_newlines=un)
  204. self._check_res(res, None, None, 0)
  205. def test_stdin_void(self):
  206. res = subprocess2.communicate(TEST_COMMAND + ['--read'],
  207. stdin=subprocess2.DEVNULL)
  208. self._check_res(res, None, None, 0)
  209. @_run_test(with_subprocess=False)
  210. def test_stdin_void_stdout(self, c, cmd, un, subp):
  211. # Make sure a mix ofsubprocess2.DEVNULL andsubprocess2.PIPE works.
  212. res = subprocess2.communicate(cmd + ['--stdout', '--read'],
  213. stdin=subprocess2.DEVNULL,
  214. stdout=subprocess2.PIPE,
  215. universal_newlines=un,
  216. shell=False)
  217. self._check_res(res, c('A\nBB\nCCC\n'), None, 0)
  218. @_run_test(with_subprocess=False)
  219. def test_stdout_void(self, c, cmd, un, subp):
  220. res = subprocess2.communicate(cmd + ['--stdout', '--stderr'],
  221. stdout=subprocess2.DEVNULL,
  222. stderr=subprocess2.PIPE,
  223. universal_newlines=un)
  224. self._check_res(res, None, c('a\nbb\nccc\n'), 0)
  225. @_run_test(with_subprocess=False)
  226. def test_stderr_void(self, c, cmd, un, subp):
  227. res = subprocess2.communicate(cmd + ['--stdout', '--stderr'],
  228. stdout=subprocess2.PIPE,
  229. stderr=subprocess2.DEVNULL,
  230. universal_newlines=un)
  231. self._check_res(res, c('A\nBB\nCCC\n'), None, 0)
  232. @_run_test(with_subprocess=False)
  233. def test_stdout_void_stderr_redirect(self, c, cmd, un, subp):
  234. res = subprocess2.communicate(cmd + ['--stdout', '--stderr'],
  235. stdout=subprocess2.DEVNULL,
  236. stderr=subprocess2.STDOUT,
  237. universal_newlines=un)
  238. self._check_res(res, None, None, 0)
  239. if __name__ == '__main__':
  240. unittest.main()