fetch_test.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #!/usr/bin/env vpython3
  2. # coding=utf-8
  3. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  4. # Use of this source code is governed by a BSD-style license that can be
  5. # found in the LICENSE file.
  6. """Unit tests for fetch.py."""
  7. import contextlib
  8. import logging
  9. import argparse
  10. import os
  11. import subprocess
  12. import sys
  13. import tempfile
  14. import unittest
  15. from io import StringIO
  16. from unittest import mock
  17. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  18. import fetch
  19. class SystemExitMock(Exception):
  20. pass
  21. class TestUtilityFunctions(unittest.TestCase):
  22. """This test case is against utility functions"""
  23. def _usage_static_message(self, stdout):
  24. valid_fetch_config_text = 'Valid fetch configs:'
  25. self.assertIn(valid_fetch_config_text, stdout)
  26. # split[0] contains static text, whereas split[1] contains list of
  27. # configs
  28. split = stdout.split(valid_fetch_config_text)
  29. self.assertEqual(2, len(split))
  30. # verify a few fetch_configs
  31. self.assertIn('foo', split[1])
  32. self.assertNotIn('bar', split[1])
  33. def test_handle_args_valid_usage(self):
  34. response = fetch.handle_args(['filename', 'foo'])
  35. self.assertEqual(
  36. argparse.Namespace(dry_run=False,
  37. nohooks=False,
  38. nohistory=False,
  39. force=False,
  40. config='foo',
  41. protocol_override=None,
  42. props=[]), response)
  43. response = fetch.handle_args([
  44. 'filename', '-n', '--dry-run', '--nohooks', '--no-history',
  45. '--force', '--protocol-override', 'sso', 'foo', '--some-param=1',
  46. '--bar=2'
  47. ])
  48. self.assertEqual(
  49. argparse.Namespace(dry_run=True,
  50. nohooks=True,
  51. nohistory=True,
  52. force=True,
  53. config='foo',
  54. protocol_override='sso',
  55. props=['--some-param=1', '--bar=2']), response)
  56. response = fetch.handle_args([
  57. 'filename', '-n', '--dry-run', '--no-hooks', '--nohistory',
  58. '--force', '-p', 'sso', 'foo', '--some-param=1', '--bar=2'
  59. ])
  60. self.assertEqual(
  61. argparse.Namespace(dry_run=True,
  62. nohooks=True,
  63. nohistory=True,
  64. force=True,
  65. config='foo',
  66. protocol_override='sso',
  67. props=['--some-param=1', '--bar=2']), response)
  68. @mock.patch('os.path.exists', return_value=False)
  69. @mock.patch('sys.stdout', StringIO())
  70. @mock.patch('sys.exit', side_effect=SystemExitMock)
  71. def test_run_config_fetch_not_found(self, exit_mock, exists):
  72. with self.assertRaises(SystemExitMock):
  73. fetch.run_config_fetch('foo', [])
  74. exit_mock.assert_called_with(1)
  75. exists.assert_called_once()
  76. self.assertEqual(1, len(exists.call_args[0]))
  77. self.assertTrue(exists.call_args[0][0].endswith('foo.py'))
  78. stdout = sys.stdout.getvalue()
  79. self.assertEqual('Could not find a config for foo\n', stdout)
  80. def test_run_config_fetch_integration(self):
  81. config = fetch.run_config_fetch('depot_tools', [])
  82. url = 'https://chromium.googlesource.com/chromium/tools/depot_tools.git'
  83. spec = {
  84. 'type': 'gclient_git',
  85. 'gclient_git_spec': {
  86. 'solutions': [{
  87. 'url': url,
  88. 'managed': False,
  89. 'name': 'depot_tools',
  90. 'deps_file': 'DEPS',
  91. }],
  92. }
  93. }
  94. self.assertEqual((spec, 'depot_tools'), config)
  95. def test_checkout_factory(self):
  96. with self.assertRaises(KeyError):
  97. fetch.CheckoutFactory('invalid', {}, {}, "root")
  98. gclient = fetch.CheckoutFactory('gclient', {}, {}, "root")
  99. self.assertTrue(isinstance(gclient, fetch.GclientCheckout))
  100. class TestCheckout(unittest.TestCase):
  101. def setUp(self):
  102. mock.patch('sys.stdout', StringIO()).start()
  103. self.addCleanup(mock.patch.stopall)
  104. self.opts = argparse.Namespace(dry_run=False)
  105. self.checkout = fetch.Checkout(self.opts, {}, '')
  106. @contextlib.contextmanager
  107. def _temporary_file(self):
  108. """Creates a temporary file and removes it once it's out of scope"""
  109. name = tempfile.mktemp()
  110. try:
  111. with open(name, 'w+') as f:
  112. yield f
  113. finally:
  114. os.remove(name)
  115. def test_run_dry(self):
  116. self.opts.dry_run = True
  117. self.checkout.run(['foo-not-found'])
  118. self.assertEqual('Running: foo-not-found\n', sys.stdout.getvalue())
  119. def test_run_non_existing_command(self):
  120. with self.assertRaises(OSError):
  121. self.checkout.run(['foo-not-found'])
  122. self.assertEqual('Running: foo-not-found\n', sys.stdout.getvalue())
  123. def test_run_non_existing_command_return_stdout(self):
  124. with self.assertRaises(OSError):
  125. self.checkout.run(['foo-not-found'], return_stdout=True)
  126. self.assertEqual('Running: foo-not-found\n', sys.stdout.getvalue())
  127. @mock.patch('sys.stderr', StringIO())
  128. @mock.patch('sys.exit', side_effect=SystemExitMock)
  129. def test_run_wrong_param(self, exit_mock):
  130. # mocked version of sys.std* is not passed to subprocess, use temp files
  131. with self._temporary_file() as f:
  132. with self.assertRaises(subprocess.CalledProcessError):
  133. self.checkout.run([sys.executable, '-invalid-param'],
  134. return_stdout=True,
  135. stderr=f)
  136. f.seek(0)
  137. # Expect some message to stderr
  138. self.assertNotEqual('', f.read())
  139. self.assertEqual('', sys.stderr.getvalue())
  140. with self._temporary_file() as f:
  141. with self.assertRaises(SystemExitMock):
  142. self.checkout.run([sys.executable, '-invalid-param'], stderr=f)
  143. f.seek(0)
  144. # Expect some message to stderr
  145. self.assertNotEqual('', f.read())
  146. self.assertIn('Subprocess failed with return code',
  147. sys.stdout.getvalue())
  148. exit_mock.assert_called_once()
  149. def test_run_return_as_value(self):
  150. cmd = [sys.executable, '-c', 'print("foo")']
  151. response = self.checkout.run(cmd, return_stdout=True)
  152. # we expect no response other than information about command
  153. self.assertNotIn('foo', sys.stdout.getvalue().split('\n'))
  154. # this file should be included in response
  155. self.assertEqual('foo', response.strip())
  156. def test_run_print_to_stdout(self):
  157. cmd = [sys.executable, '-c', 'print("foo")']
  158. # mocked version of sys.std* is not passed to subprocess, use temp files
  159. with self._temporary_file() as stdout:
  160. with self._temporary_file() as stderr:
  161. response = self.checkout.run(cmd, stdout=stdout, stderr=stderr)
  162. stdout.seek(0)
  163. stderr.seek(0)
  164. self.assertEqual('foo\n', stdout.read())
  165. self.assertEqual('', stderr.read())
  166. stdout = sys.stdout.getvalue()
  167. self.assertEqual('', response)
  168. class TestGClientCheckout(unittest.TestCase):
  169. def setUp(self):
  170. self.run = mock.patch('fetch.Checkout.run').start()
  171. self.opts = argparse.Namespace(dry_run=False)
  172. self.checkout = fetch.GclientCheckout(self.opts, {}, '/root')
  173. self.addCleanup(mock.patch.stopall)
  174. @mock.patch('distutils.spawn.find_executable', return_value=True)
  175. def test_run_gclient_executable_found(self, find_executable):
  176. self.checkout.run_gclient('foo', 'bar', baz='qux')
  177. find_executable.assert_called_once_with('gclient')
  178. self.run.assert_called_once_with(('gclient', 'foo', 'bar'), baz='qux')
  179. @mock.patch('distutils.spawn.find_executable', return_value=False)
  180. def test_run_gclient_executable_not_found(self, find_executable):
  181. self.checkout.run_gclient('foo', 'bar', baz='qux')
  182. find_executable.assert_called_once_with('gclient')
  183. args = self.run.call_args[0][0]
  184. kargs = self.run.call_args[1]
  185. self.assertEqual(4, len(args))
  186. self.assertEqual(sys.executable, args[0])
  187. self.assertTrue(args[1].endswith('gclient.py'))
  188. self.assertEqual(('foo', 'bar'), args[2:])
  189. self.assertEqual({'baz': 'qux'}, kargs)
  190. class TestGclientGitCheckout(unittest.TestCase):
  191. def setUp(self):
  192. self.run_gclient = mock.patch(
  193. 'fetch.GclientCheckout.run_gclient').start()
  194. self.run_git = mock.patch('fetch.GitCheckout.run_git').start()
  195. self.opts = argparse.Namespace(dry_run=False,
  196. nohooks=True,
  197. nohistory=False)
  198. specs = {
  199. 'solutions': [{
  200. 'foo': 'bar',
  201. 'baz': 1
  202. }, {
  203. 'foo': False
  204. }],
  205. 'with_branch_heads': True,
  206. }
  207. self.checkout = fetch.GclientGitCheckout(self.opts, specs, '/root')
  208. self.addCleanup(mock.patch.stopall)
  209. def test_init(self):
  210. self.checkout.init()
  211. self.assertEqual(2, self.run_gclient.call_count)
  212. self.assertEqual(2, self.run_git.call_count)
  213. # Verify only expected commands and ignore arguments to avoid copying
  214. # commands from fetch.py
  215. self.assertEqual(['config', 'sync'],
  216. [a[0][0] for a in self.run_gclient.call_args_list])
  217. self.assertEqual(['config', 'config'],
  218. [a[0][0] for a in self.run_git.call_args_list])
  219. # First call to gclient, format spec is expected to be called so "foo"
  220. # is expected to be present
  221. args = self.run_gclient.call_args_list[0][0]
  222. self.assertEqual('config', args[0])
  223. self.assertIn('foo', args[2])
  224. if __name__ == '__main__':
  225. logging.basicConfig(
  226. level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
  227. unittest.main()