Fixed python_path problem.
[smonitor.git] / lib / cherrypy / test / test_config.py
bloba0bd8ab945db2f2c9534d1a45df81f0580ddc376
1 """Tests for the CherryPy configuration system."""
3 import os, sys
4 localDir = os.path.join(os.getcwd(), os.path.dirname(__file__))
6 from cherrypy._cpcompat import ntob, StringIO
7 import unittest
9 import cherrypy
11 def setup_server():
13 class Root:
15 _cp_config = {'foo': 'this',
16 'bar': 'that'}
18 def __init__(self):
19 cherrypy.config.namespaces['db'] = self.db_namespace
21 def db_namespace(self, k, v):
22 if k == "scheme":
23 self.db = v
25 # @cherrypy.expose(alias=('global_', 'xyz'))
26 def index(self, key):
27 return cherrypy.request.config.get(key, "None")
28 index = cherrypy.expose(index, alias=('global_', 'xyz'))
30 def repr(self, key):
31 return repr(cherrypy.request.config.get(key, None))
32 repr.exposed = True
34 def dbscheme(self):
35 return self.db
36 dbscheme.exposed = True
38 def plain(self, x):
39 return x
40 plain.exposed = True
41 plain._cp_config = {'request.body.attempt_charsets': ['utf-16']}
43 favicon_ico = cherrypy.tools.staticfile.handler(
44 filename=os.path.join(localDir, '../favicon.ico'))
46 class Foo:
48 _cp_config = {'foo': 'this2',
49 'baz': 'that2'}
51 def index(self, key):
52 return cherrypy.request.config.get(key, "None")
53 index.exposed = True
54 nex = index
56 def silly(self):
57 return 'Hello world'
58 silly.exposed = True
59 silly._cp_config = {'response.headers.X-silly': 'sillyval'}
61 def bar(self, key):
62 return repr(cherrypy.request.config.get(key, None))
63 bar.exposed = True
64 bar._cp_config = {'foo': 'this3', 'bax': 'this4'}
66 class Another:
68 def index(self, key):
69 return str(cherrypy.request.config.get(key, "None"))
70 index.exposed = True
73 def raw_namespace(key, value):
74 if key == 'input.map':
75 handler = cherrypy.request.handler
76 def wrapper():
77 params = cherrypy.request.params
78 for name, coercer in list(value.items()):
79 try:
80 params[name] = coercer(params[name])
81 except KeyError:
82 pass
83 return handler()
84 cherrypy.request.handler = wrapper
85 elif key == 'output':
86 handler = cherrypy.request.handler
87 def wrapper():
88 # 'value' is a type (like int or str).
89 return value(handler())
90 cherrypy.request.handler = wrapper
92 class Raw:
94 _cp_config = {'raw.output': repr}
96 def incr(self, num):
97 return num + 1
98 incr.exposed = True
99 incr._cp_config = {'raw.input.map': {'num': int}}
101 ioconf = StringIO("""
103 neg: -1234
104 filename: os.path.join(sys.prefix, "hello.py")
105 thing1: cherrypy.lib.httputil.response_codes[404]
106 thing2: __import__('cherrypy.tutorial', globals(), locals(), ['']).thing2
107 complex: 3+2j
108 ones: "11"
109 twos: "22"
110 stradd: %%(ones)s + %%(twos)s + "33"
112 [/favicon.ico]
113 tools.staticfile.filename = %r
114 """ % os.path.join(localDir, 'static/dirback.jpg'))
116 root = Root()
117 root.foo = Foo()
118 root.raw = Raw()
119 app = cherrypy.tree.mount(root, config=ioconf)
120 app.request_class.namespaces['raw'] = raw_namespace
122 cherrypy.tree.mount(Another(), "/another")
123 cherrypy.config.update({'luxuryyacht': 'throatwobblermangrove',
124 'db.scheme': r"sqlite///memory",
128 # Client-side code #
130 from cherrypy.test import helper
132 class ConfigTests(helper.CPWebCase):
133 setup_server = staticmethod(setup_server)
135 def testConfig(self):
136 tests = [
137 ('/', 'nex', 'None'),
138 ('/', 'foo', 'this'),
139 ('/', 'bar', 'that'),
140 ('/xyz', 'foo', 'this'),
141 ('/foo/', 'foo', 'this2'),
142 ('/foo/', 'bar', 'that'),
143 ('/foo/', 'bax', 'None'),
144 ('/foo/bar', 'baz', "'that2'"),
145 ('/foo/nex', 'baz', 'that2'),
146 # If 'foo' == 'this', then the mount point '/another' leaks into '/'.
147 ('/another/','foo', 'None'),
149 for path, key, expected in tests:
150 self.getPage(path + "?key=" + key)
151 self.assertBody(expected)
153 expectedconf = {
154 # From CP defaults
155 'tools.log_headers.on': False,
156 'tools.log_tracebacks.on': True,
157 'request.show_tracebacks': True,
158 'log.screen': False,
159 'environment': 'test_suite',
160 'engine.autoreload_on': False,
161 # From global config
162 'luxuryyacht': 'throatwobblermangrove',
163 # From Root._cp_config
164 'bar': 'that',
165 # From Foo._cp_config
166 'baz': 'that2',
167 # From Foo.bar._cp_config
168 'foo': 'this3',
169 'bax': 'this4',
171 for key, expected in expectedconf.items():
172 self.getPage("/foo/bar?key=" + key)
173 self.assertBody(repr(expected))
175 def testUnrepr(self):
176 self.getPage("/repr?key=neg")
177 self.assertBody("-1234")
179 self.getPage("/repr?key=filename")
180 self.assertBody(repr(os.path.join(sys.prefix, "hello.py")))
182 self.getPage("/repr?key=thing1")
183 self.assertBody(repr(cherrypy.lib.httputil.response_codes[404]))
185 if not getattr(cherrypy.server, "using_apache", False):
186 # The object ID's won't match up when using Apache, since the
187 # server and client are running in different processes.
188 self.getPage("/repr?key=thing2")
189 from cherrypy.tutorial import thing2
190 self.assertBody(repr(thing2))
192 self.getPage("/repr?key=complex")
193 self.assertBody("(3+2j)")
195 self.getPage("/repr?key=stradd")
196 self.assertBody(repr("112233"))
198 def testRespNamespaces(self):
199 self.getPage("/foo/silly")
200 self.assertHeader('X-silly', 'sillyval')
201 self.assertBody('Hello world')
203 def testCustomNamespaces(self):
204 self.getPage("/raw/incr?num=12")
205 self.assertBody("13")
207 self.getPage("/dbscheme")
208 self.assertBody(r"sqlite///memory")
210 def testHandlerToolConfigOverride(self):
211 # Assert that config overrides tool constructor args. Above, we set
212 # the favicon in the page handler to be '../favicon.ico',
213 # but then overrode it in config to be './static/dirback.jpg'.
214 self.getPage("/favicon.ico")
215 self.assertBody(open(os.path.join(localDir, "static/dirback.jpg"),
216 "rb").read())
218 def test_request_body_namespace(self):
219 self.getPage("/plain", method='POST', headers=[
220 ('Content-Type', 'application/x-www-form-urlencoded'),
221 ('Content-Length', '13')],
222 body=ntob('\xff\xfex\x00=\xff\xfea\x00b\x00c\x00'))
223 self.assertBody("abc")
226 class VariableSubstitutionTests(unittest.TestCase):
227 setup_server = staticmethod(setup_server)
229 def test_config(self):
230 from textwrap import dedent
232 # variable substitution with [DEFAULT]
233 conf = dedent("""
234 [DEFAULT]
235 dir = "/some/dir"
236 my.dir = %(dir)s + "/sub"
238 [my]
239 my.dir = %(dir)s + "/my/dir"
240 my.dir2 = %(my.dir)s + '/dir2'
242 """)
244 fp = StringIO(conf)
246 cherrypy.config.update(fp)
247 self.assertEqual(cherrypy.config["my"]["my.dir"], "/some/dir/my/dir")
248 self.assertEqual(cherrypy.config["my"]["my.dir2"], "/some/dir/my/dir/dir2")