File: test_wsgi_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 (301 lines) | stat: -rw-r--r-- 8,723 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
import hashlib
import os
import random
import subprocess
import sys
import time

import pytest

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

from falcon import testing

_HERE = os.path.abspath(os.path.dirname(__file__))
_SERVER_HOST = '127.0.0.1'
_SIZE_1_KB = 1024
_SIZE_1_MB = _SIZE_1_KB**2

_REQUEST_TIMEOUT = 10
_STARTUP_TIMEOUT = 10
_SHUTDOWN_TIMEOUT = 20


def _gunicorn_args(host, port, extra_opts=()):
    """Gunicorn"""
    try:
        import gunicorn  # noqa: F401
    except ImportError:
        pytest.skip('gunicorn not installed')

    args = (
        sys.executable,
        '-m',
        'gunicorn',
        '--access-logfile',
        '-',
        '--bind',
        '{}:{}'.format(host, port),
        # NOTE(vytas): Although rare, but Meinheld workers have been noticed to
        #   occasionally hang on shutdown.
        '--graceful-timeout',
        str(_SHUTDOWN_TIMEOUT // 2),
        # NOTE(vytas): In case a worker hangs for an unexpectedly long time
        #   while reading or processing request (the default value is 30).
        '--timeout',
        str(_REQUEST_TIMEOUT),
    )
    return args + extra_opts + ('_wsgi_test_app:app',)


def _meinheld_args(host, port):
    """Gunicorn + Meinheld"""
    try:
        import meinheld  # noqa: F401
    except ImportError:
        pytest.skip('meinheld not installed')

    return _gunicorn_args(
        host,
        port,
        (
            '--workers',
            '2',
            '--worker-class',
            'egg:meinheld#gunicorn_worker',
        ),
    )


def _uvicorn_args(host, port):
    """Uvicorn (WSGI interface)"""
    try:
        import uvicorn  # noqa: F401
    except ImportError:
        pytest.skip('uvicorn not installed')

    return (
        sys.executable,
        '-m',
        'uvicorn',
        '--host',
        host,
        '--port',
        str(port),
        '--interface',
        'wsgi',
        '_wsgi_test_app:app',
    )


def _uwsgi_args(host, port):
    """uWSGI"""
    return (
        'uwsgi',
        '--http',
        '{}:{}'.format(host, port),
        '--wsgi-file',
        '_wsgi_test_app.py',
    )


def _waitress_args(host, port):
    """Waitress"""
    try:
        import waitress  # noqa: F401
    except ImportError:
        pytest.skip('waitress not installed')

    return (
        sys.executable,
        '-m',
        'waitress',
        '--listen',
        '{}:{}'.format(host, port),
        '_wsgi_test_app:app',
    )


@pytest.fixture(params=['gunicorn', 'meinheld', 'uvicorn', 'uwsgi', 'waitress'])
def wsgi_server(request):
    return request.param


@pytest.fixture
def server_args(wsgi_server):
    servers = {
        'gunicorn': _gunicorn_args,
        'meinheld': _meinheld_args,
        'uvicorn': _uvicorn_args,
        'uwsgi': _uwsgi_args,
        'waitress': _waitress_args,
    }
    return servers[wsgi_server]


@pytest.fixture
def server_url(server_args):
    if sys.platform.startswith('win'):
        pytest.skip('WSGI server tests are currently unsupported on Windows')

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

        args = server_args(_SERVER_HOST, server_port)
        print('Starting {}...'.format(server_args.__doc__))
        print(' '.join(args))
        try:
            server = subprocess.Popen(args, cwd=_HERE)
        except FileNotFoundError:
            pytest.skip('{} executable is not installed'.format(args[0]))

        # NOTE(vytas): give the app server some time to start.
        start_time = time.time()
        while time.time() - start_time < _STARTUP_TIMEOUT:
            try:
                requests.get(base_url + '/hello', 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
        break

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

    print('\n[Sending SIGTERM to server process...]')
    server.terminate()

    try:
        server.communicate(timeout=_SHUTDOWN_TIMEOUT)
    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.'
        )


@pytest.mark.skipif(
    requests is None, reason='requests module is required for this test'
)
class TestWSGIServer:
    def test_get(self, server_url):
        resp = requests.get(server_url + '/hello', timeout=_REQUEST_TIMEOUT)
        assert resp.status_code == 200
        assert resp.text == 'Hello, World!\n'
        assert resp.headers.get('Content-Type') == 'text/plain; charset=utf-8'
        assert resp.headers.get('X-Falcon') == 'peregrine'

    def test_get_deprecated(self, server_url):
        resp = requests.get(server_url + '/deprecated', timeout=_REQUEST_TIMEOUT)

        # Since it tries to use resp.add_link() we expect an unhandled error
        assert resp.status_code == 500

    def test_post_multipart_form(self, server_url):
        size = random.randint(8 * _SIZE_1_MB, 15 * _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_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_static_file(self, server_url):
        resp = requests.get(
            server_url + '/tests/test_wsgi_servers.py', timeout=_REQUEST_TIMEOUT
        )
        assert resp.status_code == 200

        # TODO(vytas): In retrospect, it would be easier to maintain these
        #   static route tests by creating a separate file instead of relying
        #   on the content of this same __file__.
        assert resp.text.startswith(
            'import hashlib\n'
            'import os\n'
            'import random\n'
            'import subprocess\n'
            'import sys\n'
            'import time\n'
        )
        assert resp.headers.get('Content-Disposition') == (
            'attachment; filename="test_wsgi_servers.py"'
        )

        content_length = int(resp.headers['Content-Length'])
        file_size = os.path.getsize(__file__)
        assert len(resp.content) == content_length == file_size

    @pytest.mark.parametrize(
        'byte_range,expected_head',
        [
            ('7-', b'hashlib'),
            ('2-6', b'port'),
            ('32-38', b'random'),
            ('-47', b'The content of this comment is part of a test.\n'),
        ],
    )
    def test_static_file_byte_range(
        self, byte_range, expected_head, wsgi_server, server_url
    ):
        if wsgi_server == 'meinheld':
            pytest.xfail(
                "Meinheld's file_wrapper fails without a fileno(), see also: "
                'https://github.com/mopemope/meinheld/issues/130'
            )

        resp = requests.get(
            server_url + '/tests/test_wsgi_servers.py',
            timeout=_REQUEST_TIMEOUT,
            headers={'Range': 'bytes=' + byte_range},
        )

        assert resp.status_code == 206
        assert resp.content.startswith(expected_head)

        content_length = int(resp.headers['Content-Length'])
        assert len(resp.content) == content_length

        file_size = os.path.getsize(__file__)
        content_range_size = int(resp.headers['Content-Range'].split('/')[-1])
        assert file_size == content_range_size

        # TODO(vytas): In retrospect, it would be easier to maintain these
        #   static route tests by creating a separate file instead of relying
        #   on the content of this same __file__.

        # NOTE(vytas): The content of this comment is part of a test.