utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. # utils.py -- Test utilities for Dulwich.
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; version 2
  7. # of the License or (at your option) any later version of
  8. # the License.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  18. # MA 02110-1301, USA.
  19. """Utility functions common to Dulwich tests."""
  20. import datetime
  21. import os
  22. import shutil
  23. import sys
  24. import tempfile
  25. import time
  26. import types
  27. import warnings
  28. from dulwich.index import (
  29. commit_tree,
  30. )
  31. from dulwich.objects import (
  32. FixedSha,
  33. Commit,
  34. Tag,
  35. object_class,
  36. )
  37. from dulwich.pack import (
  38. OFS_DELTA,
  39. REF_DELTA,
  40. DELTA_TYPES,
  41. obj_sha,
  42. SHA1Writer,
  43. write_pack_header,
  44. write_pack_object,
  45. create_delta,
  46. )
  47. from dulwich.repo import Repo
  48. from dulwich.tests import (
  49. SkipTest,
  50. skipIf,
  51. )
  52. # Plain files are very frequently used in tests, so let the mode be very short.
  53. F = 0o100644 # Shorthand mode for Files.
  54. def open_repo(name, temp_dir=None):
  55. """Open a copy of a repo in a temporary directory.
  56. Use this function for accessing repos in dulwich/tests/data/repos to avoid
  57. accidentally or intentionally modifying those repos in place. Use
  58. tear_down_repo to delete any temp files created.
  59. :param name: The name of the repository, relative to
  60. dulwich/tests/data/repos
  61. :temp_dir: temporary directory to initialize to. If not provided, a
  62. temporary directory will be created.
  63. :returns: An initialized Repo object that lives in a temporary directory.
  64. """
  65. temp_dir = tempfile.mkdtemp()
  66. repo_dir = os.path.join(os.path.dirname(__file__), 'data', 'repos', name)
  67. temp_repo_dir = os.path.join(temp_dir, name)
  68. shutil.copytree(repo_dir, temp_repo_dir, symlinks=True)
  69. return Repo(temp_repo_dir)
  70. def tear_down_repo(repo):
  71. """Tear down a test repository."""
  72. temp_dir = os.path.dirname(repo._path_bytes.rstrip(os.sep.encode(sys.getfilesystemencoding())))
  73. shutil.rmtree(temp_dir)
  74. def make_object(cls, **attrs):
  75. """Make an object for testing and assign some members.
  76. This method creates a new subclass to allow arbitrary attribute
  77. reassignment, which is not otherwise possible with objects having __slots__.
  78. :param attrs: dict of attributes to set on the new object.
  79. :return: A newly initialized object of type cls.
  80. """
  81. class TestObject(cls):
  82. """Class that inherits from the given class, but without __slots__.
  83. Note that classes with __slots__ can't have arbitrary attributes monkey-
  84. patched in, so this is a class that is exactly the same only with a
  85. __dict__ instead of __slots__.
  86. """
  87. pass
  88. TestObject.__name__ = 'TestObject_' + cls.__name__
  89. obj = TestObject()
  90. for name, value in attrs.items():
  91. if name == 'id':
  92. # id property is read-only, so we overwrite sha instead.
  93. sha = FixedSha(value)
  94. obj.sha = lambda: sha
  95. else:
  96. setattr(obj, name, value)
  97. return obj
  98. def make_commit(**attrs):
  99. """Make a Commit object with a default set of members.
  100. :param attrs: dict of attributes to overwrite from the default values.
  101. :return: A newly initialized Commit object.
  102. """
  103. default_time = int(time.mktime(datetime.datetime(2010, 1, 1).timetuple()))
  104. all_attrs = {'author': b'Test Author <test@nodomain.com>',
  105. 'author_time': default_time,
  106. 'author_timezone': 0,
  107. 'committer': b'Test Committer <test@nodomain.com>',
  108. 'commit_time': default_time,
  109. 'commit_timezone': 0,
  110. 'message': b'Test message.',
  111. 'parents': [],
  112. 'tree': b'0' * 40}
  113. all_attrs.update(attrs)
  114. return make_object(Commit, **all_attrs)
  115. def make_tag(target, **attrs):
  116. """Make a Tag object with a default set of values.
  117. :param target: object to be tagged (Commit, Blob, Tree, etc)
  118. :param attrs: dict of attributes to overwrite from the default values.
  119. :return: A newly initialized Tag object.
  120. """
  121. target_id = target.id
  122. target_type = object_class(target.type_name)
  123. default_time = int(time.mktime(datetime.datetime(2010, 1, 1).timetuple()))
  124. all_attrs = {'tagger': b'Test Author <test@nodomain.com>',
  125. 'tag_time': default_time,
  126. 'tag_timezone': 0,
  127. 'message': b'Test message.',
  128. 'object': (target_type, target_id),
  129. 'name': b'Test Tag',
  130. }
  131. all_attrs.update(attrs)
  132. return make_object(Tag, **all_attrs)
  133. def functest_builder(method, func):
  134. """Generate a test method that tests the given function."""
  135. def do_test(self):
  136. method(self, func)
  137. return do_test
  138. def ext_functest_builder(method, func):
  139. """Generate a test method that tests the given extension function.
  140. This is intended to generate test methods that test both a pure-Python
  141. version and an extension version using common test code. The extension test
  142. will raise SkipTest if the extension is not found.
  143. Sample usage:
  144. class MyTest(TestCase);
  145. def _do_some_test(self, func_impl):
  146. self.assertEqual('foo', func_impl())
  147. test_foo = functest_builder(_do_some_test, foo_py)
  148. test_foo_extension = ext_functest_builder(_do_some_test, _foo_c)
  149. :param method: The method to run. It must must two parameters, self and the
  150. function implementation to test.
  151. :param func: The function implementation to pass to method.
  152. """
  153. def do_test(self):
  154. if not isinstance(func, types.BuiltinFunctionType):
  155. raise SkipTest("%s extension not found" % func)
  156. method(self, func)
  157. return do_test
  158. def build_pack(f, objects_spec, store=None):
  159. """Write test pack data from a concise spec.
  160. :param f: A file-like object to write the pack to.
  161. :param objects_spec: A list of (type_num, obj). For non-delta types, obj
  162. is the string of that object's data.
  163. For delta types, obj is a tuple of (base, data), where:
  164. * base can be either an index in objects_spec of the base for that
  165. * delta; or for a ref delta, a SHA, in which case the resulting pack
  166. * will be thin and the base will be an external ref.
  167. * data is a string of the full, non-deltified data for that object.
  168. Note that offsets/refs and deltas are computed within this function.
  169. :param store: An optional ObjectStore for looking up external refs.
  170. :return: A list of tuples in the order specified by objects_spec:
  171. (offset, type num, data, sha, CRC32)
  172. """
  173. sf = SHA1Writer(f)
  174. num_objects = len(objects_spec)
  175. write_pack_header(sf, num_objects)
  176. full_objects = {}
  177. offsets = {}
  178. crc32s = {}
  179. while len(full_objects) < num_objects:
  180. for i, (type_num, data) in enumerate(objects_spec):
  181. if type_num not in DELTA_TYPES:
  182. full_objects[i] = (type_num, data,
  183. obj_sha(type_num, [data]))
  184. continue
  185. base, data = data
  186. if isinstance(base, int):
  187. if base not in full_objects:
  188. continue
  189. base_type_num, _, _ = full_objects[base]
  190. else:
  191. base_type_num, _ = store.get_raw(base)
  192. full_objects[i] = (base_type_num, data,
  193. obj_sha(base_type_num, [data]))
  194. for i, (type_num, obj) in enumerate(objects_spec):
  195. offset = f.tell()
  196. if type_num == OFS_DELTA:
  197. base_index, data = obj
  198. base = offset - offsets[base_index]
  199. _, base_data, _ = full_objects[base_index]
  200. obj = (base, create_delta(base_data, data))
  201. elif type_num == REF_DELTA:
  202. base_ref, data = obj
  203. if isinstance(base_ref, int):
  204. _, base_data, base = full_objects[base_ref]
  205. else:
  206. base_type_num, base_data = store.get_raw(base_ref)
  207. base = obj_sha(base_type_num, base_data)
  208. obj = (base, create_delta(base_data, data))
  209. crc32 = write_pack_object(sf, type_num, obj)
  210. offsets[i] = offset
  211. crc32s[i] = crc32
  212. expected = []
  213. for i in range(num_objects):
  214. type_num, data, sha = full_objects[i]
  215. assert len(sha) == 20
  216. expected.append((offsets[i], type_num, data, sha, crc32s[i]))
  217. sf.write_sha()
  218. f.seek(0)
  219. return expected
  220. def build_commit_graph(object_store, commit_spec, trees=None, attrs=None):
  221. """Build a commit graph from a concise specification.
  222. Sample usage:
  223. >>> c1, c2, c3 = build_commit_graph(store, [[1], [2, 1], [3, 1, 2]])
  224. >>> store[store[c3].parents[0]] == c1
  225. True
  226. >>> store[store[c3].parents[1]] == c2
  227. True
  228. If not otherwise specified, commits will refer to the empty tree and have
  229. commit times increasing in the same order as the commit spec.
  230. :param object_store: An ObjectStore to commit objects to.
  231. :param commit_spec: An iterable of iterables of ints defining the commit
  232. graph. Each entry defines one commit, and entries must be in topological
  233. order. The first element of each entry is a commit number, and the
  234. remaining elements are its parents. The commit numbers are only
  235. meaningful for the call to make_commits; since real commit objects are
  236. created, they will get created with real, opaque SHAs.
  237. :param trees: An optional dict of commit number -> tree spec for building
  238. trees for commits. The tree spec is an iterable of (path, blob, mode) or
  239. (path, blob) entries; if mode is omitted, it defaults to the normal file
  240. mode (0100644).
  241. :param attrs: A dict of commit number -> (dict of attribute -> value) for
  242. assigning additional values to the commits.
  243. :return: The list of commit objects created.
  244. :raise ValueError: If an undefined commit identifier is listed as a parent.
  245. """
  246. if trees is None:
  247. trees = {}
  248. if attrs is None:
  249. attrs = {}
  250. commit_time = 0
  251. nums = {}
  252. commits = []
  253. for commit in commit_spec:
  254. commit_num = commit[0]
  255. try:
  256. parent_ids = [nums[pn] for pn in commit[1:]]
  257. except KeyError as e:
  258. missing_parent, = e.args
  259. raise ValueError('Unknown parent %i' % missing_parent)
  260. blobs = []
  261. for entry in trees.get(commit_num, []):
  262. if len(entry) == 2:
  263. path, blob = entry
  264. entry = (path, blob, F)
  265. path, blob, mode = entry
  266. blobs.append((path, blob.id, mode))
  267. object_store.add_object(blob)
  268. tree_id = commit_tree(object_store, blobs)
  269. commit_attrs = {
  270. 'message': ('Commit %i' % commit_num).encode('ascii'),
  271. 'parents': parent_ids,
  272. 'tree': tree_id,
  273. 'commit_time': commit_time,
  274. }
  275. commit_attrs.update(attrs.get(commit_num, {}))
  276. commit_obj = make_commit(**commit_attrs)
  277. # By default, increment the time by a lot. Out-of-order commits should
  278. # be closer together than this because their main cause is clock skew.
  279. commit_time = commit_attrs['commit_time'] + 100
  280. nums[commit_num] = commit_obj.id
  281. object_store.add_object(commit_obj)
  282. commits.append(commit_obj)
  283. return commits
  284. def setup_warning_catcher():
  285. """Wrap warnings.showwarning with code that records warnings."""
  286. caught_warnings = []
  287. original_showwarning = warnings.showwarning
  288. def custom_showwarning(*args, **kwargs):
  289. caught_warnings.append(args[0])
  290. warnings.showwarning = custom_showwarning
  291. def restore_showwarning():
  292. warnings.showwarning = original_showwarning
  293. return caught_warnings, restore_showwarning
  294. skipIfPY3 = skipIf(sys.version_info[0] == 3, "Feature not yet ported to python3.")