git_test_utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. 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 'main'
  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='', content_fn=lambda v: {v: {'data': v}}):
  111. """Builds a new GitRepoSchema.
  112. Args:
  113. repo_schema (str) - Initial schema for this repo. See class docstring for
  114. info on the schema format.
  115. content_fn ((commit_name) -> commit_data) - A function which will be
  116. lazily called to obtain data for each commit. The results of this
  117. function are cached (i.e. it will never be called twice for the same
  118. commit_name). See the docstring on the GitRepo class for the format of
  119. the data returned by this function.
  120. """
  121. self.main = None
  122. self.par_map = {}
  123. self.data_cache = {}
  124. self.content_fn = content_fn
  125. self.add_commits(repo_schema)
  126. def walk(self):
  127. """(Generator) Walks the repo schema from roots to tips.
  128. Generates GitRepoSchema.COMMIT objects for each commit.
  129. Throws an AssertionError if it detects a cycle.
  130. """
  131. is_root = True
  132. par_map = copy.deepcopy(self.par_map)
  133. while par_map:
  134. empty_keys = set(k for k, v in par_map.items() if not v)
  135. assert empty_keys, 'Cycle detected! %s' % par_map
  136. for k in sorted(empty_keys):
  137. yield self.COMMIT(
  138. k, self.par_map[k],
  139. not any(k in v for v in self.par_map.values()), is_root)
  140. del par_map[k]
  141. for v in par_map.values():
  142. v.difference_update(empty_keys)
  143. is_root = False
  144. def add_partial(self, commit, parent=None):
  145. if commit not in self.par_map:
  146. self.par_map[commit] = OrderedSet()
  147. if parent is not None:
  148. self.par_map[commit].add(parent)
  149. def add_commits(self, schema):
  150. """Adds more commits from a schema into the existing Schema.
  151. Args:
  152. schema (str) - See class docstring for info on schema format.
  153. Throws an AssertionError if it detects a cycle.
  154. """
  155. for commits in (l.split() for l in schema.splitlines() if l.strip()):
  156. parent = None
  157. for commit in commits:
  158. self.add_partial(commit, parent)
  159. parent = commit
  160. if parent and not self.main:
  161. self.main = parent
  162. for _ in self.walk(): # This will throw if there are any cycles.
  163. pass
  164. def reify(self):
  165. """Returns a real GitRepo for this GitRepoSchema"""
  166. return GitRepo(self)
  167. def data_for(self, commit):
  168. """Obtains the data for |commit|.
  169. See the docstring on the GitRepo class for the format of the returned data.
  170. Caches the result on this GitRepoSchema instance.
  171. """
  172. if commit not in self.data_cache:
  173. self.data_cache[commit] = self.content_fn(commit)
  174. return self.data_cache[commit]
  175. def simple_graph(self):
  176. """Returns a dictionary of {commit_subject: {parent commit_subjects}}
  177. This allows you to get a very simple connection graph over the whole repo
  178. for comparison purposes. Only commit subjects (not ids, not content/data)
  179. are considered
  180. """
  181. ret = {}
  182. for commit in self.walk():
  183. ret.setdefault(commit.name, set()).update(commit.parents)
  184. return ret
  185. class GitRepo(object):
  186. """Creates a real git repo for a GitRepoSchema.
  187. Obtains schema and content information from the GitRepoSchema.
  188. The format for the commit data supplied by GitRepoSchema.data_for is:
  189. {
  190. SPECIAL_KEY: special_value,
  191. ...
  192. "path/to/some/file": { 'data': "some data content for this file",
  193. 'mode': 0o755 },
  194. ...
  195. }
  196. The SPECIAL_KEYs are the following attributes of the GitRepo class:
  197. * AUTHOR_NAME
  198. * AUTHOR_EMAIL
  199. * AUTHOR_DATE - must be a datetime.datetime instance
  200. * COMMITTER_NAME
  201. * COMMITTER_EMAIL
  202. * COMMITTER_DATE - must be a datetime.datetime instance
  203. For file content, if 'data' is None, then this commit will `git rm` that file.
  204. """
  205. BASE_TEMP_DIR = tempfile.mkdtemp(suffix='base', prefix='git_repo')
  206. atexit.register(gclient_utils.rmtree, BASE_TEMP_DIR)
  207. # Singleton objects to specify specific data in a commit dictionary.
  208. AUTHOR_NAME = object()
  209. AUTHOR_EMAIL = object()
  210. AUTHOR_DATE = object()
  211. COMMITTER_NAME = object()
  212. COMMITTER_EMAIL = object()
  213. COMMITTER_DATE = object()
  214. DEFAULT_AUTHOR_NAME = 'Author McAuthorly'
  215. DEFAULT_AUTHOR_EMAIL = 'author@example.com'
  216. DEFAULT_COMMITTER_NAME = 'Charles Committish'
  217. DEFAULT_COMMITTER_EMAIL = 'commitish@example.com'
  218. COMMAND_OUTPUT = collections.namedtuple('COMMAND_OUTPUT', 'retcode stdout')
  219. def __init__(self, schema):
  220. """Makes new GitRepo.
  221. Automatically creates a temp folder under GitRepo.BASE_TEMP_DIR. It's
  222. recommended that you clean this repo up by calling nuke() on it, but if not,
  223. GitRepo will automatically clean up all allocated repos at the exit of the
  224. program (assuming a normal exit like with sys.exit)
  225. Args:
  226. schema - An instance of GitRepoSchema
  227. """
  228. self.repo_path = os.path.realpath(
  229. 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', '-b', DEFAULT_BRANCH)
  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.main:
  240. self.git('update-ref', 'refs/heads/main', self[schema.main])
  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',
  255. *[self[x] for x in parents[1:]])
  256. else:
  257. self.git('checkout', '--orphan', 'root_%s' % commit.name)
  258. self.git('rm', '-rf', '.')
  259. env = self.get_git_commit_env(commit_data)
  260. for fname, file_data in commit_data.items():
  261. # If it isn't a string, it's one of the special keys.
  262. if not isinstance(fname, str):
  263. continue
  264. deleted = False
  265. if 'data' in file_data:
  266. data = file_data.get('data')
  267. if data is None:
  268. deleted = True
  269. self.git('rm', fname)
  270. else:
  271. path = os.path.join(self.repo_path, fname)
  272. pardir = os.path.dirname(path)
  273. if not os.path.exists(pardir):
  274. os.makedirs(pardir)
  275. with open(path, 'wb') as f:
  276. f.write(data)
  277. mode = file_data.get('mode')
  278. if mode and not deleted:
  279. os.chmod(path, mode)
  280. self.git('add', fname)
  281. rslt = self.git('commit', '--allow-empty', '-m', commit.name, env=env)
  282. assert rslt.retcode == 0, 'Failed to commit %s' % str(commit)
  283. self.commit_map[commit.name] = self.git('rev-parse',
  284. '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,
  288. 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(('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
  336. set to 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
  346. to 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',
  372. *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. return getattr(cls, commit, None)
  407. @classmethod
  408. def setUpClass(cls):
  409. super(GitRepoSchemaTestBase, cls).setUpClass()
  410. assert cls.REPO_SCHEMA is not None
  411. cls.r_schema = GitRepoSchema(cls.REPO_SCHEMA, cls.getRepoContent)
  412. class GitRepoReadOnlyTestBase(GitRepoSchemaTestBase):
  413. """Injects a GitRepo object given the schema and content from
  414. GitRepoSchemaTestBase into TestCase classes which subclass this.
  415. This GitRepo will appear as self.repo, and will be deleted and recreated once
  416. for the duration of all the tests in the subclass.
  417. """
  418. REPO_SCHEMA = None
  419. @classmethod
  420. def setUpClass(cls):
  421. super(GitRepoReadOnlyTestBase, cls).setUpClass()
  422. assert cls.REPO_SCHEMA is not None
  423. cls.repo = cls.r_schema.reify()
  424. def setUp(self):
  425. self.repo.git('checkout', '-f', self.repo.last_commit)
  426. @classmethod
  427. def tearDownClass(cls):
  428. cls.repo.nuke()
  429. super(GitRepoReadOnlyTestBase, cls).tearDownClass()
  430. class GitRepoReadWriteTestBase(GitRepoSchemaTestBase):
  431. """Injects a GitRepo object given the schema and content from
  432. GitRepoSchemaTestBase into TestCase classes which subclass this.
  433. This GitRepo will appear as self.repo, and will be deleted and recreated for
  434. each test function in the subclass.
  435. """
  436. REPO_SCHEMA = None
  437. def setUp(self):
  438. super(GitRepoReadWriteTestBase, self).setUp()
  439. self.repo = self.r_schema.reify()
  440. def tearDown(self):
  441. self.repo.nuke()
  442. super(GitRepoReadWriteTestBase, self).tearDown()
  443. def assertSchema(self, schema_string):
  444. self.assertEqual(
  445. GitRepoSchema(schema_string).simple_graph(),
  446. self.repo.to_schema().simple_graph())