File: test_web_functional.py

package info (click to toggle)
python-aiohttp 1.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,288 kB
  • ctags: 4,380
  • sloc: python: 27,221; makefile: 236
file content (1210 lines) | stat: -rw-r--r-- 34,218 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
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
import asyncio
import json
import pathlib
import zlib
from unittest import mock

import pytest
from multidict import MultiDict
from yarl import URL

from aiohttp import FormData, multipart, web
from aiohttp.protocol import HttpVersion, HttpVersion10, HttpVersion11

try:
    import ssl
except:
    ssl = False


@asyncio.coroutine
def test_simple_get(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        body = yield from request.read()
        assert b'' == body
        return web.Response(body=b'OK')

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    resp = yield from client.get('/')
    assert 200 == resp.status
    txt = yield from resp.text()
    assert 'OK' == txt


@asyncio.coroutine
def test_handler_returns_not_response(loop, test_server, test_client):
    logger = mock.Mock()

    @asyncio.coroutine
    def handler(request):
        return 'abc'

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    server = yield from test_server(app, logger=logger)
    client = yield from test_client(server)

    resp = yield from client.get('/')
    assert 500 == resp.status

    assert logger.exception.called


@asyncio.coroutine
def test_head_returns_empty_body(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        return web.Response(body=b'test')

    app = web.Application(loop=loop)
    app.router.add_head('/', handler)
    client = yield from test_client(app)

    resp = yield from client.head('/', version=HttpVersion11)
    assert 200 == resp.status
    txt = yield from resp.text()
    assert '' == txt


@asyncio.coroutine
def test_post_form(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        data = yield from request.post()
        assert {'a': '1', 'b': '2'} == data
        return web.Response(body=b'OK')

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    resp = yield from client.post('/', data={'a': 1, 'b': 2})
    assert 200 == resp.status
    txt = yield from resp.text()
    assert 'OK' == txt


@asyncio.coroutine
def test_post_text(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        data = yield from request.text()
        assert 'русский' == data
        data2 = yield from request.text()
        assert data == data2
        return web.Response(text=data)

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    resp = yield from client.post('/', data='русский')
    assert 200 == resp.status
    txt = yield from resp.text()
    assert 'русский' == txt


@asyncio.coroutine
def test_post_json(loop, test_client):

    dct = {'key': 'текст'}

    @asyncio.coroutine
    def handler(request):
        data = yield from request.json()
        assert dct == data
        data2 = yield from request.json(loads=json.loads)
        assert data == data2
        with pytest.warns(DeprecationWarning):
            data3 = yield from request.json(loader=json.loads)
        assert data == data3
        resp = web.Response()
        resp.content_type = 'application/json'
        resp.body = json.dumps(data).encode('utf8')
        return resp

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    headers = {'Content-Type': 'application/json'}
    resp = yield from client.post('/', data=json.dumps(dct), headers=headers)
    assert 200 == resp.status
    data = yield from resp.json()
    assert dct == data


@asyncio.coroutine
def test_multipart(loop, test_client):
    with multipart.MultipartWriter() as writer:
        writer.append('test')
        writer.append_json({'passed': True})

    @asyncio.coroutine
    def handler(request):
        reader = yield from request.multipart()
        assert isinstance(reader, multipart.MultipartReader)

        part = yield from reader.next()
        assert isinstance(part, multipart.BodyPartReader)
        thing = yield from part.text()
        assert thing == 'test'

        part = yield from reader.next()
        assert isinstance(part, multipart.BodyPartReader)
        assert part.headers['Content-Type'] == 'application/json'
        thing = yield from part.json()
        assert thing == {'passed': True}

        resp = web.Response()
        resp.content_type = 'application/json'
        resp.body = b''
        return resp

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    resp = yield from client.post('/', data=writer, headers=writer.headers)
    assert 200 == resp.status
    yield from resp.release()


@asyncio.coroutine
def test_multipart_content_transfer_encoding(loop, test_client):
    """For issue #1168"""
    with multipart.MultipartWriter() as writer:
        writer.append(b'\x00' * 10,
                      headers={'Content-Transfer-Encoding': 'binary'})

    @asyncio.coroutine
    def handler(request):
        reader = yield from request.multipart()
        assert isinstance(reader, multipart.MultipartReader)

        part = yield from reader.next()
        assert isinstance(part, multipart.BodyPartReader)
        assert part.headers['Content-Transfer-Encoding'] == 'binary'
        thing = yield from part.read()
        assert thing == b'\x00' * 10

        resp = web.Response()
        resp.content_type = 'application/json'
        resp.body = b''
        return resp

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    resp = yield from client.post('/', data=writer, headers=writer.headers)
    assert 200 == resp.status
    yield from resp.release()


@asyncio.coroutine
def test_render_redirect(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        raise web.HTTPMovedPermanently(location='/path')

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    resp = yield from client.get('/', allow_redirects=False)
    assert 301 == resp.status
    txt = yield from resp.text()
    assert '301: Moved Permanently' == txt
    assert '/path' == resp.headers['location']


@asyncio.coroutine
def test_post_single_file(loop, test_client):

    here = pathlib.Path(__file__).parent

    def check_file(fs):
        fullname = here / fs.filename
        with fullname.open() as f:
            test_data = f.read().encode()
            data = fs.file.read()
            assert test_data == data

    @asyncio.coroutine
    def handler(request):
        with pytest.warns(DeprecationWarning):
            data = yield from request.post()
        assert ['sample.crt'] == list(data.keys())
        for fs in data.values():
            check_file(fs)
            fs.file.close()
        resp = web.Response(body=b'OK')
        return resp

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    fname = here / 'sample.crt'

    resp = yield from client.post('/', data=[fname.open()])
    assert 200 == resp.status


@asyncio.coroutine
def test_files_upload_with_same_key(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        data = yield from request.post()
        files = data.getall('file')
        file_names = set()
        for _file in files:
            assert not _file.file.closed
            if _file.filename == 'test1.jpeg':
                assert _file.file.read() == b'binary data 1'
            if _file.filename == 'test2.jpeg':
                assert _file.file.read() == b'binary data 2'
            file_names.add(_file.filename)
        assert len(files) == 2
        assert file_names == {'test1.jpeg', 'test2.jpeg'}
        resp = web.Response(body=b'OK')
        return resp

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    data = FormData()
    data.add_field('file', b'binary data 1',
                   content_type='image/jpeg',
                   filename='test1.jpeg')
    data.add_field('file', b'binary data 2',
                   content_type='image/jpeg',
                   filename='test2.jpeg')
    resp = yield from client.post('/', data=data)
    assert 200 == resp.status


@asyncio.coroutine
def test_post_files(loop, test_client):

    here = pathlib.Path(__file__).parent

    def check_file(fs):
        fullname = here / fs.filename
        with fullname.open() as f:
            test_data = f.read().encode()
            data = fs.file.read()
            assert test_data == data

    @asyncio.coroutine
    def handler(request):
        data = yield from request.post()
        assert ['sample.crt', 'sample.key'] == list(data.keys())
        for fs in data.values():
            check_file(fs)
            fs.file.close()
        resp = web.Response(body=b'OK')
        return resp

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    with (here / 'sample.crt').open() as f1:
        with (here / 'sample.key').open() as f2:
            resp = yield from client.post('/', data=[f1, f2])
            assert 200 == resp.status


@asyncio.coroutine
def test_release_post_data(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        yield from request.release()
        chunk = yield from request.content.readany()
        assert chunk == b''
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    resp = yield from client.post('/', data='post text')
    assert 200 == resp.status


@asyncio.coroutine
def test_POST_DATA_with_content_transfer_encoding(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        data = yield from request.post()
        assert b'123' == data['name']
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    form = FormData()
    form.add_field('name', b'123',
                   content_transfer_encoding='base64')

    resp = yield from client.post('/', data=form)
    assert 200 == resp.status


@asyncio.coroutine
def test_post_form_with_duplicate_keys(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        data = yield from request.post()
        lst = list(data.items())
        assert [('a', '1'), ('a', '2')] == lst
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    resp = yield from client.post('/', data=MultiDict([('a', 1), ('a', 2)]))
    assert 200 == resp.status


def test_repr_for_application(loop):
    app = web.Application(loop=loop)
    assert "<Application 0x{:x}>".format(id(app)) == repr(app)


@asyncio.coroutine
def test_expect_default_handler_unknown(loop, test_client):
    """Test default Expect handler for unknown Expect value.

    A server that does not understand or is unable to comply with any of
    the expectation values in the Expect field of a request MUST respond
    with appropriate error status. The server MUST respond with a 417
    (Expectation Failed) status if any of the expectations cannot be met
    or, if there are other problems with the request, some other 4xx
    status.

    http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.20
    """
    @asyncio.coroutine
    def handler(request):
        yield from request.post()
        pytest.xfail('Handler should not proceed to this point in case of '
                     'unknown Expect header')

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    resp = yield from client.post('/', headers={'Expect': 'SPAM'})
    assert 417 == resp.status


@asyncio.coroutine
def test_100_continue(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        data = yield from request.post()
        assert b'123' == data['name']
        return web.Response()

    form = FormData()
    form.add_field('name', b'123',
                   content_transfer_encoding='base64')

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    resp = yield from client.post('/', data=form, expect100=True)
    assert 200 == resp.status


@asyncio.coroutine
def test_100_continue_custom(loop, test_client):

    expect_received = False

    @asyncio.coroutine
    def handler(request):
        data = yield from request.post()
        assert b'123' == data['name']
        return web.Response()

    @asyncio.coroutine
    def expect_handler(request):
        nonlocal expect_received
        expect_received = True
        if request.version == HttpVersion11:
            request.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n")

    form = FormData()
    form.add_field('name', b'123',
                   content_transfer_encoding='base64')

    app = web.Application(loop=loop)
    app.router.add_post('/', handler, expect_handler=expect_handler)
    client = yield from test_client(app)

    resp = yield from client.post('/', data=form, expect100=True)
    assert 200 == resp.status
    assert expect_received


@asyncio.coroutine
def test_100_continue_custom_response(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        data = yield from request.post()
        assert b'123', data['name']
        return web.Response()

    @asyncio.coroutine
    def expect_handler(request):
        if request.version == HttpVersion11:
            if auth_err:
                return web.HTTPForbidden()

            request.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n")

    form = FormData()
    form.add_field('name', b'123',
                   content_transfer_encoding='base64')

    app = web.Application(loop=loop)
    app.router.add_post('/', handler, expect_handler=expect_handler)
    client = yield from test_client(app)

    auth_err = False
    resp = yield from client.post('/', data=form, expect100=True)
    assert 200 == resp.status

    auth_err = True
    resp = yield from client.post('/', data=form, expect100=True)
    assert 403 == resp.status


@asyncio.coroutine
def test_100_continue_for_not_found(loop, test_client):

    app = web.Application(loop=loop)
    client = yield from test_client(app)

    resp = yield from client.post('/not_found', data='data', expect100=True)
    assert 404 == resp.status


@asyncio.coroutine
def test_100_continue_for_not_allowed(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    resp = yield from client.get('/', expect100=True)
    assert 405 == resp.status


@asyncio.coroutine
def test_http11_keep_alive_default(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    resp = yield from client.get('/', version=HttpVersion11)
    assert 200 == resp.status
    assert resp.version == HttpVersion11
    assert 'Connection' not in resp.headers


@asyncio.coroutine
def test_http10_keep_alive_default(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    resp = yield from client.get('/', version=HttpVersion10)
    assert 200 == resp.status
    assert resp.version == HttpVersion10
    assert resp.headers['Connection'] == 'keep-alive'


@asyncio.coroutine
def test_http09_keep_alive_default(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        yield from request.read()
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    headers = {'Connection': 'keep-alive'}  # should be ignored
    resp = yield from client.get('/', version=HttpVersion(0, 9),
                                 headers=headers)
    assert 200 == resp.status
    assert resp.version == HttpVersion(0, 9)
    assert 'Connection' not in resp.headers


@asyncio.coroutine
def test_http10_keep_alive_with_headers_close(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        yield from request.read()
        return web.Response(body=b'OK')

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    headers = {'Connection': 'close'}
    resp = yield from client.get('/', version=HttpVersion10,
                                 headers=headers)
    assert 200 == resp.status
    assert resp.version == HttpVersion10
    assert 'Connection' not in resp.headers


@asyncio.coroutine
def test_http10_keep_alive_with_headers(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        yield from request.read()
        return web.Response(body=b'OK')

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    headers = {'Connection': 'keep-alive'}
    resp = yield from client.get('/', version=HttpVersion10,
                                 headers=headers)
    assert 200 == resp.status
    assert resp.version == HttpVersion10
    assert resp.headers['Connection'] == 'keep-alive'


@asyncio.coroutine
def test_upload_file(loop, test_client):

    here = pathlib.Path(__file__).parent
    fname = here / 'software_development_in_picture.jpg'
    with fname.open('rb') as f:
        data = f.read()

    @asyncio.coroutine
    def handler(request):
        form = yield from request.post()
        raw_data = form['file'].file.read()
        assert data == raw_data
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    resp = yield from client.post('/', data={'file': data})
    assert 200 == resp.status


@asyncio.coroutine
def test_upload_file_object(loop, test_client):
    here = pathlib.Path(__file__).parent
    fname = here / 'software_development_in_picture.jpg'
    with fname.open('rb') as f:
        data = f.read()

    @asyncio.coroutine
    def handler(request):
        form = yield from request.post()
        raw_data = form['file'].file.read()
        assert data == raw_data
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    with fname.open('rb') as f:
        resp = yield from client.post('/', data={'file': f})
        assert 200 == resp.status


@asyncio.coroutine
def test_empty_content_for_query_without_body(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        assert not request.has_body
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    resp = yield from client.get('/')
    assert 200 == resp.status


@asyncio.coroutine
def test_empty_content_for_query_with_body(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        assert request.has_body
        body = yield from request.read()
        return web.Response(body=body)

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    resp = yield from client.post('/', data=b'data')
    assert 200 == resp.status


@asyncio.coroutine
def test_get_with_empty_arg(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        assert 'arg' in request.GET
        assert '' == request.GET['arg']
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    resp = yield from client.get('/?arg')
    assert 200 == resp.status


@asyncio.coroutine
def test_large_header(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    headers = {'Long-Header': 'ab' * 8129}
    resp = yield from client.get('/', headers=headers)
    assert 400 == resp.status


@asyncio.coroutine
def test_large_header_allowed(loop, test_client, test_server):

    @asyncio.coroutine
    def handler(request):
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    server = yield from test_server(app, max_field_size=81920)
    client = yield from test_client(server)

    headers = {'Long-Header': 'ab' * 8129}
    resp = yield from client.get('/', headers=headers)
    assert 200 == resp.status


@asyncio.coroutine
def test_get_with_empty_arg_with_equal(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        assert 'arg' in request.GET
        assert '' == request.GET['arg']
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    resp = yield from client.get('/?arg=')
    assert 200 == resp.status


@pytest.mark.xfail  # and had never worked
@asyncio.coroutine
def test_response_with_precompressed_body(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        headers = {'Content-Encoding': 'gzip'}
        deflated_data = zlib.compress(b'mydata')
        return web.Response(body=deflated_data, headers=headers)

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    resp = yield from client.get('/')
    assert 200 == resp.status
    data = yield from resp.read()
    assert b'mydata' == data
    assert resp.headers.get('Content-Encoding') == 'deflate'


@asyncio.coroutine
def test_stream_response_multiple_chunks(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        resp = web.StreamResponse()
        resp.enable_chunked_encoding()
        yield from resp.prepare(request)
        resp.write(b'x')
        resp.write(b'y')
        resp.write(b'z')
        return resp

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    resp = yield from client.get('/')
    assert 200 == resp.status
    data = yield from resp.read()
    assert b'xyz' == data


@asyncio.coroutine
def test_start_without_routes(loop, test_client):

    app = web.Application(loop=loop)
    client = yield from test_client(app)

    resp = yield from client.get('/')
    assert 404 == resp.status


@asyncio.coroutine
def test_requests_count(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)
    assert client.server.handler.requests_count == 0

    resp = yield from client.get('/')
    assert 200 == resp.status
    assert client.server.handler.requests_count == 1

    resp = yield from client.get('/')
    assert 200 == resp.status
    assert client.server.handler.requests_count == 2

    resp = yield from client.get('/')
    assert 200 == resp.status
    assert client.server.handler.requests_count == 3


@asyncio.coroutine
def test_redirect_url(loop, test_client):

    @asyncio.coroutine
    def redirector(request):
        raise web.HTTPFound(location=URL('/redirected'))

    @asyncio.coroutine
    def redirected(request):
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_get('/redirector', redirector)
    app.router.add_get('/redirected', redirected)

    client = yield from test_client(app)
    resp = yield from client.get('/redirector')
    assert resp.status == 200


@asyncio.coroutine
def test_simple_subapp(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        return web.Response(text="OK")

    app = web.Application(loop=loop)
    subapp = web.Application(loop=loop)
    subapp.router.add_get('/to', handler)
    app.router.add_subapp('/path', subapp)

    client = yield from test_client(app)
    resp = yield from client.get('/path/to')
    assert resp.status == 200
    txt = yield from resp.text()
    assert 'OK' == txt


@asyncio.coroutine
def test_subapp_reverse_url(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        return web.HTTPMovedPermanently(
            location=subapp.router['name'].url_for())

    @asyncio.coroutine
    def handler2(request):
        return web.Response(text="OK")

    app = web.Application(loop=loop)
    subapp = web.Application(loop=loop)
    subapp.router.add_get('/to', handler)
    subapp.router.add_get('/final', handler2, name='name')
    app.router.add_subapp('/path', subapp)

    client = yield from test_client(app)
    resp = yield from client.get('/path/to')
    assert resp.status == 200
    txt = yield from resp.text()
    assert 'OK' == txt
    assert resp.url_obj.path == '/path/final'


@asyncio.coroutine
def test_subapp_reverse_variable_url(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        return web.HTTPMovedPermanently(
            location=subapp.router['name'].url_for(part='final'))

    @asyncio.coroutine
    def handler2(request):
        return web.Response(text="OK")

    app = web.Application(loop=loop)
    subapp = web.Application(loop=loop)
    subapp.router.add_get('/to', handler)
    subapp.router.add_get('/{part}', handler2, name='name')
    app.router.add_subapp('/path', subapp)

    client = yield from test_client(app)
    resp = yield from client.get('/path/to')
    assert resp.status == 200
    txt = yield from resp.text()
    assert 'OK' == txt
    assert resp.url_obj.path == '/path/final'


@asyncio.coroutine
def test_subapp_reverse_static_url(loop, test_client):
    fname = 'software_development_in_picture.jpg'

    @asyncio.coroutine
    def handler(request):
        return web.HTTPMovedPermanently(
            location=subapp.router['name'].url_for(filename=fname))

    app = web.Application(loop=loop)
    subapp = web.Application(loop=loop)
    subapp.router.add_get('/to', handler)
    here = pathlib.Path(__file__).parent
    subapp.router.add_static('/static', here, name='name')
    app.router.add_subapp('/path', subapp)

    client = yield from test_client(app)
    resp = yield from client.get('/path/to')
    assert resp.url_obj.path == '/path/static/' + fname
    assert resp.status == 200
    body = yield from resp.read()
    with (here / fname).open('rb') as f:
        assert body == f.read()


@asyncio.coroutine
def test_subapp_app(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        assert request.app is subapp
        return web.HTTPOk(text='OK')

    app = web.Application(loop=loop)
    subapp = web.Application(loop=loop)
    subapp.router.add_get('/to', handler)
    app.router.add_subapp('/path/', subapp)

    client = yield from test_client(app)
    resp = yield from client.get('/path/to')
    assert resp.status == 200
    txt = yield from resp.text()
    assert 'OK' == txt


@asyncio.coroutine
def test_subapp_not_found(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        return web.HTTPOk(text='OK')

    app = web.Application(loop=loop)
    subapp = web.Application(loop=loop)
    subapp.router.add_get('/to', handler)
    app.router.add_subapp('/path/', subapp)

    client = yield from test_client(app)
    resp = yield from client.get('/path/other')
    assert resp.status == 404


@asyncio.coroutine
def test_subapp_not_found2(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        return web.HTTPOk(text='OK')

    app = web.Application(loop=loop)
    subapp = web.Application(loop=loop)
    subapp.router.add_get('/to', handler)
    app.router.add_subapp('/path/', subapp)

    client = yield from test_client(app)
    resp = yield from client.get('/invalid/other')
    assert resp.status == 404


@asyncio.coroutine
def test_subapp_not_allowed(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        return web.HTTPOk(text='OK')

    app = web.Application(loop=loop)
    subapp = web.Application(loop=loop)
    subapp.router.add_get('/to', handler)
    app.router.add_subapp('/path/', subapp)

    client = yield from test_client(app)
    resp = yield from client.post('/path/to')
    assert resp.status == 405
    assert resp.headers['Allow'] == 'GET'


@asyncio.coroutine
def test_subapp_cannot_add_app_in_handler(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        request.match_info.add_app(app)
        return web.HTTPOk(text='OK')

    app = web.Application(loop=loop)
    subapp = web.Application(loop=loop)
    subapp.router.add_get('/to', handler)
    app.router.add_subapp('/path/', subapp)

    client = yield from test_client(app)
    resp = yield from client.get('/path/to')
    assert resp.status == 500


@asyncio.coroutine
def test_subapp_middlewares(loop, test_client):
    order = []

    @asyncio.coroutine
    def handler(request):
        return web.HTTPOk(text='OK')

    @asyncio.coroutine
    def middleware_factory(app, handler):

        @asyncio.coroutine
        def middleware(request):
            order.append((1, app))
            resp = yield from handler(request)
            assert 200 == resp.status
            order.append((2, app))
            return resp
        return middleware

    app = web.Application(loop=loop, middlewares=[middleware_factory])
    subapp1 = web.Application(loop=loop, middlewares=[middleware_factory])
    subapp2 = web.Application(loop=loop, middlewares=[middleware_factory])
    subapp2.router.add_get('/to', handler)
    subapp1.router.add_subapp('/b/', subapp2)
    app.router.add_subapp('/a/', subapp1)

    client = yield from test_client(app)
    resp = yield from client.get('/a/b/to')
    assert resp.status == 200
    assert [(1, app), (1, subapp1), (1, subapp2),
            (2, subapp2), (2, subapp1), (2, app)] == order


@asyncio.coroutine
def test_subapp_on_response_prepare(loop, test_client):
    order = []

    @asyncio.coroutine
    def handler(request):
        return web.HTTPOk(text='OK')

    def make_signal(app):

        @asyncio.coroutine
        def on_response(request, response):
            order.append(app)

        return on_response

    app = web.Application(loop=loop)
    app.on_response_prepare.append(make_signal(app))
    subapp1 = web.Application(loop=loop)
    subapp1.on_response_prepare.append(make_signal(subapp1))
    subapp2 = web.Application(loop=loop)
    subapp2.on_response_prepare.append(make_signal(subapp2))
    subapp2.router.add_get('/to', handler)
    subapp1.router.add_subapp('/b/', subapp2)
    app.router.add_subapp('/a/', subapp1)

    client = yield from test_client(app)
    resp = yield from client.get('/a/b/to')
    assert resp.status == 200
    assert [app, subapp1, subapp2] == order


@asyncio.coroutine
def test_subapp_on_startup(loop, test_server):
    order = []

    @asyncio.coroutine
    def on_signal(app):
        order.append(app)

    app = web.Application(loop=loop)
    app.on_startup.append(on_signal)
    subapp1 = web.Application(loop=loop)
    subapp1.on_startup.append(on_signal)
    subapp2 = web.Application(loop=loop)
    subapp2.on_startup.append(on_signal)
    subapp1.router.add_subapp('/b/', subapp2)
    app.router.add_subapp('/a/', subapp1)

    yield from test_server(app)

    assert [app, subapp1, subapp2] == order


@asyncio.coroutine
def test_subapp_on_shutdown(loop, test_server):
    order = []

    def on_signal(app):
        order.append(app)

    app = web.Application(loop=loop)
    app.on_shutdown.append(on_signal)
    subapp1 = web.Application(loop=loop)
    subapp1.on_shutdown.append(on_signal)
    subapp2 = web.Application(loop=loop)
    subapp2.on_shutdown.append(on_signal)
    subapp1.router.add_subapp('/b/', subapp2)
    app.router.add_subapp('/a/', subapp1)

    server = yield from test_server(app)
    yield from server.close()

    assert [app, subapp1, subapp2] == order


@asyncio.coroutine
def test_subapp_on_cleanup(loop, test_server):
    order = []

    @asyncio.coroutine
    def on_signal(app):
        order.append(app)

    app = web.Application(loop=loop)
    app.on_cleanup.append(on_signal)
    subapp1 = web.Application(loop=loop)
    subapp1.on_cleanup.append(on_signal)
    subapp2 = web.Application(loop=loop)
    subapp2.on_cleanup.append(on_signal)
    subapp1.router.add_subapp('/b/', subapp2)
    app.router.add_subapp('/a/', subapp1)

    server = yield from test_server(app)
    yield from server.close()

    assert [app, subapp1, subapp2] == order


@asyncio.coroutine
def test_custom_date_header(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        return web.Response(headers={'Date': 'Sun, 30 Oct 2016 03:13:52 GMT'})

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    resp = yield from client.get('/')
    assert 200 == resp.status
    assert resp.headers['Date'] == 'Sun, 30 Oct 2016 03:13:52 GMT'


@asyncio.coroutine
def test_response_task(loop, test_client):

    srv_resp = None

    @asyncio.coroutine
    def handler(request):
        nonlocal srv_resp
        srv_resp = web.StreamResponse()
        assert srv_resp.task is None
        yield from srv_resp.prepare(request)
        assert srv_resp.task is not None
        return srv_resp

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    client = yield from test_client(app)

    resp = yield from client.get('/')
    assert 200 == resp.status
    assert srv_resp.task is None