Ticket #1466: webtest_prelim.patch
| File webtest_prelim.patch, 70.3 kB (added by kskuhlman, 10 months ago) |
|---|
-
turbogears/controllers.py
old new 412 412 assert isinstance(output, basestring) or isinstance(output, dict) \ 413 413 or isinstance(output, types.GeneratorType), \ 414 414 "Method %s.%s() returned unexpected output. Output should " \ 415 "be of type basestring, dict or generator ." % (416 args[0].__class__.__name__, func.__name__ )415 "be of type basestring, dict or generator, not %s." % ( 416 args[0].__class__.__name__, func.__name__, type(output)) 417 417 if isinstance(output, dict): 418 418 template = output.pop("tg_template", template) 419 419 format = output.pop("tg_format", format) -
turbogears/tests/test_form_controllers.py
old new 34 34 self.name = name 35 35 self.age = age 36 36 self.date = date 37 return dict(name=name, age=age, date=date) 37 38 38 39 @expose() 39 40 @validate(form=myform) … … 43 44 self.name = name 44 45 self.age = age 45 46 self.date = date 47 return dict(name=name, age=age, date=date) 46 48 47 49 def test_form_translation(): 48 50 """Form input is translated into properly converted parameters""" 49 51 root = MyRoot() 50 52 cherrypy.root = root 51 testutil.create_request("/testform?name=ed&date=11/05/2005&age=5")53 response = testutil.create_request("/testform?name=ed&date=11/05/2005&age=5") 52 54 assert root.name == "ed" 53 55 assert root.age == 5 54 56 … … 56 58 """Form input is translated into properly converted parameters""" 57 59 root = MyRoot() 58 60 cherrypy.root = root 59 testutil.create_request("/testform_new_style?name=ed&date=11/05/2005&age=5&")61 response = testutil.create_request("/testform_new_style?name=ed&date=11/05/2005&age=5&") 60 62 assert root.name == "ed" 61 63 assert root.age == 5 62 64 63 65 def test_invalid_form_with_error_handling(): 64 66 """Invalid forms can be handled by the method""" 65 root = cherrypy.root 66 testutil.create_request("/testform?name=ed&age=edalso&date=11/05/2005") 67 assert root.has_errors 67 response = testutil.create_request("/testform?name=ed&age=edalso&date=11/05/2005", status=200) 68 68 69 69 def test_css_should_appear(): 70 70 """CSS should appear when asked for""" 71 testutil.create_request("/") 72 assert "calendar-system.css" in cherrypy.response.body[0] 71 root = cherrypy.root 72 response = testutil.create_request("/") 73 print response.body 74 assert "calendar-system.css" in response.body 73 75 74 76 def test_javascript_should_appear(): 75 77 """JavaScript should appear when asked for""" 76 testutil.create_request("/")77 assert "calendar.js" in cherrypy.response.body[0]78 response = testutil.create_request("/") 79 assert "calendar.js" in response.body 78 80 79 81 def test_include_mochikit(): 80 82 """JSLinks (and MochiKit especially) can be included easily""" 81 testutil.create_request("/usemochi") 82 assert "MochiKit.js" in cherrypy.response.body[0] 83 response = testutil.create_request("/usemochi") 84 print response.body 85 assert "MochiKit.js" in response.body 83 86 84 87 def test_suppress_mochikit(): 85 88 """MochiKit inclusion can be suppressed""" 86 config.update({"global": {"tg.mochikit_suppress": True}}) 87 testutil.create_request("/usemochi") 88 suppressed_body = cherrypy.response.body[0] 89 config.update({"global":{"tg.mochikit_suppress" : True}}) 90 suppressed = testutil.create_request("/usemochi") 89 91 # repair the fixture 90 config.update({"global": {"tg.mochikit_suppress": False}}) 91 testutil.create_request("/usemochi") 92 included_body = cherrypy.response.body[0] 93 assert "MochiKit.js" not in suppressed_body 94 assert "MochiKit.js" in included_body 92 config.update({"global":{"tg.mochikit_suppress" : False}}) 95 93 94 included = testutil.create_request("/usemochi") 95 assert "MochiKit.js" not in suppressed.body 96 assert "MochiKit.js" in included.body 97 96 98 def test_mochikit_everywhere(): 97 99 """MochiKit can be included everywhere by setting tg.mochikit_all""" 98 config.update({"global": {"tg.mochikit_all": True}})99 testutil.create_request("/")100 config.update({"global": {"tg.mochikit_all": False}})101 assert "MochiKit.js" in cherrypy.response.body[0]100 config.update({"global":{"tg.mochikit_all" : True}}) 101 response = testutil.create_request("/") 102 config.update({"global":{"tg.mochikit_all" : False}}) 103 assert "MochiKit.js" in response.body 102 104 103 105 def test_mochikit_nowhere(): 104 106 """Setting tg.mochikit_suppress will prevent including it everywhere""" 105 107 config.update({"global": {"tg.mochikit_all": True}}) 106 108 config.update({"global": {"tg.mochikit_suppress": True}}) 107 testutil.create_request("/")109 response = testutil.create_request("/") 108 110 config.update({"global": {"tg.mochikit_all": False}}) 109 111 config.update({"global": {"tg.mochikit_suppress": False}}) 110 assert "MochiKit.js" not in cherrypy.response.body[0]112 assert "MochiKit.js" not in response.body 111 113 112 114 def test_include_widgets(): 113 115 """Any widget can be included everywhere by setting tg.include_widgets""" 114 116 config.update({"global": {"tg.include_widgets": ["mochikit"]}}) 115 testutil.create_request("/")117 response = testutil.create_request("/") 116 118 config.update({"global": {"tg.include_widgets": []}}) 117 assert "MochiKit.js" in cherrypy.response.body[0]119 assert "MochiKit.js" in response.body 118 120 119 121 120 122 class State(object): … … 149 151 cherrypy.root = self.Controller() 150 152 # parameter values are irrelevant 151 153 url = '/validation?a=1&b=2&c.a=3&c.b=4' 152 testutil.create_request(url) 153 body = cherrypy.response.body[0] 154 response = testutil.create_request(url) 154 155 msg = "Validation state is not handled properly" 155 156 # 4 == 1 (a) + 1(b) + 1(c.a) + 1(c.b) 156 self.failUnless('counter: 4' in body, msg)157 self.failUnless('counter: 4' in response.body, msg) -
turbogears/tests/test_errorhandling.py
old new 223 223 224 224 def test_defaultErrorHandler(self): 225 225 """ Default error handler. """ 226 testutil.create_request("/defaulterror?bar=abc")227 self.failUnless("Default error handler" in cherrypy.response.body[0])228 testutil.create_request("/defaulterror?bar=true")229 self.failUnless("Default error provider" in cherrypy.response.body[0])226 response = testutil.create_request("/defaulterror?bar=abc") 227 self.failUnless("Default error handler" in response.body) 228 response = testutil.create_request("/defaulterror?bar=true") 229 self.failUnless("Default error provider" in response.body) 230 230 231 231 def test_specialisedErrorHandler(self): 232 232 """ Error handler specialisation. """ 233 testutil.create_request("/specialisederror?bar=abc&baz=a@b.com") 234 self.failUnless("Default error handler" in cherrypy.response.body[0]) 235 testutil.create_request("/specialisederror?baz=abc&bar=1") 236 self.failUnless("Specialised error handler" in 237 cherrypy.response.body[0]) 238 testutil.create_request("/specialisederror?bar=1&baz=a@b.com") 239 self.failUnless("Specialised error provider" in 240 cherrypy.response.body[0]) 233 response = testutil.create_request("/specialisederror?bar=abc&baz=a@b.com") 234 self.failUnless("Default error handler" in response.body) 235 response = testutil.create_request("/specialisederror?baz=abc&bar=1") 236 self.failUnless("Specialised error handler" in response.body) 237 response = testutil.create_request("/specialisederror?bar=1&baz=a@b.com") 238 self.failUnless("Specialised error provider" in response.body) 241 239 242 240 def test_exceptionErrorHandler(self): 243 241 """ Error handler for exceptions. """ 244 testutil.create_request("/exceptionerror")245 self.failUnless("Default error handler" in cherrypy.response.body[0])242 response = testutil.create_request("/exceptionerror") 243 self.failUnless("Default error handler" in response.body) 246 244 247 245 def test_recursiveErrorHandler(self): 248 246 """ Recursive error handler. """ 249 testutil.create_request("/recursiveerror?bar=abc") 250 self.failUnless("Recursive error handler" in cherrypy.response.body[0]) 251 testutil.create_request("/recursiveerror?bar=1") 252 self.failUnless("Recursive error provider" in 253 cherrypy.response.body[0]) 247 response = testutil.create_request("/recursiveerror?bar=abc") 248 self.failUnless("Recursive error handler" in response.body) 249 response = testutil.create_request("/recursiveerror?bar=1") 250 self.failUnless("Recursive error provider" in response.body) 254 251 255 252 def test_implicitErrorHandler(self): 256 253 """ Implicit error handling. """ 257 testutil.create_request("/impliciterror?bar=abc") 258 self.failUnless("Implicit error handler" in 259 cherrypy.response.body[0]) 260 testutil.create_request("/impliciterror?bar=1") 261 self.failUnless("Implicit error provider" in 262 cherrypy.response.body[0]) 254 response = testutil.create_request("/impliciterror?bar=abc") 255 self.failUnless("Implicit error handler" in response.body) 256 response = testutil.create_request("/impliciterror?bar=1") 257 self.failUnless("Implicit error provider" in response.body) 263 258 264 259 def test_normalMethodErrorHandler(self): 265 260 """ Normal method as an error handler. """ 266 testutil.create_request("/normalmethodcaller?bar=abc")267 self.failUnless("Normal method" in cherrypy.response.body[0])268 testutil.create_request("/normalmethodcaller?bar=true")269 self.failUnless("Normal method caller" in cherrypy.response.body[0])261 response = testutil.create_request("/normalmethodcaller?bar=abc") 262 self.failUnless("Normal method" in response.body) 263 response = testutil.create_request("/normalmethodcaller?bar=true") 264 self.failUnless("Normal method caller" in response.body) 270 265 271 266 def test_infiniteRecursionPrevention(self): 272 267 """ Infinite recursion prevention. """ 273 testutil.create_request("/infiniteloop")274 self.failUnless("Exception 2" in cherrypy.response.body[0])268 response = testutil.create_request("/infiniteloop") 269 self.failUnless("Exception 2" in response.body) 275 270 276 271 def test_positionalArgs(self): 277 272 """ Positional argument validation. """ 278 testutil.create_request("/positionalargs/first/23/third?bar=abc")279 self.failUnless("Default error handler" in cherrypy.response.body[0])280 testutil.create_request("/positionalargs/first/abc/third?bar=false")281 self.failUnless("Default error handler" in cherrypy.response.body[0])282 testutil.create_request("/positionalargs/first/abc/third?bar=abc")283 self.failUnless("Default error handler" in cherrypy.response.body[0])284 testutil.create_request("/positionalargs/first/23/third?bar=true")285 self.failUnless("Positional arguments" in cherrypy.response.body[0])273 response = testutil.create_request("/positionalargs/first/23/third?bar=abc") 274 self.failUnless("Default error handler" in response.body) 275 response = testutil.create_request("/positionalargs/first/abc/third?bar=false") 276 self.failUnless("Default error handler" in response.body) 277 response = testutil.create_request("/positionalargs/first/abc/third?bar=abc") 278 self.failUnless("Default error handler" in response.body) 279 response = testutil.create_request("/positionalargs/first/23/third?bar=true") 280 self.failUnless("Positional arguments" in response.body) 286 281 self.failUnless(cherrypy.root.first == "first") 287 282 self.failUnless(cherrypy.root.second == 23) 288 283 self.failUnless(cherrypy.root.third == "third") 289 284 290 285 def test_missingArgs(self): 291 286 """ Arguments required in validation missing. """ 292 testutil.create_request("/missingargs")293 self.failUnless("Default error handler" in cherrypy.response.body[0])294 testutil.create_request("/missingargs?bar=12")295 self.failUnless("Missing args provider" in cherrypy.response.body[0])287 response = testutil.create_request("/missingargs") 288 self.failUnless("Default error handler" in response.body) 289 response = testutil.create_request("/missingargs?bar=12") 290 self.failUnless("Missing args provider" in response.body) 296 291 297 292 def test_nohandler(self): 298 """ No error han lder declared. """299 testutil.create_request("/nohandler")300 self.failUnless("Exception raised" in cherrypy.response.body[0])293 """ No error handler declared. """ 294 response = testutil.create_request("/nohandler") 295 self.failUnless("Exception raised" in response.body) 301 296 302 297 def test_bindArgs(self): 303 298 """ Arguments can be bond to an error handler. """ 304 testutil.create_request("/bindargs")305 self.failUnless("123" in cherrypy.response.body[0])299 response = testutil.create_request("/bindargs") 300 self.failUnless("123" in response.body) 306 301 307 302 def test_notExposed(self): 308 303 """ Validation error handling is decoupled from expose. """ 309 testutil.create_request("/notexposedcaller?foo=a&bar=rab&baz=c")310 self.failUnless("Not exposed error" in cherrypy.response.body[0])311 self.failUnless("rab" in cherrypy.response.body[0])304 response = testutil.create_request("/notexposedcaller?foo=a&bar=rab&baz=c") 305 self.failUnless("Not exposed error" in response.body) 306 self.failUnless("rab" in response.body) 312 307 313 308 def test_continuations(self): 314 309 """ Continuations via error handling mechanism. """ 315 testutil.create_request("/continuationcaller?bar=a")316 self.failUnless("Continuation caller" in cherrypy.response.body[0])310 response = testutil.create_request("/continuationcaller?bar=a") 311 self.failUnless("Continuation caller" in response.body) 317 312 self.failUnless(cherrypy.root.continuation == True) 318 313 319 314 def test_nested(self): 320 315 """ Potentially ambiguous cases. """ 321 testutil.create_request("/nest?bar=a")322 self.failUnless("Default error handler" in cherrypy.response.body[0])323 testutil.create_request("/nestedcontroller/nest?bar=a")324 self.failUnless("Nested" in cherrypy.response.body[0])316 response = testutil.create_request("/nest?bar=a") 317 self.failUnless("Default error handler" in response.body) 318 response = testutil.create_request("/nestedcontroller/nest?bar=a") 319 self.failUnless("Nested" in response.body) 325 320 326 321 def test_failsafe(self): 327 322 """ Failsafe values for erroneous input. """ 328 testutil.create_request("/failsafenone?bar=a&baz=b")329 self.failUnless('"bar": "a"' in cherrypy.response.body[0])330 self.failUnless('"baz": "b"' in cherrypy.response.body[0])331 testutil.create_request("/failsafevaluesdict?bar=a&baz=b")332 self.failUnless('"bar": 1' in cherrypy.response.body[0])333 self.failUnless('"baz": 2' in cherrypy.response.body[0])334 testutil.create_request("/failsafevaluesatom?bar=a&baz=b")335 self.failUnless('"bar": 13' in cherrypy.response.body[0])336 self.failUnless('"baz": 13' in cherrypy.response.body[0])337 testutil.create_request("/failsafemaperrors?bar=a&baz=b")323 response = testutil.create_request("/failsafenone?bar=a&baz=b") 324 self.failUnless('"bar": "a"' in response.body) 325 self.failUnless('"baz": "b"' in response.body) 326 response = testutil.create_request("/failsafevaluesdict?bar=a&baz=b") 327 self.failUnless('"bar": 1' in response.body) 328 self.failUnless('"baz": 2' in response.body) 329 response = testutil.create_request("/failsafevaluesatom?bar=a&baz=b") 330 self.failUnless('"bar": 13' in response.body) 331 self.failUnless('"baz": 13' in response.body) 332 response = testutil.create_request("/failsafemaperrors?bar=a&baz=b") 338 333 self.failUnless('"bar": "Please enter an integer value"' in 339 cherrypy.response.body[0])340 self.failUnless('"baz": "Please enter an integer value"' in 341 cherrypy.response.body[0])342 testutil.create_request("/failsafeformencode?bar=a&baz=b")343 self.failUnless('"bar": 1' in cherrypy.response.body[0])344 self.failUnless('"baz": 2' in cherrypy.response.body[0])345 testutil.create_request("/failsafedefaults?bar=a&baz=b")346 self.failUnless('"bar": 1' in cherrypy.response.body[0],cherrypy.response.body[0])347 self.failUnless('"baz": 2' in cherrypy.response.body[0])334 response.body) 335 self.failUnless('"baz": "Please enter an integer value"' in 336 response.body) 337 response = testutil.create_request("/failsafeformencode?bar=a&baz=b") 338 self.failUnless('"bar": 1' in response.body) 339 self.failUnless('"baz": 2' in response.body) 340 response = testutil.create_request("/failsafedefaults?bar=a&baz=b") 341 self.failUnless('"bar": 1' in response.body,response.body) 342 self.failUnless('"baz": 2' in response.body) -
turbogears/tests/test_sqlalchemy.py
old new 135 135 will be marked with this name :) 136 136 137 137 """ 138 cherrypy.response.code = 501139 138 msg = "KARL25 responding\n" 140 139 msg += "user with id: '%s' should not be saved.\n" % id 141 140 msg += "An exception occurred: %r (%s)" % ((tg_exceptions,)*2) … … 181 180 """If a controller causes an SA exception, it is raised properly.""" 182 181 capture_log("turbogears.database") 183 182 cherrypy.root = MyRoot() 184 create_request("/create_person?id=20") 185 output = cherrypy.response.body[0] 183 response = create_request("/create_person?id=20") 186 184 print_log() 185 assert 'No exceptions occurred' in response.body 186 response = create_request("/create_person?id=20", status=500) 187 output = response.body 187 188 print output 188 assert 'No exceptions occurred' in output189 create_request("/create_person?id=20")190 output = cherrypy.response.body[0]191 print output192 189 assert 'KARL25' not in output, \ 193 190 'Exception should NOT have been handled by our handler' 194 191 assert 'DBAPIError' in output, \ … … 218 215 def test_cntrl_commit(): 219 216 """It's safe to commit a transaction in the controller.""" 220 217 cherrypy.root = MyRoot() 221 create_request("/create_person?id=23&docom=1")222 assert 'InvalidRequestError' not in cherrypy.response.body[0]218 response = create_request("/create_person?id=23&docom=1") 219 assert 'InvalidRequestError' not in response.body 223 220 assert session.query(Person).get(23) is not None, \ 224 221 'The Person 23 should have been saved during commit inside controller' 225 222 226 223 def test_cntrl_commit2(): 227 224 """A commit inside the controller is not rolled back by the exception.""" 228 225 cherrypy.root = MyRoot() 229 create_request("/create_person?id=24&docom=1&doerr=1")230 assert 'InvalidRequestError' not in cherrypy.response.body[0]226 response = create_request("/create_person?id=24&docom=1&doerr=1") 227 assert 'InvalidRequestError' not in response.body 231 228 assert session.query(Person).get(24) is not None, \ 232 229 'The Person 24 should have been saved during commit' \ 233 230 ' inside controller and not rolled back' … … 235 232 def test_cntrl_flush(): 236 233 """It's safe to flush in the controller.""" 237 234 cherrypy.root = MyRoot() 238 create_request("/create_person?id=25&doflush=1")239 print cherrypy.response.body[0]240 assert 'No exceptions occurred' in cherrypy.response.body[0]241 create_request("/create_person?id=25&doflush=0")242 assert 'IntegrityError' in cherrypy.response.body[0]243 create_request("/create_person?id=25&doflush=1")244 assert 'IntegrityError' in cherrypy.response.body[0]245 create_request("/create_person?id=25&doflush=2")246 assert 'No exceptions occurred' in cherrypy.response.body[0]235 response = create_request("/create_person?id=25&doflush=1") 236 print response.body 237 assert 'No exceptions occurred' in response.body 238 response = create_request("/create_person?id=25&doflush=0", status=500) 239 assert 'IntegrityError' in response.body 240 response = create_request("/create_person?id=25&doflush=1") 241 assert 'IntegrityError' in response.body 242 response = create_request("/create_person?id=25&doflush=2") 243 assert 'No exceptions occurred' in response.body 247 244 248 245 249 246 # Exception handling with rollback … … 297 294 298 295 """ 299 296 cherrypy.root = RbRoot() 300 create_request('/doerr?id=26')301 output = cherrypy.response.body[0]297 response = create_request('/doerr?id=26') 298 output = response.body 302 299 print output 303 300 assert 'KARL27' in output, 'Exception handler should have answered' 304 301 assert session.query(User).get(26) is None … … 312 309 313 310 """ 314 311 cherrypy.root = RbRoot() 315 create_request('/doerr?id=XX')316 output = cherrypy.response.body[0]312 response = create_request('/doerr?id=XX') 313 output = response.body 317 314 assert 'KARL27' in output, 'Exception handler should have answered' 318 315 assert session.query(User).get('XX') is None 319 316 320 317 def test_exc_done_rollback(): 321 318 """No problems with error handler if controller manually rollbacks.""" 322 319 cherrypy.root = RbRoot() 323 create_request('/doerr?id=28&dorb=1')324 output = cherrypy.response.body[0]320 response = create_request('/doerr?id=28&dorb=1') 321 output = response.body 325 322 assert 'KARL27' in output, 'Exception handler should have answered' 326 323 assert session.query(User).get(28) is None 327 324 assert session.query(User).get(29) is not None … … 356 353 """ 357 354 test_table.insert().execute(dict(id=1, val='a')) 358 355 cherrypy.root = FreshRoot() 359 create_request("/test1")360 assert 'AssertionError' not in cherrypy.response.body[0]356 response = create_request("/test1", status=500) 357 assert 'AssertionError' not in response.body 361 358 # Call test2 in a different thread 362 359 class ThreadB(threading.Thread): 363 360 def run(self): 364 create_request("/test2")365 assert 'AssertionError' not in cherrypy.response.body[0]361 response = create_request("/test2", status=500) 362 assert 'AssertionError' not in response.body 366 363 thrdb = ThreadB() 367 364 thrdb.start() 368 365 thrdb.join() 369 create_request("/test3")370 assert 'AssertionError' not in cherrypy.response.body[0]366 response = create_request("/test3", status=500) 367 assert 'AssertionError' not in response.body -
turbogears/tests/test_expose.py
old new 21 21 22 22 def test_gettinghtml(): 23 23 cherrypy.root = ExposeRoot() 24 create_request("/with_json") 25 body = cherrypy.response.body[0] 26 assert "Paging all foo" in body 24 response = create_request("/with_json") 25 assert "Paging all foo" in response.body 27 26 28 27 def test_gettingjson(): 29 28 cherrypy.root = ExposeRoot() 30 create_request("/with_json?tg_format=json") 31 body = cherrypy.response.body[0] 32 assert '"title": "Foobar"' in body 29 response = create_request("/with_json?tg_format=json") 30 assert '"title": "Foobar"' in response.body 33 31 34 32 def test_gettingjsonviaaccept(): 35 33 cherrypy.root = ExposeRoot() 36 create_request("/with_json_via_accept",34 response = create_request("/with_json_via_accept", 37 35 headers=dict(Accept="text/javascript")) 38 body = cherrypy.response.body[0] 39 assert '"title": "Foobar"' in body 36 assert '"title": "Foobar"' in response.body 40 37 41 38 def test_getting_json_with_accept_but_using_tg_format(): 42 39 cherrypy.root = ExposeRoot() 43 create_request("/with_json_via_accept?tg_format=json") 44 body = cherrypy.response.body[0] 45 assert '"title": "Foobar"' in body 40 response = create_request("/with_json_via_accept?tg_format=json") 41 assert '"title": "Foobar"' in response.body 46 42 47 43 def test_getting_plaintext(): 48 44 cherrypy.root = ExposeRoot() 49 create_request("/with_json_via_accept",45 response = create_request("/with_json_via_accept", 50 46 headers=dict(Accept="text/plain")) 51 print cherrypy.response.body[0] 52 assert cherrypy.response.body[0] == "This is a plain text for foo." 47 assert response.body == "This is a plain text for foo." 53 48 54 49 def test_allow_json(): 55 50 … … 59 54 return dict(title="Foobar", mybool=False, someval="niggles") 60 55 61 56 cherrypy.root = NewRoot() 62 create_request("/test", headers= dict(accept="text/javascript")) 63 body = cherrypy.response.body[0] 64 values = simplejson.loads(body) 57 response = create_request("/test", headers= dict(accept="text/javascript")) 58 values = simplejson.loads(response.body) 65 59 assert values == dict(title="Foobar", mybool=False, someval="niggles", 66 60 tg_flash=None) 67 assert cherrypy.response.headers["Content-Type"] == "text/javascript" 68 create_request("/test?tg_format=json") 69 body = cherrypy.response.body[0] 70 values = simplejson.loads(body) 61 assert response.headers["Content-Type"] == "text/javascript" 62 response = create_request("/test?tg_format=json") 63 values = simplejson.loads(response.body) 71 64 assert values == dict(title="Foobar", mybool=False, someval="niggles", 72 65 tg_flash=None) 73 assert cherrypy.response.headers["Content-Type"] == "text/javascript"66 assert response.headers["Content-Type"] == "text/javascript" -
turbogears/tests/test_controllers.py
old new 1 1 import unittest 2 import turbogears 3 from turbogears import config, controllers, database, \ 4 error_handler, exception_handler, expose, flash, redirect, \ 5 startup, testutil, url, validate, validators 6 import simplejson 2 7 import formencode 3 8 import cherrypy 4 9 import pkg_resources 5 from turbogears import config, controllers, database, \ 6 error_handler, exception_handler, expose, flash, redirect, \ 7 startup, testutil, url, validate, validators 10 from nose.tools import eq_ 8 11 9 12 10 13 class SubApp(controllers.RootController): 11 14 15 @expose() 12 16 def index(self): 13 17 return url("/Foo/") 14 index = expose()(index)15 18 19 @expose() 20 def foo(self): 21 return url("foo") 16 22 23 @expose() 24 def foo2(self): 25 return url("/foo") 26 27 @expose() 28 def redir(self): 29 turbogears.redirect("foo") 30 31 @expose() 32 def redir2(self): 33 raise turbogears.redirect("foo") 34 35 17 36 class MyRoot(controllers.RootController): 18 37 19 38 @expose() 20 39 def index(self): 21 pass40 return {} 22 41 23 42 def validation_error_handler(self, tg_source, tg_errors, *args, **kw): 24 43 self.functionname = tg_source.__name__ … … 215 234 216 235 def test_js_files(self): 217 236 """Can access the JavaScript files""" 218 testutil.create_request("/tg_js/MochiKit.js") 219 assert cherrypy.response.headers[ 220 "Content-Type"] == "application/x-javascript" 221 assert cherrypy.response.status == "200 OK" 237 response = testutil.create_request("/tg_js/MochiKit.js", status=200) 238 assert response.headers["Content-Type"] == "application/x-javascript" 222 239 223 240 def test_json_output(self): 224 testutil.create_request("/test?tg_format=json")225 import simplejson226 values = simplejson.loads(cherrypy.response.body[0])227 assert values == dict(title="Foobar", mybool=False,228 someval="niggles", tg_flash=None)229 assert cherrypy.response.headers["Content-Type"] == "text/javascript"241 response = testutil.create_request("/test?tg_format=json") 242 values = simplejson.loads(response.body) 243 expected = dict(title="Foobar", mybool=False, someval="niggles", 244 tg_flash=None) 245 eq_(values, expected) 246 assert response.headers["Content-Type"] == "text/javascript" 230 247 231 248 def test_implied_json(self): 232 testutil.create_request("/impliedjson?tg_format=json")233 assert '"title": "Blah"' in cherrypy.response.body[0]249 response = testutil.create_request("/impliedjson?tg_format=json") 250 assert '"title": "Blah"' in response.body 234 251 235 252 def test_allow_json(self): 236 testutil.create_request("/allowjson?tg_format=json")237 assert cherrypy.response.headers["Content-Type"] == "text/html"253 response = testutil.create_request("/allowjson?tg_format=json", status=500) 254 assert response.headers["Content-Type"] == "text/html", response.headers 238 255 239 256 def test_allow_json_config(self): 240 257 """JSON output can be enabled via config.""" … … 245 262 return dict(title="Foobar", mybool=False, someval="foo", 246 263 tg_html="turbogears.tests.simple") 247 264 cherrypy.root = JSONRoot() 248 testutil.create_request('/allowjsonconfig?tg_format=json')249 assert cherrypy.response.headers["Content-Type"] =="text/javascript"250 config.update({'tg.allow_json': False})265 response = testutil.create_request('/allowjsonconfig?tg_format=json') 266 assert response.headers["Content-Type"]=="text/javascript" 267 config.update({'tg.allow_json':False}) 251 268 252 269 def test_allow_json_config_false(self): 253 270 """Make sure JSON can still be restricted with a global config on.""" … … 258 275 return dict(title="Foobar", mybool=False, someval="foo", 259 276 tg_html="turbogears.tests.simple") 260 277 cherrypy.root = JSONRoot() 261 testutil.create_request('/allowjson?tg_format=json')262 assert cherrypy.response.headers["Content-Type"] =="text/html"278 response = testutil.create_request('/allowjson?tg_format=json', status=404) 279 assert response.headers["Content-Type"]=="text/html" 263 280 config.update({'tg.allow_json': False}) 264 281 265 282 def test_invalid_return(self): 266 testutil.create_request("/invalid") 267 assert cherrypy.response.status.startswith("500") 283 response = testutil.create_request("/invalid", status=500) 268 284 269 285 def test_strict_parameters(self): 270 config.update({"tg.strict_parameters": True}) 271 testutil.create_request( 272 "/save?submit=save&firstname=Foo&lastname=Bar&badparam=1") 273 assert cherrypy.response.status.startswith("500") 274 assert not hasattr(cherrypy.root, "errors") 286 config.update({"tg.strict_parameters" : True}) 287 response = testutil.create_request( 288 "/save?submit=save&firstname=Foo&lastname=Bar&badparam=1", 289 status = 500) 275 290 276 291 def test_throw_out_random(self): 277 292 """Can append random value to the URL to avoid caching problems.""" 278 testutil.create_request("/test?tg_random=1")279 assert "Paging all niggles" in cherrypy.response.body[0]293 response = testutil.create_request("/test?tg_random=1") 294 assert "Paging all niggles" in response.body 280 295 config.update({"tg.strict_parameters": True}) 281 testutil.create_request("/test?tg_random=1") 282 assert cherrypy.response.status.startswith("200") 283 assert "Paging all niggles" in cherrypy.response.body[0] 284 testutil.create_request("/test?tg_not_random=1") 285 assert cherrypy.response.status.startswith("500") 286 assert not hasattr(cherrypy.root, "errors") 296 response = testutil.create_request("/test?tg_random=1", status=200) 297 assert "Paging all niggles" in response.body 298 response = testutil.create_request("/test?tg_not_random=1", status=500) 287 299 288 300 def test_ignore_parameters(self): 289 301 config.update({"tg.strict_parameters": True}) 290 testutil.create_request("/test?ignore_me=1") 291 assert cherrypy.response.status.startswith("500") 302 response = testutil.create_request("/test?ignore_me=1", status=500) 292 303 assert not hasattr(cherrypy.root, "errors") 293 304 config.update({"tg.ignore_parameters": ['ignore_me', 'me_too']}) 294 testutil.create_request("/test?ignore_me=1") 295 assert "Paging all niggles" in cherrypy.response.body[0] 296 testutil.create_request("/test?me_too=1") 297 assert cherrypy.response.status.startswith("200") 298 assert "Paging all niggles" in cherrypy.response.body[0] 299 testutil.create_request("/test?me_not=1") 300 assert cherrypy.response.status.startswith("500") 305 response = testutil.create_request("/test?ignore_me=1") 306 assert "Paging all niggles" in response.body 307 response = testutil.create_request("/test?me_too=1", status=200) 308 assert "Paging all niggles" in response.body 309 testutil.create_request("/test?me_not=1", status=500) 301 310 assert not hasattr(cherrypy.root, "errors") 302 311 303 312 def test_retrieve_dict_directly(self): … … 305 314 assert d["title"] == "Foobar" 306 315 307 316 def test_templateOutput(self): 308 testutil.create_request("/test") 309 assert "Paging all niggles" in cherrypy.response.body[0] 317 response = testutil.create_request("/test") 318 print response.body 319 assert "Paging all niggles" in response.body 310 320 321 def test_throw_out_random(self): 322 """A random value can be appended to the URL to avoid caching 323 problems.""" 324 response = testutil.create_request("/test?tg_random=1") 325 assert "Paging all niggles" in response.body 326 311 327 def test_safari_unicode_fix(self): 312 testutil.create_request("/unicode", headers={'User-Agent':313 "Apple WebKit Safari/412.2"} )314 firstline = cherrypy.response.body[0].split('\n')[0]328 response = testutil.create_request("/unicode", headers={'User-Agent' : 329 "Apple WebKit Safari/412.2"}, status=200) 330 firstline = response.body.split('\n')[0] 315 331 assert firstline == "¿Habla español?" 316 332 assert isinstance(firstline, str) 317 333 318 334 def test_default_format(self): 319 335 """The default format can be set via expose""" 320 testutil.create_request("/returnjson") 321 firstline = cherrypy.response.body[0] 322 assert '"title": "Foobar"' in firstline 323 testutil.create_request("/returnjson?tg_format=html") 324 firstline = cherrypy.response.body[0] 325 assert '"title": "Foobar"' not in firstline 336 response = testutil.create_request("/returnjson") 337 assert '"title": "Foobar"' in response.body 338 response = testutil.create_request("/returnjson?tg_format=html", status=500) 339 assert '"title": "Foobar"' not in response.body 326 340 327 341 def test_content_type(self): 328 342 """The content-type can be set via expose""" 329 testutil.create_request("/contenttype")330 assert cherrypy.response.headers["Content-Type"] == "xml/atom"343 response = testutil.create_request("/contenttype") 344 assert response.headers["Content-Type"] == "xml/atom" 331 345 332 346 def test_returned_template_name(self): 333 testutil.create_request("/returnedtemplate")334 data = cherrypy.response.body[0].lower()347 response = testutil.create_request("/returnedtemplate") 348 data = response.body.lower() 335 349 assert "<body>" in data 336 350 assert 'groovy test template' in data 337 351 338 352 def test_returned_template_short(self): 339 testutil.create_request("/returnedtemplate_short")340 assert "Paging all foo" in cherrypy.response.body[0]353 response = testutil.create_request("/returnedtemplate_short") 354 assert "Paging all foo" in response.body 341 355 342 356 def test_expose_template_short(self): 343 testutil.create_request("/exposetemplate_short")344 assert "Paging all foo" in cherrypy.response.body[0]357 response = testutil.create_request("/exposetemplate_short") 358 assert "Paging all foo" in response.body 345 359 346 360 def test_validation(self): 347 361 """Data can be converted and validated""" 348 testutil.create_request("/istrue?value=true") 362 #TODO: Convert these to testutil.call, to make them less dependant on cp internals 363 response = testutil.create_request("/istrue?value=true") 349 364 assert cherrypy.root.value is True 350 365 testutil.create_request("/istrue?value=false") 351 366 assert cherrypy.root.value is False 352 367 cherrypy.root = MyRoot() 353 testutil.create_request("/istrue?value=foo")368 response = testutil.create_request("/istrue?value=foo") 354 369 assert not hasattr(cherrypy.root, "value") 355 370 assert cherrypy.root.functionname == "istrue" 356 testutil.create_request("/save?submit=send&firstname=John&lastname=Doe") 371 372 response = testutil.create_request("/save?submit=send&firstname=John&lastname=Doe") 357 373 assert cherrypy.root.fullname == "John Doe" 358 374 assert cherrypy.root.submit == "send" 359 375 testutil.create_request("/save?submit=send&firstname=Arthur") … … 369 385 assert cherrypy.root.errors.has_key("firstname") 370 386 371 387 def test_validation_with_schema(self): 372 """Data can be converted /validated with formencode.Schema instance"""388 """Data can be converted and validated with formencode.Schema instance""" 373 389 testutil.create_request("/save2?submit=send&firstname=Joe&lastname=Doe") 374 390 assert cherrypy.root.fullname == "Joe Doe" 375 391 assert cherrypy.root.submit == "send" … … 384 400 385 401 def test_other_template(self): 386 402 """'tg_html' in a returned dict will use the template specified there""" 387 testutil.create_request("/useother")388 assert "This is the other template" in cherrypy.response.body[0]403 response = testutil.create_request("/useother") 404 assert "This is the other template" in response.body, response.body 389 405 390 406 def test_cheetah_template(self): 391 407 """Cheetah templates can be used as well""" 392 testutil.create_request("/usecheetah") 393 body = cherrypy.response.body[0] 394 assert "This is the Cheetah test template." in body 395 assert "Paging all chimps." in body 408 response = testutil.create_request("/usecheetah") 409 assert "This is the Cheetah test template." in response.body 410 assert "Paging all chimps." in response.body 396 411 397 412 def test_run_with_trans(self): 398 413 """run_with_transaction is called only on topmost exposed method""" … … 405 420 406 421 def test_positional(self): 407 422 """Positional parameters should work""" 408 testutil.create_request("/pos/foo")423 response = testutil.create_request("/pos/foo") 409 424 assert cherrypy.root.posvalue == "foo" 410 425 411 426 def test_flash_plain(self): 412 427 """flash with strings should work""" 413 testutil.create_request("/flash_plain?tg_format=json") 414 import simplejson 415 values = simplejson.loads(cherrypy.response.body[0]) 428 response = testutil.create_request("/flash_plain?tg_format=json") 429 values = simplejson.loads(response.body) 416 430 assert values["tg_flash"] == "plain" 417 assert not cherrypy.response.simple_cookie.has_key("tg_flash")431 assert not response.cookies_set.has_key("tg_flash"), response.cookies_set 418 432 419 433 def test_flash_unicode(self): 420 434 """flash with unicode objects should work""" 421 testutil.create_request("/flash_unicode?tg_format=json") 422 import simplejson 423 values = simplejson.loads(cherrypy.response.body[0]) 435 response = testutil.create_request("/flash_unicode?tg_format=json") 436 values = simplejson.loads(response.body) 424 437 assert values["tg_flash"] == u"\xfcnicode" 425 assert not cherrypy.response.simple_cookie.has_key("tg_flash")438 assert not response.cookies_set.has_key("tg_flash"), response.cookies_set 426 439 427 440 def test_flash_on_redirect(self): 428 441 """flash must survive a redirect""" 429 testutil.create_request("/flash_redirect?tg_format=json") 430 assert cherrypy.response.status.startswith("302") 431 testutil.create_request(cherrypy.response.headers["Location"], 432 headers=dict(Cookie 433 =cherrypy.response.simple_cookie.output(header="").strip())) 434 import simplejson 435 values = simplejson.loads(cherrypy.response.body[0]) 442 response = testutil.create_request("/flash_redirect?tg_format=json", 443 status = 302) 444 response = testutil.create_request(response.headers["Location"], 445 headers=dict(Cookie=response.cookies_set.output())) 446 print response.body 447 values = simplejson.loads(response.body) 436 448 assert values["tg_flash"] == u"redirect \xfcnicode" 437 449 438 450 def test_double_flash(self): … … 440 452 # Here we are calling method that sets a flash message. However flash 441 453 # cookie is still there. Turbogears should discard old flash message 442 454 # from cookie and use new one, set by flash_plain(). 443 testutil.create_request("/flash_plain?tg_format=json", 444 headers=dict(Cookie='tg_flash="old flash"; Path=/;')) 445 import simplejson 446 values = simplejson.loads(cherrypy.response.body[0]) 455 response = testutil.create_request("/flash_plain?tg_format=json", 456 headers= {'Cookie':'tg_flash="old flash"; Path=/;'}) 457 values = simplejson.loads(response.body) 447 458 assert values["tg_flash"] == "plain" 448 assert cherrypy.response.simple_cookie.has_key("tg_flash"), \459 assert response.cookies_set.has_key("tg_flash"), \ 449 460 "Cookie clearing request should be present" 450 flashcookie = cherrypy.response.simple_cookie['tg_flash']461 flashcookie = response.cookies_set['tg_flash'] 451 462 assert flashcookie['expires'] == 0 452 463 453 464 def test_set_kid_outputformat_in_config(self): 454 465 """the outputformat for kid can be set in the config""" 455 466 config.update({'kid.outputformat': 'xhtml'}) 456 testutil.create_request('/test') 457 response = cherrypy.response.body[0] 458 assert '<!DOCTY