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