utils.py 12 KB

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