git_test_utils.py 17 KB

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