1 """Tests for the CherryPy configuration system."""
2
3 import os, sys
4 localDir = os.path.join(os.getcwd(), os.path.dirname(__file__))
5
6 from cherrypy._cpcompat import ntob, StringIO
7 import unittest
8
9 import cherrypy
10
20
21 def db_namespace(self, k, v):
22 if k == "scheme":
23 self.db = v
24
25
26 def index(self, key):
27 return cherrypy.request.config.get(key, "None")
28 index = cherrypy.expose(index, alias=('global_', 'xyz'))
29
30 def repr(self, key):
31 return repr(cherrypy.request.config.get(key, None))
32 repr.exposed = True
33
34 def dbscheme(self):
35 return self.db
36 dbscheme.exposed = True
37
38 def plain(self, x):
39 return x
40 plain.exposed = True
41 plain._cp_config = {'request.body.attempt_charsets': ['utf-16']}
42
43 favicon_ico = cherrypy.tools.staticfile.handler(
44 filename=os.path.join(localDir, '../favicon.ico'))
45
46 class Foo:
47
48 _cp_config = {'foo': 'this2',
49 'baz': 'that2'}
50
51 def index(self, key):
52 return cherrypy.request.config.get(key, "None")
53 index.exposed = True
54 nex = index
55
56 def silly(self):
57 return 'Hello world'
58 silly.exposed = True
59 silly._cp_config = {'response.headers.X-silly': 'sillyval'}
60
61
62
63
64 def bar(self, key):
65 return repr(cherrypy.request.config.get(key, None))
66 bar.exposed = True
67 bar._cp_config = {'foo': 'this3', 'bax': 'this4'}
68
69 class Another:
70
71 def index(self, key):
72 return str(cherrypy.request.config.get(key, "None"))
73 index.exposed = True
74
75
76 def raw_namespace(key, value):
77 if key == 'input.map':
78 handler = cherrypy.request.handler
79 def wrapper():
80 params = cherrypy.request.params
81 for name, coercer in list(value.items()):
82 try:
83 params[name] = coercer(params[name])
84 except KeyError:
85 pass
86 return handler()
87 cherrypy.request.handler = wrapper
88 elif key == 'output':
89 handler = cherrypy.request.handler
90 def wrapper():
91
92 return value(handler())
93 cherrypy.request.handler = wrapper
94
95 class Raw:
96
97 _cp_config = {'raw.output': repr}
98
99 def incr(self, num):
100 return num + 1
101 incr.exposed = True
102 incr._cp_config = {'raw.input.map': {'num': int}}
103
104 ioconf = StringIO("""
105 [/]
106 neg: -1234
107 filename: os.path.join(sys.prefix, "hello.py")
108 thing1: cherrypy.lib.httputil.response_codes[404]
109 thing2: __import__('cherrypy.tutorial', globals(), locals(), ['']).thing2
110 complex: 3+2j
111 mul: 6*3
112 ones: "11"
113 twos: "22"
114 stradd: %%(ones)s + %%(twos)s + "33"
115
116 [/favicon.ico]
117 tools.staticfile.filename = %r
118 """ % os.path.join(localDir, 'static/dirback.jpg'))
119
120 root = Root()
121 root.foo = Foo()
122 root.raw = Raw()
123 app = cherrypy.tree.mount(root, config=ioconf)
124 app.request_class.namespaces['raw'] = raw_namespace
125
126 cherrypy.tree.mount(Another(), "/another")
127 cherrypy.config.update({'luxuryyacht': 'throatwobblermangrove',
128 'db.scheme': r"sqlite///memory",
129 })
130
131
132
133
134 from cherrypy.test import helper
135
137 setup_server = staticmethod(setup_server)
138
140 tests = [
141 ('/', 'nex', 'None'),
142 ('/', 'foo', 'this'),
143 ('/', 'bar', 'that'),
144 ('/xyz', 'foo', 'this'),
145 ('/foo/', 'foo', 'this2'),
146 ('/foo/', 'bar', 'that'),
147 ('/foo/', 'bax', 'None'),
148 ('/foo/bar', 'baz', "'that2'"),
149 ('/foo/nex', 'baz', 'that2'),
150
151 ('/another/','foo', 'None'),
152 ]
153 for path, key, expected in tests:
154 self.getPage(path + "?key=" + key)
155 self.assertBody(expected)
156
157 expectedconf = {
158
159 'tools.log_headers.on': False,
160 'tools.log_tracebacks.on': True,
161 'request.show_tracebacks': True,
162 'log.screen': False,
163 'environment': 'test_suite',
164 'engine.autoreload_on': False,
165
166 'luxuryyacht': 'throatwobblermangrove',
167
168 'bar': 'that',
169
170 'baz': 'that2',
171
172 'foo': 'this3',
173 'bax': 'this4',
174 }
175 for key, expected in expectedconf.items():
176 self.getPage("/foo/bar?key=" + key)
177 self.assertBody(repr(expected))
178
204
209
216
224
226 self.getPage("/plain", method='POST', headers=[
227 ('Content-Type', 'application/x-www-form-urlencoded'),
228 ('Content-Length', '13')],
229 body=ntob('\xff\xfex\x00=\xff\xfea\x00b\x00c\x00'))
230 self.assertBody("abc")
231
232
234 setup_server = staticmethod(setup_server)
235
237 from textwrap import dedent
238
239
240 conf = dedent("""
241 [DEFAULT]
242 dir = "/some/dir"
243 my.dir = %(dir)s + "/sub"
244
245 [my]
246 my.dir = %(dir)s + "/my/dir"
247 my.dir2 = %(my.dir)s + '/dir2'
248
249 """)
250
251 fp = StringIO(conf)
252
253 cherrypy.config.update(fp)
254 self.assertEqual(cherrypy.config["my"]["my.dir"], "/some/dir/my/dir")
255 self.assertEqual(cherrypy.config["my"]["my.dir2"], "/some/dir/my/dir/dir2")
256