~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_smart_request.py

  • Committer: Ian Clatworthy
  • Date: 2007-08-13 14:33:10 UTC
  • mto: (2733.1.1 ianc-integration)
  • mto: This revision was merged to the branch mainline in revision 2734.
  • Revision ID: ian.clatworthy@internode.on.net-20070813143310-twhj4la0qnupvze8
Added Quick Start Summary

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2009, 2010 Canonical Ltd
2
 
#
3
 
# This program is free software; you can redistribute it and/or modify
4
 
# it under the terms of the GNU General Public License as published by
5
 
# the Free Software Foundation; either version 2 of the License, or
6
 
# (at your option) any later version.
7
 
#
8
 
# This program is distributed in the hope that it will be useful,
9
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
 
# GNU General Public License for more details.
12
 
#
13
 
# You should have received a copy of the GNU General Public License
14
 
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
17
 
"""Tests for smart server request infrastructure (bzrlib.smart.request)."""
18
 
 
19
 
import threading
20
 
 
21
 
from bzrlib import (
22
 
    errors,
23
 
    transport,
24
 
    )
25
 
from bzrlib.bzrdir import BzrDir
26
 
from bzrlib.smart import request
27
 
from bzrlib.tests import TestCase, TestCaseWithMemoryTransport
28
 
 
29
 
 
30
 
class NoBodyRequest(request.SmartServerRequest):
31
 
    """A request that does not implement do_body."""
32
 
 
33
 
    def do(self):
34
 
        return request.SuccessfulSmartServerResponse(('ok',))
35
 
 
36
 
 
37
 
class DoErrorRequest(request.SmartServerRequest):
38
 
    """A request that raises an error from self.do()."""
39
 
 
40
 
    def do(self):
41
 
        raise errors.NoSuchFile('xyzzy')
42
 
 
43
 
 
44
 
class DoUnexpectedErrorRequest(request.SmartServerRequest):
45
 
    """A request that encounters a generic error in self.do()"""
46
 
 
47
 
    def do(self):
48
 
        dict()[1]
49
 
 
50
 
 
51
 
class ChunkErrorRequest(request.SmartServerRequest):
52
 
    """A request that raises an error from self.do_chunk()."""
53
 
    
54
 
    def do(self):
55
 
        """No-op."""
56
 
        pass
57
 
 
58
 
    def do_chunk(self, bytes):
59
 
        raise errors.NoSuchFile('xyzzy')
60
 
 
61
 
 
62
 
class EndErrorRequest(request.SmartServerRequest):
63
 
    """A request that raises an error from self.do_end()."""
64
 
    
65
 
    def do(self):
66
 
        """No-op."""
67
 
        pass
68
 
 
69
 
    def do_chunk(self, bytes):
70
 
        """No-op."""
71
 
        pass
72
 
        
73
 
    def do_end(self):
74
 
        raise errors.NoSuchFile('xyzzy')
75
 
 
76
 
 
77
 
class CheckJailRequest(request.SmartServerRequest):
78
 
 
79
 
    def __init__(self, *args):
80
 
        request.SmartServerRequest.__init__(self, *args)
81
 
        self.jail_transports_log = []
82
 
 
83
 
    def do(self):
84
 
        self.jail_transports_log.append(request.jail_info.transports)
85
 
 
86
 
    def do_chunk(self, bytes):
87
 
        self.jail_transports_log.append(request.jail_info.transports)
88
 
 
89
 
    def do_end(self):
90
 
        self.jail_transports_log.append(request.jail_info.transports)
91
 
 
92
 
 
93
 
class TestSmartRequest(TestCase):
94
 
 
95
 
    def test_request_class_without_do_body(self):
96
 
        """If a request has no body data, and the request's implementation does
97
 
        not override do_body, then no exception is raised.
98
 
        """
99
 
        # Create a SmartServerRequestHandler with a SmartServerRequest subclass
100
 
        # that does not implement do_body.
101
 
        handler = request.SmartServerRequestHandler(
102
 
            None, {'foo': NoBodyRequest}, '/')
103
 
        # Emulate a request with no body (i.e. just args).
104
 
        handler.args_received(('foo',))
105
 
        handler.end_received()
106
 
        # Request done, no exception was raised.
107
 
 
108
 
    def test_only_request_code_is_jailed(self):
109
 
        transport = 'dummy transport'
110
 
        handler = request.SmartServerRequestHandler(
111
 
            transport, {'foo': CheckJailRequest}, '/')
112
 
        handler.args_received(('foo',))
113
 
        self.assertEqual(None, request.jail_info.transports)
114
 
        handler.accept_body('bytes')
115
 
        self.assertEqual(None, request.jail_info.transports)
116
 
        handler.end_received()
117
 
        self.assertEqual(None, request.jail_info.transports)
118
 
        self.assertEqual(
119
 
            [[transport]] * 3, handler._command.jail_transports_log)
120
 
 
121
 
 
122
 
 
123
 
class TestSmartRequestHandlerErrorTranslation(TestCase):
124
 
    """Tests that SmartServerRequestHandler will translate exceptions raised by
125
 
    a SmartServerRequest into FailedSmartServerResponses.
126
 
    """
127
 
 
128
 
    def assertNoResponse(self, handler):
129
 
        self.assertEqual(None, handler.response)
130
 
 
131
 
    def assertResponseIsTranslatedError(self, handler):
132
 
        expected_translation = ('NoSuchFile', 'xyzzy')
133
 
        self.assertEqual(
134
 
            request.FailedSmartServerResponse(expected_translation),
135
 
            handler.response)
136
 
 
137
 
    def test_error_translation_from_args_received(self):
138
 
        handler = request.SmartServerRequestHandler(
139
 
            None, {'foo': DoErrorRequest}, '/')
140
 
        handler.args_received(('foo',))
141
 
        self.assertResponseIsTranslatedError(handler)
142
 
 
143
 
    def test_error_translation_from_chunk_received(self):
144
 
        handler = request.SmartServerRequestHandler(
145
 
            None, {'foo': ChunkErrorRequest}, '/')
146
 
        handler.args_received(('foo',))
147
 
        self.assertNoResponse(handler)
148
 
        handler.accept_body('bytes')
149
 
        self.assertResponseIsTranslatedError(handler)
150
 
 
151
 
    def test_error_translation_from_end_received(self):
152
 
        handler = request.SmartServerRequestHandler(
153
 
            None, {'foo': EndErrorRequest}, '/')
154
 
        handler.args_received(('foo',))
155
 
        self.assertNoResponse(handler)
156
 
        handler.end_received()
157
 
        self.assertResponseIsTranslatedError(handler)
158
 
 
159
 
    def test_unexpected_error_translation(self):
160
 
        handler = request.SmartServerRequestHandler(
161
 
            None, {'foo': DoUnexpectedErrorRequest}, '/')
162
 
        handler.args_received(('foo',))
163
 
        self.assertEqual(
164
 
            request.FailedSmartServerResponse(('error', 'KeyError', "1")),
165
 
            handler.response)
166
 
 
167
 
 
168
 
class TestRequestHanderErrorTranslation(TestCase):
169
 
    """Tests for bzrlib.smart.request._translate_error."""
170
 
 
171
 
    def assertTranslationEqual(self, expected_tuple, error):
172
 
        self.assertEqual(expected_tuple, request._translate_error(error))
173
 
 
174
 
    def test_NoSuchFile(self):
175
 
        self.assertTranslationEqual(
176
 
            ('NoSuchFile', 'path'), errors.NoSuchFile('path'))
177
 
 
178
 
    def test_LockContention(self):
179
 
        # For now, LockContentions are always transmitted with no details.
180
 
        # Eventually they should include a relpath or url or something else to
181
 
        # identify which lock is busy.
182
 
        self.assertTranslationEqual(
183
 
            ('LockContention',), errors.LockContention('lock', 'msg'))
184
 
 
185
 
    def test_TokenMismatch(self):
186
 
        self.assertTranslationEqual(
187
 
            ('TokenMismatch', 'some-token', 'actual-token'),
188
 
            errors.TokenMismatch('some-token', 'actual-token'))
189
 
 
190
 
    def test_MemoryError(self):
191
 
        self.assertTranslationEqual(("MemoryError",), MemoryError())
192
 
 
193
 
    def test_generic_Exception(self):
194
 
        self.assertTranslationEqual(('error', 'Exception', ""),
195
 
            Exception())
196
 
 
197
 
    def test_generic_BzrError(self):
198
 
        self.assertTranslationEqual(('error', 'BzrError', "some text"),
199
 
            errors.BzrError(msg="some text"))
200
 
 
201
 
    def test_generic_zlib_error(self):
202
 
        from zlib import error
203
 
        msg = "Error -3 while decompressing data: incorrect data check"
204
 
        self.assertTranslationEqual(('error', 'zlib.error', msg),
205
 
            error(msg))
206
 
 
207
 
 
208
 
class TestRequestJail(TestCaseWithMemoryTransport):
209
 
 
210
 
    def test_jail(self):
211
 
        transport = self.get_transport('blah')
212
 
        req = request.SmartServerRequest(transport)
213
 
        self.assertEqual(None, request.jail_info.transports)
214
 
        req.setup_jail()
215
 
        self.assertEqual([transport], request.jail_info.transports)
216
 
        req.teardown_jail()
217
 
        self.assertEqual(None, request.jail_info.transports)
218
 
 
219
 
 
220
 
class TestJailHook(TestCaseWithMemoryTransport):
221
 
 
222
 
    def setUp(self):
223
 
        super(TestJailHook, self).setUp()
224
 
        def clear_jail_info():
225
 
            request.jail_info.transports = None
226
 
        self.addCleanup(clear_jail_info)
227
 
 
228
 
    def test_jail_hook(self):
229
 
        request.jail_info.transports = None
230
 
        _pre_open_hook = request._pre_open_hook
231
 
        # Any transport is fine if jail_info.transports is None
232
 
        t = self.get_transport('foo')
233
 
        _pre_open_hook(t)
234
 
        # A transport in jail_info.transports is allowed
235
 
        request.jail_info.transports = [t]
236
 
        _pre_open_hook(t)
237
 
        # A child of a transport in jail_info is allowed
238
 
        _pre_open_hook(t.clone('child'))
239
 
        # A parent is not allowed
240
 
        self.assertRaises(errors.JailBreak, _pre_open_hook, t.clone('..'))
241
 
        # A completely unrelated transport is not allowed
242
 
        self.assertRaises(errors.JailBreak, _pre_open_hook,
243
 
                          transport.get_transport_from_url('http://host/'))
244
 
 
245
 
    def test_open_bzrdir_in_non_main_thread(self):
246
 
        """Opening a bzrdir in a non-main thread should work ok.
247
 
        
248
 
        This makes sure that the globally-installed
249
 
        bzrlib.smart.request._pre_open_hook, which uses a threading.local(),
250
 
        works in a newly created thread.
251
 
        """
252
 
        bzrdir = self.make_bzrdir('.')
253
 
        transport = bzrdir.root_transport
254
 
        thread_result = []
255
 
        def t():
256
 
            BzrDir.open_from_transport(transport)
257
 
            thread_result.append('ok')
258
 
        thread = threading.Thread(target=t)
259
 
        thread.start()
260
 
        thread.join()
261
 
        self.assertEqual(['ok'], thread_result)
262