Lazily read the contents of ShaFiles from disk.
[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, cls, data):
216         obj = cls()
217         obj.set_raw_string(data)
218         self.assertRaises(ObjectFormatException, obj.check)
219
220     def assertCheckSucceeds(self, cls, data):
221         obj = cls()
222         obj.set_raw_string(data)
223         try:
224             obj.check()
225         except ObjectFormatException, e:
226             raise
227             self.fail(e)
228
229
230 class CommitSerializationTests(unittest.TestCase):
231
232     def make_base(self):
233         c = Commit()
234         c.tree = 'd80c186a03f423a81b39df39dc87fd269736ca86'
235         c.parents = ['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd', '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6']
236         c.author = 'James Westby <jw+debian@jameswestby.net>'
237         c.committer = 'James Westby <jw+debian@jameswestby.net>'
238         c.commit_time = 1174773719
239         c.author_time = 1174773719
240         c.commit_timezone = 0
241         c.author_timezone = 0
242         c.message =  'Merge ../b\n'
243         return c
244
245     def test_encoding(self):
246         c = self.make_base()
247         c.encoding = "iso8859-1"
248         self.assertTrue("encoding iso8859-1\n" in c.as_raw_string())        
249
250     def test_short_timestamp(self):
251         c = self.make_base()
252         c.commit_time = 30
253         c1 = Commit()
254         c1.set_raw_string(c.as_raw_string())
255         self.assertEquals(30, c1.commit_time)
256
257     def test_raw_length(self):
258         c = self.make_base()
259         self.assertEquals(len(c.as_raw_string()), c.raw_length())
260
261     def test_simple(self):
262         c = self.make_base()
263         self.assertEquals(c.id, '5dac377bdded4c9aeb8dff595f0faeebcc8498cc')
264         self.assertEquals(
265                 'tree d80c186a03f423a81b39df39dc87fd269736ca86\n'
266                 'parent ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd\n'
267                 'parent 4cffe90e0a41ad3f5190079d7c8f036bde29cbe6\n'
268                 'author James Westby <jw+debian@jameswestby.net> 1174773719 +0000\n'
269                 'committer James Westby <jw+debian@jameswestby.net> 1174773719 +0000\n'
270                 '\n'
271                 'Merge ../b\n', c.as_raw_string())
272
273     def test_timezone(self):
274         c = self.make_base()
275         c.commit_timezone = 5 * 60
276         self.assertTrue(" +0005\n" in c.as_raw_string())
277
278     def test_neg_timezone(self):
279         c = self.make_base()
280         c.commit_timezone = -1 * 3600
281         self.assertTrue(" -0100\n" in c.as_raw_string())
282
283
284 default_committer = 'James Westby <jw+debian@jameswestby.net> 1174773719 +0000'
285
286 class CommitParseTests(ShaFileCheckTests):
287
288     def make_commit_lines(self,
289                           tree='d80c186a03f423a81b39df39dc87fd269736ca86',
290                           parents=['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
291                                    '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'],
292                           author=default_committer,
293                           committer=default_committer,
294                           encoding=None,
295                           message='Merge ../b\n',
296                           extra=None):
297         lines = []
298         if tree is not None:
299             lines.append('tree %s' % tree)
300         if parents is not None:
301             lines.extend('parent %s' % p for p in parents)
302         if author is not None:
303             lines.append('author %s' % author)
304         if committer is not None:
305             lines.append('committer %s' % committer)
306         if encoding is not None:
307             lines.append('encoding %s' % encoding)
308         if extra is not None:
309             for name, value in sorted(extra.iteritems()):
310                 lines.append('%s %s' % (name, value))
311         lines.append('')
312         if message is not None:
313             lines.append(message)
314         return lines
315
316     def make_commit_text(self, **kwargs):
317         return '\n'.join(self.make_commit_lines(**kwargs))
318
319     def test_simple(self):
320         c = Commit.from_string(self.make_commit_text())
321         self.assertEquals('Merge ../b\n', c.message)
322         self.assertEquals('James Westby <jw+debian@jameswestby.net>', c.author)
323         self.assertEquals('James Westby <jw+debian@jameswestby.net>',
324                           c.committer)
325         self.assertEquals('d80c186a03f423a81b39df39dc87fd269736ca86', c.tree)
326         self.assertEquals(['ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
327                            '4cffe90e0a41ad3f5190079d7c8f036bde29cbe6'],
328                           c.parents)
329         expected_time = datetime.datetime(2007, 3, 24, 22, 1, 59)
330         self.assertEquals(expected_time,
331                           datetime.datetime.utcfromtimestamp(c.commit_time))
332         self.assertEquals(0, c.commit_timezone)
333         self.assertEquals(expected_time,
334                           datetime.datetime.utcfromtimestamp(c.author_time))
335         self.assertEquals(0, c.author_timezone)
336         self.assertEquals(None, c.encoding)
337
338     def test_custom(self):
339         c = Commit.from_string(self.make_commit_text(
340           extra={'extra-field': 'data'}))
341         self.assertEquals([('extra-field', 'data')], c.extra)
342
343     def test_encoding(self):
344         c = Commit.from_string(self.make_commit_text(encoding='UTF-8'))
345         self.assertEquals('UTF-8', c.encoding)
346
347     def test_check(self):
348         self.assertCheckSucceeds(Commit, self.make_commit_text())
349         self.assertCheckSucceeds(Commit, self.make_commit_text(parents=None))
350         self.assertCheckSucceeds(Commit,
351                                  self.make_commit_text(encoding='UTF-8'))
352
353         self.assertCheckFails(Commit, self.make_commit_text(tree='xxx'))
354         self.assertCheckFails(Commit, self.make_commit_text(
355           parents=[a_sha, 'xxx']))
356         bad_committer = "some guy without an email address 1174773719 +0000"
357         self.assertCheckFails(Commit,
358                               self.make_commit_text(committer=bad_committer))
359         self.assertCheckFails(Commit,
360                               self.make_commit_text(author=bad_committer))
361         self.assertCheckFails(Commit, self.make_commit_text(author=None))
362         self.assertCheckFails(Commit, self.make_commit_text(committer=None))
363         self.assertCheckFails(Commit, self.make_commit_text(
364           author=None, committer=None))
365
366     def test_check_duplicates(self):
367         # duplicate each of the header fields
368         for i in xrange(5):
369             lines = self.make_commit_lines(parents=[a_sha], encoding='UTF-8')
370             lines.insert(i, lines[i])
371             text = '\n'.join(lines)
372             if lines[i].startswith('parent'):
373                 # duplicate parents are ok for now
374                 self.assertCheckSucceeds(Commit, text)
375             else:
376                 self.assertCheckFails(Commit, text)
377
378     def test_check_order(self):
379         lines = self.make_commit_lines(parents=[a_sha], encoding='UTF-8')
380         headers = lines[:5]
381         rest = lines[5:]
382         # of all possible permutations, ensure only the original succeeds
383         for perm in permutations(headers):
384             perm = list(perm)
385             text = '\n'.join(perm + rest)
386             if perm == headers:
387                 self.assertCheckSucceeds(Commit, text)
388             else:
389                 self.assertCheckFails(Commit, text)
390
391
392 class TreeTests(ShaFileCheckTests):
393
394     def test_simple(self):
395         myhexsha = "d80c186a03f423a81b39df39dc87fd269736ca86"
396         x = Tree()
397         x["myname"] = (0100755, myhexsha)
398         self.assertEquals('100755 myname\0' + hex_to_sha(myhexsha),
399                 x.as_raw_string())
400
401     def test_tree_dir_sort(self):
402         x = Tree()
403         x["a.c"] = (0100755, "d80c186a03f423a81b39df39dc87fd269736ca86")
404         x["a"] = (stat.S_IFDIR, "d80c186a03f423a81b39df39dc87fd269736ca86")
405         x["a/c"] = (stat.S_IFDIR, "d80c186a03f423a81b39df39dc87fd269736ca86")
406         self.assertEquals(["a.c", "a", "a/c"], [p[0] for p in x.iteritems()])
407
408     def _do_test_parse_tree(self, parse_tree):
409         o = Tree.from_file(os.path.join(os.path.dirname(__file__), 'data',
410                                         'trees', tree_sha))
411         o._parse_file()
412         self.assertEquals([('a', 0100644, a_sha), ('b', 0100644, b_sha)],
413                           list(parse_tree(o.as_raw_string())))
414
415     def test_parse_tree(self):
416         self._do_test_parse_tree(_parse_tree_py)
417
418     def test_parse_tree_extension(self):
419         if parse_tree is _parse_tree_py:
420             raise TestSkipped('parse_tree extension not found')
421         self._do_test_parse_tree(parse_tree)
422
423     def test_check(self):
424         t = Tree
425         sha = hex_to_sha(a_sha)
426
427         # filenames
428         self.assertCheckSucceeds(t, '100644 .a\0%s' % sha)
429         self.assertCheckFails(t, '100644 \0%s' % sha)
430         self.assertCheckFails(t, '100644 .\0%s' % sha)
431         self.assertCheckFails(t, '100644 a/a\0%s' % sha)
432         self.assertCheckFails(t, '100644 ..\0%s' % sha)
433
434         # modes
435         self.assertCheckSucceeds(t, '100644 a\0%s' % sha)
436         self.assertCheckSucceeds(t, '100755 a\0%s' % sha)
437         self.assertCheckSucceeds(t, '160000 a\0%s' % sha)
438         # TODO more whitelisted modes
439         self.assertCheckFails(t, '123456 a\0%s' % sha)
440         self.assertCheckFails(t, '123abc a\0%s' % sha)
441
442         # shas
443         self.assertCheckFails(t, '100644 a\0%s' % ('x' * 5))
444         self.assertCheckFails(t, '100644 a\0%s' % ('x' * 18 + '\0'))
445         self.assertCheckFails(t, '100644 a\0%s\n100644 b\0%s' % ('x' * 21, sha))
446
447         # ordering
448         sha2 = hex_to_sha(b_sha)
449         self.assertCheckSucceeds(t, '100644 a\0%s\n100644 b\0%s' % (sha, sha))
450         self.assertCheckSucceeds(t, '100644 a\0%s\n100644 b\0%s' % (sha, sha2))
451         self.assertCheckFails(t, '100644 a\0%s\n100755 a\0%s' % (sha, sha2))
452         self.assertCheckFails(t, '100644 b\0%s\n100644 a\0%s' % (sha2, sha))
453
454     def test_iter(self):
455         t = Tree()
456         t["foo"] = (0100644, a_sha)
457         self.assertEquals(set(["foo"]), set(t))
458
459
460 class TagSerializeTests(unittest.TestCase):
461
462     def test_serialize_simple(self):
463         x = Tag()
464         x.tagger = "Jelmer Vernooij <jelmer@samba.org>"
465         x.name = "0.1"
466         x.message = "Tag 0.1"
467         x.object = (Blob, "d80c186a03f423a81b39df39dc87fd269736ca86")
468         x.tag_time = 423423423
469         x.tag_timezone = 0
470         self.assertEquals("""object d80c186a03f423a81b39df39dc87fd269736ca86
471 type blob
472 tag 0.1
473 tagger Jelmer Vernooij <jelmer@samba.org> 423423423 +0000
474
475 Tag 0.1""", x.as_raw_string())
476
477
478 default_tagger = ('Linus Torvalds <torvalds@woody.linux-foundation.org> '
479                   '1183319674 -0700')
480 default_message = """Linux 2.6.22-rc7
481 -----BEGIN PGP SIGNATURE-----
482 Version: GnuPG v1.4.7 (GNU/Linux)
483
484 iD8DBQBGiAaAF3YsRnbiHLsRAitMAKCiLboJkQECM/jpYsY3WPfvUgLXkACgg3ql
485 OK2XeQOiEeXtT76rV4t2WR4=
486 =ivrA
487 -----END PGP SIGNATURE-----
488 """
489
490
491 class TagParseTests(ShaFileCheckTests):
492     def make_tag_lines(self,
493                        object_sha="a38d6181ff27824c79fc7df825164a212eff6a3f",
494                        object_type_name="commit",
495                        name="v2.6.22-rc7",
496                        tagger=default_tagger,
497                        message=default_message):
498         lines = []
499         if object_sha is not None:
500             lines.append("object %s" % object_sha)
501         if object_type_name is not None:
502             lines.append("type %s" % object_type_name)
503         if name is not None:
504             lines.append("tag %s" % name)
505         if tagger is not None:
506             lines.append("tagger %s" % tagger)
507         lines.append("")
508         if message is not None:
509             lines.append(message)
510         return lines
511
512     def make_tag_text(self, **kwargs):
513         return "\n".join(self.make_tag_lines(**kwargs))
514
515     def test_parse(self):
516         x = Tag()
517         x.set_raw_string(self.make_tag_text())
518         self.assertEquals(
519             "Linus Torvalds <torvalds@woody.linux-foundation.org>", x.tagger)
520         self.assertEquals("v2.6.22-rc7", x.name)
521         object_type, object_sha = x.object
522         self.assertEquals("a38d6181ff27824c79fc7df825164a212eff6a3f",
523                           object_sha)
524         self.assertEquals(Commit, object_type)
525         self.assertEquals(datetime.datetime.utcfromtimestamp(x.tag_time),
526                           datetime.datetime(2007, 7, 1, 19, 54, 34))
527         self.assertEquals(-25200, x.tag_timezone)
528
529     def test_parse_no_tagger(self):
530         x = Tag()
531         x.set_raw_string(self.make_tag_text(tagger=None))
532         self.assertEquals(None, x.tagger)
533         self.assertEquals("v2.6.22-rc7", x.name)
534
535     def test_check(self):
536         self.assertCheckSucceeds(Tag, self.make_tag_text())
537         self.assertCheckFails(Tag, self.make_tag_text(object_sha=None))
538         self.assertCheckFails(Tag, self.make_tag_text(object_type_name=None))
539         self.assertCheckFails(Tag, self.make_tag_text(name=None))
540         self.assertCheckFails(Tag, self.make_tag_text(name=''))
541         self.assertCheckFails(Tag, self.make_tag_text(
542           object_type_name="foobar"))
543         self.assertCheckFails(Tag, self.make_tag_text(
544           tagger="some guy without an email address 1183319674 -0700"))
545         self.assertCheckFails(Tag, self.make_tag_text(
546           tagger=("Linus Torvalds <torvalds@woody.linux-foundation.org> "
547                   "Sun 7 Jul 2007 12:54:34 +0700")))
548         self.assertCheckFails(Tag, self.make_tag_text(object_sha="xxx"))
549
550     def test_check_duplicates(self):
551         # duplicate each of the header fields
552         for i in xrange(4):
553             lines = self.make_tag_lines()
554             lines.insert(i, lines[i])
555             self.assertCheckFails(Tag, '\n'.join(lines))
556
557     def test_check_order(self):
558         lines = self.make_tag_lines()
559         headers = lines[:4]
560         rest = lines[4:]
561         # of all possible permutations, ensure only the original succeeds
562         for perm in permutations(headers):
563             perm = list(perm)
564             text = '\n'.join(perm + rest)
565             if perm == headers:
566                 self.assertCheckSucceeds(Tag, text)
567             else:
568                 self.assertCheckFails(Tag, text)
569
570
571 class CheckTests(unittest.TestCase):
572
573     def test_check_hexsha(self):
574         check_hexsha(a_sha, "failed to check good sha")
575         self.assertRaises(ObjectFormatException, check_hexsha, '1' * 39,
576                           'sha too short')
577         self.assertRaises(ObjectFormatException, check_hexsha, '1' * 41,
578                           'sha too long')
579         self.assertRaises(ObjectFormatException, check_hexsha, 'x' * 40,
580                           'invalid characters')
581
582     def test_check_identity(self):
583         check_identity("Dave Borowitz <dborowitz@google.com>",
584                        "failed to check good identity")
585         check_identity("<dborowitz@google.com>",
586                        "failed to check good identity")
587         self.assertRaises(ObjectFormatException, check_identity,
588                           "Dave Borowitz", "no email")
589         self.assertRaises(ObjectFormatException, check_identity,
590                           "Dave Borowitz <dborowitz", "incomplete email")
591         self.assertRaises(ObjectFormatException, check_identity,
592                           "dborowitz@google.com>", "incomplete email")
593         self.assertRaises(ObjectFormatException, check_identity,
594                           "Dave Borowitz <<dborowitz@google.com>", "typo")
595         self.assertRaises(ObjectFormatException, check_identity,
596                           "Dave Borowitz <dborowitz@google.com>>", "typo")
597         self.assertRaises(ObjectFormatException, check_identity,
598                           "Dave Borowitz <dborowitz@google.com>xxx",
599                           "trailing characters")
600
601
602 class TimezoneTests(unittest.TestCase):
603
604     def test_parse_timezone_utc(self):
605         self.assertEquals((0, False), parse_timezone("+0000"))
606
607     def test_parse_timezone_utc_negative(self):
608         self.assertEquals((0, True), parse_timezone("-0000"))
609
610     def test_generate_timezone_utc(self):
611         self.assertEquals("+0000", format_timezone(0))
612
613     def test_generate_timezone_utc_negative(self):
614         self.assertEquals("-0000", format_timezone(0, True))
615
616     def test_parse_timezone_cet(self):
617         self.assertEquals((60 * 60, False), parse_timezone("+0100"))
618
619     def test_format_timezone_cet(self):
620         self.assertEquals("+0100", format_timezone(60 * 60))
621
622     def test_format_timezone_pdt(self):
623         self.assertEquals("-0400", format_timezone(-4 * 60 * 60))
624
625     def test_parse_timezone_pdt(self):
626         self.assertEquals((-4 * 60 * 60, False), parse_timezone("-0400"))
627
628     def test_format_timezone_pdt_half(self):
629         self.assertEquals("-0440",
630             format_timezone(int(((-4 * 60) - 40) * 60)))
631
632     def test_parse_timezone_pdt_half(self):
633         self.assertEquals((((-4 * 60) - 40) * 60, False),
634             parse_timezone("-0440"))