test_objects.py 27 KB

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