/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
1
# Copyright (C) 2005, 2006 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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
1185.16.68 by Martin Pool
- http url fixes suggested by Robey Pointer, and tests
16
1540.3.3 by Martin Pool
Review updates of pycurl transport
17
# FIXME: This test should be repeated for each available http client
18
# implementation; at the moment we have urllib and pycurl.
19
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
20
# TODO: Should be renamed to bzrlib.transport.http.tests?
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
21
# TODO: What about renaming to bzrlib.tests.transport.http ?
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
22
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
23
import os
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
24
import select
2000.2.2 by John Arbash Meinel
Update the urllib.has test.
25
import socket
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
26
import threading
2000.2.2 by John Arbash Meinel
Update the urllib.has test.
27
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
28
import bzrlib
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
29
from bzrlib import errors
2091.1.1 by Martin Pool
Avoid MSG_WAITALL as it doesn't work on Windows
30
from bzrlib import osutils
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
31
from bzrlib.tests import (
32
    TestCase,
33
    TestSkipped,
34
    )
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
35
from bzrlib.tests.HttpServer import (
36
    HttpServer,
37
    HttpServer_PyCurl,
38
    HttpServer_urllib,
39
    )
40
from bzrlib.tests.HTTPTestUtil import (
41
    BadProtocolRequestHandler,
42
    BadStatusRequestHandler,
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
43
    FakeProxyRequestHandler,
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
44
    ForbiddenRequestHandler,
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
45
    InvalidStatusRequestHandler,
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
46
    NoRangeRequestHandler,
47
    SingleRangeRequestHandler,
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
48
    TestCaseWithTwoWebservers,
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
49
    TestCaseWithWebserver,
50
    WallRequestHandler,
51
    )
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
52
from bzrlib.transport import (
53
    get_transport,
54
    Transport,
55
    )
2004.3.3 by vila
Better (but still incomplete) design for bogus servers.
56
from bzrlib.transport.http import (
57
    extract_auth,
58
    HttpTransportBase,
59
    )
1540.3.26 by Martin Pool
[merge] bzr.dev; pycurl not updated for readv yet
60
from bzrlib.transport.http._urllib import HttpTransport_urllib
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
61
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
62
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
63
class FakeManager(object):
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
64
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
65
    def __init__(self):
66
        self.credentials = []
2004.3.1 by vila
Test ConnectionError exceptions.
67
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
68
    def add_password(self, realm, host, username, password):
69
        self.credentials.append([realm, host, username, password])
70
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
71
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
72
class RecordingServer(object):
73
    """A fake HTTP server.
74
    
75
    It records the bytes sent to it, and replies with a 200.
76
    """
77
78
    def __init__(self, expect_body_tail=None):
2018.2.28 by Andrew Bennetts
Changes in response to review: re-use _base_curl, rather than keeping a seperate _post_curl object; add docstring to test_http.RecordingServer, set is_user_error on some new exceptions.
79
        """Constructor.
80
81
        :type expect_body_tail: str
82
        :param expect_body_tail: a reply won't be sent until this string is
83
            received.
84
        """
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
85
        self._expect_body_tail = expect_body_tail
86
        self.host = None
87
        self.port = None
88
        self.received_bytes = ''
89
90
    def setUp(self):
91
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
92
        self._sock.bind(('127.0.0.1', 0))
93
        self.host, self.port = self._sock.getsockname()
94
        self._ready = threading.Event()
95
        self._thread = threading.Thread(target=self._accept_read_and_reply)
96
        self._thread.setDaemon(True)
97
        self._thread.start()
98
        self._ready.wait(5)
99
100
    def _accept_read_and_reply(self):
101
        self._sock.listen(1)
102
        self._ready.set()
103
        self._sock.settimeout(5)
104
        try:
105
            conn, address = self._sock.accept()
106
            # On win32, the accepted connection will be non-blocking to start
107
            # with because we're using settimeout.
108
            conn.setblocking(True)
109
            while not self.received_bytes.endswith(self._expect_body_tail):
110
                self.received_bytes += conn.recv(4096)
111
            conn.sendall('HTTP/1.1 200 OK\r\n')
112
        except socket.timeout:
113
            # Make sure the client isn't stuck waiting for us to e.g. accept.
114
            self._sock.close()
2158.2.1 by v.ladeuil+lp at free
Windows tests cleanup.
115
        except socket.error:
116
            # The client may have already closed the socket.
117
            pass
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
118
119
    def tearDown(self):
120
        try:
121
            self._sock.close()
122
        except socket.error:
123
            # We might have already closed it.  We don't care.
124
            pass
125
        self.host = None
126
        self.port = None
127
128
1185.16.68 by Martin Pool
- http url fixes suggested by Robey Pointer, and tests
129
class TestHttpUrls(TestCase):
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
130
2004.1.40 by v.ladeuil+lp at free
Fix the race condition again and correct some small typos to be in
131
    # FIXME: Some of these tests should be done for both
132
    # implementations
133
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
134
    def test_url_parsing(self):
135
        f = FakeManager()
136
        url = extract_auth('http://example.com', f)
137
        self.assertEquals('http://example.com', url)
138
        self.assertEquals(0, len(f.credentials))
1185.50.94 by John Arbash Meinel
Updated web page url to http://bazaar-vcs.org
139
        url = extract_auth('http://user:pass@www.bazaar-vcs.org/bzr/bzr.dev', f)
140
        self.assertEquals('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
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
141
        self.assertEquals(1, len(f.credentials))
2004.3.1 by vila
Test ConnectionError exceptions.
142
        self.assertEquals([None, 'www.bazaar-vcs.org', 'user', 'pass'],
143
                          f.credentials[0])
144
1185.16.68 by Martin Pool
- http url fixes suggested by Robey Pointer, and tests
145
    def test_abs_url(self):
146
        """Construction of absolute http URLs"""
1185.50.94 by John Arbash Meinel
Updated web page url to http://bazaar-vcs.org
147
        t = HttpTransport_urllib('http://bazaar-vcs.org/bzr/bzr.dev/')
1185.16.68 by Martin Pool
- http url fixes suggested by Robey Pointer, and tests
148
        eq = self.assertEqualDiff
149
        eq(t.abspath('.'),
1185.50.94 by John Arbash Meinel
Updated web page url to http://bazaar-vcs.org
150
           'http://bazaar-vcs.org/bzr/bzr.dev')
2004.3.1 by vila
Test ConnectionError exceptions.
151
        eq(t.abspath('foo/bar'),
1185.50.94 by John Arbash Meinel
Updated web page url to http://bazaar-vcs.org
152
           'http://bazaar-vcs.org/bzr/bzr.dev/foo/bar')
1185.16.68 by Martin Pool
- http url fixes suggested by Robey Pointer, and tests
153
        eq(t.abspath('.bzr'),
1185.50.94 by John Arbash Meinel
Updated web page url to http://bazaar-vcs.org
154
           'http://bazaar-vcs.org/bzr/bzr.dev/.bzr')
1185.16.68 by Martin Pool
- http url fixes suggested by Robey Pointer, and tests
155
        eq(t.abspath('.bzr/1//2/./3'),
1185.50.94 by John Arbash Meinel
Updated web page url to http://bazaar-vcs.org
156
           'http://bazaar-vcs.org/bzr/bzr.dev/.bzr/1/2/3')
1185.16.68 by Martin Pool
- http url fixes suggested by Robey Pointer, and tests
157
158
    def test_invalid_http_urls(self):
159
        """Trap invalid construction of urls"""
1185.50.94 by John Arbash Meinel
Updated web page url to http://bazaar-vcs.org
160
        t = HttpTransport_urllib('http://bazaar-vcs.org/bzr/bzr.dev/')
1185.16.68 by Martin Pool
- http url fixes suggested by Robey Pointer, and tests
161
        self.assertRaises(ValueError,
162
            t.abspath,
163
            '.bzr/')
2004.1.42 by v.ladeuil+lp at free
Fix #70803 by catching the httplib exception.
164
        t = HttpTransport_urllib('http://http://bazaar-vcs.org/bzr/bzr.dev/')
165
        self.assertRaises(errors.InvalidURL, t.has, 'foo/bar')
1185.16.68 by Martin Pool
- http url fixes suggested by Robey Pointer, and tests
166
167
    def test_http_root_urls(self):
168
        """Construction of URLs from server root"""
1540.3.26 by Martin Pool
[merge] bzr.dev; pycurl not updated for readv yet
169
        t = HttpTransport_urllib('http://bzr.ozlabs.org/')
1185.16.68 by Martin Pool
- http url fixes suggested by Robey Pointer, and tests
170
        eq = self.assertEqualDiff
171
        eq(t.abspath('.bzr/tree-version'),
172
           'http://bzr.ozlabs.org/.bzr/tree-version')
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
173
1540.3.24 by Martin Pool
Add new protocol 'http+pycurl' that always uses PyCurl.
174
    def test_http_impl_urls(self):
175
        """There are servers which ask for particular clients to connect"""
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
176
        server = HttpServer_PyCurl()
1540.3.24 by Martin Pool
Add new protocol 'http+pycurl' that always uses PyCurl.
177
        try:
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
178
            server.setUp()
179
            url = server.get_url()
180
            self.assertTrue(url.startswith('http+pycurl://'))
181
        finally:
182
            server.tearDown()
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
183
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
184
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
185
class TestHttpConnections(object):
186
    """Test the http connections.
187
188
    This MUST be used by daughter classes that also inherit from
189
    TestCaseWithWebserver.
2004.1.16 by v.ladeuil+lp at free
Add tests against erroneous http status lines.
190
191
    We can't inherit directly from TestCaseWithWebserver or the
192
    test framework will try to create an instance which cannot
193
    run, its implementation being incomplete.
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
194
    """
195
196
    def setUp(self):
197
        TestCaseWithWebserver.setUp(self)
1540.3.33 by Martin Pool
Fix http tests that were failing to run tearDown when setup got a missing dependency
198
        self.build_tree(['xxx', 'foo/', 'foo/bar'], line_endings='binary',
199
                        transport=self.get_transport())
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
200
201
    def test_http_has(self):
1185.50.84 by John Arbash Meinel
[merge] bzr.dev, cleanup conflicts, fixup http tests for new TestCase layout.
202
        server = self.get_readonly_server()
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
203
        t = self._transport(server.get_url())
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
204
        self.assertEqual(t.has('foo/bar'), True)
1185.50.84 by John Arbash Meinel
[merge] bzr.dev, cleanup conflicts, fixup http tests for new TestCase layout.
205
        self.assertEqual(len(server.logs), 1)
2004.3.1 by vila
Test ConnectionError exceptions.
206
        self.assertContainsRe(server.logs[0],
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
207
            r'"HEAD /foo/bar HTTP/1.." (200|302) - "-" "bzr/')
1553.1.5 by James Henstridge
Make HTTP transport has() method do HEAD requests, and update test to
208
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
209
    def test_http_has_not_found(self):
210
        server = self.get_readonly_server()
211
        t = self._transport(server.get_url())
1553.1.5 by James Henstridge
Make HTTP transport has() method do HEAD requests, and update test to
212
        self.assertEqual(t.has('not-found'), False)
2004.3.1 by vila
Test ConnectionError exceptions.
213
        self.assertContainsRe(server.logs[1],
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
214
            r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
215
216
    def test_http_get(self):
1185.50.84 by John Arbash Meinel
[merge] bzr.dev, cleanup conflicts, fixup http tests for new TestCase layout.
217
        server = self.get_readonly_server()
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
218
        t = self._transport(server.get_url())
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
219
        fp = t.get('foo/bar')
220
        self.assertEqualDiff(
221
            fp.read(),
1553.1.3 by James Henstridge
Make bzrlib.transport.http.HttpServer output referer and user agent as in
222
            'contents of foo/bar\n')
1185.50.84 by John Arbash Meinel
[merge] bzr.dev, cleanup conflicts, fixup http tests for new TestCase layout.
223
        self.assertEqual(len(server.logs), 1)
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
224
        self.assertTrue(server.logs[0].find(
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
225
            '"GET /foo/bar HTTP/1.1" 200 - "-" "bzr/%s'
226
            % bzrlib.__version__) > -1)
1540.3.33 by Martin Pool
Fix http tests that were failing to run tearDown when setup got a missing dependency
227
2018.2.3 by Andrew Bennetts
Starting factoring out the smart server client "medium" from the protocol.
228
    def test_get_smart_medium(self):
229
        # For HTTP, get_smart_medium should return the transport object.
230
        server = self.get_readonly_server()
231
        http_transport = self._transport(server.get_url())
232
        medium = http_transport.get_smart_medium()
2018.2.26 by Andrew Bennetts
Changes prompted by j-a-meinel's review.
233
        self.assertIs(medium, http_transport)
1540.3.33 by Martin Pool
Fix http tests that were failing to run tearDown when setup got a missing dependency
234
2000.2.2 by John Arbash Meinel
Update the urllib.has test.
235
    def test_has_on_bogus_host(self):
2004.1.1 by vila
Connection sharing, with redirection. without authentification.
236
        # Get a free address and don't 'accept' on it, so that we
237
        # can be sure there is no http handler there, but set a
238
        # reasonable timeout to not slow down tests too much.
239
        default_timeout = socket.getdefaulttimeout()
240
        try:
241
            socket.setdefaulttimeout(2)
242
            s = socket.socket()
243
            s.bind(('localhost', 0))
244
            t = self._transport('http://%s:%s/' % s.getsockname())
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
245
            self.assertRaises(errors.ConnectionError, t.has, 'foo/bar')
2004.1.1 by vila
Connection sharing, with redirection. without authentification.
246
        finally:
247
            socket.setdefaulttimeout(default_timeout)
248
1540.3.33 by Martin Pool
Fix http tests that were failing to run tearDown when setup got a missing dependency
249
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
250
class TestWithTransport_pycurl(object):
251
    """Test case to inherit from if pycurl is present"""
2004.1.40 by v.ladeuil+lp at free
Fix the race condition again and correct some small typos to be in
252
1540.3.33 by Martin Pool
Fix http tests that were failing to run tearDown when setup got a missing dependency
253
    def _get_pycurl_maybe(self):
1540.3.29 by Martin Pool
Prevent selftest failure when pycurl is not installed
254
        try:
255
            from bzrlib.transport.http._pycurl import PyCurlTransport
1612.1.1 by Martin Pool
Raise errors correctly on pycurl connection failure
256
            return PyCurlTransport
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
257
        except errors.DependencyNotPresent:
1540.3.29 by Martin Pool
Prevent selftest failure when pycurl is not installed
258
            raise TestSkipped('pycurl not present')
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
259
1540.3.33 by Martin Pool
Fix http tests that were failing to run tearDown when setup got a missing dependency
260
    _transport = property(_get_pycurl_maybe)
261
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
262
263
class TestHttpConnections_urllib(TestHttpConnections, TestCaseWithWebserver):
264
    """Test http connections with urllib"""
265
266
    _transport = HttpTransport_urllib
267
268
269
270
class TestHttpConnections_pycurl(TestWithTransport_pycurl,
271
                                 TestHttpConnections,
272
                                 TestCaseWithWebserver):
273
    """Test http connections with pycurl"""
1540.3.33 by Martin Pool
Fix http tests that were failing to run tearDown when setup got a missing dependency
274
275
1540.3.23 by Martin Pool
Allow urls like http+pycurl://host/ to use a particular impl
276
class TestHttpTransportRegistration(TestCase):
277
    """Test registrations of various http implementations"""
278
279
    def test_http_registered(self):
280
        # urlllib should always be present
281
        t = get_transport('http+urllib://bzr.google.com/')
282
        self.assertIsInstance(t, Transport)
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
283
        self.assertIsInstance(t, HttpTransport_urllib)
1786.1.23 by John Arbash Meinel
Move offset_to_http_ranges back onto HttpTransportBase, clarify tests.
284
285
286
class TestOffsets(TestCase):
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
287
    """Test offsets_to_ranges method"""
1786.1.23 by John Arbash Meinel
Move offset_to_http_ranges back onto HttpTransportBase, clarify tests.
288
289
    def test_offsets_to_ranges_simple(self):
290
        to_range = HttpTransportBase.offsets_to_ranges
1786.1.39 by John Arbash Meinel
Remove the ability to read negative offsets from readv()
291
        ranges = to_range([(10, 1)])
1786.1.23 by John Arbash Meinel
Move offset_to_http_ranges back onto HttpTransportBase, clarify tests.
292
        self.assertEqual([[10, 10]], ranges)
1786.1.39 by John Arbash Meinel
Remove the ability to read negative offsets from readv()
293
294
        ranges = to_range([(0, 1), (1, 1)])
295
        self.assertEqual([[0, 1]], ranges)
296
297
        ranges = to_range([(1, 1), (0, 1)])
298
        self.assertEqual([[0, 1]], ranges)
1786.1.23 by John Arbash Meinel
Move offset_to_http_ranges back onto HttpTransportBase, clarify tests.
299
300
    def test_offset_to_ranges_overlapped(self):
301
        to_range = HttpTransportBase.offsets_to_ranges
302
1786.1.39 by John Arbash Meinel
Remove the ability to read negative offsets from readv()
303
        ranges = to_range([(10, 1), (20, 2), (22, 5)])
304
        self.assertEqual([[10, 10], [20, 26]], ranges)
305
306
        ranges = to_range([(10, 1), (11, 2), (22, 5)])
307
        self.assertEqual([[10, 12], [22, 26]], ranges)
1786.1.23 by John Arbash Meinel
Move offset_to_http_ranges back onto HttpTransportBase, clarify tests.
308
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
309
2158.2.1 by v.ladeuil+lp at free
Windows tests cleanup.
310
class TestPost(object):
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
311
312
    def _test_post_body_is_received(self, scheme):
313
        server = RecordingServer(expect_body_tail='end-of-body')
314
        server.setUp()
315
        self.addCleanup(server.tearDown)
316
        url = '%s://%s:%s/' % (scheme, server.host, server.port)
317
        try:
318
            http_transport = get_transport(url)
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
319
        except errors.UnsupportedProtocol:
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
320
            raise TestSkipped('%s not available' % scheme)
321
        code, response = http_transport._post('abc def end-of-body')
322
        self.assertTrue(
323
            server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
324
        self.assertTrue('content-length: 19\r' in server.received_bytes.lower())
325
        # The transport should not be assuming that the server can accept
326
        # chunked encoding the first time it connects, because HTTP/1.1, so we
327
        # check for the literal string.
328
        self.assertTrue(
329
            server.received_bytes.endswith('\r\n\r\nabc def end-of-body'))
330
2158.2.1 by v.ladeuil+lp at free
Windows tests cleanup.
331
332
class TestPost_urllib(TestCase, TestPost):
333
    """TestPost for urllib implementation"""
334
335
    _transport = HttpTransport_urllib
336
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
337
    def test_post_body_is_received_urllib(self):
338
        self._test_post_body_is_received('http+urllib')
339
2158.2.1 by v.ladeuil+lp at free
Windows tests cleanup.
340
341
class TestPost_pycurl(TestWithTransport_pycurl, TestCase, TestPost):
342
    """TestPost for pycurl implementation"""
343
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
344
    def test_post_body_is_received_pycurl(self):
345
        self._test_post_body_is_received('http+pycurl')
346
347
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
348
class TestRangeHeader(TestCase):
349
    """Test range_header method"""
350
351
    def check_header(self, value, ranges=[], tail=0):
352
        range_header = HttpTransportBase.range_header
353
        self.assertEqual(value, range_header(ranges, tail))
354
355
    def test_range_header_single(self):
1786.1.36 by John Arbash Meinel
pycurl expects us to just set the range of bytes, not including bytes=
356
        self.check_header('0-9', ranges=[[0,9]])
357
        self.check_header('100-109', ranges=[[100,109]])
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
358
359
    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=
360
        self.check_header('-10', tail=10)
361
        self.check_header('-50', tail=50)
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
362
363
    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=
364
        self.check_header('0-9,100-200,300-5000',
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
365
                          ranges=[(0,9), (100, 200), (300,5000)])
366
367
    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=
368
        self.check_header('0-9,300-5000,-50',
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
369
                          ranges=[(0,9), (300,5000)],
370
                          tail=50)
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
371
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
372
373
class TestWallServer(object):
374
    """Tests exceptions during the connection phase"""
375
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
376
    def create_transport_readonly_server(self):
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
377
        return HttpServer(WallRequestHandler)
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
378
379
    def test_http_has(self):
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
380
        server = self.get_readonly_server()
2004.3.1 by vila
Test ConnectionError exceptions.
381
        t = self._transport(server.get_url())
2004.1.40 by v.ladeuil+lp at free
Fix the race condition again and correct some small typos to be in
382
        # Unfortunately httplib (see HTTPResponse._read_status
383
        # for details) make no distinction between a closed
384
        # socket and badly formatted status line, so we can't
385
        # just test for ConnectionError, we have to test
386
        # InvalidHttpResponse too.
387
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
388
                          t.has, 'foo/bar')
2004.3.3 by vila
Better (but still incomplete) design for bogus servers.
389
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
390
    def test_http_get(self):
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
391
        server = self.get_readonly_server()
2004.3.3 by vila
Better (but still incomplete) design for bogus servers.
392
        t = self._transport(server.get_url())
2145.1.1 by mbp at sourcefrog
merge urllib keepalive etc
393
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
394
                          t.get, 'foo/bar')
2004.3.3 by vila
Better (but still incomplete) design for bogus servers.
395
396
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
397
class TestWallServer_urllib(TestWallServer, TestCaseWithWebserver):
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
398
    """Tests "wall" server for urllib implementation"""
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
399
400
    _transport = HttpTransport_urllib
401
402
403
class TestWallServer_pycurl(TestWithTransport_pycurl,
404
                            TestWallServer,
405
                            TestCaseWithWebserver):
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
406
    """Tests "wall" server for pycurl implementation"""
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
407
408
2004.1.16 by v.ladeuil+lp at free
Add tests against erroneous http status lines.
409
class TestBadStatusServer(object):
410
    """Tests bad status from server."""
411
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
412
    def create_transport_readonly_server(self):
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
413
        return HttpServer(BadStatusRequestHandler)
2004.1.16 by v.ladeuil+lp at free
Add tests against erroneous http status lines.
414
415
    def test_http_has(self):
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
416
        server = self.get_readonly_server()
2004.1.16 by v.ladeuil+lp at free
Add tests against erroneous http status lines.
417
        t = self._transport(server.get_url())
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
418
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
2004.1.16 by v.ladeuil+lp at free
Add tests against erroneous http status lines.
419
420
    def test_http_get(self):
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
421
        server = self.get_readonly_server()
2004.1.16 by v.ladeuil+lp at free
Add tests against erroneous http status lines.
422
        t = self._transport(server.get_url())
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
423
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
2004.1.16 by v.ladeuil+lp at free
Add tests against erroneous http status lines.
424
425
426
class TestBadStatusServer_urllib(TestBadStatusServer, TestCaseWithWebserver):
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
427
    """Tests bad status server for urllib implementation"""
2004.1.16 by v.ladeuil+lp at free
Add tests against erroneous http status lines.
428
429
    _transport = HttpTransport_urllib
430
431
432
class TestBadStatusServer_pycurl(TestWithTransport_pycurl,
433
                                 TestBadStatusServer,
434
                                 TestCaseWithWebserver):
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
435
    """Tests bad status server for pycurl implementation"""
2004.1.16 by v.ladeuil+lp at free
Add tests against erroneous http status lines.
436
437
438
class TestInvalidStatusServer(TestBadStatusServer):
439
    """Tests invalid status from server.
440
441
    Both implementations raises the same error as for a bad status.
442
    """
443
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
444
    def create_transport_readonly_server(self):
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
445
        return HttpServer(InvalidStatusRequestHandler)
2004.1.16 by v.ladeuil+lp at free
Add tests against erroneous http status lines.
446
447
448
class TestInvalidStatusServer_urllib(TestInvalidStatusServer,
449
                                     TestCaseWithWebserver):
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
450
    """Tests invalid status server for urllib implementation"""
2004.1.16 by v.ladeuil+lp at free
Add tests against erroneous http status lines.
451
452
    _transport = HttpTransport_urllib
453
454
455
class TestInvalidStatusServer_pycurl(TestWithTransport_pycurl,
456
                                     TestInvalidStatusServer,
457
                                     TestCaseWithWebserver):
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
458
    """Tests invalid status server for pycurl implementation"""
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
459
460
461
class TestBadProtocolServer(object):
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
462
    """Tests bad protocol from server."""
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
463
464
    def create_transport_readonly_server(self):
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
465
        return HttpServer(BadProtocolRequestHandler)
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
466
467
    def test_http_has(self):
468
        server = self.get_readonly_server()
469
        t = self._transport(server.get_url())
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
470
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
471
472
    def test_http_get(self):
473
        server = self.get_readonly_server()
474
        t = self._transport(server.get_url())
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
475
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
476
477
478
class TestBadProtocolServer_urllib(TestBadProtocolServer,
479
                                   TestCaseWithWebserver):
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
480
    """Tests bad protocol server for urllib implementation"""
2004.1.19 by v.ladeuil+lp at free
Test protocol version in http responses.
481
482
    _transport = HttpTransport_urllib
483
484
# curl don't check the protocol version
485
#class TestBadProtocolServer_pycurl(TestWithTransport_pycurl,
486
#                                   TestBadProtocolServer,
487
#                                   TestCaseWithWebserver):
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
488
#    """Tests bad protocol server for pycurl implementation"""
489
490
491
class TestForbiddenServer(object):
492
    """Tests forbidden server"""
493
494
    def create_transport_readonly_server(self):
495
        return HttpServer(ForbiddenRequestHandler)
496
497
    def test_http_has(self):
498
        server = self.get_readonly_server()
499
        t = self._transport(server.get_url())
500
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
501
502
    def test_http_get(self):
503
        server = self.get_readonly_server()
504
        t = self._transport(server.get_url())
505
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
506
507
508
class TestForbiddenServer_urllib(TestForbiddenServer, TestCaseWithWebserver):
509
    """Tests forbidden server for urllib implementation"""
510
511
    _transport = HttpTransport_urllib
512
513
514
class TestForbiddenServer_pycurl(TestWithTransport_pycurl,
515
                                 TestForbiddenServer,
516
                                 TestCaseWithWebserver):
517
    """Tests forbidden server for pycurl implementation"""
518
2004.1.28 by v.ladeuil+lp at free
Merge bzr.dev. Including http modifications by "smart" related code
519
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
520
class TestRecordingServer(TestCase):
521
522
    def test_create(self):
523
        server = RecordingServer(expect_body_tail=None)
524
        self.assertEqual('', server.received_bytes)
525
        self.assertEqual(None, server.host)
526
        self.assertEqual(None, server.port)
527
528
    def test_setUp_and_tearDown(self):
529
        server = RecordingServer(expect_body_tail=None)
530
        server.setUp()
531
        try:
532
            self.assertNotEqual(None, server.host)
533
            self.assertNotEqual(None, server.port)
534
        finally:
535
            server.tearDown()
536
        self.assertEqual(None, server.host)
537
        self.assertEqual(None, server.port)
538
539
    def test_send_receive_bytes(self):
540
        server = RecordingServer(expect_body_tail='c')
541
        server.setUp()
542
        self.addCleanup(server.tearDown)
543
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
544
        sock.connect((server.host, server.port))
545
        sock.sendall('abc')
546
        self.assertEqual('HTTP/1.1 200 OK\r\n',
2091.1.1 by Martin Pool
Avoid MSG_WAITALL as it doesn't work on Windows
547
                         osutils.recv_all(sock, 4096))
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
548
        self.assertEqual('abc', server.received_bytes)
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
549
550
551
class TestRangeRequestServer(object):
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
552
    """Tests readv requests against server.
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
553
554
    This MUST be used by daughter classes that also inherit from
555
    TestCaseWithWebserver.
556
557
    We can't inherit directly from TestCaseWithWebserver or the
558
    test framework will try to create an instance which cannot
559
    run, its implementation being incomplete.
560
    """
561
562
    def setUp(self):
563
        TestCaseWithWebserver.setUp(self)
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
564
        self.build_tree_contents([('a', '0123456789')],)
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
565
566
    def test_readv(self):
567
        server = self.get_readonly_server()
568
        t = self._transport(server.get_url())
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
569
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
570
        self.assertEqual(l[0], (0, '0'))
571
        self.assertEqual(l[1], (1, '1'))
572
        self.assertEqual(l[2], (3, '34'))
573
        self.assertEqual(l[3], (9, '9'))
574
575
    def test_readv_out_of_order(self):
576
        server = self.get_readonly_server()
577
        t = self._transport(server.get_url())
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
578
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
579
        self.assertEqual(l[0], (1, '1'))
580
        self.assertEqual(l[1], (9, '9'))
581
        self.assertEqual(l[2], (0, '0'))
582
        self.assertEqual(l[3], (3, '34'))
583
2000.3.9 by v.ladeuil+lp at free
The tests that would have help avoid bug #73948 and all that mess :)
584
    def test_readv_invalid_ranges(self):
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
585
        server = self.get_readonly_server()
586
        t = self._transport(server.get_url())
587
588
        # This is intentionally reading off the end of the file
589
        # since we are sure that it cannot get there
2000.3.9 by v.ladeuil+lp at free
The tests that would have help avoid bug #73948 and all that mess :)
590
        self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
591
                              t.readv, 'a', [(1,1), (8,10)])
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
592
593
        # This is trying to seek past the end of the file, it should
594
        # also raise a special error
2000.3.9 by v.ladeuil+lp at free
The tests that would have help avoid bug #73948 and all that mess :)
595
        self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
596
                              t.readv, 'a', [(12,2)])
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
597
598
599
class TestSingleRangeRequestServer(TestRangeRequestServer):
600
    """Test readv against a server which accept only single range requests"""
601
602
    def create_transport_readonly_server(self):
603
        return HttpServer(SingleRangeRequestHandler)
604
605
606
class TestSingleRangeRequestServer_urllib(TestSingleRangeRequestServer,
607
                                          TestCaseWithWebserver):
608
    """Tests single range requests accepting server for urllib implementation"""
609
610
    _transport = HttpTransport_urllib
611
612
613
class TestSingleRangeRequestServer_pycurl(TestWithTransport_pycurl,
614
                                          TestSingleRangeRequestServer,
615
                                          TestCaseWithWebserver):
616
    """Tests single range requests accepting server for pycurl implementation"""
617
618
619
class TestNoRangeRequestServer(TestRangeRequestServer):
620
    """Test readv against a server which do not accept range requests"""
621
622
    def create_transport_readonly_server(self):
623
        return HttpServer(NoRangeRequestHandler)
624
625
626
class TestNoRangeRequestServer_urllib(TestNoRangeRequestServer,
627
                                      TestCaseWithWebserver):
628
    """Tests range requests refusing server for urllib implementation"""
629
630
    _transport = HttpTransport_urllib
631
632
633
class TestNoRangeRequestServer_pycurl(TestWithTransport_pycurl,
634
                               TestNoRangeRequestServer,
635
                               TestCaseWithWebserver):
636
    """Tests range requests refusing server for pycurl implementation"""
637
638
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
639
class TestHttpProxyWhiteBox(TestCase):
640
    """Whitebox test proxy http authorization."""
641
642
    def setUp(self):
643
        TestCase.setUp(self)
644
        self._old_env = {}
645
646
    def tearDown(self):
647
        self._restore_env()
648
649
    def _set_and_capture_env_var(self, name, new_value):
650
        """Set an environment variable, and reset it when finished."""
651
        self._old_env[name] = osutils.set_or_unset_env(name, new_value)
652
653
    def _install_env(self, env):
654
        for name, value in env.iteritems():
655
            self._set_and_capture_env_var(name, value)
656
657
    def _restore_env(self):
658
        for name, value in self._old_env.iteritems():
659
            osutils.set_or_unset_env(name, value)
660
661
    def _proxied_request(self):
662
        from bzrlib.transport.http._urllib2_wrappers import (
663
            ProxyHandler,
664
            Request,
665
            )
666
667
        handler = ProxyHandler()
668
        request = Request('GET','http://baz/buzzle')
669
        handler.set_proxy(request, 'http')
670
        return request
671
672
    def test_empty_user(self):
673
        self._install_env({'http_proxy': 'http://bar.com'})
674
        request = self._proxied_request()
675
        self.assertFalse(request.headers.has_key('Proxy-authorization'))
676
677
    def test_empty_pass(self):
678
        self._install_env({'http_proxy': 'http://joe@bar.com'})
679
        request = self._proxied_request()
680
        self.assertEqual('Basic ' + 'joe:'.encode('base64').strip(),
681
                         request.headers['Proxy-authorization'])
682
    def test_user_pass(self):
683
        self._install_env({'http_proxy': 'http://joe:foo@bar.com'})
684
        request = self._proxied_request()
685
        self.assertEqual('Basic ' + 'joe:foo'.encode('base64').strip(),
686
                         request.headers['Proxy-authorization'])
687
688
689
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
690
class TestProxyHttpServer(object):
691
    """Tests proxy server.
692
693
    This MUST be used by daughter classes that also inherit from
694
    TestCaseWithTwoWebservers.
695
696
    We can't inherit directly from TestCaseWithTwoWebservers or
697
    the test framework will try to create an instance which
698
    cannot run, its implementation being incomplete.
2167.3.6 by v.ladeuil+lp at free
Take John's comments into account and add more tests.
699
700
    Be aware that we do not setup a real proxy here. Instead, we
2167.3.7 by v.ladeuil+lp at free
Typos corrected.
701
    check that the *connection* goes through the proxy by serving
2167.3.6 by v.ladeuil+lp at free
Take John's comments into account and add more tests.
702
    different content (the faked proxy server append '-proxied'
703
    to the file names).
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
704
    """
705
2167.3.6 by v.ladeuil+lp at free
Take John's comments into account and add more tests.
706
    # FIXME: We don't have an https server available, so we don't
707
    # test https connections.
708
2273.2.1 by v.ladeuil+lp at free
Fix bug #83954.
709
    # FIXME: Once the test suite is better fitted to test
710
    # authorization schemes, test proxy authorizations too (see
711
    # bug #83954).
712
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
713
    def setUp(self):
714
        TestCaseWithTwoWebservers.setUp(self)
715
        self.build_tree_contents([('foo', 'contents of foo\n'),
716
                                  ('foo-proxied', 'proxied contents of foo\n')])
2167.3.6 by v.ladeuil+lp at free
Take John's comments into account and add more tests.
717
        # Let's setup some attributes for tests
718
        self.server = self.get_readonly_server()
719
        self.no_proxy_host = 'localhost:%d' % self.server.port
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
720
        # The secondary server is the proxy
2167.3.6 by v.ladeuil+lp at free
Take John's comments into account and add more tests.
721
        self.proxy = self.get_secondary_server()
722
        self.proxy_url = self.proxy.get_url()
723
        self._old_env = {}
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
724
725
    def create_transport_secondary_server(self):
726
        """Creates an http server that will serve files with
727
        '-proxied' appended to their names.
728
        """
729
        return HttpServer(FakeProxyRequestHandler)
730
2167.3.6 by v.ladeuil+lp at free
Take John's comments into account and add more tests.
731
    def _set_and_capture_env_var(self, name, new_value):
732
        """Set an environment variable, and reset it when finished."""
733
        self._old_env[name] = osutils.set_or_unset_env(name, new_value)
734
735
    def _install_env(self, env):
736
        for name, value in env.iteritems():
737
            self._set_and_capture_env_var(name, value)
738
739
    def _restore_env(self):
740
        for name, value in self._old_env.iteritems():
741
            osutils.set_or_unset_env(name, value)
742
743
    def proxied_in_env(self, env):
744
        self._install_env(env)
745
        url = self.server.get_url()
746
        t = self._transport(url)
747
        try:
748
            self.assertEqual(t.get('foo').read(), 'proxied contents of foo\n')
749
        finally:
750
            self._restore_env()
751
752
    def not_proxied_in_env(self, env):
753
        self._install_env(env)
754
        url = self.server.get_url()
755
        t = self._transport(url)
756
        try:
757
            self.assertEqual(t.get('foo').read(), 'contents of foo\n')
758
        finally:
759
            self._restore_env()
760
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
761
    def test_http_proxy(self):
2167.3.6 by v.ladeuil+lp at free
Take John's comments into account and add more tests.
762
        self.proxied_in_env({'http_proxy': self.proxy_url})
763
764
    def test_HTTP_PROXY(self):
765
        self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
766
767
    def test_all_proxy(self):
768
        self.proxied_in_env({'all_proxy': self.proxy_url})
769
770
    def test_ALL_PROXY(self):
771
        self.proxied_in_env({'ALL_PROXY': self.proxy_url})
772
773
    def test_http_proxy_with_no_proxy(self):
774
        self.not_proxied_in_env({'http_proxy': self.proxy_url,
775
                                 'no_proxy': self.no_proxy_host})
776
777
    def test_HTTP_PROXY_with_NO_PROXY(self):
778
        self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
779
                                 'NO_PROXY': self.no_proxy_host})
780
781
    def test_all_proxy_with_no_proxy(self):
782
        self.not_proxied_in_env({'all_proxy': self.proxy_url,
783
                                 'no_proxy': self.no_proxy_host})
784
785
    def test_ALL_PROXY_with_NO_PROXY(self):
786
        self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
787
                                 'NO_PROXY': self.no_proxy_host})
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
788
789
790
class TestProxyHttpServer_urllib(TestProxyHttpServer,
791
                                 TestCaseWithTwoWebservers):
792
    """Tests proxy server for urllib implementation"""
793
794
    _transport = HttpTransport_urllib
795
796
797
class TestProxyHttpServer_pycurl(TestWithTransport_pycurl,
798
                                 TestProxyHttpServer,
799
                                 TestCaseWithTwoWebservers):
800
    """Tests proxy server for pycurl implementation"""
801
2167.3.6 by v.ladeuil+lp at free
Take John's comments into account and add more tests.
802
    def setUp(self):
803
        TestProxyHttpServer.setUp(self)
804
        # Oh my ! pycurl does not check for the port as part of
805
        # no_proxy :-( So we just test the host part
806
        self.no_proxy_host = 'localhost'
807
808
    def test_HTTP_PROXY(self):
809
        # pycurl do not check HTTP_PROXY for security reasons
810
        # (for use in a CGI context that we do not care
811
        # about. Should we ?)
812
        raise TestSkipped()
813
814
    def test_HTTP_PROXY_with_NO_PROXY(self):
815
        raise TestSkipped()
2183.1.1 by Aaron Bentley
Make test HTTP server's range handling more spec-compliant (Vincent Ladeuil)
816
817
2182.2.2 by v.ladeuil+lp at free
Thanks again to Aaron, the http server RFC2616 compliance
818
class TestRanges(object):
819
    """Test the Range header in GET methods..
820
821
    This MUST be used by daughter classes that also inherit from
822
    TestCaseWithWebserver.
823
824
    We can't inherit directly from TestCaseWithWebserver or the
825
    test framework will try to create an instance which cannot
826
    run, its implementation being incomplete.
827
    """
828
829
    def setUp(self):
830
        TestCaseWithWebserver.setUp(self)
831
        self.build_tree_contents([('a', '0123456789')],)
832
        server = self.get_readonly_server()
833
        self.transport = self._transport(server.get_url())
834
835
    def _file_contents(self, relpath, ranges, tail_amount=0):
836
         code, data = self.transport._get(relpath, ranges)
837
         self.assertTrue(code in (200, 206),'_get returns: %d' % code)
838
         for start, end in ranges:
839
             data.seek(start)
840
             yield data.read(end - start + 1)
841
842
    def _file_tail(self, relpath, tail_amount):
843
         code, data = self.transport._get(relpath, [], tail_amount)
844
         self.assertTrue(code in (200, 206),'_get returns: %d' % code)
845
         data.seek(-tail_amount + 1, 2)
846
         return data.read(tail_amount)
847
848
    def test_range_header(self):
849
        # Valid ranges
850
        map(self.assertEqual,['0', '234'],
851
            list(self._file_contents('a', [(0,0), (2,4)])),)
852
        # Tail
853
        self.assertEqual('789', self._file_tail('a', 3))
854
        # Syntactically invalid range
855
        self.assertRaises(errors.InvalidRange,
856
                          self.transport._get, 'a', [(4, 3)])
857
        # Semantically invalid range
858
        self.assertRaises(errors.InvalidRange,
859
                          self.transport._get, 'a', [(42, 128)])
860
861
862
class TestRanges_urllib(TestRanges, TestCaseWithWebserver):
863
    """Test the Range header in GET methods for urllib implementation"""
864
865
    _transport = HttpTransport_urllib
866
867
868
class TestRanges_pycurl(TestWithTransport_pycurl,
869
                        TestRanges,
870
                        TestCaseWithWebserver):
871
    """Test the Range header in GET methods for pycurl implementation"""