test_pack.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. # test_pack.py -- Tests for the handling of git packs.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008 Jelmer Vernooij <jelmer@samba.org>
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; version 2
  8. # of the License, or (at your option) any later version of 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. """Tests for Dulwich packs."""
  20. from cStringIO import StringIO
  21. import os
  22. import shutil
  23. import tempfile
  24. import zlib
  25. from dulwich._compat import (
  26. make_sha,
  27. )
  28. from dulwich.errors import (
  29. ChecksumMismatch,
  30. )
  31. from dulwich.file import (
  32. GitFile,
  33. )
  34. from dulwich.object_store import (
  35. MemoryObjectStore,
  36. )
  37. from dulwich.objects import (
  38. Blob,
  39. hex_to_sha,
  40. sha_to_hex,
  41. Commit,
  42. Tree,
  43. Blob,
  44. )
  45. from dulwich.pack import (
  46. OFS_DELTA,
  47. REF_DELTA,
  48. DELTA_TYPES,
  49. MemoryPackIndex,
  50. Pack,
  51. PackData,
  52. apply_delta,
  53. create_delta,
  54. deltify_pack_objects,
  55. load_pack_index,
  56. UnpackedObject,
  57. read_zlib_chunks,
  58. write_pack_header,
  59. write_pack_index_v1,
  60. write_pack_index_v2,
  61. SHA1Writer,
  62. write_pack_object,
  63. write_pack,
  64. unpack_object,
  65. compute_file_sha,
  66. PackStreamReader,
  67. DeltaChainIterator,
  68. )
  69. from dulwich.tests import (
  70. TestCase,
  71. )
  72. from utils import (
  73. make_object,
  74. build_pack,
  75. )
  76. pack1_sha = 'bc63ddad95e7321ee734ea11a7a62d314e0d7481'
  77. a_sha = '6f670c0fb53f9463760b7295fbb814e965fb20c8'
  78. tree_sha = 'b2a2766a2879c209ab1176e7e778b81ae422eeaa'
  79. commit_sha = 'f18faa16531ac570a3fdc8c7ca16682548dafd12'
  80. class PackTests(TestCase):
  81. """Base class for testing packs"""
  82. def setUp(self):
  83. super(PackTests, self).setUp()
  84. self.tempdir = tempfile.mkdtemp()
  85. self.addCleanup(shutil.rmtree, self.tempdir)
  86. datadir = os.path.abspath(os.path.join(os.path.dirname(__file__),
  87. 'data/packs'))
  88. def get_pack_index(self, sha):
  89. """Returns a PackIndex from the datadir with the given sha"""
  90. return load_pack_index(os.path.join(self.datadir, 'pack-%s.idx' % sha))
  91. def get_pack_data(self, sha):
  92. """Returns a PackData object from the datadir with the given sha"""
  93. return PackData(os.path.join(self.datadir, 'pack-%s.pack' % sha))
  94. def get_pack(self, sha):
  95. return Pack(os.path.join(self.datadir, 'pack-%s' % sha))
  96. def assertSucceeds(self, func, *args, **kwargs):
  97. try:
  98. func(*args, **kwargs)
  99. except ChecksumMismatch, e:
  100. self.fail(e)
  101. class PackIndexTests(PackTests):
  102. """Class that tests the index of packfiles"""
  103. def test_object_index(self):
  104. """Tests that the correct object offset is returned from the index."""
  105. p = self.get_pack_index(pack1_sha)
  106. self.assertRaises(KeyError, p.object_index, pack1_sha)
  107. self.assertEqual(p.object_index(a_sha), 178)
  108. self.assertEqual(p.object_index(tree_sha), 138)
  109. self.assertEqual(p.object_index(commit_sha), 12)
  110. def test_index_len(self):
  111. p = self.get_pack_index(pack1_sha)
  112. self.assertEqual(3, len(p))
  113. def test_get_stored_checksum(self):
  114. p = self.get_pack_index(pack1_sha)
  115. self.assertEqual('f2848e2ad16f329ae1c92e3b95e91888daa5bd01',
  116. sha_to_hex(p.get_stored_checksum()))
  117. self.assertEqual('721980e866af9a5f93ad674144e1459b8ba3e7b7',
  118. sha_to_hex(p.get_pack_checksum()))
  119. def test_index_check(self):
  120. p = self.get_pack_index(pack1_sha)
  121. self.assertSucceeds(p.check)
  122. def test_iterentries(self):
  123. p = self.get_pack_index(pack1_sha)
  124. entries = [(sha_to_hex(s), o, c) for s, o, c in p.iterentries()]
  125. self.assertEqual([
  126. ('6f670c0fb53f9463760b7295fbb814e965fb20c8', 178, None),
  127. ('b2a2766a2879c209ab1176e7e778b81ae422eeaa', 138, None),
  128. ('f18faa16531ac570a3fdc8c7ca16682548dafd12', 12, None)
  129. ], entries)
  130. def test_iter(self):
  131. p = self.get_pack_index(pack1_sha)
  132. self.assertEqual(set([tree_sha, commit_sha, a_sha]), set(p))
  133. class TestPackDeltas(TestCase):
  134. test_string1 = 'The answer was flailing in the wind'
  135. test_string2 = 'The answer was falling down the pipe'
  136. test_string3 = 'zzzzz'
  137. test_string_empty = ''
  138. test_string_big = 'Z' * 8192
  139. test_string_huge = 'Z' * 100000
  140. def _test_roundtrip(self, base, target):
  141. self.assertEqual(target,
  142. ''.join(apply_delta(base, create_delta(base, target))))
  143. def test_nochange(self):
  144. self._test_roundtrip(self.test_string1, self.test_string1)
  145. def test_change(self):
  146. self._test_roundtrip(self.test_string1, self.test_string2)
  147. def test_rewrite(self):
  148. self._test_roundtrip(self.test_string1, self.test_string3)
  149. def test_overflow(self):
  150. self._test_roundtrip(self.test_string_empty, self.test_string_big)
  151. def test_overflow_64k(self):
  152. self.skipTest("big strings don't work yet")
  153. self._test_roundtrip(self.test_string_huge, self.test_string_huge)
  154. class TestPackData(PackTests):
  155. """Tests getting the data from the packfile."""
  156. def test_create_pack(self):
  157. p = self.get_pack_data(pack1_sha)
  158. def test_from_file(self):
  159. path = os.path.join(self.datadir, 'pack-%s.pack' % pack1_sha)
  160. PackData.from_file(open(path), os.path.getsize(path))
  161. def test_pack_len(self):
  162. p = self.get_pack_data(pack1_sha)
  163. self.assertEqual(3, len(p))
  164. def test_index_check(self):
  165. p = self.get_pack_data(pack1_sha)
  166. self.assertSucceeds(p.check)
  167. def test_iterobjects(self):
  168. p = self.get_pack_data(pack1_sha)
  169. commit_data = ('tree b2a2766a2879c209ab1176e7e778b81ae422eeaa\n'
  170. 'author James Westby <jw+debian@jameswestby.net> '
  171. '1174945067 +0100\n'
  172. 'committer James Westby <jw+debian@jameswestby.net> '
  173. '1174945067 +0100\n'
  174. '\n'
  175. 'Test commit\n')
  176. blob_sha = '6f670c0fb53f9463760b7295fbb814e965fb20c8'
  177. tree_data = '100644 a\0%s' % hex_to_sha(blob_sha)
  178. actual = []
  179. for offset, type_num, chunks, crc32 in p.iterobjects():
  180. actual.append((offset, type_num, ''.join(chunks), crc32))
  181. self.assertEqual([
  182. (12, 1, commit_data, 3775879613L),
  183. (138, 2, tree_data, 912998690L),
  184. (178, 3, 'test 1\n', 1373561701L)
  185. ], actual)
  186. def test_iterentries(self):
  187. p = self.get_pack_data(pack1_sha)
  188. entries = set((sha_to_hex(s), o, c) for s, o, c in p.iterentries())
  189. self.assertEqual(set([
  190. ('6f670c0fb53f9463760b7295fbb814e965fb20c8', 178, 1373561701L),
  191. ('b2a2766a2879c209ab1176e7e778b81ae422eeaa', 138, 912998690L),
  192. ('f18faa16531ac570a3fdc8c7ca16682548dafd12', 12, 3775879613L),
  193. ]), entries)
  194. def test_create_index_v1(self):
  195. p = self.get_pack_data(pack1_sha)
  196. filename = os.path.join(self.tempdir, 'v1test.idx')
  197. p.create_index_v1(filename)
  198. idx1 = load_pack_index(filename)
  199. idx2 = self.get_pack_index(pack1_sha)
  200. self.assertEqual(idx1, idx2)
  201. def test_create_index_v2(self):
  202. p = self.get_pack_data(pack1_sha)
  203. filename = os.path.join(self.tempdir, 'v2test.idx')
  204. p.create_index_v2(filename)
  205. idx1 = load_pack_index(filename)
  206. idx2 = self.get_pack_index(pack1_sha)
  207. self.assertEqual(idx1, idx2)
  208. def test_compute_file_sha(self):
  209. f = StringIO('abcd1234wxyz')
  210. self.assertEqual(make_sha('abcd1234wxyz').hexdigest(),
  211. compute_file_sha(f).hexdigest())
  212. self.assertEqual(make_sha('abcd1234wxyz').hexdigest(),
  213. compute_file_sha(f, buffer_size=5).hexdigest())
  214. self.assertEqual(make_sha('abcd1234').hexdigest(),
  215. compute_file_sha(f, end_ofs=-4).hexdigest())
  216. self.assertEqual(make_sha('1234wxyz').hexdigest(),
  217. compute_file_sha(f, start_ofs=4).hexdigest())
  218. self.assertEqual(
  219. make_sha('1234').hexdigest(),
  220. compute_file_sha(f, start_ofs=4, end_ofs=-4).hexdigest())
  221. class TestPack(PackTests):
  222. def test_len(self):
  223. p = self.get_pack(pack1_sha)
  224. self.assertEqual(3, len(p))
  225. def test_contains(self):
  226. p = self.get_pack(pack1_sha)
  227. self.assertTrue(tree_sha in p)
  228. def test_get(self):
  229. p = self.get_pack(pack1_sha)
  230. self.assertEqual(type(p[tree_sha]), Tree)
  231. def test_iter(self):
  232. p = self.get_pack(pack1_sha)
  233. self.assertEqual(set([tree_sha, commit_sha, a_sha]), set(p))
  234. def test_iterobjects(self):
  235. p = self.get_pack(pack1_sha)
  236. expected = set([p[s] for s in [commit_sha, tree_sha, a_sha]])
  237. self.assertEqual(expected, set(list(p.iterobjects())))
  238. def test_pack_tuples(self):
  239. p = self.get_pack(pack1_sha)
  240. tuples = p.pack_tuples()
  241. expected = set([(p[s], None) for s in [commit_sha, tree_sha, a_sha]])
  242. self.assertEqual(expected, set(list(tuples)))
  243. self.assertEqual(expected, set(list(tuples)))
  244. self.assertEqual(3, len(tuples))
  245. def test_get_object_at(self):
  246. """Tests random access for non-delta objects"""
  247. p = self.get_pack(pack1_sha)
  248. obj = p[a_sha]
  249. self.assertEqual(obj.type_name, 'blob')
  250. self.assertEqual(obj.sha().hexdigest(), a_sha)
  251. obj = p[tree_sha]
  252. self.assertEqual(obj.type_name, 'tree')
  253. self.assertEqual(obj.sha().hexdigest(), tree_sha)
  254. obj = p[commit_sha]
  255. self.assertEqual(obj.type_name, 'commit')
  256. self.assertEqual(obj.sha().hexdigest(), commit_sha)
  257. def test_copy(self):
  258. origpack = self.get_pack(pack1_sha)
  259. try:
  260. self.assertSucceeds(origpack.index.check)
  261. basename = os.path.join(self.tempdir, 'Elch')
  262. write_pack(basename, origpack.pack_tuples())
  263. newpack = Pack(basename)
  264. try:
  265. self.assertEqual(origpack, newpack)
  266. self.assertSucceeds(newpack.index.check)
  267. self.assertEqual(origpack.name(), newpack.name())
  268. self.assertEqual(origpack.index.get_pack_checksum(),
  269. newpack.index.get_pack_checksum())
  270. wrong_version = origpack.index.version != newpack.index.version
  271. orig_checksum = origpack.index.get_stored_checksum()
  272. new_checksum = newpack.index.get_stored_checksum()
  273. self.assertTrue(wrong_version or orig_checksum == new_checksum)
  274. finally:
  275. newpack.close()
  276. finally:
  277. origpack.close()
  278. def test_commit_obj(self):
  279. p = self.get_pack(pack1_sha)
  280. commit = p[commit_sha]
  281. self.assertEqual('James Westby <jw+debian@jameswestby.net>',
  282. commit.author)
  283. self.assertEqual([], commit.parents)
  284. def _copy_pack(self, origpack):
  285. basename = os.path.join(self.tempdir, 'somepack')
  286. write_pack(basename, origpack.pack_tuples())
  287. return Pack(basename)
  288. def test_keep_no_message(self):
  289. p = self.get_pack(pack1_sha)
  290. p = self._copy_pack(p)
  291. keepfile_name = p.keep()
  292. # file should exist
  293. self.assertTrue(os.path.exists(keepfile_name))
  294. f = open(keepfile_name, 'r')
  295. try:
  296. buf = f.read()
  297. self.assertEqual('', buf)
  298. finally:
  299. f.close()
  300. def test_keep_message(self):
  301. p = self.get_pack(pack1_sha)
  302. p = self._copy_pack(p)
  303. msg = 'some message'
  304. keepfile_name = p.keep(msg)
  305. # file should exist
  306. self.assertTrue(os.path.exists(keepfile_name))
  307. # and contain the right message, with a linefeed
  308. f = open(keepfile_name, 'r')
  309. try:
  310. buf = f.read()
  311. self.assertEqual(msg + '\n', buf)
  312. finally:
  313. f.close()
  314. def test_name(self):
  315. p = self.get_pack(pack1_sha)
  316. self.assertEqual(pack1_sha, p.name())
  317. def test_length_mismatch(self):
  318. data = self.get_pack_data(pack1_sha)
  319. index = self.get_pack_index(pack1_sha)
  320. Pack.from_objects(data, index).check_length_and_checksum()
  321. data._file.seek(12)
  322. bad_file = StringIO()
  323. write_pack_header(bad_file, 9999)
  324. bad_file.write(data._file.read())
  325. bad_file = StringIO(bad_file.getvalue())
  326. bad_data = PackData('', file=bad_file)
  327. bad_pack = Pack.from_lazy_objects(lambda: bad_data, lambda: index)
  328. self.assertRaises(AssertionError, lambda: bad_pack.data)
  329. self.assertRaises(AssertionError,
  330. lambda: bad_pack.check_length_and_checksum())
  331. def test_checksum_mismatch(self):
  332. data = self.get_pack_data(pack1_sha)
  333. index = self.get_pack_index(pack1_sha)
  334. Pack.from_objects(data, index).check_length_and_checksum()
  335. data._file.seek(0)
  336. bad_file = StringIO(data._file.read()[:-20] + ('\xff' * 20))
  337. bad_data = PackData('', file=bad_file)
  338. bad_pack = Pack.from_lazy_objects(lambda: bad_data, lambda: index)
  339. self.assertRaises(ChecksumMismatch, lambda: bad_pack.data)
  340. self.assertRaises(ChecksumMismatch, lambda:
  341. bad_pack.check_length_and_checksum())
  342. def test_iterobjects(self):
  343. p = self.get_pack(pack1_sha)
  344. objs = dict((o.id, o) for o in p.iterobjects())
  345. self.assertEqual(3, len(objs))
  346. self.assertEqual(sorted(objs), sorted(p.index))
  347. self.assertTrue(isinstance(objs[a_sha], Blob))
  348. self.assertTrue(isinstance(objs[tree_sha], Tree))
  349. self.assertTrue(isinstance(objs[commit_sha], Commit))
  350. class WritePackTests(TestCase):
  351. def test_write_pack_header(self):
  352. f = StringIO()
  353. write_pack_header(f, 42)
  354. self.assertEqual('PACK\x00\x00\x00\x02\x00\x00\x00*',
  355. f.getvalue())
  356. def test_write_pack_object(self):
  357. f = StringIO()
  358. f.write('header')
  359. offset = f.tell()
  360. crc32 = write_pack_object(f, Blob.type_num, 'blob')
  361. self.assertEqual(crc32, zlib.crc32(f.getvalue()[6:]) & 0xffffffff)
  362. f.write('x') # unpack_object needs extra trailing data.
  363. f.seek(offset)
  364. comp_len = len(f.getvalue()) - offset - 1
  365. unpacked, unused = unpack_object(f.read, compute_crc32=True)
  366. self.assertEqual(Blob.type_num, unpacked.pack_type_num)
  367. self.assertEqual(Blob.type_num, unpacked.obj_type_num)
  368. self.assertEqual(['blob'], unpacked.decomp_chunks)
  369. self.assertEqual(crc32, unpacked.crc32)
  370. self.assertEqual('x', unused)
  371. def test_write_pack_object_sha(self):
  372. f = StringIO()
  373. f.write('header')
  374. offset = f.tell()
  375. sha_a = make_sha('foo')
  376. sha_b = sha_a.copy()
  377. write_pack_object(f, Blob.type_num, 'blob', sha=sha_a)
  378. self.assertNotEqual(sha_a.digest(), sha_b.digest())
  379. sha_b.update(f.getvalue()[offset:])
  380. self.assertEqual(sha_a.digest(), sha_b.digest())
  381. pack_checksum = hex_to_sha('721980e866af9a5f93ad674144e1459b8ba3e7b7')
  382. class BaseTestPackIndexWriting(object):
  383. def assertSucceeds(self, func, *args, **kwargs):
  384. try:
  385. func(*args, **kwargs)
  386. except ChecksumMismatch, e:
  387. self.fail(e)
  388. def index(self, filename, entries, pack_checksum):
  389. raise NotImplementedError(self.index)
  390. def test_empty(self):
  391. idx = self.index('empty.idx', [], pack_checksum)
  392. self.assertEqual(idx.get_pack_checksum(), pack_checksum)
  393. self.assertEqual(0, len(idx))
  394. def test_large(self):
  395. entry1_sha = hex_to_sha('4e6388232ec39792661e2e75db8fb117fc869ce6')
  396. entry2_sha = hex_to_sha('e98f071751bd77f59967bfa671cd2caebdccc9a2')
  397. entries = [(entry1_sha, 0xf2972d0830529b87, 24),
  398. (entry2_sha, (~0xf2972d0830529b87)&(2**64-1), 92)]
  399. if not self._supports_large:
  400. self.assertRaises(TypeError, self.index, 'single.idx',
  401. entries, pack_checksum)
  402. return
  403. idx = self.index('single.idx', entries, pack_checksum)
  404. self.assertEqual(idx.get_pack_checksum(), pack_checksum)
  405. self.assertEqual(2, len(idx))
  406. actual_entries = list(idx.iterentries())
  407. self.assertEqual(len(entries), len(actual_entries))
  408. for mine, actual in zip(entries, actual_entries):
  409. my_sha, my_offset, my_crc = mine
  410. actual_sha, actual_offset, actual_crc = actual
  411. self.assertEqual(my_sha, actual_sha)
  412. self.assertEqual(my_offset, actual_offset)
  413. if self._has_crc32_checksum:
  414. self.assertEqual(my_crc, actual_crc)
  415. else:
  416. self.assertTrue(actual_crc is None)
  417. def test_single(self):
  418. entry_sha = hex_to_sha('6f670c0fb53f9463760b7295fbb814e965fb20c8')
  419. my_entries = [(entry_sha, 178, 42)]
  420. idx = self.index('single.idx', my_entries, pack_checksum)
  421. self.assertEqual(idx.get_pack_checksum(), pack_checksum)
  422. self.assertEqual(1, len(idx))
  423. actual_entries = list(idx.iterentries())
  424. self.assertEqual(len(my_entries), len(actual_entries))
  425. for mine, actual in zip(my_entries, actual_entries):
  426. my_sha, my_offset, my_crc = mine
  427. actual_sha, actual_offset, actual_crc = actual
  428. self.assertEqual(my_sha, actual_sha)
  429. self.assertEqual(my_offset, actual_offset)
  430. if self._has_crc32_checksum:
  431. self.assertEqual(my_crc, actual_crc)
  432. else:
  433. self.assertTrue(actual_crc is None)
  434. class BaseTestFilePackIndexWriting(BaseTestPackIndexWriting):
  435. def setUp(self):
  436. self.tempdir = tempfile.mkdtemp()
  437. def tearDown(self):
  438. shutil.rmtree(self.tempdir)
  439. def index(self, filename, entries, pack_checksum):
  440. path = os.path.join(self.tempdir, filename)
  441. self.writeIndex(path, entries, pack_checksum)
  442. idx = load_pack_index(path)
  443. self.assertSucceeds(idx.check)
  444. self.assertEqual(idx.version, self._expected_version)
  445. return idx
  446. def writeIndex(self, filename, entries, pack_checksum):
  447. # FIXME: Write to StringIO instead rather than hitting disk ?
  448. f = GitFile(filename, "wb")
  449. try:
  450. self._write_fn(f, entries, pack_checksum)
  451. finally:
  452. f.close()
  453. class TestMemoryIndexWriting(TestCase, BaseTestPackIndexWriting):
  454. def setUp(self):
  455. TestCase.setUp(self)
  456. self._has_crc32_checksum = True
  457. self._supports_large = True
  458. def index(self, filename, entries, pack_checksum):
  459. return MemoryPackIndex(entries, pack_checksum)
  460. def tearDown(self):
  461. TestCase.tearDown(self)
  462. class TestPackIndexWritingv1(TestCase, BaseTestFilePackIndexWriting):
  463. def setUp(self):
  464. TestCase.setUp(self)
  465. BaseTestFilePackIndexWriting.setUp(self)
  466. self._has_crc32_checksum = False
  467. self._expected_version = 1
  468. self._supports_large = False
  469. self._write_fn = write_pack_index_v1
  470. def tearDown(self):
  471. TestCase.tearDown(self)
  472. BaseTestFilePackIndexWriting.tearDown(self)
  473. class TestPackIndexWritingv2(TestCase, BaseTestFilePackIndexWriting):
  474. def setUp(self):
  475. TestCase.setUp(self)
  476. BaseTestFilePackIndexWriting.setUp(self)
  477. self._has_crc32_checksum = True
  478. self._supports_large = True
  479. self._expected_version = 2
  480. self._write_fn = write_pack_index_v2
  481. def tearDown(self):
  482. TestCase.tearDown(self)
  483. BaseTestFilePackIndexWriting.tearDown(self)
  484. class ReadZlibTests(TestCase):
  485. decomp = (
  486. 'tree 4ada885c9196b6b6fa08744b5862bf92896fc002\n'
  487. 'parent None\n'
  488. 'author Jelmer Vernooij <jelmer@samba.org> 1228980214 +0000\n'
  489. 'committer Jelmer Vernooij <jelmer@samba.org> 1228980214 +0000\n'
  490. '\n'
  491. "Provide replacement for mmap()'s offset argument.")
  492. comp = zlib.compress(decomp)
  493. extra = 'nextobject'
  494. def setUp(self):
  495. super(ReadZlibTests, self).setUp()
  496. self.read = StringIO(self.comp + self.extra).read
  497. self.unpacked = UnpackedObject(Tree.type_num, None, len(self.decomp), 0)
  498. def test_decompress_size(self):
  499. good_decomp_len = len(self.decomp)
  500. self.unpacked.decomp_len = -1
  501. self.assertRaises(ValueError, read_zlib_chunks, self.read,
  502. self.unpacked)
  503. self.unpacked.decomp_len = good_decomp_len - 1
  504. self.assertRaises(zlib.error, read_zlib_chunks, self.read,
  505. self.unpacked)
  506. self.unpacked.decomp_len = good_decomp_len + 1
  507. self.assertRaises(zlib.error, read_zlib_chunks, self.read,
  508. self.unpacked)
  509. def test_decompress_truncated(self):
  510. read = StringIO(self.comp[:10]).read
  511. self.assertRaises(zlib.error, read_zlib_chunks, read, self.unpacked)
  512. read = StringIO(self.comp).read
  513. self.assertRaises(zlib.error, read_zlib_chunks, read, self.unpacked)
  514. def test_decompress_empty(self):
  515. unpacked = UnpackedObject(Tree.type_num, None, 0, None)
  516. comp = zlib.compress('')
  517. read = StringIO(comp + self.extra).read
  518. unused = read_zlib_chunks(read, unpacked)
  519. self.assertEqual('', ''.join(unpacked.decomp_chunks))
  520. self.assertNotEquals('', unused)
  521. self.assertEqual(self.extra, unused + read())
  522. def test_decompress_no_crc32(self):
  523. self.unpacked.crc32 = None
  524. read_zlib_chunks(self.read, self.unpacked)
  525. self.assertEqual(None, self.unpacked.crc32)
  526. def _do_decompress_test(self, buffer_size, **kwargs):
  527. unused = read_zlib_chunks(self.read, self.unpacked,
  528. buffer_size=buffer_size, **kwargs)
  529. self.assertEqual(self.decomp, ''.join(self.unpacked.decomp_chunks))
  530. self.assertEqual(zlib.crc32(self.comp), self.unpacked.crc32)
  531. self.assertNotEquals('', unused)
  532. self.assertEqual(self.extra, unused + self.read())
  533. def test_simple_decompress(self):
  534. self._do_decompress_test(4096)
  535. self.assertEqual(None, self.unpacked.comp_chunks)
  536. # These buffer sizes are not intended to be realistic, but rather simulate
  537. # larger buffer sizes that may end at various places.
  538. def test_decompress_buffer_size_1(self):
  539. self._do_decompress_test(1)
  540. def test_decompress_buffer_size_2(self):
  541. self._do_decompress_test(2)
  542. def test_decompress_buffer_size_3(self):
  543. self._do_decompress_test(3)
  544. def test_decompress_buffer_size_4(self):
  545. self._do_decompress_test(4)
  546. def test_decompress_include_comp(self):
  547. self._do_decompress_test(4096, include_comp=True)
  548. self.assertEqual(self.comp, ''.join(self.unpacked.comp_chunks))
  549. class DeltifyTests(TestCase):
  550. def test_empty(self):
  551. self.assertEqual([], list(deltify_pack_objects([])))
  552. def test_single(self):
  553. b = Blob.from_string("foo")
  554. self.assertEqual(
  555. [(b.type_num, b.sha().digest(), None, b.as_raw_string())],
  556. list(deltify_pack_objects([(b, "")])))
  557. def test_simple_delta(self):
  558. b1 = Blob.from_string("a" * 101)
  559. b2 = Blob.from_string("a" * 100)
  560. delta = create_delta(b1.as_raw_string(), b2.as_raw_string())
  561. self.assertEqual([
  562. (b1.type_num, b1.sha().digest(), None, b1.as_raw_string()),
  563. (b2.type_num, b2.sha().digest(), b1.sha().digest(), delta)
  564. ],
  565. list(deltify_pack_objects([(b1, ""), (b2, "")])))
  566. class TestPackStreamReader(TestCase):
  567. def test_read_objects_emtpy(self):
  568. f = StringIO()
  569. build_pack(f, [])
  570. reader = PackStreamReader(f.read)
  571. self.assertEqual(0, len(list(reader.read_objects())))
  572. def test_read_objects(self):
  573. f = StringIO()
  574. entries = build_pack(f, [
  575. (Blob.type_num, 'blob'),
  576. (OFS_DELTA, (0, 'blob1')),
  577. ])
  578. reader = PackStreamReader(f.read)
  579. objects = list(reader.read_objects(compute_crc32=True))
  580. self.assertEqual(2, len(objects))
  581. unpacked_blob, unpacked_delta = objects
  582. self.assertEqual(entries[0][0], unpacked_blob.offset)
  583. self.assertEqual(Blob.type_num, unpacked_blob.pack_type_num)
  584. self.assertEqual(Blob.type_num, unpacked_blob.obj_type_num)
  585. self.assertEqual(None, unpacked_blob.delta_base)
  586. self.assertEqual('blob', ''.join(unpacked_blob.decomp_chunks))
  587. self.assertEqual(entries[0][4], unpacked_blob.crc32)
  588. self.assertEqual(entries[1][0], unpacked_delta.offset)
  589. self.assertEqual(OFS_DELTA, unpacked_delta.pack_type_num)
  590. self.assertEqual(None, unpacked_delta.obj_type_num)
  591. self.assertEqual(unpacked_delta.offset - unpacked_blob.offset,
  592. unpacked_delta.delta_base)
  593. delta = create_delta('blob', 'blob1')
  594. self.assertEqual(delta, ''.join(unpacked_delta.decomp_chunks))
  595. self.assertEqual(entries[1][4], unpacked_delta.crc32)
  596. def test_read_objects_buffered(self):
  597. f = StringIO()
  598. build_pack(f, [
  599. (Blob.type_num, 'blob'),
  600. (OFS_DELTA, (0, 'blob1')),
  601. ])
  602. reader = PackStreamReader(f.read, zlib_bufsize=4)
  603. self.assertEqual(2, len(list(reader.read_objects())))
  604. def test_read_objects_empty(self):
  605. reader = PackStreamReader(StringIO().read)
  606. self.assertEqual([], list(reader.read_objects()))
  607. class TestPackIterator(DeltaChainIterator):
  608. _compute_crc32 = True
  609. def __init__(self, *args, **kwargs):
  610. super(TestPackIterator, self).__init__(*args, **kwargs)
  611. self._unpacked_offsets = set()
  612. def _result(self, unpacked):
  613. """Return entries in the same format as build_pack."""
  614. return (unpacked.offset, unpacked.obj_type_num,
  615. ''.join(unpacked.obj_chunks), unpacked.sha(), unpacked.crc32)
  616. def _resolve_object(self, offset, pack_type_num, base_chunks):
  617. assert offset not in self._unpacked_offsets, (
  618. 'Attempted to re-inflate offset %i' % offset)
  619. self._unpacked_offsets.add(offset)
  620. return super(TestPackIterator, self)._resolve_object(
  621. offset, pack_type_num, base_chunks)
  622. class DeltaChainIteratorTests(TestCase):
  623. def setUp(self):
  624. super(DeltaChainIteratorTests, self).setUp()
  625. self.store = MemoryObjectStore()
  626. self.fetched = set()
  627. def store_blobs(self, blobs_data):
  628. blobs = []
  629. for data in blobs_data:
  630. blob = make_object(Blob, data=data)
  631. blobs.append(blob)
  632. self.store.add_object(blob)
  633. return blobs
  634. def get_raw_no_repeat(self, bin_sha):
  635. """Wrapper around store.get_raw that doesn't allow repeat lookups."""
  636. hex_sha = sha_to_hex(bin_sha)
  637. self.assertFalse(hex_sha in self.fetched,
  638. 'Attempted to re-fetch object %s' % hex_sha)
  639. self.fetched.add(hex_sha)
  640. return self.store.get_raw(hex_sha)
  641. def make_pack_iter(self, f, thin=None):
  642. if thin is None:
  643. thin = bool(list(self.store))
  644. resolve_ext_ref = thin and self.get_raw_no_repeat or None
  645. data = PackData('test.pack', file=f)
  646. return TestPackIterator.for_pack_data(
  647. data, resolve_ext_ref=resolve_ext_ref)
  648. def assertEntriesMatch(self, expected_indexes, entries, pack_iter):
  649. expected = [entries[i] for i in expected_indexes]
  650. self.assertEqual(expected, list(pack_iter._walk_all_chains()))
  651. def test_no_deltas(self):
  652. f = StringIO()
  653. entries = build_pack(f, [
  654. (Commit.type_num, 'commit'),
  655. (Blob.type_num, 'blob'),
  656. (Tree.type_num, 'tree'),
  657. ])
  658. self.assertEntriesMatch([0, 1, 2], entries, self.make_pack_iter(f))
  659. def test_ofs_deltas(self):
  660. f = StringIO()
  661. entries = build_pack(f, [
  662. (Blob.type_num, 'blob'),
  663. (OFS_DELTA, (0, 'blob1')),
  664. (OFS_DELTA, (0, 'blob2')),
  665. ])
  666. self.assertEntriesMatch([0, 1, 2], entries, self.make_pack_iter(f))
  667. def test_ofs_deltas_chain(self):
  668. f = StringIO()
  669. entries = build_pack(f, [
  670. (Blob.type_num, 'blob'),
  671. (OFS_DELTA, (0, 'blob1')),
  672. (OFS_DELTA, (1, 'blob2')),
  673. ])
  674. self.assertEntriesMatch([0, 1, 2], entries, self.make_pack_iter(f))
  675. def test_ref_deltas(self):
  676. f = StringIO()
  677. entries = build_pack(f, [
  678. (REF_DELTA, (1, 'blob1')),
  679. (Blob.type_num, ('blob')),
  680. (REF_DELTA, (1, 'blob2')),
  681. ])
  682. self.assertEntriesMatch([1, 0, 2], entries, self.make_pack_iter(f))
  683. def test_ref_deltas_chain(self):
  684. f = StringIO()
  685. entries = build_pack(f, [
  686. (REF_DELTA, (2, 'blob1')),
  687. (Blob.type_num, ('blob')),
  688. (REF_DELTA, (1, 'blob2')),
  689. ])
  690. self.assertEntriesMatch([1, 2, 0], entries, self.make_pack_iter(f))
  691. def test_ofs_and_ref_deltas(self):
  692. # Deltas pending on this offset are popped before deltas depending on
  693. # this ref.
  694. f = StringIO()
  695. entries = build_pack(f, [
  696. (REF_DELTA, (1, 'blob1')),
  697. (Blob.type_num, ('blob')),
  698. (OFS_DELTA, (1, 'blob2')),
  699. ])
  700. self.assertEntriesMatch([1, 2, 0], entries, self.make_pack_iter(f))
  701. def test_mixed_chain(self):
  702. f = StringIO()
  703. entries = build_pack(f, [
  704. (Blob.type_num, 'blob'),
  705. (REF_DELTA, (2, 'blob2')),
  706. (OFS_DELTA, (0, 'blob1')),
  707. (OFS_DELTA, (1, 'blob3')),
  708. (OFS_DELTA, (0, 'bob')),
  709. ])
  710. self.assertEntriesMatch([0, 2, 1, 3, 4], entries,
  711. self.make_pack_iter(f))
  712. def test_long_chain(self):
  713. n = 100
  714. objects_spec = [(Blob.type_num, 'blob')]
  715. for i in xrange(n):
  716. objects_spec.append((OFS_DELTA, (i, 'blob%i' % i)))
  717. f = StringIO()
  718. entries = build_pack(f, objects_spec)
  719. self.assertEntriesMatch(xrange(n + 1), entries, self.make_pack_iter(f))
  720. def test_branchy_chain(self):
  721. n = 100
  722. objects_spec = [(Blob.type_num, 'blob')]
  723. for i in xrange(n):
  724. objects_spec.append((OFS_DELTA, (0, 'blob%i' % i)))
  725. f = StringIO()
  726. entries = build_pack(f, objects_spec)
  727. self.assertEntriesMatch(xrange(n + 1), entries, self.make_pack_iter(f))
  728. def test_ext_ref(self):
  729. blob, = self.store_blobs(['blob'])
  730. f = StringIO()
  731. entries = build_pack(f, [(REF_DELTA, (blob.id, 'blob1'))],
  732. store=self.store)
  733. pack_iter = self.make_pack_iter(f)
  734. self.assertEntriesMatch([0], entries, pack_iter)
  735. self.assertEqual([hex_to_sha(blob.id)], pack_iter.ext_refs())
  736. def test_ext_ref_chain(self):
  737. blob, = self.store_blobs(['blob'])
  738. f = StringIO()
  739. entries = build_pack(f, [
  740. (REF_DELTA, (1, 'blob2')),
  741. (REF_DELTA, (blob.id, 'blob1')),
  742. ], store=self.store)
  743. pack_iter = self.make_pack_iter(f)
  744. self.assertEntriesMatch([1, 0], entries, pack_iter)
  745. self.assertEqual([hex_to_sha(blob.id)], pack_iter.ext_refs())
  746. def test_ext_ref_multiple_times(self):
  747. blob, = self.store_blobs(['blob'])
  748. f = StringIO()
  749. entries = build_pack(f, [
  750. (REF_DELTA, (blob.id, 'blob1')),
  751. (REF_DELTA, (blob.id, 'blob2')),
  752. ], store=self.store)
  753. pack_iter = self.make_pack_iter(f)
  754. self.assertEntriesMatch([0, 1], entries, pack_iter)
  755. self.assertEqual([hex_to_sha(blob.id)], pack_iter.ext_refs())
  756. def test_multiple_ext_refs(self):
  757. b1, b2 = self.store_blobs(['foo', 'bar'])
  758. f = StringIO()
  759. entries = build_pack(f, [
  760. (REF_DELTA, (b1.id, 'foo1')),
  761. (REF_DELTA, (b2.id, 'bar2')),
  762. ], store=self.store)
  763. pack_iter = self.make_pack_iter(f)
  764. self.assertEntriesMatch([0, 1], entries, pack_iter)
  765. self.assertEqual([hex_to_sha(b1.id), hex_to_sha(b2.id)],
  766. pack_iter.ext_refs())
  767. def test_bad_ext_ref_non_thin_pack(self):
  768. blob, = self.store_blobs(['blob'])
  769. f = StringIO()
  770. entries = build_pack(f, [(REF_DELTA, (blob.id, 'blob1'))],
  771. store=self.store)
  772. pack_iter = self.make_pack_iter(f, thin=False)
  773. try:
  774. list(pack_iter._walk_all_chains())
  775. self.fail()
  776. except KeyError, e:
  777. self.assertEqual(([blob.id],), e.args)
  778. def test_bad_ext_ref_thin_pack(self):
  779. b1, b2, b3 = self.store_blobs(['foo', 'bar', 'baz'])
  780. f = StringIO()
  781. entries = build_pack(f, [
  782. (REF_DELTA, (1, 'foo99')),
  783. (REF_DELTA, (b1.id, 'foo1')),
  784. (REF_DELTA, (b2.id, 'bar2')),
  785. (REF_DELTA, (b3.id, 'baz3')),
  786. ], store=self.store)
  787. del self.store[b2.id]
  788. del self.store[b3.id]
  789. pack_iter = self.make_pack_iter(f)
  790. try:
  791. list(pack_iter._walk_all_chains())
  792. self.fail()
  793. except KeyError, e:
  794. self.assertEqual((sorted([b2.id, b3.id]),), e.args)