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