File: test_handlers.py

package info (click to toggle)
python-gabbi 3.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 932 kB
  • sloc: python: 3,711; makefile: 60; sh: 32
file content (483 lines) | stat: -rw-r--r-- 18,354 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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Test response handlers.
"""

import json
import os
import unittest

from gabbi import case
from gabbi.exception import GabbiFormatError
from gabbi.handlers import core
from gabbi.handlers import jsonhandler
from gabbi.handlers import yaml_disk_loading_jsonhandler
from gabbi import suitemaker


class HandlersTest(unittest.TestCase):
    """Test the response handlers.

    Note that this does not test the magic template variables, that
    should be tested somewhere else.
    """

    def setUp(self):
        super(HandlersTest, self).setUp()
        self.test_class = case.HTTPTestCase
        self.test = suitemaker.TestBuilder('mytest', (self.test_class,),
                                           {'test_data': {},
                                            'content_handlers': []})

    def test_empty_response_handler(self):
        self.test.test_data = {'url': '$RESPONSE["barnabas"]'}
        self.test.response = {'content-type': 'unmatchable'}
        self.test.response_data = ''
        self.test.prior = self.test

        url = self.test('test_request').replace_template(
            self.test.test_data['url'])
        self.assertEqual('barnabas', url)

        self.test.response_data = None
        self.test.content_handlers = [jsonhandler.JSONHandler()]
        url = self.test('test_request').replace_template(
            self.test.test_data['url'])
        self.assertEqual('barnabas', url)

    def test_response_strings(self):
        handler = core.StringResponseHandler()
        self.test.content_type = "text/plain"
        self.test.response_data = None
        self.test.test_data = {'response_strings': ['alpha', 'beta']}
        self.test.output = 'alpha\nbeta\n'
        self._assert_handler(handler)

    def test_response_strings_fail(self):
        handler = core.StringResponseHandler()
        self.test.content_type = "text/plain"
        self.test.response_data = None
        self.test.test_data = {'response_strings': ['alpha', 'beta']}
        self.test.output = 'alpha\nbta\n'
        with self.assertRaises(AssertionError):
            self._assert_handler(handler)

    def test_response_strings_fail_big_output(self):
        handler = core.StringResponseHandler()
        self.test.content_type = "text/plain"
        self.test.response_data = None
        self.test.test_data = {'response_strings': ['alpha', 'beta']}
        self.test.output = 'alpha\nbta\n' * 1000
        with self.assertRaises(AssertionError) as cm:
            self._assert_handler(handler)

        msg = str(cm.exception)
        self.assertEqual(2036, len(msg))

    def test_response_strings_fail_big_payload(self):
        string_handler = core.StringResponseHandler()
        # Register the JSON handler so response_data is set.
        json_handler = jsonhandler.JSONHandler()
        self.test.response_handlers = [string_handler, json_handler]
        self.test.content_handlers = [json_handler]
        self.test.content_type = "application/json"
        self.test.test_data = {'response_strings': ['foobar']}
        self.test.response_data = {
            'objects': [{'name': 'cw',
                         'location': 'barn'},
                        {'name': 'chris',
                         'location': 'house'}] * 100
        }
        self.test.output = json.dumps(self.test.response_data)
        with self.assertRaises(AssertionError) as cm:
            self._assert_handler(string_handler)

        msg = str(cm.exception)
        self.assertEqual(2038, len(msg))
        # Check the pprint of the json
        self.assertIn('      "location": "house"', msg)

    def test_response_string_list_type(self):
        handler = core.StringResponseHandler()
        self.test.test_data = {
            'name': 'omega test',
            'response_strings': 'omega'
        }
        self.test.output = 'omega\n'
        with self.assertRaises(GabbiFormatError) as exc:
            self._assert_handler(handler)
            self.assertIn('has incorrect type', str(exc))
            self.assertIn("response_strings in 'omega test'",
                          str(exc))

    def test_response_json_paths(self):
        handler = jsonhandler.JSONHandler()
        self.test.content_type = "application/json"
        self.test.test_data = {'response_json_paths': {
            '$.objects[0].name': 'cow',
            '$.objects[1].location': 'house',
        }}
        self.test.response_data = {
            'objects': [{'name': 'cow',
                         'location': 'barn'},
                        {'name': 'chris',
                         'location': 'house'}]
        }
        self._assert_handler(handler)

    def test_response_json_paths_fail_data(self):
        handler = jsonhandler.JSONHandler()
        self.test.content_type = "application/json"
        self.test.test_data = {'response_json_paths': {
            '$.objects[0].name': 'cow',
            '$.objects[1].location': 'house',
        }}
        self.test.response_data = {
            'objects': [{'name': 'cw',
                         'location': 'barn'},
                        {'name': 'chris',
                         'location': 'house'}]
        }
        with self.assertRaises(AssertionError):
            self._assert_handler(handler)

    def test_response_json_paths_fail_path(self):
        handler = jsonhandler.JSONHandler()
        self.test.content_type = "application/json"
        self.test.test_data = {'response_json_paths': {
            '$.objects[1].name': 'cow',
        }}
        self.test.response_data = {
            'objects': [{'name': 'cow',
                         'location': 'barn'},
                        {'name': 'chris',
                         'location': 'house'}]
        }
        with self.assertRaises(AssertionError):
            self._assert_handler(handler)

    def test_response_json_paths_regex(self):
        handler = jsonhandler.JSONHandler()
        self.test.content_type = "application/json"
        self.test.test_data = {'response_json_paths': {
            '$.objects[0].name': '/ow/',
        }}
        self.test.response_data = {
            'objects': [{'name': u'cow\U0001F404',
                         'location': 'barn'},
                        {'name': 'chris',
                         'location': 'house'}]
        }
        self._assert_handler(handler)

    def test_response_json_paths_regex_path_match(self):
        handler = jsonhandler.JSONHandler()
        self.test.content_type = "application/json"
        self.test.test_data = {'response_json_paths': {
            '$.pathtest': '//bar//',
        }}
        self.test.response_data = {
            'pathtest': '/foo/bar/baz'
        }
        self._assert_handler(handler)

    def test_response_json_paths_regex_path_nomatch(self):
        handler = jsonhandler.JSONHandler()
        self.test.content_type = "application/json"
        self.test.test_data = {'response_json_paths': {
            '$.pathtest': '//bar//',
        }}
        self.test.response_data = {
            'pathtest': '/foo/foobar/baz'
        }
        with self.assertRaises(AssertionError):
            self._assert_handler(handler)

    def test_response_json_paths_substitution_regex(self):
        handler = jsonhandler.JSONHandler()
        self.test.location = '/foo/bar'
        self.test.prior = self.test
        self.test.content_type = "application/json"
        self.test.test_data = {'response_json_paths': {
            '$.pathtest': '/$LOCATION/',
        }}
        self.test.response_data = {
            'pathtest': '/foo/bar/baz'
        }
        self._assert_handler(handler)

    def test_response_json_paths_substitution_noregex(self):
        handler = jsonhandler.JSONHandler()
        self.test.location = '/foo/bar/'
        self.test.prior = self.test
        self.test.content_type = "application/json"
        self.test.test_data = {'response_json_paths': {
            '$.pathtest': '$LOCATION',
        }}
        self.test.response_data = {
            'pathtest': '/foo/bar/baz'
        }
        with self.assertRaises(AssertionError):
            self._assert_handler(handler)

    def test_response_json_paths_substitution_esc_regex(self):
        handler = jsonhandler.JSONHandler()
        self.test.location = '/foo/bar?query'
        self.test.prior = self.test
        self.test.content_type = "application/json"
        self.test.test_data = {'response_json_paths': {
            '$.pathtest': '/$LOCATION/',
        }}
        self.test.response_data = {
            'pathtest': '/foo/bar?query=value'
        }
        self._assert_handler(handler)

    def test_response_json_paths_regex_number(self):
        handler = jsonhandler.JSONHandler()
        self.test.content_type = "application/json"
        self.test.test_data = {'response_json_paths': {
            '$.objects[0].name': r'/\d+/',
        }}
        self.test.response_data = {
            'objects': [{'name': 99,
                         'location': 'barn'},
                        {'name': 'chris',
                         'location': 'house'}]
        }
        self._assert_handler(handler)

    def test_response_json_paths_dict_type(self):
        handler = jsonhandler.JSONHandler()
        self.test.test_data = {
            'name': 'omega test',
            'response_json_paths': ['alpha', 'beta']
        }
        self.test.output = 'omega\n'
        with self.assertRaises(GabbiFormatError) as exc:
            self._assert_handler(handler)
            self.assertIn('has incorrect type', str(exc))
            self.assertIn("response_json_paths in 'omega test'",
                          str(exc))

    def test_response_json_paths_from_disk_json_path(self):
        handler = jsonhandler.JSONHandler()
        lhs = '$.pets[?type = "cat"].sound'
        rhs = '$.values[0].pets[?type = "cat"].sound'
        self.test.test_directory = os.path.dirname(__file__)
        self.test.test_data = {'response_json_paths': {
            lhs: '<@gabbits_handlers/values.json:' + rhs,
        }}
        self.test.response_data = {
            "pets": [
                {"type": "cat", "sound": "meow"},
                {"type": "dog", "sound": "woof"}
            ]
        }
        self._assert_handler(handler)

    def test_response_json_paths_from_disk_json_path_fail(self):
        handler = jsonhandler.JSONHandler()
        lhs = '$.pets[?type = "cat"].sound'
        rhs = '$.values[0].pets[?type = "bad"].sound'
        self.test.test_directory = os.path.dirname(__file__)
        self.test.test_data = {'response_json_paths': {
            lhs: '<@gabbits_handlers/values.json:' + rhs,
        }}
        self.test.response_data = {
            "pets": [
                {"type": "cat", "sound": "meow"},
                {"type": "dog", "sound": "woof"}
            ]
        }
        with self.assertRaises(AssertionError):
            self._assert_handler(handler)

    def test_response_json_paths_yamlhandler(self):
        handler = yaml_disk_loading_jsonhandler.YAMLDiskLoadingJSONHandler()
        lhs = '$.pets[?type = "cat"].sound'
        rhs = '$.values[0].pets[?type = "cat"].sound'
        self.test.test_directory = os.path.dirname(__file__)
        self.test.test_data = {'response_json_paths': {
            lhs: '<@gabbits_handlers/subdir/values.yaml:' + rhs,
        }}
        self.test.response_data = {
            "pets": [
                {"type": "cat", "sound": "meow"},
                {"type": "dog", "sound": "woof"}
            ]
        }
        self._assert_handler(handler)

    def test_response_headers(self):
        handler = core.HeadersResponseHandler()
        self.test.response = {'content-type': 'text/plain'}

        self.test.test_data = {'response_headers': {
            'content-type': 'text/plain',
        }}
        self._assert_handler(handler)

        self.test.test_data = {'response_headers': {
            'Content-Type': 'text/plain',
        }}
        self._assert_handler(handler)

    def test_response_headers_regex(self):
        handler = core.HeadersResponseHandler()
        self.test.test_data = {'response_headers': {
            'content-type': '/text/plain/',
        }}
        self.test.response = {'content-type': 'text/plain; charset=UTF-8'}
        self._assert_handler(handler)

    def test_response_headers_substitute_noregex(self):
        handler = core.HeadersResponseHandler()
        self.test.location = '/foo/bar/'
        self.test.prior = self.test
        self.test.test_data = {'response_headers': {
            'location': '$LOCATION',
        }}
        self.test.response = {'location': '/foo/bar/baz'}
        with self.assertRaises(AssertionError):
            self._assert_handler(handler)

    def test_response_headers_substitute_regex(self):
        handler = core.HeadersResponseHandler()
        self.test.location = '/foo/bar/'
        self.test.prior = self.test
        self.test.test_data = {'response_headers': {
            'location': '/^$LOCATION/',
        }}
        self.test.response = {'location': '/foo/bar/baz'}
        self._assert_handler(handler)

    def test_response_headers_substitute_esc_regex(self):
        handler = core.HeadersResponseHandler()
        self.test.scheme = 'git+ssh'
        self.test.test_data = {'response_headers': {
            'location': '/^$SCHEME://.*/',
        }}
        self.test.response = {'location': 'git+ssh://example.test'}
        self._assert_handler(handler)

    def test_response_headers_noregex_path_match(self):
        handler = core.HeadersResponseHandler()
        self.test.test_data = {'response_headers': {
            'location': '/',
        }}
        self.test.response = {'location': '/'}
        self._assert_handler(handler)

    def test_response_headers_noregex_path_nomatch(self):
        handler = core.HeadersResponseHandler()
        self.test.test_data = {'response_headers': {
            'location': '/',
        }}
        self.test.response = {'location': '/foo'}
        with self.assertRaises(AssertionError):
            self._assert_handler(handler)

    def test_response_headers_regex_path_match(self):
        handler = core.HeadersResponseHandler()
        self.test.test_data = {'response_headers': {
            'location': '//bar//',
        }}
        self.test.response = {'location': '/foo/bar/baz'}
        self._assert_handler(handler)

    def test_response_headers_regex_path_nomatch(self):
        handler = core.HeadersResponseHandler()
        self.test.test_data = {'response_headers': {
            'location': '//bar//',
        }}
        self.test.response = {'location': '/foo/foobar/baz'}
        with self.assertRaises(AssertionError):
            self._assert_handler(handler)

    def test_response_headers_fail_data(self):
        handler = core.HeadersResponseHandler()
        self.test.test_data = {'response_headers': {
            'content-type': 'text/plain',
        }}
        self.test.response = {'content-type': 'application/json'}
        with self.assertRaises(AssertionError) as failure:
            self._assert_handler(handler)
        self.assertIn("Expect header content-type with value text/plain,"
                      " got application/json",
                      str(failure.exception))

    def test_response_headers_fail_header(self):
        handler = core.HeadersResponseHandler()
        self.test.test_data = {'response_headers': {
            'location': '/somewhere',
        }}
        self.test.response = {'content-type': 'application/json'}
        with self.assertRaises(AssertionError) as failure:
            self._assert_handler(handler)
        self.assertIn("'location' header not present in response:",
                      str(failure.exception))

    def test_resonse_headers_stringify(self):
        handler = core.HeadersResponseHandler()
        self.test.test_data = {'response_headers': {
            'x-alpha-beta': 2.0,
        }}
        self.test.response = {'x-alpha-beta': '2.0'}
        self._assert_handler(handler)

        self.test.response = {'x-alpha-beta': 2.0}
        self._assert_handler(handler)

    def _assert_handler(self, handler):
        # Instantiate our contained test class by naming its test
        # method and then run its tests to confirm.
        test = self.test('test_request')
        handler(test)


class TestJSONHandlerAccept(unittest.TestCase):
    """Test that the json handler accepts function.

    We need to confirm that it returns True and False at the right
    times. This is somewhat tricky as there are a fair number of
    MIME-types that include the string "JSON" but aren't, as a
    whole document, capable of being decoded.
    """

    def _test_content_type(self, content_type, expected):
        if expected:
            self.assertTrue(
                jsonhandler.JSONHandler.accepts(content_type),
                "expected %s to be accepted but it was not!" % content_type)
        else:
            self.assertFalse(
                jsonhandler.JSONHandler.accepts(content_type),
                "expected %s to not be accepted but it was!" % content_type)

    def test_many_content_types(self):
        cases = [
            ("application/json", True),
            ("application/JSON", True),
            ("text/plain", False),
            ("application/jsonlines", False),
            ("application/json;stream=true", False),
            ("application/json;streamable=pony", True),
            ("application/stream+json", True),
            ("application/xml", False),
            ("application/json-seq", False),
            ("application/json-home", False),
        ]
        for test in cases:
            with self.subTest(test[0]):
                self._test_content_type(*test)