/brz/remove-bazaar

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