git_test_utils.py 16 KB

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