summaryrefslogtreecommitdiff
path: root/cherrypy/test/test_config.py
blob: 491321ddaf9b2daacde219670c51506dd60f1078 (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
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
"""Tests for the CherryPy configuration system."""

import os
import sys
import unittest

import cherrypy
import cherrypy._cpcompat as compat

localDir = os.path.join(os.getcwd(), os.path.dirname(__file__))


def setup_server():

    class Root:

        _cp_config = {'foo': 'this',
                      'bar': 'that'}

        def __init__(self):
            cherrypy.config.namespaces['db'] = self.db_namespace

        def db_namespace(self, k, v):
            if k == "scheme":
                self.db = v

        # @cherrypy.expose(alias=('global_', 'xyz'))
        def index(self, key):
            return cherrypy.request.config.get(key, "None")
        index = cherrypy.expose(index, alias=('global_', 'xyz'))

        def repr(self, key):
            return repr(cherrypy.request.config.get(key, None))
        repr.exposed = True

        def dbscheme(self):
            return self.db
        dbscheme.exposed = True

        def plain(self, x):
            return x
        plain.exposed = True
        plain._cp_config = {'request.body.attempt_charsets': ['utf-16']}

        favicon_ico = cherrypy.tools.staticfile.handler(
            filename=os.path.join(localDir, '../favicon.ico'))

    class Foo:

        _cp_config = {'foo': 'this2',
                      'baz': 'that2'}

        def index(self, key):
            return cherrypy.request.config.get(key, "None")
        index.exposed = True
        nex = index

        def silly(self):
            return 'Hello world'
        silly.exposed = True
        silly._cp_config = {'response.headers.X-silly': 'sillyval'}

        # Test the expose and config decorators
        #@cherrypy.expose
        #@cherrypy.config(foo='this3', **{'bax': 'this4'})
        def bar(self, key):
            return repr(cherrypy.request.config.get(key, None))
        bar.exposed = True
        bar._cp_config = {'foo': 'this3', 'bax': 'this4'}

    class Another:

        def index(self, key):
            return str(cherrypy.request.config.get(key, "None"))
        index.exposed = True

    def raw_namespace(key, value):
        if key == 'input.map':
            handler = cherrypy.request.handler

            def wrapper():
                params = cherrypy.request.params
                for name, coercer in list(value.items()):
                    try:
                        params[name] = coercer(params[name])
                    except KeyError:
                        pass
                return handler()
            cherrypy.request.handler = wrapper
        elif key == 'output':
            handler = cherrypy.request.handler

            def wrapper():
                # 'value' is a type (like int or str).
                return value(handler())
            cherrypy.request.handler = wrapper

    class Raw:

        _cp_config = {'raw.output': repr}

        def incr(self, num):
            return num + 1
        incr.exposed = True
        incr._cp_config = {'raw.input.map': {'num': int}}

    if not compat.py3k:
        thing3 = "thing3: unicode('test', errors='ignore')"
    else:
        thing3 = ''

    ioconf = compat.StringIO("""
[/]
neg: -1234
filename: os.path.join(sys.prefix, "hello.py")
thing1: cherrypy.lib.httputil.response_codes[404]
thing2: __import__('cherrypy.tutorial', globals(), locals(), ['']).thing2
%s
complex: 3+2j
mul: 6*3
ones: "11"
twos: "22"
stradd: %%(ones)s + %%(twos)s + "33"

[/favicon.ico]
tools.staticfile.filename = %r
""" % (thing3, os.path.join(localDir, 'static/dirback.jpg')))

    root = Root()
    root.foo = Foo()
    root.raw = Raw()
    app = cherrypy.tree.mount(root, config=ioconf)
    app.request_class.namespaces['raw'] = raw_namespace

    cherrypy.tree.mount(Another(), "/another")
    cherrypy.config.update({'luxuryyacht': 'throatwobblermangrove',
                            'db.scheme': r"sqlite///memory",
                            })


#                             Client-side code                             #

from cherrypy.test import helper


class ConfigTests(helper.CPWebCase):
    setup_server = staticmethod(setup_server)

    def testConfig(self):
        tests = [
            ('/',        'nex', 'None'),
            ('/',        'foo', 'this'),
            ('/',        'bar', 'that'),
            ('/xyz',     'foo', 'this'),
            ('/foo/',    'foo', 'this2'),
            ('/foo/',    'bar', 'that'),
            ('/foo/',    'bax', 'None'),
            ('/foo/bar', 'baz', "'that2'"),
            ('/foo/nex', 'baz', 'that2'),
            # If 'foo' == 'this', then the mount point '/another' leaks into
            # '/'.
            ('/another/', 'foo', 'None'),
        ]
        for path, key, expected in tests:
            self.getPage(path + "?key=" + key)
            self.assertBody(expected)

        expectedconf = {
            # From CP defaults
            'tools.log_headers.on': False,
            'tools.log_tracebacks.on': True,
            'request.show_tracebacks': True,
            'log.screen': False,
            'environment': 'test_suite',
            'engine.autoreload.on': False,
            # From global config
            'luxuryyacht': 'throatwobblermangrove',
            # From Root._cp_config
            'bar': 'that',
            # From Foo._cp_config
            'baz': 'that2',
            # From Foo.bar._cp_config
            'foo': 'this3',
            'bax': 'this4',
        }
        for key, expected in expectedconf.items():
            self.getPage("/foo/bar?key=" + key)
            self.assertBody(repr(expected))

    def testUnrepr(self):
        self.getPage("/repr?key=neg")
        self.assertBody("-1234")

        self.getPage("/repr?key=filename")
        self.assertBody(repr(os.path.join(sys.prefix, "hello.py")))

        self.getPage("/repr?key=thing1")
        self.assertBody(repr(cherrypy.lib.httputil.response_codes[404]))

        if not getattr(cherrypy.server, "using_apache", False):
            # The object ID's won't match up when using Apache, since the
            # server and client are running in different processes.
            self.getPage("/repr?key=thing2")
            from cherrypy.tutorial import thing2
            self.assertBody(repr(thing2))

        if not compat.py3k:
            self.getPage("/repr?key=thing3")
            self.assertBody(repr(unicode('test')))

        self.getPage("/repr?key=complex")
        self.assertBody("(3+2j)")

        self.getPage("/repr?key=mul")
        self.assertBody("18")

        self.getPage("/repr?key=stradd")
        self.assertBody(repr("112233"))

    def testRespNamespaces(self):
        self.getPage("/foo/silly")
        self.assertHeader('X-silly', 'sillyval')
        self.assertBody('Hello world')

    def testCustomNamespaces(self):
        self.getPage("/raw/incr?num=12")
        self.assertBody("13")

        self.getPage("/dbscheme")
        self.assertBody(r"sqlite///memory")

    def testHandlerToolConfigOverride(self):
        # Assert that config overrides tool constructor args. Above, we set
        # the favicon in the page handler to be '../favicon.ico',
        # but then overrode it in config to be './static/dirback.jpg'.
        self.getPage("/favicon.ico")
        self.assertBody(open(os.path.join(localDir, "static/dirback.jpg"),
                             "rb").read())

    def test_request_body_namespace(self):
        self.getPage("/plain", method='POST', headers=[
            ('Content-Type', 'application/x-www-form-urlencoded'),
            ('Content-Length', '13')],
            body=compat.ntob('\xff\xfex\x00=\xff\xfea\x00b\x00c\x00'))
        self.assertBody("abc")


class VariableSubstitutionTests(unittest.TestCase):
    setup_server = staticmethod(setup_server)

    def test_config(self):
        from textwrap import dedent

        # variable substitution with [DEFAULT]
        conf = dedent("""
        [DEFAULT]
        dir = "/some/dir"
        my.dir = %(dir)s + "/sub"

        [my]
        my.dir = %(dir)s + "/my/dir"
        my.dir2 = %(my.dir)s + '/dir2'

        """)

        fp = compat.StringIO(conf)

        cherrypy.config.update(fp)
        self.assertEqual(cherrypy.config["my"]["my.dir"], "/some/dir/my/dir")
        self.assertEqual(cherrypy.config["my"]
                         ["my.dir2"], "/some/dir/my/dir/dir2")


class CallablesInConfigTest(unittest.TestCase):
    setup_server = staticmethod(setup_server)


    def test_call_with_literal_dict(self):
        from textwrap import dedent
        conf = dedent("""
        [my]
        value = dict(**{'foo': 'bar'})
        """)
        fp = compat.StringIO(conf)
        cherrypy.config.update(fp)
        self.assertEqual(cherrypy.config['my']['value'], {'foo': 'bar'})

    def test_call_with_kwargs(self):
        from textwrap import dedent
        conf = dedent("""
        [my]
        value = dict(test_suite="OVERRIDE", **cherrypy.config.environments)
        """)
        fp = compat.StringIO(conf)
        cherrypy.config.update(fp)
        env = cherrypy.config.environments.copy()
        env['test_suite'] = 'OVERRIDE'
        self.assertEqual(cherrypy.config['my']['value']['test_suite'], 'OVERRIDE')
        self.assertEqual(cherrypy.config['my']['value'], env)