summaryrefslogtreecommitdiff
path: root/pecan/tests/test_generic.py
blob: 19127fcc8b70873b933e82db8c1386c3288b71ed (plain)
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
from webtest import TestApp
try:
    from simplejson import dumps
except:
    from json import dumps  # noqa

from six import b as b_

from pecan import Pecan, expose, abort
from pecan.tests import PecanTestCase


class TestGeneric(PecanTestCase):

    def test_simple_generic(self):
        class RootController(object):
            @expose(generic=True)
            def index(self):
                pass

            @index.when(method='POST', template='json')
            def do_post(self):
                return dict(result='POST')

            @index.when(method='GET')
            def do_get(self):
                return 'GET'

        app = TestApp(Pecan(RootController()))
        r = app.get('/')
        assert r.status_int == 200
        assert r.body == b_('GET')

        r = app.post('/')
        assert r.status_int == 200
        assert r.body == b_(dumps(dict(result='POST')))

        r = app.get('/do_get', status=404)
        assert r.status_int == 404

    def test_generic_allow_header(self):
        class RootController(object):
            @expose(generic=True)
            def index(self):
                abort(405)

            @index.when(method='POST', template='json')
            def do_post(self):
                return dict(result='POST')

            @index.when(method='GET')
            def do_get(self):
                return 'GET'

            @index.when(method='PATCH')
            def do_patch(self):
                return 'PATCH'

        app = TestApp(Pecan(RootController()))
        r = app.delete('/', expect_errors=True)
        assert r.status_int == 405
        assert r.headers['Allow'] == 'GET, PATCH, POST'

    def test_nested_generic(self):

        class SubSubController(object):
            @expose(generic=True)
            def index(self):
                return 'GET'

            @index.when(method='DELETE', template='json')
            def do_delete(self, name, *args):
                return dict(result=name, args=', '.join(args))

        class SubController(object):
            sub = SubSubController()

        class RootController(object):
            sub = SubController()

        app = TestApp(Pecan(RootController()))
        r = app.get('/sub/sub/')
        assert r.status_int == 200
        assert r.body == b_('GET')

        r = app.delete('/sub/sub/joe/is/cool')
        assert r.status_int == 200
        assert r.body == b_(dumps(dict(result='joe', args='is, cool')))