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