test_objects.py 25 KB

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