git_test_utils.py 17 KB

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