/brz/remove-bazaar

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