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