File: test_dump.py

package info (click to toggle)
python-requests-toolbelt 1.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 876 kB
  • sloc: python: 3,653; makefile: 166; sh: 7
file content (405 lines) | stat: -rw-r--r-- 13,517 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
"""Collection of tests for utils.dump.

The dump utility module only has two public attributes:

- dump_response
- dump_all

This module, however, tests many of the private implementation details since
those public functions just wrap them and testing the public functions will be
very complex and high-level.
"""
from requests_toolbelt._compat import HTTPHeaderDict
from requests_toolbelt.utils import dump

try:
    from unittest import mock
except ImportError:
    import mock
import pytest
import requests

from . import get_betamax

HTTP_1_1 = 11
HTTP_1_0 = 10
HTTP_0_9 = 9
HTTP_UNKNOWN = 5000


class TestSimplePrivateFunctions(object):

    """Excercise simple private functions in one logical place."""

    def test_coerce_to_bytes_skips_byte_strings(self):
        """Show that _coerce_to_bytes skips bytes input."""
        bytestr = b'some bytes'
        assert dump._coerce_to_bytes(bytestr) is bytestr

    def test_coerce_to_bytes_converts_text(self):
        """Show that _coerce_to_bytes handles text input."""
        bytestr = b'some bytes'
        text = bytestr.decode('utf-8')
        assert dump._coerce_to_bytes(text) == bytestr

    def test_format_header(self):
        """Prove that _format_header correctly formats bytes input."""
        header = b'Connection'
        value = b'close'
        expected = b'Connection: close\r\n'
        assert dump._format_header(header, value) == expected

    def test_format_header_handles_unicode(self):
        """Prove that _format_header correctly formats text input."""
        header = b'Connection'.decode('utf-8')
        value = b'close'.decode('utf-8')
        expected = b'Connection: close\r\n'
        assert dump._format_header(header, value) == expected

    def test_build_request_path(self):
        """Show we get the right request path for a normal request."""
        path, _ = dump._build_request_path(
            'https://example.com/foo/bar', {}
        )
        assert path == b'/foo/bar'

    def test_build_request_path_with_query_string(self):
        """Show we include query strings appropriately."""
        path, _ = dump._build_request_path(
            'https://example.com/foo/bar?query=data', {}
        )
        assert path == b'/foo/bar?query=data'

    def test_build_request_path_with_proxy_info(self):
        """Show that we defer to the proxy request_path info."""
        path, _ = dump._build_request_path(
            'https://example.com/', {
                'request_path': b'https://example.com/test'
            }
        )
        assert path == b'https://example.com/test'


class RequestResponseMixin(object):

    """Mix-in for test classes needing mocked requests and responses."""

    response_spec = [
        'connection',
        'content',
        'raw',
        'reason',
        'request',
        'url',
    ]

    request_spec = [
        'body',
        'headers',
        'method',
        'url',
    ]

    httpresponse_spec = [
        'headers',
        'reason',
        'status',
        'version',
    ]

    adapter_spec = [
        'proxy_manager',
    ]

    @pytest.fixture(autouse=True)
    def set_up(self):
        """xUnit style autoused fixture creating mocks."""
        self.response = mock.Mock(spec=self.response_spec)
        self.request = mock.Mock(spec=self.request_spec)
        self.httpresponse = mock.Mock(spec=self.httpresponse_spec)
        self.adapter = mock.Mock(spec=self.adapter_spec)

        self.response.connection = self.adapter
        self.response.request = self.request
        self.response.raw = self.httpresponse

    def configure_response(self, content=b'', proxy_manager=None, url=None,
                           reason=b''):
        """Helper function to configure a mocked response."""
        self.adapter.proxy_manager = proxy_manager or {}
        self.response.content = content
        self.response.url = url
        self.response.reason = reason

    def configure_request(self, body=b'', headers=None, method=None,
                          url=None):
        """Helper function to configure a mocked request."""
        self.request.body = body
        self.request.headers = headers or {}
        self.request.method = method
        self.request.url = url

    def configure_httpresponse(self, headers=None, reason=b'', status=200,
                               version=HTTP_1_1):
        """Helper function to configure a mocked urllib3 response."""
        self.httpresponse.headers = HTTPHeaderDict(headers or {})
        self.httpresponse.reason = reason
        self.httpresponse.status = status
        self.httpresponse.version = version


class TestResponsePrivateFunctions(RequestResponseMixin):

    """Excercise private functions using responses."""

    def test_get_proxy_information_sans_proxy(self):
        """Show no information is returned when not using a proxy."""
        self.configure_response()

        assert dump._get_proxy_information(self.response) is None

    def test_get_proxy_information_with_proxy_over_http(self):
        """Show only the request path is returned for HTTP requests.

        Using HTTP over a proxy doesn't alter anything except the request path
        of the request. The method doesn't change a dictionary with the
        request_path is the only thing that should be returned.
        """
        self.configure_response(
            proxy_manager={'http://': 'http://local.proxy:3939'},
        )
        self.configure_request(
            url='http://example.com',
            method='GET',
        )

        assert dump._get_proxy_information(self.response) == {
            'request_path': 'http://example.com'
        }

    def test_get_proxy_information_with_proxy_over_https(self):
        """Show that the request path and method are returned for HTTPS reqs.

        Using HTTPS over a proxy changes the method used and the request path.
        """
        self.configure_response(
            proxy_manager={'http://': 'http://local.proxy:3939'},
        )
        self.configure_request(
            url='https://example.com',
            method='GET',
        )

        assert dump._get_proxy_information(self.response) == {
            'method': 'CONNECT',
            'request_path': 'https://example.com'
        }

    def test_dump_request_data(self):
        """Build up the request data into a bytearray."""
        self.configure_request(
            url='http://example.com/',
            method='GET',
        )

        array = bytearray()
        prefixes = dump.PrefixSettings('request:', 'response:')
        dump._dump_request_data(
            request=self.request,
            prefixes=prefixes,
            bytearr=array,
            proxy_info={},
        )

        assert b'request:GET / HTTP/1.1\r\n' in array
        assert b'request:Host: example.com\r\n' in array

    def test_dump_non_string_request_data(self):
        """Build up the request data into a bytearray."""
        self.configure_request(
            url='http://example.com/',
            method='POST',
            body=1
        )

        array = bytearray()
        prefixes = dump.PrefixSettings('request:', 'response:')
        dump._dump_request_data(
            request=self.request,
            prefixes=prefixes,
            bytearr=array,
            proxy_info={},
        )
        assert b'request:POST / HTTP/1.1\r\n' in array
        assert b'request:Host: example.com\r\n' in array
        assert b'<< Request body is not a string-like type >>\r\n' in array

    def test_dump_request_data_with_proxy_info(self):
        """Build up the request data into a bytearray."""
        self.configure_request(
            url='http://example.com/',
            method='GET',
        )

        array = bytearray()
        prefixes = dump.PrefixSettings('request:', 'response:')
        dump._dump_request_data(
            request=self.request,
            prefixes=prefixes,
            bytearr=array,
            proxy_info={
                'request_path': b'fake-request-path',
                'method': b'CONNECT',
            },
        )

        assert b'request:CONNECT fake-request-path HTTP/1.1\r\n' in array
        assert b'request:Host: example.com\r\n' in array

    def test_dump_response_data(self):
        """Build up the response data into a bytearray."""
        self.configure_response(
            url='https://example.com/redirected',
            content=b'foobarbogus',
            reason=b'OK',
        )
        self.configure_httpresponse(
            headers={'Content-Type': 'application/json'},
            reason=b'OK',
            status=201,
        )

        array = bytearray()
        prefixes = dump.PrefixSettings('request:', 'response:')
        dump._dump_response_data(
            response=self.response,
            prefixes=prefixes,
            bytearr=array,
        )

        assert b'response:HTTP/1.1 201 OK\r\n' in array
        assert b'response:Content-Type: application/json\r\n' in array

    def test_dump_response_data_with_older_http_version(self):
        """Build up the response data into a bytearray."""
        self.configure_response(
            url='https://example.com/redirected',
            content=b'foobarbogus',
            reason=b'OK',
        )
        self.configure_httpresponse(
            headers={'Content-Type': 'application/json'},
            reason=b'OK',
            status=201,
            version=HTTP_0_9,
        )

        array = bytearray()
        prefixes = dump.PrefixSettings('request:', 'response:')
        dump._dump_response_data(
            response=self.response,
            prefixes=prefixes,
            bytearr=array,
        )

        assert b'response:HTTP/0.9 201 OK\r\n' in array
        assert b'response:Content-Type: application/json\r\n' in array

    def test_dump_response_data_with_unknown_http_version(self):
        """Build up the response data into a bytearray."""
        self.configure_response(
            url='https://example.com/redirected',
            content=b'foobarbogus',
            reason=b'OK',
        )
        self.configure_httpresponse(
            headers={'Content-Type': 'application/json'},
            reason=b'OK',
            status=201,
            version=HTTP_UNKNOWN,
        )

        array = bytearray()
        prefixes = dump.PrefixSettings('request:', 'response:')
        dump._dump_response_data(
            response=self.response,
            prefixes=prefixes,
            bytearr=array,
        )

        assert b'response:HTTP/? 201 OK\r\n' in array
        assert b'response:Content-Type: application/json\r\n' in array


class TestResponsePublicFunctions(RequestResponseMixin):

    """Excercise public functions using responses."""

    def test_dump_response_fails_without_request(self):
        """Show that a response without a request raises a ValueError."""
        del self.response.request
        assert hasattr(self.response, 'request') is False

        with pytest.raises(ValueError):
            dump.dump_response(self.response)

    def test_dump_response_uses_provided_bytearray(self):
        """Show that users providing bytearrays receive those back."""
        self.configure_request(
            url='http://example.com/',
            method='GET',
        )
        self.configure_response(
            url='https://example.com/redirected',
            content=b'foobarbogus',
            reason=b'OK',
        )
        self.configure_httpresponse(
            headers={'Content-Type': 'application/json'},
            reason=b'OK',
            status=201,
        )
        arr = bytearray()

        retarr = dump.dump_response(self.response, data_array=arr)
        assert retarr is arr


class TestDumpRealResponses(object):

    """Exercise dump utilities against real data."""

    def test_dump_response(self):
        session = requests.Session()
        recorder = get_betamax(session)
        with recorder.use_cassette('simple_get_request'):
            response = session.get('https://httpbin.org/get')

        arr = dump.dump_response(response)
        assert b'< GET /get HTTP/1.1\r\n' in arr
        assert b'< Host: httpbin.org\r\n' in arr
        # NOTE(sigmavirus24): The ? below is only because Betamax doesn't
        # preserve which HTTP version the server reports as supporting.
        # When not using Betamax, there should be a different version
        # reported.
        assert b'> HTTP/? 200 OK\r\n' in arr
        assert b'> Content-Type: application/json\r\n' in arr

    def test_dump_all(self):
        session = requests.Session()
        recorder = get_betamax(session)
        with recorder.use_cassette('redirect_request_for_dump_all'):
            response = session.get('https://httpbin.org/redirect/5')

        arr = dump.dump_all(response)
        assert b'< GET /redirect/5 HTTP/1.1\r\n' in arr
        assert b'> Location: /relative-redirect/4\r\n' in arr
        assert b'< GET /relative-redirect/4 HTTP/1.1\r\n' in arr
        assert b'> Location: /relative-redirect/3\r\n' in arr
        assert b'< GET /relative-redirect/3 HTTP/1.1\r\n' in arr
        assert b'> Location: /relative-redirect/2\r\n' in arr
        assert b'< GET /relative-redirect/2 HTTP/1.1\r\n' in arr
        assert b'> Location: /relative-redirect/1\r\n' in arr
        assert b'< GET /relative-redirect/1 HTTP/1.1\r\n' in arr
        assert b'> Location: /get\r\n' in arr
        assert b'< GET /get HTTP/1.1\r\n' in arr