git_test_utils.py 16 KB

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