test_objects.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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. from dulwich.errors import (
  26. ObjectFormatException,
  27. )
  28. from dulwich.misc import (
  29. TreeEntry,
  30. )
  31. from dulwich.objects import (
  32. Blob,
  33. Tree,
  34. Commit,
  35. Tag,
  36. format_timezone,
  37. hex_to_sha,
  38. sha_to_hex,
  39. hex_to_filename,
  40. check_hexsha,
  41. check_identity,
  42. parse_timezone,
  43. parse_tree,
  44. _parse_tree_py,
  45. sorted_tree_items,
  46. _sorted_tree_items_py,
  47. )
  48. from dulwich.tests import (
  49. TestCase,
  50. TestSkipped,
  51. )
  52. from utils import (
  53. make_commit,
  54. make_object,
  55. )
  56. a_sha = '6f670c0fb53f9463760b7295fbb814e965fb20c8'
  57. b_sha = '2969be3e8ee1c0222396a5611407e4769f14e54b'
  58. c_sha = '954a536f7819d40e6f637f849ee187dd10066349'
  59. tree_sha = '70c190eb48fa8bbb50ddc692a17b44cb781af7f6'
  60. tag_sha = '71033db03a03c6a36721efcf1968dd8f8e0cf023'
  61. try:
  62. from itertools import permutations
  63. except ImportError:
  64. # Implementation of permutations from Python 2.6 documentation:
  65. # http://docs.python.org/2.6/library/itertools.html#itertools.permutations
  66. # Copyright (c) 2001-2010 Python Software Foundation; All Rights Reserved
  67. # Modified syntax slightly to run under Python 2.4.
  68. def permutations(iterable, r=None):
  69. # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
  70. # permutations(range(3)) --> 012 021 102 120 201 210
  71. pool = tuple(iterable)
  72. n = len(pool)
  73. if r is None:
  74. r = n
  75. if r > n:
  76. return
  77. indices = range(n)
  78. cycles = range(n, n-r, -1)
  79. yield tuple(pool[i] for i in indices[:r])
  80. while n:
  81. for i in reversed(range(r)):
  82. cycles[i] -= 1
  83. if cycles[i] == 0:
  84. indices[i:] = indices[i+1:] + indices[i:i+1]
  85. cycles[i] = n - i
  86. else:
  87. j = cycles[i]
  88. indices[i], indices[-j] = indices[-j], indices[i]
  89. yield tuple(pool[i] for i in indices[:r])
  90. break
  91. else:
  92. return
  93. class TestHexToSha(TestCase):
  94. def test_simple(self):
  95. self.assertEquals("\xab\xcd" * 10, hex_to_sha("abcd" * 10))
  96. def test_reverse(self):
  97. self.assertEquals("abcd" * 10, sha_to_hex("\xab\xcd" * 10))
  98. class BlobReadTests(TestCase):
  99. """Test decompression of blobs"""
  100. def get_sha_file(self, cls, base, sha):
  101. dir = os.path.join(os.path.dirname(__file__), 'data', base)
  102. return cls.from_path(hex_to_filename(dir, sha))
  103. def get_blob(self, sha):
  104. """Return the blob named sha from the test data dir"""
  105. return self.get_sha_file(Blob, 'blobs', sha)
  106. def get_tree(self, sha):
  107. return self.get_sha_file(Tree, 'trees', sha)
  108. def get_tag(self, sha):
  109. return self.get_sha_file(Tag, 'tags', sha)
  110. def commit(self, sha):
  111. return self.get_sha_file(Commit, 'commits', sha)
  112. def test_decompress_simple_blob(self):
  113. b = self.get_blob(a_sha)
  114. self.assertEqual(b.data, 'test 1\n')
  115. self.assertEqual(b.sha().hexdigest(), a_sha)
  116. def test_hash(self):
  117. b = self.get_blob(a_sha)
  118. self.assertEqual(hash(b.id), hash(b))
  119. def test_parse_empty_blob_object(self):
  120. sha = 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391'
  121. b = self.get_blob(sha)
  122. self.assertEqual(b.data, '')
  123. self.assertEqual(b.id, sha)
  124. self.assertEqual(b.sha().hexdigest(), sha)
  125. def test_create_blob_from_string(self):
  126. string = 'test 2\n'
  127. b = Blob.from_string(string)
  128. self.assertEqual(b.data, string)
  129. self.assertEqual(b.sha().hexdigest(), b_sha)
  130. def test_legacy_from_file(self):
  131. b1 = Blob.from_string("foo")
  132. b_raw = b1.as_legacy_object()
  133. b2 = b1.from_file(StringIO(b_raw))
  134. self.assertEquals(b1, b2)
  135. def test_chunks(self):
  136. string = 'test 5\n'
  137. b = Blob.from_string(string)
  138. self.assertEqual([string], b.chunked)
  139. def test_set_chunks(self):
  140. b = Blob()
  141. b.chunked = ['te', 'st', ' 5\n']
  142. self.assertEqual('test 5\n', b.data)
  143. b.chunked = ['te', 'st', ' 6\n']
  144. self.assertEqual('test 6\n', b.as_raw_string())
  145. def test_parse_legacy_blob(self):
  146. string = 'test 3\n'
  147. b = self.get_blob(c_sha)
  148. self.assertEqual(b.data, string)
  149. self.assertEqual(b.sha().hexdigest(), c_sha)
  150. def test_eq(self):
  151. blob1 = self.get_blob(a_sha)
  152. blob2 = self.get_blob(a_sha)
  153. self.assertEqual(blob1, blob2)
  154. def test_read_tree_from_file(self):
  155. t = self.get_tree(tree_sha)
  156. self.assertEqual(t.entries()[0], (33188, 'a', a_sha))
  157. self.assertEqual(t.entries()[1], (33188, 'b', b_sha))
  158. def test_read_tag_from_file(self):
  159. t = self.get_tag(tag_sha)
  160. self.assertEqual(t.object, (Commit, '51b668fd5bf7061b7d6fa525f88803e6cfadaa51'))
  161. self.assertEqual(t.name,'signed')
  162. self.assertEqual(t.tagger,'Ali Sabil <ali.sabil@gmail.com>')
  163. self.assertEqual(t.tag_time, 1231203091)
  164. 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')
  165. def test_read_commit_from_file(self):
  166. sha = '60dacdc733de308bb77bb76ce0fb0f9b44c9769e'
  167. c = self.commit(sha)
  168. self.assertEqual(c.tree, tree_sha)
  169. self.assertEqual(c.parents,
  170. ['0d89f20333fbb1d2f3a94da77f4981373d8f4310'])
  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, 1174759230)
  176. self.assertEqual(c.commit_timezone, 0)
  177. self.assertEqual(c.author_timezone, 0)
  178. self.assertEqual(c.message, 'Test commit\n')
  179. def test_read_commit_no_parents(self):
  180. sha = '0d89f20333fbb1d2f3a94da77f4981373d8f4310'
  181. c = self.commit(sha)
  182. self.assertEqual(c.tree, '90182552c4a85a45ec2a835cadc3451bebdfe870')
  183. self.assertEqual(c.parents, [])
  184. self.assertEqual(c.author,
  185. 'James Westby <jw+debian@jameswestby.net>')
  186. self.assertEqual(c.committer,
  187. 'James Westby <jw+debian@jameswestby.net>')
  188. self.assertEqual(c.commit_time, 1174758034)
  189. self.assertEqual(c.commit_timezone, 0)
  190. self.assertEqual(c.author_timezone, 0)
  191. self.assertEqual(c.message, 'Test commit\n')
  192. def test_read_commit_two_parents(self):
  193. sha = '5dac377bdded4c9aeb8dff595f0faeebcc8498cc'
  194. c = self.commit(sha)
  195. self.assertEqual(c.tree, 'd80c186a03f423a81b39df39dc87fd269736ca86')
  196. self.assertEqual(c.parents, ['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  197. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'])
  198. self.assertEqual(c.author,
  199. 'James Westby <jw+debian@jameswestby.net>')
  200. self.assertEqual(c.committer,
  201. 'James Westby <jw+debian@jameswestby.net>')
  202. self.assertEqual(c.commit_time, 1174773719)
  203. self.assertEqual(c.commit_timezone, 0)
  204. self.assertEqual(c.author_timezone, 0)
  205. self.assertEqual(c.message, 'Merge ../b\n')
  206. def test_stub_sha(self):
  207. sha = '5' * 40
  208. c = make_commit(id=sha, message='foo')
  209. self.assertTrue(isinstance(c, Commit))
  210. self.assertEqual(sha, c.id)
  211. self.assertNotEqual(sha, c._make_sha())
  212. class ShaFileCheckTests(TestCase):
  213. def assertCheckFails(self, cls, data):
  214. obj = cls()
  215. def do_check():
  216. obj.set_raw_string(data)
  217. obj.check()
  218. self.assertRaises(ObjectFormatException, do_check)
  219. def assertCheckSucceeds(self, cls, data):
  220. obj = cls()
  221. obj.set_raw_string(data)
  222. self.assertEqual(None, obj.check())
  223. class CommitSerializationTests(TestCase):
  224. def make_commit(self, **kwargs):
  225. attrs = {'tree': 'd80c186a03f423a81b39df39dc87fd269736ca86',
  226. 'parents': ['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  227. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'],
  228. 'author': 'James Westby <jw+debian@jameswestby.net>',
  229. 'committer': 'James Westby <jw+debian@jameswestby.net>',
  230. 'commit_time': 1174773719,
  231. 'author_time': 1174773719,
  232. 'commit_timezone': 0,
  233. 'author_timezone': 0,
  234. 'message': 'Merge ../b\n'}
  235. attrs.update(kwargs)
  236. return make_commit(**attrs)
  237. def test_encoding(self):
  238. c = self.make_commit(encoding='iso8859-1')
  239. self.assertTrue('encoding iso8859-1\n' in c.as_raw_string())
  240. def test_short_timestamp(self):
  241. c = self.make_commit(commit_time=30)
  242. c1 = Commit()
  243. c1.set_raw_string(c.as_raw_string())
  244. self.assertEquals(30, c1.commit_time)
  245. def test_raw_length(self):
  246. c = self.make_commit()
  247. self.assertEquals(len(c.as_raw_string()), c.raw_length())
  248. def test_simple(self):
  249. c = self.make_commit()
  250. self.assertEquals(c.id, '5dac377bdded4c9aeb8dff595f0faeebcc8498cc')
  251. self.assertEquals(
  252. 'tree d80c186a03f423a81b39df39dc87fd269736ca86\n'
  253. 'parent ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd\n'
  254. 'parent 4cffe90e0a41ad3f5190079d7c8f036bde29cbe6\n'
  255. 'author James Westby <jw+debian@jameswestby.net> '
  256. '1174773719 +0000\n'
  257. 'committer James Westby <jw+debian@jameswestby.net> '
  258. '1174773719 +0000\n'
  259. '\n'
  260. 'Merge ../b\n', c.as_raw_string())
  261. def test_timezone(self):
  262. c = self.make_commit(commit_timezone=(5 * 60))
  263. self.assertTrue(" +0005\n" in c.as_raw_string())
  264. def test_neg_timezone(self):
  265. c = self.make_commit(commit_timezone=(-1 * 3600))
  266. self.assertTrue(" -0100\n" in c.as_raw_string())
  267. default_committer = 'James Westby <jw+debian@jameswestby.net> 1174773719 +0000'
  268. class CommitParseTests(ShaFileCheckTests):
  269. def make_commit_lines(self,
  270. tree='d80c186a03f423a81b39df39dc87fd269736ca86',
  271. parents=['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  272. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'],
  273. author=default_committer,
  274. committer=default_committer,
  275. encoding=None,
  276. message='Merge ../b\n',
  277. extra=None):
  278. lines = []
  279. if tree is not None:
  280. lines.append('tree %s' % tree)
  281. if parents is not None:
  282. lines.extend('parent %s' % p for p in parents)
  283. if author is not None:
  284. lines.append('author %s' % author)
  285. if committer is not None:
  286. lines.append('committer %s' % committer)
  287. if encoding is not None:
  288. lines.append('encoding %s' % encoding)
  289. if extra is not None:
  290. for name, value in sorted(extra.iteritems()):
  291. lines.append('%s %s' % (name, value))
  292. lines.append('')
  293. if message is not None:
  294. lines.append(message)
  295. return lines
  296. def make_commit_text(self, **kwargs):
  297. return '\n'.join(self.make_commit_lines(**kwargs))
  298. def test_simple(self):
  299. c = Commit.from_string(self.make_commit_text())
  300. self.assertEquals('Merge ../b\n', c.message)
  301. self.assertEquals('James Westby <jw+debian@jameswestby.net>', c.author)
  302. self.assertEquals('James Westby <jw+debian@jameswestby.net>',
  303. c.committer)
  304. self.assertEquals('d80c186a03f423a81b39df39dc87fd269736ca86', c.tree)
  305. self.assertEquals(['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  306. '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'],
  307. c.parents)
  308. expected_time = datetime.datetime(2007, 3, 24, 22, 1, 59)
  309. self.assertEquals(expected_time,
  310. datetime.datetime.utcfromtimestamp(c.commit_time))
  311. self.assertEquals(0, c.commit_timezone)
  312. self.assertEquals(expected_time,
  313. datetime.datetime.utcfromtimestamp(c.author_time))
  314. self.assertEquals(0, c.author_timezone)
  315. self.assertEquals(None, c.encoding)
  316. def test_custom(self):
  317. c = Commit.from_string(self.make_commit_text(
  318. extra={'extra-field': 'data'}))
  319. self.assertEquals([('extra-field', 'data')], c.extra)
  320. def test_encoding(self):
  321. c = Commit.from_string(self.make_commit_text(encoding='UTF-8'))
  322. self.assertEquals('UTF-8', c.encoding)
  323. def test_check(self):
  324. self.assertCheckSucceeds(Commit, self.make_commit_text())
  325. self.assertCheckSucceeds(Commit, self.make_commit_text(parents=None))
  326. self.assertCheckSucceeds(Commit,
  327. self.make_commit_text(encoding='UTF-8'))
  328. self.assertCheckFails(Commit, self.make_commit_text(tree='xxx'))
  329. self.assertCheckFails(Commit, self.make_commit_text(
  330. parents=[a_sha, 'xxx']))
  331. bad_committer = "some guy without an email address 1174773719 +0000"
  332. self.assertCheckFails(Commit,
  333. self.make_commit_text(committer=bad_committer))
  334. self.assertCheckFails(Commit,
  335. self.make_commit_text(author=bad_committer))
  336. self.assertCheckFails(Commit, self.make_commit_text(author=None))
  337. self.assertCheckFails(Commit, self.make_commit_text(committer=None))
  338. self.assertCheckFails(Commit, self.make_commit_text(
  339. author=None, committer=None))
  340. def test_check_duplicates(self):
  341. # duplicate each of the header fields
  342. for i in xrange(5):
  343. lines = self.make_commit_lines(parents=[a_sha], encoding='UTF-8')
  344. lines.insert(i, lines[i])
  345. text = '\n'.join(lines)
  346. if lines[i].startswith('parent'):
  347. # duplicate parents are ok for now
  348. self.assertCheckSucceeds(Commit, text)
  349. else:
  350. self.assertCheckFails(Commit, text)
  351. def test_check_order(self):
  352. lines = self.make_commit_lines(parents=[a_sha], encoding='UTF-8')
  353. headers = lines[:5]
  354. rest = lines[5:]
  355. # of all possible permutations, ensure only the original succeeds
  356. for perm in permutations(headers):
  357. perm = list(perm)
  358. text = '\n'.join(perm + rest)
  359. if perm == headers:
  360. self.assertCheckSucceeds(Commit, text)
  361. else:
  362. self.assertCheckFails(Commit, text)
  363. _TREE_ITEMS = {
  364. 'a.c': (0100755, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  365. 'a': (stat.S_IFDIR, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  366. 'a/c': (stat.S_IFDIR, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  367. }
  368. _SORTED_TREE_ITEMS = [
  369. TreeEntry('a.c', 0100755, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  370. TreeEntry('a', stat.S_IFDIR, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  371. TreeEntry('a/c', stat.S_IFDIR, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  372. ]
  373. class TreeTests(ShaFileCheckTests):
  374. def test_simple(self):
  375. myhexsha = "d80c186a03f423a81b39df39dc87fd269736ca86"
  376. x = Tree()
  377. x["myname"] = (0100755, myhexsha)
  378. self.assertEquals('100755 myname\0' + hex_to_sha(myhexsha),
  379. x.as_raw_string())
  380. def test_tree_update_id(self):
  381. x = Tree()
  382. x["a.c"] = (0100755, "d80c186a03f423a81b39df39dc87fd269736ca86")
  383. self.assertEquals("0c5c6bc2c081accfbc250331b19e43b904ab9cdd", x.id)
  384. x["a.b"] = (stat.S_IFDIR, "d80c186a03f423a81b39df39dc87fd269736ca86")
  385. self.assertEquals("07bfcb5f3ada15bbebdfa3bbb8fd858a363925c8", x.id)
  386. def test_tree_iteritems_dir_sort(self):
  387. x = Tree()
  388. for name, item in _TREE_ITEMS.iteritems():
  389. x[name] = item
  390. self.assertEquals(_SORTED_TREE_ITEMS, list(x.iteritems()))
  391. def test_tree_items_dir_sort(self):
  392. x = Tree()
  393. for name, item in _TREE_ITEMS.iteritems():
  394. x[name] = item
  395. self.assertEquals(_SORTED_TREE_ITEMS, x.items())
  396. def _do_test_parse_tree(self, parse_tree):
  397. dir = os.path.join(os.path.dirname(__file__), 'data', 'trees')
  398. o = Tree.from_path(hex_to_filename(dir, tree_sha))
  399. self.assertEquals([('a', 0100644, a_sha), ('b', 0100644, b_sha)],
  400. list(parse_tree(o.as_raw_string())))
  401. def test_parse_tree(self):
  402. self._do_test_parse_tree(_parse_tree_py)
  403. def test_parse_tree_extension(self):
  404. if parse_tree is _parse_tree_py:
  405. raise TestSkipped('parse_tree extension not found')
  406. self._do_test_parse_tree(parse_tree)
  407. def _do_test_sorted_tree_items(self, sorted_tree_items):
  408. def do_sort(entries):
  409. return list(sorted_tree_items(entries))
  410. actual = do_sort(_TREE_ITEMS)
  411. self.assertEqual(_SORTED_TREE_ITEMS, actual)
  412. self.assertTrue(isinstance(actual[0], TreeEntry))
  413. # C/Python implementations may differ in specific error types, but
  414. # should all error on invalid inputs.
  415. # For example, the C implementation has stricter type checks, so may
  416. # raise TypeError where the Python implementation raises AttributeError.
  417. errors = (TypeError, ValueError, AttributeError)
  418. self.assertRaises(errors, do_sort, 'foo')
  419. self.assertRaises(errors, do_sort, {'foo': (1, 2, 3)})
  420. myhexsha = 'd80c186a03f423a81b39df39dc87fd269736ca86'
  421. self.assertRaises(errors, do_sort, {'foo': ('xxx', myhexsha)})
  422. self.assertRaises(errors, do_sort, {'foo': (0100755, 12345)})
  423. def test_sorted_tree_items(self):
  424. self._do_test_sorted_tree_items(_sorted_tree_items_py)
  425. def test_sorted_tree_items_extension(self):
  426. if sorted_tree_items is _sorted_tree_items_py:
  427. raise TestSkipped('sorted_tree_items extension not found')
  428. self._do_test_sorted_tree_items(sorted_tree_items)
  429. def test_check(self):
  430. t = Tree
  431. sha = hex_to_sha(a_sha)
  432. # filenames
  433. self.assertCheckSucceeds(t, '100644 .a\0%s' % sha)
  434. self.assertCheckFails(t, '100644 \0%s' % sha)
  435. self.assertCheckFails(t, '100644 .\0%s' % sha)
  436. self.assertCheckFails(t, '100644 a/a\0%s' % sha)
  437. self.assertCheckFails(t, '100644 ..\0%s' % sha)
  438. # modes
  439. self.assertCheckSucceeds(t, '100644 a\0%s' % sha)
  440. self.assertCheckSucceeds(t, '100755 a\0%s' % sha)
  441. self.assertCheckSucceeds(t, '160000 a\0%s' % sha)
  442. # TODO more whitelisted modes
  443. self.assertCheckFails(t, '123456 a\0%s' % sha)
  444. self.assertCheckFails(t, '123abc a\0%s' % sha)
  445. # shas
  446. self.assertCheckFails(t, '100644 a\0%s' % ('x' * 5))
  447. self.assertCheckFails(t, '100644 a\0%s' % ('x' * 18 + '\0'))
  448. self.assertCheckFails(t, '100644 a\0%s\n100644 b\0%s' % ('x' * 21, sha))
  449. # ordering
  450. sha2 = hex_to_sha(b_sha)
  451. self.assertCheckSucceeds(t, '100644 a\0%s\n100644 b\0%s' % (sha, sha))
  452. self.assertCheckSucceeds(t, '100644 a\0%s\n100644 b\0%s' % (sha, sha2))
  453. self.assertCheckFails(t, '100644 a\0%s\n100755 a\0%s' % (sha, sha2))
  454. self.assertCheckFails(t, '100644 b\0%s\n100644 a\0%s' % (sha2, sha))
  455. def test_iter(self):
  456. t = Tree()
  457. t["foo"] = (0100644, a_sha)
  458. self.assertEquals(set(["foo"]), set(t))
  459. class TagSerializeTests(TestCase):
  460. def test_serialize_simple(self):
  461. x = make_object(Tag,
  462. tagger='Jelmer Vernooij <jelmer@samba.org>',
  463. name='0.1',
  464. message='Tag 0.1',
  465. object=(Blob, 'd80c186a03f423a81b39df39dc87fd269736ca86'),
  466. tag_time=423423423,
  467. tag_timezone=0)
  468. self.assertEquals(('object d80c186a03f423a81b39df39dc87fd269736ca86\n'
  469. 'type blob\n'
  470. 'tag 0.1\n'
  471. 'tagger Jelmer Vernooij <jelmer@samba.org> '
  472. '423423423 +0000\n'
  473. '\n'
  474. 'Tag 0.1'), x.as_raw_string())
  475. default_tagger = ('Linus Torvalds <torvalds@woody.linux-foundation.org> '
  476. '1183319674 -0700')
  477. default_message = """Linux 2.6.22-rc7
  478. -----BEGIN PGP SIGNATURE-----
  479. Version: GnuPG v1.4.7 (GNU/Linux)
  480. iD8DBQBGiAaAF3YsRnbiHLsRAitMAKCiLboJkQECM/jpYsY3WPfvUgLXkACgg3ql
  481. OK2XeQOiEeXtT76rV4t2WR4=
  482. =ivrA
  483. -----END PGP SIGNATURE-----
  484. """
  485. class TagParseTests(ShaFileCheckTests):
  486. def make_tag_lines(self,
  487. object_sha="a38d6181ff27824c79fc7df825164a212eff6a3f",
  488. object_type_name="commit",
  489. name="v2.6.22-rc7",
  490. tagger=default_tagger,
  491. message=default_message):
  492. lines = []
  493. if object_sha is not None:
  494. lines.append("object %s" % object_sha)
  495. if object_type_name is not None:
  496. lines.append("type %s" % object_type_name)
  497. if name is not None:
  498. lines.append("tag %s" % name)
  499. if tagger is not None:
  500. lines.append("tagger %s" % tagger)
  501. lines.append("")
  502. if message is not None:
  503. lines.append(message)
  504. return lines
  505. def make_tag_text(self, **kwargs):
  506. return "\n".join(self.make_tag_lines(**kwargs))
  507. def test_parse(self):
  508. x = Tag()
  509. x.set_raw_string(self.make_tag_text())
  510. self.assertEquals(
  511. "Linus Torvalds <torvalds@woody.linux-foundation.org>", x.tagger)
  512. self.assertEquals("v2.6.22-rc7", x.name)
  513. object_type, object_sha = x.object
  514. self.assertEquals("a38d6181ff27824c79fc7df825164a212eff6a3f",
  515. object_sha)
  516. self.assertEquals(Commit, object_type)
  517. self.assertEquals(datetime.datetime.utcfromtimestamp(x.tag_time),
  518. datetime.datetime(2007, 7, 1, 19, 54, 34))
  519. self.assertEquals(-25200, x.tag_timezone)
  520. def test_parse_no_tagger(self):
  521. x = Tag()
  522. x.set_raw_string(self.make_tag_text(tagger=None))
  523. self.assertEquals(None, x.tagger)
  524. self.assertEquals("v2.6.22-rc7", x.name)
  525. def test_check(self):
  526. self.assertCheckSucceeds(Tag, self.make_tag_text())
  527. self.assertCheckFails(Tag, self.make_tag_text(object_sha=None))
  528. self.assertCheckFails(Tag, self.make_tag_text(object_type_name=None))
  529. self.assertCheckFails(Tag, self.make_tag_text(name=None))
  530. self.assertCheckFails(Tag, self.make_tag_text(name=''))
  531. self.assertCheckFails(Tag, self.make_tag_text(
  532. object_type_name="foobar"))
  533. self.assertCheckFails(Tag, self.make_tag_text(
  534. tagger="some guy without an email address 1183319674 -0700"))
  535. self.assertCheckFails(Tag, self.make_tag_text(
  536. tagger=("Linus Torvalds <torvalds@woody.linux-foundation.org> "
  537. "Sun 7 Jul 2007 12:54:34 +0700")))
  538. self.assertCheckFails(Tag, self.make_tag_text(object_sha="xxx"))
  539. def test_check_duplicates(self):
  540. # duplicate each of the header fields
  541. for i in xrange(4):
  542. lines = self.make_tag_lines()
  543. lines.insert(i, lines[i])
  544. self.assertCheckFails(Tag, '\n'.join(lines))
  545. def test_check_order(self):
  546. lines = self.make_tag_lines()
  547. headers = lines[:4]
  548. rest = lines[4:]
  549. # of all possible permutations, ensure only the original succeeds
  550. for perm in permutations(headers):
  551. perm = list(perm)
  552. text = '\n'.join(perm + rest)
  553. if perm == headers:
  554. self.assertCheckSucceeds(Tag, text)
  555. else:
  556. self.assertCheckFails(Tag, text)
  557. class CheckTests(TestCase):
  558. def test_check_hexsha(self):
  559. check_hexsha(a_sha, "failed to check good sha")
  560. self.assertRaises(ObjectFormatException, check_hexsha, '1' * 39,
  561. 'sha too short')
  562. self.assertRaises(ObjectFormatException, check_hexsha, '1' * 41,
  563. 'sha too long')
  564. self.assertRaises(ObjectFormatException, check_hexsha, 'x' * 40,
  565. 'invalid characters')
  566. def test_check_identity(self):
  567. check_identity("Dave Borowitz <dborowitz@google.com>",
  568. "failed to check good identity")
  569. check_identity("<dborowitz@google.com>",
  570. "failed to check good identity")
  571. self.assertRaises(ObjectFormatException, check_identity,
  572. "Dave Borowitz", "no email")
  573. self.assertRaises(ObjectFormatException, check_identity,
  574. "Dave Borowitz <dborowitz", "incomplete email")
  575. self.assertRaises(ObjectFormatException, check_identity,
  576. "dborowitz@google.com>", "incomplete email")
  577. self.assertRaises(ObjectFormatException, check_identity,
  578. "Dave Borowitz <<dborowitz@google.com>", "typo")
  579. self.assertRaises(ObjectFormatException, check_identity,
  580. "Dave Borowitz <dborowitz@google.com>>", "typo")
  581. self.assertRaises(ObjectFormatException, check_identity,
  582. "Dave Borowitz <dborowitz@google.com>xxx",
  583. "trailing characters")
  584. class TimezoneTests(TestCase):
  585. def test_parse_timezone_utc(self):
  586. self.assertEquals((0, False), parse_timezone("+0000"))
  587. def test_parse_timezone_utc_negative(self):
  588. self.assertEquals((0, True), parse_timezone("-0000"))
  589. def test_generate_timezone_utc(self):
  590. self.assertEquals("+0000", format_timezone(0))
  591. def test_generate_timezone_utc_negative(self):
  592. self.assertEquals("-0000", format_timezone(0, True))
  593. def test_parse_timezone_cet(self):
  594. self.assertEquals((60 * 60, False), parse_timezone("+0100"))
  595. def test_format_timezone_cet(self):
  596. self.assertEquals("+0100", format_timezone(60 * 60))
  597. def test_format_timezone_pdt(self):
  598. self.assertEquals("-0400", format_timezone(-4 * 60 * 60))
  599. def test_parse_timezone_pdt(self):
  600. self.assertEquals((-4 * 60 * 60, False), parse_timezone("-0400"))
  601. def test_format_timezone_pdt_half(self):
  602. self.assertEquals("-0440",
  603. format_timezone(int(((-4 * 60) - 40) * 60)))
  604. def test_parse_timezone_pdt_half(self):
  605. self.assertEquals((((-4 * 60) - 40) * 60, False),
  606. parse_timezone("-0440"))