/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4986.2.1 by Martin Pool
Remove tearDown in tests in favor of addCleanup
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Canonical Ltd
1540.3.24 by Martin Pool
Add new protocol 'http+pycurl' that always uses PyCurl.
2
#
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
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.
1540.3.24 by Martin Pool
Add new protocol 'http+pycurl' that always uses PyCurl.
7
#
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
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.
1540.3.24 by Martin Pool
Add new protocol 'http+pycurl' that always uses PyCurl.
12
#
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1185.16.68 by Martin Pool
- http url fixes suggested by Robey Pointer, and tests
16
3111.1.30 by Vincent Ladeuil
Update NEWS. Some cosmetic changes.
17
"""Tests for HTTP implementations.
3111.1.10 by Vincent Ladeuil
Finish http parameterization, 24 auth tests failing for pycurl (not
18
3111.1.30 by Vincent Ladeuil
Update NEWS. Some cosmetic changes.
19
This module defines a load_tests() method that parametrize tests classes for
20
transport implementation, http protocol versions and authentication schemes.
3111.1.10 by Vincent Ladeuil
Finish http parameterization, 24 auth tests failing for pycurl (not
21
"""
1540.3.3 by Martin Pool
Review updates of pycurl transport
22
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
23
# TODO: Should be renamed to bzrlib.transport.http.tests?
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
24
# TODO: What about renaming to bzrlib.tests.transport.http ?
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
25
2363.4.12 by Vincent Ladeuil
Take jam's review comments into account. Fix typos, give better
26
from cStringIO import StringIO
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
27
import httplib
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
28
import os
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
29
import select
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
30
import SimpleHTTPServer
2000.2.2 by John Arbash Meinel
Update the urllib.has test.
31
import socket
2420.1.20 by Vincent Ladeuil
Fix test failure on pqm.
32
import sys
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
33
import threading
2000.2.2 by John Arbash Meinel
Update the urllib.has test.
34
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
35
import bzrlib
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
36
from bzrlib import (
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
37
    bzrdir,
2900.2.6 by Vincent Ladeuil
Make http aware of authentication config.
38
    config,
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
39
    errors,
40
    osutils,
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
41
    remote as _mod_remote,
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
42
    tests,
3111.1.10 by Vincent Ladeuil
Finish http parameterization, 24 auth tests failing for pycurl (not
43
    transport,
2363.4.12 by Vincent Ladeuil
Take jam's review comments into account. Fix typos, give better
44
    ui,
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
45
    urlutils,
46
    )
3995.2.2 by Martin Pool
Cope with read_bundle_from_url deprecation in test_http
47
from bzrlib.symbol_versioning import (
48
    deprecated_in,
49
    )
3102.1.1 by Vincent Ladeuil
Rename bzrlib/test/HTTPTestUtils.py to bzrlib/tests/http_utils.py and fix
50
from bzrlib.tests import (
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
51
    features,
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
52
    http_server,
3111.1.7 by Vincent Ladeuil
Further refactoring.
53
    http_utils,
3102.1.1 by Vincent Ladeuil
Rename bzrlib/test/HTTPTestUtils.py to bzrlib/tests/http_utils.py and fix
54
    )
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
55
from bzrlib.transport import (
56
    http,
57
    remote,
58
    )
2004.3.3 by vila
Better (but still incomplete) design for bogus servers.
59
from bzrlib.transport.http import (
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
60
    _urllib,
2164.2.29 by Vincent Ladeuil
Test the http redirection at the request level even if it's not
61
    _urllib2_wrappers,
2004.3.3 by vila
Better (but still incomplete) design for bogus servers.
62
    )
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
63
64
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
65
if features.pycurl.available():
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
66
    from bzrlib.transport.http._pycurl import PyCurlTransport
67
68
69
def load_tests(standard_tests, module, loader):
70
    """Multiply tests for http clients and protocol versions."""
3945.1.7 by Vincent Ladeuil
Test against https.
71
    result = loader.suiteClass()
72
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
73
    # one for each transport implementation
3945.1.7 by Vincent Ladeuil
Test against https.
74
    t_tests, remaining_tests = tests.split_suite_by_condition(
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
75
        standard_tests, tests.condition_isinstance((
3945.1.7 by Vincent Ladeuil
Test against https.
76
                TestHttpTransportRegistration,
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
77
                TestHttpTransportUrls,
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
78
                Test_redirected_to,
3945.1.7 by Vincent Ladeuil
Test against https.
79
                )))
80
    transport_scenarios = [
81
        ('urllib', dict(_transport=_urllib.HttpTransport_urllib,
82
                        _server=http_server.HttpServer_urllib,
83
                        _qualified_prefix='http+urllib',)),
84
        ]
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
85
    if features.pycurl.available():
3945.1.7 by Vincent Ladeuil
Test against https.
86
        transport_scenarios.append(
87
            ('pycurl', dict(_transport=PyCurlTransport,
88
                            _server=http_server.HttpServer_PyCurl,
89
                            _qualified_prefix='http+pycurl',)))
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
90
    tests.multiply_tests(t_tests, transport_scenarios, result)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
91
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
92
    # each implementation tested with each HTTP version
3945.1.7 by Vincent Ladeuil
Test against https.
93
    tp_tests, remaining_tests = tests.split_suite_by_condition(
94
        remaining_tests, tests.condition_isinstance((
95
                SmartHTTPTunnellingTest,
96
                TestDoCatchRedirections,
97
                TestHTTPConnections,
98
                TestHTTPRedirections,
99
                TestHTTPSilentRedirections,
100
                TestLimitedRangeRequestServer,
101
                TestPost,
102
                TestProxyHttpServer,
103
                TestRanges,
104
                TestSpecificRequestHandler,
105
                )))
106
    protocol_scenarios = [
107
            ('HTTP/1.0',  dict(_protocol_version='HTTP/1.0')),
108
            ('HTTP/1.1',  dict(_protocol_version='HTTP/1.1')),
109
            ]
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
110
    tp_scenarios = tests.multiply_scenarios(transport_scenarios,
3945.1.7 by Vincent Ladeuil
Test against https.
111
                                            protocol_scenarios)
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
112
    tests.multiply_tests(tp_tests, tp_scenarios, result)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
113
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
114
    # proxy auth: each auth scheme on all http versions on all implementations.
115
    tppa_tests, remaining_tests = tests.split_suite_by_condition(
116
        remaining_tests, tests.condition_isinstance((
117
                TestProxyAuth,
118
                )))
119
    proxy_auth_scheme_scenarios = [
120
        ('basic', dict(_auth_server=http_utils.ProxyBasicAuthServer)),
121
        ('digest', dict(_auth_server=http_utils.ProxyDigestAuthServer)),
122
        ('basicdigest',
123
         dict(_auth_server=http_utils.ProxyBasicAndDigestAuthServer)),
124
        ]
125
    tppa_scenarios = tests.multiply_scenarios(tp_scenarios,
126
                                              proxy_auth_scheme_scenarios)
127
    tests.multiply_tests(tppa_tests, tppa_scenarios, result)
128
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
129
    # auth: each auth scheme on all http versions on all implementations.
3945.1.7 by Vincent Ladeuil
Test against https.
130
    tpa_tests, remaining_tests = tests.split_suite_by_condition(
131
        remaining_tests, tests.condition_isinstance((
132
                TestAuth,
133
                )))
134
    auth_scheme_scenarios = [
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
135
        ('basic', dict(_auth_server=http_utils.HTTPBasicAuthServer)),
136
        ('digest', dict(_auth_server=http_utils.HTTPDigestAuthServer)),
137
        ('basicdigest',
138
         dict(_auth_server=http_utils.HTTPBasicAndDigestAuthServer)),
3945.1.7 by Vincent Ladeuil
Test against https.
139
        ]
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
140
    tpa_scenarios = tests.multiply_scenarios(tp_scenarios,
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
141
                                             auth_scheme_scenarios)
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
142
    tests.multiply_tests(tpa_tests, tpa_scenarios, result)
3945.1.7 by Vincent Ladeuil
Test against https.
143
4382.1.1 by Vincent Ladeuil
Fix test failures for https/pycurl.
144
    # activity: on all http[s] versions on all implementations
3945.1.7 by Vincent Ladeuil
Test against https.
145
    tpact_tests, remaining_tests = tests.split_suite_by_condition(
146
        remaining_tests, tests.condition_isinstance((
147
                TestActivity,
148
                )))
149
    activity_scenarios = [
4382.1.3 by Vincent Ladeuil
Take more configurations into account.
150
        ('urllib,http', dict(_activity_server=ActivityHTTPServer,
151
                             _transport=_urllib.HttpTransport_urllib,)),
4382.1.1 by Vincent Ladeuil
Fix test failures for https/pycurl.
152
        ]
3945.1.7 by Vincent Ladeuil
Test against https.
153
    if tests.HTTPSServerFeature.available():
154
        activity_scenarios.append(
4382.1.3 by Vincent Ladeuil
Take more configurations into account.
155
            ('urllib,https', dict(_activity_server=ActivityHTTPSServer,
156
                                  _transport=_urllib.HttpTransport_urllib,)),)
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
157
    if features.pycurl.available():
4382.1.3 by Vincent Ladeuil
Take more configurations into account.
158
        activity_scenarios.append(
159
            ('pycurl,http', dict(_activity_server=ActivityHTTPServer,
160
                                 _transport=PyCurlTransport,)),)
161
        if tests.HTTPSServerFeature.available():
4382.1.1 by Vincent Ladeuil
Fix test failures for https/pycurl.
162
            from bzrlib.tests import (
163
                ssl_certs,
164
                )
165
            # FIXME: Until we have a better way to handle self-signed
166
            # certificates (like allowing them in a test specific
167
            # authentication.conf for example), we need some specialized pycurl
168
            # transport for tests.
169
            class HTTPS_pycurl_transport(PyCurlTransport):
170
171
                def __init__(self, base, _from_transport=None):
172
                    super(HTTPS_pycurl_transport, self).__init__(
173
                        base, _from_transport)
174
                    self.cabundle = str(ssl_certs.build_path('ca.crt'))
175
4382.1.3 by Vincent Ladeuil
Take more configurations into account.
176
            activity_scenarios.append(
177
                ('pycurl,https', dict(_activity_server=ActivityHTTPSServer,
178
                                      _transport=HTTPS_pycurl_transport,)),)
4382.1.1 by Vincent Ladeuil
Fix test failures for https/pycurl.
179
4382.1.3 by Vincent Ladeuil
Take more configurations into account.
180
    tpact_scenarios = tests.multiply_scenarios(activity_scenarios,
181
                                               protocol_scenarios)
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
182
    tests.multiply_tests(tpact_tests, tpact_scenarios, result)
3945.1.7 by Vincent Ladeuil
Test against https.
183
184
    # No parametrization for the remaining tests
185
    result.addTests(remaining_tests)
186
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
187
    return result
1185.40.20 by Robey Pointer
allow user:pass@ info in http urls to be used for auth; this should be easily expandable later to use auth config files
188
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
189
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
190
class FakeManager(object):
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
191
1185.40.20 by Robey Pointer
allow user:pass@ info in http urls to be used for auth; this should be easily expandable later to use auth config files
192
    def __init__(self):
193
        self.credentials = []
2004.3.1 by vila
Test ConnectionError exceptions.
194
1185.40.20 by Robey Pointer
allow user:pass@ info in http urls to be used for auth; this should be easily expandable later to use auth config files
195
    def add_password(self, realm, host, username, password):
196
        self.credentials.append([realm, host, username, password])
197
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
198
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
199
class RecordingServer(object):
200
    """A fake HTTP server.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
201
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
202
    It records the bytes sent to it, and replies with a 200.
203
    """
204
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
205
    def __init__(self, expect_body_tail=None, scheme=''):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
206
        """Constructor.
207
208
        :type expect_body_tail: str
209
        :param expect_body_tail: a reply won't be sent until this string is
210
            received.
211
        """
212
        self._expect_body_tail = expect_body_tail
213
        self.host = None
214
        self.port = None
215
        self.received_bytes = ''
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
216
        self.scheme = scheme
217
218
    def get_url(self):
219
        return '%s://%s:%s/' % (self.scheme, self.host, self.port)
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
220
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
221
    def start_server(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
222
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
223
        self._sock.bind(('127.0.0.1', 0))
224
        self.host, self.port = self._sock.getsockname()
225
        self._ready = threading.Event()
226
        self._thread = threading.Thread(target=self._accept_read_and_reply)
227
        self._thread.setDaemon(True)
228
        self._thread.start()
229
        self._ready.wait(5)
230
231
    def _accept_read_and_reply(self):
232
        self._sock.listen(1)
233
        self._ready.set()
234
        self._sock.settimeout(5)
235
        try:
236
            conn, address = self._sock.accept()
237
            # On win32, the accepted connection will be non-blocking to start
238
            # with because we're using settimeout.
239
            conn.setblocking(True)
240
            while not self.received_bytes.endswith(self._expect_body_tail):
241
                self.received_bytes += conn.recv(4096)
242
            conn.sendall('HTTP/1.1 200 OK\r\n')
243
        except socket.timeout:
244
            # Make sure the client isn't stuck waiting for us to e.g. accept.
245
            self._sock.close()
246
        except socket.error:
247
            # The client may have already closed the socket.
248
            pass
249
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
250
    def stop_server(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
251
        try:
252
            self._sock.close()
253
        except socket.error:
254
            # We might have already closed it.  We don't care.
255
            pass
256
        self.host = None
257
        self.port = None
258
259
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
260
class TestAuthHeader(tests.TestCase):
261
4284.1.1 by Vincent Ladeuil
Fix wrong realm extraction in http basic authentication (reported
262
    def parse_header(self, header, auth_handler_class=None):
263
        if auth_handler_class is None:
264
            auth_handler_class = _urllib2_wrappers.AbstractAuthHandler
265
        self.auth_handler =  auth_handler_class()
266
        return self.auth_handler._parse_auth_header(header)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
267
268
    def test_empty_header(self):
269
        scheme, remainder = self.parse_header('')
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
270
        self.assertEqual('', scheme)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
271
        self.assertIs(None, remainder)
272
273
    def test_negotiate_header(self):
274
        scheme, remainder = self.parse_header('Negotiate')
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
275
        self.assertEqual('negotiate', scheme)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
276
        self.assertIs(None, remainder)
277
278
    def test_basic_header(self):
279
        scheme, remainder = self.parse_header(
280
            'Basic realm="Thou should not pass"')
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
281
        self.assertEqual('basic', scheme)
282
        self.assertEqual('realm="Thou should not pass"', remainder)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
283
4284.1.1 by Vincent Ladeuil
Fix wrong realm extraction in http basic authentication (reported
284
    def test_basic_extract_realm(self):
285
        scheme, remainder = self.parse_header(
286
            'Basic realm="Thou should not pass"',
287
            _urllib2_wrappers.BasicAuthHandler)
288
        match, realm = self.auth_handler.extract_realm(remainder)
289
        self.assertTrue(match is not None)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
290
        self.assertEqual('Thou should not pass', realm)
4284.1.1 by Vincent Ladeuil
Fix wrong realm extraction in http basic authentication (reported
291
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
292
    def test_digest_header(self):
293
        scheme, remainder = self.parse_header(
294
            'Digest realm="Thou should not pass"')
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
295
        self.assertEqual('digest', scheme)
296
        self.assertEqual('realm="Thou should not pass"', remainder)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
297
298
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
299
class TestHTTPServer(tests.TestCase):
300
    """Test the HTTP servers implementations."""
301
302
    def test_invalid_protocol(self):
303
        class BogusRequestHandler(http_server.TestingHTTPRequestHandler):
304
305
            protocol_version = 'HTTP/0.1'
306
307
        server = http_server.HttpServer(BogusRequestHandler)
308
        try:
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
309
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
310
        except:
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
311
            server.stop_server()
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
312
            self.fail('HTTP Server creation did not raise UnknownProtocol')
313
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
314
    def test_force_invalid_protocol(self):
315
        server = http_server.HttpServer(protocol_version='HTTP/0.1')
316
        try:
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
317
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
318
        except:
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
319
            server.stop_server()
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
320
            self.fail('HTTP Server creation did not raise UnknownProtocol')
321
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
322
    def test_server_start_and_stop(self):
323
        server = http_server.HttpServer()
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
324
        server.start_server()
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
325
        try:
326
            self.assertTrue(server._http_running)
327
        finally:
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
328
            server.stop_server()
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
329
        self.assertFalse(server._http_running)
330
331
    def test_create_http_server_one_zero(self):
332
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
333
334
            protocol_version = 'HTTP/1.0'
335
336
        server = http_server.HttpServer(RequestHandlerOneZero)
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
337
        self.start_server(server)
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
338
        self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
339
340
    def test_create_http_server_one_one(self):
341
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
342
343
            protocol_version = 'HTTP/1.1'
344
345
        server = http_server.HttpServer(RequestHandlerOneOne)
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
346
        self.start_server(server)
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
347
        self.assertIsInstance(server._httpd,
348
                              http_server.TestingThreadingHTTPServer)
349
350
    def test_create_http_server_force_one_one(self):
351
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
352
353
            protocol_version = 'HTTP/1.0'
354
355
        server = http_server.HttpServer(RequestHandlerOneZero,
356
                                        protocol_version='HTTP/1.1')
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
357
        self.start_server(server)
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
358
        self.assertIsInstance(server._httpd,
359
                              http_server.TestingThreadingHTTPServer)
360
361
    def test_create_http_server_force_one_zero(self):
362
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
363
364
            protocol_version = 'HTTP/1.1'
365
366
        server = http_server.HttpServer(RequestHandlerOneOne,
367
                                        protocol_version='HTTP/1.0')
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
368
        self.start_server(server)
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
369
        self.assertIsInstance(server._httpd,
370
                              http_server.TestingHTTPServer)
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
371
372
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
373
class TestWithTransport_pycurl(object):
374
    """Test case to inherit from if pycurl is present"""
375
376
    def _get_pycurl_maybe(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
377
        self.requireFeature(features.pycurl)
378
        return PyCurlTransport
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
379
380
    _transport = property(_get_pycurl_maybe)
381
382
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
383
class TestHttpUrls(tests.TestCase):
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
384
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
385
    # TODO: This should be moved to authorization tests once they
386
    # are written.
2004.1.40 by v.ladeuil+lp at free
Fix the race condition again and correct some small typos to be in
387
1185.40.20 by Robey Pointer
allow user:pass@ info in http urls to be used for auth; this should be easily expandable later to use auth config files
388
    def test_url_parsing(self):
389
        f = FakeManager()
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
390
        url = http.extract_auth('http://example.com', f)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
391
        self.assertEqual('http://example.com', url)
392
        self.assertEqual(0, len(f.credentials))
3111.1.30 by Vincent Ladeuil
Update NEWS. Some cosmetic changes.
393
        url = http.extract_auth(
394
            'http://user:pass@www.bazaar-vcs.org/bzr/bzr.dev', f)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
395
        self.assertEqual('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
396
        self.assertEqual(1, len(f.credentials))
397
        self.assertEqual([None, 'www.bazaar-vcs.org', 'user', 'pass'],
398
                         f.credentials[0])
2004.3.1 by vila
Test ConnectionError exceptions.
399
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
400
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
401
class TestHttpTransportUrls(tests.TestCase):
402
    """Test the http urls."""
403
404
    def test_abs_url(self):
405
        """Construction of absolute http URLs"""
406
        t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
407
        eq = self.assertEqualDiff
408
        eq(t.abspath('.'), 'http://bazaar-vcs.org/bzr/bzr.dev')
409
        eq(t.abspath('foo/bar'), 'http://bazaar-vcs.org/bzr/bzr.dev/foo/bar')
410
        eq(t.abspath('.bzr'), 'http://bazaar-vcs.org/bzr/bzr.dev/.bzr')
411
        eq(t.abspath('.bzr/1//2/./3'),
412
           'http://bazaar-vcs.org/bzr/bzr.dev/.bzr/1/2/3')
413
414
    def test_invalid_http_urls(self):
415
        """Trap invalid construction of urls"""
416
        t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
417
        self.assertRaises(errors.InvalidURL,
418
                          self._transport,
419
                          'http://http://bazaar-vcs.org/bzr/bzr.dev/')
420
421
    def test_http_root_urls(self):
422
        """Construction of URLs from server root"""
423
        t = self._transport('http://bzr.ozlabs.org/')
424
        eq = self.assertEqualDiff
425
        eq(t.abspath('.bzr/tree-version'),
426
           'http://bzr.ozlabs.org/.bzr/tree-version')
427
428
    def test_http_impl_urls(self):
429
        """There are servers which ask for particular clients to connect"""
430
        server = self._server()
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
431
        server.start_server()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
432
        try:
433
            url = server.get_url()
434
            self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
435
        finally:
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
436
            server.stop_server()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
437
438
3111.1.9 by Vincent Ladeuil
Most refactoring regarding parameterization for urllib/pycurl and custom
439
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
440
441
    # TODO: This should really be moved into another pycurl
442
    # specific test. When https tests will be implemented, take
443
    # this one into account.
444
    def test_pycurl_without_https_support(self):
445
        """Test that pycurl without SSL do not fail with a traceback.
446
447
        For the purpose of the test, we force pycurl to ignore
448
        https by supplying a fake version_info that do not
449
        support it.
450
        """
4913.2.13 by John Arbash Meinel
Finish the pycurl feature.
451
        self.requireFeature(features.pycurl)
4926.1.1 by Vincent Ladeuil
Fix ModuleFeature() side-effect.
452
        # Import the module locally now that we now it's available.
453
        pycurl = features.pycurl.module
3111.1.14 by Vincent Ladeuil
Fix test leakage.
454
455
        version_info_orig = pycurl.version_info
4926.1.1 by Vincent Ladeuil
Fix ModuleFeature() side-effect.
456
        def restore():
3111.1.14 by Vincent Ladeuil
Fix test leakage.
457
            pycurl.version_info = version_info_orig
4926.1.1 by Vincent Ladeuil
Fix ModuleFeature() side-effect.
458
        self.addCleanup(restore)
459
460
        # Fake the pycurl version_info This was taken from a windows pycurl
461
        # without SSL (thanks to bialix)
462
        pycurl.version_info = lambda : (2,
463
                                        '7.13.2',
464
                                        462082,
465
                                        'i386-pc-win32',
466
                                        2576,
467
                                        None,
468
                                        0,
469
                                        None,
470
                                        ('ftp', 'gopher', 'telnet',
471
                                         'dict', 'ldap', 'http', 'file'),
472
                                        None,
473
                                        0,
474
                                        None)
475
        self.assertRaises(errors.DependencyNotPresent, self._transport,
476
                          'https://launchpad.net')
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
477
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
478
479
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
480
    """Test the http connections."""
481
482
    def setUp(self):
483
        http_utils.TestCaseWithWebserver.setUp(self)
484
        self.build_tree(['foo/', 'foo/bar'], line_endings='binary',
485
                        transport=self.get_transport())
486
487
    def test_http_has(self):
488
        server = self.get_readonly_server()
489
        t = self._transport(server.get_url())
490
        self.assertEqual(t.has('foo/bar'), True)
491
        self.assertEqual(len(server.logs), 1)
492
        self.assertContainsRe(server.logs[0],
493
            r'"HEAD /foo/bar HTTP/1.." (200|302) - "-" "bzr/')
494
495
    def test_http_has_not_found(self):
496
        server = self.get_readonly_server()
497
        t = self._transport(server.get_url())
498
        self.assertEqual(t.has('not-found'), False)
499
        self.assertContainsRe(server.logs[1],
500
            r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
501
502
    def test_http_get(self):
503
        server = self.get_readonly_server()
504
        t = self._transport(server.get_url())
505
        fp = t.get('foo/bar')
506
        self.assertEqualDiff(
507
            fp.read(),
508
            'contents of foo/bar\n')
509
        self.assertEqual(len(server.logs), 1)
510
        self.assertTrue(server.logs[0].find(
511
            '"GET /foo/bar HTTP/1.1" 200 - "-" "bzr/%s'
512
            % bzrlib.__version__) > -1)
513
514
    def test_has_on_bogus_host(self):
515
        # Get a free address and don't 'accept' on it, so that we
516
        # can be sure there is no http handler there, but set a
517
        # reasonable timeout to not slow down tests too much.
518
        default_timeout = socket.getdefaulttimeout()
519
        try:
520
            socket.setdefaulttimeout(2)
521
            s = socket.socket()
522
            s.bind(('localhost', 0))
523
            t = self._transport('http://%s:%s/' % s.getsockname())
524
            self.assertRaises(errors.ConnectionError, t.has, 'foo/bar')
525
        finally:
526
            socket.setdefaulttimeout(default_timeout)
527
528
529
class TestHttpTransportRegistration(tests.TestCase):
530
    """Test registrations of various http implementations"""
531
532
    def test_http_registered(self):
533
        t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
534
        self.assertIsInstance(t, transport.Transport)
535
        self.assertIsInstance(t, self._transport)
536
537
538
class TestPost(tests.TestCase):
539
540
    def test_post_body_is_received(self):
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
541
        server = RecordingServer(expect_body_tail='end-of-body',
542
            scheme=self._qualified_prefix)
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
543
        self.start_server(server)
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
544
        url = server.get_url()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
545
        http_transport = self._transport(url)
546
        code, response = http_transport._post('abc def end-of-body')
547
        self.assertTrue(
548
            server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
549
        self.assertTrue('content-length: 19\r' in server.received_bytes.lower())
550
        # The transport should not be assuming that the server can accept
551
        # chunked encoding the first time it connects, because HTTP/1.1, so we
552
        # check for the literal string.
553
        self.assertTrue(
554
            server.received_bytes.endswith('\r\n\r\nabc def end-of-body'))
555
556
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
557
class TestRangeHeader(tests.TestCase):
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
558
    """Test range_header method"""
559
560
    def check_header(self, value, ranges=[], tail=0):
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
561
        offsets = [ (start, end - start + 1) for start, end in ranges]
3111.1.10 by Vincent Ladeuil
Finish http parameterization, 24 auth tests failing for pycurl (not
562
        coalesce = transport.Transport._coalesce_offsets
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
563
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
564
        range_header = http.HttpTransportBase._range_header
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
565
        self.assertEqual(value, range_header(coalesced, tail))
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
566
567
    def test_range_header_single(self):
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
568
        self.check_header('0-9', ranges=[(0,9)])
569
        self.check_header('100-109', ranges=[(100,109)])
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
570
571
    def test_range_header_tail(self):
1786.1.36 by John Arbash Meinel
pycurl expects us to just set the range of bytes, not including bytes=
572
        self.check_header('-10', tail=10)
573
        self.check_header('-50', tail=50)
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
574
575
    def test_range_header_multi(self):
1786.1.36 by John Arbash Meinel
pycurl expects us to just set the range of bytes, not including bytes=
576
        self.check_header('0-9,100-200,300-5000',
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
577
                          ranges=[(0,9), (100, 200), (300,5000)])
578
579
    def test_range_header_mixed(self):
1786.1.36 by John Arbash Meinel
pycurl expects us to just set the range of bytes, not including bytes=
580
        self.check_header('0-9,300-5000,-50',
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
581
                          ranges=[(0,9), (300,5000)],
582
                          tail=50)
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
583
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
584
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
585
class TestSpecificRequestHandler(http_utils.TestCaseWithWebserver):
586
    """Tests a specific request handler.
587
3111.1.31 by Vincent Ladeuil
Review feeback.
588
    Daughter classes are expected to override _req_handler_class
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
589
    """
590
591
    # Provide a useful default
592
    _req_handler_class = http_server.TestingHTTPRequestHandler
593
594
    def create_transport_readonly_server(self):
595
        return http_server.HttpServer(self._req_handler_class,
596
                                      protocol_version=self._protocol_version)
597
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
598
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
599
        # TODO: This is duplicated for lots of the classes in this file
600
        return (features.pycurl.available()
601
                and self._transport == PyCurlTransport)
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
602
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
603
604
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
605
    """Whatever request comes in, close the connection"""
606
607
    def handle_one_request(self):
608
        """Handle a single HTTP request, by abruptly closing the connection"""
609
        self.close_connection = 1
610
611
612
class TestWallServer(TestSpecificRequestHandler):
613
    """Tests exceptions during the connection phase"""
614
615
    _req_handler_class = WallRequestHandler
616
617
    def test_http_has(self):
618
        server = self.get_readonly_server()
619
        t = self._transport(server.get_url())
620
        # Unfortunately httplib (see HTTPResponse._read_status
621
        # for details) make no distinction between a closed
622
        # socket and badly formatted status line, so we can't
623
        # just test for ConnectionError, we have to test
4628.1.2 by Vincent Ladeuil
More complete fix.
624
        # InvalidHttpResponse too. And pycurl may raise ConnectionReset
625
        # instead of ConnectionError too.
626
        self.assertRaises(( errors.ConnectionError, errors.ConnectionReset,
627
                            errors.InvalidHttpResponse),
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
628
                          t.has, 'foo/bar')
629
630
    def test_http_get(self):
631
        server = self.get_readonly_server()
632
        t = self._transport(server.get_url())
4628.1.2 by Vincent Ladeuil
More complete fix.
633
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
634
                           errors.InvalidHttpResponse),
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
635
                          t.get, 'foo/bar')
636
637
638
class BadStatusRequestHandler(http_server.TestingHTTPRequestHandler):
639
    """Whatever request comes in, returns a bad status"""
640
641
    def parse_request(self):
642
        """Fakes handling a single HTTP request, returns a bad status"""
643
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
644
        self.send_response(0, "Bad status")
645
        self.close_connection = 1
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
646
        return False
647
648
649
class TestBadStatusServer(TestSpecificRequestHandler):
650
    """Tests bad status from server."""
651
652
    _req_handler_class = BadStatusRequestHandler
653
654
    def test_http_has(self):
655
        server = self.get_readonly_server()
656
        t = self._transport(server.get_url())
657
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
658
659
    def test_http_get(self):
660
        server = self.get_readonly_server()
661
        t = self._transport(server.get_url())
662
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
663
664
665
class InvalidStatusRequestHandler(http_server.TestingHTTPRequestHandler):
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
666
    """Whatever request comes in, returns an invalid status"""
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
667
668
    def parse_request(self):
669
        """Fakes handling a single HTTP request, returns a bad status"""
670
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
671
        self.wfile.write("Invalid status line\r\n")
672
        return False
673
674
675
class TestInvalidStatusServer(TestBadStatusServer):
676
    """Tests invalid status from server.
677
678
    Both implementations raises the same error as for a bad status.
679
    """
680
681
    _req_handler_class = InvalidStatusRequestHandler
682
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
683
    def test_http_has(self):
684
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
685
            raise tests.KnownFailure(
686
                'pycurl hangs if the server send back garbage')
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
687
        super(TestInvalidStatusServer, self).test_http_has()
688
689
    def test_http_get(self):
690
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
691
            raise tests.KnownFailure(
692
                'pycurl hangs if the server send back garbage')
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
693
        super(TestInvalidStatusServer, self).test_http_get()
694
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
695
696
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
697
    """Whatever request comes in, returns a bad protocol version"""
698
699
    def parse_request(self):
700
        """Fakes handling a single HTTP request, returns a bad status"""
701
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
702
        # Returns an invalid protocol version, but curl just
703
        # ignores it and those cannot be tested.
704
        self.wfile.write("%s %d %s\r\n" % ('HTTP/0.0',
705
                                           404,
706
                                           'Look at my protocol version'))
707
        return False
708
709
710
class TestBadProtocolServer(TestSpecificRequestHandler):
711
    """Tests bad protocol from server."""
712
713
    _req_handler_class = BadProtocolRequestHandler
714
715
    def setUp(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
716
        if self._testing_pycurl():
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
717
            raise tests.TestNotApplicable(
718
                "pycurl doesn't check the protocol version")
719
        super(TestBadProtocolServer, self).setUp()
720
721
    def test_http_has(self):
722
        server = self.get_readonly_server()
723
        t = self._transport(server.get_url())
724
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
725
726
    def test_http_get(self):
727
        server = self.get_readonly_server()
728
        t = self._transport(server.get_url())
729
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
730
731
732
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
733
    """Whatever request comes in, returns a 403 code"""
734
735
    def parse_request(self):
736
        """Handle a single HTTP request, by replying we cannot handle it"""
737
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
738
        self.send_error(403)
739
        return False
740
741
742
class TestForbiddenServer(TestSpecificRequestHandler):
743
    """Tests forbidden server"""
744
745
    _req_handler_class = ForbiddenRequestHandler
746
747
    def test_http_has(self):
748
        server = self.get_readonly_server()
749
        t = self._transport(server.get_url())
750
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
751
752
    def test_http_get(self):
753
        server = self.get_readonly_server()
754
        t = self._transport(server.get_url())
755
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
756
757
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
758
class TestRecordingServer(tests.TestCase):
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
759
760
    def test_create(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
761
        server = RecordingServer(expect_body_tail=None)
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
762
        self.assertEqual('', server.received_bytes)
763
        self.assertEqual(None, server.host)
764
        self.assertEqual(None, server.port)
765
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
766
    def test_setUp_and_stop(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
767
        server = RecordingServer(expect_body_tail=None)
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
768
        server.start_server()
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
769
        try:
770
            self.assertNotEqual(None, server.host)
771
            self.assertNotEqual(None, server.port)
772
        finally:
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
773
            server.stop_server()
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
774
        self.assertEqual(None, server.host)
775
        self.assertEqual(None, server.port)
776
777
    def test_send_receive_bytes(self):
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
778
        server = RecordingServer(expect_body_tail='c', scheme='http')
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
779
        self.start_server(server)
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
780
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
781
        sock.connect((server.host, server.port))
782
        sock.sendall('abc')
783
        self.assertEqual('HTTP/1.1 200 OK\r\n',
2091.1.1 by Martin Pool
Avoid MSG_WAITALL as it doesn't work on Windows
784
                         osutils.recv_all(sock, 4096))
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
785
        self.assertEqual('abc', server.received_bytes)
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
786
787
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
788
class TestRangeRequestServer(TestSpecificRequestHandler):
789
    """Tests readv requests against server.
790
791
    We test against default "normal" server.
792
    """
793
794
    def setUp(self):
795
        super(TestRangeRequestServer, self).setUp()
796
        self.build_tree_contents([('a', '0123456789')],)
797
798
    def test_readv(self):
799
        server = self.get_readonly_server()
800
        t = self._transport(server.get_url())
801
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
802
        self.assertEqual(l[0], (0, '0'))
803
        self.assertEqual(l[1], (1, '1'))
804
        self.assertEqual(l[2], (3, '34'))
805
        self.assertEqual(l[3], (9, '9'))
806
807
    def test_readv_out_of_order(self):
808
        server = self.get_readonly_server()
809
        t = self._transport(server.get_url())
810
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
811
        self.assertEqual(l[0], (1, '1'))
812
        self.assertEqual(l[1], (9, '9'))
813
        self.assertEqual(l[2], (0, '0'))
814
        self.assertEqual(l[3], (3, '34'))
815
816
    def test_readv_invalid_ranges(self):
817
        server = self.get_readonly_server()
818
        t = self._transport(server.get_url())
819
820
        # This is intentionally reading off the end of the file
821
        # since we are sure that it cannot get there
822
        self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
823
                              t.readv, 'a', [(1,1), (8,10)])
824
825
        # This is trying to seek past the end of the file, it should
826
        # also raise a special error
827
        self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
828
                              t.readv, 'a', [(12,2)])
829
830
    def test_readv_multiple_get_requests(self):
831
        server = self.get_readonly_server()
832
        t = self._transport(server.get_url())
833
        # force transport to issue multiple requests
834
        t._max_readv_combine = 1
835
        t._max_get_ranges = 1
836
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
837
        self.assertEqual(l[0], (0, '0'))
838
        self.assertEqual(l[1], (1, '1'))
839
        self.assertEqual(l[2], (3, '34'))
840
        self.assertEqual(l[3], (9, '9'))
841
        # The server should have issued 4 requests
842
        self.assertEqual(4, server.GET_request_nb)
843
844
    def test_readv_get_max_size(self):
845
        server = self.get_readonly_server()
846
        t = self._transport(server.get_url())
847
        # force transport to issue multiple requests by limiting the number of
848
        # bytes by request. Note that this apply to coalesced offsets only, a
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
849
        # single range will keep its size even if bigger than the limit.
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
850
        t._get_max_size = 2
851
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
852
        self.assertEqual(l[0], (0, '0'))
853
        self.assertEqual(l[1], (1, '1'))
854
        self.assertEqual(l[2], (2, '2345'))
855
        self.assertEqual(l[3], (6, '6789'))
856
        # The server should have issued 3 requests
857
        self.assertEqual(3, server.GET_request_nb)
858
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
859
    def test_complete_readv_leave_pipe_clean(self):
860
        server = self.get_readonly_server()
861
        t = self._transport(server.get_url())
862
        # force transport to issue multiple requests
863
        t._get_max_size = 2
864
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
865
        # The server should have issued 3 requests
866
        self.assertEqual(3, server.GET_request_nb)
867
        self.assertEqual('0123456789', t.get_bytes('a'))
868
        self.assertEqual(4, server.GET_request_nb)
869
870
    def test_incomplete_readv_leave_pipe_clean(self):
871
        server = self.get_readonly_server()
872
        t = self._transport(server.get_url())
873
        # force transport to issue multiple requests
874
        t._get_max_size = 2
875
        # Don't collapse readv results into a list so that we leave unread
876
        # bytes on the socket
877
        ireadv = iter(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
878
        self.assertEqual((0, '0'), ireadv.next())
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
879
        # The server should have issued one request so far
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
880
        self.assertEqual(1, server.GET_request_nb)
881
        self.assertEqual('0123456789', t.get_bytes('a'))
882
        # get_bytes issued an additional request, the readv pending ones are
883
        # lost
884
        self.assertEqual(2, server.GET_request_nb)
885
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
886
887
class SingleRangeRequestHandler(http_server.TestingHTTPRequestHandler):
888
    """Always reply to range request as if they were single.
889
890
    Don't be explicit about it, just to annoy the clients.
891
    """
892
893
    def get_multiple_ranges(self, file, file_size, ranges):
894
        """Answer as if it was a single range request and ignores the rest"""
895
        (start, end) = ranges[0]
896
        return self.get_single_range(file, file_size, start, end)
897
898
899
class TestSingleRangeRequestServer(TestRangeRequestServer):
900
    """Test readv against a server which accept only single range requests"""
901
902
    _req_handler_class = SingleRangeRequestHandler
903
904
905
class SingleOnlyRangeRequestHandler(http_server.TestingHTTPRequestHandler):
906
    """Only reply to simple range requests, errors out on multiple"""
907
908
    def get_multiple_ranges(self, file, file_size, ranges):
909
        """Refuses the multiple ranges request"""
910
        if len(ranges) > 1:
911
            file.close()
912
            self.send_error(416, "Requested range not satisfiable")
913
            return
914
        (start, end) = ranges[0]
915
        return self.get_single_range(file, file_size, start, end)
916
917
918
class TestSingleOnlyRangeRequestServer(TestRangeRequestServer):
919
    """Test readv against a server which only accept single range requests"""
920
921
    _req_handler_class = SingleOnlyRangeRequestHandler
922
923
924
class NoRangeRequestHandler(http_server.TestingHTTPRequestHandler):
925
    """Ignore range requests without notice"""
926
927
    def do_GET(self):
928
        # Update the statistics
929
        self.server.test_case_server.GET_request_nb += 1
930
        # Just bypass the range handling done by TestingHTTPRequestHandler
931
        return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
932
933
934
class TestNoRangeRequestServer(TestRangeRequestServer):
935
    """Test readv against a server which do not accept range requests"""
936
937
    _req_handler_class = NoRangeRequestHandler
938
939
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
940
class MultipleRangeWithoutContentLengthRequestHandler(
941
    http_server.TestingHTTPRequestHandler):
942
    """Reply to multiple range requests without content length header."""
943
944
    def get_multiple_ranges(self, file, file_size, ranges):
945
        self.send_response(206)
946
        self.send_header('Accept-Ranges', 'bytes')
947
        boundary = "%d" % random.randint(0,0x7FFFFFFF)
948
        self.send_header("Content-Type",
949
                         "multipart/byteranges; boundary=%s" % boundary)
950
        self.end_headers()
951
        for (start, end) in ranges:
952
            self.wfile.write("--%s\r\n" % boundary)
953
            self.send_header("Content-type", 'application/octet-stream')
954
            self.send_header("Content-Range", "bytes %d-%d/%d" % (start,
955
                                                                  end,
956
                                                                  file_size))
957
            self.end_headers()
958
            self.send_range_content(file, start, end - start + 1)
959
        # Final boundary
960
        self.wfile.write("--%s\r\n" % boundary)
961
962
963
class TestMultipleRangeWithoutContentLengthServer(TestRangeRequestServer):
964
965
    _req_handler_class = MultipleRangeWithoutContentLengthRequestHandler
966
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
967
968
class TruncatedMultipleRangeRequestHandler(
969
    http_server.TestingHTTPRequestHandler):
970
    """Reply to multiple range requests truncating the last ones.
971
972
    This server generates responses whose Content-Length describes all the
973
    ranges, but fail to include the last ones leading to client short reads.
974
    This has been observed randomly with lighttpd (bug #179368).
975
    """
976
977
    _truncated_ranges = 2
978
979
    def get_multiple_ranges(self, file, file_size, ranges):
980
        self.send_response(206)
981
        self.send_header('Accept-Ranges', 'bytes')
982
        boundary = 'tagada'
983
        self.send_header('Content-Type',
984
                         'multipart/byteranges; boundary=%s' % boundary)
985
        boundary_line = '--%s\r\n' % boundary
986
        # Calculate the Content-Length
987
        content_length = 0
988
        for (start, end) in ranges:
989
            content_length += len(boundary_line)
990
            content_length += self._header_line_length(
991
                'Content-type', 'application/octet-stream')
992
            content_length += self._header_line_length(
993
                'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
994
            content_length += len('\r\n') # end headers
995
            content_length += end - start # + 1
996
        content_length += len(boundary_line)
997
        self.send_header('Content-length', content_length)
998
        self.end_headers()
999
1000
        # Send the multipart body
1001
        cur = 0
1002
        for (start, end) in ranges:
1003
            self.wfile.write(boundary_line)
1004
            self.send_header('Content-type', 'application/octet-stream')
1005
            self.send_header('Content-Range', 'bytes %d-%d/%d'
1006
                             % (start, end, file_size))
1007
            self.end_headers()
1008
            if cur + self._truncated_ranges >= len(ranges):
1009
                # Abruptly ends the response and close the connection
1010
                self.close_connection = 1
1011
                return
1012
            self.send_range_content(file, start, end - start + 1)
1013
            cur += 1
1014
        # No final boundary
1015
        self.wfile.write(boundary_line)
1016
1017
1018
class TestTruncatedMultipleRangeServer(TestSpecificRequestHandler):
1019
1020
    _req_handler_class = TruncatedMultipleRangeRequestHandler
1021
1022
    def setUp(self):
1023
        super(TestTruncatedMultipleRangeServer, self).setUp()
1024
        self.build_tree_contents([('a', '0123456789')],)
1025
1026
    def test_readv_with_short_reads(self):
1027
        server = self.get_readonly_server()
1028
        t = self._transport(server.get_url())
1029
        # Force separate ranges for each offset
1030
        t._bytes_to_read_before_seek = 0
1031
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1032
        self.assertEqual((0, '0'), ireadv.next())
1033
        self.assertEqual((2, '2'), ireadv.next())
1034
        if not self._testing_pycurl():
1035
            # Only one request have been issued so far (except for pycurl that
1036
            # try to read the whole response at once)
1037
            self.assertEqual(1, server.GET_request_nb)
1038
        self.assertEqual((4, '45'), ireadv.next())
1039
        self.assertEqual((9, '9'), ireadv.next())
1040
        # Both implementations issue 3 requests but:
1041
        # - urllib does two multiple (4 ranges, then 2 ranges) then a single
1042
        #   range,
1043
        # - pycurl does two multiple (4 ranges, 4 ranges) then a single range
1044
        self.assertEqual(3, server.GET_request_nb)
1045
        # Finally the client have tried a single range request and stays in
1046
        # that mode
1047
        self.assertEqual('single', t._range_hint)
1048
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1049
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1050
    """Errors out when range specifiers exceed the limit"""
1051
1052
    def get_multiple_ranges(self, file, file_size, ranges):
1053
        """Refuses the multiple ranges request"""
1054
        tcs = self.server.test_case_server
1055
        if tcs.range_limit is not None and len(ranges) > tcs.range_limit:
1056
            file.close()
1057
            # Emulate apache behavior
1058
            self.send_error(400, "Bad Request")
1059
            return
1060
        return http_server.TestingHTTPRequestHandler.get_multiple_ranges(
1061
            self, file, file_size, ranges)
1062
1063
1064
class LimitedRangeHTTPServer(http_server.HttpServer):
1065
    """An HttpServer erroring out on requests with too much range specifiers"""
1066
1067
    def __init__(self, request_handler=LimitedRangeRequestHandler,
1068
                 protocol_version=None,
1069
                 range_limit=None):
1070
        http_server.HttpServer.__init__(self, request_handler,
1071
                                        protocol_version=protocol_version)
1072
        self.range_limit = range_limit
1073
1074
1075
class TestLimitedRangeRequestServer(http_utils.TestCaseWithWebserver):
1076
    """Tests readv requests against a server erroring out on too much ranges."""
1077
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
1078
    # Requests with more range specifiers will error out
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1079
    range_limit = 3
1080
1081
    def create_transport_readonly_server(self):
1082
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1083
                                      protocol_version=self._protocol_version)
1084
1085
    def get_transport(self):
1086
        return self._transport(self.get_readonly_server().get_url())
1087
1088
    def setUp(self):
1089
        http_utils.TestCaseWithWebserver.setUp(self)
1090
        # We need to manipulate ranges that correspond to real chunks in the
1091
        # response, so we build a content appropriately.
1092
        filler = ''.join(['abcdefghij' for x in range(102)])
1093
        content = ''.join(['%04d' % v + filler for v in range(16)])
1094
        self.build_tree_contents([('a', content)],)
1095
1096
    def test_few_ranges(self):
1097
        t = self.get_transport()
1098
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1099
        self.assertEqual(l[0], (0, '0000'))
1100
        self.assertEqual(l[1], (1024, '0001'))
1101
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1102
1103
    def test_more_ranges(self):
1104
        t = self.get_transport()
1105
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1106
        self.assertEqual(l[0], (0, '0000'))
1107
        self.assertEqual(l[1], (1024, '0001'))
1108
        self.assertEqual(l[2], (4096, '0004'))
1109
        self.assertEqual(l[3], (8192, '0008'))
1110
        # The server will refuse to serve the first request (too much ranges),
3199.1.2 by Vincent Ladeuil
Fix two more leaked log files.
1111
        # a second request will succeed.
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1112
        self.assertEqual(2, self.get_readonly_server().GET_request_nb)
1113
1114
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
1115
class TestHttpProxyWhiteBox(tests.TestCase):
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1116
    """Whitebox test proxy http authorization.
1117
2420.1.3 by Vincent Ladeuil
Implement http proxy basic authentication.
1118
    Only the urllib implementation is tested here.
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1119
    """
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1120
1121
    def setUp(self):
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
1122
        tests.TestCase.setUp(self)
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1123
        self._old_env = {}
4986.2.1 by Martin Pool
Remove tearDown in tests in favor of addCleanup
1124
        self.addCleanup(self._restore_env)
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1125
1126
    def _install_env(self, env):
1127
        for name, value in env.iteritems():
2420.1.2 by Vincent Ladeuil
Define tests for http proxy basic authentication. They fail.
1128
            self._old_env[name] = osutils.set_or_unset_env(name, value)
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1129
1130
    def _restore_env(self):
1131
        for name, value in self._old_env.iteritems():
1132
            osutils.set_or_unset_env(name, value)
1133
1134
    def _proxied_request(self):
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
1135
        handler = _urllib2_wrappers.ProxyHandler()
1136
        request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1137
        handler.set_proxy(request, 'http')
1138
        return request
1139
1140
    def test_empty_user(self):
1141
        self._install_env({'http_proxy': 'http://bar.com'})
1142
        request = self._proxied_request()
1143
        self.assertFalse(request.headers.has_key('Proxy-authorization'))
1144
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1145
    def test_invalid_proxy(self):
1146
        """A proxy env variable without scheme"""
1147
        self._install_env({'http_proxy': 'host:1234'})
1148
        self.assertRaises(errors.InvalidURL, self._proxied_request)
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1149
1150
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1151
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1152
    """Tests proxy server.
1153
1154
    Be aware that we do not setup a real proxy here. Instead, we
1155
    check that the *connection* goes through the proxy by serving
1156
    different content (the faked proxy server append '-proxied'
1157
    to the file names).
1158
    """
1159
1160
    # FIXME: We don't have an https server available, so we don't
1161
    # test https connections.
1162
1163
    def setUp(self):
1164
        super(TestProxyHttpServer, self).setUp()
1165
        self.build_tree_contents([('foo', 'contents of foo\n'),
1166
                                  ('foo-proxied', 'proxied contents of foo\n')])
1167
        # Let's setup some attributes for tests
1168
        self.server = self.get_readonly_server()
1169
        self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1170
        if self._testing_pycurl():
1171
            # Oh my ! pycurl does not check for the port as part of
1172
            # no_proxy :-( So we just test the host part
4807.1.1 by Vincent Ladeuil
Fix babune failures, most probably due to jam's fix for the http slowness on windows.
1173
            self.no_proxy_host = self.server.host
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1174
        else:
1175
            self.no_proxy_host = self.proxy_address
1176
        # The secondary server is the proxy
1177
        self.proxy = self.get_secondary_server()
1178
        self.proxy_url = self.proxy.get_url()
1179
        self._old_env = {}
1180
1181
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1182
        # TODO: This is duplicated for lots of the classes in this file
1183
        return (features.pycurl.available()
1184
                and self._transport == PyCurlTransport)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1185
1186
    def create_transport_secondary_server(self):
1187
        """Creates an http server that will serve files with
1188
        '-proxied' appended to their names.
1189
        """
1190
        return http_utils.ProxyServer(protocol_version=self._protocol_version)
1191
1192
    def _install_env(self, env):
1193
        for name, value in env.iteritems():
1194
            self._old_env[name] = osutils.set_or_unset_env(name, value)
1195
1196
    def _restore_env(self):
1197
        for name, value in self._old_env.iteritems():
1198
            osutils.set_or_unset_env(name, value)
1199
1200
    def proxied_in_env(self, env):
1201
        self._install_env(env)
1202
        url = self.server.get_url()
1203
        t = self._transport(url)
1204
        try:
3734.2.8 by Vincent Ladeuil
Catch spurious exceptions (python-2.6) when SocketServer is shut down.
1205
            self.assertEqual('proxied contents of foo\n', t.get('foo').read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1206
        finally:
1207
            self._restore_env()
1208
1209
    def not_proxied_in_env(self, env):
1210
        self._install_env(env)
1211
        url = self.server.get_url()
1212
        t = self._transport(url)
1213
        try:
3734.2.8 by Vincent Ladeuil
Catch spurious exceptions (python-2.6) when SocketServer is shut down.
1214
            self.assertEqual('contents of foo\n', t.get('foo').read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1215
        finally:
1216
            self._restore_env()
1217
1218
    def test_http_proxy(self):
1219
        self.proxied_in_env({'http_proxy': self.proxy_url})
1220
1221
    def test_HTTP_PROXY(self):
1222
        if self._testing_pycurl():
1223
            # pycurl does not check HTTP_PROXY for security reasons
1224
            # (for use in a CGI context that we do not care
1225
            # about. Should we ?)
1226
            raise tests.TestNotApplicable(
1227
                'pycurl does not check HTTP_PROXY for security reasons')
1228
        self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
1229
1230
    def test_all_proxy(self):
1231
        self.proxied_in_env({'all_proxy': self.proxy_url})
1232
1233
    def test_ALL_PROXY(self):
1234
        self.proxied_in_env({'ALL_PROXY': self.proxy_url})
1235
1236
    def test_http_proxy_with_no_proxy(self):
1237
        self.not_proxied_in_env({'http_proxy': self.proxy_url,
1238
                                 'no_proxy': self.no_proxy_host})
1239
1240
    def test_HTTP_PROXY_with_NO_PROXY(self):
1241
        if self._testing_pycurl():
1242
            raise tests.TestNotApplicable(
1243
                'pycurl does not check HTTP_PROXY for security reasons')
1244
        self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
1245
                                 'NO_PROXY': self.no_proxy_host})
1246
1247
    def test_all_proxy_with_no_proxy(self):
1248
        self.not_proxied_in_env({'all_proxy': self.proxy_url,
1249
                                 'no_proxy': self.no_proxy_host})
1250
1251
    def test_ALL_PROXY_with_NO_PROXY(self):
1252
        self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
1253
                                 'NO_PROXY': self.no_proxy_host})
1254
1255
    def test_http_proxy_without_scheme(self):
1256
        if self._testing_pycurl():
1257
            # pycurl *ignores* invalid proxy env variables. If that ever change
1258
            # in the future, this test will fail indicating that pycurl do not
1259
            # ignore anymore such variables.
1260
            self.not_proxied_in_env({'http_proxy': self.proxy_address})
1261
        else:
1262
            self.assertRaises(errors.InvalidURL,
1263
                              self.proxied_in_env,
1264
                              {'http_proxy': self.proxy_address})
1265
1266
1267
class TestRanges(http_utils.TestCaseWithWebserver):
1268
    """Test the Range header in GET methods."""
1269
1270
    def setUp(self):
1271
        http_utils.TestCaseWithWebserver.setUp(self)
1272
        self.build_tree_contents([('a', '0123456789')],)
1273
        server = self.get_readonly_server()
1274
        self.transport = self._transport(server.get_url())
1275
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
1276
    def create_transport_readonly_server(self):
1277
        return http_server.HttpServer(protocol_version=self._protocol_version)
1278
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1279
    def _file_contents(self, relpath, ranges):
1280
        offsets = [ (start, end - start + 1) for start, end in ranges]
1281
        coalesce = self.transport._coalesce_offsets
1282
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1283
        code, data = self.transport._get(relpath, coalesced)
1284
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1285
        for start, end in ranges:
1286
            data.seek(start)
1287
            yield data.read(end - start + 1)
1288
1289
    def _file_tail(self, relpath, tail_amount):
1290
        code, data = self.transport._get(relpath, [], tail_amount)
1291
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1292
        data.seek(-tail_amount, 2)
1293
        return data.read(tail_amount)
1294
1295
    def test_range_header(self):
1296
        # Valid ranges
1297
        map(self.assertEqual,['0', '234'],
1298
            list(self._file_contents('a', [(0,0), (2,4)])),)
1299
1300
    def test_range_header_tail(self):
1301
        self.assertEqual('789', self._file_tail('a', 3))
1302
1303
    def test_syntactically_invalid_range_header(self):
1304
        self.assertListRaises(errors.InvalidHttpRange,
1305
                          self._file_contents, 'a', [(4, 3)])
1306
1307
    def test_semantically_invalid_range_header(self):
1308
        self.assertListRaises(errors.InvalidHttpRange,
1309
                          self._file_contents, 'a', [(42, 128)])
1310
1311
1312
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1313
    """Test redirection between http servers."""
1314
1315
    def create_transport_secondary_server(self):
1316
        """Create the secondary server redirecting to the primary server"""
1317
        new = self.get_readonly_server()
1318
1319
        redirecting = http_utils.HTTPServerRedirecting(
1320
            protocol_version=self._protocol_version)
1321
        redirecting.redirect_to(new.host, new.port)
1322
        return redirecting
1323
1324
    def setUp(self):
1325
        super(TestHTTPRedirections, self).setUp()
1326
        self.build_tree_contents([('a', '0123456789'),
1327
                                  ('bundle',
1328
                                  '# Bazaar revision bundle v0.9\n#\n')
1329
                                  ],)
3878.4.1 by Vincent Ladeuil
Fix bug #245964 by preserving decorators during redirections (when
1330
        # The requests to the old server will be redirected to the new server
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1331
        self.old_transport = self._transport(self.old_server.get_url())
1332
1333
    def test_redirected(self):
1334
        self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
1335
        t = self._transport(self.new_server.get_url())
1336
        self.assertEqual('0123456789', t.get('a').read())
1337
1338
    def test_read_redirected_bundle_from_url(self):
1339
        from bzrlib.bundle import read_bundle_from_url
1340
        url = self.old_transport.abspath('bundle')
3995.2.2 by Martin Pool
Cope with read_bundle_from_url deprecation in test_http
1341
        bundle = self.applyDeprecated(deprecated_in((1, 12, 0)),
1342
                read_bundle_from_url, url)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1343
        # If read_bundle_from_url was successful we get an empty bundle
1344
        self.assertEqual([], bundle.revisions)
1345
1346
1347
class RedirectedRequest(_urllib2_wrappers.Request):
1348
    """Request following redirections. """
1349
1350
    init_orig = _urllib2_wrappers.Request.__init__
1351
1352
    def __init__(self, method, url, *args, **kwargs):
1353
        """Constructor.
1354
1355
        """
1356
        # Since the tests using this class will replace
1357
        # _urllib2_wrappers.Request, we can't just call the base class __init__
1358
        # or we'll loop.
4208.3.2 by Andrew Bennetts
Fix one test failure in test_http under Python 2.7a0.
1359
        RedirectedRequest.init_orig(self, method, url, *args, **kwargs)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1360
        self.follow_redirections = True
1361
1362
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1363
def install_redirected_request(test):
1364
    test.original_class = _urllib2_wrappers.Request
1365
    def restore():
1366
        _urllib2_wrappers.Request = test.original_class
1367
    _urllib2_wrappers.Request = RedirectedRequest
1368
    test.addCleanup(restore)
1369
1370
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1371
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1372
    """Test redirections.
1373
1374
    http implementations do not redirect silently anymore (they
1375
    do not redirect at all in fact). The mechanism is still in
1376
    place at the _urllib2_wrappers.Request level and these tests
1377
    exercise it.
1378
1379
    For the pycurl implementation
1380
    the redirection have been deleted as we may deprecate pycurl
1381
    and I have no place to keep a working implementation.
1382
    -- vila 20070212
1383
    """
1384
1385
    def setUp(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1386
        if (features.pycurl.available()
1387
            and self._transport == PyCurlTransport):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1388
            raise tests.TestNotApplicable(
1389
                "pycurl doesn't redirect silently annymore")
1390
        super(TestHTTPSilentRedirections, self).setUp()
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1391
        install_redirected_request(self)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1392
        self.build_tree_contents([('a','a'),
1393
                                  ('1/',),
1394
                                  ('1/a', 'redirected once'),
1395
                                  ('2/',),
1396
                                  ('2/a', 'redirected twice'),
1397
                                  ('3/',),
1398
                                  ('3/a', 'redirected thrice'),
1399
                                  ('4/',),
1400
                                  ('4/a', 'redirected 4 times'),
1401
                                  ('5/',),
1402
                                  ('5/a', 'redirected 5 times'),
1403
                                  ],)
1404
1405
        self.old_transport = self._transport(self.old_server.get_url())
1406
1407
    def create_transport_secondary_server(self):
1408
        """Create the secondary server, redirections are defined in the tests"""
1409
        return http_utils.HTTPServerRedirecting(
1410
            protocol_version=self._protocol_version)
1411
1412
    def test_one_redirection(self):
1413
        t = self.old_transport
1414
1415
        req = RedirectedRequest('GET', t.abspath('a'))
1416
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1417
                                       self.new_server.port)
1418
        self.old_server.redirections = \
1419
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1420
        self.assertEqual('redirected once',t._perform(req).read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1421
1422
    def test_five_redirections(self):
1423
        t = self.old_transport
1424
1425
        req = RedirectedRequest('GET', t.abspath('a'))
1426
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1427
                                       self.old_server.port)
1428
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1429
                                       self.new_server.port)
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
1430
        self.old_server.redirections = [
1431
            ('/1(.*)', r'%s/2\1' % (old_prefix), 302),
1432
            ('/2(.*)', r'%s/3\1' % (old_prefix), 303),
1433
            ('/3(.*)', r'%s/4\1' % (old_prefix), 307),
1434
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1435
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1436
            ]
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1437
        self.assertEqual('redirected 5 times',t._perform(req).read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1438
1439
1440
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1441
    """Test transport.do_catching_redirections."""
1442
1443
    def setUp(self):
1444
        super(TestDoCatchRedirections, self).setUp()
1445
        self.build_tree_contents([('a', '0123456789'),],)
1446
1447
        self.old_transport = self._transport(self.old_server.get_url())
1448
1449
    def get_a(self, transport):
1450
        return transport.get('a')
1451
1452
    def test_no_redirection(self):
1453
        t = self._transport(self.new_server.get_url())
1454
1455
        # We use None for redirected so that we fail if redirected
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1456
        self.assertEqual('0123456789',
1457
                         transport.do_catching_redirections(
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1458
                self.get_a, t, None).read())
1459
1460
    def test_one_redirection(self):
1461
        self.redirections = 0
1462
1463
        def redirected(transport, exception, redirection_notice):
1464
            self.redirections += 1
1465
            dir, file = urlutils.split(exception.target)
1466
            return self._transport(dir)
1467
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1468
        self.assertEqual('0123456789',
1469
                         transport.do_catching_redirections(
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1470
                self.get_a, self.old_transport, redirected).read())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1471
        self.assertEqual(1, self.redirections)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1472
1473
    def test_redirection_loop(self):
1474
1475
        def redirected(transport, exception, redirection_notice):
1476
            # By using the redirected url as a base dir for the
1477
            # *old* transport, we create a loop: a => a/a =>
1478
            # a/a/a
1479
            return self.old_transport.clone(exception.target)
1480
1481
        self.assertRaises(errors.TooManyRedirections,
1482
                          transport.do_catching_redirections,
1483
                          self.get_a, self.old_transport, redirected)
1484
1485
1486
class TestAuth(http_utils.TestCaseWithWebserver):
1487
    """Test authentication scheme"""
1488
1489
    _auth_header = 'Authorization'
1490
    _password_prompt_prefix = ''
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1491
    _username_prompt_prefix = ''
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
1492
    # Set by load_tests
1493
    _auth_server = None
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1494
1495
    def setUp(self):
1496
        super(TestAuth, self).setUp()
1497
        self.server = self.get_readonly_server()
1498
        self.build_tree_contents([('a', 'contents of a\n'),
1499
                                  ('b', 'contents of b\n'),])
1500
1501
    def create_transport_readonly_server(self):
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
1502
        return self._auth_server(protocol_version=self._protocol_version)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1503
1504
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1505
        # TODO: This is duplicated for lots of the classes in this file
1506
        return (features.pycurl.available()
1507
                and self._transport == PyCurlTransport)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1508
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1509
    def get_user_url(self, user, password):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1510
        """Build an url embedding user and password"""
1511
        url = '%s://' % self.server._url_protocol
1512
        if user is not None:
1513
            url += user
1514
            if password is not None:
1515
                url += ':' + password
1516
            url += '@'
1517
        url += '%s:%s/' % (self.server.host, self.server.port)
1518
        return url
1519
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1520
    def get_user_transport(self, user, password):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1521
        return self._transport(self.get_user_url(user, password))
1522
1523
    def test_no_user(self):
1524
        self.server.add_user('joe', 'foo')
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1525
        t = self.get_user_transport(None, None)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1526
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1527
        # Only one 'Authentication Required' error should occur
1528
        self.assertEqual(1, self.server.auth_required_errors)
1529
1530
    def test_empty_pass(self):
1531
        self.server.add_user('joe', '')
1532
        t = self.get_user_transport('joe', '')
1533
        self.assertEqual('contents of a\n', t.get('a').read())
1534
        # Only one 'Authentication Required' error should occur
1535
        self.assertEqual(1, self.server.auth_required_errors)
1536
1537
    def test_user_pass(self):
1538
        self.server.add_user('joe', 'foo')
1539
        t = self.get_user_transport('joe', 'foo')
1540
        self.assertEqual('contents of a\n', t.get('a').read())
1541
        # Only one 'Authentication Required' error should occur
1542
        self.assertEqual(1, self.server.auth_required_errors)
1543
1544
    def test_unknown_user(self):
1545
        self.server.add_user('joe', 'foo')
1546
        t = self.get_user_transport('bill', 'foo')
1547
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1548
        # Two 'Authentication Required' errors should occur (the
1549
        # initial 'who are you' and 'I don't know you, who are
1550
        # you').
1551
        self.assertEqual(2, self.server.auth_required_errors)
1552
1553
    def test_wrong_pass(self):
1554
        self.server.add_user('joe', 'foo')
1555
        t = self.get_user_transport('joe', 'bar')
1556
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1557
        # Two 'Authentication Required' errors should occur (the
1558
        # initial 'who are you' and 'this is not you, who are you')
1559
        self.assertEqual(2, self.server.auth_required_errors)
1560
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1561
    def test_prompt_for_username(self):
1562
        if self._testing_pycurl():
1563
            raise tests.TestNotApplicable(
1564
                'pycurl cannot prompt, it handles auth by embedding'
1565
                ' user:pass in urls only')
1566
1567
        self.server.add_user('joe', 'foo')
1568
        t = self.get_user_transport(None, None)
1569
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1570
        stderr = tests.StringIOWrapper()
1571
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
1572
                                            stdout=stdout, stderr=stderr)
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1573
        self.assertEqual('contents of a\n',t.get('a').read())
1574
        # stdin should be empty
1575
        self.assertEqual('', ui.ui_factory.stdin.readline())
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1576
        stderr.seek(0)
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1577
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1578
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
1579
        self.assertEqual('', stdout.getvalue())
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1580
        self._check_password_prompt(t._unqualified_scheme, 'joe',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1581
                                    stderr.readline())
4284.1.2 by Vincent Ladeuil
Delete spurious space.
1582
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1583
    def test_prompt_for_password(self):
1584
        if self._testing_pycurl():
1585
            raise tests.TestNotApplicable(
1586
                'pycurl cannot prompt, it handles auth by embedding'
1587
                ' user:pass in urls only')
1588
1589
        self.server.add_user('joe', 'foo')
1590
        t = self.get_user_transport('joe', None)
1591
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1592
        stderr = tests.StringIOWrapper()
1593
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n',
1594
                                            stdout=stdout, stderr=stderr)
1595
        self.assertEqual('contents of a\n', t.get('a').read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1596
        # stdin should be empty
1597
        self.assertEqual('', ui.ui_factory.stdin.readline())
1598
        self._check_password_prompt(t._unqualified_scheme, 'joe',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1599
                                    stderr.getvalue())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1600
        self.assertEqual('', stdout.getvalue())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1601
        # And we shouldn't prompt again for a different request
1602
        # against the same transport.
1603
        self.assertEqual('contents of b\n',t.get('b').read())
1604
        t2 = t.clone()
1605
        # And neither against a clone
1606
        self.assertEqual('contents of b\n',t2.get('b').read())
1607
        # Only one 'Authentication Required' error should occur
1608
        self.assertEqual(1, self.server.auth_required_errors)
1609
1610
    def _check_password_prompt(self, scheme, user, actual_prompt):
1611
        expected_prompt = (self._password_prompt_prefix
1612
                           + ("%s %s@%s:%d, Realm: '%s' password: "
1613
                              % (scheme.upper(),
1614
                                 user, self.server.host, self.server.port,
1615
                                 self.server.auth_realm)))
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1616
        self.assertEqual(expected_prompt, actual_prompt)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1617
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1618
    def _expected_username_prompt(self, scheme):
1619
        return (self._username_prompt_prefix
1620
                + "%s %s:%d, Realm: '%s' username: " % (scheme.upper(),
1621
                                 self.server.host, self.server.port,
1622
                                 self.server.auth_realm))
1623
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1624
    def test_no_prompt_for_password_when_using_auth_config(self):
1625
        if self._testing_pycurl():
1626
            raise tests.TestNotApplicable(
1627
                'pycurl does not support authentication.conf'
1628
                ' since it cannot prompt')
1629
1630
        user =' joe'
1631
        password = 'foo'
1632
        stdin_content = 'bar\n'  # Not the right password
1633
        self.server.add_user(user, password)
1634
        t = self.get_user_transport(user, None)
1635
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1636
                                            stderr=tests.StringIOWrapper())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1637
        # Create a minimal config file with the right password
1638
        conf = config.AuthenticationConfig()
1639
        conf._get_config().update(
1640
            {'httptest': {'scheme': 'http', 'port': self.server.port,
1641
                          'user': user, 'password': password}})
1642
        conf._save()
1643
        # Issue a request to the server to connect
1644
        self.assertEqual('contents of a\n',t.get('a').read())
1645
        # stdin should have  been left untouched
1646
        self.assertEqual(stdin_content, ui.ui_factory.stdin.readline())
1647
        # Only one 'Authentication Required' error should occur
1648
        self.assertEqual(1, self.server.auth_required_errors)
1649
3910.2.2 by Vincent Ladeuil
Fix bug #300347 by allowing querying authentication.conf if no
1650
    def test_user_from_auth_conf(self):
1651
        if self._testing_pycurl():
1652
            raise tests.TestNotApplicable(
1653
                'pycurl does not support authentication.conf')
3910.2.3 by Ben Jansen
Made tweaks requested by John Arbash Meinel.
1654
        user = 'joe'
3910.2.2 by Vincent Ladeuil
Fix bug #300347 by allowing querying authentication.conf if no
1655
        password = 'foo'
1656
        self.server.add_user(user, password)
1657
        # Create a minimal config file with the right password
1658
        conf = config.AuthenticationConfig()
1659
        conf._get_config().update(
1660
            {'httptest': {'scheme': 'http', 'port': self.server.port,
1661
                          'user': user, 'password': password}})
1662
        conf._save()
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1663
        t = self.get_user_transport(None, None)
3910.2.2 by Vincent Ladeuil
Fix bug #300347 by allowing querying authentication.conf if no
1664
        # Issue a request to the server to connect
3910.2.3 by Ben Jansen
Made tweaks requested by John Arbash Meinel.
1665
        self.assertEqual('contents of a\n', t.get('a').read())
3910.2.2 by Vincent Ladeuil
Fix bug #300347 by allowing querying authentication.conf if no
1666
        # Only one 'Authentication Required' error should occur
1667
        self.assertEqual(1, self.server.auth_required_errors)
1668
3111.1.26 by Vincent Ladeuil
Re-add a test lost in refactoring.
1669
    def test_changing_nonce(self):
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
1670
        if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1671
                                     http_utils.ProxyDigestAuthServer):
1672
            raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
3111.1.26 by Vincent Ladeuil
Re-add a test lost in refactoring.
1673
        if self._testing_pycurl():
1674
            raise tests.KnownFailure(
1675
                'pycurl does not handle a nonce change')
1676
        self.server.add_user('joe', 'foo')
1677
        t = self.get_user_transport('joe', 'foo')
1678
        self.assertEqual('contents of a\n', t.get('a').read())
1679
        self.assertEqual('contents of b\n', t.get('b').read())
1680
        # Only one 'Authentication Required' error should have
1681
        # occured so far
1682
        self.assertEqual(1, self.server.auth_required_errors)
1683
        # The server invalidates the current nonce
1684
        self.server.auth_nonce = self.server.auth_nonce + '. No, now!'
1685
        self.assertEqual('contents of a\n', t.get('a').read())
1686
        # Two 'Authentication Required' errors should occur (the
1687
        # initial 'who are you' and a second 'who are you' with the new nonce)
1688
        self.assertEqual(2, self.server.auth_required_errors)
1689
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1690
1691
1692
class TestProxyAuth(TestAuth):
1693
    """Test proxy authentication schemes."""
1694
1695
    _auth_header = 'Proxy-authorization'
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1696
    _password_prompt_prefix = 'Proxy '
1697
    _username_prompt_prefix = 'Proxy '
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1698
1699
    def setUp(self):
1700
        super(TestProxyAuth, self).setUp()
1701
        self._old_env = {}
1702
        self.addCleanup(self._restore_env)
1703
        # Override the contents to avoid false positives
1704
        self.build_tree_contents([('a', 'not proxied contents of a\n'),
1705
                                  ('b', 'not proxied contents of b\n'),
1706
                                  ('a-proxied', 'contents of a\n'),
1707
                                  ('b-proxied', 'contents of b\n'),
1708
                                  ])
1709
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1710
    def get_user_transport(self, user, password):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1711
        self._install_env({'all_proxy': self.get_user_url(user, password)})
1712
        return self._transport(self.server.get_url())
1713
1714
    def _install_env(self, env):
1715
        for name, value in env.iteritems():
1716
            self._old_env[name] = osutils.set_or_unset_env(name, value)
1717
1718
    def _restore_env(self):
1719
        for name, value in self._old_env.iteritems():
1720
            osutils.set_or_unset_env(name, value)
1721
1722
    def test_empty_pass(self):
1723
        if self._testing_pycurl():
1724
            import pycurl
1725
            if pycurl.version_info()[1] < '7.16.0':
1726
                raise tests.KnownFailure(
1727
                    'pycurl < 7.16.0 does not handle empty proxy passwords')
1728
        super(TestProxyAuth, self).test_empty_pass()
1729
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1730
1731
class SampleSocket(object):
1732
    """A socket-like object for use in testing the HTTP request handler."""
1733
1734
    def __init__(self, socket_read_content):
1735
        """Constructs a sample socket.
1736
1737
        :param socket_read_content: a byte sequence
1738
        """
1739
        # Use plain python StringIO so we can monkey-patch the close method to
1740
        # not discard the contents.
1741
        from StringIO import StringIO
1742
        self.readfile = StringIO(socket_read_content)
1743
        self.writefile = StringIO()
1744
        self.writefile.close = lambda: None
1745
1746
    def makefile(self, mode='r', bufsize=None):
1747
        if 'r' in mode:
1748
            return self.readfile
1749
        else:
1750
            return self.writefile
1751
1752
1753
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1754
1755
    def setUp(self):
1756
        super(SmartHTTPTunnellingTest, self).setUp()
1757
        # We use the VFS layer as part of HTTP tunnelling tests.
1758
        self._captureVar('BZR_NO_SMART_VFS', None)
1759
        self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1760
1761
    def create_transport_readonly_server(self):
1762
        return http_utils.HTTPServerWithSmarts(
1763
            protocol_version=self._protocol_version)
1764
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
1765
    def test_open_bzrdir(self):
1766
        branch = self.make_branch('relpath')
1767
        http_server = self.get_readonly_server()
1768
        url = http_server.get_url() + 'relpath'
1769
        bd = bzrdir.BzrDir.open(url)
1770
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1771
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1772
    def test_bulk_data(self):
1773
        # We should be able to send and receive bulk data in a single message.
1774
        # The 'readv' command in the smart protocol both sends and receives
1775
        # bulk data, so we use that.
1776
        self.build_tree(['data-file'])
1777
        http_server = self.get_readonly_server()
1778
        http_transport = self._transport(http_server.get_url())
1779
        medium = http_transport.get_smart_medium()
1780
        # Since we provide the medium, the url below will be mostly ignored
1781
        # during the test, as long as the path is '/'.
1782
        remote_transport = remote.RemoteTransport('bzr://fake_host/',
1783
                                                  medium=medium)
1784
        self.assertEqual(
1785
            [(0, "c")], list(remote_transport.readv("data-file", [(0,1)])))
1786
1787
    def test_http_send_smart_request(self):
1788
1789
        post_body = 'hello\n'
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
1790
        expected_reply_body = 'ok\x012\n'
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1791
1792
        http_server = self.get_readonly_server()
1793
        http_transport = self._transport(http_server.get_url())
1794
        medium = http_transport.get_smart_medium()
1795
        response = medium.send_http_smart_request(post_body)
1796
        reply_body = response.read()
1797
        self.assertEqual(expected_reply_body, reply_body)
1798
1799
    def test_smart_http_server_post_request_handler(self):
1800
        httpd = self.get_readonly_server()._get_httpd()
1801
1802
        socket = SampleSocket(
1803
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1804
            # HTTP/1.1 posts must have a Content-Length (but it doesn't hurt
1805
            # for 1.0)
1806
            + 'Content-Length: 6\r\n'
1807
            '\r\n'
1808
            'hello\n')
1809
        # Beware: the ('localhost', 80) below is the
1810
        # client_address parameter, but we don't have one because
1811
        # we have defined a socket which is not bound to an
1812
        # address. The test framework never uses this client
1813
        # address, so far...
1814
        request_handler = http_utils.SmartRequestHandler(socket,
1815
                                                         ('localhost', 80),
1816
                                                         httpd)
1817
        response = socket.writefile.getvalue()
1818
        self.assertStartsWith(response, '%s 200 ' % self._protocol_version)
1819
        # This includes the end of the HTTP headers, and all the body.
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
1820
        expected_end_of_response = '\r\n\r\nok\x012\n'
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1821
        self.assertEndsWith(response, expected_end_of_response)
1822
1823
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1824
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
1825
    """No smart server here request handler."""
1826
1827
    def do_POST(self):
1828
        self.send_error(403, "Forbidden")
1829
1830
1831
class SmartClientAgainstNotSmartServer(TestSpecificRequestHandler):
1832
    """Test smart client behaviour against an http server without smarts."""
1833
1834
    _req_handler_class = ForbiddenRequestHandler
1835
1836
    def test_probe_smart_server(self):
1837
        """Test error handling against server refusing smart requests."""
1838
        server = self.get_readonly_server()
1839
        t = self._transport(server.get_url())
1840
        # No need to build a valid smart request here, the server will not even
1841
        # try to interpret it.
1842
        self.assertRaises(errors.SmartProtocolError,
3734.3.1 by Vincent Ladeuil
Fix SmartHTTPMedium refactoring related test.
1843
                          t.get_smart_medium().send_http_smart_request,
1844
                          'whatever')
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1845
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1846
class Test_redirected_to(tests.TestCase):
1847
1848
    def test_redirected_to_subdir(self):
1849
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1850
        r = t._redirected_to('http://www.example.com/foo',
1851
                             'http://www.example.com/foo/subdir')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1852
        self.assertIsInstance(r, type(t))
1853
        # Both transports share the some connection
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1854
        self.assertEqual(t._get_connection(), r._get_connection())
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1855
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1856
    def test_redirected_to_self_with_slash(self):
1857
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1858
        r = t._redirected_to('http://www.example.com/foo',
1859
                             'http://www.example.com/foo/')
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1860
        self.assertIsInstance(r, type(t))
1861
        # Both transports share the some connection (one can argue that we
1862
        # should return the exact same transport here, but that seems
1863
        # overkill).
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1864
        self.assertEqual(t._get_connection(), r._get_connection())
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1865
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1866
    def test_redirected_to_host(self):
1867
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1868
        r = t._redirected_to('http://www.example.com/foo',
1869
                             'http://foo.example.com/foo/subdir')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1870
        self.assertIsInstance(r, type(t))
1871
1872
    def test_redirected_to_same_host_sibling_protocol(self):
1873
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1874
        r = t._redirected_to('http://www.example.com/foo',
1875
                             'https://www.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1876
        self.assertIsInstance(r, type(t))
1877
1878
    def test_redirected_to_same_host_different_protocol(self):
1879
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1880
        r = t._redirected_to('http://www.example.com/foo',
1881
                             'ftp://www.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1882
        self.assertNotEquals(type(r), type(t))
1883
1884
    def test_redirected_to_different_host_same_user(self):
1885
        t = self._transport('http://joe@www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1886
        r = t._redirected_to('http://www.example.com/foo',
1887
                             'https://foo.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1888
        self.assertIsInstance(r, type(t))
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1889
        self.assertEqual(t._user, r._user)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1890
1891
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1892
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1893
    """Request handler for a unique and pre-defined request.
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1894
1895
    The only thing we care about here is how many bytes travel on the wire. But
1896
    since we want to measure it for a real http client, we have to send it
1897
    correct responses.
1898
1899
    We expect to receive a *single* request nothing more (and we won't even
1900
    check what request it is, we just measure the bytes read until an empty
1901
    line.
1902
    """
1903
1904
    def handle_one_request(self):
1905
        tcs = self.server.test_case_server
1906
        requestline = self.rfile.readline()
1907
        headers = self.MessageClass(self.rfile, 0)
1908
        # We just read: the request, the headers, an empty line indicating the
1909
        # end of the headers.
1910
        bytes_read = len(requestline)
1911
        for line in headers.headers:
1912
            bytes_read += len(line)
1913
        bytes_read += len('\r\n')
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1914
        if requestline.startswith('POST'):
1915
            # The body should be a single line (or we don't know where it ends
1916
            # and we don't want to issue a blocking read)
1917
            body = self.rfile.readline()
1918
            bytes_read += len(body)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1919
        tcs.bytes_read = bytes_read
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1920
1921
        # We set the bytes written *before* issuing the write, the client is
1922
        # supposed to consume every produced byte *before* checking that value.
3945.1.7 by Vincent Ladeuil
Test against https.
1923
1924
        # Doing the oppposite may lead to test failure: we may be interrupted
1925
        # after the write but before updating the value. The client can then
1926
        # continue and read the value *before* we can update it. And yes,
1927
        # this has been observed -- vila 20090129
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1928
        tcs.bytes_written = len(tcs.canned_response)
1929
        self.wfile.write(tcs.canned_response)
1930
1931
1932
class ActivityServerMixin(object):
1933
1934
    def __init__(self, protocol_version):
1935
        super(ActivityServerMixin, self).__init__(
1936
            request_handler=PredefinedRequestHandler,
1937
            protocol_version=protocol_version)
1938
        # Bytes read and written by the server
1939
        self.bytes_read = 0
1940
        self.bytes_written = 0
1941
        self.canned_response = None
1942
1943
1944
class ActivityHTTPServer(ActivityServerMixin, http_server.HttpServer):
1945
    pass
1946
1947
1948
if tests.HTTPSServerFeature.available():
1949
    from bzrlib.tests import https_server
1950
    class ActivityHTTPSServer(ActivityServerMixin, https_server.HTTPSServer):
1951
        pass
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1952
1953
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
1954
class TestActivityMixin(object):
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1955
    """Test socket activity reporting.
1956
1957
    We use a special purpose server to control the bytes sent and received and
1958
    be able to predict the activity on the client socket.
1959
    """
1960
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1961
    def setUp(self):
1962
        tests.TestCase.setUp(self)
1963
        self.server = self._activity_server(self._protocol_version)
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
1964
        self.server.start_server()
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1965
        self.activities = {}
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1966
        def report_activity(t, bytes, direction):
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1967
            count = self.activities.get(direction, 0)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1968
            count += bytes
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1969
            self.activities[direction] = count
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1970
1971
        # We override at class level because constructors may propagate the
1972
        # bound method and render instance overriding ineffective (an
4031.3.1 by Frank Aspell
Fixing various typos
1973
        # alternative would be to define a specific ui factory instead...)
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1974
        self.orig_report_activity = self._transport._report_activity
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1975
        self._transport._report_activity = report_activity
1976
4986.2.1 by Martin Pool
Remove tearDown in tests in favor of addCleanup
1977
        def teardown():
1978
            self._transport._report_activity = self.orig_report_activity
1979
            self.server.stop_server()
1980
        self.addCleanup(teardown)
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1981
1982
    def get_transport(self):
1983
        return self._transport(self.server.get_url())
1984
1985
    def assertActivitiesMatch(self):
1986
        self.assertEqual(self.server.bytes_read,
1987
                         self.activities.get('write', 0), 'written bytes')
1988
        self.assertEqual(self.server.bytes_written,
1989
                         self.activities.get('read', 0), 'read bytes')
1990
1991
    def test_get(self):
1992
        self.server.canned_response = '''HTTP/1.1 200 OK\r
1993
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
1994
Server: Apache/2.0.54 (Fedora)\r
1995
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
1996
ETag: "56691-23-38e9ae00"\r
1997
Accept-Ranges: bytes\r
1998
Content-Length: 35\r
1999
Connection: close\r
2000
Content-Type: text/plain; charset=UTF-8\r
2001
\r
2002
Bazaar-NG meta directory, format 1
2003
'''
2004
        t = self.get_transport()
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
2005
        self.assertEqual('Bazaar-NG meta directory, format 1\n',
2006
                         t.get('foo/bar').read())
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2007
        self.assertActivitiesMatch()
2008
2009
    def test_has(self):
2010
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2011
Server: SimpleHTTP/0.6 Python/2.5.2\r
2012
Date: Thu, 29 Jan 2009 20:21:47 GMT\r
2013
Content-type: application/octet-stream\r
2014
Content-Length: 20\r
2015
Last-Modified: Thu, 29 Jan 2009 20:21:47 GMT\r
2016
\r
2017
'''
2018
        t = self.get_transport()
2019
        self.assertTrue(t.has('foo/bar'))
2020
        self.assertActivitiesMatch()
2021
2022
    def test_readv(self):
2023
        self.server.canned_response = '''HTTP/1.1 206 Partial Content\r
2024
Date: Tue, 11 Jul 2006 04:49:48 GMT\r
2025
Server: Apache/2.0.54 (Fedora)\r
2026
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
2027
ETag: "238a3c-16ec2-805c5540"\r
2028
Accept-Ranges: bytes\r
2029
Content-Length: 1534\r
2030
Connection: close\r
2031
Content-Type: multipart/byteranges; boundary=418470f848b63279b\r
2032
\r
2033
\r
2034
--418470f848b63279b\r
2035
Content-type: text/plain; charset=UTF-8\r
2036
Content-range: bytes 0-254/93890\r
2037
\r
2038
mbp@sourcefrog.net-20050309040815-13242001617e4a06
2039
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e7627
2040
mbp@sourcefrog.net-20050309040957-6cad07f466bb0bb8
2041
mbp@sourcefrog.net-20050309041501-c840e09071de3b67
2042
mbp@sourcefrog.net-20050309044615-c24a3250be83220a
2043
\r
2044
--418470f848b63279b\r
2045
Content-type: text/plain; charset=UTF-8\r
2046
Content-range: bytes 1000-2049/93890\r
2047
\r
2048
40-fd4ec249b6b139ab
2049
mbp@sourcefrog.net-20050311063625-07858525021f270b
2050
mbp@sourcefrog.net-20050311231934-aa3776aff5200bb9
2051
mbp@sourcefrog.net-20050311231953-73aeb3a131c3699a
2052
mbp@sourcefrog.net-20050311232353-f5e33da490872c6a
2053
mbp@sourcefrog.net-20050312071639-0a8f59a34a024ff0
2054
mbp@sourcefrog.net-20050312073432-b2c16a55e0d6e9fb
2055
mbp@sourcefrog.net-20050312073831-a47c3335ece1920f
2056
mbp@sourcefrog.net-20050312085412-13373aa129ccbad3
2057
mbp@sourcefrog.net-20050313052251-2bf004cb96b39933
2058
mbp@sourcefrog.net-20050313052856-3edd84094687cb11
2059
mbp@sourcefrog.net-20050313053233-e30a4f28aef48f9d
2060
mbp@sourcefrog.net-20050313053853-7c64085594ff3072
2061
mbp@sourcefrog.net-20050313054757-a86c3f5871069e22
2062
mbp@sourcefrog.net-20050313061422-418f1f73b94879b9
2063
mbp@sourcefrog.net-20050313120651-497bd231b19df600
2064
mbp@sourcefrog.net-20050314024931-eae0170ef25a5d1a
2065
mbp@sourcefrog.net-20050314025438-d52099f915fe65fc
2066
mbp@sourcefrog.net-20050314025539-637a636692c055cf
2067
mbp@sourcefrog.net-20050314025737-55eb441f430ab4ba
2068
mbp@sourcefrog.net-20050314025901-d74aa93bb7ee8f62
2069
mbp@source\r
2070
--418470f848b63279b--\r
2071
'''
2072
        t = self.get_transport()
2073
        # Remember that the request is ignored and that the ranges below
2074
        # doesn't have to match the canned response.
2075
        l = list(t.readv('/foo/bar', ((0, 255), (1000, 1050))))
2076
        self.assertEqual(2, len(l))
2077
        self.assertActivitiesMatch()
2078
2079
    def test_post(self):
2080
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2081
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2082
Server: Apache/2.0.54 (Fedora)\r
2083
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2084
ETag: "56691-23-38e9ae00"\r
2085
Accept-Ranges: bytes\r
2086
Content-Length: 35\r
2087
Connection: close\r
2088
Content-Type: text/plain; charset=UTF-8\r
2089
\r
2090
lalala whatever as long as itsssss
2091
'''
2092
        t = self.get_transport()
2093
        # We must send a single line of body bytes, see
2094
        # PredefinedRequestHandler.handle_one_request
2095
        code, f = t._post('abc def end-of-body\n')
2096
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2097
        self.assertActivitiesMatch()
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2098
2099
2100
class TestActivity(tests.TestCase, TestActivityMixin):
2101
2102
    def setUp(self):
2103
        tests.TestCase.setUp(self)
2104
        self.server = self._activity_server(self._protocol_version)
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
2105
        self.server.start_server()
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2106
        self.activities = {}
2107
        def report_activity(t, bytes, direction):
2108
            count = self.activities.get(direction, 0)
2109
            count += bytes
2110
            self.activities[direction] = count
2111
2112
        # We override at class level because constructors may propagate the
2113
        # bound method and render instance overriding ineffective (an
2114
        # alternative would be to define a specific ui factory instead...)
2115
        self.orig_report_activity = self._transport._report_activity
2116
        self._transport._report_activity = report_activity
2117
4986.2.1 by Martin Pool
Remove tearDown in tests in favor of addCleanup
2118
        def teardown():
2119
            self._transport._report_activity = self.orig_report_activity
2120
            self.server.stop_server()
2121
2122
        self.addCleanup(teardown)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2123
2124
2125
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2126
2127
    def setUp(self):
2128
        tests.TestCase.setUp(self)
2129
        # Unlike TestActivity, we are really testing ReportingFileSocket and
2130
        # ReportingSocket, so we don't need all the parametrization. Since
2131
        # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2132
        # test them through their use by the transport than directly (that's a
2133
        # bit less clean but far more simpler and effective).
2134
        self.server = ActivityHTTPServer('HTTP/1.1')
2135
        self._transport=_urllib.HttpTransport_urllib
2136
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
2137
        self.server.start_server()
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2138
2139
        # We override at class level because constructors may propagate the
2140
        # bound method and render instance overriding ineffective (an
2141
        # alternative would be to define a specific ui factory instead...)
2142
        self.orig_report_activity = self._transport._report_activity
2143
        self._transport._report_activity = None
2144
4986.2.1 by Martin Pool
Remove tearDown in tests in favor of addCleanup
2145
        def tearDown():
2146
            self._transport._report_activity = self.orig_report_activity
2147
            self.server.stop_server()
2148
        self.addCleanup(teardown)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2149
2150
    def assertActivitiesMatch(self):
2151
        # Nothing to check here
2152
        pass
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2153
2154
2155
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
2156
    """Test authentication on the redirected http server."""
2157
2158
    _auth_header = 'Authorization'
2159
    _password_prompt_prefix = ''
2160
    _username_prompt_prefix = ''
2161
    _auth_server = http_utils.HTTPBasicAuthServer
2162
    _transport = _urllib.HttpTransport_urllib
2163
2164
    def create_transport_readonly_server(self):
2165
        return self._auth_server()
2166
2167
    def create_transport_secondary_server(self):
2168
        """Create the secondary server redirecting to the primary server"""
2169
        new = self.get_readonly_server()
2170
2171
        redirecting = http_utils.HTTPServerRedirecting()
2172
        redirecting.redirect_to(new.host, new.port)
2173
        return redirecting
2174
2175
    def setUp(self):
2176
        super(TestAuthOnRedirected, self).setUp()
2177
        self.build_tree_contents([('a','a'),
2178
                                  ('1/',),
2179
                                  ('1/a', 'redirected once'),
2180
                                  ],)
2181
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2182
                                       self.new_server.port)
2183
        self.old_server.redirections = [
2184
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2185
        self.old_transport = self._transport(self.old_server.get_url())
2186
        self.new_server.add_user('joe', 'foo')
2187
2188
    def get_a(self, transport):
2189
        return transport.get('a')
2190
2191
    def test_auth_on_redirected_via_do_catching_redirections(self):
2192
        self.redirections = 0
2193
2194
        def redirected(transport, exception, redirection_notice):
2195
            self.redirections += 1
2196
            dir, file = urlutils.split(exception.target)
2197
            return self._transport(dir)
2198
2199
        stdout = tests.StringIOWrapper()
2200
        stderr = tests.StringIOWrapper()
2201
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2202
                                            stdout=stdout, stderr=stderr)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2203
        self.assertEqual('redirected once',
2204
                         transport.do_catching_redirections(
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2205
                self.get_a, self.old_transport, redirected).read())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2206
        self.assertEqual(1, self.redirections)
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2207
        # stdin should be empty
2208
        self.assertEqual('', ui.ui_factory.stdin.readline())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2209
        # stdout should be empty, stderr will contains the prompts
2210
        self.assertEqual('', stdout.getvalue())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2211
2212
    def test_auth_on_redirected_via_following_redirections(self):
2213
        self.new_server.add_user('joe', 'foo')
2214
        stdout = tests.StringIOWrapper()
2215
        stderr = tests.StringIOWrapper()
2216
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2217
                                            stdout=stdout, stderr=stderr)
2218
        t = self.old_transport
2219
        req = RedirectedRequest('GET', t.abspath('a'))
2220
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2221
                                       self.new_server.port)
2222
        self.old_server.redirections = [
2223
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2224
        self.assertEqual('redirected once',t._perform(req).read())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2225
        # stdin should be empty
2226
        self.assertEqual('', ui.ui_factory.stdin.readline())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2227
        # stdout should be empty, stderr will contains the prompts
2228
        self.assertEqual('', stdout.getvalue())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2229
2230