git_test_utils.py 15 KB

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