• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# (c) 2005 Ian Bicking, Clark C. Evans and contributors
2# This module is part of the Python Paste Project and is released under
3# the MIT License: http://www.opensource.org/licenses/mit-license.php
4"""
5WSGI Exception Middleware
6
7Regression Test Suite
8"""
9from nose.tools import assert_raises
10from paste.httpexceptions import *
11from paste.response import header_value
12import six
13
14
15def test_HTTPMove():
16    """ make sure that location is a mandatory attribute of Redirects """
17    assert_raises(AssertionError, HTTPFound)
18    assert_raises(AssertionError, HTTPTemporaryRedirect,
19                   headers=[('l0cation','/bing')])
20    assert isinstance(HTTPMovedPermanently("This is a message",
21                          headers=[('Location','/bing')])
22                     ,HTTPRedirection)
23    assert isinstance(HTTPUseProxy(headers=[('LOCATION','/bing')])
24                     ,HTTPRedirection)
25    assert isinstance(HTTPFound('/foobar'),HTTPRedirection)
26
27def test_badapp():
28    """ verify that the middleware handles previously-started responses """
29    def badapp(environ, start_response):
30        start_response("200 OK",[])
31        raise HTTPBadRequest("Do not do this at home.")
32    newapp = HTTPExceptionHandler(badapp)
33    assert b'Bad Request' in b''.join(newapp({'HTTP_ACCEPT': 'text/html'},
34                                             (lambda a, b, c=None: None)))
35
36def test_unicode():
37    """ verify unicode output """
38    tstr = u"\0xCAFE"
39    def badapp(environ, start_response):
40        start_response("200 OK",[])
41        raise HTTPBadRequest(tstr)
42    newapp = HTTPExceptionHandler(badapp)
43    assert tstr.encode("utf-8") in b''.join(newapp({'HTTP_ACCEPT':
44                                         'text/html'},
45                                         (lambda a, b, c=None: None)))
46    assert tstr.encode("utf-8") in b''.join(newapp({'HTTP_ACCEPT':
47                                         'text/plain'},
48                                         (lambda a, b, c=None: None)))
49
50def test_template():
51    """ verify that html() and plain() output methods work """
52    e = HTTPInternalServerError()
53    e.template = 'A %(ping)s and <b>%(pong)s</b> message.'
54    assert str(e).startswith("500 Internal Server Error")
55    assert e.plain({'ping': 'fun', 'pong': 'happy'}) == (
56        '500 Internal Server Error\r\n'
57        'A fun and happy message.\r\n')
58    assert '<p>A fun and <b>happy</b> message.</p>' in \
59           e.html({'ping': 'fun', 'pong': 'happy'})
60
61def test_redapp():
62    """ check that redirect returns the correct, expected results """
63    saved = []
64    def saveit(status, headers, exc_info = None):
65        saved.append((status,headers))
66    def redapp(environ, start_response):
67        raise HTTPFound("/bing/foo")
68    app = HTTPExceptionHandler(redapp)
69    result = list(app({'HTTP_ACCEPT': 'text/html'},saveit))
70    assert b'<a href="/bing/foo">' in result[0]
71    assert "302 Found" == saved[0][0]
72    if six.PY3:
73        assert "text/html; charset=utf8" == header_value(saved[0][1], 'content-type')
74    else:
75        assert "text/html" == header_value(saved[0][1], 'content-type')
76    assert "/bing/foo" == header_value(saved[0][1],'location')
77    result = list(app({'HTTP_ACCEPT': 'text/plain'},saveit))
78    assert "text/plain; charset=utf8" == header_value(saved[1][1],'content-type')
79    assert "/bing/foo" == header_value(saved[1][1],'location')
80
81def test_misc():
82    assert get_exception(301) == HTTPMovedPermanently
83    redirect = HTTPFound("/some/path")
84    assert isinstance(redirect,HTTPException)
85    assert isinstance(redirect,HTTPRedirection)
86    assert not isinstance(redirect,HTTPError)
87    notfound = HTTPNotFound()
88    assert isinstance(notfound,HTTPException)
89    assert isinstance(notfound,HTTPError)
90    assert isinstance(notfound,HTTPClientError)
91    assert not isinstance(notfound,HTTPServerError)
92    notimpl = HTTPNotImplemented()
93    assert isinstance(notimpl,HTTPException)
94    assert isinstance(notimpl,HTTPError)
95    assert isinstance(notimpl,HTTPServerError)
96    assert not isinstance(notimpl,HTTPClientError)
97
98