File: test_request_attrs.py

package info (click to toggle)
python-falcon 4.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,172 kB
  • sloc: python: 33,608; javascript: 92; sh: 50; makefile: 50
file content (1029 lines) | stat: -rw-r--r-- 34,303 bytes parent folder | download
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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
import datetime
import itertools

import pytest

import falcon
from falcon.request import Request
from falcon.request import RequestOptions
from falcon.request_helpers import _parse_etags
import falcon.testing as testing
import falcon.uri
from falcon.util import DeprecatedWarning
from falcon.util.structures import ETag

_HTTP_VERSIONS = ['1.0', '1.1', '2']


def _make_etag(value, is_weak=False):
    """Creates and returns an ETag object.

    Args:
        value (str): Unquated entity tag value
        is_weak (bool): The weakness indicator

    Returns:
        A ``str``-like Etag instance with weakness indicator.

    """
    etag = ETag(value)

    etag.is_weak = is_weak
    return etag


# NOTE(vytas): create_req is very heavily used in this module in unittest-style
#   classes, so we simply recreate the function here.
def create_req(asgi, options=None, **environ_or_scope_kwargs):
    create_method = testing.create_asgi_req if asgi else testing.create_req
    return create_method(options=options, **environ_or_scope_kwargs)


def test_missing_qs():
    env = testing.create_environ()
    if 'QUERY_STRING' in env:
        del env['QUERY_STRING']

    # Should not cause an exception when Request is instantiated
    Request(env)


def test_app_missing():
    env = testing.create_environ()
    del env['SCRIPT_NAME']
    req = Request(env)

    assert req.root_path == ''
    with pytest.warns(DeprecatedWarning):
        assert req.app == ''


class TestRequestAttributes:
    def setup_method(self, method):
        asgi = self._item.callspec.getparam('asgi')

        self.qs = 'marker=deadbeef&limit=10'

        self.headers = {
            'Content-Type': 'text/plain',
            'Content-Length': '4829',
            'Authorization': '',
        }

        self.root_path = '/test'
        self.path = '/hello'
        self.relative_uri = self.path + '?' + self.qs

        self.req = create_req(
            asgi,
            root_path=self.root_path,
            port=8080,
            path='/hello',
            query_string=self.qs,
            headers=self.headers,
        )

        self.req_noqs = create_req(
            asgi, root_path=self.root_path, path='/hello', headers=self.headers
        )

    def test_empty(self, asgi):
        assert self.req.auth is None

    def test_host(self, asgi):
        assert self.req.host == testing.DEFAULT_HOST

    def test_subdomain(self, asgi):
        req = create_req(asgi, host='com', path='/hello', headers=self.headers)
        assert req.subdomain is None

        req = create_req(asgi, host='example.com', path='/hello', headers=self.headers)
        assert req.subdomain == 'example'

        req = create_req(
            asgi, host='highwire.example.com', path='/hello', headers=self.headers
        )
        assert req.subdomain == 'highwire'

        req = create_req(
            asgi,
            host='lb01.dfw01.example.com',
            port=8080,
            path='/hello',
            headers=self.headers,
        )
        assert req.subdomain == 'lb01'

        # NOTE(kgriffs): Behavior for IP addresses is undefined,
        # so just make sure it doesn't blow up.
        req = create_req(asgi, host='127.0.0.1', path='/hello', headers=self.headers)
        assert type(req.subdomain) is str

        # NOTE(kgriffs): Test fallback to SERVER_NAME by using
        # HTTP 1.0, which will cause .create_environ to not set
        # HTTP_HOST.
        req = create_req(
            asgi,
            http_version='1.0',
            host='example.com',
            path='/hello',
            headers=self.headers,
        )
        assert req.subdomain == 'example'

    def test_reconstruct_url(self, asgi):
        req = self.req

        scheme = req.scheme
        host = req.get_header('host')
        app = req.root_path
        with pytest.warns(DeprecatedWarning):
            assert req.app == app
        path = req.path
        query_string = req.query_string

        expected_prefix = ''.join([scheme, '://', host, app])
        expected_uri = ''.join([expected_prefix, path, '?', query_string])

        assert req.uri == expected_uri
        assert req.prefix == expected_prefix
        assert req.prefix == expected_prefix  # Check cached value

    @pytest.mark.parametrize(
        'test_path',
        [
            '/hello_\u043f\u0440\u0438\u0432\u0435\u0442',
            '/test/%E5%BB%B6%E5%AE%89',
            '/test/%C3%A4%C3%B6%C3%BC%C3%9F%E2%82%AC',
        ],
    )
    def test_nonlatin_path(self, asgi, test_path):
        # NOTE(kgriffs): When a request comes in, web servers decode
        # the path.  The decoded path may contain UTF-8 characters,
        # but according to the WSGI spec, no strings can contain chars
        # outside ISO-8859-1. Therefore, to reconcile the URI
        # encoding standard that allows UTF-8 with the WSGI spec
        # that does not, WSGI servers tunnel the string via
        # ISO-8859-1. falcon.testing.create_environ() mimics this
        # behavior, e.g.:
        #
        #   tunnelled_path = path.encode('utf-8').decode('iso-8859-1')
        #
        # falcon.Request does the following to reverse the process:
        #
        #   path = tunnelled_path.encode('iso-8859-1').decode('utf-8', 'replace')
        #

        req = create_req(asgi, host='com', path=test_path, headers=self.headers)

        assert req.path == falcon.uri.decode(test_path)

    def test_uri(self, asgi):
        prefix = 'http://' + testing.DEFAULT_HOST + ':8080' + self.root_path
        uri = prefix + self.relative_uri

        assert self.req.url == uri
        assert self.req.prefix == prefix

        # NOTE(kgriffs): Call twice to check caching works
        assert self.req.uri == uri
        assert self.req.uri == uri

        uri_noqs = 'http://' + testing.DEFAULT_HOST + self.root_path + self.path
        assert self.req_noqs.uri == uri_noqs

    def test_uri_https(self, asgi):
        # =======================================================
        # Default port, implicit
        # =======================================================
        req = create_req(asgi, path='/hello', scheme='https')
        uri = 'https://' + testing.DEFAULT_HOST + '/hello'

        assert req.uri == uri

        # =======================================================
        # Default port, explicit
        # =======================================================
        req = create_req(asgi, path='/hello', scheme='https', port=443)
        uri = 'https://' + testing.DEFAULT_HOST + '/hello'

        assert req.uri == uri

        # =======================================================
        # Non-default port
        # =======================================================
        req = create_req(asgi, path='/hello', scheme='https', port=22)
        uri = 'https://' + testing.DEFAULT_HOST + ':22/hello'

        assert req.uri == uri

    def test_uri_http_1_0(self, asgi):
        # =======================================================
        # HTTP, 80
        # =======================================================
        req = create_req(
            asgi,
            http_version='1.0',
            root_path=self.root_path,
            port=80,
            path='/hello',
            query_string=self.qs,
            headers=self.headers,
        )

        uri = 'http://' + testing.DEFAULT_HOST + self.root_path + self.relative_uri

        assert req.uri == uri

        # =======================================================
        # HTTP, 80
        # =======================================================
        req = create_req(
            asgi,
            http_version='1.0',
            root_path=self.root_path,
            port=8080,
            path='/hello',
            query_string=self.qs,
            headers=self.headers,
        )

        uri = (
            'http://'
            + testing.DEFAULT_HOST
            + ':8080'
            + self.root_path
            + self.relative_uri
        )

        assert req.uri == uri

        # =======================================================
        # HTTP, 80
        # =======================================================
        req = create_req(
            asgi,
            http_version='1.0',
            scheme='https',
            root_path=self.root_path,
            port=443,
            path='/hello',
            query_string=self.qs,
            headers=self.headers,
        )

        uri = 'https://' + testing.DEFAULT_HOST + self.root_path + self.relative_uri

        assert req.uri == uri

        # =======================================================
        # HTTP, 80
        # =======================================================
        req = create_req(
            asgi,
            http_version='1.0',
            scheme='https',
            root_path=self.root_path,
            port=22,
            path='/hello',
            query_string=self.qs,
            headers=self.headers,
        )

        uri = (
            'https://'
            + testing.DEFAULT_HOST
            + ':22'
            + self.root_path
            + self.relative_uri
        )

        assert req.uri == uri

    def test_relative_uri(self, asgi):
        assert self.req.relative_uri == self.root_path + self.relative_uri
        assert self.req_noqs.relative_uri == self.root_path + self.path

        req_noapp = create_req(
            asgi, path='/hello', query_string=self.qs, headers=self.headers
        )

        assert req_noapp.relative_uri == self.relative_uri

        req_noapp = create_req(
            asgi, path='/hello/', query_string=self.qs, headers=self.headers
        )

        relative_trailing_uri = self.path + '/?' + self.qs
        # NOTE(kgriffs): Call twice to check caching works
        assert req_noapp.relative_uri == relative_trailing_uri
        assert req_noapp.relative_uri == relative_trailing_uri

        options = RequestOptions()
        options.strip_url_path_trailing_slash = False
        req_noapp = create_req(
            asgi,
            options=options,
            path='/hello/',
            query_string=self.qs,
            headers=self.headers,
        )

        assert req_noapp.relative_uri == '/hello/' + '?' + self.qs

    def test_client_accepts(self, asgi):
        headers = {'Accept': 'application/xml'}
        req = create_req(asgi, headers=headers)
        assert req.client_accepts('application/xml')

        headers = {'Accept': '*/*'}
        req = create_req(asgi, headers=headers)
        assert req.client_accepts('application/xml')
        assert req.client_accepts('application/json')
        assert req.client_accepts('application/x-msgpack')

        headers = {'Accept': 'application/x-msgpack'}
        req = create_req(asgi, headers=headers)
        assert not req.client_accepts('application/xml')
        assert not req.client_accepts('application/json')
        assert req.client_accepts('application/x-msgpack')

        headers = {}  # NOTE(kgriffs): Equivalent to '*/*' per RFC
        req = create_req(asgi, headers=headers)
        assert req.client_accepts('application/xml')

        headers = {'Accept': 'application/json'}
        req = create_req(asgi, headers=headers)
        assert not req.client_accepts('application/xml')

        headers = {'Accept': 'application/x-msgpack'}
        req = create_req(asgi, headers=headers)
        assert req.client_accepts('application/x-msgpack')

        headers = {'Accept': 'application/xm'}
        req = create_req(asgi, headers=headers)
        assert not req.client_accepts('application/xml')

        headers = {'Accept': 'application/*'}
        req = create_req(asgi, headers=headers)
        assert req.client_accepts('application/json')
        assert req.client_accepts('application/xml')
        assert req.client_accepts('application/x-msgpack')

        headers = {'Accept': 'text/*'}
        req = create_req(asgi, headers=headers)
        assert req.client_accepts('text/plain')
        assert req.client_accepts('text/csv')
        assert not req.client_accepts('application/xhtml+xml')

        headers = {'Accept': 'text/*, application/xhtml+xml; q=0.0'}
        req = create_req(asgi, headers=headers)
        assert req.client_accepts('text/plain')
        assert req.client_accepts('text/csv')
        assert not req.client_accepts('application/xhtml+xml')

        headers = {'Accept': 'text/*; q=0.1, application/xhtml+xml; q=0.5'}
        req = create_req(asgi, headers=headers)
        assert req.client_accepts('text/plain')
        assert req.client_accepts('application/xhtml+xml')

        headers = {'Accept': 'text/*,         application/*'}
        req = create_req(asgi, headers=headers)
        assert req.client_accepts('text/plain')
        assert req.client_accepts('application/xml')
        assert req.client_accepts('application/json')
        assert req.client_accepts('application/x-msgpack')

        headers = {'Accept': 'text/*,application/*'}
        req = create_req(asgi, headers=headers)
        assert req.client_accepts('text/plain')
        assert req.client_accepts('application/xml')
        assert req.client_accepts('application/json')
        assert req.client_accepts('application/x-msgpack')

    def test_client_accepts_bogus(self, asgi):
        headers = {'Accept': '~'}
        req = create_req(asgi, headers=headers)
        assert not req.client_accepts('text/plain')
        assert not req.client_accepts('application/json')

    def test_client_accepts_props(self, asgi):
        headers = {'Accept': 'application/xml'}
        req = create_req(asgi, headers=headers)
        assert req.client_accepts_xml
        assert not req.client_accepts_json
        assert not req.client_accepts_msgpack

        headers = {'Accept': 'application/*'}
        req = create_req(asgi, headers=headers)
        assert req.client_accepts_xml
        assert req.client_accepts_json
        assert req.client_accepts_msgpack

        headers = {'Accept': 'application/json'}
        req = create_req(asgi, headers=headers)
        assert not req.client_accepts_xml
        assert req.client_accepts_json
        assert not req.client_accepts_msgpack

        headers = {'Accept': 'application/x-msgpack'}
        req = create_req(asgi, headers=headers)
        assert not req.client_accepts_xml
        assert not req.client_accepts_json
        assert req.client_accepts_msgpack

        headers = {'Accept': 'application/msgpack'}
        req = create_req(asgi, headers=headers)
        assert not req.client_accepts_xml
        assert not req.client_accepts_json
        assert req.client_accepts_msgpack

        headers = {'Accept': 'application/json,application/xml,application/x-msgpack'}
        req = create_req(asgi, headers=headers)
        assert req.client_accepts_xml
        assert req.client_accepts_json
        assert req.client_accepts_msgpack

    def test_client_prefers(self, asgi):
        headers = {'Accept': 'application/xml'}
        req = create_req(asgi, headers=headers)
        preferred_type = req.client_prefers(['application/xml'])
        assert preferred_type == 'application/xml'

        headers = {'Accept': '*/*'}
        preferred_type = req.client_prefers(('application/xml', 'application/json'))

        # NOTE(kgriffs): If client doesn't care, "prefer" the first one
        assert preferred_type == 'application/xml'

        headers = {'Accept': 'text/*; q=0.1, application/xhtml+xml; q=0.5'}
        req = create_req(asgi, headers=headers)
        preferred_type = req.client_prefers(['application/xhtml+xml'])
        assert preferred_type == 'application/xhtml+xml'

        headers = {'Accept': '3p12845j;;;asfd;'}
        req = create_req(asgi, headers=headers)
        preferred_type = req.client_prefers(['application/xhtml+xml'])
        assert preferred_type is None

    def test_range(self, asgi):
        headers = {'Range': 'bytes=10-'}
        req = create_req(asgi, headers=headers)
        assert req.range == (10, -1)

        headers = {'Range': 'bytes=10-20'}
        req = create_req(asgi, headers=headers)
        assert req.range == (10, 20)

        headers = {'Range': 'bytes=-10240'}
        req = create_req(asgi, headers=headers)
        assert req.range == (-10240, -1)

        headers = {'Range': 'bytes=0-2'}
        req = create_req(asgi, headers=headers)
        assert req.range == (0, 2)

        headers = {'Range': ''}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPInvalidHeader):
            req.range

        req = create_req(asgi)
        assert req.range is None

    def test_range_unit(self, asgi):
        headers = {'Range': 'bytes=10-'}
        req = create_req(asgi, headers=headers)
        assert req.range == (10, -1)
        assert req.range_unit == 'bytes'

        headers = {'Range': 'items=10-'}
        req = create_req(asgi, headers=headers)
        assert req.range == (10, -1)
        assert req.range_unit == 'items'

        headers = {'Range': ''}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPInvalidHeader):
            req.range_unit

        req = create_req(asgi)
        assert req.range_unit is None

    def test_range_invalid(self, asgi):
        headers = {'Range': 'bytes=10240'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=-'}
        expected_desc = (
            'The value provided for the "Range" header is '
            'invalid. The range offsets are missing.'
        )
        self._test_error_details(
            headers,
            'range',
            falcon.HTTPInvalidHeader,
            'Invalid header value',
            expected_desc,
            asgi,
        )

        headers = {'Range': 'bytes=--'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=--1'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=--0'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=-3-'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=-3-4'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=4-3'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=3-3-4'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=3-3-'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=3-3- '}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=fizbit'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=a-'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=a-3'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=-b'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=3-b'}
        req = create_req(asgi, headers=headers)
        with pytest.raises(falcon.HTTPBadRequest):
            req.range

        headers = {'Range': 'bytes=x-y'}
        expected_desc = (
            'The value provided for the "Range" header is '
            'invalid. It must be a range formatted '
            'according to RFC 7233.'
        )
        self._test_error_details(
            headers,
            'range',
            falcon.HTTPInvalidHeader,
            'Invalid header value',
            expected_desc,
            asgi,
        )

        headers = {'Range': 'bytes=0-0,-1'}
        expected_desc = (
            'The value provided for the "Range" '
            'header is invalid. The value must be a '
            'continuous range.'
        )
        self._test_error_details(
            headers,
            'range',
            falcon.HTTPInvalidHeader,
            'Invalid header value',
            expected_desc,
            asgi,
        )

        headers = {'Range': '10-'}
        expected_desc = (
            'The value provided for the "Range" '
            'header is invalid. The value must be '
            "prefixed with a range unit, e.g. 'bytes='"
        )
        self._test_error_details(
            headers,
            'range',
            falcon.HTTPInvalidHeader,
            'Invalid header value',
            expected_desc,
            asgi,
        )

    def test_missing_attribute_header(self, asgi):
        req = create_req(asgi)
        assert req.range is None

        req = create_req(asgi)
        assert req.content_length is None

    def test_content_length(self, asgi):
        headers = {'content-length': '5656'}
        req = create_req(asgi, headers=headers)
        assert req.content_length == 5656

        headers = {'content-length': ''}
        req = create_req(asgi, headers=headers)
        assert req.content_length is None

    def test_bogus_content_length_nan(self, asgi):
        headers = {'content-length': 'fuzzy-bunnies'}
        expected_desc = (
            'The value provided for the '
            '"Content-Length" header is invalid. The value '
            'of the header must be a number.'
        )
        self._test_error_details(
            headers,
            'content_length',
            falcon.HTTPInvalidHeader,
            'Invalid header value',
            expected_desc,
            asgi,
        )

    def test_bogus_content_length_neg(self, asgi):
        headers = {'content-length': '-1'}
        expected_desc = (
            'The value provided for the "Content-Length" '
            'header is invalid. The value of the header '
            'must be a positive number.'
        )
        self._test_error_details(
            headers,
            'content_length',
            falcon.HTTPInvalidHeader,
            'Invalid header value',
            expected_desc,
            asgi,
        )

    @pytest.mark.parametrize(
        'header,attr',
        [
            ('Date', 'date'),
            ('If-Modified-Since', 'if_modified_since'),
            ('If-Unmodified-Since', 'if_unmodified_since'),
        ],
    )
    def test_date(self, asgi, header, attr):
        date = datetime.datetime(2013, 4, 4, 5, 19, 18, tzinfo=datetime.timezone.utc)
        date_str = 'Thu, 04 Apr 2013 05:19:18 GMT'

        headers = {header: date_str}
        req = create_req(asgi, headers=headers)
        assert getattr(req, attr) == date

    @pytest.mark.parametrize(
        'header,attr',
        [
            ('Date', 'date'),
            ('If-Modified-Since', 'if_modified_since'),
            ('If-Unmodified-Since', 'if_unmodified_since'),
        ],
    )
    def test_date_invalid(self, asgi, header, attr):
        # Date formats don't conform to RFC 1123
        headers = {header: 'Thu, 04 Apr 2013'}
        expected_desc = (
            'The value provided for the "{}" '
            'header is invalid. It must be formatted '
            'according to RFC 7231, Section 7.1.1.1'
        )

        self._test_error_details(
            headers,
            attr,
            falcon.HTTPInvalidHeader,
            'Invalid header value',
            expected_desc.format(header),
            asgi,
        )

        headers = {header: ''}
        self._test_error_details(
            headers,
            attr,
            falcon.HTTPInvalidHeader,
            'Invalid header value',
            expected_desc.format(header),
            asgi,
        )

    @pytest.mark.parametrize(
        'attr', ('date', 'if_modified_since', 'if_unmodified_since')
    )
    def test_date_missing(self, asgi, attr):
        req = create_req(asgi)
        assert getattr(req, attr) is None

    @pytest.mark.parametrize(
        'name,value,attr,default',
        [
            ('Accept', 'x-falcon', 'accept', '*/*'),
            (
                'Authorization',
                'HMAC_SHA1 c590afa9bb59191ffab30f223791e82d3fd3e3af',
                'auth',
                None,
            ),
            ('Content-Type', 'text/plain', 'content_type', None),
            ('Expect', '100-continue', 'expect', None),
            ('If-Range', 'Wed, 21 Oct 2015 07:28:00 GMT', 'if_range', None),
            (
                'User-Agent',
                'testing/3.0',
                'user_agent',
                'falcon-client/' + falcon.__version__,
            ),
            ('Referer', 'https://www.google.com/', 'referer', None),
        ],
    )
    def test_attribute_headers(self, asgi, name, value, attr, default):
        headers = {name: value}
        req = create_req(asgi, headers=headers)
        assert getattr(req, attr) == value

        req = create_req(asgi)
        assert getattr(req, attr) == default

    def test_method(self, asgi):
        assert self.req.method == 'GET'

        self.req = create_req(asgi, path='', method='HEAD')
        assert self.req.method == 'HEAD'

    def test_empty_path(self, asgi):
        self.req = create_req(asgi, path='')
        assert self.req.path == '/'

    def test_content_type_method(self, asgi):
        assert self.req.get_header('content-type') == 'text/plain'

    def test_content_length_method(self, asgi):
        assert self.req.get_header('content-length') == '4829'

    # TODO(kgriffs): Migrate to pytest and parametrized fixtures
    # to DRY things up a bit.
    @pytest.mark.parametrize('http_version', _HTTP_VERSIONS)
    def test_port_explicit(self, asgi, http_version):
        port = 9000
        req = create_req(
            asgi,
            http_version=http_version,
            port=port,
            root_path=self.root_path,
            path='/hello',
            query_string=self.qs,
            headers=self.headers,
        )

        assert req.port == port

    @pytest.mark.parametrize('http_version', _HTTP_VERSIONS)
    def test_scheme_https(self, asgi, http_version):
        scheme = 'https'
        req = create_req(
            asgi,
            http_version=http_version,
            scheme=scheme,
            root_path=self.root_path,
            path='/hello',
            query_string=self.qs,
            headers=self.headers,
        )

        assert req.scheme == scheme
        assert req.port == 443

    @pytest.mark.parametrize(
        'http_version, set_forwarded_proto',
        list(itertools.product(_HTTP_VERSIONS, [True, False])),
    )
    def test_scheme_http(self, asgi, http_version, set_forwarded_proto):
        scheme = 'http'
        forwarded_scheme = 'HttPs'

        headers = dict(self.headers)

        if set_forwarded_proto:
            headers['X-Forwarded-Proto'] = forwarded_scheme

        req = create_req(
            asgi,
            http_version=http_version,
            scheme=scheme,
            root_path=self.root_path,
            path='/hello',
            query_string=self.qs,
            headers=headers,
        )

        assert req.scheme == scheme
        assert req.port == 80

        if set_forwarded_proto:
            assert req.forwarded_scheme == forwarded_scheme.lower()
        else:
            assert req.forwarded_scheme == scheme

    @pytest.mark.parametrize('http_version', _HTTP_VERSIONS)
    def test_netloc_default_port(self, asgi, http_version):
        req = create_req(
            asgi,
            http_version=http_version,
            root_path=self.root_path,
            path='/hello',
            query_string=self.qs,
            headers=self.headers,
        )

        assert req.netloc == 'falconframework.org'

    @pytest.mark.parametrize('http_version', _HTTP_VERSIONS)
    def test_netloc_nondefault_port(self, asgi, http_version):
        req = create_req(
            asgi,
            http_version=http_version,
            port='8080',
            root_path=self.root_path,
            path='/hello',
            query_string=self.qs,
            headers=self.headers,
        )

        assert req.netloc == 'falconframework.org:8080'

    @pytest.mark.parametrize('http_version', _HTTP_VERSIONS)
    def test_netloc_from_env(self, asgi, http_version):
        port = 9000
        host = 'example.org'

        req = create_req(
            asgi,
            http_version=http_version,
            host=host,
            port=port,
            root_path=self.root_path,
            path='/hello',
            query_string=self.qs,
            headers=self.headers,
        )

        assert req.port == port
        assert req.netloc == '{}:{}'.format(host, port)

    def test_app_present(self, asgi):
        req = create_req(asgi, root_path='/moving-pictures')
        with pytest.warns(DeprecatedWarning):
            assert req.app == '/moving-pictures'
        assert req.root_path == '/moving-pictures'

    def test_app_blank(self, asgi):
        req = create_req(asgi, root_path='')
        with pytest.warns(DeprecatedWarning):
            assert req.app == ''
        assert req.root_path == ''

    @pytest.mark.parametrize(
        'etag,expected_value',
        [
            ('', None),
            (' ', None),
            ('   ', None),
            ('\t', None),
            (' \t', None),
            (',', None),
            (',,', None),
            (',, ', None),
            (', , ', None),
            ('*', ['*']),
            ('W/"67ab43"', [_make_etag('67ab43', is_weak=True)]),
            ('w/"67ab43"', [_make_etag('67ab43', is_weak=True)]),
            (' w/"67ab43"', [_make_etag('67ab43', is_weak=True)]),
            ('w/"67ab43" ', [_make_etag('67ab43', is_weak=True)]),
            ('w/"67ab43 " ', [_make_etag('67ab43 ', is_weak=True)]),
            ('"67ab43"', [_make_etag('67ab43')]),
            (' "67ab43"', [_make_etag('67ab43')]),
            (' "67ab43" ', [_make_etag('67ab43')]),
            ('"67ab43" ', [_make_etag('67ab43')]),
            ('" 67ab43" ', [_make_etag(' 67ab43')]),
            ('67ab43"', [_make_etag('67ab43"')]),
            ('"67ab43', [_make_etag('"67ab43')]),
            ('67ab43', [_make_etag('67ab43')]),
            ('67ab43 ', [_make_etag('67ab43')]),
            ('  67ab43 ', [_make_etag('67ab43')]),
            ('  67ab43', [_make_etag('67ab43')]),
            (
                # NOTE(kgriffs): To simplify parsing and improve performance, we
                #   do not attempt to handle unquoted entity-tags when there is
                #   a list; it is non-standard anyway, and has been since 1999.
                'W/"67ab43", "54ed21", junk"F9,22", junk "41, 7F", '
                'unquoted, w/"22, 41, 7F", "", W/""',
                [
                    _make_etag('67ab43', is_weak=True),
                    _make_etag('54ed21'),
                    # NOTE(kgriffs): Test that the ETag initializer defaults to
                    #   is_weak == False
                    ETag('F9,22'),
                    _make_etag('41, 7F'),
                    _make_etag('22, 41, 7F', is_weak=True),
                    # NOTE(kgriffs): According to the grammar in RFC 7232, zero
                    #  etagc's is acceptable.
                    _make_etag(''),
                    _make_etag('', is_weak=True),
                ],
            ),
        ],
    )
    @pytest.mark.parametrize(
        'name,attr',
        [
            ('If-Match', 'if_match'),
            ('If-None-Match', 'if_none_match'),
        ],
    )
    def test_etag(self, asgi, name, attr, etag, expected_value):
        headers = {name: etag}
        req = create_req(asgi, headers=headers)

        # NOTE(kgriffs): Loop in order to test caching
        for __ in range(3):
            value = getattr(req, attr)

            if expected_value is None:
                assert value is None
                return

            assert value is not None

            for element, expected_element in zip(value, expected_value):
                assert element == expected_element
                if isinstance(expected_element, ETag):
                    assert element.is_weak == expected_element.is_weak

    def test_etag_is_missing(self, asgi):
        # NOTE(kgriffs): Loop in order to test caching
        for __ in range(3):
            assert self.req.if_match is None
            assert self.req.if_none_match is None

    @pytest.mark.parametrize('header_value', ['', ' ', '  '])
    def test_etag_parsing_helper(self, asgi, header_value):
        # NOTE(kgriffs): Test a couple of cases that are not directly covered
        #   elsewhere (but that we want the helper to still support
        #   for the sake of avoiding surprises if they are ever called without
        #   preflighting the header value).

        assert _parse_etags(header_value) is None

    # -------------------------------------------------------------------------
    # Helpers
    # -------------------------------------------------------------------------

    def _test_error_details(
        self, headers, attr_name, error_type, title, description, asgi
    ):
        req = create_req(asgi, headers=headers)

        try:
            getattr(req, attr_name)
            pytest.fail('{} not raised'.format(error_type.__name__))
        except error_type as ex:
            assert ex.title == title
            assert ex.description == description