test_object_store.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. # test_object_store.py -- tests for object_store.py
  2. # Copyright (C) 2008 Jelmer Vernooij <jelmer@jelmer.uk>
  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. """Tests for the object store interface."""
  21. import os
  22. import shutil
  23. import stat
  24. import sys
  25. import tempfile
  26. from contextlib import closing
  27. from io import BytesIO
  28. from dulwich.errors import NotTreeError
  29. from dulwich.index import commit_tree
  30. from dulwich.object_store import (
  31. DiskObjectStore,
  32. MemoryObjectStore,
  33. ObjectStoreGraphWalker,
  34. OverlayObjectStore,
  35. commit_tree_changes,
  36. read_packs_file,
  37. tree_lookup_path,
  38. )
  39. from dulwich.objects import (
  40. S_IFGITLINK,
  41. Blob,
  42. EmptyFileException,
  43. SubmoduleEncountered,
  44. Tree,
  45. TreeEntry,
  46. sha_to_hex,
  47. )
  48. from dulwich.pack import REF_DELTA, write_pack_objects
  49. from dulwich.tests.test_object_store import ObjectStoreTests, PackBasedObjectStoreTests
  50. from dulwich.tests.utils import build_pack, make_object
  51. from . import TestCase
  52. testobject = make_object(Blob, data=b"yummy data")
  53. class OverlayObjectStoreTests(ObjectStoreTests, TestCase):
  54. def setUp(self):
  55. TestCase.setUp(self)
  56. self.bases = [MemoryObjectStore(), MemoryObjectStore()]
  57. self.store = OverlayObjectStore(self.bases, self.bases[0])
  58. class MemoryObjectStoreTests(ObjectStoreTests, TestCase):
  59. def setUp(self):
  60. TestCase.setUp(self)
  61. self.store = MemoryObjectStore()
  62. def test_add_pack(self):
  63. o = MemoryObjectStore()
  64. f, commit, abort = o.add_pack()
  65. try:
  66. b = make_object(Blob, data=b"more yummy data")
  67. write_pack_objects(f.write, [(b, None)])
  68. except BaseException:
  69. abort()
  70. raise
  71. else:
  72. commit()
  73. def test_add_pack_emtpy(self):
  74. o = MemoryObjectStore()
  75. f, commit, abort = o.add_pack()
  76. commit()
  77. def test_add_thin_pack(self):
  78. o = MemoryObjectStore()
  79. blob = make_object(Blob, data=b"yummy data")
  80. o.add_object(blob)
  81. f = BytesIO()
  82. entries = build_pack(
  83. f,
  84. [
  85. (REF_DELTA, (blob.id, b"more yummy data")),
  86. ],
  87. store=o,
  88. )
  89. o.add_thin_pack(f.read, None)
  90. packed_blob_sha = sha_to_hex(entries[0][3])
  91. self.assertEqual(
  92. (Blob.type_num, b"more yummy data"), o.get_raw(packed_blob_sha)
  93. )
  94. def test_add_thin_pack_empty(self):
  95. o = MemoryObjectStore()
  96. f = BytesIO()
  97. entries = build_pack(f, [], store=o)
  98. self.assertEqual([], entries)
  99. o.add_thin_pack(f.read, None)
  100. class DiskObjectStoreTests(PackBasedObjectStoreTests, TestCase):
  101. def setUp(self):
  102. TestCase.setUp(self)
  103. self.store_dir = tempfile.mkdtemp()
  104. self.addCleanup(shutil.rmtree, self.store_dir)
  105. self.store = DiskObjectStore.init(self.store_dir)
  106. def tearDown(self):
  107. TestCase.tearDown(self)
  108. PackBasedObjectStoreTests.tearDown(self)
  109. def test_loose_compression_level(self):
  110. alternate_dir = tempfile.mkdtemp()
  111. self.addCleanup(shutil.rmtree, alternate_dir)
  112. alternate_store = DiskObjectStore(alternate_dir, loose_compression_level=6)
  113. b2 = make_object(Blob, data=b"yummy data")
  114. alternate_store.add_object(b2)
  115. def test_alternates(self):
  116. alternate_dir = tempfile.mkdtemp()
  117. self.addCleanup(shutil.rmtree, alternate_dir)
  118. alternate_store = DiskObjectStore(alternate_dir)
  119. b2 = make_object(Blob, data=b"yummy data")
  120. alternate_store.add_object(b2)
  121. store = DiskObjectStore(self.store_dir)
  122. self.assertRaises(KeyError, store.__getitem__, b2.id)
  123. store.add_alternate_path(alternate_dir)
  124. self.assertIn(b2.id, store)
  125. self.assertEqual(b2, store[b2.id])
  126. def test_read_alternate_paths(self):
  127. store = DiskObjectStore(self.store_dir)
  128. abs_path = os.path.abspath(os.path.normpath("/abspath"))
  129. # ensures in particular existence of the alternates file
  130. store.add_alternate_path(abs_path)
  131. self.assertEqual(set(store._read_alternate_paths()), {abs_path})
  132. store.add_alternate_path("relative-path")
  133. self.assertIn(
  134. os.path.join(store.path, "relative-path"),
  135. set(store._read_alternate_paths()),
  136. )
  137. # arguably, add_alternate_path() could strip comments.
  138. # Meanwhile it's more convenient to use it than to import INFODIR
  139. store.add_alternate_path("# comment")
  140. for alt_path in store._read_alternate_paths():
  141. self.assertNotIn("#", alt_path)
  142. def test_file_modes(self):
  143. self.store.add_object(testobject)
  144. path = self.store._get_shafile_path(testobject.id)
  145. mode = os.stat(path).st_mode
  146. packmode = "0o100444" if sys.platform != "win32" else "0o100666"
  147. self.assertEqual(oct(mode), packmode)
  148. def test_corrupted_object_raise_exception(self):
  149. """Corrupted sha1 disk file should raise specific exception."""
  150. self.store.add_object(testobject)
  151. self.assertEqual(
  152. (Blob.type_num, b"yummy data"), self.store.get_raw(testobject.id)
  153. )
  154. self.assertTrue(self.store.contains_loose(testobject.id))
  155. self.assertIsNotNone(self.store._get_loose_object(testobject.id))
  156. path = self.store._get_shafile_path(testobject.id)
  157. old_mode = os.stat(path).st_mode
  158. os.chmod(path, 0o600)
  159. with open(path, "wb") as f: # corrupt the file
  160. f.write(b"")
  161. os.chmod(path, old_mode)
  162. expected_error_msg = "Corrupted empty file detected"
  163. try:
  164. self.store.contains_loose(testobject.id)
  165. except EmptyFileException as e:
  166. self.assertEqual(str(e), expected_error_msg)
  167. try:
  168. self.store._get_loose_object(testobject.id)
  169. except EmptyFileException as e:
  170. self.assertEqual(str(e), expected_error_msg)
  171. # this does not change iteration on loose objects though
  172. self.assertEqual([testobject.id], list(self.store._iter_loose_objects()))
  173. def test_tempfile_in_loose_store(self):
  174. self.store.add_object(testobject)
  175. self.assertEqual([testobject.id], list(self.store._iter_loose_objects()))
  176. # add temporary files to the loose store
  177. for i in range(256):
  178. dirname = os.path.join(self.store_dir, f"{i:02x}")
  179. if not os.path.isdir(dirname):
  180. os.makedirs(dirname)
  181. fd, n = tempfile.mkstemp(prefix="tmp_obj_", dir=dirname)
  182. os.close(fd)
  183. self.assertEqual([testobject.id], list(self.store._iter_loose_objects()))
  184. def test_add_alternate_path(self):
  185. store = DiskObjectStore(self.store_dir)
  186. self.assertEqual([], list(store._read_alternate_paths()))
  187. store.add_alternate_path(os.path.abspath("/foo/path"))
  188. self.assertEqual(
  189. [os.path.abspath("/foo/path")], list(store._read_alternate_paths())
  190. )
  191. if sys.platform == "win32":
  192. store.add_alternate_path("D:\\bar\\path")
  193. else:
  194. store.add_alternate_path("/bar/path")
  195. if sys.platform == "win32":
  196. self.assertEqual(
  197. [os.path.abspath("/foo/path"), "D:\\bar\\path"],
  198. list(store._read_alternate_paths()),
  199. )
  200. else:
  201. self.assertEqual(
  202. [os.path.abspath("/foo/path"), "/bar/path"],
  203. list(store._read_alternate_paths()),
  204. )
  205. def test_rel_alternative_path(self):
  206. alternate_dir = tempfile.mkdtemp()
  207. self.addCleanup(shutil.rmtree, alternate_dir)
  208. alternate_store = DiskObjectStore(alternate_dir)
  209. b2 = make_object(Blob, data=b"yummy data")
  210. alternate_store.add_object(b2)
  211. store = DiskObjectStore(self.store_dir)
  212. self.assertRaises(KeyError, store.__getitem__, b2.id)
  213. store.add_alternate_path(os.path.relpath(alternate_dir, self.store_dir))
  214. self.assertEqual(list(alternate_store), list(store.alternates[0]))
  215. self.assertIn(b2.id, store)
  216. self.assertEqual(b2, store[b2.id])
  217. def test_pack_dir(self):
  218. o = DiskObjectStore(self.store_dir)
  219. self.assertEqual(os.path.join(self.store_dir, "pack"), o.pack_dir)
  220. def test_add_pack(self):
  221. o = DiskObjectStore(self.store_dir)
  222. self.addCleanup(o.close)
  223. f, commit, abort = o.add_pack()
  224. try:
  225. b = make_object(Blob, data=b"more yummy data")
  226. write_pack_objects(f.write, [(b, None)])
  227. except BaseException:
  228. abort()
  229. raise
  230. else:
  231. commit()
  232. def test_add_thin_pack(self):
  233. o = DiskObjectStore(self.store_dir)
  234. try:
  235. blob = make_object(Blob, data=b"yummy data")
  236. o.add_object(blob)
  237. f = BytesIO()
  238. entries = build_pack(
  239. f,
  240. [
  241. (REF_DELTA, (blob.id, b"more yummy data")),
  242. ],
  243. store=o,
  244. )
  245. with o.add_thin_pack(f.read, None) as pack:
  246. packed_blob_sha = sha_to_hex(entries[0][3])
  247. pack.check_length_and_checksum()
  248. self.assertEqual(sorted([blob.id, packed_blob_sha]), list(pack))
  249. self.assertTrue(o.contains_packed(packed_blob_sha))
  250. self.assertTrue(o.contains_packed(blob.id))
  251. self.assertEqual(
  252. (Blob.type_num, b"more yummy data"),
  253. o.get_raw(packed_blob_sha),
  254. )
  255. finally:
  256. o.close()
  257. def test_add_thin_pack_empty(self):
  258. with closing(DiskObjectStore(self.store_dir)) as o:
  259. f = BytesIO()
  260. entries = build_pack(f, [], store=o)
  261. self.assertEqual([], entries)
  262. o.add_thin_pack(f.read, None)
  263. class TreeLookupPathTests(TestCase):
  264. def setUp(self):
  265. TestCase.setUp(self)
  266. self.store = MemoryObjectStore()
  267. blob_a = make_object(Blob, data=b"a")
  268. blob_b = make_object(Blob, data=b"b")
  269. blob_c = make_object(Blob, data=b"c")
  270. for blob in [blob_a, blob_b, blob_c]:
  271. self.store.add_object(blob)
  272. blobs = [
  273. (b"a", blob_a.id, 0o100644),
  274. (b"ad/b", blob_b.id, 0o100644),
  275. (b"ad/bd/c", blob_c.id, 0o100755),
  276. (b"ad/c", blob_c.id, 0o100644),
  277. (b"c", blob_c.id, 0o100644),
  278. (b"d", blob_c.id, S_IFGITLINK),
  279. ]
  280. self.tree_id = commit_tree(self.store, blobs)
  281. def get_object(self, sha):
  282. return self.store[sha]
  283. def test_lookup_blob(self):
  284. o_id = tree_lookup_path(self.get_object, self.tree_id, b"a")[1]
  285. self.assertIsInstance(self.store[o_id], Blob)
  286. def test_lookup_tree(self):
  287. o_id = tree_lookup_path(self.get_object, self.tree_id, b"ad")[1]
  288. self.assertIsInstance(self.store[o_id], Tree)
  289. o_id = tree_lookup_path(self.get_object, self.tree_id, b"ad/bd")[1]
  290. self.assertIsInstance(self.store[o_id], Tree)
  291. o_id = tree_lookup_path(self.get_object, self.tree_id, b"ad/bd/")[1]
  292. self.assertIsInstance(self.store[o_id], Tree)
  293. def test_lookup_submodule(self):
  294. tree_lookup_path(self.get_object, self.tree_id, b"d")[1]
  295. self.assertRaises(
  296. SubmoduleEncountered,
  297. tree_lookup_path,
  298. self.get_object,
  299. self.tree_id,
  300. b"d/a",
  301. )
  302. def test_lookup_nonexistent(self):
  303. self.assertRaises(
  304. KeyError, tree_lookup_path, self.get_object, self.tree_id, b"j"
  305. )
  306. def test_lookup_not_tree(self):
  307. self.assertRaises(
  308. NotTreeError,
  309. tree_lookup_path,
  310. self.get_object,
  311. self.tree_id,
  312. b"ad/b/j",
  313. )
  314. class ObjectStoreGraphWalkerTests(TestCase):
  315. def get_walker(self, heads, parent_map):
  316. new_parent_map = {
  317. k * 40: [(p * 40) for p in ps] for (k, ps) in parent_map.items()
  318. }
  319. return ObjectStoreGraphWalker(
  320. [x * 40 for x in heads], new_parent_map.__getitem__
  321. )
  322. def test_ack_invalid_value(self):
  323. gw = self.get_walker([], {})
  324. self.assertRaises(ValueError, gw.ack, "tooshort")
  325. def test_empty(self):
  326. gw = self.get_walker([], {})
  327. self.assertIs(None, next(gw))
  328. gw.ack(b"a" * 40)
  329. self.assertIs(None, next(gw))
  330. def test_descends(self):
  331. gw = self.get_walker([b"a"], {b"a": [b"b"], b"b": []})
  332. self.assertEqual(b"a" * 40, next(gw))
  333. self.assertEqual(b"b" * 40, next(gw))
  334. def test_present(self):
  335. gw = self.get_walker([b"a"], {b"a": [b"b"], b"b": []})
  336. gw.ack(b"a" * 40)
  337. self.assertIs(None, next(gw))
  338. def test_parent_present(self):
  339. gw = self.get_walker([b"a"], {b"a": [b"b"], b"b": []})
  340. self.assertEqual(b"a" * 40, next(gw))
  341. gw.ack(b"a" * 40)
  342. self.assertIs(None, next(gw))
  343. def test_child_ack_later(self):
  344. gw = self.get_walker([b"a"], {b"a": [b"b"], b"b": [b"c"], b"c": []})
  345. self.assertEqual(b"a" * 40, next(gw))
  346. self.assertEqual(b"b" * 40, next(gw))
  347. gw.ack(b"a" * 40)
  348. self.assertIs(None, next(gw))
  349. def test_only_once(self):
  350. # a b
  351. # | |
  352. # c d
  353. # \ /
  354. # e
  355. gw = self.get_walker(
  356. [b"a", b"b"],
  357. {
  358. b"a": [b"c"],
  359. b"b": [b"d"],
  360. b"c": [b"e"],
  361. b"d": [b"e"],
  362. b"e": [],
  363. },
  364. )
  365. walk = []
  366. acked = False
  367. walk.append(next(gw))
  368. walk.append(next(gw))
  369. # A branch (a, c) or (b, d) may be done after 2 steps or 3 depending on
  370. # the order walked: 3-step walks include (a, b, c) and (b, a, d), etc.
  371. if walk == [b"a" * 40, b"c" * 40] or walk == [b"b" * 40, b"d" * 40]:
  372. gw.ack(walk[0])
  373. acked = True
  374. walk.append(next(gw))
  375. if not acked and walk[2] == b"c" * 40:
  376. gw.ack(b"a" * 40)
  377. elif not acked and walk[2] == b"d" * 40:
  378. gw.ack(b"b" * 40)
  379. walk.append(next(gw))
  380. self.assertIs(None, next(gw))
  381. self.assertEqual([b"a" * 40, b"b" * 40, b"c" * 40, b"d" * 40], sorted(walk))
  382. self.assertLess(walk.index(b"a" * 40), walk.index(b"c" * 40))
  383. self.assertLess(walk.index(b"b" * 40), walk.index(b"d" * 40))
  384. class CommitTreeChangesTests(TestCase):
  385. def setUp(self):
  386. super().setUp()
  387. self.store = MemoryObjectStore()
  388. self.blob_a = make_object(Blob, data=b"a")
  389. self.blob_b = make_object(Blob, data=b"b")
  390. self.blob_c = make_object(Blob, data=b"c")
  391. for blob in [self.blob_a, self.blob_b, self.blob_c]:
  392. self.store.add_object(blob)
  393. blobs = [
  394. (b"a", self.blob_a.id, 0o100644),
  395. (b"ad/b", self.blob_b.id, 0o100644),
  396. (b"ad/bd/c", self.blob_c.id, 0o100755),
  397. (b"ad/c", self.blob_c.id, 0o100644),
  398. (b"c", self.blob_c.id, 0o100644),
  399. ]
  400. self.tree_id = commit_tree(self.store, blobs)
  401. def test_no_changes(self):
  402. self.assertEqual(
  403. self.store[self.tree_id],
  404. commit_tree_changes(self.store, self.store[self.tree_id], []),
  405. )
  406. def test_add_blob(self):
  407. blob_d = make_object(Blob, data=b"d")
  408. new_tree = commit_tree_changes(
  409. self.store, self.store[self.tree_id], [(b"d", 0o100644, blob_d.id)]
  410. )
  411. self.assertEqual(
  412. new_tree[b"d"],
  413. (33188, b"c59d9b6344f1af00e504ba698129f07a34bbed8d"),
  414. )
  415. def test_add_blob_in_dir(self):
  416. blob_d = make_object(Blob, data=b"d")
  417. new_tree = commit_tree_changes(
  418. self.store,
  419. self.store[self.tree_id],
  420. [(b"e/f/d", 0o100644, blob_d.id)],
  421. )
  422. self.assertEqual(
  423. new_tree.items(),
  424. [
  425. TreeEntry(path=b"a", mode=stat.S_IFREG | 0o100644, sha=self.blob_a.id),
  426. TreeEntry(
  427. path=b"ad",
  428. mode=stat.S_IFDIR,
  429. sha=b"0e2ce2cd7725ff4817791be31ccd6e627e801f4a",
  430. ),
  431. TreeEntry(path=b"c", mode=stat.S_IFREG | 0o100644, sha=self.blob_c.id),
  432. TreeEntry(
  433. path=b"e",
  434. mode=stat.S_IFDIR,
  435. sha=b"6ab344e288724ac2fb38704728b8896e367ed108",
  436. ),
  437. ],
  438. )
  439. e_tree = self.store[new_tree[b"e"][1]]
  440. self.assertEqual(
  441. e_tree.items(),
  442. [
  443. TreeEntry(
  444. path=b"f",
  445. mode=stat.S_IFDIR,
  446. sha=b"24d2c94d8af232b15a0978c006bf61ef4479a0a5",
  447. )
  448. ],
  449. )
  450. f_tree = self.store[e_tree[b"f"][1]]
  451. self.assertEqual(
  452. f_tree.items(),
  453. [TreeEntry(path=b"d", mode=stat.S_IFREG | 0o100644, sha=blob_d.id)],
  454. )
  455. def test_delete_blob(self):
  456. new_tree = commit_tree_changes(
  457. self.store, self.store[self.tree_id], [(b"ad/bd/c", None, None)]
  458. )
  459. self.assertEqual(set(new_tree), {b"a", b"ad", b"c"})
  460. ad_tree = self.store[new_tree[b"ad"][1]]
  461. self.assertEqual(set(ad_tree), {b"b", b"c"})
  462. class TestReadPacksFile(TestCase):
  463. def test_read_packs(self):
  464. self.assertEqual(
  465. ["pack-1.pack"],
  466. list(
  467. read_packs_file(
  468. BytesIO(
  469. b"""P pack-1.pack
  470. """
  471. )
  472. )
  473. ),
  474. )