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