~bzr-pqm/bzr/bzr.dev

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