forked from flask-restful/flask-restful
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_reqparse.py
846 lines (648 loc) · 29.1 KB
/
test_reqparse.py
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
# -*- coding: utf-8 -*-
import unittest
from mock import Mock, patch
from flask import Flask
from werkzeug import exceptions, MultiDict
from werkzeug.wrappers import Request
from werkzeug.datastructures import FileStorage
from flask_restful.reqparse import Argument, RequestParser, Namespace
import six
import decimal
import json
class ReqParseTestCase(unittest.TestCase):
def test_default_help(self):
arg = Argument("foo")
self.assertEquals(arg.help, None)
@patch('flask_restful.abort')
def test_help(self, abort):
app = Flask(__name__)
with app.app_context():
parser = RequestParser()
parser.add_argument('foo', choices=['one', 'two'], help='Bad choice')
req = Mock(['values'])
req.values = MultiDict([('foo', 'three')])
parser.parse_args(req)
expected = {'foo': '(Bad choice) three is not a valid choice'}
abort.assert_called_with(400, message=expected)
@patch('flask_restful.abort', side_effect=exceptions.BadRequest('Bad Request'))
def test_no_help(self, abort):
def bad_choice():
parser = RequestParser()
parser.add_argument('foo', choices=['one', 'two'])
req = Mock(['values'])
req.values = MultiDict([('foo', 'three')])
parser.parse_args(req)
abort.assert_called_with(400, message='three is not a valid choice')
app = Flask(__name__)
with app.app_context():
self.assertRaises(exceptions.BadRequest, bad_choice)
def test_name(self):
arg = Argument("foo")
self.assertEquals(arg.name, "foo")
def test_dest(self):
arg = Argument("foo", dest="foobar")
self.assertEquals(arg.dest, "foobar")
def test_location_url(self):
arg = Argument("foo", location="url")
self.assertEquals(arg.location, "url")
def test_location_url_list(self):
arg = Argument("foo", location=["url"])
self.assertEquals(arg.location, ["url"])
def test_location_header(self):
arg = Argument("foo", location="headers")
self.assertEquals(arg.location, "headers")
def test_location_json(self):
arg = Argument("foo", location="json")
self.assertEquals(arg.location, "json")
def test_location_get_json(self):
arg = Argument("foo", location="get_json")
self.assertEquals(arg.location, "get_json")
def test_location_header_list(self):
arg = Argument("foo", location=["headers"])
self.assertEquals(arg.location, ["headers"])
def test_type(self):
arg = Argument("foo", type=int)
self.assertEquals(arg.type, int)
def test_default(self):
arg = Argument("foo", default=True)
self.assertEquals(arg.default, True)
def test_required(self):
arg = Argument("foo", required=True)
self.assertEquals(arg.required, True)
def test_ignore(self):
arg = Argument("foo", ignore=True)
self.assertEquals(arg.ignore, True)
def test_operator(self):
arg = Argument("foo", operators=[">=", "<=", "="])
self.assertEquals(arg.operators, [">=", "<=", "="])
def test_action_filter(self):
arg = Argument("foo", action="filter")
self.assertEquals(arg.action, u"filter")
def test_action(self):
arg = Argument("foo", action="append")
self.assertEquals(arg.action, u"append")
def test_choices(self):
arg = Argument("foo", choices=[1, 2])
self.assertEquals(arg.choices, [1, 2])
def test_default_dest(self):
arg = Argument("foo")
self.assertEquals(arg.dest, None)
def test_default_operators(self):
arg = Argument("foo")
self.assertEquals(arg.operators[0], "=")
self.assertEquals(len(arg.operators), 1)
@patch('flask_restful.reqparse.six')
def test_default_type(self, mock_six):
arg = Argument("foo")
sentinel = object()
arg.type(sentinel)
mock_six.text_type.assert_called_with(sentinel)
def test_default_default(self):
arg = Argument("foo")
self.assertEquals(arg.default, None)
def test_required_default(self):
arg = Argument("foo")
self.assertEquals(arg.required, False)
def test_ignore_default(self):
arg = Argument("foo")
self.assertEquals(arg.ignore, False)
def test_action_default(self):
arg = Argument("foo")
self.assertEquals(arg.action, u"store")
def test_choices_default(self):
arg = Argument("foo")
self.assertEquals(len(arg.choices), 0)
def test_source(self):
req = Mock(['args', 'headers', 'values'])
req.args = {'foo': 'bar'}
req.headers = {'baz': 'bat'}
arg = Argument('foo', location=['args'])
self.assertEquals(arg.source(req), MultiDict(req.args))
arg = Argument('foo', location=['headers'])
self.assertEquals(arg.source(req), MultiDict(req.headers))
def test_convert_default_type_with_null_input(self):
"""convert() should properly handle case where input is None"""
arg = Argument('foo')
self.assertEquals(arg.convert(None, None), None)
def test_source_bad_location(self):
req = Mock(['values'])
arg = Argument('foo', location=['foo'])
self.assertTrue(len(arg.source(req)) == 0) # yes, basically you don't find it
def test_source_default_location(self):
req = Mock(['values'])
req._get_child_mock = lambda **kwargs: MultiDict()
arg = Argument('foo')
self.assertEquals(arg.source(req), req.values)
def test_option_case_sensitive(self):
arg = Argument("foo", choices=["bar", "baz"], case_sensitive=True)
self.assertEquals(True, arg.case_sensitive)
# Insensitive
arg = Argument("foo", choices=["bar", "baz"], case_sensitive=False)
self.assertEquals(False, arg.case_sensitive)
# Default
arg = Argument("foo", choices=["bar", "baz"])
self.assertEquals(True, arg.case_sensitive)
def test_viewargs(self):
req = Request.from_values()
req.view_args = {"foo": "bar"}
parser = RequestParser()
parser.add_argument("foo", location=["view_args"])
args = parser.parse_args(req)
self.assertEquals(args['foo'], "bar")
req = Mock()
req.values = ()
req.json = None
req.view_args = {"foo": "bar"}
parser = RequestParser()
parser.add_argument("foo", store_missing=True)
args = parser.parse_args(req)
self.assertEquals(args["foo"], None)
def test_parse_unicode(self):
req = Request.from_values("/bubble?foo=barß")
parser = RequestParser()
parser.add_argument("foo")
args = parser.parse_args(req)
self.assertEquals(args['foo'], u"barß")
def test_parse_unicode_app(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument("foo")
with app.test_request_context('/bubble?foo=barß'):
args = parser.parse_args()
self.assertEquals(args['foo'], u"barß")
def test_json_location(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument("foo", location="json", store_missing=True)
with app.test_request_context('/bubble', method="post"):
args = parser.parse_args()
self.assertEquals(args['foo'], None)
def test_get_json_location(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument("foo", location="json")
with app.test_request_context('/bubble', method="post",
data=json.dumps({"foo": "bar"}),
content_type='application/json'):
args = parser.parse_args()
self.assertEquals(args['foo'], 'bar')
def test_parse_append_ignore(self):
req = Request.from_values("/bubble?foo=bar")
parser = RequestParser()
parser.add_argument("foo", ignore=True, type=int, action="append",
store_missing=True),
args = parser.parse_args(req)
self.assertEquals(args['foo'], None)
def test_parse_append_default(self):
req = Request.from_values("/bubble?")
parser = RequestParser()
parser.add_argument("foo", action="append", store_missing=True),
args = parser.parse_args(req)
self.assertEquals(args['foo'], None)
def test_parse_append(self):
req = Request.from_values("/bubble?foo=bar&foo=bat")
parser = RequestParser()
parser.add_argument("foo", action="append"),
args = parser.parse_args(req)
self.assertEquals(args['foo'], ["bar", "bat"])
def test_parse_append_single(self):
req = Request.from_values("/bubble?foo=bar")
parser = RequestParser()
parser.add_argument("foo", action="append"),
args = parser.parse_args(req)
self.assertEquals(args['foo'], ["bar"])
def test_parse_dest(self):
req = Request.from_values("/bubble?foo=bar")
parser = RequestParser()
parser.add_argument("foo", dest="bat")
args = parser.parse_args(req)
self.assertEquals(args['bat'], "bar")
def test_parse_gte_lte_eq(self):
req = Request.from_values("/bubble?foo>=bar&foo<=bat&foo=foo")
parser = RequestParser()
parser.add_argument("foo", operators=[">=", "<=", "="], action="append"),
args = parser.parse_args(req)
self.assertEquals(args['foo'], ["bar", "bat", "foo"])
def test_parse_gte(self):
req = Request.from_values("/bubble?foo>=bar")
parser = RequestParser()
parser.add_argument("foo", operators=[">="])
args = parser.parse_args(req)
self.assertEquals(args['foo'], "bar")
def test_parse_foo_operators_four_hunderd(self):
app = Flask(__name__)
with app.app_context():
parser = RequestParser()
parser.add_argument("foo", type=int),
self.assertRaises(exceptions.BadRequest, lambda: parser.parse_args(Request.from_values("/bubble?foo=bar")))
def test_parse_foo_operators_ignore(self):
parser = RequestParser()
parser.add_argument("foo", ignore=True, store_missing=True)
args = parser.parse_args(Request.from_values("/bubble"))
self.assertEquals(args['foo'], None)
def test_parse_lte_gte_mock(self):
mock_type = Mock()
req = Request.from_values("/bubble?foo<=bar")
parser = RequestParser()
parser.add_argument("foo", type=mock_type, operators=["<="])
parser.parse_args(req)
mock_type.assert_called_with("bar", "foo", "<=")
def test_parse_lte_gte_append(self):
parser = RequestParser()
parser.add_argument("foo", operators=["<=", "="], action="append")
args = parser.parse_args(Request.from_values("/bubble?foo<=bar"))
self.assertEquals(args['foo'], ["bar"])
def test_parse_lte_gte_missing(self):
parser = RequestParser()
parser.add_argument("foo", operators=["<=", "="])
args = parser.parse_args(Request.from_values("/bubble?foo<=bar"))
self.assertEquals(args['foo'], "bar")
def test_parse_eq_other(self):
parser = RequestParser()
parser.add_argument("foo"),
args = parser.parse_args(Request.from_values("/bubble?foo=bar&foo=bat"))
self.assertEquals(args['foo'], "bar")
def test_parse_eq(self):
req = Request.from_values("/bubble?foo=bar")
parser = RequestParser()
parser.add_argument("foo"),
args = parser.parse_args(req)
self.assertEquals(args['foo'], "bar")
def test_parse_lte(self):
req = Request.from_values("/bubble?foo<=bar")
parser = RequestParser()
parser.add_argument("foo", operators=["<="])
args = parser.parse_args(req)
self.assertEquals(args['foo'], "bar")
def test_parse_required(self):
app = Flask(__name__)
with app.app_context():
req = Request.from_values("/bubble")
parser = RequestParser()
parser.add_argument("foo", required=True, location='values')
message = ''
try:
parser.parse_args(req)
except exceptions.BadRequest as e:
message = e.data['message']
self.assertEquals(message, ({'foo': 'Missing required parameter in '
'the post body or the query '
'string'}))
parser = RequestParser()
parser.add_argument("bar", required=True, location=['values', 'cookies'])
try:
parser.parse_args(req)
except exceptions.BadRequest as e:
message = e.data['message']
self.assertEquals(message, ({'bar': 'Missing required parameter in '
'the post body or the query '
'string or the request\'s '
'cookies'}))
def test_parse_error_bundling(self):
app = Flask(__name__)
app.config['BUNDLE_ERRORS']=True
with app.app_context():
req = Request.from_values("/bubble")
parser = RequestParser()
parser.add_argument("foo", required=True, location='values')
parser.add_argument("bar", required=True, location=['values', 'cookies'])
message = ''
try:
parser.parse_args(req)
except exceptions.BadRequest as e:
message = e.data['message']
error_message = {'foo': 'Missing required parameter in the post '
'body or the query string',
'bar': 'Missing required parameter in the post '
'body or the query string or the '
'request\'s cookies'}
self.assertEquals(message, error_message)
def test_parse_error_bundling_w_parser_arg(self):
app = Flask(__name__)
app.config['BUNDLE_ERRORS']=False
with app.app_context():
req = Request.from_values("/bubble")
parser = RequestParser(bundle_errors=True)
parser.add_argument("foo", required=True, location='values')
parser.add_argument("bar", required=True, location=['values', 'cookies'])
message = ''
try:
parser.parse_args(req)
except exceptions.BadRequest as e:
message = e.data['message']
error_message = {'foo': 'Missing required parameter in the post '
'body or the query string',
'bar': 'Missing required parameter in the post '
'body or the query string or the request\'s '
'cookies'}
self.assertEquals(message, error_message)
def test_parse_default_append(self):
req = Request.from_values("/bubble")
parser = RequestParser()
parser.add_argument("foo", default="bar", action="append",
store_missing=True)
args = parser.parse_args(req)
self.assertEquals(args['foo'], "bar")
def test_parse_default(self):
req = Request.from_values("/bubble")
parser = RequestParser()
parser.add_argument("foo", default="bar", store_missing=True)
args = parser.parse_args(req)
self.assertEquals(args['foo'], "bar")
def test_parse_callable_default(self):
req = Request.from_values("/bubble")
parser = RequestParser()
parser.add_argument("foo", default=lambda: "bar", store_missing=True)
args = parser.parse_args(req)
self.assertEquals(args['foo'], "bar")
def test_parse(self):
req = Request.from_values("/bubble?foo=bar")
parser = RequestParser()
parser.add_argument("foo"),
args = parser.parse_args(req)
self.assertEquals(args['foo'], "bar")
def test_parse_none(self):
req = Request.from_values("/bubble")
parser = RequestParser()
parser.add_argument("foo")
args = parser.parse_args(req)
self.assertEquals(args['foo'], None)
def test_parse_store_missing(self):
req = Request.from_values("/bubble")
parser = RequestParser()
parser.add_argument("foo", store_missing=False)
args = parser.parse_args(req)
self.assertFalse('foo' in args)
def test_parse_choices_correct(self):
req = Request.from_values("/bubble?foo=bat")
parser = RequestParser()
parser.add_argument("foo", choices=["bat"]),
args = parser.parse_args(req)
self.assertEquals(args['foo'], "bat")
def test_parse_choices(self):
app = Flask(__name__)
with app.app_context():
req = Request.from_values("/bubble?foo=bar")
parser = RequestParser()
parser.add_argument("foo", choices=["bat"]),
self.assertRaises(exceptions.BadRequest, lambda: parser.parse_args(req))
def test_parse_choices_sensitive(self):
app = Flask(__name__)
with app.app_context():
req = Request.from_values("/bubble?foo=BAT")
parser = RequestParser()
parser.add_argument("foo", choices=["bat"], case_sensitive=True),
self.assertRaises(exceptions.BadRequest, lambda: parser.parse_args(req))
def test_parse_choices_insensitive(self):
req = Request.from_values("/bubble?foo=BAT")
parser = RequestParser()
parser.add_argument("foo", choices=["bat"], case_sensitive=False),
args = parser.parse_args(req)
self.assertEquals('bat', args.get('foo'))
# both choices and args are case_insensitive
req = Request.from_values("/bubble?foo=bat")
parser = RequestParser()
parser.add_argument("foo", choices=["BAT"], case_sensitive=False),
args = parser.parse_args(req)
self.assertEquals('bat', args.get('foo'))
def test_parse_ignore(self):
req = Request.from_values("/bubble?foo=bar")
parser = RequestParser()
parser.add_argument("foo", type=int, ignore=True, store_missing=True),
args = parser.parse_args(req)
self.assertEquals(args['foo'], None)
def test_chaining(self):
parser = RequestParser()
self.assertTrue(parser is parser.add_argument("foo"))
def test_namespace_existence(self):
namespace = Namespace()
namespace.foo = 'bar'
namespace['bar'] = 'baz'
self.assertEquals(namespace['foo'], 'bar')
self.assertEquals(namespace.bar, 'baz')
def test_namespace_missing(self):
namespace = Namespace()
self.assertRaises(AttributeError, lambda: namespace.spam)
self.assertRaises(KeyError, lambda: namespace['eggs'])
def test_namespace_configurability(self):
req = Request.from_values()
self.assertTrue(isinstance(RequestParser().parse_args(req), Namespace))
self.assertTrue(type(RequestParser(namespace_class=dict).parse_args(req)) is dict)
def test_none_argument(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument("foo", location="json")
with app.test_request_context('/bubble', method="post",
data=json.dumps({"foo": None}),
content_type='application/json'):
args = parser.parse_args()
self.assertEquals(args['foo'], None)
def test_type_callable(self):
req = Request.from_values("/bubble?foo=1")
parser = RequestParser()
parser.add_argument("foo", type=lambda x: x, required=False),
args = parser.parse_args(req)
self.assertEquals(args['foo'], "1")
def test_type_callable_none(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument("foo", type=lambda x: x, location="json", required=False),
with app.test_request_context('/bubble', method="post",
data=json.dumps({"foo": None}),
content_type='application/json'):
try:
args = parser.parse_args()
self.assertEquals(args['foo'], None)
except exceptions.BadRequest:
self.fail()
def test_type_decimal(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument("foo", type=decimal.Decimal, location="json")
with app.test_request_context('/bubble', method='post',
data=json.dumps({"foo": "1.0025"}),
content_type='application/json'):
args = parser.parse_args()
self.assertEquals(args['foo'], decimal.Decimal("1.0025"))
def test_type_filestorage(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument("foo", type=FileStorage, location='files')
fdata = six.b('foo bar baz qux')
with app.test_request_context('/bubble', method='POST',
data={'foo': (six.BytesIO(fdata), 'baz.txt')}):
args = parser.parse_args()
self.assertEquals(args['foo'].name, 'foo')
self.assertEquals(args['foo'].filename, 'baz.txt')
self.assertEquals(args['foo'].read(), fdata)
def test_filestorage_custom_type(self):
def _custom_type(f):
return FileStorage(stream=f.stream,
filename="{0}aaaa".format(f.filename),
name="{0}aaaa".format(f.name))
app = Flask(__name__)
parser = RequestParser()
parser.add_argument("foo", type=_custom_type, location='files')
fdata = six.b('foo bar baz qux')
with app.test_request_context('/bubble', method='POST',
data={'foo': (six.BytesIO(fdata), 'baz.txt')}):
args = parser.parse_args()
self.assertEquals(args['foo'].name, 'fooaaaa')
self.assertEquals(args['foo'].filename, 'baz.txtaaaa')
self.assertEquals(args['foo'].read(), fdata)
def test_passing_arguments_object(self):
req = Request.from_values("/bubble?foo=bar")
parser = RequestParser()
parser.add_argument(Argument("foo"))
args = parser.parse_args(req)
self.assertEquals(args['foo'], u"bar")
def test_int_choice_types(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument("foo", type=int, choices=[1, 2, 3], location='json')
with app.test_request_context(
'/bubble', method='post',
data=json.dumps({'foo': 5}),
content_type='application/json'
):
try:
parser.parse_args()
self.fail()
except exceptions.BadRequest:
pass
def test_int_range_choice_types(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument("foo", type=int, choices=range(100), location='json')
with app.test_request_context(
'/bubble', method='post',
data=json.dumps({'foo': 101}),
content_type='application/json'
):
try:
parser.parse_args()
self.fail()
except exceptions.BadRequest:
pass
def test_request_parser_copy(self):
req = Request.from_values("/bubble?foo=101&bar=baz")
parser = RequestParser()
foo_arg = Argument('foo', type=int)
parser.args.append(foo_arg)
parser_copy = parser.copy()
# Deepcopy should create a clone of the argument object instead of
# copying a reference to the new args list
self.assertFalse(foo_arg in parser_copy.args)
# Args added to new parser should not be added to the original
bar_arg = Argument('bar')
parser_copy.args.append(bar_arg)
self.assertFalse(bar_arg in parser.args)
args = parser_copy.parse_args(req)
self.assertEquals(args['foo'], 101)
self.assertEquals(args['bar'], u'baz')
def test_request_parse_copy_including_settings(self):
parser = RequestParser(trim=True, bundle_errors=True)
parser_copy = parser.copy()
self.assertEqual(parser.trim, parser_copy.trim)
self.assertEqual(parser.bundle_errors, parser_copy.bundle_errors)
def test_request_parser_replace_argument(self):
req = Request.from_values("/bubble?foo=baz")
parser = RequestParser()
parser.add_argument('foo', type=int)
parser_copy = parser.copy()
parser_copy.replace_argument('foo')
args = parser_copy.parse_args(req)
self.assertEquals(args['foo'], u'baz')
def test_both_json_and_values_location(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument('foo', type=int)
parser.add_argument('baz', type=int)
with app.test_request_context('/bubble?foo=1', method="post",
data=json.dumps({"baz": 2}),
content_type='application/json'):
args = parser.parse_args()
self.assertEquals(args['foo'], 1)
self.assertEquals(args['baz'], 2)
def test_not_json_location_and_content_type_json(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument('foo', location='args')
with app.test_request_context('/bubble', method='get',
content_type='application/json'):
parser.parse_args() # Should not raise a 400: BadRequest
def test_request_parser_remove_argument(self):
req = Request.from_values("/bubble?foo=baz")
parser = RequestParser()
parser.add_argument('foo', type=int)
parser_copy = parser.copy()
parser_copy.remove_argument('foo')
args = parser_copy.parse_args(req)
self.assertEquals(args, {})
def test_strict_parsing_off(self):
req = Request.from_values("/bubble?foo=baz")
parser = RequestParser()
args = parser.parse_args(req)
self.assertEquals(args, {})
def test_strict_parsing_on(self):
req = Request.from_values("/bubble?foo=baz")
parser = RequestParser()
self.assertRaises(exceptions.BadRequest, parser.parse_args, req, strict=True)
def test_strict_parsing_off_partial_hit(self):
req = Request.from_values("/bubble?foo=1&bar=bees&n=22")
parser = RequestParser()
parser.add_argument('foo', type=int)
args = parser.parse_args(req)
self.assertEquals(args['foo'], 1)
def test_strict_parsing_on_partial_hit(self):
req = Request.from_values("/bubble?foo=1&bar=bees&n=22")
parser = RequestParser()
parser.add_argument('foo', type=int)
self.assertRaises(exceptions.BadRequest, parser.parse_args, req, strict=True)
def test_trim_argument(self):
req = Request.from_values("/bubble?foo= 1 &bar=bees&n=22")
parser = RequestParser()
parser.add_argument('foo')
args = parser.parse_args(req)
self.assertEquals(args['foo'], ' 1 ')
parser = RequestParser()
parser.add_argument('foo', trim=True)
args = parser.parse_args(req)
self.assertEquals(args['foo'], '1')
parser = RequestParser()
parser.add_argument('foo', trim=True, type=int)
args = parser.parse_args(req)
self.assertEquals(args['foo'], 1)
def test_trim_request_parser(self):
req = Request.from_values("/bubble?foo= 1 &bar=bees&n=22")
parser = RequestParser(trim=False)
parser.add_argument('foo')
args = parser.parse_args(req)
self.assertEquals(args['foo'], ' 1 ')
parser = RequestParser(trim=True)
parser.add_argument('foo')
args = parser.parse_args(req)
self.assertEquals(args['foo'], '1')
parser = RequestParser(trim=True)
parser.add_argument('foo', type=int)
args = parser.parse_args(req)
self.assertEquals(args['foo'], 1)
def test_trim_request_parser_override_by_argument(self):
parser = RequestParser(trim=True)
parser.add_argument('foo', trim=False)
self.assertFalse(parser.args[0].trim)
def test_trim_request_parser_json(self):
app = Flask(__name__)
parser = RequestParser(trim=True)
parser.add_argument("foo", location="json")
parser.add_argument("int1", location="json", type=int)
parser.add_argument("int2", location="json", type=int)
with app.test_request_context('/bubble', method="post",
data=json.dumps({"foo": " bar ", "int1": 1, "int2": " 2 "}),
content_type='application/json'):
args = parser.parse_args()
self.assertEquals(args['foo'], 'bar')
self.assertEquals(args['int1'], 1)
self.assertEquals(args['int2'], 2)
if __name__ == '__main__':
unittest.main()