git_test_utils.py 15 KB

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