File: test_wsgiutils.py

package info (click to toggle)
pesto 16-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 568 kB
  • ctags: 734
  • sloc: python: 4,386; makefile: 69
file content (436 lines) | stat: -rw-r--r-- 12,791 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
# vim: set fileencoding=utf-8 :
# Copyright (c) 2007-2009 Oliver Cope. All rights reserved.
# See LICENSE.txt for terms of redistribution and use.

from nose.tools import assert_equal

import pesto
from pesto.request import Request
from pesto.response import Response
from pesto.wsgiutils import mount_app, use_x_forwarded, make_uri_component, make_query, overlay, with_request_args, ClosingIterator, StartResponseWrapper
from pesto.testing import TestApp, make_environ
from pesto.core import PestoWSGIApplication, to_wsgi

def test_mountapp_match_order():
    """
    Regression test for bug where paths were matched in an arbitrary order,
    rather than testing the most specific paths first
    """
    def app1(e, sr):
        sr('200 OK', [('Content-Type', 'text/plain')])
        return ["app1"]

    def app2(e, sr):
        sr('200 OK', [('Content-Type', 'text/plain')])
        return ["app2"]

    m = mount_app({
        '/' : app1,
        '/a' : app2,
    })

    assert_equal(
        TestApp(m).get(SCRIPT_NAME='', PATH_INFO='/').body, "app1"
    )
    assert_equal(
        TestApp(m).get(SCRIPT_NAME='', PATH_INFO='/a').body, "app2"
    )

    m = mount_app({
        '/' : app2,
        '/a' : app1,
    })
    assert_equal(
        TestApp(m).get(SCRIPT_NAME='/', PATH_INFO='').body, "app2"
    )
    assert_equal(
        TestApp(m).get(SCRIPT_NAME='/', PATH_INFO='a').body, "app1"
    )

def test_mountapp_script_name_path_info():
    """
    Check that mount_app correctly sets the SCRIPT_NAME and PATH_INFO variables
    """
    def app1(e, sr):
        sr('200 OK', [('Content-Type', 'text/plain')])
        return ["1", e["SCRIPT_NAME"], e["PATH_INFO"]]
    def app2(e, sr):
        sr('200 OK', [('Content-Type', 'text/plain')])
        return ["2", e["SCRIPT_NAME"], e["PATH_INFO"]]
    m = mount_app({
        '/app1' : app1,
        '/app2' : app2,
    })

    assert_equal(
        TestApp(m).get(SCRIPT_NAME='/a', PATH_INFO='/app1').content,
        ["1", "/a/app1", ""]
    )

    assert_equal(
        TestApp(m).get(SCRIPT_NAME='/a', PATH_INFO='/app2').content,
        ["2", "/a/app2", ""]
    )

def test_use_x_forwarded_no_forwarding():

    def app(e, sr):
        sr('200 OK', [('Content-Type', 'text/plain')])
        return [ Request(e).request_uri, Request(e).remote_addr ]

    app = use_x_forwarded(trusted=['127.0.0.1'])(app)

    # Without the HTTP_X_FORWARDED headers, we should get back the original URI + remote address
    assert_equal(
        TestApp(app).get(HTTP_HOST='127.0.0.1:1234', REMOTE_ADDR='4.3.2.1').content,
        ['http://127.0.0.1:1234/', '4.3.2.1']
    )

def test_use_x_forwarded_forward_host():

    def app(e, sr):
        sr('200 OK', [('Content-Type', 'text/plain')])
        return [ Request(e).request_uri, Request(e).remote_addr ]

    app = use_x_forwarded(trusted=['127.0.0.1'])(app)

    # With HTTP_X_FORWARDED_HOST from a trusted IP, should override SERVER_NAME and SERVER_PORT
    assert_equal(
        TestApp(app).get(HTTP_HOST='127.0.0.1:1234', REMOTE_ADDR='127.0.0.1', HTTP_X_FORWARDED_HOST='example.org:80').content,
        ['http://example.org/', '127.0.0.1']
    )

def test_use_x_forwarded_forward_host_ssl():

    def app(e, sr):
        sr('200 OK', [('Content-Type', 'text/plain')])
        return [ Request(e).request_uri, Request(e).remote_addr ]

    app = use_x_forwarded(trusted=['127.0.0.1'])(app)

    # With HTTP_X_FORWARDED_HOST from a trusted IP, should override SERVER_NAME and SERVER_PORT
    assert_equal(
        TestApp(app).get(
            HTTP_HOST='127.0.0.1:1234',
            REMOTE_ADDR='127.0.0.1',
            HTTP_X_FORWARDED_HOST='example.org',
            HTTP_X_FORWARDED_SSL='on',
        ).content,
        ['https://example.org/', '127.0.0.1']
    )

def test_use_x_forwarded_forward_host_nonstandard_port():

    def app(e, sr):
        sr('200 OK', [('Content-Type', 'text/plain')])
        return [ Request(e).request_uri, Request(e).remote_addr ]

    app = use_x_forwarded(trusted=['127.0.0.1'])(app)

    assert_equal(
        TestApp(app).get(
            HTTP_HOST='127.0.0.1:1234',
            REMOTE_ADDR='127.0.0.1',
            HTTP_X_FORWARDED_HOST='example.org:8080',
        ).content,
        ['http://example.org:8080/', '127.0.0.1']
    )

def test_use_x_forwarded_forward_host_ssl_nonstandard_port():

    def app(e, sr):
        sr('200 OK', [('Content-Type', 'text/plain')])
        return [ Request(e).request_uri, Request(e).remote_addr ]

    app = use_x_forwarded(trusted=['127.0.0.1'])(app)

    # With HTTP_X_FORWARDED_HOST from a trusted IP, should override SERVER_NAME and SERVER_PORT
    assert_equal(
        TestApp(app).get(
            '/',
            SERVER_NAME='127.0.0.1',
            SERVER_PORT='1234',
            REMOTE_ADDR='127.0.0.1',
            HTTP_X_FORWARDED_HOST='example.org:8080',
            HTTP_X_FORWARDED_SSL='on'
        ).content,
        ['https://example.org:8080/', '127.0.0.1']
    )


def test_use_x_forwarded_forward_remote_addr():

    def app(e, sr):
        sr('200 OK', [('Content-Type', 'text/plain')])
        return [ Request(e).request_uri, Request(e).remote_addr ]

    app = use_x_forwarded(trusted=['127.0.0.1'])(app)

    # With HTTP_X_FORWARDED_HOST from a trusted IP, should override SERVER_NAME and SERVER_PORT
    assert_equal(
        TestApp(app).get(
            SERVER_NAME='127.0.0.1',
            SERVER_PORT='1234',
            REMOTE_ADDR='127.0.0.1',
            HTTP_X_FORWARDED_HOST='example.org',
            HTTP_X_FORWARDED_FOR='4.3.2.1'
        ).content,
        ['http://example.org/', '4.3.2.1']
    )

def test_unicode():
    assert make_uri_component(u"Arvo Pärt") == "arvo-part"

def test_make_query():
    assert make_query(a='1', b=2) == 'a=1;b=2'
    assert make_query(a='one two three') == 'a=one+two+three'
    assert make_query(a=['one', 'two', 'three']) == 'a=one;a=two;a=three'

alpha = u'\u03b1' # Greek alpha
beta = u'\u03b2' # Greek beta
gamma = u'\u03b3' # Greek gamma

def test_make_query_unicode():
    assert make_query(a=[alpha, beta, gamma], charset='utf8') == 'a=%CE%B1;a=%CE%B2;a=%CE%B3'

def test_make_query_unicode_default_encoding():
    assert make_query(a=[alpha, beta, gamma], charset='utf8') == make_query(a=[alpha, beta, gamma])

def test_overlay_app():

    def app1(environ, start_response):
        request = Request(environ)
        if request.path_info == '/app1':
            return Response(['app1 response'])(environ, start_response)
        return Response(['not found'], status=404)(environ, start_response)

    def app2(environ, start_response):
        request = Request(environ)
        if request.path_info == '/app2':
            return Response(['app2 response'])(environ, start_response)
        return Response(['not found'], status=404)(environ, start_response)

    app = TestApp(overlay(app1, app2))
    assert_equal(app.get('/app1').content, ['app1 response'])
    assert_equal(app.get('/app2').content, ['app2 response'])
    assert_equal(app.get('/app3').status, '404 Not Found')

def test_withargs_dispatch_args():

        dispatcher = pesto.dispatcher_app()

        @dispatcher.match(r'/<arg1:unicode>/<arg2:unicode>', 'GET')
        @with_request_args(arg1=unicode, arg2=int)
        def app(request, arg1, arg2):
            return Response([
                'Received %r:%s, %r:%s' % (arg1, type(arg1).__name__, arg2, type(arg2).__name__)
            ])


        assert_equal(
            TestApp(dispatcher).get('/foo/29').body,
            "Received u'foo':unicode, 29:int"
        )

def test_withargs_query_args():

        @to_wsgi
        @with_request_args(arg1=unicode, arg2=int)
        def app(request, arg1, arg2):
            return Response([
                'Received %r:%s, %r:%s' % (arg1, type(arg1).__name__, arg2, type(arg2).__name__)
            ])

        assert_equal(
            TestApp(app).get(QUERY_STRING='arg1=foo;arg2=29').body,
            "Received u'foo':unicode, 29:int"
        )

def test_withargs_missing_args():

        @to_wsgi
        @with_request_args(arg1=unicode, arg2=int)
        def app(request, arg1, arg2):
            return Response([
                'Received %r:%s, %r:%s' % (arg1, type(arg1).__name__, arg2, type(arg2).__name__)
            ])

        try:
            TestApp(app).get(QUERY_STRING='arg1=foo').status,
        except KeyError, e:
            assert_equal(e.args, ('arg2',))
        else:
            raise AssertionError("KeyError expected but not raised")

        @to_wsgi
        @with_request_args(arg1=unicode, arg2=int)
        def app(request, arg1, arg2=None):
            return Response([
                'Received %r:%s, %r:%s' % (arg1, type(arg1).__name__, arg2, type(arg2).__name__)
            ])

        response = TestApp(app).get(QUERY_STRING='arg1=foo')
        assert_equal(response.status, '200 OK')
        assert_equal(response.body, "Received u'foo':unicode, None:NoneType")

def test_closingiterator():

    class TestException(Exception):
        """
        An exception to test with
        """
    mock_environ = make_environ()
    def mock_start_response(status, headers):
        pass

    def app(environ, start_response):
        start_response('200 OK', [('Content-Type: text/plain')])
        yield "Foo"
        yield "Bar"

    def app_with_exception(environ, start_response):
        start_response('200 OK', [('Content-Type: text/plain')])
        yield "Foo"
        raise TestException()

    def test_close(app):
        l = []
        def close():
            l.append(1)
        app = app(mock_environ, mock_start_response)
        app = ClosingIterator(app, close)
        try:
            try:
                for i in app:
                    pass
            finally:
                app.close()
        except TestException:
            pass
        assert_equal(l, [1])

    def test_close2(app):
        l = []
        m = MockWSGI()
        def close():
            l.append(1)
        def close2():
            l.append(2)
        app = app(mock_environ, mock_start_response)
        app = ClosingIterator(app, close, close2)
        try:
            try:
                for i in app:
                    pass
            finally:
                app.close()
        except TestException:
            pass
        assert_equal(l, [1, 2])

    test_close(app)
    test_close(app_with_exception)

def test_StartResponseWrapper_write():

    def wsgiapp(environ, start_response):
        start_response = StartResponseWrapper(start_response)
        write = start_response('200 OK', [('X-We-All-Adora', 'Kia-Ora'), ('Content-Type', 'text/plain')])

        write('cat')
        write('sat')

        write2 = start_response.call_start_response()

        write2('mat')
        return []

    assert_equal(TestApp(wsgiapp).get('/').content, ['catsatmat'])


def test_ClosingItertor_with_exception():

    class TestException(Exception):
        pass

    @PestoWSGIApplication
    def app(request):
        raise TestException()
        return Response(['foobar'])

    l = []
    def close():
        l.append(1)

    def middleware(app):
        def middleware(environ, start_response):
            return ClosingIterator(app(environ, start_response), close)
        return middleware
    app = middleware(app)
    try:
        TestApp(app).get('/')
    except TestException:
        pass

    assert_equal(l, [1])

def test_pesto_app_runs_on_first_iteration():

    l = []
    @PestoWSGIApplication
    def app(request):
        l.append(1)
        return Response(['foobar'])

    mock_environ = make_environ()
    def mock_start_response(status, headers):
        pass

    response_iterator = app(mock_environ, mock_start_response)
    assert_equal(l, [])

    response_iterator.next()
    assert_equal(l, [1])

    response_iterator.close()

def test_pesto_dispatcher_app_runs_on_first_iteration():

    l = []
    dispatcher = pesto.dispatcher_app()

    mock_environ = make_environ()
    def mock_start_response(status, headers):
        pass

    @dispatcher.match('/', 'GET')
    def app(request):
        l.append(1)
        return Response(['foobar'])

    response_iterator = dispatcher(mock_environ, mock_start_response)
    assert_equal(l, [])

    response_iterator.next()
    assert_equal(l, [1])

    response_iterator.close()

def test_script_name_returned_from_requests_via_a_mount_app():

    def app(request):
        return Response([request.script_name], content_type='text/plain')

    m = mount_app({
        '/a' : to_wsgi(app),
        '/b' : to_wsgi(app),
    })

    assert_equal(
        TestApp(m).get(SCRIPT_NAME='', PATH_INFO='/a').body, "/a"
    )
    assert_equal(
        TestApp(m).get(SCRIPT_NAME='', PATH_INFO='/b').body, "/b"
    )