Package cherrypy :: Package test :: Module test_config
[hide private]
[frames] | no frames]

Source Code for Module cherrypy.test.test_config

  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   
11 -def setup_server():
12 13 class Root: 14 15 _cp_config = {'foo': 'this', 16 'bar': 'that'} 17 18 def __init__(self): 19 cherrypy.config.namespaces['db'] = self.db_namespace
20 21 def db_namespace(self, k, v): 22 if k == "scheme": 23 self.db = v 24 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')) 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 # Test the expose and config decorators 62 #@cherrypy.expose 63 #@cherrypy.config(foo='this3', **{'bax': 'this4'}) 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 # 'value' is a type (like int or str). 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 # Client-side code # 133 134 from cherrypy.test import helper 135
136 -class ConfigTests(helper.CPWebCase):
137 setup_server = staticmethod(setup_server) 138
139 - def testConfig(self):
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 # If 'foo' == 'this', then the mount point '/another' leaks into '/'. 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 # From CP defaults 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 # From global config 166 'luxuryyacht': 'throatwobblermangrove', 167 # From Root._cp_config 168 'bar': 'that', 169 # From Foo._cp_config 170 'baz': 'that2', 171 # From Foo.bar._cp_config 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
179 - def testUnrepr(self):
180 self.getPage("/repr?key=neg") 181 self.assertBody("-1234") 182 183 self.getPage("/repr?key=filename") 184 self.assertBody(repr(os.path.join(sys.prefix, "hello.py"))) 185 186 self.getPage("/repr?key=thing1") 187 self.assertBody(repr(cherrypy.lib.httputil.response_codes[404])) 188 189 if not getattr(cherrypy.server, "using_apache", False): 190 # The object ID's won't match up when using Apache, since the 191 # server and client are running in different processes. 192 self.getPage("/repr?key=thing2") 193 from cherrypy.tutorial import thing2 194 self.assertBody(repr(thing2)) 195 196 self.getPage("/repr?key=complex") 197 self.assertBody("(3+2j)") 198 199 self.getPage("/repr?key=mul") 200 self.assertBody("18") 201 202 self.getPage("/repr?key=stradd") 203 self.assertBody(repr("112233"))
204
205 - def testRespNamespaces(self):
206 self.getPage("/foo/silly") 207 self.assertHeader('X-silly', 'sillyval') 208 self.assertBody('Hello world')
209
210 - def testCustomNamespaces(self):
211 self.getPage("/raw/incr?num=12") 212 self.assertBody("13") 213 214 self.getPage("/dbscheme") 215 self.assertBody(r"sqlite///memory")
216
218 # Assert that config overrides tool constructor args. Above, we set 219 # the favicon in the page handler to be '../favicon.ico', 220 # but then overrode it in config to be './static/dirback.jpg'. 221 self.getPage("/favicon.ico") 222 self.assertBody(open(os.path.join(localDir, "static/dirback.jpg"), 223 "rb").read())
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
233 -class VariableSubstitutionTests(unittest.TestCase):
234 setup_server = staticmethod(setup_server) 235
236 - def test_config(self):
237 from textwrap import dedent 238 239 # variable substitution with [DEFAULT] 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