test_repository.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. # test_repository.py -- tests for repository.py
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  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. """Tests for the repository."""
  20. from cStringIO import StringIO
  21. import os
  22. import shutil
  23. import tempfile
  24. import warnings
  25. from dulwich import errors
  26. from dulwich.file import (
  27. GitFile,
  28. )
  29. from dulwich.object_store import (
  30. tree_lookup_path,
  31. )
  32. from dulwich import objects
  33. from dulwich.config import Config
  34. from dulwich.repo import (
  35. check_ref_format,
  36. DictRefsContainer,
  37. InfoRefsContainer,
  38. Repo,
  39. MemoryRepo,
  40. read_packed_refs,
  41. read_packed_refs_with_peeled,
  42. write_packed_refs,
  43. _split_ref_line,
  44. )
  45. from dulwich.tests import (
  46. TestCase,
  47. )
  48. from dulwich.tests.utils import (
  49. open_repo,
  50. tear_down_repo,
  51. )
  52. missing_sha = 'b91fa4d900e17e99b433218e988c4eb4a3e9a097'
  53. class CreateRepositoryTests(TestCase):
  54. def assertFileContentsEqual(self, expected, repo, path):
  55. f = repo.get_named_file(path)
  56. if not f:
  57. self.assertEqual(expected, None)
  58. else:
  59. try:
  60. self.assertEqual(expected, f.read())
  61. finally:
  62. f.close()
  63. def _check_repo_contents(self, repo, expect_bare):
  64. self.assertEqual(expect_bare, repo.bare)
  65. self.assertFileContentsEqual('Unnamed repository', repo, 'description')
  66. self.assertFileContentsEqual('', repo, os.path.join('info', 'exclude'))
  67. self.assertFileContentsEqual(None, repo, 'nonexistent file')
  68. barestr = 'bare = %s' % str(expect_bare).lower()
  69. config_text = repo.get_named_file('config').read()
  70. self.assertTrue(barestr in config_text, "%r" % config_text)
  71. def test_create_disk_bare(self):
  72. tmp_dir = tempfile.mkdtemp()
  73. self.addCleanup(shutil.rmtree, tmp_dir)
  74. repo = Repo.init_bare(tmp_dir)
  75. self.assertEqual(tmp_dir, repo._controldir)
  76. self._check_repo_contents(repo, True)
  77. def test_create_disk_non_bare(self):
  78. tmp_dir = tempfile.mkdtemp()
  79. self.addCleanup(shutil.rmtree, tmp_dir)
  80. repo = Repo.init(tmp_dir)
  81. self.assertEqual(os.path.join(tmp_dir, '.git'), repo._controldir)
  82. self._check_repo_contents(repo, False)
  83. def test_create_memory(self):
  84. repo = MemoryRepo.init_bare([], {})
  85. self._check_repo_contents(repo, True)
  86. class RepositoryTests(TestCase):
  87. def setUp(self):
  88. super(RepositoryTests, self).setUp()
  89. self._repo = None
  90. def tearDown(self):
  91. if self._repo is not None:
  92. tear_down_repo(self._repo)
  93. super(RepositoryTests, self).tearDown()
  94. def test_simple_props(self):
  95. r = self._repo = open_repo('a.git')
  96. self.assertEqual(r.controldir(), r.path)
  97. def test_ref(self):
  98. r = self._repo = open_repo('a.git')
  99. self.assertEqual(r.ref('refs/heads/master'),
  100. 'a90fa2d900a17e99b433217e988c4eb4a2e9a097')
  101. def test_setitem(self):
  102. r = self._repo = open_repo('a.git')
  103. r["refs/tags/foo"] = 'a90fa2d900a17e99b433217e988c4eb4a2e9a097'
  104. self.assertEqual('a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  105. r["refs/tags/foo"].id)
  106. def test_delitem(self):
  107. r = self._repo = open_repo('a.git')
  108. del r['refs/heads/master']
  109. self.assertRaises(KeyError, lambda: r['refs/heads/master'])
  110. del r['HEAD']
  111. self.assertRaises(KeyError, lambda: r['HEAD'])
  112. self.assertRaises(ValueError, r.__delitem__, 'notrefs/foo')
  113. def test_get_refs(self):
  114. r = self._repo = open_repo('a.git')
  115. self.assertEqual({
  116. 'HEAD': 'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  117. 'refs/heads/master': 'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  118. 'refs/tags/mytag': '28237f4dc30d0d462658d6b937b08a0f0b6ef55a',
  119. 'refs/tags/mytag-packed': 'b0931cadc54336e78a1d980420e3268903b57a50',
  120. }, r.get_refs())
  121. def test_head(self):
  122. r = self._repo = open_repo('a.git')
  123. self.assertEqual(r.head(), 'a90fa2d900a17e99b433217e988c4eb4a2e9a097')
  124. def test_get_object(self):
  125. r = self._repo = open_repo('a.git')
  126. obj = r.get_object(r.head())
  127. self.assertEqual(obj.type_name, 'commit')
  128. def test_get_object_non_existant(self):
  129. r = self._repo = open_repo('a.git')
  130. self.assertRaises(KeyError, r.get_object, missing_sha)
  131. def test_contains_object(self):
  132. r = self._repo = open_repo('a.git')
  133. self.assertTrue(r.head() in r)
  134. def test_contains_ref(self):
  135. r = self._repo = open_repo('a.git')
  136. self.assertTrue("HEAD" in r)
  137. def test_contains_missing(self):
  138. r = self._repo = open_repo('a.git')
  139. self.assertFalse("bar" in r)
  140. def test_commit(self):
  141. r = self._repo = open_repo('a.git')
  142. warnings.simplefilter("ignore", DeprecationWarning)
  143. self.addCleanup(warnings.resetwarnings)
  144. obj = r.commit(r.head())
  145. self.assertEqual(obj.type_name, 'commit')
  146. def test_commit_not_commit(self):
  147. r = self._repo = open_repo('a.git')
  148. warnings.simplefilter("ignore", DeprecationWarning)
  149. self.addCleanup(warnings.resetwarnings)
  150. self.assertRaises(errors.NotCommitError,
  151. r.commit, '4f2e6529203aa6d44b5af6e3292c837ceda003f9')
  152. def test_tree(self):
  153. r = self._repo = open_repo('a.git')
  154. commit = r[r.head()]
  155. warnings.simplefilter("ignore", DeprecationWarning)
  156. self.addCleanup(warnings.resetwarnings)
  157. tree = r.tree(commit.tree)
  158. self.assertEqual(tree.type_name, 'tree')
  159. self.assertEqual(tree.sha().hexdigest(), commit.tree)
  160. def test_tree_not_tree(self):
  161. r = self._repo = open_repo('a.git')
  162. warnings.simplefilter("ignore", DeprecationWarning)
  163. self.addCleanup(warnings.resetwarnings)
  164. self.assertRaises(errors.NotTreeError, r.tree, r.head())
  165. def test_tag(self):
  166. r = self._repo = open_repo('a.git')
  167. tag_sha = '28237f4dc30d0d462658d6b937b08a0f0b6ef55a'
  168. warnings.simplefilter("ignore", DeprecationWarning)
  169. self.addCleanup(warnings.resetwarnings)
  170. tag = r.tag(tag_sha)
  171. self.assertEqual(tag.type_name, 'tag')
  172. self.assertEqual(tag.sha().hexdigest(), tag_sha)
  173. obj_class, obj_sha = tag.object
  174. self.assertEqual(obj_class, objects.Commit)
  175. self.assertEqual(obj_sha, r.head())
  176. def test_tag_not_tag(self):
  177. r = self._repo = open_repo('a.git')
  178. warnings.simplefilter("ignore", DeprecationWarning)
  179. self.addCleanup(warnings.resetwarnings)
  180. self.assertRaises(errors.NotTagError, r.tag, r.head())
  181. def test_get_peeled(self):
  182. # unpacked ref
  183. r = self._repo = open_repo('a.git')
  184. tag_sha = '28237f4dc30d0d462658d6b937b08a0f0b6ef55a'
  185. self.assertNotEqual(r[tag_sha].sha().hexdigest(), r.head())
  186. self.assertEqual(r.get_peeled('refs/tags/mytag'), r.head())
  187. # packed ref with cached peeled value
  188. packed_tag_sha = 'b0931cadc54336e78a1d980420e3268903b57a50'
  189. parent_sha = r[r.head()].parents[0]
  190. self.assertNotEqual(r[packed_tag_sha].sha().hexdigest(), parent_sha)
  191. self.assertEqual(r.get_peeled('refs/tags/mytag-packed'), parent_sha)
  192. # TODO: add more corner cases to test repo
  193. def test_get_peeled_not_tag(self):
  194. r = self._repo = open_repo('a.git')
  195. self.assertEqual(r.get_peeled('HEAD'), r.head())
  196. def test_get_blob(self):
  197. r = self._repo = open_repo('a.git')
  198. commit = r[r.head()]
  199. tree = r[commit.tree]
  200. blob_sha = tree.items()[0][2]
  201. warnings.simplefilter("ignore", DeprecationWarning)
  202. self.addCleanup(warnings.resetwarnings)
  203. blob = r.get_blob(blob_sha)
  204. self.assertEqual(blob.type_name, 'blob')
  205. self.assertEqual(blob.sha().hexdigest(), blob_sha)
  206. def test_get_blob_notblob(self):
  207. r = self._repo = open_repo('a.git')
  208. warnings.simplefilter("ignore", DeprecationWarning)
  209. self.addCleanup(warnings.resetwarnings)
  210. self.assertRaises(errors.NotBlobError, r.get_blob, r.head())
  211. def test_get_walker(self):
  212. r = self._repo = open_repo('a.git')
  213. # include defaults to [r.head()]
  214. self.assertEqual([e.commit.id for e in r.get_walker()],
  215. [r.head(), '2a72d929692c41d8554c07f6301757ba18a65d91'])
  216. self.assertEqual(
  217. [e.commit.id for e in r.get_walker(['2a72d929692c41d8554c07f6301757ba18a65d91'])],
  218. ['2a72d929692c41d8554c07f6301757ba18a65d91'])
  219. def test_linear_history(self):
  220. r = self._repo = open_repo('a.git')
  221. warnings.simplefilter("ignore", DeprecationWarning)
  222. self.addCleanup(warnings.resetwarnings)
  223. history = r.revision_history(r.head())
  224. shas = [c.sha().hexdigest() for c in history]
  225. self.assertEqual(shas, [r.head(),
  226. '2a72d929692c41d8554c07f6301757ba18a65d91'])
  227. def test_clone(self):
  228. r = self._repo = open_repo('a.git')
  229. tmp_dir = tempfile.mkdtemp()
  230. self.addCleanup(shutil.rmtree, tmp_dir)
  231. t = r.clone(tmp_dir, mkdir=False)
  232. self.assertEqual({
  233. 'HEAD': 'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  234. 'refs/remotes/origin/master':
  235. 'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  236. 'refs/heads/master': 'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  237. 'refs/tags/mytag': '28237f4dc30d0d462658d6b937b08a0f0b6ef55a',
  238. 'refs/tags/mytag-packed':
  239. 'b0931cadc54336e78a1d980420e3268903b57a50',
  240. }, t.refs.as_dict())
  241. shas = [e.commit.id for e in r.get_walker()]
  242. self.assertEqual(shas, [t.head(),
  243. '2a72d929692c41d8554c07f6301757ba18a65d91'])
  244. def test_clone_no_head(self):
  245. temp_dir = tempfile.mkdtemp()
  246. self.addCleanup(shutil.rmtree, temp_dir)
  247. repo_dir = os.path.join(os.path.dirname(__file__), 'data', 'repos')
  248. dest_dir = os.path.join(temp_dir, 'a.git')
  249. shutil.copytree(os.path.join(repo_dir, 'a.git'),
  250. dest_dir, symlinks=True)
  251. r = Repo(dest_dir)
  252. del r.refs["refs/heads/master"]
  253. del r.refs["HEAD"]
  254. t = r.clone(os.path.join(temp_dir, 'b.git'), mkdir=True)
  255. self.assertEqual({
  256. 'refs/tags/mytag': '28237f4dc30d0d462658d6b937b08a0f0b6ef55a',
  257. 'refs/tags/mytag-packed':
  258. 'b0931cadc54336e78a1d980420e3268903b57a50',
  259. }, t.refs.as_dict())
  260. def test_clone_empty(self):
  261. """Test clone() doesn't crash if HEAD points to a non-existing ref.
  262. This simulates cloning server-side bare repository either when it is
  263. still empty or if user renames master branch and pushes private repo
  264. to the server.
  265. Non-bare repo HEAD always points to an existing ref.
  266. """
  267. r = self._repo = open_repo('empty.git')
  268. tmp_dir = tempfile.mkdtemp()
  269. self.addCleanup(shutil.rmtree, tmp_dir)
  270. r.clone(tmp_dir, mkdir=False, bare=True)
  271. def test_merge_history(self):
  272. r = self._repo = open_repo('simple_merge.git')
  273. shas = [e.commit.id for e in r.get_walker()]
  274. self.assertEqual(shas, ['5dac377bdded4c9aeb8dff595f0faeebcc8498cc',
  275. 'ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  276. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6',
  277. '60dacdc733de308bb77bb76ce0fb0f9b44c9769e',
  278. '0d89f20333fbb1d2f3a94da77f4981373d8f4310'])
  279. def test_revision_history_missing_commit(self):
  280. r = self._repo = open_repo('simple_merge.git')
  281. warnings.simplefilter("ignore", DeprecationWarning)
  282. self.addCleanup(warnings.resetwarnings)
  283. self.assertRaises(errors.MissingCommitError, r.revision_history,
  284. missing_sha)
  285. def test_out_of_order_merge(self):
  286. """Test that revision history is ordered by date, not parent order."""
  287. r = self._repo = open_repo('ooo_merge.git')
  288. shas = [e.commit.id for e in r.get_walker()]
  289. self.assertEqual(shas, ['7601d7f6231db6a57f7bbb79ee52e4d462fd44d1',
  290. 'f507291b64138b875c28e03469025b1ea20bc614',
  291. 'fb5b0425c7ce46959bec94d54b9a157645e114f5',
  292. 'f9e39b120c68182a4ba35349f832d0e4e61f485c'])
  293. def test_get_tags_empty(self):
  294. r = self._repo = open_repo('ooo_merge.git')
  295. self.assertEqual({}, r.refs.as_dict('refs/tags'))
  296. def test_get_config(self):
  297. r = self._repo = open_repo('ooo_merge.git')
  298. self.assertIsInstance(r.get_config(), Config)
  299. def test_get_config_stack(self):
  300. r = self._repo = open_repo('ooo_merge.git')
  301. self.assertIsInstance(r.get_config_stack(), Config)
  302. def test_submodule(self):
  303. temp_dir = tempfile.mkdtemp()
  304. repo_dir = os.path.join(os.path.dirname(__file__), 'data', 'repos')
  305. shutil.copytree(os.path.join(repo_dir, 'a.git'),
  306. os.path.join(temp_dir, 'a.git'), symlinks=True)
  307. rel = os.path.relpath(os.path.join(repo_dir, 'submodule'), temp_dir)
  308. os.symlink(os.path.join(rel, 'dotgit'), os.path.join(temp_dir, '.git'))
  309. r = Repo(temp_dir)
  310. self.assertEqual(r.head(), 'a90fa2d900a17e99b433217e988c4eb4a2e9a097')
  311. def test_common_revisions(self):
  312. """
  313. This test demonstrates that ``find_common_revisions()`` actually returns
  314. common heads, not revisions; dulwich already uses
  315. ``find_common_revisions()`` in such a manner (see
  316. ``Repo.fetch_objects()``).
  317. """
  318. expected_shas = set(['60dacdc733de308bb77bb76ce0fb0f9b44c9769e'])
  319. # Source for objects.
  320. r_base = open_repo('simple_merge.git')
  321. # Re-create each-side of the merge in simple_merge.git.
  322. #
  323. # Since the trees and blobs are missing, the repository created is
  324. # corrupted, but we're only checking for commits for the purpose of this
  325. # test, so it's immaterial.
  326. r1_dir = tempfile.mkdtemp()
  327. r1_commits = ['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd', # HEAD
  328. '60dacdc733de308bb77bb76ce0fb0f9b44c9769e',
  329. '0d89f20333fbb1d2f3a94da77f4981373d8f4310']
  330. r2_dir = tempfile.mkdtemp()
  331. r2_commits = ['4cffe90e0a41ad3f5190079d7c8f036bde29cbe6', # HEAD
  332. '60dacdc733de308bb77bb76ce0fb0f9b44c9769e',
  333. '0d89f20333fbb1d2f3a94da77f4981373d8f4310']
  334. try:
  335. r1 = Repo.init_bare(r1_dir)
  336. map(lambda c: r1.object_store.add_object(r_base.get_object(c)), \
  337. r1_commits)
  338. r1.refs['HEAD'] = r1_commits[0]
  339. r2 = Repo.init_bare(r2_dir)
  340. map(lambda c: r2.object_store.add_object(r_base.get_object(c)), \
  341. r2_commits)
  342. r2.refs['HEAD'] = r2_commits[0]
  343. # Finally, the 'real' testing!
  344. shas = r2.object_store.find_common_revisions(r1.get_graph_walker())
  345. self.assertEqual(set(shas), expected_shas)
  346. shas = r1.object_store.find_common_revisions(r2.get_graph_walker())
  347. self.assertEqual(set(shas), expected_shas)
  348. finally:
  349. shutil.rmtree(r1_dir)
  350. shutil.rmtree(r2_dir)
  351. class BuildRepoTests(TestCase):
  352. """Tests that build on-disk repos from scratch.
  353. Repos live in a temp dir and are torn down after each test. They start with
  354. a single commit in master having single file named 'a'.
  355. """
  356. def setUp(self):
  357. super(BuildRepoTests, self).setUp()
  358. repo_dir = os.path.join(tempfile.mkdtemp(), 'test')
  359. os.makedirs(repo_dir)
  360. r = self._repo = Repo.init(repo_dir)
  361. self.assertFalse(r.bare)
  362. self.assertEqual('ref: refs/heads/master', r.refs.read_ref('HEAD'))
  363. self.assertRaises(KeyError, lambda: r.refs['refs/heads/master'])
  364. f = open(os.path.join(r.path, 'a'), 'wb')
  365. try:
  366. f.write('file contents')
  367. finally:
  368. f.close()
  369. r.stage(['a'])
  370. commit_sha = r.do_commit('msg',
  371. committer='Test Committer <test@nodomain.com>',
  372. author='Test Author <test@nodomain.com>',
  373. commit_timestamp=12345, commit_timezone=0,
  374. author_timestamp=12345, author_timezone=0)
  375. self.assertEqual([], r[commit_sha].parents)
  376. self._root_commit = commit_sha
  377. def tearDown(self):
  378. tear_down_repo(self._repo)
  379. super(BuildRepoTests, self).tearDown()
  380. def test_build_repo(self):
  381. r = self._repo
  382. self.assertEqual('ref: refs/heads/master', r.refs.read_ref('HEAD'))
  383. self.assertEqual(self._root_commit, r.refs['refs/heads/master'])
  384. expected_blob = objects.Blob.from_string('file contents')
  385. self.assertEqual(expected_blob.data, r[expected_blob.id].data)
  386. actual_commit = r[self._root_commit]
  387. self.assertEqual('msg', actual_commit.message)
  388. def test_commit_modified(self):
  389. r = self._repo
  390. f = open(os.path.join(r.path, 'a'), 'wb')
  391. try:
  392. f.write('new contents')
  393. finally:
  394. f.close()
  395. r.stage(['a'])
  396. commit_sha = r.do_commit('modified a',
  397. committer='Test Committer <test@nodomain.com>',
  398. author='Test Author <test@nodomain.com>',
  399. commit_timestamp=12395, commit_timezone=0,
  400. author_timestamp=12395, author_timezone=0)
  401. self.assertEqual([self._root_commit], r[commit_sha].parents)
  402. _, blob_id = tree_lookup_path(r.get_object, r[commit_sha].tree, 'a')
  403. self.assertEqual('new contents', r[blob_id].data)
  404. def test_commit_deleted(self):
  405. r = self._repo
  406. os.remove(os.path.join(r.path, 'a'))
  407. r.stage(['a'])
  408. commit_sha = r.do_commit('deleted a',
  409. committer='Test Committer <test@nodomain.com>',
  410. author='Test Author <test@nodomain.com>',
  411. commit_timestamp=12395, commit_timezone=0,
  412. author_timestamp=12395, author_timezone=0)
  413. self.assertEqual([self._root_commit], r[commit_sha].parents)
  414. self.assertEqual([], list(r.open_index()))
  415. tree = r[r[commit_sha].tree]
  416. self.assertEqual([], list(tree.iteritems()))
  417. def test_commit_encoding(self):
  418. r = self._repo
  419. commit_sha = r.do_commit('commit with strange character \xee',
  420. committer='Test Committer <test@nodomain.com>',
  421. author='Test Author <test@nodomain.com>',
  422. commit_timestamp=12395, commit_timezone=0,
  423. author_timestamp=12395, author_timezone=0,
  424. encoding="iso8859-1")
  425. self.assertEqual("iso8859-1", r[commit_sha].encoding)
  426. def test_commit_config_identity(self):
  427. # commit falls back to the users' identity if it wasn't specified
  428. r = self._repo
  429. c = r.get_config()
  430. c.set(("user", ), "name", "Jelmer")
  431. c.set(("user", ), "email", "jelmer@apache.org")
  432. c.write_to_path()
  433. commit_sha = r.do_commit('message')
  434. self.assertEqual(
  435. "Jelmer <jelmer@apache.org>",
  436. r[commit_sha].author)
  437. self.assertEqual(
  438. "Jelmer <jelmer@apache.org>",
  439. r[commit_sha].committer)
  440. def test_commit_fail_ref(self):
  441. r = self._repo
  442. def set_if_equals(name, old_ref, new_ref):
  443. return False
  444. r.refs.set_if_equals = set_if_equals
  445. def add_if_new(name, new_ref):
  446. self.fail('Unexpected call to add_if_new')
  447. r.refs.add_if_new = add_if_new
  448. old_shas = set(r.object_store)
  449. self.assertRaises(errors.CommitError, r.do_commit, 'failed commit',
  450. committer='Test Committer <test@nodomain.com>',
  451. author='Test Author <test@nodomain.com>',
  452. commit_timestamp=12345, commit_timezone=0,
  453. author_timestamp=12345, author_timezone=0)
  454. new_shas = set(r.object_store) - old_shas
  455. self.assertEqual(1, len(new_shas))
  456. # Check that the new commit (now garbage) was added.
  457. new_commit = r[new_shas.pop()]
  458. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  459. self.assertEqual('failed commit', new_commit.message)
  460. def test_commit_branch(self):
  461. r = self._repo
  462. commit_sha = r.do_commit('commit to branch',
  463. committer='Test Committer <test@nodomain.com>',
  464. author='Test Author <test@nodomain.com>',
  465. commit_timestamp=12395, commit_timezone=0,
  466. author_timestamp=12395, author_timezone=0,
  467. ref="refs/heads/new_branch")
  468. self.assertEqual(self._root_commit, r["HEAD"].id)
  469. self.assertEqual(commit_sha, r["refs/heads/new_branch"].id)
  470. self.assertEqual([], r[commit_sha].parents)
  471. self.assertTrue("refs/heads/new_branch" in r)
  472. new_branch_head = commit_sha
  473. commit_sha = r.do_commit('commit to branch 2',
  474. committer='Test Committer <test@nodomain.com>',
  475. author='Test Author <test@nodomain.com>',
  476. commit_timestamp=12395, commit_timezone=0,
  477. author_timestamp=12395, author_timezone=0,
  478. ref="refs/heads/new_branch")
  479. self.assertEqual(self._root_commit, r["HEAD"].id)
  480. self.assertEqual(commit_sha, r["refs/heads/new_branch"].id)
  481. self.assertEqual([new_branch_head], r[commit_sha].parents)
  482. def test_commit_merge_heads(self):
  483. r = self._repo
  484. merge_1 = r.do_commit('commit to branch 2',
  485. committer='Test Committer <test@nodomain.com>',
  486. author='Test Author <test@nodomain.com>',
  487. commit_timestamp=12395, commit_timezone=0,
  488. author_timestamp=12395, author_timezone=0,
  489. ref="refs/heads/new_branch")
  490. commit_sha = r.do_commit('commit with merge',
  491. committer='Test Committer <test@nodomain.com>',
  492. author='Test Author <test@nodomain.com>',
  493. commit_timestamp=12395, commit_timezone=0,
  494. author_timestamp=12395, author_timezone=0,
  495. merge_heads=[merge_1])
  496. self.assertEqual(
  497. [self._root_commit, merge_1],
  498. r[commit_sha].parents)
  499. def test_stage_deleted(self):
  500. r = self._repo
  501. os.remove(os.path.join(r.path, 'a'))
  502. r.stage(['a'])
  503. r.stage(['a']) # double-stage a deleted path
  504. class CheckRefFormatTests(TestCase):
  505. """Tests for the check_ref_format function.
  506. These are the same tests as in the git test suite.
  507. """
  508. def test_valid(self):
  509. self.assertTrue(check_ref_format('heads/foo'))
  510. self.assertTrue(check_ref_format('foo/bar/baz'))
  511. self.assertTrue(check_ref_format('refs///heads/foo'))
  512. self.assertTrue(check_ref_format('foo./bar'))
  513. self.assertTrue(check_ref_format('heads/foo@bar'))
  514. self.assertTrue(check_ref_format('heads/fix.lock.error'))
  515. def test_invalid(self):
  516. self.assertFalse(check_ref_format('foo'))
  517. self.assertFalse(check_ref_format('heads/foo/'))
  518. self.assertFalse(check_ref_format('./foo'))
  519. self.assertFalse(check_ref_format('.refs/foo'))
  520. self.assertFalse(check_ref_format('heads/foo..bar'))
  521. self.assertFalse(check_ref_format('heads/foo?bar'))
  522. self.assertFalse(check_ref_format('heads/foo.lock'))
  523. self.assertFalse(check_ref_format('heads/v@{ation'))
  524. self.assertFalse(check_ref_format('heads/foo\bar'))
  525. ONES = "1" * 40
  526. TWOS = "2" * 40
  527. THREES = "3" * 40
  528. FOURS = "4" * 40
  529. class PackedRefsFileTests(TestCase):
  530. def test_split_ref_line_errors(self):
  531. self.assertRaises(errors.PackedRefsException, _split_ref_line,
  532. 'singlefield')
  533. self.assertRaises(errors.PackedRefsException, _split_ref_line,
  534. 'badsha name')
  535. self.assertRaises(errors.PackedRefsException, _split_ref_line,
  536. '%s bad/../refname' % ONES)
  537. def test_read_without_peeled(self):
  538. f = StringIO('# comment\n%s ref/1\n%s ref/2' % (ONES, TWOS))
  539. self.assertEqual([(ONES, 'ref/1'), (TWOS, 'ref/2')],
  540. list(read_packed_refs(f)))
  541. def test_read_without_peeled_errors(self):
  542. f = StringIO('%s ref/1\n^%s' % (ONES, TWOS))
  543. self.assertRaises(errors.PackedRefsException, list, read_packed_refs(f))
  544. def test_read_with_peeled(self):
  545. f = StringIO('%s ref/1\n%s ref/2\n^%s\n%s ref/4' % (
  546. ONES, TWOS, THREES, FOURS))
  547. self.assertEqual([
  548. (ONES, 'ref/1', None),
  549. (TWOS, 'ref/2', THREES),
  550. (FOURS, 'ref/4', None),
  551. ], list(read_packed_refs_with_peeled(f)))
  552. def test_read_with_peeled_errors(self):
  553. f = StringIO('^%s\n%s ref/1' % (TWOS, ONES))
  554. self.assertRaises(errors.PackedRefsException, list, read_packed_refs(f))
  555. f = StringIO('%s ref/1\n^%s\n^%s' % (ONES, TWOS, THREES))
  556. self.assertRaises(errors.PackedRefsException, list, read_packed_refs(f))
  557. def test_write_with_peeled(self):
  558. f = StringIO()
  559. write_packed_refs(f, {'ref/1': ONES, 'ref/2': TWOS},
  560. {'ref/1': THREES})
  561. self.assertEqual(
  562. "# pack-refs with: peeled\n%s ref/1\n^%s\n%s ref/2\n" % (
  563. ONES, THREES, TWOS), f.getvalue())
  564. def test_write_without_peeled(self):
  565. f = StringIO()
  566. write_packed_refs(f, {'ref/1': ONES, 'ref/2': TWOS})
  567. self.assertEqual("%s ref/1\n%s ref/2\n" % (ONES, TWOS), f.getvalue())
  568. # Dict of refs that we expect all RefsContainerTests subclasses to define.
  569. _TEST_REFS = {
  570. 'HEAD': '42d06bd4b77fed026b154d16493e5deab78f02ec',
  571. 'refs/heads/master': '42d06bd4b77fed026b154d16493e5deab78f02ec',
  572. 'refs/heads/packed': '42d06bd4b77fed026b154d16493e5deab78f02ec',
  573. 'refs/tags/refs-0.1': 'df6800012397fb85c56e7418dd4eb9405dee075c',
  574. 'refs/tags/refs-0.2': '3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8',
  575. }
  576. class RefsContainerTests(object):
  577. def test_keys(self):
  578. actual_keys = set(self._refs.keys())
  579. self.assertEqual(set(self._refs.allkeys()), actual_keys)
  580. # ignore the symref loop if it exists
  581. actual_keys.discard('refs/heads/loop')
  582. self.assertEqual(set(_TEST_REFS.iterkeys()), actual_keys)
  583. actual_keys = self._refs.keys('refs/heads')
  584. actual_keys.discard('loop')
  585. self.assertEqual(['master', 'packed'], sorted(actual_keys))
  586. self.assertEqual(['refs-0.1', 'refs-0.2'],
  587. sorted(self._refs.keys('refs/tags')))
  588. def test_as_dict(self):
  589. # refs/heads/loop does not show up even if it exists
  590. self.assertEqual(_TEST_REFS, self._refs.as_dict())
  591. def test_setitem(self):
  592. self._refs['refs/some/ref'] = '42d06bd4b77fed026b154d16493e5deab78f02ec'
  593. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  594. self._refs['refs/some/ref'])
  595. self.assertRaises(errors.RefFormatError, self._refs.__setitem__,
  596. 'notrefs/foo', '42d06bd4b77fed026b154d16493e5deab78f02ec')
  597. def test_set_if_equals(self):
  598. nines = '9' * 40
  599. self.assertFalse(self._refs.set_if_equals('HEAD', 'c0ffee', nines))
  600. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  601. self._refs['HEAD'])
  602. self.assertTrue(self._refs.set_if_equals(
  603. 'HEAD', '42d06bd4b77fed026b154d16493e5deab78f02ec', nines))
  604. self.assertEqual(nines, self._refs['HEAD'])
  605. self.assertTrue(self._refs.set_if_equals('refs/heads/master', None,
  606. nines))
  607. self.assertEqual(nines, self._refs['refs/heads/master'])
  608. def test_add_if_new(self):
  609. nines = '9' * 40
  610. self.assertFalse(self._refs.add_if_new('refs/heads/master', nines))
  611. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  612. self._refs['refs/heads/master'])
  613. self.assertTrue(self._refs.add_if_new('refs/some/ref', nines))
  614. self.assertEqual(nines, self._refs['refs/some/ref'])
  615. def test_set_symbolic_ref(self):
  616. self._refs.set_symbolic_ref('refs/heads/symbolic', 'refs/heads/master')
  617. self.assertEqual('ref: refs/heads/master',
  618. self._refs.read_loose_ref('refs/heads/symbolic'))
  619. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  620. self._refs['refs/heads/symbolic'])
  621. def test_set_symbolic_ref_overwrite(self):
  622. nines = '9' * 40
  623. self.assertFalse('refs/heads/symbolic' in self._refs)
  624. self._refs['refs/heads/symbolic'] = nines
  625. self.assertEqual(nines, self._refs.read_loose_ref('refs/heads/symbolic'))
  626. self._refs.set_symbolic_ref('refs/heads/symbolic', 'refs/heads/master')
  627. self.assertEqual('ref: refs/heads/master',
  628. self._refs.read_loose_ref('refs/heads/symbolic'))
  629. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  630. self._refs['refs/heads/symbolic'])
  631. def test_check_refname(self):
  632. self._refs._check_refname('HEAD')
  633. self._refs._check_refname('refs/stash')
  634. self._refs._check_refname('refs/heads/foo')
  635. self.assertRaises(errors.RefFormatError, self._refs._check_refname,
  636. 'refs')
  637. self.assertRaises(errors.RefFormatError, self._refs._check_refname,
  638. 'notrefs/foo')
  639. def test_contains(self):
  640. self.assertTrue('refs/heads/master' in self._refs)
  641. self.assertFalse('refs/heads/bar' in self._refs)
  642. def test_delitem(self):
  643. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  644. self._refs['refs/heads/master'])
  645. del self._refs['refs/heads/master']
  646. self.assertRaises(KeyError, lambda: self._refs['refs/heads/master'])
  647. def test_remove_if_equals(self):
  648. self.assertFalse(self._refs.remove_if_equals('HEAD', 'c0ffee'))
  649. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  650. self._refs['HEAD'])
  651. self.assertTrue(self._refs.remove_if_equals(
  652. 'refs/tags/refs-0.2', '3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8'))
  653. self.assertFalse('refs/tags/refs-0.2' in self._refs)
  654. class DictRefsContainerTests(RefsContainerTests, TestCase):
  655. def setUp(self):
  656. TestCase.setUp(self)
  657. self._refs = DictRefsContainer(dict(_TEST_REFS))
  658. def test_invalid_refname(self):
  659. # FIXME: Move this test into RefsContainerTests, but requires
  660. # some way of injecting invalid refs.
  661. self._refs._refs["refs/stash"] = "00" * 20
  662. expected_refs = dict(_TEST_REFS)
  663. expected_refs["refs/stash"] = "00" * 20
  664. self.assertEqual(expected_refs, self._refs.as_dict())
  665. class DiskRefsContainerTests(RefsContainerTests, TestCase):
  666. def setUp(self):
  667. TestCase.setUp(self)
  668. self._repo = open_repo('refs.git')
  669. self._refs = self._repo.refs
  670. def tearDown(self):
  671. tear_down_repo(self._repo)
  672. TestCase.tearDown(self)
  673. def test_get_packed_refs(self):
  674. self.assertEqual({
  675. 'refs/heads/packed': '42d06bd4b77fed026b154d16493e5deab78f02ec',
  676. 'refs/tags/refs-0.1': 'df6800012397fb85c56e7418dd4eb9405dee075c',
  677. }, self._refs.get_packed_refs())
  678. def test_get_peeled_not_packed(self):
  679. # not packed
  680. self.assertEqual(None, self._refs.get_peeled('refs/tags/refs-0.2'))
  681. self.assertEqual('3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8',
  682. self._refs['refs/tags/refs-0.2'])
  683. # packed, known not peelable
  684. self.assertEqual(self._refs['refs/heads/packed'],
  685. self._refs.get_peeled('refs/heads/packed'))
  686. # packed, peeled
  687. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  688. self._refs.get_peeled('refs/tags/refs-0.1'))
  689. def test_setitem(self):
  690. RefsContainerTests.test_setitem(self)
  691. f = open(os.path.join(self._refs.path, 'refs', 'some', 'ref'), 'rb')
  692. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  693. f.read()[:40])
  694. f.close()
  695. def test_setitem_symbolic(self):
  696. ones = '1' * 40
  697. self._refs['HEAD'] = ones
  698. self.assertEqual(ones, self._refs['HEAD'])
  699. # ensure HEAD was not modified
  700. f = open(os.path.join(self._refs.path, 'HEAD'), 'rb')
  701. self.assertEqual('ref: refs/heads/master', iter(f).next().rstrip('\n'))
  702. f.close()
  703. # ensure the symbolic link was written through
  704. f = open(os.path.join(self._refs.path, 'refs', 'heads', 'master'), 'rb')
  705. self.assertEqual(ones, f.read()[:40])
  706. f.close()
  707. def test_set_if_equals(self):
  708. RefsContainerTests.test_set_if_equals(self)
  709. # ensure symref was followed
  710. self.assertEqual('9' * 40, self._refs['refs/heads/master'])
  711. # ensure lockfile was deleted
  712. self.assertFalse(os.path.exists(
  713. os.path.join(self._refs.path, 'refs', 'heads', 'master.lock')))
  714. self.assertFalse(os.path.exists(
  715. os.path.join(self._refs.path, 'HEAD.lock')))
  716. def test_add_if_new_packed(self):
  717. # don't overwrite packed ref
  718. self.assertFalse(self._refs.add_if_new('refs/tags/refs-0.1', '9' * 40))
  719. self.assertEqual('df6800012397fb85c56e7418dd4eb9405dee075c',
  720. self._refs['refs/tags/refs-0.1'])
  721. def test_add_if_new_symbolic(self):
  722. # Use an empty repo instead of the default.
  723. tear_down_repo(self._repo)
  724. repo_dir = os.path.join(tempfile.mkdtemp(), 'test')
  725. os.makedirs(repo_dir)
  726. self._repo = Repo.init(repo_dir)
  727. refs = self._repo.refs
  728. nines = '9' * 40
  729. self.assertEqual('ref: refs/heads/master', refs.read_ref('HEAD'))
  730. self.assertFalse('refs/heads/master' in refs)
  731. self.assertTrue(refs.add_if_new('HEAD', nines))
  732. self.assertEqual('ref: refs/heads/master', refs.read_ref('HEAD'))
  733. self.assertEqual(nines, refs['HEAD'])
  734. self.assertEqual(nines, refs['refs/heads/master'])
  735. self.assertFalse(refs.add_if_new('HEAD', '1' * 40))
  736. self.assertEqual(nines, refs['HEAD'])
  737. self.assertEqual(nines, refs['refs/heads/master'])
  738. def test_follow(self):
  739. self.assertEqual(
  740. ('refs/heads/master', '42d06bd4b77fed026b154d16493e5deab78f02ec'),
  741. self._refs._follow('HEAD'))
  742. self.assertEqual(
  743. ('refs/heads/master', '42d06bd4b77fed026b154d16493e5deab78f02ec'),
  744. self._refs._follow('refs/heads/master'))
  745. self.assertRaises(KeyError, self._refs._follow, 'refs/heads/loop')
  746. def test_delitem(self):
  747. RefsContainerTests.test_delitem(self)
  748. ref_file = os.path.join(self._refs.path, 'refs', 'heads', 'master')
  749. self.assertFalse(os.path.exists(ref_file))
  750. self.assertFalse('refs/heads/master' in self._refs.get_packed_refs())
  751. def test_delitem_symbolic(self):
  752. self.assertEqual('ref: refs/heads/master',
  753. self._refs.read_loose_ref('HEAD'))
  754. del self._refs['HEAD']
  755. self.assertRaises(KeyError, lambda: self._refs['HEAD'])
  756. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  757. self._refs['refs/heads/master'])
  758. self.assertFalse(os.path.exists(os.path.join(self._refs.path, 'HEAD')))
  759. def test_remove_if_equals_symref(self):
  760. # HEAD is a symref, so shouldn't equal its dereferenced value
  761. self.assertFalse(self._refs.remove_if_equals(
  762. 'HEAD', '42d06bd4b77fed026b154d16493e5deab78f02ec'))
  763. self.assertTrue(self._refs.remove_if_equals(
  764. 'refs/heads/master', '42d06bd4b77fed026b154d16493e5deab78f02ec'))
  765. self.assertRaises(KeyError, lambda: self._refs['refs/heads/master'])
  766. # HEAD is now a broken symref
  767. self.assertRaises(KeyError, lambda: self._refs['HEAD'])
  768. self.assertEqual('ref: refs/heads/master',
  769. self._refs.read_loose_ref('HEAD'))
  770. self.assertFalse(os.path.exists(
  771. os.path.join(self._refs.path, 'refs', 'heads', 'master.lock')))
  772. self.assertFalse(os.path.exists(
  773. os.path.join(self._refs.path, 'HEAD.lock')))
  774. def test_remove_packed_without_peeled(self):
  775. refs_file = os.path.join(self._repo.path, 'packed-refs')
  776. f = GitFile(refs_file)
  777. refs_data = f.read()
  778. f.close()
  779. f = GitFile(refs_file, 'wb')
  780. f.write('\n'.join(l for l in refs_data.split('\n')
  781. if not l or l[0] not in '#^'))
  782. f.close()
  783. self._repo = Repo(self._repo.path)
  784. refs = self._repo.refs
  785. self.assertTrue(refs.remove_if_equals(
  786. 'refs/heads/packed', '42d06bd4b77fed026b154d16493e5deab78f02ec'))
  787. def test_remove_if_equals_packed(self):
  788. # test removing ref that is only packed
  789. self.assertEqual('df6800012397fb85c56e7418dd4eb9405dee075c',
  790. self._refs['refs/tags/refs-0.1'])
  791. self.assertTrue(
  792. self._refs.remove_if_equals('refs/tags/refs-0.1',
  793. 'df6800012397fb85c56e7418dd4eb9405dee075c'))
  794. self.assertRaises(KeyError, lambda: self._refs['refs/tags/refs-0.1'])
  795. def test_read_ref(self):
  796. self.assertEqual('ref: refs/heads/master', self._refs.read_ref("HEAD"))
  797. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  798. self._refs.read_ref("refs/heads/packed"))
  799. self.assertEqual(None,
  800. self._refs.read_ref("nonexistant"))
  801. _TEST_REFS_SERIALIZED = (
  802. '42d06bd4b77fed026b154d16493e5deab78f02ec\trefs/heads/master\n'
  803. '42d06bd4b77fed026b154d16493e5deab78f02ec\trefs/heads/packed\n'
  804. 'df6800012397fb85c56e7418dd4eb9405dee075c\trefs/tags/refs-0.1\n'
  805. '3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8\trefs/tags/refs-0.2\n')
  806. class InfoRefsContainerTests(TestCase):
  807. def test_invalid_refname(self):
  808. text = _TEST_REFS_SERIALIZED + '00' * 20 + '\trefs/stash\n'
  809. refs = InfoRefsContainer(StringIO(text))
  810. expected_refs = dict(_TEST_REFS)
  811. del expected_refs['HEAD']
  812. expected_refs["refs/stash"] = "00" * 20
  813. self.assertEqual(expected_refs, refs.as_dict())
  814. def test_keys(self):
  815. refs = InfoRefsContainer(StringIO(_TEST_REFS_SERIALIZED))
  816. actual_keys = set(refs.keys())
  817. self.assertEqual(set(refs.allkeys()), actual_keys)
  818. # ignore the symref loop if it exists
  819. actual_keys.discard('refs/heads/loop')
  820. expected_refs = dict(_TEST_REFS)
  821. del expected_refs['HEAD']
  822. self.assertEqual(set(expected_refs.iterkeys()), actual_keys)
  823. actual_keys = refs.keys('refs/heads')
  824. actual_keys.discard('loop')
  825. self.assertEqual(['master', 'packed'], sorted(actual_keys))
  826. self.assertEqual(['refs-0.1', 'refs-0.2'],
  827. sorted(refs.keys('refs/tags')))
  828. def test_as_dict(self):
  829. refs = InfoRefsContainer(StringIO(_TEST_REFS_SERIALIZED))
  830. # refs/heads/loop does not show up even if it exists
  831. expected_refs = dict(_TEST_REFS)
  832. del expected_refs['HEAD']
  833. self.assertEqual(expected_refs, refs.as_dict())
  834. def test_contains(self):
  835. refs = InfoRefsContainer(StringIO(_TEST_REFS_SERIALIZED))
  836. self.assertTrue('refs/heads/master' in refs)
  837. self.assertFalse('refs/heads/bar' in refs)
  838. def test_get_peeled(self):
  839. refs = InfoRefsContainer(StringIO(_TEST_REFS_SERIALIZED))
  840. # refs/heads/loop does not show up even if it exists
  841. self.assertEqual(
  842. _TEST_REFS['refs/heads/master'],
  843. refs.get_peeled('refs/heads/master'))