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