~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_errors.py

Merge and cleanup pre-external-reference-repository tests

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
 
2
#   Authors: Robert Collins <robert.collins@canonical.com>
 
3
#            and others
2
4
#
3
5
# This program is free software; you can redistribute it and/or modify
4
6
# it under the terms of the GNU General Public License as published by
12
14
#
13
15
# You should have received a copy of the GNU General Public License
14
16
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
18
 
17
19
"""Tests for the formatting and construction of errors."""
18
20
 
19
 
import inspect
20
 
import re
21
 
import socket
22
 
import sys
23
 
 
24
21
from bzrlib import (
25
22
    bzrdir,
26
23
    errors,
27
24
    osutils,
 
25
    symbol_versioning,
28
26
    urlutils,
29
27
    )
30
 
from bzrlib.tests import (
31
 
    TestCase,
32
 
    TestCaseWithTransport,
33
 
    TestSkipped,
34
 
    )
 
28
from bzrlib.tests import TestCase, TestCaseWithTransport
35
29
 
36
30
 
37
31
class TestErrors(TestCaseWithTransport):
38
32
 
39
 
    def test_no_arg_named_message(self):
40
 
        """Ensure the __init__ and _fmt in errors do not have "message" arg.
41
 
 
42
 
        This test fails if __init__ or _fmt in errors has an argument
43
 
        named "message" as this can cause errors in some Python versions.
44
 
        Python 2.5 uses a slot for StandardError.message.
45
 
        See bug #603461
46
 
        """
47
 
        fmt_pattern = re.compile("%\(message\)[sir]")
48
 
        subclasses_present = getattr(errors.BzrError, '__subclasses__', None)
49
 
        if not subclasses_present:
50
 
            raise TestSkipped('__subclasses__ attribute required for classes. '
51
 
                'Requires Python 2.5 or later.')
52
 
        for c in errors.BzrError.__subclasses__():
53
 
            init = getattr(c, '__init__', None)
54
 
            fmt = getattr(c, '_fmt', None)
55
 
            if init:
56
 
                args = inspect.getargspec(init)[0]
57
 
                self.assertFalse('message' in args,
58
 
                    ('Argument name "message" not allowed for '
59
 
                    '"errors.%s.__init__"' % c.__name__))
60
 
            if fmt and fmt_pattern.search(fmt):
61
 
                self.assertFalse(True, ('"message" not allowed in '
62
 
                    '"errors.%s._fmt"' % c.__name__))
63
 
 
64
 
    def test_bad_filename_encoding(self):
65
 
        error = errors.BadFilenameEncoding('bad/filen\xe5me', 'UTF-8')
66
 
        self.assertEqualDiff(
67
 
            "Filename 'bad/filen\\xe5me' is not valid in your current"
68
 
            " filesystem encoding UTF-8",
69
 
            str(error))
70
 
 
71
33
    def test_corrupt_dirstate(self):
72
34
        error = errors.CorruptDirstate('path/to/dirstate', 'the reason why')
73
35
        self.assertEqualDiff(
75
37
            "Error: the reason why",
76
38
            str(error))
77
39
 
78
 
    def test_dirstate_corrupt(self):
79
 
        error = errors.DirstateCorrupt('.bzr/checkout/dirstate',
80
 
                                       'trailing garbage: "x"')
81
 
        self.assertEqualDiff("The dirstate file (.bzr/checkout/dirstate)"
82
 
            " appears to be corrupt: trailing garbage: \"x\"",
83
 
            str(error))
84
 
 
85
40
    def test_disabled_method(self):
86
41
        error = errors.DisabledMethod("class name")
87
42
        self.assertEqualDiff(
117
72
            "reason: reason for foo",
118
73
            str(error))
119
74
 
120
 
    def test_inconsistent_delta_delta(self):
121
 
        error = errors.InconsistentDeltaDelta([], 'reason')
122
 
        self.assertEqualDiff(
123
 
            "An inconsistent delta was supplied: []\nreason: reason",
124
 
            str(error))
125
 
 
126
75
    def test_in_process_transport(self):
127
76
        error = errors.InProcessTransport('fpp')
128
77
        self.assertEqualDiff(
150
99
            "read without data loss.",
151
100
            str(error))
152
101
 
153
 
    def test_jail_break(self):
154
 
        error = errors.JailBreak("some url")
155
 
        self.assertEqualDiff("An attempt to access a url outside the server"
156
 
            " jail was made: 'some url'.",
157
 
            str(error))
 
102
    def test_install_failed(self):
 
103
        error = errors.InstallFailed(['rev-one'])
 
104
        self.assertEqual("Could not install revisions:\nrev-one", str(error))
 
105
        error = errors.InstallFailed(['rev-one', 'rev-two'])
 
106
        self.assertEqual("Could not install revisions:\nrev-one, rev-two",
 
107
                         str(error))
 
108
        error = errors.InstallFailed([None])
 
109
        self.assertEqual("Could not install revisions:\nNone", str(error))
158
110
 
159
111
    def test_lock_active(self):
160
112
        error = errors.LockActive("lock description")
162
114
            "cannot be broken.",
163
115
            str(error))
164
116
 
165
 
    def test_lock_corrupt(self):
166
 
        error = errors.LockCorrupt("corruption info")
167
 
        self.assertEqualDiff("Lock is apparently held, but corrupted: "
168
 
            "corruption info\n"
169
 
            "Use 'bzr break-lock' to clear it",
170
 
            str(error))
171
 
 
172
117
    def test_knit_data_stream_incompatible(self):
173
118
        error = errors.KnitDataStreamIncompatible(
174
119
            'stream format', 'target format')
198
143
        error = errors.MediumNotConnected("a medium")
199
144
        self.assertEqualDiff(
200
145
            "The medium 'a medium' is not connected.", str(error))
201
 
 
 
146
 
202
147
    def test_no_public_branch(self):
203
148
        b = self.make_branch('.')
204
149
        error = errors.NoPublicBranch(b)
211
156
        error = errors.NoRepositoryPresent(dir)
212
157
        self.assertNotEqual(-1, str(error).find((dir.transport.clone('..').base)))
213
158
        self.assertEqual(-1, str(error).find((dir.transport.base)))
214
 
 
 
159
        
215
160
    def test_no_smart_medium(self):
216
161
        error = errors.NoSmartMedium("a transport")
217
162
        self.assertEqualDiff("The transport 'a transport' cannot tunnel the "
285
230
            "You will need to upgrade the branch to permit branch stacking.",
286
231
            str(error))
287
232
 
288
 
    def test_unstackable_location(self):
289
 
        error = errors.UnstackableLocationError('foo', 'bar')
290
 
        self.assertEqualDiff("The branch 'foo' cannot be stacked on 'bar'.",
291
 
            str(error))
292
 
 
293
233
    def test_unstackable_repository_format(self):
294
234
        format = u'foo'
295
235
        url = "/foo"
300
240
            str(error))
301
241
 
302
242
    def test_up_to_date(self):
303
 
        error = errors.UpToDateFormat("someformat")
304
 
        self.assertEqualDiff(
305
 
            "The branch format someformat is already at the most "
306
 
            "recent format.", str(error))
 
243
        error = errors.UpToDateFormat(bzrdir.BzrDirFormat4())
 
244
        self.assertEqualDiff("The branch format Bazaar-NG branch, "
 
245
                             "format 0.0.4 is already at the most "
 
246
                             "recent format.",
 
247
                             str(error))
307
248
 
308
249
    def test_corrupt_repository(self):
309
250
        repo = self.make_repository('.')
435
376
            host='ahost', port=444, msg='Unable to connect to ssh host',
436
377
            orig_error='my_error')
437
378
 
438
 
    def test_target_not_branch(self):
439
 
        """Test the formatting of TargetNotBranch."""
440
 
        error = errors.TargetNotBranch('foo')
441
 
        self.assertEqual(
442
 
            "Your branch does not have all of the revisions required in "
443
 
            "order to merge this merge directive and the target "
444
 
            "location specified in the merge directive is not a branch: "
445
 
            "foo.", str(error))
446
 
 
447
379
    def test_malformed_bug_identifier(self):
448
380
        """Test the formatting of MalformedBugIdentifier."""
449
381
        error = errors.MalformedBugIdentifier('bogus', 'reason for bogosity')
450
382
        self.assertEqual(
451
 
            'Did not understand bug identifier bogus: reason for bogosity. '
452
 
            'See "bzr help bugs" for more information on this feature.',
 
383
            "Did not understand bug identifier bogus: reason for bogosity",
453
384
            str(error))
454
385
 
455
386
    def test_unknown_bug_tracker_abbreviation(self):
506
437
        self.assertEqual(
507
438
            "Container has multiple records with the same name: n\xc3\xa5me",
508
439
            str(e))
509
 
 
 
440
        
510
441
    def test_check_error(self):
511
442
        # This has a member called 'message', which is problematic in
512
443
        # python2.5 because that is a slot on the base Exception class
568
499
        err = errors.UnknownFormatError('bar', kind='foo')
569
500
        self.assertEquals("Unknown foo format: 'bar'", str(err))
570
501
 
571
 
    def test_unknown_rules(self):
572
 
        err = errors.UnknownRules(['foo', 'bar'])
573
 
        self.assertEquals("Unknown rules detected: foo, bar.", str(err))
574
 
 
575
 
    def test_hook_failed(self):
576
 
        # Create an exc_info tuple by raising and catching an exception.
577
 
        try:
578
 
            1/0
579
 
        except ZeroDivisionError:
580
 
            err = errors.HookFailed('hook stage', 'hook name', sys.exc_info(),
581
 
                warn=False)
582
 
        # GZ 2010-11-08: Should not store exc_info in exception instances, but
583
 
        #                HookFailed is deprecated anyway and could maybe go.
584
 
        try:
585
 
            self.assertStartsWith(
586
 
                str(err), 'Hook \'hook name\' during hook stage failed:\n')
587
 
            self.assertEndsWith(
588
 
                str(err), 'integer division or modulo by zero')
589
 
        finally:
590
 
            del err
591
 
 
592
 
    def test_tip_change_rejected(self):
593
 
        err = errors.TipChangeRejected(u'Unicode message\N{INTERROBANG}')
594
 
        self.assertEquals(
595
 
            u'Tip change rejected: Unicode message\N{INTERROBANG}',
596
 
            unicode(err))
597
 
        self.assertEquals(
598
 
            'Tip change rejected: Unicode message\xe2\x80\xbd',
599
 
            str(err))
600
 
 
601
 
    def test_error_from_smart_server(self):
602
 
        error_tuple = ('error', 'tuple')
603
 
        err = errors.ErrorFromSmartServer(error_tuple)
604
 
        self.assertEquals(
605
 
            "Error received from smart server: ('error', 'tuple')", str(err))
606
 
 
607
 
    def test_untranslateable_error_from_smart_server(self):
608
 
        error_tuple = ('error', 'tuple')
609
 
        orig_err = errors.ErrorFromSmartServer(error_tuple)
610
 
        err = errors.UnknownErrorFromSmartServer(orig_err)
611
 
        self.assertEquals(
612
 
            "Server sent an unexpected error: ('error', 'tuple')", str(err))
613
 
 
614
 
    def test_smart_message_handler_error(self):
615
 
        # Make an exc_info tuple.
616
 
        try:
617
 
            raise Exception("example error")
618
 
        except Exception:
619
 
            err = errors.SmartMessageHandlerError(sys.exc_info())
620
 
        # GZ 2010-11-08: Should not store exc_info in exception instances.
621
 
        try:
622
 
            self.assertStartsWith(
623
 
                str(err), "The message handler raised an exception:\n")
624
 
            self.assertEndsWith(str(err), "Exception: example error\n")
625
 
        finally:
626
 
            del err
627
 
 
628
 
    def test_must_have_working_tree(self):
629
 
        err = errors.MustHaveWorkingTree('foo', 'bar')
630
 
        self.assertEqual(str(err), "Branching 'bar'(foo) must create a"
631
 
                                   " working tree.")
632
 
 
633
 
    def test_no_such_view(self):
634
 
        err = errors.NoSuchView('foo')
635
 
        self.assertEquals("No such view: foo.", str(err))
636
 
 
637
 
    def test_views_not_supported(self):
638
 
        err = errors.ViewsNotSupported('atree')
639
 
        err_str = str(err)
640
 
        self.assertStartsWith(err_str, "Views are not supported by ")
641
 
        self.assertEndsWith(err_str, "; use 'bzr upgrade' to change your "
642
 
            "tree to a later format.")
643
 
 
644
 
    def test_file_outside_view(self):
645
 
        err = errors.FileOutsideView('baz', ['foo', 'bar'])
646
 
        self.assertEquals('Specified file "baz" is outside the current view: '
647
 
            'foo, bar', str(err))
648
 
 
649
 
    def test_invalid_shelf_id(self):
650
 
        invalid_id = "foo"
651
 
        err = errors.InvalidShelfId(invalid_id)
652
 
        self.assertEqual('"foo" is not a valid shelf id, '
653
 
            'try a number instead.', str(err))
654
 
 
655
 
    def test_unresumable_write_group(self):
656
 
        repo = "dummy repo"
657
 
        wg_tokens = ['token']
658
 
        reason = "a reason"
659
 
        err = errors.UnresumableWriteGroup(repo, wg_tokens, reason)
660
 
        self.assertEqual(
661
 
            "Repository dummy repo cannot resume write group "
662
 
            "['token']: a reason", str(err))
663
 
 
664
 
    def test_unsuspendable_write_group(self):
665
 
        repo = "dummy repo"
666
 
        err = errors.UnsuspendableWriteGroup(repo)
667
 
        self.assertEqual(
668
 
            'Repository dummy repo cannot suspend a write group.', str(err))
669
 
 
670
 
    def test_not_branch_no_args(self):
671
 
        err = errors.NotBranchError('path')
672
 
        self.assertEqual('Not a branch: "path".', str(err))
673
 
 
674
 
    def test_not_branch_bzrdir_with_repo(self):
675
 
        bzrdir = self.make_repository('repo').bzrdir
676
 
        err = errors.NotBranchError('path', bzrdir=bzrdir)
677
 
        self.assertEqual(
678
 
            'Not a branch: "path": location is a repository.', str(err))
679
 
 
680
 
    def test_not_branch_bzrdir_without_repo(self):
681
 
        bzrdir = self.make_bzrdir('bzrdir')
682
 
        err = errors.NotBranchError('path', bzrdir=bzrdir)
683
 
        self.assertEqual('Not a branch: "path".', str(err))
684
 
 
685
 
    def test_not_branch_bzrdir_with_recursive_not_branch_error(self):
686
 
        class FakeBzrDir(object):
687
 
            def open_repository(self):
688
 
                # str() on the NotBranchError will trigger a call to this,
689
 
                # which in turn will another, identical NotBranchError.
690
 
                raise errors.NotBranchError('path', bzrdir=FakeBzrDir())
691
 
        err = errors.NotBranchError('path', bzrdir=FakeBzrDir())
692
 
        self.assertEqual('Not a branch: "path".', str(err))
693
 
 
694
 
    def test_not_branch_laziness(self):
695
 
        real_bzrdir = self.make_bzrdir('path')
696
 
        class FakeBzrDir(object):
697
 
            def __init__(self):
698
 
                self.calls = []
699
 
            def open_repository(self):
700
 
                self.calls.append('open_repository')
701
 
                raise errors.NoRepositoryPresent(real_bzrdir)
702
 
        fake_bzrdir = FakeBzrDir()
703
 
        err = errors.NotBranchError('path', bzrdir=fake_bzrdir)
704
 
        self.assertEqual([], fake_bzrdir.calls)
705
 
        str(err)
706
 
        self.assertEqual(['open_repository'], fake_bzrdir.calls)
707
 
        # Stringifying twice doesn't try to open a repository twice.
708
 
        str(err)
709
 
        self.assertEqual(['open_repository'], fake_bzrdir.calls)
710
 
 
711
 
    def test_invalid_pattern(self):
712
 
        error = errors.InvalidPattern('Bad pattern msg.')
713
 
        self.assertEqualDiff("Invalid pattern(s) found. Bad pattern msg.",
714
 
            str(error))
715
 
 
716
 
    def test_recursive_bind(self):
717
 
        error = errors.RecursiveBind('foo_bar_branch')
718
 
        msg = ('Branch "foo_bar_branch" appears to be bound to itself. '
719
 
            'Please use `bzr unbind` to fix.')
720
 
        self.assertEqualDiff(msg, str(error))
721
 
 
722
502
 
723
503
class PassThroughError(errors.BzrError):
724
 
 
 
504
    
725
505
    _fmt = """Pass through %(foo)s and %(bar)s"""
726
506
 
727
507
    def __init__(self, foo, bar):
734
514
 
735
515
 
736
516
class ErrorWithNoFormat(errors.BzrError):
737
 
    __doc__ = """This class has a docstring but no format string."""
 
517
    """This class has a docstring but no format string."""
738
518
 
739
519
 
740
520
class TestErrorFormatting(TestCase):
741
 
 
 
521
    
742
522
    def test_always_str(self):
743
523
        e = PassThroughError(u'\xb5', 'bar')
744
524
        self.assertIsInstance(e.__str__(), str)
755
535
                ['ErrorWithNoFormat uses its docstring as a format, it should use _fmt instead'],
756
536
                lambda x: str(x), e)
757
537
        ## s = str(e)
758
 
        self.assertEqual(s,
 
538
        self.assertEqual(s, 
759
539
                "This class has a docstring but no format string.")
760
540
 
761
541
    def test_mismatched_format_args(self):
765
545
        e = ErrorWithBadFormat(not_thing='x')
766
546
        self.assertStartsWith(
767
547
            str(e), 'Unprintable exception ErrorWithBadFormat')
768
 
 
769
 
    def test_cannot_bind_address(self):
770
 
        # see <https://bugs.launchpad.net/bzr/+bug/286871>
771
 
        e = errors.CannotBindAddress('example.com', 22,
772
 
            socket.error(13, 'Permission denied'))
773
 
        self.assertContainsRe(str(e),
774
 
            r'Cannot bind address "example\.com:22":.*Permission denied')
775
 
 
776
 
    def test_file_timestamp_unavailable(self):            
777
 
        e = errors.FileTimestampUnavailable("/path/foo")
778
 
        self.assertEquals("The filestamp for /path/foo is not available.",
779
 
            str(e))
780
 
            
781
 
    def test_transform_rename_failed(self):
782
 
        e = errors.TransformRenameFailed(u"from", u"to", "readonly file", 2)
783
 
        self.assertEquals(
784
 
            u"Failed to rename from to to: readonly file",
785
 
            str(e))