File: test_asgi_servers.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 (666 lines) | stat: -rw-r--r-- 21,773 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
import asyncio
from contextlib import contextmanager
import hashlib
import os
import platform
import random
import signal
import subprocess
import sys
import time

import pytest

try:
    import httpx
except ImportError:
    httpx = None  # type: ignore

try:
    import requests
    import requests.exceptions
except ImportError:
    requests = None  # type: ignore

try:
    import websockets
    import websockets.exceptions
except ImportError:
    websockets = None  # type: ignore


from falcon import testing

from . import _asgi_test_app

_MODULE_DIR = os.path.abspath(os.path.dirname(__file__))

_PYPY = platform.python_implementation() == 'PyPy'
_WIN32 = sys.platform.startswith('win')

_SERVER_HOST = '127.0.0.1'
_SIZE_1_KB = 1024
_SIZE_1_MB = _SIZE_1_KB**2
# NOTE(vytas): Windows specific: {Application Exit by CTRL+C}.
#   The application terminated as a result of a CTRL+C.
_STATUS_CONTROL_C_EXIT = 0xC000013A

_REQUEST_TIMEOUT = 10


@pytest.mark.skipif(
    requests is None, reason='requests module is required for this test'
)
class TestASGIServer:
    def test_get(self, server_base_url):
        resp = requests.get(server_base_url, timeout=_REQUEST_TIMEOUT)
        assert resp.status_code == 200
        assert resp.text == '127.0.0.1'

    def test_put(self, server_base_url):
        body = '{}'
        resp = requests.put(server_base_url, data=body, timeout=_REQUEST_TIMEOUT)
        assert resp.status_code == 200
        assert resp.text == '{}'

    def test_head_405(self, server_base_url):
        body = '{}'
        resp = requests.head(server_base_url, data=body, timeout=_REQUEST_TIMEOUT)
        assert resp.status_code == 405

    def test_post_multipart_form(self, server_base_url):
        size = random.randint(16 * _SIZE_1_MB, 32 * _SIZE_1_MB)
        data = os.urandom(size)
        digest = hashlib.sha1(data).hexdigest()
        files = {
            'random': ('random.dat', data),
            'message': ('hello.txt', b'Hello, World!\n'),
        }

        resp = requests.post(
            server_base_url + 'forms', files=files, timeout=_REQUEST_TIMEOUT
        )
        assert resp.status_code == 200
        assert resp.json() == {
            'message': {
                'filename': 'hello.txt',
                'sha1': '60fde9c2310b0d4cad4dab8d126b04387efba289',
            },
            'random': {
                'filename': 'random.dat',
                'sha1': digest,
            },
        }

    def test_post_multiple(self, server_base_url):
        body = testing.rand_string(_SIZE_1_KB // 2, _SIZE_1_KB)
        resp = requests.post(server_base_url, data=body, timeout=_REQUEST_TIMEOUT)
        assert resp.status_code == 200
        assert resp.text == body
        assert resp.headers['X-Counter'] == '0'

        time.sleep(1)

        resp = requests.post(server_base_url, data=body, timeout=_REQUEST_TIMEOUT)
        assert resp.headers['X-Counter'] == '2002'

    def test_post_invalid_content_length(self, server_base_url):
        headers = {'Content-Length': 'invalid'}

        try:
            resp = requests.post(
                server_base_url, headers=headers, timeout=_REQUEST_TIMEOUT
            )

            # Daphne responds with a 400
            assert resp.status_code == 400

        except requests.ConnectionError:
            # NOTE(kgriffs): Uvicorn will kill the request so it does not
            #   even get to our app; the app logic is tested on the WSGI
            #   side. We leave this here in case something changes in
            #   the way uvicorn handles it or something and we want to
            #   get a heads-up if the request is no longer blocked.
            pass

    def test_post_read_bounded_stream(self, server_base_url):
        body = testing.rand_string(_SIZE_1_KB // 2, _SIZE_1_KB)
        resp = requests.post(
            server_base_url + 'bucket', data=body, timeout=_REQUEST_TIMEOUT
        )
        assert resp.status_code == 200
        assert resp.text == body

    def test_post_read_bounded_stream_large(self, server_base_url):
        """Test that we can correctly read large bodies chunked server-side.

        ASGI servers typically employ some type of flow control to stream
        large request bodies to the app. This occurs regardless of whether
        "chunked" Transfer-Encoding is employed by the client.
        """

        # NOTE(kgriffs): One would hope that flow control is effective enough
        #   to at least prevent bursting over 1 MB.
        size_mb = 5

        body = os.urandom(_SIZE_1_MB * size_mb)
        resp = requests.put(
            server_base_url + 'bucket/drops', data=body, timeout=_REQUEST_TIMEOUT
        )
        assert resp.status_code == 200
        assert resp.json().get('drops') > size_mb
        assert resp.json().get('sha1') == hashlib.sha1(body).hexdigest()

    def test_post_read_bounded_stream_no_body(self, server_base_url):
        resp = requests.post(server_base_url + 'bucket', timeout=_REQUEST_TIMEOUT)
        assert not resp.text

    def test_sse(self, server_base_url):
        resp = requests.get(server_base_url + 'events', timeout=_REQUEST_TIMEOUT)
        assert resp.status_code == 200

        events = resp.text.split('\n\n')
        assert len(events) > 2
        for e in events[:-1]:
            assert e == 'data: hello world'

        assert not events[-1]

    def test_sse_client_disconnects_early(self, server_base_url):
        """Test that when the client connection is lost, the server task does not hang.

        In the case of SSE, Falcon should detect when the client connection is
        lost and immediately bail out. Currently this is observable by watching
        the output of the uvicorn and daphne server processes. Also, the
        _run_server_isolated() method will fail the test if the server process
        takes too long to shut down.
        """
        with pytest.raises(requests.exceptions.ConnectionError):
            requests.get(
                server_base_url + 'events',
                timeout=(_asgi_test_app.SSE_TEST_MAX_DELAY_SEC / 2),
            )

    @pytest.mark.skipif(httpx is None, reason='httpx is required for this test')
    async def test_stream_chunked_request(self, server_base_url):
        """Regression test for https://github.com/falconry/falcon/issues/2024"""

        async def emitter():
            for _ in range(64):
                yield b'123456789ABCDEF\n'

        async with httpx.AsyncClient() as client:
            resp = await client.put(
                server_base_url + 'bucket/drops',
                content=emitter(),
                timeout=_REQUEST_TIMEOUT,
            )
            resp.raise_for_status()
            assert resp.json().get('drops') >= 1


@pytest.mark.skipif(
    requests is None, reason='requests module is required for this test'
)
@pytest.mark.skipif(
    websockets is None, reason='websockets is required for this test class'
)
class TestWebSocket:
    @pytest.mark.parametrize('explicit_close', [True, False])
    @pytest.mark.parametrize('close_code', [None, 4321])
    @pytest.mark.parametrize('max_receive_queue', [0, 4, 17])
    async def test_hello(
        self,
        explicit_close,
        close_code,
        max_receive_queue,
        server_base_url,
        server_url_events_ws,
    ):
        resp = requests.patch(
            server_base_url + 'wsoptions', json={'max_receive_queue': max_receive_queue}
        )
        resp.raise_for_status()

        echo_expected = 'Check 1 - \U0001f600'

        extra_headers = {'X-Command': 'recv'}

        if explicit_close:
            extra_headers['X-Close'] = 'True'

        if close_code:
            extra_headers['X-Close-Code'] = str(close_code)

        async with websockets.connect(
            server_url_events_ws,
            extra_headers=extra_headers,
        ) as ws:
            got_message = False

            while True:
                try:
                    # TODO: Why is this failing to decode on the other side?
                    #   (raises an error)
                    # TODO: Why does this cause Daphne to hang?
                    await ws.send(f'{{"command": "echo", "echo": "{echo_expected}"}}')

                    message_text = await ws.recv()
                    message_echo = await ws.recv()
                    message_binary = await ws.recv()
                except websockets.exceptions.ConnectionClosed as ex:
                    if explicit_close and close_code:
                        assert ex.rcvd.code == close_code
                    else:
                        assert ex.rcvd.code == 1000

                    break

                got_message = True
                assert message_text == 'hello world'
                assert message_echo == echo_expected
                assert message_binary == b'hello\x00world'

            assert got_message

    @pytest.mark.parametrize('explicit_close', [True, False])
    @pytest.mark.parametrize('close_code', [None, 4040])
    async def test_rejected(self, explicit_close, close_code, server_url_events_ws):
        extra_headers = {'X-Accept': 'reject'}
        if explicit_close:
            extra_headers['X-Close'] = 'True'

        if close_code:
            extra_headers['X-Close-Code'] = str(close_code)

        with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info:
            async with websockets.connect(
                server_url_events_ws, extra_headers=extra_headers
            ):
                pass

        assert exc_info.value.status_code == 403

    async def test_missing_responder(self, server_url_events_ws):
        server_url_events_ws += '/404'

        with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info:
            async with websockets.connect(server_url_events_ws):
                pass

        assert exc_info.value.status_code == 403

    @pytest.mark.parametrize(
        'subprotocol, expected',
        [
            ('*', 'amqp'),
            ('wamp', 'wamp'),
        ],
    )
    async def test_select_subprotocol_known(
        self, subprotocol, expected, server_url_events_ws
    ):
        extra_headers = {'X-Subprotocol': subprotocol}
        async with websockets.connect(
            server_url_events_ws,
            extra_headers=extra_headers,
            subprotocols=['amqp', 'wamp'],
        ) as ws:
            assert ws.subprotocol == expected

    async def test_select_subprotocol_unknown(self, server_url_events_ws):
        extra_headers = {'X-Subprotocol': 'xmpp'}

        try:
            async with websockets.connect(
                server_url_events_ws,
                extra_headers=extra_headers,
                subprotocols=['amqp', 'wamp'],
            ):
                pass

            # NOTE(kgriffs): Taking the approach of asserting inside
            #   except clauses is a little bit cleaner in this case vs.
            #   multiple pytest.raises(), so we fail the test if no
            #   error is raised as expected.
            pytest.fail('no error raised')

        # Uvicorn
        except websockets.exceptions.NegotiationError as ex:
            assert 'unsupported subprotocol: xmpp' in str(ex)

        # Daphne
        except websockets.exceptions.InvalidMessage:
            pass

    # NOTE(kgriffs): When executing this test under pytest with the -s
    #   argument, one should be able to see the message
    #   "on_websocket:WebSocketDisconnected" printed to the console. I have
    #   tried to capture this output and check it in the test below,
    #   but the usual ways of capturing stdout/stderr with pytest do
    #   not work.
    async def test_disconnecting_client_early(self, server_url_events_ws):
        ws = await websockets.connect(
            server_url_events_ws, extra_headers={'X-Close': 'True'}
        )
        await asyncio.sleep(0.2)

        message_text = await ws.recv()
        assert message_text == 'hello world'

        message_binary = await ws.recv()
        assert message_binary == b'hello\x00world'

        await ws.close()
        print('closed')

        # NOTE(kgriffs): Let the app continue to attempt to send us
        #   messages after the close.
        await asyncio.sleep(1)

    async def test_send_before_accept(self, server_url_events_ws):
        extra_headers = {'x-accept': 'skip'}

        async with websockets.connect(
            server_url_events_ws, extra_headers=extra_headers
        ) as ws:
            message = await ws.recv()
            assert message == 'OperationNotAllowed'

    async def test_recv_before_accept(self, server_url_events_ws):
        extra_headers = {'x-accept': 'skip', 'x-command': 'recv'}

        async with websockets.connect(
            server_url_events_ws, extra_headers=extra_headers
        ) as ws:
            message = await ws.recv()
            assert message == 'OperationNotAllowed'

    async def test_invalid_close_code(self, server_url_events_ws):
        extra_headers = {'x-close': 'True', 'x-close-code': 42}

        async with websockets.connect(
            server_url_events_ws, extra_headers=extra_headers
        ) as ws:
            start = time.time()

            while True:
                message = await asyncio.wait_for(ws.recv(), timeout=1)
                if message == 'ValueError':
                    break

                elapsed = time.time() - start
                assert elapsed < 2

    async def test_close_code_on_unhandled_error(self, server_url_events_ws):
        extra_headers = {'x-raise-error': 'generic'}

        async with websockets.connect(
            server_url_events_ws, extra_headers=extra_headers
        ) as ws:
            await ws.wait_closed()

        assert ws.close_code in {3011, 1011}

    async def test_close_code_on_unhandled_http_error(self, server_url_events_ws):
        extra_headers = {'x-raise-error': 'http'}

        async with websockets.connect(
            server_url_events_ws, extra_headers=extra_headers
        ) as ws:
            await ws.wait_closed()

        assert ws.close_code == 3400

    @pytest.mark.parametrize('mismatch', ['send', 'recv'])
    @pytest.mark.parametrize('mismatch_type', ['text', 'data'])
    async def test_type_mismatch(self, mismatch, mismatch_type, server_url_events_ws):
        extra_headers = {
            'X-Mismatch': mismatch,
            'X-Mismatch-Type': mismatch_type,
        }

        async with websockets.connect(
            server_url_events_ws, extra_headers=extra_headers
        ) as ws:
            if mismatch == 'recv':
                if mismatch_type == 'text':
                    await ws.send(b'hello')
                else:
                    await ws.send('hello')

            await ws.wait_closed()

        assert ws.close_code in {3011, 1011}

    async def test_passing_path_params(self, server_base_url_ws):
        expected_feed_id = '1ee7'
        url = f'{server_base_url_ws}feeds/{expected_feed_id}'

        async with websockets.connect(url) as ws:
            feed_id = await ws.recv()
            assert feed_id == expected_feed_id


@contextmanager
def _run_server_isolated(process_factory, host, port):
    # NOTE(kgriffs): We have to use subprocess because uvicorn has a tendency
    #   to corrupt our asyncio state and cause intermittent hangs in the test
    #   suite.
    print('\n[Starting server process...]')
    server = process_factory(host, port)

    yield server

    if _WIN32:
        # NOTE(kgriffs): Calling server.terminate() is equivalent to
        #   server.kill() on Windows. We don't want to do the this;
        #   forcefully killing a proc causes the CI job to fail,
        #   regardless of the tox/pytest exit code. """
        #
        #   Instead, we send CTRL+C. This does require that the handler be
        #   enabled via SetConsoleCtrlHandler() in _uvicorn_factory()
        #   below. Alternatively, we could send CTRL+BREAK and allow
        #   the process exit code to be 3221225786.
        #
        import signal

        print('\n[Sending CTRL+C (SIGINT) to server process...]')
        server.send_signal(signal.CTRL_C_EVENT)
        try:
            server.wait(timeout=10)
        except KeyboardInterrupt:
            pass
        except subprocess.TimeoutExpired:
            print('\n[Killing stubborn server process...]')

            server.kill()
            server.communicate()

            pytest.fail(
                'Server process did not exit in a timely manner and had to be killed.'
            )
    else:
        print('\n[Sending SIGTERM to server process...]')
        server.terminate()

        try:
            server.communicate(timeout=10)
        except subprocess.TimeoutExpired:
            print('\n[Killing stubborn server process...]')

            server.kill()
            server.communicate()

            pytest.fail(
                'Server process did not exit in a timely manner and had to be killed.'
            )


def _uvicorn_factory(host, port):
    if _WIN32:
        script = f"""
import uvicorn
import ctypes
ctypes.windll.kernel32.SetConsoleCtrlHandler(None, 0)
uvicorn.run('_asgi_test_app:application', host='{host}', port={port})
"""
        return subprocess.Popen(
            (sys.executable, '-c', script),
            cwd=_MODULE_DIR,
            creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
        )

    # NOTE(vytas): uvicorn+uvloop is not (well) supported on PyPy at the time
    #   of writing.
    loop_options = ('--http', 'h11', '--loop', 'asyncio') if _PYPY else ()
    options = (
        '--host',
        host,
        '--port',
        str(port),
        '--interface',
        'asgi3',
        '_asgi_test_app:application',
    )

    return subprocess.Popen(
        (
            sys.executable,
            '-m',
            'uvicorn',
        )
        + loop_options
        + options,
        cwd=_MODULE_DIR,
    )


def _daphne_factory(host, port):
    return subprocess.Popen(
        (
            sys.executable,
            '-m',
            'daphne',
            '--bind',
            host,
            '--port',
            str(port),
            '--verbosity',
            '2',
            '--access-log',
            '-',
            '_asgi_test_app:application',
        ),
        cwd=_MODULE_DIR,
    )


def _hypercorn_factory(host, port):
    if _WIN32:
        script = f"""
from hypercorn.run import Config, run
import ctypes
ctypes.windll.kernel32.SetConsoleCtrlHandler(None, 0)
config = Config()
config.application_path = '_asgi_test_app:application'
config.bind = ['{host}:{port}']
config.accesslog = '-'
config.debug = True
run(config)
"""
        return subprocess.Popen(
            (sys.executable, '-c', script),
            cwd=_MODULE_DIR,
            creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
        )
    return subprocess.Popen(
        (
            sys.executable,
            '-m',
            'hypercorn',
            '--bind',
            f'{host}:{port}',
            '--access-logfile',
            '-',
            '--debug',
            '_asgi_test_app:application',
        ),
        cwd=_MODULE_DIR,
    )


def _can_run(factory):
    if _WIN32 and factory == _daphne_factory:
        pytest.skip('daphne does not support windows')

    if factory == _daphne_factory:
        try:
            import daphne  # noqa
        except Exception:
            pytest.skip('daphne not installed')
    elif factory == _hypercorn_factory:
        try:
            import hypercorn  # noqa
        except Exception:
            pytest.skip('hypercorn not installed')
    elif factory == _uvicorn_factory:
        try:
            import uvicorn  # noqa
        except Exception:
            pytest.skip('uvicorn not installed')


@pytest.fixture(params=[_uvicorn_factory, _daphne_factory, _hypercorn_factory])
def server_base_url(request):
    process_factory = request.param
    _can_run(process_factory)

    for i in range(3):
        server_port = testing.get_unused_port()
        base_url = 'http://{}:{}/'.format(_SERVER_HOST, server_port)

        with _run_server_isolated(process_factory, _SERVER_HOST, server_port) as server:
            # NOTE(kgriffs): Let the server start up. Give up after 5 seconds.
            start_ts = time.time()
            while (time.time() - start_ts) < 5:
                try:
                    requests.get(base_url, timeout=0.2)
                except (
                    requests.exceptions.Timeout,
                    requests.exceptions.ConnectionError,
                ):
                    time.sleep(0.2)
                else:
                    break
            else:
                if server.poll() is None:
                    pytest.fail('Server is not responding to requests')
                else:
                    # NOTE(kgriffs): The server did not start up; probably due to
                    #   the port being in use. We could check the output but
                    #   capsys fixture may not have buffered the error output
                    #   yet, so we just retry.
                    continue

            yield base_url

        # NOTE(vytas): Starting with 0.29.0, Uvicorn will propagate signal
        #   values into the return code (which is a good practice in Unix);
        #   see also https://github.com/encode/uvicorn/pull/1600
        assert server.returncode in (0, -signal.SIGTERM, _STATUS_CONTROL_C_EXIT)

        break

    else:
        pytest.fail('Could not start server')


@pytest.fixture
def server_base_url_ws(server_base_url):
    return server_base_url.replace('http', 'ws')


@pytest.fixture
def server_url_events_ws(server_base_url_ws):
    return server_base_url_ws + 'events'