1 """Tests for the CherryPy configuration system."""
4 localDir
= os
.path
.join(os
.getcwd(), os
.path
.dirname(__file__
))
6 from cherrypy
._cpcompat
import ntob
, StringIO
15 _cp_config
= {'foo': 'this',
19 cherrypy
.config
.namespaces
['db'] = self
.db_namespace
21 def db_namespace(self
, k
, v
):
25 # @cherrypy.expose(alias=('global_', 'xyz'))
27 return cherrypy
.request
.config
.get(key
, "None")
28 index
= cherrypy
.expose(index
, alias
=('global_', 'xyz'))
31 return repr(cherrypy
.request
.config
.get(key
, None))
36 dbscheme
.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'))
48 _cp_config
= {'foo': 'this2',
52 return cherrypy
.request
.config
.get(key
, "None")
59 silly
._cp
_config
= {'response.headers.X-silly': 'sillyval'}
62 return repr(cherrypy
.request
.config
.get(key
, None))
64 bar
._cp
_config
= {'foo': 'this3', 'bax': 'this4'}
69 return str(cherrypy
.request
.config
.get(key
, "None"))
73 def raw_namespace(key
, value
):
74 if key
== 'input.map':
75 handler
= cherrypy
.request
.handler
77 params
= cherrypy
.request
.params
78 for name
, coercer
in list(value
.items()):
80 params
[name
] = coercer(params
[name
])
84 cherrypy
.request
.handler
= wrapper
86 handler
= cherrypy
.request
.handler
88 # 'value' is a type (like int or str).
89 return value(handler())
90 cherrypy
.request
.handler
= wrapper
94 _cp_config
= {'raw.output': repr}
99 incr
._cp
_config
= {'raw.input.map': {'num': int}}
101 ioconf
= StringIO("""
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
110 stradd: %%(ones)s + %%(twos)s + "33"
113 tools.staticfile.filename = %r
114 """ % os
.path
.join(localDir
, 'static/dirback.jpg'))
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",
130 from cherrypy
.test
import helper
132 class ConfigTests(helper
.CPWebCase
):
133 setup_server
= staticmethod(setup_server
)
135 def testConfig(self
):
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
)
155 'tools.log_headers.on': False,
156 'tools.log_tracebacks.on': True,
157 'request.show_tracebacks': True,
159 'environment': 'test_suite',
160 'engine.autoreload_on': False,
162 'luxuryyacht': 'throatwobblermangrove',
163 # From Root._cp_config
165 # From Foo._cp_config
167 # From Foo.bar._cp_config
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"),
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]
236 my.dir = %(dir)s + "/sub"
239 my.dir = %(dir)s + "/my/dir"
240 my.dir2 = %(my.dir)s + '/dir2'
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")