git_test_utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. # Copyright 2013 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. import atexit
  5. import collections
  6. import copy
  7. import datetime
  8. import hashlib
  9. import os
  10. import shutil
  11. import subprocess
  12. import tempfile
  13. import unittest
  14. def git_hash_data(data, typ='blob'):
  15. """Calculate the git-style SHA1 for some data.
  16. Only supports 'blob' type data at the moment.
  17. """
  18. assert typ == 'blob', 'Only support blobs for now'
  19. return hashlib.sha1('blob %s\0%s' % (len(data), data)).hexdigest()
  20. class OrderedSet(collections.MutableSet):
  21. # from http://code.activestate.com/recipes/576694/
  22. def __init__(self, iterable=None):
  23. self.end = end = []
  24. end += [None, end, end] # sentinel node for doubly linked list
  25. self.data = {} # key --> [key, prev, next]
  26. if iterable is not None:
  27. self |= iterable
  28. def __contains__(self, key):
  29. return key in self.data
  30. def __eq__(self, other):
  31. if isinstance(other, OrderedSet):
  32. return len(self) == len(other) and list(self) == list(other)
  33. return set(self) == set(other)
  34. def __ne__(self, other):
  35. if isinstance(other, OrderedSet):
  36. return len(self) != len(other) or list(self) != list(other)
  37. return set(self) != set(other)
  38. def __len__(self):
  39. return len(self.data)
  40. def __iter__(self):
  41. end = self.end
  42. curr = end[2]
  43. while curr is not end:
  44. yield curr[0]
  45. curr = curr[2]
  46. def __repr__(self):
  47. if not self:
  48. return '%s()' % (self.__class__.__name__,)
  49. return '%s(%r)' % (self.__class__.__name__, list(self))
  50. def __reversed__(self):
  51. end = self.end
  52. curr = end[1]
  53. while curr is not end:
  54. yield curr[0]
  55. curr = curr[1]
  56. def add(self, key):
  57. if key not in self.data:
  58. end = self.end
  59. curr = end[1]
  60. curr[2] = end[1] = self.data[key] = [key, curr, end]
  61. def difference_update(self, *others):
  62. for other in others:
  63. for i in other:
  64. self.discard(i)
  65. def discard(self, key):
  66. if key in self.data:
  67. key, prev, nxt = self.data.pop(key)
  68. prev[2] = nxt
  69. nxt[1] = prev
  70. def pop(self, last=True): # pylint: disable=W0221
  71. if not self:
  72. raise KeyError('set is empty')
  73. key = self.end[1][0] if last else self.end[2][0]
  74. self.discard(key)
  75. return key
  76. class GitRepoSchema(object):
  77. """A declarative git testing repo.
  78. Pass a schema to __init__ in the form of:
  79. A B C D
  80. B E D
  81. This is the repo
  82. A - B - C - D
  83. \ E /
  84. Whitespace doesn't matter. Each line is a declaration of which commits come
  85. before which other commits.
  86. Every commit gets a tag 'tag_%(commit)s'
  87. Every unique terminal commit gets a branch 'branch_%(commit)s'
  88. Last commit in First line is the branch 'master'
  89. Root commits get a ref 'root_%(commit)s'
  90. Timestamps are in topo order, earlier commits (as indicated by their presence
  91. in the schema) get earlier timestamps. Stamps start at the Unix Epoch, and
  92. increment by 1 day each.
  93. """
  94. COMMIT = collections.namedtuple('COMMIT', 'name parents is_branch is_root')
  95. def __init__(self, repo_schema='',
  96. content_fn=lambda v: {v: {'data': v}}):
  97. """Builds a new GitRepoSchema.
  98. Args:
  99. repo_schema (str) - Initial schema for this repo. See class docstring for
  100. info on the schema format.
  101. content_fn ((commit_name) -> commit_data) - A function which will be
  102. lazily called to obtain data for each commit. The results of this
  103. function are cached (i.e. it will never be called twice for the same
  104. commit_name). See the docstring on the GitRepo class for the format of
  105. the data returned by this function.
  106. """
  107. self.master = None
  108. self.par_map = {}
  109. self.data_cache = {}
  110. self.content_fn = content_fn
  111. self.add_commits(repo_schema)
  112. def walk(self):
  113. """(Generator) Walks the repo schema from roots to tips.
  114. Generates GitRepoSchema.COMMIT objects for each commit.
  115. Throws an AssertionError if it detects a cycle.
  116. """
  117. is_root = True
  118. par_map = copy.deepcopy(self.par_map)
  119. while par_map:
  120. empty_keys = set(k for k, v in par_map.iteritems() if not v)
  121. assert empty_keys, 'Cycle detected! %s' % par_map
  122. for k in sorted(empty_keys):
  123. yield self.COMMIT(k, self.par_map[k],
  124. not any(k in v for v in self.par_map.itervalues()),
  125. is_root)
  126. del par_map[k]
  127. for v in par_map.itervalues():
  128. v.difference_update(empty_keys)
  129. is_root = False
  130. def add_commits(self, schema):
  131. """Adds more commits from a schema into the existing Schema.
  132. Args:
  133. schema (str) - See class docstring for info on schema format.
  134. Throws an AssertionError if it detects a cycle.
  135. """
  136. for commits in (l.split() for l in schema.splitlines() if l.strip()):
  137. parent = None
  138. for commit in commits:
  139. if commit not in self.par_map:
  140. self.par_map[commit] = OrderedSet()
  141. if parent is not None:
  142. self.par_map[commit].add(parent)
  143. parent = commit
  144. if parent and not self.master:
  145. self.master = parent
  146. for _ in self.walk(): # This will throw if there are any cycles.
  147. pass
  148. def reify(self):
  149. """Returns a real GitRepo for this GitRepoSchema"""
  150. return GitRepo(self)
  151. def data_for(self, commit):
  152. """Obtains the data for |commit|.
  153. See the docstring on the GitRepo class for the format of the returned data.
  154. Caches the result on this GitRepoSchema instance.
  155. """
  156. if commit not in self.data_cache:
  157. self.data_cache[commit] = self.content_fn(commit)
  158. return self.data_cache[commit]
  159. class GitRepo(object):
  160. """Creates a real git repo for a GitRepoSchema.
  161. Obtains schema and content information from the GitRepoSchema.
  162. The format for the commit data supplied by GitRepoSchema.data_for is:
  163. {
  164. SPECIAL_KEY: special_value,
  165. ...
  166. "path/to/some/file": { 'data': "some data content for this file",
  167. 'mode': 0755 },
  168. ...
  169. }
  170. The SPECIAL_KEYs are the following attribues of the GitRepo class:
  171. * AUTHOR_NAME
  172. * AUTHOR_EMAIL
  173. * AUTHOR_DATE - must be a datetime.datetime instance
  174. * COMMITTER_NAME
  175. * COMMITTER_EMAIL
  176. * COMMITTER_DATE - must be a datetime.datetime instance
  177. For file content, if 'data' is None, then this commit will `git rm` that file.
  178. """
  179. BASE_TEMP_DIR = tempfile.mkdtemp(suffix='base', prefix='git_repo')
  180. atexit.register(shutil.rmtree, BASE_TEMP_DIR)
  181. # Singleton objects to specify specific data in a commit dictionary.
  182. AUTHOR_NAME = object()
  183. AUTHOR_EMAIL = object()
  184. AUTHOR_DATE = object()
  185. COMMITTER_NAME = object()
  186. COMMITTER_EMAIL = object()
  187. COMMITTER_DATE = object()
  188. DEFAULT_AUTHOR_NAME = 'Author McAuthorly'
  189. DEFAULT_AUTHOR_EMAIL = 'author@example.com'
  190. DEFAULT_COMMITTER_NAME = 'Charles Committish'
  191. DEFAULT_COMMITTER_EMAIL = 'commitish@example.com'
  192. COMMAND_OUTPUT = collections.namedtuple('COMMAND_OUTPUT', 'retcode stdout')
  193. def __init__(self, schema):
  194. """Makes new GitRepo.
  195. Automatically creates a temp folder under GitRepo.BASE_TEMP_DIR. It's
  196. recommended that you clean this repo up by calling nuke() on it, but if not,
  197. GitRepo will automatically clean up all allocated repos at the exit of the
  198. program (assuming a normal exit like with sys.exit)
  199. Args:
  200. schema - An instance of GitRepoSchema
  201. """
  202. self.repo_path = tempfile.mkdtemp(dir=self.BASE_TEMP_DIR)
  203. self.commit_map = {}
  204. self._date = datetime.datetime(1970, 1, 1)
  205. self.git('init')
  206. for commit in schema.walk():
  207. self._add_schema_commit(commit, schema.data_for(commit.name))
  208. if schema.master:
  209. self.git('update-ref', 'master', self[schema.master])
  210. def __getitem__(self, commit_name):
  211. """Gets the hash of a commit by its schema name.
  212. >>> r = GitRepo(GitRepoSchema('A B C'))
  213. >>> r['B']
  214. '7381febe1da03b09da47f009963ab7998a974935'
  215. """
  216. return self.commit_map[commit_name]
  217. def _add_schema_commit(self, commit, data):
  218. data = data or {}
  219. if commit.parents:
  220. parents = list(commit.parents)
  221. self.git('checkout', '--detach', '-q', self[parents[0]])
  222. if len(parents) > 1:
  223. self.git('merge', '--no-commit', '-q', *[self[x] for x in parents[1:]])
  224. else:
  225. self.git('checkout', '--orphan', 'root_%s' % commit.name)
  226. self.git('rm', '-rf', '.')
  227. env = {}
  228. for prefix in ('AUTHOR', 'COMMITTER'):
  229. for suffix in ('NAME', 'EMAIL', 'DATE'):
  230. singleton = '%s_%s' % (prefix, suffix)
  231. key = getattr(self, singleton)
  232. if key in data:
  233. val = data[key]
  234. else:
  235. if suffix == 'DATE':
  236. val = self._date
  237. self._date += datetime.timedelta(days=1)
  238. else:
  239. val = getattr(self, 'DEFAULT_%s' % singleton)
  240. env['GIT_%s' % singleton] = str(val)
  241. for fname, file_data in data.iteritems():
  242. deleted = False
  243. if 'data' in file_data:
  244. data = file_data.get('data')
  245. if data is None:
  246. deleted = True
  247. self.git('rm', fname)
  248. else:
  249. path = os.path.join(self.repo_path, fname)
  250. pardir = os.path.dirname(path)
  251. if not os.path.exists(pardir):
  252. os.makedirs(pardir)
  253. with open(path, 'wb') as f:
  254. f.write(data)
  255. mode = file_data.get('mode')
  256. if mode and not deleted:
  257. os.chmod(path, mode)
  258. self.git('add', fname)
  259. rslt = self.git('commit', '--allow-empty', '-m', commit.name, env=env)
  260. assert rslt.retcode == 0, 'Failed to commit %s' % str(commit)
  261. self.commit_map[commit.name] = self.git('rev-parse', 'HEAD').stdout.strip()
  262. self.git('tag', 'tag_%s' % commit.name, self[commit.name])
  263. if commit.is_branch:
  264. self.git('update-ref', 'branch_%s' % commit.name, self[commit.name])
  265. def git(self, *args, **kwargs):
  266. """Runs a git command specified by |args| in this repo."""
  267. assert self.repo_path is not None
  268. try:
  269. with open(os.devnull, 'wb') as devnull:
  270. output = subprocess.check_output(
  271. ('git',) + args, cwd=self.repo_path, stderr=devnull, **kwargs)
  272. return self.COMMAND_OUTPUT(0, output)
  273. except subprocess.CalledProcessError as e:
  274. return self.COMMAND_OUTPUT(e.returncode, e.output)
  275. def nuke(self):
  276. """Obliterates the git repo on disk.
  277. Causes this GitRepo to be unusable.
  278. """
  279. shutil.rmtree(self.repo_path)
  280. self.repo_path = None
  281. def run(self, fn, *args, **kwargs):
  282. """Run a python function with the given args and kwargs with the cwd set to
  283. the git repo."""
  284. assert self.repo_path is not None
  285. curdir = os.getcwd()
  286. try:
  287. os.chdir(self.repo_path)
  288. return fn(*args, **kwargs)
  289. finally:
  290. os.chdir(curdir)
  291. class GitRepoSchemaTestBase(unittest.TestCase):
  292. """A TestCase with a built-in GitRepoSchema.
  293. Expects a class variable REPO to be a GitRepoSchema string in the form
  294. described by that class.
  295. You may also set class variables in the form COMMIT_%(commit_name)s, which
  296. provide the content for the given commit_name commits.
  297. You probably will end up using either GitRepoReadOnlyTestBase or
  298. GitRepoReadWriteTestBase for real tests.
  299. """
  300. REPO = None
  301. @classmethod
  302. def getRepoContent(cls, commit):
  303. return getattr(cls, 'COMMIT_%s' % commit, None)
  304. @classmethod
  305. def setUpClass(cls):
  306. super(GitRepoSchemaTestBase, cls).setUpClass()
  307. assert cls.REPO is not None
  308. cls.r_schema = GitRepoSchema(cls.REPO, cls.getRepoContent)
  309. class GitRepoReadOnlyTestBase(GitRepoSchemaTestBase):
  310. """Injects a GitRepo object given the schema and content from
  311. GitRepoSchemaTestBase into TestCase classes which subclass this.
  312. This GitRepo will appear as self.repo, and will be deleted and recreated once
  313. for the duration of all the tests in the subclass.
  314. """
  315. REPO = None
  316. @classmethod
  317. def setUpClass(cls):
  318. super(GitRepoReadOnlyTestBase, cls).setUpClass()
  319. assert cls.REPO is not None
  320. cls.repo = cls.r_schema.reify()
  321. @classmethod
  322. def tearDownClass(cls):
  323. cls.repo.nuke()
  324. super(GitRepoReadOnlyTestBase, cls).tearDownClass()
  325. class GitRepoReadWriteTestBase(GitRepoSchemaTestBase):
  326. """Injects a GitRepo object given the schema and content from
  327. GitRepoSchemaTestBase into TestCase classes which subclass this.
  328. This GitRepo will appear as self.repo, and will be deleted and recreated for
  329. each test function in the subclass.
  330. """
  331. REPO = None
  332. def setUp(self):
  333. super(GitRepoReadWriteTestBase, self).setUp()
  334. self.repo = self.r_schema.reify()
  335. def tearDown(self):
  336. self.repo.nuke()
  337. super(GitRepoReadWriteTestBase, self).tearDown()