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