/brz/remove-bazaar

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