bot_update_coverage_test.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. #!/usr/bin/env vpython3
  2. # Copyright (c) 2015 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. import codecs
  6. import copy
  7. import os
  8. import sys
  9. import unittest
  10. #import test_env # pylint: disable=relative-import,unused-import
  11. sys.path.insert(0, os.path.join(
  12. os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
  13. 'recipes', 'recipe_modules', 'bot_update', 'resources'))
  14. import bot_update
  15. class MockedPopen(object):
  16. """A fake instance of a called subprocess.
  17. This is meant to be used in conjunction with MockedCall.
  18. """
  19. def __init__(self, args=None, kwargs=None):
  20. self.args = args or []
  21. self.kwargs = kwargs or {}
  22. self.return_value = None
  23. self.fails = False
  24. def returns(self, rv):
  25. """Set the return value when this popen is called.
  26. rv can be a string, or a callable (eg function).
  27. """
  28. self.return_value = rv
  29. return self
  30. def check(self, args, kwargs):
  31. """Check to see if the given args/kwargs call match this instance.
  32. This does a partial match, so that a call to "git clone foo" will match
  33. this instance if this instance was recorded as "git clone"
  34. """
  35. if any(input_arg != expected_arg
  36. for (input_arg, expected_arg) in zip(args, self.args)):
  37. return False
  38. return self.return_value
  39. def __call__(self, args, kwargs):
  40. """Actually call this popen instance."""
  41. if hasattr(self.return_value, '__call__'):
  42. return self.return_value(*args, **kwargs)
  43. return self.return_value
  44. class MockedCall(object):
  45. """A fake instance of bot_update.call().
  46. This object is pre-seeded with "answers" in self.expectations. The type
  47. is a MockedPopen object, or any object with a __call__() and check() method.
  48. The check() method is used to check to see if the correct popen object is
  49. chosen (can be a partial match, eg a "git clone" popen module would match
  50. a "git clone foo" call).
  51. By default, if no answers have been pre-seeded, the call() returns successful
  52. with an empty string.
  53. """
  54. def __init__(self, fake_filesystem):
  55. self.expectations = []
  56. self.records = []
  57. def expect(self, args=None, kwargs=None):
  58. args = args or []
  59. kwargs = kwargs or {}
  60. popen = MockedPopen(args, kwargs)
  61. self.expectations.append(popen)
  62. return popen
  63. def __call__(self, *args, **kwargs):
  64. self.records.append((args, kwargs))
  65. for popen in self.expectations:
  66. if popen.check(args, kwargs):
  67. self.expectations.remove(popen)
  68. return popen(args, kwargs)
  69. return ''
  70. class MockedGclientSync():
  71. """A class producing a callable instance of gclient sync."""
  72. def __init__(self, fake_filesystem):
  73. self.records = []
  74. def __call__(self, *args, **_):
  75. self.records.append(args)
  76. class FakeFile():
  77. def __init__(self):
  78. self.contents = ''
  79. def write(self, buf):
  80. self.contents += buf
  81. def read(self):
  82. return self.contents
  83. def __enter__(self):
  84. return self
  85. def __exit__(self, _, __, ___):
  86. pass
  87. class FakeFilesystem():
  88. def __init__(self):
  89. self.files = {}
  90. def open(self, target, mode='r', encoding=None):
  91. if 'w' in mode:
  92. self.files[target] = FakeFile()
  93. return self.files[target]
  94. return self.files[target]
  95. def fake_git(*args, **kwargs):
  96. return bot_update.call('git', *args, **kwargs)
  97. class BotUpdateUnittests(unittest.TestCase):
  98. DEFAULT_PARAMS = {
  99. 'solutions': [{
  100. 'name': 'somename',
  101. 'url': 'https://fake.com'
  102. }],
  103. 'revisions': {},
  104. 'first_sln': 'somename',
  105. 'target_os': None,
  106. 'target_os_only': None,
  107. 'target_cpu': None,
  108. 'patch_root': None,
  109. 'patch_refs': [],
  110. 'gerrit_rebase_patch_ref': None,
  111. 'no_fetch_tags': False,
  112. 'refs': [],
  113. 'git_cache_dir': '',
  114. 'cleanup_dir': None,
  115. 'gerrit_reset': None,
  116. 'enforce_fetch': False,
  117. 'experiments': [],
  118. }
  119. def setUp(self):
  120. sys.platform = 'linux2' # For consistency, ya know?
  121. self.filesystem = FakeFilesystem()
  122. self.call = MockedCall(self.filesystem)
  123. self.gclient = MockedGclientSync(self.filesystem)
  124. self.call.expect(
  125. (sys.executable, '-u', bot_update.GCLIENT_PATH, 'sync')
  126. ).returns(self.gclient)
  127. self.old_call = getattr(bot_update, 'call')
  128. self.params = copy.deepcopy(self.DEFAULT_PARAMS)
  129. setattr(bot_update, 'call', self.call)
  130. setattr(bot_update, 'git', fake_git)
  131. self.old_os_cwd = os.getcwd
  132. setattr(os, 'getcwd', lambda: '/b/build/foo/build')
  133. setattr(bot_update, 'open', self.filesystem.open)
  134. self.old_codecs_open = codecs.open
  135. setattr(codecs, 'open', self.filesystem.open)
  136. def tearDown(self):
  137. setattr(bot_update, 'call', self.old_call)
  138. setattr(os, 'getcwd', self.old_os_cwd)
  139. delattr(bot_update, 'open')
  140. setattr(codecs, 'open', self.old_codecs_open)
  141. def overrideSetupForWindows(self):
  142. sys.platform = 'win'
  143. self.call.expect(
  144. (sys.executable, '-u', bot_update.GCLIENT_PATH, 'sync')
  145. ).returns(self.gclient)
  146. def testBasic(self):
  147. bot_update.ensure_checkout(**self.params)
  148. return self.call.records
  149. def testBasicCachepackOffloading(self):
  150. os.environ['PACKFILE_OFFLOADING'] = '1'
  151. bot_update.ensure_checkout(**self.params)
  152. os.environ.pop('PACKFILE_OFFLOADING')
  153. return self.call.records
  154. def testBasicRevision(self):
  155. self.params['revisions'] = {
  156. 'src': 'HEAD', 'src/v8': 'deadbeef', 'somename': 'DNE'}
  157. bot_update.ensure_checkout(**self.params)
  158. args = self.gclient.records[0]
  159. idx_first_revision = args.index('--revision')
  160. idx_second_revision = args.index(
  161. '--revision', idx_first_revision+1)
  162. idx_third_revision = args.index('--revision', idx_second_revision+1)
  163. self.assertEqual(args[idx_first_revision+1], 'somename@unmanaged')
  164. self.assertEqual(
  165. args[idx_second_revision+1], 'src@refs/remotes/origin/main')
  166. self.assertEqual(args[idx_third_revision+1], 'src/v8@deadbeef')
  167. return self.call.records
  168. def testTagsByDefault(self):
  169. bot_update.ensure_checkout(**self.params)
  170. found = False
  171. for record in self.call.records:
  172. args = record[0]
  173. if args[:3] == ('git', 'cache', 'populate'):
  174. self.assertFalse('--no-fetch-tags' in args)
  175. found = True
  176. self.assertTrue(found)
  177. return self.call.records
  178. def testNoTags(self):
  179. params = self.params
  180. params['no_fetch_tags'] = True
  181. bot_update.ensure_checkout(**params)
  182. found = False
  183. for record in self.call.records:
  184. args = record[0]
  185. if args[:3] == ('git', 'cache', 'populate'):
  186. self.assertTrue('--no-fetch-tags' in args)
  187. found = True
  188. self.assertTrue(found)
  189. return self.call.records
  190. def testApplyPatchOnGclient(self):
  191. ref = 'refs/changes/12/345/6'
  192. repo = 'https://chromium.googlesource.com/v8/v8'
  193. self.params['patch_refs'] = ['%s@%s' % (repo, ref)]
  194. bot_update.ensure_checkout(**self.params)
  195. args = self.gclient.records[0]
  196. idx = args.index('--patch-ref')
  197. self.assertEqual(args[idx+1], self.params['patch_refs'][0])
  198. self.assertNotIn('--patch-ref', args[idx+1:])
  199. # Assert we're not patching in bot_update.py
  200. for record in self.call.records:
  201. self.assertNotIn('git fetch ' + repo,
  202. ' '.join(record[0]))
  203. def testPatchRefs(self):
  204. self.params['patch_refs'] = [
  205. 'https://chromium.googlesource.com/chromium/src@refs/changes/12/345/6',
  206. 'https://chromium.googlesource.com/v8/v8@refs/changes/1/234/56']
  207. bot_update.ensure_checkout(**self.params)
  208. args = self.gclient.records[0]
  209. patch_refs = set(
  210. args[i+1] for i in range(len(args))
  211. if args[i] == '--patch-ref' and i+1 < len(args))
  212. self.assertIn(self.params['patch_refs'][0], patch_refs)
  213. self.assertIn(self.params['patch_refs'][1], patch_refs)
  214. def testGitCheckoutBreaksLocks(self):
  215. self.overrideSetupForWindows()
  216. path = '/b/build/foo/build/.git'
  217. lockfile = 'index.lock'
  218. removed = []
  219. old_os_walk = os.walk
  220. old_os_remove = os.remove
  221. setattr(os, 'walk', lambda _: [(path, None, [lockfile])])
  222. setattr(os, 'remove', removed.append)
  223. bot_update.ensure_checkout(**self.params)
  224. setattr(os, 'walk', old_os_walk)
  225. setattr(os, 'remove', old_os_remove)
  226. self.assertTrue(os.path.join(path, lockfile) in removed)
  227. def testParsesRevisions(self):
  228. revisions = [
  229. 'f671d3baeb64d9dba628ad582e867cf1aebc0207',
  230. 'src@deadbeef',
  231. 'https://foo.googlesource.com/bar@12345',
  232. 'bar@refs/experimental/test@example.com/test',
  233. ]
  234. expected_results = {
  235. 'root': 'f671d3baeb64d9dba628ad582e867cf1aebc0207',
  236. 'src': 'deadbeef',
  237. 'https://foo.googlesource.com/bar.git': '12345',
  238. 'bar': 'refs/experimental/test@example.com/test',
  239. }
  240. actual_results = bot_update.parse_revisions(revisions, 'root')
  241. self.assertEqual(expected_results, actual_results)
  242. class CallUnitTest(unittest.TestCase):
  243. def testCall(self):
  244. ret = bot_update.call(sys.executable, '-c', 'print(1)')
  245. self.assertEqual(u'1\n', ret)
  246. if __name__ == '__main__':
  247. unittest.main()