git_cache_test.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. #!/usr/bin/env vpython3
  2. # Copyright 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. """Unit tests for git_cache.py"""
  6. import logging
  7. import os
  8. import shutil
  9. import subprocess
  10. import sys
  11. import tempfile
  12. import unittest
  13. if sys.version_info.major == 2:
  14. from StringIO import StringIO
  15. import mock
  16. else:
  17. from io import StringIO
  18. from unittest import mock
  19. DEPOT_TOOLS_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  20. sys.path.insert(0, DEPOT_TOOLS_ROOT)
  21. from testing_support import coverage_utils
  22. import git_cache
  23. class GitCacheTest(unittest.TestCase):
  24. def setUp(self):
  25. self.cache_dir = tempfile.mkdtemp(prefix='git_cache_test_')
  26. self.addCleanup(shutil.rmtree, self.cache_dir, ignore_errors=True)
  27. self.origin_dir = tempfile.mkdtemp(suffix='origin.git')
  28. self.addCleanup(shutil.rmtree, self.origin_dir, ignore_errors=True)
  29. git_cache.Mirror.SetCachePath(self.cache_dir)
  30. def git(self, cmd, cwd=None):
  31. cwd = cwd or self.origin_dir
  32. git = 'git.bat' if sys.platform == 'win32' else 'git'
  33. subprocess.check_call([git] + cmd, cwd=cwd)
  34. def testParseFetchSpec(self):
  35. testData = [
  36. ([], []),
  37. (['main'], [('+refs/heads/main:refs/heads/main',
  38. r'\+refs/heads/main:.*')]),
  39. (['main/'], [('+refs/heads/main:refs/heads/main',
  40. r'\+refs/heads/main:.*')]),
  41. (['+main'], [('+refs/heads/main:refs/heads/main',
  42. r'\+refs/heads/main:.*')]),
  43. (['master'], [('+refs/heads/master:refs/heads/master',
  44. r'\+refs/heads/master:.*')]),
  45. (['master/'], [('+refs/heads/master:refs/heads/master',
  46. r'\+refs/heads/master:.*')]),
  47. (['+master'], [('+refs/heads/master:refs/heads/master',
  48. r'\+refs/heads/master:.*')]),
  49. (['refs/heads/*'], [('+refs/heads/*:refs/heads/*',
  50. r'\+refs/heads/\*:.*')]),
  51. (['foo/bar/*', 'baz'], [('+refs/heads/foo/bar/*:refs/heads/foo/bar/*',
  52. r'\+refs/heads/foo/bar/\*:.*'),
  53. ('+refs/heads/baz:refs/heads/baz',
  54. r'\+refs/heads/baz:.*')]),
  55. (['refs/foo/*:refs/bar/*'], [('+refs/foo/*:refs/bar/*',
  56. r'\+refs/foo/\*:.*')])
  57. ]
  58. mirror = git_cache.Mirror('test://phony.example.biz')
  59. for fetch_specs, expected in testData:
  60. mirror = git_cache.Mirror('test://phony.example.biz', refs=fetch_specs)
  61. self.assertEqual(mirror.fetch_specs, set(expected))
  62. def testPopulate(self):
  63. self.git(['init', '-q'])
  64. with open(os.path.join(self.origin_dir, 'foo'), 'w') as f:
  65. f.write('touched\n')
  66. self.git(['add', 'foo'])
  67. self.git(['commit', '-m', 'foo'])
  68. mirror = git_cache.Mirror(self.origin_dir)
  69. mirror.populate()
  70. def testPopulateResetFetchConfig(self):
  71. self.git(['init', '-q'])
  72. with open(os.path.join(self.origin_dir, 'foo'), 'w') as f:
  73. f.write('touched\n')
  74. self.git(['add', 'foo'])
  75. self.git(['commit', '-m', 'foo'])
  76. mirror = git_cache.Mirror(self.origin_dir)
  77. mirror.populate()
  78. # Add a bad refspec to the cache's fetch config.
  79. cache_dir = os.path.join(
  80. self.cache_dir, mirror.UrlToCacheDir(self.origin_dir))
  81. self.git(['config', '--add', 'remote.origin.fetch',
  82. '+refs/heads/foo:refs/heads/foo'],
  83. cwd=cache_dir)
  84. mirror.populate(reset_fetch_config=True)
  85. def testPopulateTwice(self):
  86. self.git(['init', '-q'])
  87. with open(os.path.join(self.origin_dir, 'foo'), 'w') as f:
  88. f.write('touched\n')
  89. self.git(['add', 'foo'])
  90. self.git(['commit', '-m', 'foo'])
  91. mirror = git_cache.Mirror(self.origin_dir)
  92. mirror.populate()
  93. mirror.populate()
  94. @mock.patch('sys.stdout', StringIO())
  95. def testPruneRequired(self):
  96. self.git(['init', '-q'])
  97. with open(os.path.join(self.origin_dir, 'foo'), 'w') as f:
  98. f.write('touched\n')
  99. self.git(['checkout', '-b', 'foo'])
  100. self.git(['add', 'foo'])
  101. self.git(['commit', '-m', 'foo'])
  102. mirror = git_cache.Mirror(self.origin_dir)
  103. mirror.populate()
  104. self.git(['checkout', '-b', 'foo_tmp', 'foo'])
  105. self.git(['branch', '-D', 'foo'])
  106. self.git(['checkout', '-b', 'foo/bar', 'foo_tmp'])
  107. mirror.populate()
  108. self.assertNotIn(git_cache.GIT_CACHE_CORRUPT_MESSAGE, sys.stdout.getvalue())
  109. def _makeGitRepoWithTag(self):
  110. self.git(['init', '-q'])
  111. with open(os.path.join(self.origin_dir, 'foo'), 'w') as f:
  112. f.write('touched\n')
  113. self.git(['add', 'foo'])
  114. self.git(['commit', '-m', 'foo'])
  115. self.git(['tag', 'TAG'])
  116. self.git(['pack-refs'])
  117. def testPopulateFetchTagsByDefault(self):
  118. self._makeGitRepoWithTag()
  119. # Default behaviour includes tags.
  120. mirror = git_cache.Mirror(self.origin_dir)
  121. mirror.populate()
  122. cache_dir = os.path.join(self.cache_dir,
  123. mirror.UrlToCacheDir(self.origin_dir))
  124. self.assertTrue(os.path.exists(cache_dir + '/refs/tags/TAG'))
  125. def testPopulateFetchWithoutTags(self):
  126. self._makeGitRepoWithTag()
  127. # Ask to not include tags.
  128. mirror = git_cache.Mirror(self.origin_dir)
  129. mirror.populate(no_fetch_tags=True)
  130. cache_dir = os.path.join(self.cache_dir,
  131. mirror.UrlToCacheDir(self.origin_dir))
  132. self.assertFalse(os.path.exists(cache_dir + '/refs/tags/TAG'))
  133. def testPopulateResetFetchConfigEmptyFetchConfig(self):
  134. self.git(['init', '-q'])
  135. with open(os.path.join(self.origin_dir, 'foo'), 'w') as f:
  136. f.write('touched\n')
  137. self.git(['add', 'foo'])
  138. self.git(['commit', '-m', 'foo'])
  139. mirror = git_cache.Mirror(self.origin_dir)
  140. mirror.populate(reset_fetch_config=True)
  141. class GitCacheDirTest(unittest.TestCase):
  142. def setUp(self):
  143. try:
  144. delattr(git_cache.Mirror, 'cachepath')
  145. except AttributeError:
  146. pass
  147. super(GitCacheDirTest, self).setUp()
  148. def tearDown(self):
  149. try:
  150. delattr(git_cache.Mirror, 'cachepath')
  151. except AttributeError:
  152. pass
  153. super(GitCacheDirTest, self).tearDown()
  154. def test_git_config_read(self):
  155. (fd, tmpFile) = tempfile.mkstemp()
  156. old = git_cache.Mirror._GIT_CONFIG_LOCATION
  157. try:
  158. try:
  159. os.write(fd, b'[cache]\n cachepath="hello world"\n')
  160. finally:
  161. os.close(fd)
  162. git_cache.Mirror._GIT_CONFIG_LOCATION = ['-f', tmpFile]
  163. self.assertEqual(git_cache.Mirror.GetCachePath(), 'hello world')
  164. finally:
  165. git_cache.Mirror._GIT_CONFIG_LOCATION = old
  166. os.remove(tmpFile)
  167. def test_environ_read(self):
  168. path = os.environ.get('GIT_CACHE_PATH')
  169. config = os.environ.get('GIT_CONFIG')
  170. try:
  171. os.environ['GIT_CACHE_PATH'] = 'hello world'
  172. os.environ['GIT_CONFIG'] = 'disabled'
  173. self.assertEqual(git_cache.Mirror.GetCachePath(), 'hello world')
  174. finally:
  175. for name, val in zip(('GIT_CACHE_PATH', 'GIT_CONFIG'), (path, config)):
  176. if val is None:
  177. os.environ.pop(name, None)
  178. else:
  179. os.environ[name] = val
  180. def test_manual_set(self):
  181. git_cache.Mirror.SetCachePath('hello world')
  182. self.assertEqual(git_cache.Mirror.GetCachePath(), 'hello world')
  183. def test_unconfigured(self):
  184. path = os.environ.get('GIT_CACHE_PATH')
  185. config = os.environ.get('GIT_CONFIG')
  186. try:
  187. os.environ.pop('GIT_CACHE_PATH', None)
  188. os.environ['GIT_CONFIG'] = 'disabled'
  189. with self.assertRaisesRegexp(RuntimeError, 'cache\.cachepath'):
  190. git_cache.Mirror.GetCachePath()
  191. # negatively cached value still raises
  192. with self.assertRaisesRegexp(RuntimeError, 'cache\.cachepath'):
  193. git_cache.Mirror.GetCachePath()
  194. finally:
  195. for name, val in zip(('GIT_CACHE_PATH', 'GIT_CONFIG'), (path, config)):
  196. if val is None:
  197. os.environ.pop(name, None)
  198. else:
  199. os.environ[name] = val
  200. class MirrorTest(unittest.TestCase):
  201. def test_same_cache_for_authenticated_and_unauthenticated_urls(self):
  202. # GoB can fetch a repo via two different URLs; if the url contains '/a/'
  203. # it forces authenticated access instead of allowing anonymous access,
  204. # even in the case where a repo is public. We want this in order to make
  205. # sure bots are authenticated and get the right quotas. However, we
  206. # only want to maintain a single cache for the repo.
  207. self.assertEqual(git_cache.Mirror.UrlToCacheDir(
  208. 'https://chromium.googlesource.com/a/chromium/src.git'),
  209. 'chromium.googlesource.com-chromium-src')
  210. if __name__ == '__main__':
  211. logging.basicConfig(
  212. level=logging.DEBUG if '-v' in sys.argv else logging.ERROR)
  213. sys.exit(coverage_utils.covered_main((
  214. os.path.join(DEPOT_TOOLS_ROOT, 'git_cache.py')
  215. ), required_percentage=0))