utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. from cStringIO import StringIO
  21. import datetime
  22. import os
  23. import shutil
  24. import tempfile
  25. import time
  26. import types
  27. from dulwich.index import (
  28. commit_tree,
  29. )
  30. from dulwich.objects import (
  31. FixedSha,
  32. Commit,
  33. )
  34. from dulwich.pack import (
  35. OFS_DELTA,
  36. REF_DELTA,
  37. DELTA_TYPES,
  38. obj_sha,
  39. SHA1Writer,
  40. write_pack_header,
  41. write_pack_object,
  42. create_delta,
  43. )
  44. from dulwich.repo import Repo
  45. from dulwich.tests import (
  46. SkipTest,
  47. )
  48. # Plain files are very frequently used in tests, so let the mode be very short.
  49. F = 0100644 # Shorthand mode for Files.
  50. def open_repo(name):
  51. """Open a copy of a repo in a temporary directory.
  52. Use this function for accessing repos in dulwich/tests/data/repos to avoid
  53. accidentally or intentionally modifying those repos in place. Use
  54. tear_down_repo to delete any temp files created.
  55. :param name: The name of the repository, relative to
  56. dulwich/tests/data/repos
  57. :returns: An initialized Repo object that lives in a temporary directory.
  58. """
  59. temp_dir = tempfile.mkdtemp()
  60. repo_dir = os.path.join(os.path.dirname(__file__), 'data', 'repos', name)
  61. temp_repo_dir = os.path.join(temp_dir, name)
  62. shutil.copytree(repo_dir, temp_repo_dir, symlinks=True)
  63. return Repo(temp_repo_dir)
  64. def tear_down_repo(repo):
  65. """Tear down a test repository."""
  66. temp_dir = os.path.dirname(repo.path.rstrip(os.sep))
  67. shutil.rmtree(temp_dir)
  68. def make_object(cls, **attrs):
  69. """Make an object for testing and assign some members.
  70. This method creates a new subclass to allow arbitrary attribute
  71. reassignment, which is not otherwise possible with objects having __slots__.
  72. :param attrs: dict of attributes to set on the new object.
  73. :return: A newly initialized object of type cls.
  74. """
  75. class TestObject(cls):
  76. """Class that inherits from the given class, but without __slots__.
  77. Note that classes with __slots__ can't have arbitrary attributes monkey-
  78. patched in, so this is a class that is exactly the same only with a
  79. __dict__ instead of __slots__.
  80. """
  81. pass
  82. obj = TestObject()
  83. for name, value in attrs.iteritems():
  84. if name == 'id':
  85. # id property is read-only, so we overwrite sha instead.
  86. sha = FixedSha(value)
  87. obj.sha = lambda: sha
  88. else:
  89. setattr(obj, name, value)
  90. return obj
  91. def make_commit(**attrs):
  92. """Make a Commit object with a default set of members.
  93. :param attrs: dict of attributes to overwrite from the default values.
  94. :return: A newly initialized Commit object.
  95. """
  96. default_time = int(time.mktime(datetime.datetime(2010, 1, 1).timetuple()))
  97. all_attrs = {'author': 'Test Author <test@nodomain.com>',
  98. 'author_time': default_time,
  99. 'author_timezone': 0,
  100. 'committer': 'Test Committer <test@nodomain.com>',
  101. 'commit_time': default_time,
  102. 'commit_timezone': 0,
  103. 'message': 'Test message.',
  104. 'parents': [],
  105. 'tree': '0' * 40}
  106. all_attrs.update(attrs)
  107. return make_object(Commit, **all_attrs)
  108. def functest_builder(method, func):
  109. """Generate a test method that tests the given function."""
  110. def do_test(self):
  111. method(self, func)
  112. return do_test
  113. def ext_functest_builder(method, func):
  114. """Generate a test method that tests the given extension function.
  115. This is intended to generate test methods that test both a pure-Python
  116. version and an extension version using common test code. The extension test
  117. will raise SkipTest if the extension is not found.
  118. Sample usage:
  119. class MyTest(TestCase);
  120. def _do_some_test(self, func_impl):
  121. self.assertEqual('foo', func_impl())
  122. test_foo = functest_builder(_do_some_test, foo_py)
  123. test_foo_extension = ext_functest_builder(_do_some_test, _foo_c)
  124. :param method: The method to run. It must must two parameters, self and the
  125. function implementation to test.
  126. :param func: The function implementation to pass to method.
  127. """
  128. def do_test(self):
  129. if not isinstance(func, types.BuiltinFunctionType):
  130. raise SkipTest("%s extension not found" % func.func_name)
  131. method(self, func)
  132. return do_test
  133. def build_pack(f, objects_spec, store=None):
  134. """Write test pack data from a concise spec.
  135. :param f: A file-like object to write the pack to.
  136. :param objects_spec: A list of (type_num, obj). For non-delta types, obj
  137. is the string of that object's data.
  138. For delta types, obj is a tuple of (base, data), where:
  139. * base can be either an index in objects_spec of the base for that
  140. * delta; or for a ref delta, a SHA, in which case the resulting pack
  141. * will be thin and the base will be an external ref.
  142. * data is a string of the full, non-deltified data for that object.
  143. Note that offsets/refs and deltas are computed within this function.
  144. :param store: An optional ObjectStore for looking up external refs.
  145. :return: A list of tuples in the order specified by objects_spec:
  146. (offset, type num, data, sha, CRC32)
  147. """
  148. sf = SHA1Writer(f)
  149. num_objects = len(objects_spec)
  150. write_pack_header(sf, num_objects)
  151. full_objects = {}
  152. offsets = {}
  153. crc32s = {}
  154. while len(full_objects) < num_objects:
  155. for i, (type_num, data) in enumerate(objects_spec):
  156. if type_num not in DELTA_TYPES:
  157. full_objects[i] = (type_num, data,
  158. obj_sha(type_num, [data]))
  159. continue
  160. base, data = data
  161. if isinstance(base, int):
  162. if base not in full_objects:
  163. continue
  164. base_type_num, _, _ = full_objects[base]
  165. else:
  166. base_type_num, _ = store.get_raw(base)
  167. full_objects[i] = (base_type_num, data,
  168. obj_sha(base_type_num, [data]))
  169. for i, (type_num, obj) in enumerate(objects_spec):
  170. offset = f.tell()
  171. if type_num == OFS_DELTA:
  172. base_index, data = obj
  173. base = offset - offsets[base_index]
  174. _, base_data, _ = full_objects[base_index]
  175. obj = (base, create_delta(base_data, data))
  176. elif type_num == REF_DELTA:
  177. base_ref, data = obj
  178. if isinstance(base_ref, int):
  179. _, base_data, base = full_objects[base_ref]
  180. else:
  181. base_type_num, base_data = store.get_raw(base_ref)
  182. base = obj_sha(base_type_num, base_data)
  183. obj = (base, create_delta(base_data, data))
  184. crc32 = write_pack_object(sf, type_num, obj)
  185. offsets[i] = offset
  186. crc32s[i] = crc32
  187. expected = []
  188. for i in xrange(num_objects):
  189. type_num, data, sha = full_objects[i]
  190. expected.append((offsets[i], type_num, data, sha, crc32s[i]))
  191. sf.write_sha()
  192. f.seek(0)
  193. return expected
  194. def build_commit_graph(object_store, commit_spec, trees=None, attrs=None):
  195. """Build a commit graph from a concise specification.
  196. Sample usage:
  197. >>> c1, c2, c3 = build_commit_graph(store, [[1], [2, 1], [3, 1, 2]])
  198. >>> store[store[c3].parents[0]] == c1
  199. True
  200. >>> store[store[c3].parents[1]] == c2
  201. True
  202. If not otherwise specified, commits will refer to the empty tree and have
  203. commit times increasing in the same order as the commit spec.
  204. :param object_store: An ObjectStore to commit objects to.
  205. :param commit_spec: An iterable of iterables of ints defining the commit
  206. graph. Each entry defines one commit, and entries must be in topological
  207. order. The first element of each entry is a commit number, and the
  208. remaining elements are its parents. The commit numbers are only
  209. meaningful for the call to make_commits; since real commit objects are
  210. created, they will get created with real, opaque SHAs.
  211. :param trees: An optional dict of commit number -> tree spec for building
  212. trees for commits. The tree spec is an iterable of (path, blob, mode) or
  213. (path, blob) entries; if mode is omitted, it defaults to the normal file
  214. mode (0100644).
  215. :param attrs: A dict of commit number -> (dict of attribute -> value) for
  216. assigning additional values to the commits.
  217. :return: The list of commit objects created.
  218. :raise ValueError: If an undefined commit identifier is listed as a parent.
  219. """
  220. if trees is None:
  221. trees = {}
  222. if attrs is None:
  223. attrs = {}
  224. commit_time = 0
  225. nums = {}
  226. commits = []
  227. for commit in commit_spec:
  228. commit_num = commit[0]
  229. try:
  230. parent_ids = [nums[pn] for pn in commit[1:]]
  231. except KeyError, e:
  232. missing_parent, = e.args
  233. raise ValueError('Unknown parent %i' % missing_parent)
  234. blobs = []
  235. for entry in trees.get(commit_num, []):
  236. if len(entry) == 2:
  237. path, blob = entry
  238. entry = (path, blob, F)
  239. path, blob, mode = entry
  240. blobs.append((path, blob.id, mode))
  241. object_store.add_object(blob)
  242. tree_id = commit_tree(object_store, blobs)
  243. commit_attrs = {
  244. 'message': 'Commit %i' % commit_num,
  245. 'parents': parent_ids,
  246. 'tree': tree_id,
  247. 'commit_time': commit_time,
  248. }
  249. commit_attrs.update(attrs.get(commit_num, {}))
  250. commit_obj = make_commit(**commit_attrs)
  251. # By default, increment the time by a lot. Out-of-order commits should
  252. # be closer together than this because their main cause is clock skew.
  253. commit_time = commit_attrs['commit_time'] + 100
  254. nums[commit_num] = commit_obj.id
  255. object_store.add_object(commit_obj)
  256. commits.append(commit_obj)
  257. return commits