test_objects.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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 cStringIO import StringIO
  22. import datetime
  23. import os
  24. import stat
  25. import warnings
  26. from dulwich.errors import (
  27. ObjectFormatException,
  28. )
  29. from dulwich._compat import (
  30. permutations,
  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 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.assertEquals("\xab\xcd" * 10, hex_to_sha("abcd" * 10))
  68. def test_reverse(self):
  69. self.assertEquals("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(StringIO(b_raw))
  106. self.assertEquals(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, (Commit, '51b668fd5bf7061b7d6fa525f88803e6cfadaa51'))
  133. self.assertEqual(t.name,'signed')
  134. self.assertEqual(t.tagger,'Ali Sabil <ali.sabil@gmail.com>')
  135. self.assertEqual(t.tag_time, 1231203091)
  136. 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')
  137. def test_read_commit_from_file(self):
  138. sha = '60dacdc733de308bb77bb76ce0fb0f9b44c9769e'
  139. c = self.commit(sha)
  140. self.assertEqual(c.tree, tree_sha)
  141. self.assertEqual(c.parents,
  142. ['0d89f20333fbb1d2f3a94da77f4981373d8f4310'])
  143. self.assertEqual(c.author,
  144. 'James Westby <jw+debian@jameswestby.net>')
  145. self.assertEqual(c.committer,
  146. 'James Westby <jw+debian@jameswestby.net>')
  147. self.assertEqual(c.commit_time, 1174759230)
  148. self.assertEqual(c.commit_timezone, 0)
  149. self.assertEqual(c.author_timezone, 0)
  150. self.assertEqual(c.message, 'Test commit\n')
  151. def test_read_commit_no_parents(self):
  152. sha = '0d89f20333fbb1d2f3a94da77f4981373d8f4310'
  153. c = self.commit(sha)
  154. self.assertEqual(c.tree, '90182552c4a85a45ec2a835cadc3451bebdfe870')
  155. self.assertEqual(c.parents, [])
  156. self.assertEqual(c.author,
  157. 'James Westby <jw+debian@jameswestby.net>')
  158. self.assertEqual(c.committer,
  159. 'James Westby <jw+debian@jameswestby.net>')
  160. self.assertEqual(c.commit_time, 1174758034)
  161. self.assertEqual(c.commit_timezone, 0)
  162. self.assertEqual(c.author_timezone, 0)
  163. self.assertEqual(c.message, 'Test commit\n')
  164. def test_read_commit_two_parents(self):
  165. sha = '5dac377bdded4c9aeb8dff595f0faeebcc8498cc'
  166. c = self.commit(sha)
  167. self.assertEqual(c.tree, 'd80c186a03f423a81b39df39dc87fd269736ca86')
  168. self.assertEqual(c.parents, ['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  169. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'])
  170. self.assertEqual(c.author,
  171. 'James Westby <jw+debian@jameswestby.net>')
  172. self.assertEqual(c.committer,
  173. 'James Westby <jw+debian@jameswestby.net>')
  174. self.assertEqual(c.commit_time, 1174773719)
  175. self.assertEqual(c.commit_timezone, 0)
  176. self.assertEqual(c.author_timezone, 0)
  177. self.assertEqual(c.message, 'Merge ../b\n')
  178. def test_stub_sha(self):
  179. sha = '5' * 40
  180. c = make_commit(id=sha, message='foo')
  181. self.assertTrue(isinstance(c, Commit))
  182. self.assertEqual(sha, c.id)
  183. self.assertNotEqual(sha, c._make_sha())
  184. class ShaFileCheckTests(TestCase):
  185. def assertCheckFails(self, cls, data):
  186. obj = cls()
  187. def do_check():
  188. obj.set_raw_string(data)
  189. obj.check()
  190. self.assertRaises(ObjectFormatException, do_check)
  191. def assertCheckSucceeds(self, cls, data):
  192. obj = cls()
  193. obj.set_raw_string(data)
  194. self.assertEqual(None, obj.check())
  195. small_buffer_zlib_object = (
  196. "\x48\x89\x15\xcc\x31\x0e\xc2\x30\x0c\x40\x51\xe6"
  197. "\x9c\xc2\x3b\xaa\x64\x37\xc4\xc1\x12\x42\x5c\xc5"
  198. "\x49\xac\x52\xd4\x92\xaa\x78\xe1\xf6\x94\xed\xeb"
  199. "\x0d\xdf\x75\x02\xa2\x7c\xea\xe5\x65\xd5\x81\x8b"
  200. "\x9a\x61\xba\xa0\xa9\x08\x36\xc9\x4c\x1a\xad\x88"
  201. "\x16\xba\x46\xc4\xa8\x99\x6a\x64\xe1\xe0\xdf\xcd"
  202. "\xa0\xf6\x75\x9d\x3d\xf8\xf1\xd0\x77\xdb\xfb\xdc"
  203. "\x86\xa3\x87\xf1\x2f\x93\xed\x00\xb7\xc7\xd2\xab"
  204. "\x2e\xcf\xfe\xf1\x3b\x50\xa4\x91\x53\x12\x24\x38"
  205. "\x23\x21\x86\xf0\x03\x2f\x91\x24\x52"
  206. )
  207. class ShaFileTests(TestCase):
  208. def test_deflated_smaller_window_buffer(self):
  209. # zlib on some systems uses smaller buffers,
  210. # resulting in a different header.
  211. # See https://github.com/libgit2/libgit2/pull/464
  212. sf = ShaFile.from_file(StringIO(small_buffer_zlib_object))
  213. self.assertEquals(sf.type_name, "tag")
  214. self.assertEquals(sf.tagger, " <@localhost>")
  215. class CommitSerializationTests(TestCase):
  216. def make_commit(self, **kwargs):
  217. attrs = {'tree': 'd80c186a03f423a81b39df39dc87fd269736ca86',
  218. 'parents': ['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  219. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'],
  220. 'author': 'James Westby <jw+debian@jameswestby.net>',
  221. 'committer': 'James Westby <jw+debian@jameswestby.net>',
  222. 'commit_time': 1174773719,
  223. 'author_time': 1174773719,
  224. 'commit_timezone': 0,
  225. 'author_timezone': 0,
  226. 'message': 'Merge ../b\n'}
  227. attrs.update(kwargs)
  228. return make_commit(**attrs)
  229. def test_encoding(self):
  230. c = self.make_commit(encoding='iso8859-1')
  231. self.assertTrue('encoding iso8859-1\n' in c.as_raw_string())
  232. def test_short_timestamp(self):
  233. c = self.make_commit(commit_time=30)
  234. c1 = Commit()
  235. c1.set_raw_string(c.as_raw_string())
  236. self.assertEquals(30, c1.commit_time)
  237. def test_raw_length(self):
  238. c = self.make_commit()
  239. self.assertEquals(len(c.as_raw_string()), c.raw_length())
  240. def test_simple(self):
  241. c = self.make_commit()
  242. self.assertEquals(c.id, '5dac377bdded4c9aeb8dff595f0faeebcc8498cc')
  243. self.assertEquals(
  244. 'tree d80c186a03f423a81b39df39dc87fd269736ca86\n'
  245. 'parent ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd\n'
  246. 'parent 4cffe90e0a41ad3f5190079d7c8f036bde29cbe6\n'
  247. 'author James Westby <jw+debian@jameswestby.net> '
  248. '1174773719 +0000\n'
  249. 'committer James Westby <jw+debian@jameswestby.net> '
  250. '1174773719 +0000\n'
  251. '\n'
  252. 'Merge ../b\n', c.as_raw_string())
  253. def test_timezone(self):
  254. c = self.make_commit(commit_timezone=(5 * 60))
  255. self.assertTrue(" +0005\n" in c.as_raw_string())
  256. def test_neg_timezone(self):
  257. c = self.make_commit(commit_timezone=(-1 * 3600))
  258. self.assertTrue(" -0100\n" in c.as_raw_string())
  259. default_committer = 'James Westby <jw+debian@jameswestby.net> 1174773719 +0000'
  260. class CommitParseTests(ShaFileCheckTests):
  261. def make_commit_lines(self,
  262. tree='d80c186a03f423a81b39df39dc87fd269736ca86',
  263. parents=['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  264. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'],
  265. author=default_committer,
  266. committer=default_committer,
  267. encoding=None,
  268. message='Merge ../b\n',
  269. extra=None):
  270. lines = []
  271. if tree is not None:
  272. lines.append('tree %s' % tree)
  273. if parents is not None:
  274. lines.extend('parent %s' % p for p in parents)
  275. if author is not None:
  276. lines.append('author %s' % author)
  277. if committer is not None:
  278. lines.append('committer %s' % committer)
  279. if encoding is not None:
  280. lines.append('encoding %s' % encoding)
  281. if extra is not None:
  282. for name, value in sorted(extra.iteritems()):
  283. lines.append('%s %s' % (name, value))
  284. lines.append('')
  285. if message is not None:
  286. lines.append(message)
  287. return lines
  288. def make_commit_text(self, **kwargs):
  289. return '\n'.join(self.make_commit_lines(**kwargs))
  290. def test_simple(self):
  291. c = Commit.from_string(self.make_commit_text())
  292. self.assertEquals('Merge ../b\n', c.message)
  293. self.assertEquals('James Westby <jw+debian@jameswestby.net>', c.author)
  294. self.assertEquals('James Westby <jw+debian@jameswestby.net>',
  295. c.committer)
  296. self.assertEquals('d80c186a03f423a81b39df39dc87fd269736ca86', c.tree)
  297. self.assertEquals(['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  298. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'],
  299. c.parents)
  300. expected_time = datetime.datetime(2007, 3, 24, 22, 1, 59)
  301. self.assertEquals(expected_time,
  302. datetime.datetime.utcfromtimestamp(c.commit_time))
  303. self.assertEquals(0, c.commit_timezone)
  304. self.assertEquals(expected_time,
  305. datetime.datetime.utcfromtimestamp(c.author_time))
  306. self.assertEquals(0, c.author_timezone)
  307. self.assertEquals(None, c.encoding)
  308. def test_custom(self):
  309. c = Commit.from_string(self.make_commit_text(
  310. extra={'extra-field': 'data'}))
  311. self.assertEquals([('extra-field', 'data')], c.extra)
  312. def test_encoding(self):
  313. c = Commit.from_string(self.make_commit_text(encoding='UTF-8'))
  314. self.assertEquals('UTF-8', c.encoding)
  315. def test_check(self):
  316. self.assertCheckSucceeds(Commit, self.make_commit_text())
  317. self.assertCheckSucceeds(Commit, self.make_commit_text(parents=None))
  318. self.assertCheckSucceeds(Commit,
  319. self.make_commit_text(encoding='UTF-8'))
  320. self.assertCheckFails(Commit, self.make_commit_text(tree='xxx'))
  321. self.assertCheckFails(Commit, self.make_commit_text(
  322. parents=[a_sha, 'xxx']))
  323. bad_committer = "some guy without an email address 1174773719 +0000"
  324. self.assertCheckFails(Commit,
  325. self.make_commit_text(committer=bad_committer))
  326. self.assertCheckFails(Commit,
  327. self.make_commit_text(author=bad_committer))
  328. self.assertCheckFails(Commit, self.make_commit_text(author=None))
  329. self.assertCheckFails(Commit, self.make_commit_text(committer=None))
  330. self.assertCheckFails(Commit, self.make_commit_text(
  331. author=None, committer=None))
  332. def test_check_duplicates(self):
  333. # duplicate each of the header fields
  334. for i in xrange(5):
  335. lines = self.make_commit_lines(parents=[a_sha], encoding='UTF-8')
  336. lines.insert(i, lines[i])
  337. text = '\n'.join(lines)
  338. if lines[i].startswith('parent'):
  339. # duplicate parents are ok for now
  340. self.assertCheckSucceeds(Commit, text)
  341. else:
  342. self.assertCheckFails(Commit, text)
  343. def test_check_order(self):
  344. lines = self.make_commit_lines(parents=[a_sha], encoding='UTF-8')
  345. headers = lines[:5]
  346. rest = lines[5:]
  347. # of all possible permutations, ensure only the original succeeds
  348. for perm in permutations(headers):
  349. perm = list(perm)
  350. text = '\n'.join(perm + rest)
  351. if perm == headers:
  352. self.assertCheckSucceeds(Commit, text)
  353. else:
  354. self.assertCheckFails(Commit, text)
  355. _TREE_ITEMS = {
  356. 'a.c': (0100755, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  357. 'a': (stat.S_IFDIR, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  358. 'a/c': (stat.S_IFDIR, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  359. }
  360. _SORTED_TREE_ITEMS = [
  361. TreeEntry('a.c', 0100755, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  362. TreeEntry('a', stat.S_IFDIR, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  363. TreeEntry('a/c', stat.S_IFDIR, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  364. ]
  365. class TreeTests(ShaFileCheckTests):
  366. def test_add(self):
  367. myhexsha = "d80c186a03f423a81b39df39dc87fd269736ca86"
  368. x = Tree()
  369. x.add("myname", 0100755, myhexsha)
  370. self.assertEquals(x["myname"], (0100755, myhexsha))
  371. self.assertEquals('100755 myname\0' + hex_to_sha(myhexsha),
  372. x.as_raw_string())
  373. def test_add_old_order(self):
  374. myhexsha = "d80c186a03f423a81b39df39dc87fd269736ca86"
  375. x = Tree()
  376. warnings.simplefilter("ignore", DeprecationWarning)
  377. try:
  378. x.add(0100755, "myname", myhexsha)
  379. finally:
  380. warnings.resetwarnings()
  381. self.assertEquals(x["myname"], (0100755, myhexsha))
  382. self.assertEquals('100755 myname\0' + hex_to_sha(myhexsha),
  383. x.as_raw_string())
  384. def test_simple(self):
  385. myhexsha = "d80c186a03f423a81b39df39dc87fd269736ca86"
  386. x = Tree()
  387. x["myname"] = (0100755, myhexsha)
  388. self.assertEquals('100755 myname\0' + hex_to_sha(myhexsha),
  389. x.as_raw_string())
  390. def test_tree_update_id(self):
  391. x = Tree()
  392. x["a.c"] = (0100755, "d80c186a03f423a81b39df39dc87fd269736ca86")
  393. self.assertEquals("0c5c6bc2c081accfbc250331b19e43b904ab9cdd", x.id)
  394. x["a.b"] = (stat.S_IFDIR, "d80c186a03f423a81b39df39dc87fd269736ca86")
  395. self.assertEquals("07bfcb5f3ada15bbebdfa3bbb8fd858a363925c8", x.id)
  396. def test_tree_iteritems_dir_sort(self):
  397. x = Tree()
  398. for name, item in _TREE_ITEMS.iteritems():
  399. x[name] = item
  400. self.assertEquals(_SORTED_TREE_ITEMS, list(x.iteritems()))
  401. def test_tree_items_dir_sort(self):
  402. x = Tree()
  403. for name, item in _TREE_ITEMS.iteritems():
  404. x[name] = item
  405. self.assertEquals(_SORTED_TREE_ITEMS, x.items())
  406. def _do_test_parse_tree(self, parse_tree):
  407. dir = os.path.join(os.path.dirname(__file__), 'data', 'trees')
  408. o = Tree.from_path(hex_to_filename(dir, tree_sha))
  409. self.assertEquals([('a', 0100644, a_sha), ('b', 0100644, b_sha)],
  410. list(parse_tree(o.as_raw_string())))
  411. # test a broken tree that has a leading 0 on the file mode
  412. broken_tree = '0100644 foo\0' + hex_to_sha(a_sha)
  413. def eval_parse_tree(*args, **kwargs):
  414. return list(parse_tree(*args, **kwargs))
  415. self.assertEquals([('foo', 0100644, a_sha)],
  416. eval_parse_tree(broken_tree))
  417. self.assertRaises(ObjectFormatException,
  418. eval_parse_tree, broken_tree, strict=True)
  419. test_parse_tree = functest_builder(_do_test_parse_tree, _parse_tree_py)
  420. test_parse_tree_extension = ext_functest_builder(_do_test_parse_tree,
  421. parse_tree)
  422. def _do_test_sorted_tree_items(self, sorted_tree_items):
  423. def do_sort(entries):
  424. return list(sorted_tree_items(entries, False))
  425. actual = do_sort(_TREE_ITEMS)
  426. self.assertEqual(_SORTED_TREE_ITEMS, actual)
  427. self.assertTrue(isinstance(actual[0], TreeEntry))
  428. # C/Python implementations may differ in specific error types, but
  429. # should all error on invalid inputs.
  430. # For example, the C implementation has stricter type checks, so may
  431. # raise TypeError where the Python implementation raises AttributeError.
  432. errors = (TypeError, ValueError, AttributeError)
  433. self.assertRaises(errors, do_sort, 'foo')
  434. self.assertRaises(errors, do_sort, {'foo': (1, 2, 3)})
  435. myhexsha = 'd80c186a03f423a81b39df39dc87fd269736ca86'
  436. self.assertRaises(errors, do_sort, {'foo': ('xxx', myhexsha)})
  437. self.assertRaises(errors, do_sort, {'foo': (0100755, 12345)})
  438. test_sorted_tree_items = functest_builder(_do_test_sorted_tree_items,
  439. _sorted_tree_items_py)
  440. test_sorted_tree_items_extension = ext_functest_builder(
  441. _do_test_sorted_tree_items, sorted_tree_items)
  442. def _do_test_sorted_tree_items_name_order(self, sorted_tree_items):
  443. self.assertEqual([
  444. TreeEntry('a', stat.S_IFDIR,
  445. 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  446. TreeEntry('a.c', 0100755, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  447. TreeEntry('a/c', stat.S_IFDIR,
  448. 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  449. ], list(sorted_tree_items(_TREE_ITEMS, True)))
  450. test_sorted_tree_items_name_order = functest_builder(
  451. _do_test_sorted_tree_items_name_order, _sorted_tree_items_py)
  452. test_sorted_tree_items_name_order_extension = ext_functest_builder(
  453. _do_test_sorted_tree_items_name_order, sorted_tree_items)
  454. def test_check(self):
  455. t = Tree
  456. sha = hex_to_sha(a_sha)
  457. # filenames
  458. self.assertCheckSucceeds(t, '100644 .a\0%s' % sha)
  459. self.assertCheckFails(t, '100644 \0%s' % sha)
  460. self.assertCheckFails(t, '100644 .\0%s' % sha)
  461. self.assertCheckFails(t, '100644 a/a\0%s' % sha)
  462. self.assertCheckFails(t, '100644 ..\0%s' % sha)
  463. # modes
  464. self.assertCheckSucceeds(t, '100644 a\0%s' % sha)
  465. self.assertCheckSucceeds(t, '100755 a\0%s' % sha)
  466. self.assertCheckSucceeds(t, '160000 a\0%s' % sha)
  467. # TODO more whitelisted modes
  468. self.assertCheckFails(t, '123456 a\0%s' % sha)
  469. self.assertCheckFails(t, '123abc a\0%s' % sha)
  470. # should fail check, but parses ok
  471. self.assertCheckFails(t, '0100644 foo\0' + sha)
  472. # shas
  473. self.assertCheckFails(t, '100644 a\0%s' % ('x' * 5))
  474. self.assertCheckFails(t, '100644 a\0%s' % ('x' * 18 + '\0'))
  475. self.assertCheckFails(t, '100644 a\0%s\n100644 b\0%s' % ('x' * 21, sha))
  476. # ordering
  477. sha2 = hex_to_sha(b_sha)
  478. self.assertCheckSucceeds(t, '100644 a\0%s\n100644 b\0%s' % (sha, sha))
  479. self.assertCheckSucceeds(t, '100644 a\0%s\n100644 b\0%s' % (sha, sha2))
  480. self.assertCheckFails(t, '100644 a\0%s\n100755 a\0%s' % (sha, sha2))
  481. self.assertCheckFails(t, '100644 b\0%s\n100644 a\0%s' % (sha2, sha))
  482. def test_iter(self):
  483. t = Tree()
  484. t["foo"] = (0100644, a_sha)
  485. self.assertEquals(set(["foo"]), set(t))
  486. class TagSerializeTests(TestCase):
  487. def test_serialize_simple(self):
  488. x = make_object(Tag,
  489. tagger='Jelmer Vernooij <jelmer@samba.org>',
  490. name='0.1',
  491. message='Tag 0.1',
  492. object=(Blob, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  493. tag_time=423423423,
  494. tag_timezone=0)
  495. self.assertEquals(('object d80c186a03f423a81b39df39dc87fd269736ca86\n'
  496. 'type blob\n'
  497. 'tag 0.1\n'
  498. 'tagger Jelmer Vernooij <jelmer@samba.org> '
  499. '423423423 +0000\n'
  500. '\n'
  501. 'Tag 0.1'), x.as_raw_string())
  502. default_tagger = ('Linus Torvalds <torvalds@woody.linux-foundation.org> '
  503. '1183319674 -0700')
  504. default_message = """Linux 2.6.22-rc7
  505. -----BEGIN PGP SIGNATURE-----
  506. Version: GnuPG v1.4.7 (GNU/Linux)
  507. iD8DBQBGiAaAF3YsRnbiHLsRAitMAKCiLboJkQECM/jpYsY3WPfvUgLXkACgg3ql
  508. OK2XeQOiEeXtT76rV4t2WR4=
  509. =ivrA
  510. -----END PGP SIGNATURE-----
  511. """
  512. class TagParseTests(ShaFileCheckTests):
  513. def make_tag_lines(self,
  514. object_sha="a38d6181ff27824c79fc7df825164a212eff6a3f",
  515. object_type_name="commit",
  516. name="v2.6.22-rc7",
  517. tagger=default_tagger,
  518. message=default_message):
  519. lines = []
  520. if object_sha is not None:
  521. lines.append("object %s" % object_sha)
  522. if object_type_name is not None:
  523. lines.append("type %s" % object_type_name)
  524. if name is not None:
  525. lines.append("tag %s" % name)
  526. if tagger is not None:
  527. lines.append("tagger %s" % tagger)
  528. lines.append("")
  529. if message is not None:
  530. lines.append(message)
  531. return lines
  532. def make_tag_text(self, **kwargs):
  533. return "\n".join(self.make_tag_lines(**kwargs))
  534. def test_parse(self):
  535. x = Tag()
  536. x.set_raw_string(self.make_tag_text())
  537. self.assertEquals(
  538. "Linus Torvalds <torvalds@woody.linux-foundation.org>", x.tagger)
  539. self.assertEquals("v2.6.22-rc7", x.name)
  540. object_type, object_sha = x.object
  541. self.assertEquals("a38d6181ff27824c79fc7df825164a212eff6a3f",
  542. object_sha)
  543. self.assertEquals(Commit, object_type)
  544. self.assertEquals(datetime.datetime.utcfromtimestamp(x.tag_time),
  545. datetime.datetime(2007, 7, 1, 19, 54, 34))
  546. self.assertEquals(-25200, x.tag_timezone)
  547. def test_parse_no_tagger(self):
  548. x = Tag()
  549. x.set_raw_string(self.make_tag_text(tagger=None))
  550. self.assertEquals(None, x.tagger)
  551. self.assertEquals("v2.6.22-rc7", x.name)
  552. def test_check(self):
  553. self.assertCheckSucceeds(Tag, self.make_tag_text())
  554. self.assertCheckFails(Tag, self.make_tag_text(object_sha=None))
  555. self.assertCheckFails(Tag, self.make_tag_text(object_type_name=None))
  556. self.assertCheckFails(Tag, self.make_tag_text(name=None))
  557. self.assertCheckFails(Tag, self.make_tag_text(name=''))
  558. self.assertCheckFails(Tag, self.make_tag_text(
  559. object_type_name="foobar"))
  560. self.assertCheckFails(Tag, self.make_tag_text(
  561. tagger="some guy without an email address 1183319674 -0700"))
  562. self.assertCheckFails(Tag, self.make_tag_text(
  563. tagger=("Linus Torvalds <torvalds@woody.linux-foundation.org> "
  564. "Sun 7 Jul 2007 12:54:34 +0700")))
  565. self.assertCheckFails(Tag, self.make_tag_text(object_sha="xxx"))
  566. def test_check_duplicates(self):
  567. # duplicate each of the header fields
  568. for i in xrange(4):
  569. lines = self.make_tag_lines()
  570. lines.insert(i, lines[i])
  571. self.assertCheckFails(Tag, '\n'.join(lines))
  572. def test_check_order(self):
  573. lines = self.make_tag_lines()
  574. headers = lines[:4]
  575. rest = lines[4:]
  576. # of all possible permutations, ensure only the original succeeds
  577. for perm in permutations(headers):
  578. perm = list(perm)
  579. text = '\n'.join(perm + rest)
  580. if perm == headers:
  581. self.assertCheckSucceeds(Tag, text)
  582. else:
  583. self.assertCheckFails(Tag, text)
  584. class CheckTests(TestCase):
  585. def test_check_hexsha(self):
  586. check_hexsha(a_sha, "failed to check good sha")
  587. self.assertRaises(ObjectFormatException, check_hexsha, '1' * 39,
  588. 'sha too short')
  589. self.assertRaises(ObjectFormatException, check_hexsha, '1' * 41,
  590. 'sha too long')
  591. self.assertRaises(ObjectFormatException, check_hexsha, 'x' * 40,
  592. 'invalid characters')
  593. def test_check_identity(self):
  594. check_identity("Dave Borowitz <dborowitz@google.com>",
  595. "failed to check good identity")
  596. check_identity("<dborowitz@google.com>",
  597. "failed to check good identity")
  598. self.assertRaises(ObjectFormatException, check_identity,
  599. "Dave Borowitz", "no email")
  600. self.assertRaises(ObjectFormatException, check_identity,
  601. "Dave Borowitz <dborowitz", "incomplete email")
  602. self.assertRaises(ObjectFormatException, check_identity,
  603. "dborowitz@google.com>", "incomplete email")
  604. self.assertRaises(ObjectFormatException, check_identity,
  605. "Dave Borowitz <<dborowitz@google.com>", "typo")
  606. self.assertRaises(ObjectFormatException, check_identity,
  607. "Dave Borowitz <dborowitz@google.com>>", "typo")
  608. self.assertRaises(ObjectFormatException, check_identity,
  609. "Dave Borowitz <dborowitz@google.com>xxx",
  610. "trailing characters")
  611. class TimezoneTests(TestCase):
  612. def test_parse_timezone_utc(self):
  613. self.assertEquals((0, False), parse_timezone("+0000"))
  614. def test_parse_timezone_utc_negative(self):
  615. self.assertEquals((0, True), parse_timezone("-0000"))
  616. def test_generate_timezone_utc(self):
  617. self.assertEquals("+0000", format_timezone(0))
  618. def test_generate_timezone_utc_negative(self):
  619. self.assertEquals("-0000", format_timezone(0, True))
  620. def test_parse_timezone_cet(self):
  621. self.assertEquals((60 * 60, False), parse_timezone("+0100"))
  622. def test_format_timezone_cet(self):
  623. self.assertEquals("+0100", format_timezone(60 * 60))
  624. def test_format_timezone_pdt(self):
  625. self.assertEquals("-0400", format_timezone(-4 * 60 * 60))
  626. def test_parse_timezone_pdt(self):
  627. self.assertEquals((-4 * 60 * 60, False), parse_timezone("-0400"))
  628. def test_format_timezone_pdt_half(self):
  629. self.assertEquals("-0440",
  630. format_timezone(int(((-4 * 60) - 40) * 60)))
  631. def test_parse_timezone_pdt_half(self):
  632. self.assertEquals((((-4 * 60) - 40) * 60, False),
  633. parse_timezone("-0440"))
  634. def test_parse_timezone_double_negative(self):
  635. self.assertEquals(parse_timezone("+0700"), parse_timezone("--700"))