test_repository.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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_merge_history(self):
  245. r = self._repo = open_repo('simple_merge.git')
  246. shas = [e.commit.id for e in r.get_walker()]
  247. self.assertEqual(shas, ['5dac377bdded4c9aeb8dff595f0faeebcc8498cc',
  248. 'ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  249. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6',
  250. '60dacdc733de308bb77bb76ce0fb0f9b44c9769e',
  251. '0d89f20333fbb1d2f3a94da77f4981373d8f4310'])
  252. def test_revision_history_missing_commit(self):
  253. r = self._repo = open_repo('simple_merge.git')
  254. warnings.simplefilter("ignore", DeprecationWarning)
  255. self.addCleanup(warnings.resetwarnings)
  256. self.assertRaises(errors.MissingCommitError, r.revision_history,
  257. missing_sha)
  258. def test_out_of_order_merge(self):
  259. """Test that revision history is ordered by date, not parent order."""
  260. r = self._repo = open_repo('ooo_merge.git')
  261. shas = [e.commit.id for e in r.get_walker()]
  262. self.assertEqual(shas, ['7601d7f6231db6a57f7bbb79ee52e4d462fd44d1',
  263. 'f507291b64138b875c28e03469025b1ea20bc614',
  264. 'fb5b0425c7ce46959bec94d54b9a157645e114f5',
  265. 'f9e39b120c68182a4ba35349f832d0e4e61f485c'])
  266. def test_get_tags_empty(self):
  267. r = self._repo = open_repo('ooo_merge.git')
  268. self.assertEqual({}, r.refs.as_dict('refs/tags'))
  269. def test_get_config(self):
  270. r = self._repo = open_repo('ooo_merge.git')
  271. self.assertIsInstance(r.get_config(), Config)
  272. def test_get_config_stack(self):
  273. r = self._repo = open_repo('ooo_merge.git')
  274. self.assertIsInstance(r.get_config_stack(), Config)
  275. def test_common_revisions(self):
  276. """
  277. This test demonstrates that ``find_common_revisions()`` actually returns
  278. common heads, not revisions; dulwich already uses
  279. ``find_common_revisions()`` in such a manner (see
  280. ``Repo.fetch_objects()``).
  281. """
  282. expected_shas = set(['60dacdc733de308bb77bb76ce0fb0f9b44c9769e'])
  283. # Source for objects.
  284. r_base = open_repo('simple_merge.git')
  285. # Re-create each-side of the merge in simple_merge.git.
  286. #
  287. # Since the trees and blobs are missing, the repository created is
  288. # corrupted, but we're only checking for commits for the purpose of this
  289. # test, so it's immaterial.
  290. r1_dir = tempfile.mkdtemp()
  291. r1_commits = ['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd', # HEAD
  292. '60dacdc733de308bb77bb76ce0fb0f9b44c9769e',
  293. '0d89f20333fbb1d2f3a94da77f4981373d8f4310']
  294. r2_dir = tempfile.mkdtemp()
  295. r2_commits = ['4cffe90e0a41ad3f5190079d7c8f036bde29cbe6', # HEAD
  296. '60dacdc733de308bb77bb76ce0fb0f9b44c9769e',
  297. '0d89f20333fbb1d2f3a94da77f4981373d8f4310']
  298. try:
  299. r1 = Repo.init_bare(r1_dir)
  300. map(lambda c: r1.object_store.add_object(r_base.get_object(c)), \
  301. r1_commits)
  302. r1.refs['HEAD'] = r1_commits[0]
  303. r2 = Repo.init_bare(r2_dir)
  304. map(lambda c: r2.object_store.add_object(r_base.get_object(c)), \
  305. r2_commits)
  306. r2.refs['HEAD'] = r2_commits[0]
  307. # Finally, the 'real' testing!
  308. shas = r2.object_store.find_common_revisions(r1.get_graph_walker())
  309. self.assertEqual(set(shas), expected_shas)
  310. shas = r1.object_store.find_common_revisions(r2.get_graph_walker())
  311. self.assertEqual(set(shas), expected_shas)
  312. finally:
  313. shutil.rmtree(r1_dir)
  314. shutil.rmtree(r2_dir)
  315. class BuildRepoTests(TestCase):
  316. """Tests that build on-disk repos from scratch.
  317. Repos live in a temp dir and are torn down after each test. They start with
  318. a single commit in master having single file named 'a'.
  319. """
  320. def setUp(self):
  321. super(BuildRepoTests, self).setUp()
  322. repo_dir = os.path.join(tempfile.mkdtemp(), 'test')
  323. os.makedirs(repo_dir)
  324. r = self._repo = Repo.init(repo_dir)
  325. self.assertFalse(r.bare)
  326. self.assertEqual('ref: refs/heads/master', r.refs.read_ref('HEAD'))
  327. self.assertRaises(KeyError, lambda: r.refs['refs/heads/master'])
  328. f = open(os.path.join(r.path, 'a'), 'wb')
  329. try:
  330. f.write('file contents')
  331. finally:
  332. f.close()
  333. r.stage(['a'])
  334. commit_sha = r.do_commit('msg',
  335. committer='Test Committer <test@nodomain.com>',
  336. author='Test Author <test@nodomain.com>',
  337. commit_timestamp=12345, commit_timezone=0,
  338. author_timestamp=12345, author_timezone=0)
  339. self.assertEqual([], r[commit_sha].parents)
  340. self._root_commit = commit_sha
  341. def tearDown(self):
  342. tear_down_repo(self._repo)
  343. super(BuildRepoTests, self).tearDown()
  344. def test_build_repo(self):
  345. r = self._repo
  346. self.assertEqual('ref: refs/heads/master', r.refs.read_ref('HEAD'))
  347. self.assertEqual(self._root_commit, r.refs['refs/heads/master'])
  348. expected_blob = objects.Blob.from_string('file contents')
  349. self.assertEqual(expected_blob.data, r[expected_blob.id].data)
  350. actual_commit = r[self._root_commit]
  351. self.assertEqual('msg', actual_commit.message)
  352. def test_commit_modified(self):
  353. r = self._repo
  354. f = open(os.path.join(r.path, 'a'), 'wb')
  355. try:
  356. f.write('new contents')
  357. finally:
  358. f.close()
  359. r.stage(['a'])
  360. commit_sha = r.do_commit('modified a',
  361. committer='Test Committer <test@nodomain.com>',
  362. author='Test Author <test@nodomain.com>',
  363. commit_timestamp=12395, commit_timezone=0,
  364. author_timestamp=12395, author_timezone=0)
  365. self.assertEqual([self._root_commit], r[commit_sha].parents)
  366. _, blob_id = tree_lookup_path(r.get_object, r[commit_sha].tree, 'a')
  367. self.assertEqual('new contents', r[blob_id].data)
  368. def test_commit_deleted(self):
  369. r = self._repo
  370. os.remove(os.path.join(r.path, 'a'))
  371. r.stage(['a'])
  372. commit_sha = r.do_commit('deleted a',
  373. committer='Test Committer <test@nodomain.com>',
  374. author='Test Author <test@nodomain.com>',
  375. commit_timestamp=12395, commit_timezone=0,
  376. author_timestamp=12395, author_timezone=0)
  377. self.assertEqual([self._root_commit], r[commit_sha].parents)
  378. self.assertEqual([], list(r.open_index()))
  379. tree = r[r[commit_sha].tree]
  380. self.assertEqual([], list(tree.iteritems()))
  381. def test_commit_encoding(self):
  382. r = self._repo
  383. commit_sha = r.do_commit('commit with strange character \xee',
  384. committer='Test Committer <test@nodomain.com>',
  385. author='Test Author <test@nodomain.com>',
  386. commit_timestamp=12395, commit_timezone=0,
  387. author_timestamp=12395, author_timezone=0,
  388. encoding="iso8859-1")
  389. self.assertEqual("iso8859-1", r[commit_sha].encoding)
  390. def test_commit_config_identity(self):
  391. # commit falls back to the users' identity if it wasn't specified
  392. r = self._repo
  393. c = r.get_config()
  394. c.set(("user", ), "name", "Jelmer")
  395. c.set(("user", ), "email", "jelmer@apache.org")
  396. c.write_to_path()
  397. commit_sha = r.do_commit('message')
  398. self.assertEqual(
  399. "Jelmer <jelmer@apache.org>",
  400. r[commit_sha].author)
  401. self.assertEqual(
  402. "Jelmer <jelmer@apache.org>",
  403. r[commit_sha].committer)
  404. def test_commit_fail_ref(self):
  405. r = self._repo
  406. def set_if_equals(name, old_ref, new_ref):
  407. return False
  408. r.refs.set_if_equals = set_if_equals
  409. def add_if_new(name, new_ref):
  410. self.fail('Unexpected call to add_if_new')
  411. r.refs.add_if_new = add_if_new
  412. old_shas = set(r.object_store)
  413. self.assertRaises(errors.CommitError, r.do_commit, 'failed commit',
  414. committer='Test Committer <test@nodomain.com>',
  415. author='Test Author <test@nodomain.com>',
  416. commit_timestamp=12345, commit_timezone=0,
  417. author_timestamp=12345, author_timezone=0)
  418. new_shas = set(r.object_store) - old_shas
  419. self.assertEqual(1, len(new_shas))
  420. # Check that the new commit (now garbage) was added.
  421. new_commit = r[new_shas.pop()]
  422. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  423. self.assertEqual('failed commit', new_commit.message)
  424. def test_commit_branch(self):
  425. r = self._repo
  426. commit_sha = r.do_commit('commit to branch',
  427. committer='Test Committer <test@nodomain.com>',
  428. author='Test Author <test@nodomain.com>',
  429. commit_timestamp=12395, commit_timezone=0,
  430. author_timestamp=12395, author_timezone=0,
  431. ref="refs/heads/new_branch")
  432. self.assertEqual(self._root_commit, r["HEAD"].id)
  433. self.assertEqual(commit_sha, r["refs/heads/new_branch"].id)
  434. self.assertEqual([], r[commit_sha].parents)
  435. self.assertTrue("refs/heads/new_branch" in r)
  436. new_branch_head = commit_sha
  437. commit_sha = r.do_commit('commit to branch 2',
  438. committer='Test Committer <test@nodomain.com>',
  439. author='Test Author <test@nodomain.com>',
  440. commit_timestamp=12395, commit_timezone=0,
  441. author_timestamp=12395, author_timezone=0,
  442. ref="refs/heads/new_branch")
  443. self.assertEqual(self._root_commit, r["HEAD"].id)
  444. self.assertEqual(commit_sha, r["refs/heads/new_branch"].id)
  445. self.assertEqual([new_branch_head], r[commit_sha].parents)
  446. def test_commit_merge_heads(self):
  447. r = self._repo
  448. merge_1 = r.do_commit('commit to branch 2',
  449. committer='Test Committer <test@nodomain.com>',
  450. author='Test Author <test@nodomain.com>',
  451. commit_timestamp=12395, commit_timezone=0,
  452. author_timestamp=12395, author_timezone=0,
  453. ref="refs/heads/new_branch")
  454. commit_sha = r.do_commit('commit with merge',
  455. committer='Test Committer <test@nodomain.com>',
  456. author='Test Author <test@nodomain.com>',
  457. commit_timestamp=12395, commit_timezone=0,
  458. author_timestamp=12395, author_timezone=0,
  459. merge_heads=[merge_1])
  460. self.assertEqual(
  461. [self._root_commit, merge_1],
  462. r[commit_sha].parents)
  463. def test_stage_deleted(self):
  464. r = self._repo
  465. os.remove(os.path.join(r.path, 'a'))
  466. r.stage(['a'])
  467. r.stage(['a']) # double-stage a deleted path
  468. class CheckRefFormatTests(TestCase):
  469. """Tests for the check_ref_format function.
  470. These are the same tests as in the git test suite.
  471. """
  472. def test_valid(self):
  473. self.assertTrue(check_ref_format('heads/foo'))
  474. self.assertTrue(check_ref_format('foo/bar/baz'))
  475. self.assertTrue(check_ref_format('refs///heads/foo'))
  476. self.assertTrue(check_ref_format('foo./bar'))
  477. self.assertTrue(check_ref_format('heads/foo@bar'))
  478. self.assertTrue(check_ref_format('heads/fix.lock.error'))
  479. def test_invalid(self):
  480. self.assertFalse(check_ref_format('foo'))
  481. self.assertFalse(check_ref_format('heads/foo/'))
  482. self.assertFalse(check_ref_format('./foo'))
  483. self.assertFalse(check_ref_format('.refs/foo'))
  484. self.assertFalse(check_ref_format('heads/foo..bar'))
  485. self.assertFalse(check_ref_format('heads/foo?bar'))
  486. self.assertFalse(check_ref_format('heads/foo.lock'))
  487. self.assertFalse(check_ref_format('heads/v@{ation'))
  488. self.assertFalse(check_ref_format('heads/foo\bar'))
  489. ONES = "1" * 40
  490. TWOS = "2" * 40
  491. THREES = "3" * 40
  492. FOURS = "4" * 40
  493. class PackedRefsFileTests(TestCase):
  494. def test_split_ref_line_errors(self):
  495. self.assertRaises(errors.PackedRefsException, _split_ref_line,
  496. 'singlefield')
  497. self.assertRaises(errors.PackedRefsException, _split_ref_line,
  498. 'badsha name')
  499. self.assertRaises(errors.PackedRefsException, _split_ref_line,
  500. '%s bad/../refname' % ONES)
  501. def test_read_without_peeled(self):
  502. f = StringIO('# comment\n%s ref/1\n%s ref/2' % (ONES, TWOS))
  503. self.assertEqual([(ONES, 'ref/1'), (TWOS, 'ref/2')],
  504. list(read_packed_refs(f)))
  505. def test_read_without_peeled_errors(self):
  506. f = StringIO('%s ref/1\n^%s' % (ONES, TWOS))
  507. self.assertRaises(errors.PackedRefsException, list, read_packed_refs(f))
  508. def test_read_with_peeled(self):
  509. f = StringIO('%s ref/1\n%s ref/2\n^%s\n%s ref/4' % (
  510. ONES, TWOS, THREES, FOURS))
  511. self.assertEqual([
  512. (ONES, 'ref/1', None),
  513. (TWOS, 'ref/2', THREES),
  514. (FOURS, 'ref/4', None),
  515. ], list(read_packed_refs_with_peeled(f)))
  516. def test_read_with_peeled_errors(self):
  517. f = StringIO('^%s\n%s ref/1' % (TWOS, ONES))
  518. self.assertRaises(errors.PackedRefsException, list, read_packed_refs(f))
  519. f = StringIO('%s ref/1\n^%s\n^%s' % (ONES, TWOS, THREES))
  520. self.assertRaises(errors.PackedRefsException, list, read_packed_refs(f))
  521. def test_write_with_peeled(self):
  522. f = StringIO()
  523. write_packed_refs(f, {'ref/1': ONES, 'ref/2': TWOS},
  524. {'ref/1': THREES})
  525. self.assertEqual(
  526. "# pack-refs with: peeled\n%s ref/1\n^%s\n%s ref/2\n" % (
  527. ONES, THREES, TWOS), f.getvalue())
  528. def test_write_without_peeled(self):
  529. f = StringIO()
  530. write_packed_refs(f, {'ref/1': ONES, 'ref/2': TWOS})
  531. self.assertEqual("%s ref/1\n%s ref/2\n" % (ONES, TWOS), f.getvalue())
  532. # Dict of refs that we expect all RefsContainerTests subclasses to define.
  533. _TEST_REFS = {
  534. 'HEAD': '42d06bd4b77fed026b154d16493e5deab78f02ec',
  535. 'refs/heads/master': '42d06bd4b77fed026b154d16493e5deab78f02ec',
  536. 'refs/heads/packed': '42d06bd4b77fed026b154d16493e5deab78f02ec',
  537. 'refs/tags/refs-0.1': 'df6800012397fb85c56e7418dd4eb9405dee075c',
  538. 'refs/tags/refs-0.2': '3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8',
  539. }
  540. class RefsContainerTests(object):
  541. def test_keys(self):
  542. actual_keys = set(self._refs.keys())
  543. self.assertEqual(set(self._refs.allkeys()), actual_keys)
  544. # ignore the symref loop if it exists
  545. actual_keys.discard('refs/heads/loop')
  546. self.assertEqual(set(_TEST_REFS.iterkeys()), actual_keys)
  547. actual_keys = self._refs.keys('refs/heads')
  548. actual_keys.discard('loop')
  549. self.assertEqual(['master', 'packed'], sorted(actual_keys))
  550. self.assertEqual(['refs-0.1', 'refs-0.2'],
  551. sorted(self._refs.keys('refs/tags')))
  552. def test_as_dict(self):
  553. # refs/heads/loop does not show up even if it exists
  554. self.assertEqual(_TEST_REFS, self._refs.as_dict())
  555. def test_setitem(self):
  556. self._refs['refs/some/ref'] = '42d06bd4b77fed026b154d16493e5deab78f02ec'
  557. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  558. self._refs['refs/some/ref'])
  559. self.assertRaises(errors.RefFormatError, self._refs.__setitem__,
  560. 'notrefs/foo', '42d06bd4b77fed026b154d16493e5deab78f02ec')
  561. def test_set_if_equals(self):
  562. nines = '9' * 40
  563. self.assertFalse(self._refs.set_if_equals('HEAD', 'c0ffee', nines))
  564. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  565. self._refs['HEAD'])
  566. self.assertTrue(self._refs.set_if_equals(
  567. 'HEAD', '42d06bd4b77fed026b154d16493e5deab78f02ec', nines))
  568. self.assertEqual(nines, self._refs['HEAD'])
  569. self.assertTrue(self._refs.set_if_equals('refs/heads/master', None,
  570. nines))
  571. self.assertEqual(nines, self._refs['refs/heads/master'])
  572. def test_add_if_new(self):
  573. nines = '9' * 40
  574. self.assertFalse(self._refs.add_if_new('refs/heads/master', nines))
  575. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  576. self._refs['refs/heads/master'])
  577. self.assertTrue(self._refs.add_if_new('refs/some/ref', nines))
  578. self.assertEqual(nines, self._refs['refs/some/ref'])
  579. def test_set_symbolic_ref(self):
  580. self._refs.set_symbolic_ref('refs/heads/symbolic', 'refs/heads/master')
  581. self.assertEqual('ref: refs/heads/master',
  582. self._refs.read_loose_ref('refs/heads/symbolic'))
  583. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  584. self._refs['refs/heads/symbolic'])
  585. def test_set_symbolic_ref_overwrite(self):
  586. nines = '9' * 40
  587. self.assertFalse('refs/heads/symbolic' in self._refs)
  588. self._refs['refs/heads/symbolic'] = nines
  589. self.assertEqual(nines, self._refs.read_loose_ref('refs/heads/symbolic'))
  590. self._refs.set_symbolic_ref('refs/heads/symbolic', 'refs/heads/master')
  591. self.assertEqual('ref: refs/heads/master',
  592. self._refs.read_loose_ref('refs/heads/symbolic'))
  593. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  594. self._refs['refs/heads/symbolic'])
  595. def test_check_refname(self):
  596. self._refs._check_refname('HEAD')
  597. self._refs._check_refname('refs/stash')
  598. self._refs._check_refname('refs/heads/foo')
  599. self.assertRaises(errors.RefFormatError, self._refs._check_refname,
  600. 'refs')
  601. self.assertRaises(errors.RefFormatError, self._refs._check_refname,
  602. 'notrefs/foo')
  603. def test_contains(self):
  604. self.assertTrue('refs/heads/master' in self._refs)
  605. self.assertFalse('refs/heads/bar' in self._refs)
  606. def test_delitem(self):
  607. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  608. self._refs['refs/heads/master'])
  609. del self._refs['refs/heads/master']
  610. self.assertRaises(KeyError, lambda: self._refs['refs/heads/master'])
  611. def test_remove_if_equals(self):
  612. self.assertFalse(self._refs.remove_if_equals('HEAD', 'c0ffee'))
  613. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  614. self._refs['HEAD'])
  615. self.assertTrue(self._refs.remove_if_equals(
  616. 'refs/tags/refs-0.2', '3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8'))
  617. self.assertFalse('refs/tags/refs-0.2' in self._refs)
  618. class DictRefsContainerTests(RefsContainerTests, TestCase):
  619. def setUp(self):
  620. TestCase.setUp(self)
  621. self._refs = DictRefsContainer(dict(_TEST_REFS))
  622. def test_invalid_refname(self):
  623. # FIXME: Move this test into RefsContainerTests, but requires
  624. # some way of injecting invalid refs.
  625. self._refs._refs["refs/stash"] = "00" * 20
  626. expected_refs = dict(_TEST_REFS)
  627. expected_refs["refs/stash"] = "00" * 20
  628. self.assertEqual(expected_refs, self._refs.as_dict())
  629. class DiskRefsContainerTests(RefsContainerTests, TestCase):
  630. def setUp(self):
  631. TestCase.setUp(self)
  632. self._repo = open_repo('refs.git')
  633. self._refs = self._repo.refs
  634. def tearDown(self):
  635. tear_down_repo(self._repo)
  636. TestCase.tearDown(self)
  637. def test_get_packed_refs(self):
  638. self.assertEqual({
  639. 'refs/heads/packed': '42d06bd4b77fed026b154d16493e5deab78f02ec',
  640. 'refs/tags/refs-0.1': 'df6800012397fb85c56e7418dd4eb9405dee075c',
  641. }, self._refs.get_packed_refs())
  642. def test_get_peeled_not_packed(self):
  643. # not packed
  644. self.assertEqual(None, self._refs.get_peeled('refs/tags/refs-0.2'))
  645. self.assertEqual('3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8',
  646. self._refs['refs/tags/refs-0.2'])
  647. # packed, known not peelable
  648. self.assertEqual(self._refs['refs/heads/packed'],
  649. self._refs.get_peeled('refs/heads/packed'))
  650. # packed, peeled
  651. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  652. self._refs.get_peeled('refs/tags/refs-0.1'))
  653. def test_setitem(self):
  654. RefsContainerTests.test_setitem(self)
  655. f = open(os.path.join(self._refs.path, 'refs', 'some', 'ref'), 'rb')
  656. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  657. f.read()[:40])
  658. f.close()
  659. def test_setitem_symbolic(self):
  660. ones = '1' * 40
  661. self._refs['HEAD'] = ones
  662. self.assertEqual(ones, self._refs['HEAD'])
  663. # ensure HEAD was not modified
  664. f = open(os.path.join(self._refs.path, 'HEAD'), 'rb')
  665. self.assertEqual('ref: refs/heads/master', iter(f).next().rstrip('\n'))
  666. f.close()
  667. # ensure the symbolic link was written through
  668. f = open(os.path.join(self._refs.path, 'refs', 'heads', 'master'), 'rb')
  669. self.assertEqual(ones, f.read()[:40])
  670. f.close()
  671. def test_set_if_equals(self):
  672. RefsContainerTests.test_set_if_equals(self)
  673. # ensure symref was followed
  674. self.assertEqual('9' * 40, self._refs['refs/heads/master'])
  675. # ensure lockfile was deleted
  676. self.assertFalse(os.path.exists(
  677. os.path.join(self._refs.path, 'refs', 'heads', 'master.lock')))
  678. self.assertFalse(os.path.exists(
  679. os.path.join(self._refs.path, 'HEAD.lock')))
  680. def test_add_if_new_packed(self):
  681. # don't overwrite packed ref
  682. self.assertFalse(self._refs.add_if_new('refs/tags/refs-0.1', '9' * 40))
  683. self.assertEqual('df6800012397fb85c56e7418dd4eb9405dee075c',
  684. self._refs['refs/tags/refs-0.1'])
  685. def test_add_if_new_symbolic(self):
  686. # Use an empty repo instead of the default.
  687. tear_down_repo(self._repo)
  688. repo_dir = os.path.join(tempfile.mkdtemp(), 'test')
  689. os.makedirs(repo_dir)
  690. self._repo = Repo.init(repo_dir)
  691. refs = self._repo.refs
  692. nines = '9' * 40
  693. self.assertEqual('ref: refs/heads/master', refs.read_ref('HEAD'))
  694. self.assertFalse('refs/heads/master' in refs)
  695. self.assertTrue(refs.add_if_new('HEAD', nines))
  696. self.assertEqual('ref: refs/heads/master', refs.read_ref('HEAD'))
  697. self.assertEqual(nines, refs['HEAD'])
  698. self.assertEqual(nines, refs['refs/heads/master'])
  699. self.assertFalse(refs.add_if_new('HEAD', '1' * 40))
  700. self.assertEqual(nines, refs['HEAD'])
  701. self.assertEqual(nines, refs['refs/heads/master'])
  702. def test_follow(self):
  703. self.assertEqual(
  704. ('refs/heads/master', '42d06bd4b77fed026b154d16493e5deab78f02ec'),
  705. self._refs._follow('HEAD'))
  706. self.assertEqual(
  707. ('refs/heads/master', '42d06bd4b77fed026b154d16493e5deab78f02ec'),
  708. self._refs._follow('refs/heads/master'))
  709. self.assertRaises(KeyError, self._refs._follow, 'refs/heads/loop')
  710. def test_delitem(self):
  711. RefsContainerTests.test_delitem(self)
  712. ref_file = os.path.join(self._refs.path, 'refs', 'heads', 'master')
  713. self.assertFalse(os.path.exists(ref_file))
  714. self.assertFalse('refs/heads/master' in self._refs.get_packed_refs())
  715. def test_delitem_symbolic(self):
  716. self.assertEqual('ref: refs/heads/master',
  717. self._refs.read_loose_ref('HEAD'))
  718. del self._refs['HEAD']
  719. self.assertRaises(KeyError, lambda: self._refs['HEAD'])
  720. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  721. self._refs['refs/heads/master'])
  722. self.assertFalse(os.path.exists(os.path.join(self._refs.path, 'HEAD')))
  723. def test_remove_if_equals_symref(self):
  724. # HEAD is a symref, so shouldn't equal its dereferenced value
  725. self.assertFalse(self._refs.remove_if_equals(
  726. 'HEAD', '42d06bd4b77fed026b154d16493e5deab78f02ec'))
  727. self.assertTrue(self._refs.remove_if_equals(
  728. 'refs/heads/master', '42d06bd4b77fed026b154d16493e5deab78f02ec'))
  729. self.assertRaises(KeyError, lambda: self._refs['refs/heads/master'])
  730. # HEAD is now a broken symref
  731. self.assertRaises(KeyError, lambda: self._refs['HEAD'])
  732. self.assertEqual('ref: refs/heads/master',
  733. self._refs.read_loose_ref('HEAD'))
  734. self.assertFalse(os.path.exists(
  735. os.path.join(self._refs.path, 'refs', 'heads', 'master.lock')))
  736. self.assertFalse(os.path.exists(
  737. os.path.join(self._refs.path, 'HEAD.lock')))
  738. def test_remove_packed_without_peeled(self):
  739. refs_file = os.path.join(self._repo.path, 'packed-refs')
  740. f = GitFile(refs_file)
  741. refs_data = f.read()
  742. f.close()
  743. f = GitFile(refs_file, 'wb')
  744. f.write('\n'.join(l for l in refs_data.split('\n')
  745. if not l or l[0] not in '#^'))
  746. f.close()
  747. self._repo = Repo(self._repo.path)
  748. refs = self._repo.refs
  749. self.assertTrue(refs.remove_if_equals(
  750. 'refs/heads/packed', '42d06bd4b77fed026b154d16493e5deab78f02ec'))
  751. def test_remove_if_equals_packed(self):
  752. # test removing ref that is only packed
  753. self.assertEqual('df6800012397fb85c56e7418dd4eb9405dee075c',
  754. self._refs['refs/tags/refs-0.1'])
  755. self.assertTrue(
  756. self._refs.remove_if_equals('refs/tags/refs-0.1',
  757. 'df6800012397fb85c56e7418dd4eb9405dee075c'))
  758. self.assertRaises(KeyError, lambda: self._refs['refs/tags/refs-0.1'])
  759. def test_read_ref(self):
  760. self.assertEqual('ref: refs/heads/master', self._refs.read_ref("HEAD"))
  761. self.assertEqual('42d06bd4b77fed026b154d16493e5deab78f02ec',
  762. self._refs.read_ref("refs/heads/packed"))
  763. self.assertEqual(None,
  764. self._refs.read_ref("nonexistant"))
  765. _TEST_REFS_SERIALIZED = (
  766. '42d06bd4b77fed026b154d16493e5deab78f02ec\trefs/heads/master\n'
  767. '42d06bd4b77fed026b154d16493e5deab78f02ec\trefs/heads/packed\n'
  768. 'df6800012397fb85c56e7418dd4eb9405dee075c\trefs/tags/refs-0.1\n'
  769. '3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8\trefs/tags/refs-0.2\n')
  770. class InfoRefsContainerTests(TestCase):
  771. def test_invalid_refname(self):
  772. text = _TEST_REFS_SERIALIZED + '00' * 20 + '\trefs/stash\n'
  773. refs = InfoRefsContainer(StringIO(text))
  774. expected_refs = dict(_TEST_REFS)
  775. del expected_refs['HEAD']
  776. expected_refs["refs/stash"] = "00" * 20
  777. self.assertEqual(expected_refs, refs.as_dict())
  778. def test_keys(self):
  779. refs = InfoRefsContainer(StringIO(_TEST_REFS_SERIALIZED))
  780. actual_keys = set(refs.keys())
  781. self.assertEqual(set(refs.allkeys()), actual_keys)
  782. # ignore the symref loop if it exists
  783. actual_keys.discard('refs/heads/loop')
  784. expected_refs = dict(_TEST_REFS)
  785. del expected_refs['HEAD']
  786. self.assertEqual(set(expected_refs.iterkeys()), actual_keys)
  787. actual_keys = refs.keys('refs/heads')
  788. actual_keys.discard('loop')
  789. self.assertEqual(['master', 'packed'], sorted(actual_keys))
  790. self.assertEqual(['refs-0.1', 'refs-0.2'],
  791. sorted(refs.keys('refs/tags')))
  792. def test_as_dict(self):
  793. refs = InfoRefsContainer(StringIO(_TEST_REFS_SERIALIZED))
  794. # refs/heads/loop does not show up even if it exists
  795. expected_refs = dict(_TEST_REFS)
  796. del expected_refs['HEAD']
  797. self.assertEqual(expected_refs, refs.as_dict())
  798. def test_contains(self):
  799. refs = InfoRefsContainer(StringIO(_TEST_REFS_SERIALIZED))
  800. self.assertTrue('refs/heads/master' in refs)
  801. self.assertFalse('refs/heads/bar' in refs)
  802. def test_get_peeled(self):
  803. refs = InfoRefsContainer(StringIO(_TEST_REFS_SERIALIZED))
  804. # refs/heads/loop does not show up even if it exists
  805. self.assertEqual(
  806. _TEST_REFS['refs/heads/master'],
  807. refs.get_peeled('refs/heads/master'))