/brz/remove-bazaar

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