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