test_objects.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. # test_objects.py -- tests for objects.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 git base objects."""
  20. # TODO: Round-trip parse-serialize-parse and serialize-parse-serialize tests.
  21. from io import BytesIO
  22. import datetime
  23. from itertools import (
  24. permutations,
  25. )
  26. import os
  27. import stat
  28. import warnings
  29. from dulwich.errors import (
  30. ObjectFormatException,
  31. )
  32. from dulwich.objects import (
  33. Blob,
  34. Tree,
  35. Commit,
  36. ShaFile,
  37. Tag,
  38. format_timezone,
  39. hex_to_sha,
  40. sha_to_hex,
  41. hex_to_filename,
  42. check_hexsha,
  43. check_identity,
  44. parse_timezone,
  45. TreeEntry,
  46. parse_tree,
  47. _parse_tree_py,
  48. sorted_tree_items,
  49. _sorted_tree_items_py,
  50. )
  51. from dulwich.tests import (
  52. TestCase,
  53. )
  54. from dulwich.tests.utils import (
  55. make_commit,
  56. make_object,
  57. functest_builder,
  58. ext_functest_builder,
  59. )
  60. a_sha = '6f670c0fb53f9463760b7295fbb814e965fb20c8'
  61. b_sha = '2969be3e8ee1c0222396a5611407e4769f14e54b'
  62. c_sha = '954a536f7819d40e6f637f849ee187dd10066349'
  63. tree_sha = '70c190eb48fa8bbb50ddc692a17b44cb781af7f6'
  64. tag_sha = '71033db03a03c6a36721efcf1968dd8f8e0cf023'
  65. class TestHexToSha(TestCase):
  66. def test_simple(self):
  67. self.assertEqual("\xab\xcd" * 10, hex_to_sha("abcd" * 10))
  68. def test_reverse(self):
  69. self.assertEqual("abcd" * 10, sha_to_hex("\xab\xcd" * 10))
  70. class BlobReadTests(TestCase):
  71. """Test decompression of blobs"""
  72. def get_sha_file(self, cls, base, sha):
  73. dir = os.path.join(os.path.dirname(__file__), 'data', base)
  74. return cls.from_path(hex_to_filename(dir, sha))
  75. def get_blob(self, sha):
  76. """Return the blob named sha from the test data dir"""
  77. return self.get_sha_file(Blob, 'blobs', sha)
  78. def get_tree(self, sha):
  79. return self.get_sha_file(Tree, 'trees', sha)
  80. def get_tag(self, sha):
  81. return self.get_sha_file(Tag, 'tags', sha)
  82. def commit(self, sha):
  83. return self.get_sha_file(Commit, 'commits', sha)
  84. def test_decompress_simple_blob(self):
  85. b = self.get_blob(a_sha)
  86. self.assertEqual(b.data, 'test 1\n')
  87. self.assertEqual(b.sha().hexdigest(), a_sha)
  88. def test_hash(self):
  89. b = self.get_blob(a_sha)
  90. self.assertEqual(hash(b.id), hash(b))
  91. def test_parse_empty_blob_object(self):
  92. sha = 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391'
  93. b = self.get_blob(sha)
  94. self.assertEqual(b.data, '')
  95. self.assertEqual(b.id, sha)
  96. self.assertEqual(b.sha().hexdigest(), sha)
  97. def test_create_blob_from_string(self):
  98. string = 'test 2\n'
  99. b = Blob.from_string(string)
  100. self.assertEqual(b.data, string)
  101. self.assertEqual(b.sha().hexdigest(), b_sha)
  102. def test_legacy_from_file(self):
  103. b1 = Blob.from_string("foo")
  104. b_raw = b1.as_legacy_object()
  105. b2 = b1.from_file(BytesIO(b_raw))
  106. self.assertEqual(b1, b2)
  107. def test_chunks(self):
  108. string = 'test 5\n'
  109. b = Blob.from_string(string)
  110. self.assertEqual([string], b.chunked)
  111. def test_set_chunks(self):
  112. b = Blob()
  113. b.chunked = ['te', 'st', ' 5\n']
  114. self.assertEqual('test 5\n', b.data)
  115. b.chunked = ['te', 'st', ' 6\n']
  116. self.assertEqual('test 6\n', b.as_raw_string())
  117. def test_parse_legacy_blob(self):
  118. string = 'test 3\n'
  119. b = self.get_blob(c_sha)
  120. self.assertEqual(b.data, string)
  121. self.assertEqual(b.sha().hexdigest(), c_sha)
  122. def test_eq(self):
  123. blob1 = self.get_blob(a_sha)
  124. blob2 = self.get_blob(a_sha)
  125. self.assertEqual(blob1, blob2)
  126. def test_read_tree_from_file(self):
  127. t = self.get_tree(tree_sha)
  128. self.assertEqual(t.items()[0], ('a', 33188, a_sha))
  129. self.assertEqual(t.items()[1], ('b', 33188, b_sha))
  130. def test_read_tag_from_file(self):
  131. t = self.get_tag(tag_sha)
  132. self.assertEqual(t.object,
  133. (Commit, '51b668fd5bf7061b7d6fa525f88803e6cfadaa51'))
  134. self.assertEqual(t.name,'signed')
  135. self.assertEqual(t.tagger,'Ali Sabil <ali.sabil@gmail.com>')
  136. self.assertEqual(t.tag_time, 1231203091)
  137. self.assertEqual(t.message, 'This is a signed tag\n-----BEGIN PGP SIGNATURE-----\nVersion: GnuPG v1.4.9 (GNU/Linux)\n\niEYEABECAAYFAkliqx8ACgkQqSMmLy9u/kcx5ACfakZ9NnPl02tOyYP6pkBoEkU1\n5EcAn0UFgokaSvS371Ym/4W9iJj6vh3h\n=ql7y\n-----END PGP SIGNATURE-----\n')
  138. def test_read_commit_from_file(self):
  139. sha = '60dacdc733de308bb77bb76ce0fb0f9b44c9769e'
  140. c = self.commit(sha)
  141. self.assertEqual(c.tree, tree_sha)
  142. self.assertEqual(c.parents,
  143. ['0d89f20333fbb1d2f3a94da77f4981373d8f4310'])
  144. self.assertEqual(c.author,
  145. 'James Westby <jw+debian@jameswestby.net>')
  146. self.assertEqual(c.committer,
  147. 'James Westby <jw+debian@jameswestby.net>')
  148. self.assertEqual(c.commit_time, 1174759230)
  149. self.assertEqual(c.commit_timezone, 0)
  150. self.assertEqual(c.author_timezone, 0)
  151. self.assertEqual(c.message, 'Test commit\n')
  152. def test_read_commit_no_parents(self):
  153. sha = '0d89f20333fbb1d2f3a94da77f4981373d8f4310'
  154. c = self.commit(sha)
  155. self.assertEqual(c.tree, '90182552c4a85a45ec2a835cadc3451bebdfe870')
  156. self.assertEqual(c.parents, [])
  157. self.assertEqual(c.author,
  158. 'James Westby <jw+debian@jameswestby.net>')
  159. self.assertEqual(c.committer,
  160. 'James Westby <jw+debian@jameswestby.net>')
  161. self.assertEqual(c.commit_time, 1174758034)
  162. self.assertEqual(c.commit_timezone, 0)
  163. self.assertEqual(c.author_timezone, 0)
  164. self.assertEqual(c.message, 'Test commit\n')
  165. def test_read_commit_two_parents(self):
  166. sha = '5dac377bdded4c9aeb8dff595f0faeebcc8498cc'
  167. c = self.commit(sha)
  168. self.assertEqual(c.tree, 'd80c186a03f423a81b39df39dc87fd269736ca86')
  169. self.assertEqual(c.parents, ['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  170. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'])
  171. self.assertEqual(c.author,
  172. 'James Westby <jw+debian@jameswestby.net>')
  173. self.assertEqual(c.committer,
  174. 'James Westby <jw+debian@jameswestby.net>')
  175. self.assertEqual(c.commit_time, 1174773719)
  176. self.assertEqual(c.commit_timezone, 0)
  177. self.assertEqual(c.author_timezone, 0)
  178. self.assertEqual(c.message, 'Merge ../b\n')
  179. def test_stub_sha(self):
  180. sha = '5' * 40
  181. c = make_commit(id=sha, message='foo')
  182. self.assertTrue(isinstance(c, Commit))
  183. self.assertEqual(sha, c.id)
  184. self.assertNotEqual(sha, c._make_sha())
  185. class ShaFileCheckTests(TestCase):
  186. def assertCheckFails(self, cls, data):
  187. obj = cls()
  188. def do_check():
  189. obj.set_raw_string(data)
  190. obj.check()
  191. self.assertRaises(ObjectFormatException, do_check)
  192. def assertCheckSucceeds(self, cls, data):
  193. obj = cls()
  194. obj.set_raw_string(data)
  195. self.assertEqual(None, obj.check())
  196. small_buffer_zlib_object = (
  197. "\x48\x89\x15\xcc\x31\x0e\xc2\x30\x0c\x40\x51\xe6"
  198. "\x9c\xc2\x3b\xaa\x64\x37\xc4\xc1\x12\x42\x5c\xc5"
  199. "\x49\xac\x52\xd4\x92\xaa\x78\xe1\xf6\x94\xed\xeb"
  200. "\x0d\xdf\x75\x02\xa2\x7c\xea\xe5\x65\xd5\x81\x8b"
  201. "\x9a\x61\xba\xa0\xa9\x08\x36\xc9\x4c\x1a\xad\x88"
  202. "\x16\xba\x46\xc4\xa8\x99\x6a\x64\xe1\xe0\xdf\xcd"
  203. "\xa0\xf6\x75\x9d\x3d\xf8\xf1\xd0\x77\xdb\xfb\xdc"
  204. "\x86\xa3\x87\xf1\x2f\x93\xed\x00\xb7\xc7\xd2\xab"
  205. "\x2e\xcf\xfe\xf1\x3b\x50\xa4\x91\x53\x12\x24\x38"
  206. "\x23\x21\x86\xf0\x03\x2f\x91\x24\x52"
  207. )
  208. class ShaFileTests(TestCase):
  209. def test_deflated_smaller_window_buffer(self):
  210. # zlib on some systems uses smaller buffers,
  211. # resulting in a different header.
  212. # See https://github.com/libgit2/libgit2/pull/464
  213. sf = ShaFile.from_file(BytesIO(small_buffer_zlib_object))
  214. self.assertEqual(sf.type_name, "tag")
  215. self.assertEqual(sf.tagger, " <@localhost>")
  216. class CommitSerializationTests(TestCase):
  217. def make_commit(self, **kwargs):
  218. attrs = {'tree': 'd80c186a03f423a81b39df39dc87fd269736ca86',
  219. 'parents': ['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  220. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'],
  221. 'author': 'James Westby <jw+debian@jameswestby.net>',
  222. 'committer': 'James Westby <jw+debian@jameswestby.net>',
  223. 'commit_time': 1174773719,
  224. 'author_time': 1174773719,
  225. 'commit_timezone': 0,
  226. 'author_timezone': 0,
  227. 'message': 'Merge ../b\n'}
  228. attrs.update(kwargs)
  229. return make_commit(**attrs)
  230. def test_encoding(self):
  231. c = self.make_commit(encoding='iso8859-1')
  232. self.assertTrue('encoding iso8859-1\n' in c.as_raw_string())
  233. def test_short_timestamp(self):
  234. c = self.make_commit(commit_time=30)
  235. c1 = Commit()
  236. c1.set_raw_string(c.as_raw_string())
  237. self.assertEqual(30, c1.commit_time)
  238. def test_raw_length(self):
  239. c = self.make_commit()
  240. self.assertEqual(len(c.as_raw_string()), c.raw_length())
  241. def test_simple(self):
  242. c = self.make_commit()
  243. self.assertEqual(c.id, '5dac377bdded4c9aeb8dff595f0faeebcc8498cc')
  244. self.assertEqual(
  245. 'tree d80c186a03f423a81b39df39dc87fd269736ca86\n'
  246. 'parent ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd\n'
  247. 'parent 4cffe90e0a41ad3f5190079d7c8f036bde29cbe6\n'
  248. 'author James Westby <jw+debian@jameswestby.net> '
  249. '1174773719 +0000\n'
  250. 'committer James Westby <jw+debian@jameswestby.net> '
  251. '1174773719 +0000\n'
  252. '\n'
  253. 'Merge ../b\n', c.as_raw_string())
  254. def test_timezone(self):
  255. c = self.make_commit(commit_timezone=(5 * 60))
  256. self.assertTrue(" +0005\n" in c.as_raw_string())
  257. def test_neg_timezone(self):
  258. c = self.make_commit(commit_timezone=(-1 * 3600))
  259. self.assertTrue(" -0100\n" in c.as_raw_string())
  260. def test_deserialize(self):
  261. c = self.make_commit()
  262. d = Commit()
  263. d._deserialize(c.as_raw_chunks())
  264. self.assertEqual(c, d)
  265. def test_serialize_mergetag(self):
  266. tag = make_object(
  267. Tag, object=(Commit, "a38d6181ff27824c79fc7df825164a212eff6a3f"),
  268. object_type_name="commit",
  269. name="v2.6.22-rc7",
  270. tag_time=1183319674,
  271. tag_timezone=0,
  272. tagger="Linus Torvalds <torvalds@woody.linux-foundation.org>",
  273. message=default_message)
  274. commit = self.make_commit(mergetag=[tag])
  275. self.assertEqual("""tree d80c186a03f423a81b39df39dc87fd269736ca86
  276. parent ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd
  277. parent 4cffe90e0a41ad3f5190079d7c8f036bde29cbe6
  278. author James Westby <jw+debian@jameswestby.net> 1174773719 +0000
  279. committer James Westby <jw+debian@jameswestby.net> 1174773719 +0000
  280. mergetag object a38d6181ff27824c79fc7df825164a212eff6a3f
  281. type commit
  282. tag v2.6.22-rc7
  283. tagger Linus Torvalds <torvalds@woody.linux-foundation.org> 1183319674 +0000
  284. Linux 2.6.22-rc7
  285. -----BEGIN PGP SIGNATURE-----
  286. Version: GnuPG v1.4.7 (GNU/Linux)
  287. iD8DBQBGiAaAF3YsRnbiHLsRAitMAKCiLboJkQECM/jpYsY3WPfvUgLXkACgg3ql
  288. OK2XeQOiEeXtT76rV4t2WR4=
  289. =ivrA
  290. -----END PGP SIGNATURE-----
  291. Merge ../b
  292. """, commit.as_raw_string())
  293. def test_serialize_mergetags(self):
  294. tag = make_object(
  295. Tag, object=(Commit, "a38d6181ff27824c79fc7df825164a212eff6a3f"),
  296. object_type_name="commit",
  297. name="v2.6.22-rc7",
  298. tag_time=1183319674,
  299. tag_timezone=0,
  300. tagger="Linus Torvalds <torvalds@woody.linux-foundation.org>",
  301. message=default_message)
  302. commit = self.make_commit(mergetag=[tag, tag])
  303. self.assertEqual("""tree d80c186a03f423a81b39df39dc87fd269736ca86
  304. parent ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd
  305. parent 4cffe90e0a41ad3f5190079d7c8f036bde29cbe6
  306. author James Westby <jw+debian@jameswestby.net> 1174773719 +0000
  307. committer James Westby <jw+debian@jameswestby.net> 1174773719 +0000
  308. mergetag object a38d6181ff27824c79fc7df825164a212eff6a3f
  309. type commit
  310. tag v2.6.22-rc7
  311. tagger Linus Torvalds <torvalds@woody.linux-foundation.org> 1183319674 +0000
  312. Linux 2.6.22-rc7
  313. -----BEGIN PGP SIGNATURE-----
  314. Version: GnuPG v1.4.7 (GNU/Linux)
  315. iD8DBQBGiAaAF3YsRnbiHLsRAitMAKCiLboJkQECM/jpYsY3WPfvUgLXkACgg3ql
  316. OK2XeQOiEeXtT76rV4t2WR4=
  317. =ivrA
  318. -----END PGP SIGNATURE-----
  319. mergetag object a38d6181ff27824c79fc7df825164a212eff6a3f
  320. type commit
  321. tag v2.6.22-rc7
  322. tagger Linus Torvalds <torvalds@woody.linux-foundation.org> 1183319674 +0000
  323. Linux 2.6.22-rc7
  324. -----BEGIN PGP SIGNATURE-----
  325. Version: GnuPG v1.4.7 (GNU/Linux)
  326. iD8DBQBGiAaAF3YsRnbiHLsRAitMAKCiLboJkQECM/jpYsY3WPfvUgLXkACgg3ql
  327. OK2XeQOiEeXtT76rV4t2WR4=
  328. =ivrA
  329. -----END PGP SIGNATURE-----
  330. Merge ../b
  331. """, commit.as_raw_string())
  332. def test_deserialize_mergetag(self):
  333. tag = make_object(
  334. Tag, object=(Commit, "a38d6181ff27824c79fc7df825164a212eff6a3f"),
  335. object_type_name="commit",
  336. name="v2.6.22-rc7",
  337. tag_time=1183319674,
  338. tag_timezone=0,
  339. tagger="Linus Torvalds <torvalds@woody.linux-foundation.org>",
  340. message=default_message)
  341. commit = self.make_commit(mergetag=[tag])
  342. d = Commit()
  343. d._deserialize(commit.as_raw_chunks())
  344. self.assertEqual(commit, d)
  345. def test_deserialize_mergetags(self):
  346. tag = make_object(
  347. Tag, object=(Commit, "a38d6181ff27824c79fc7df825164a212eff6a3f"),
  348. object_type_name="commit",
  349. name="v2.6.22-rc7",
  350. tag_time=1183319674,
  351. tag_timezone=0,
  352. tagger="Linus Torvalds <torvalds@woody.linux-foundation.org>",
  353. message=default_message)
  354. commit = self.make_commit(mergetag=[tag, tag])
  355. d = Commit()
  356. d._deserialize(commit.as_raw_chunks())
  357. self.assertEquals(commit, d)
  358. default_committer = 'James Westby <jw+debian@jameswestby.net> 1174773719 +0000'
  359. class CommitParseTests(ShaFileCheckTests):
  360. def make_commit_lines(self,
  361. tree='d80c186a03f423a81b39df39dc87fd269736ca86',
  362. parents=['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  363. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'],
  364. author=default_committer,
  365. committer=default_committer,
  366. encoding=None,
  367. message='Merge ../b\n',
  368. extra=None):
  369. lines = []
  370. if tree is not None:
  371. lines.append('tree %s' % tree)
  372. if parents is not None:
  373. lines.extend('parent %s' % p for p in parents)
  374. if author is not None:
  375. lines.append('author %s' % author)
  376. if committer is not None:
  377. lines.append('committer %s' % committer)
  378. if encoding is not None:
  379. lines.append('encoding %s' % encoding)
  380. if extra is not None:
  381. for name, value in sorted(extra.iteritems()):
  382. lines.append('%s %s' % (name, value))
  383. lines.append('')
  384. if message is not None:
  385. lines.append(message)
  386. return lines
  387. def make_commit_text(self, **kwargs):
  388. return '\n'.join(self.make_commit_lines(**kwargs))
  389. def test_simple(self):
  390. c = Commit.from_string(self.make_commit_text())
  391. self.assertEqual('Merge ../b\n', c.message)
  392. self.assertEqual('James Westby <jw+debian@jameswestby.net>', c.author)
  393. self.assertEqual('James Westby <jw+debian@jameswestby.net>',
  394. c.committer)
  395. self.assertEqual('d80c186a03f423a81b39df39dc87fd269736ca86', c.tree)
  396. self.assertEqual(['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  397. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'],
  398. c.parents)
  399. expected_time = datetime.datetime(2007, 3, 24, 22, 1, 59)
  400. self.assertEqual(expected_time,
  401. datetime.datetime.utcfromtimestamp(c.commit_time))
  402. self.assertEqual(0, c.commit_timezone)
  403. self.assertEqual(expected_time,
  404. datetime.datetime.utcfromtimestamp(c.author_time))
  405. self.assertEqual(0, c.author_timezone)
  406. self.assertEqual(None, c.encoding)
  407. def test_custom(self):
  408. c = Commit.from_string(self.make_commit_text(
  409. extra={'extra-field': 'data'}))
  410. self.assertEqual([('extra-field', 'data')], c.extra)
  411. def test_encoding(self):
  412. c = Commit.from_string(self.make_commit_text(encoding='UTF-8'))
  413. self.assertEqual('UTF-8', c.encoding)
  414. def test_check(self):
  415. self.assertCheckSucceeds(Commit, self.make_commit_text())
  416. self.assertCheckSucceeds(Commit, self.make_commit_text(parents=None))
  417. self.assertCheckSucceeds(Commit,
  418. self.make_commit_text(encoding='UTF-8'))
  419. self.assertCheckFails(Commit, self.make_commit_text(tree='xxx'))
  420. self.assertCheckFails(Commit, self.make_commit_text(
  421. parents=[a_sha, 'xxx']))
  422. bad_committer = "some guy without an email address 1174773719 +0000"
  423. self.assertCheckFails(Commit,
  424. self.make_commit_text(committer=bad_committer))
  425. self.assertCheckFails(Commit,
  426. self.make_commit_text(author=bad_committer))
  427. self.assertCheckFails(Commit, self.make_commit_text(author=None))
  428. self.assertCheckFails(Commit, self.make_commit_text(committer=None))
  429. self.assertCheckFails(Commit, self.make_commit_text(
  430. author=None, committer=None))
  431. def test_check_duplicates(self):
  432. # duplicate each of the header fields
  433. for i in range(5):
  434. lines = self.make_commit_lines(parents=[a_sha], encoding='UTF-8')
  435. lines.insert(i, lines[i])
  436. text = '\n'.join(lines)
  437. if lines[i].startswith('parent'):
  438. # duplicate parents are ok for now
  439. self.assertCheckSucceeds(Commit, text)
  440. else:
  441. self.assertCheckFails(Commit, text)
  442. def test_check_order(self):
  443. lines = self.make_commit_lines(parents=[a_sha], encoding='UTF-8')
  444. headers = lines[:5]
  445. rest = lines[5:]
  446. # of all possible permutations, ensure only the original succeeds
  447. for perm in permutations(headers):
  448. perm = list(perm)
  449. text = '\n'.join(perm + rest)
  450. if perm == headers:
  451. self.assertCheckSucceeds(Commit, text)
  452. else:
  453. self.assertCheckFails(Commit, text)
  454. _TREE_ITEMS = {
  455. 'a.c': (0o100755, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  456. 'a': (stat.S_IFDIR, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  457. 'a/c': (stat.S_IFDIR, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  458. }
  459. _SORTED_TREE_ITEMS = [
  460. TreeEntry('a.c', 0o100755, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  461. TreeEntry('a', stat.S_IFDIR, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  462. TreeEntry('a/c', stat.S_IFDIR, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  463. ]
  464. class TreeTests(ShaFileCheckTests):
  465. def test_add(self):
  466. myhexsha = "d80c186a03f423a81b39df39dc87fd269736ca86"
  467. x = Tree()
  468. x.add("myname", 0o100755, myhexsha)
  469. self.assertEqual(x["myname"], (0o100755, myhexsha))
  470. self.assertEqual('100755 myname\0' + hex_to_sha(myhexsha),
  471. x.as_raw_string())
  472. def test_add_old_order(self):
  473. myhexsha = "d80c186a03f423a81b39df39dc87fd269736ca86"
  474. x = Tree()
  475. warnings.simplefilter("ignore", DeprecationWarning)
  476. try:
  477. x.add(0o100755, "myname", myhexsha)
  478. finally:
  479. warnings.resetwarnings()
  480. self.assertEqual(x["myname"], (0o100755, myhexsha))
  481. self.assertEqual('100755 myname\0' + hex_to_sha(myhexsha),
  482. x.as_raw_string())
  483. def test_simple(self):
  484. myhexsha = "d80c186a03f423a81b39df39dc87fd269736ca86"
  485. x = Tree()
  486. x["myname"] = (0o100755, myhexsha)
  487. self.assertEqual('100755 myname\0' + hex_to_sha(myhexsha),
  488. x.as_raw_string())
  489. def test_tree_update_id(self):
  490. x = Tree()
  491. x["a.c"] = (0o100755, "d80c186a03f423a81b39df39dc87fd269736ca86")
  492. self.assertEqual("0c5c6bc2c081accfbc250331b19e43b904ab9cdd", x.id)
  493. x["a.b"] = (stat.S_IFDIR, "d80c186a03f423a81b39df39dc87fd269736ca86")
  494. self.assertEqual("07bfcb5f3ada15bbebdfa3bbb8fd858a363925c8", x.id)
  495. def test_tree_iteritems_dir_sort(self):
  496. x = Tree()
  497. for name, item in _TREE_ITEMS.iteritems():
  498. x[name] = item
  499. self.assertEqual(_SORTED_TREE_ITEMS, list(x.iteritems()))
  500. def test_tree_items_dir_sort(self):
  501. x = Tree()
  502. for name, item in _TREE_ITEMS.iteritems():
  503. x[name] = item
  504. self.assertEqual(_SORTED_TREE_ITEMS, x.items())
  505. def _do_test_parse_tree(self, parse_tree):
  506. dir = os.path.join(os.path.dirname(__file__), 'data', 'trees')
  507. o = Tree.from_path(hex_to_filename(dir, tree_sha))
  508. self.assertEqual([('a', 0o100644, a_sha), ('b', 0o100644, b_sha)],
  509. list(parse_tree(o.as_raw_string())))
  510. # test a broken tree that has a leading 0 on the file mode
  511. broken_tree = '0100644 foo\0' + hex_to_sha(a_sha)
  512. def eval_parse_tree(*args, **kwargs):
  513. return list(parse_tree(*args, **kwargs))
  514. self.assertEqual([('foo', 0o100644, a_sha)],
  515. eval_parse_tree(broken_tree))
  516. self.assertRaises(ObjectFormatException,
  517. eval_parse_tree, broken_tree, strict=True)
  518. test_parse_tree = functest_builder(_do_test_parse_tree, _parse_tree_py)
  519. test_parse_tree_extension = ext_functest_builder(_do_test_parse_tree,
  520. parse_tree)
  521. def _do_test_sorted_tree_items(self, sorted_tree_items):
  522. def do_sort(entries):
  523. return list(sorted_tree_items(entries, False))
  524. actual = do_sort(_TREE_ITEMS)
  525. self.assertEqual(_SORTED_TREE_ITEMS, actual)
  526. self.assertTrue(isinstance(actual[0], TreeEntry))
  527. # C/Python implementations may differ in specific error types, but
  528. # should all error on invalid inputs.
  529. # For example, the C implementation has stricter type checks, so may
  530. # raise TypeError where the Python implementation raises AttributeError.
  531. errors = (TypeError, ValueError, AttributeError)
  532. self.assertRaises(errors, do_sort, 'foo')
  533. self.assertRaises(errors, do_sort, {'foo': (1, 2, 3)})
  534. myhexsha = 'd80c186a03f423a81b39df39dc87fd269736ca86'
  535. self.assertRaises(errors, do_sort, {'foo': ('xxx', myhexsha)})
  536. self.assertRaises(errors, do_sort, {'foo': (0o100755, 12345)})
  537. test_sorted_tree_items = functest_builder(_do_test_sorted_tree_items,
  538. _sorted_tree_items_py)
  539. test_sorted_tree_items_extension = ext_functest_builder(
  540. _do_test_sorted_tree_items, sorted_tree_items)
  541. def _do_test_sorted_tree_items_name_order(self, sorted_tree_items):
  542. self.assertEqual([
  543. TreeEntry('a', stat.S_IFDIR,
  544. 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  545. TreeEntry('a.c', 0o100755, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  546. TreeEntry('a/c', stat.S_IFDIR,
  547. 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  548. ], list(sorted_tree_items(_TREE_ITEMS, True)))
  549. test_sorted_tree_items_name_order = functest_builder(
  550. _do_test_sorted_tree_items_name_order, _sorted_tree_items_py)
  551. test_sorted_tree_items_name_order_extension = ext_functest_builder(
  552. _do_test_sorted_tree_items_name_order, sorted_tree_items)
  553. def test_check(self):
  554. t = Tree
  555. sha = hex_to_sha(a_sha)
  556. # filenames
  557. self.assertCheckSucceeds(t, '100644 .a\0%s' % sha)
  558. self.assertCheckFails(t, '100644 \0%s' % sha)
  559. self.assertCheckFails(t, '100644 .\0%s' % sha)
  560. self.assertCheckFails(t, '100644 a/a\0%s' % sha)
  561. self.assertCheckFails(t, '100644 ..\0%s' % sha)
  562. # modes
  563. self.assertCheckSucceeds(t, '100644 a\0%s' % sha)
  564. self.assertCheckSucceeds(t, '100755 a\0%s' % sha)
  565. self.assertCheckSucceeds(t, '160000 a\0%s' % sha)
  566. # TODO more whitelisted modes
  567. self.assertCheckFails(t, '123456 a\0%s' % sha)
  568. self.assertCheckFails(t, '123abc a\0%s' % sha)
  569. # should fail check, but parses ok
  570. self.assertCheckFails(t, '0100644 foo\0' + sha)
  571. # shas
  572. self.assertCheckFails(t, '100644 a\0%s' % ('x' * 5))
  573. self.assertCheckFails(t, '100644 a\0%s' % ('x' * 18 + '\0'))
  574. self.assertCheckFails(t, '100644 a\0%s\n100644 b\0%s' % ('x' * 21, sha))
  575. # ordering
  576. sha2 = hex_to_sha(b_sha)
  577. self.assertCheckSucceeds(t, '100644 a\0%s\n100644 b\0%s' % (sha, sha))
  578. self.assertCheckSucceeds(t, '100644 a\0%s\n100644 b\0%s' % (sha, sha2))
  579. self.assertCheckFails(t, '100644 a\0%s\n100755 a\0%s' % (sha, sha2))
  580. self.assertCheckFails(t, '100644 b\0%s\n100644 a\0%s' % (sha2, sha))
  581. def test_iter(self):
  582. t = Tree()
  583. t["foo"] = (0o100644, a_sha)
  584. self.assertEqual(set(["foo"]), set(t))
  585. class TagSerializeTests(TestCase):
  586. def test_serialize_simple(self):
  587. x = make_object(Tag,
  588. tagger='Jelmer Vernooij <jelmer@samba.org>',
  589. name='0.1',
  590. message='Tag 0.1',
  591. object=(Blob, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  592. tag_time=423423423,
  593. tag_timezone=0)
  594. self.assertEqual(('object d80c186a03f423a81b39df39dc87fd269736ca86\n'
  595. 'type blob\n'
  596. 'tag 0.1\n'
  597. 'tagger Jelmer Vernooij <jelmer@samba.org> '
  598. '423423423 +0000\n'
  599. '\n'
  600. 'Tag 0.1'), x.as_raw_string())
  601. default_tagger = ('Linus Torvalds <torvalds@woody.linux-foundation.org> '
  602. '1183319674 -0700')
  603. default_message = """Linux 2.6.22-rc7
  604. -----BEGIN PGP SIGNATURE-----
  605. Version: GnuPG v1.4.7 (GNU/Linux)
  606. iD8DBQBGiAaAF3YsRnbiHLsRAitMAKCiLboJkQECM/jpYsY3WPfvUgLXkACgg3ql
  607. OK2XeQOiEeXtT76rV4t2WR4=
  608. =ivrA
  609. -----END PGP SIGNATURE-----
  610. """
  611. class TagParseTests(ShaFileCheckTests):
  612. def make_tag_lines(self,
  613. object_sha="a38d6181ff27824c79fc7df825164a212eff6a3f",
  614. object_type_name="commit",
  615. name="v2.6.22-rc7",
  616. tagger=default_tagger,
  617. message=default_message):
  618. lines = []
  619. if object_sha is not None:
  620. lines.append("object %s" % object_sha)
  621. if object_type_name is not None:
  622. lines.append("type %s" % object_type_name)
  623. if name is not None:
  624. lines.append("tag %s" % name)
  625. if tagger is not None:
  626. lines.append("tagger %s" % tagger)
  627. lines.append("")
  628. if message is not None:
  629. lines.append(message)
  630. return lines
  631. def make_tag_text(self, **kwargs):
  632. return "\n".join(self.make_tag_lines(**kwargs))
  633. def test_parse(self):
  634. x = Tag()
  635. x.set_raw_string(self.make_tag_text())
  636. self.assertEqual(
  637. "Linus Torvalds <torvalds@woody.linux-foundation.org>", x.tagger)
  638. self.assertEqual("v2.6.22-rc7", x.name)
  639. object_type, object_sha = x.object
  640. self.assertEqual("a38d6181ff27824c79fc7df825164a212eff6a3f",
  641. object_sha)
  642. self.assertEqual(Commit, object_type)
  643. self.assertEqual(datetime.datetime.utcfromtimestamp(x.tag_time),
  644. datetime.datetime(2007, 7, 1, 19, 54, 34))
  645. self.assertEqual(-25200, x.tag_timezone)
  646. def test_parse_no_tagger(self):
  647. x = Tag()
  648. x.set_raw_string(self.make_tag_text(tagger=None))
  649. self.assertEqual(None, x.tagger)
  650. self.assertEqual("v2.6.22-rc7", x.name)
  651. def test_check(self):
  652. self.assertCheckSucceeds(Tag, self.make_tag_text())
  653. self.assertCheckFails(Tag, self.make_tag_text(object_sha=None))
  654. self.assertCheckFails(Tag, self.make_tag_text(object_type_name=None))
  655. self.assertCheckFails(Tag, self.make_tag_text(name=None))
  656. self.assertCheckFails(Tag, self.make_tag_text(name=''))
  657. self.assertCheckFails(Tag, self.make_tag_text(
  658. object_type_name="foobar"))
  659. self.assertCheckFails(Tag, self.make_tag_text(
  660. tagger="some guy without an email address 1183319674 -0700"))
  661. self.assertCheckFails(Tag, self.make_tag_text(
  662. tagger=("Linus Torvalds <torvalds@woody.linux-foundation.org> "
  663. "Sun 7 Jul 2007 12:54:34 +0700")))
  664. self.assertCheckFails(Tag, self.make_tag_text(object_sha="xxx"))
  665. def test_check_duplicates(self):
  666. # duplicate each of the header fields
  667. for i in range(4):
  668. lines = self.make_tag_lines()
  669. lines.insert(i, lines[i])
  670. self.assertCheckFails(Tag, '\n'.join(lines))
  671. def test_check_order(self):
  672. lines = self.make_tag_lines()
  673. headers = lines[:4]
  674. rest = lines[4:]
  675. # of all possible permutations, ensure only the original succeeds
  676. for perm in permutations(headers):
  677. perm = list(perm)
  678. text = '\n'.join(perm + rest)
  679. if perm == headers:
  680. self.assertCheckSucceeds(Tag, text)
  681. else:
  682. self.assertCheckFails(Tag, text)
  683. class CheckTests(TestCase):
  684. def test_check_hexsha(self):
  685. check_hexsha(a_sha, "failed to check good sha")
  686. self.assertRaises(ObjectFormatException, check_hexsha, '1' * 39,
  687. 'sha too short')
  688. self.assertRaises(ObjectFormatException, check_hexsha, '1' * 41,
  689. 'sha too long')
  690. self.assertRaises(ObjectFormatException, check_hexsha, 'x' * 40,
  691. 'invalid characters')
  692. def test_check_identity(self):
  693. check_identity("Dave Borowitz <dborowitz@google.com>",
  694. "failed to check good identity")
  695. check_identity("<dborowitz@google.com>",
  696. "failed to check good identity")
  697. self.assertRaises(ObjectFormatException, check_identity,
  698. "Dave Borowitz", "no email")
  699. self.assertRaises(ObjectFormatException, check_identity,
  700. "Dave Borowitz <dborowitz", "incomplete email")
  701. self.assertRaises(ObjectFormatException, check_identity,
  702. "dborowitz@google.com>", "incomplete email")
  703. self.assertRaises(ObjectFormatException, check_identity,
  704. "Dave Borowitz <<dborowitz@google.com>", "typo")
  705. self.assertRaises(ObjectFormatException, check_identity,
  706. "Dave Borowitz <dborowitz@google.com>>", "typo")
  707. self.assertRaises(ObjectFormatException, check_identity,
  708. "Dave Borowitz <dborowitz@google.com>xxx",
  709. "trailing characters")
  710. class TimezoneTests(TestCase):
  711. def test_parse_timezone_utc(self):
  712. self.assertEqual((0, False), parse_timezone("+0000"))
  713. def test_parse_timezone_utc_negative(self):
  714. self.assertEqual((0, True), parse_timezone("-0000"))
  715. def test_generate_timezone_utc(self):
  716. self.assertEqual("+0000", format_timezone(0))
  717. def test_generate_timezone_utc_negative(self):
  718. self.assertEqual("-0000", format_timezone(0, True))
  719. def test_parse_timezone_cet(self):
  720. self.assertEqual((60 * 60, False), parse_timezone("+0100"))
  721. def test_format_timezone_cet(self):
  722. self.assertEqual("+0100", format_timezone(60 * 60))
  723. def test_format_timezone_pdt(self):
  724. self.assertEqual("-0400", format_timezone(-4 * 60 * 60))
  725. def test_parse_timezone_pdt(self):
  726. self.assertEqual((-4 * 60 * 60, False), parse_timezone("-0400"))
  727. def test_format_timezone_pdt_half(self):
  728. self.assertEqual("-0440",
  729. format_timezone(int(((-4 * 60) - 40) * 60)))
  730. def test_format_timezone_double_negative(self):
  731. self.assertEqual("--700",
  732. format_timezone(int(((7 * 60)) * 60), True))
  733. def test_parse_timezone_pdt_half(self):
  734. self.assertEqual((((-4 * 60) - 40) * 60, False),
  735. parse_timezone("-0440"))
  736. def test_parse_timezone_double_negative(self):
  737. self.assertEqual(
  738. (int(((7 * 60)) * 60), False), parse_timezone("+700"))
  739. self.assertEqual(
  740. (int(((7 * 60)) * 60), True), parse_timezone("--700"))