Ticket #1762: webtest-luke-tweaked.patch
| File webtest-luke-tweaked.patch, 85.9 kB (added by kskuhlman, 2 years ago) |
|---|
-
setup.py
old new 24 24 "TurboCheetah >= 1.0", 25 25 "TurboJson >= 1.1.2", 26 26 "tgMochiKit >= 0.1alpha", 27 "WebTest", 27 28 ] 28 29 29 30 # for when we get rid of Kid & SQLObject dependency -
turbogears/identity/tests/test_identity.py
old new 55 55 56 56 @expose() 57 57 def index(self): 58 pass58 return dict() 59 59 60 60 @expose() 61 61 def identity_failed(self, **kw): … … 69 69 @expose() 70 70 @identity.require(in_group('peon')) 71 71 def in_peon_group(self): 72 assert("samIam", cherrypy.serving.request.identity.user_name) 72 73 return 'in_peon_group' 73 74 74 75 @expose() … … 136 137 return 'wrong params: %s\nexpected unicode objects' \ 137 138 ' for all strings' % cherrypy.request.params 138 139 140 @expose() 141 def is_anonymous(self): 142 assert cherrypy.serving.request.identity.user_name == None 143 assert cherrypy.serving.request.identity.anonymous 144 assert identity.current.anonymous 145 return 'is_anonymous' 139 146 140 class TestIdentity(unittest.TestCase):141 147 148 149 class TestIdentity(testutil.TGWebTest): 150 142 151 def setUp(self): 143 152 # identity requires visit and a failure_url 144 153 test_config = {'global': { … … 152 161 config.configure_loggers(test_config) 153 162 config.update(test_config['global']) 154 163 cherrypy.root = IdentityRoot() 155 startup.startTurboGears()164 testutil.TGWebTest.setUp(self) 156 165 self.init_model() 157 166 158 167 def tearDown(self): 159 startup.stopTurboGears()168 testutil.TGWebTest.tearDown(self) 160 169 config.update(self._original_config) 161 170 162 171 def init_model(self): … … 181 190 182 191 def test_user_password_parameters(self): 183 192 """Controller can receive user_name and password parameters.""" 184 testutil.create_request('/new_user_setup?user_name=test&password=pw') 185 firstline = cherrypy.response.body[0] 186 assert 'test pw' in firstline, firstline 193 response = self.app.get('/new_user_setup?user_name=test&password=pw') 194 assert 'test pw' in response 187 195 188 196 def test_user_exists(self): 189 197 u = TG_User.by_user_name('samIam') … … 205 213 config.update({'identity.soprovider.encryption_algorithm': None}) 206 214 # force new config values to load 207 215 startup.startTurboGears() 208 testutil.create_request('/')216 self.app.get('/') 209 217 hub.begin() 210 218 u = TG_User.by_user_name('samIam') 211 219 u.password = u'garçon' … … 219 227 config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 220 228 # force new config values to load 221 229 startup.startTurboGears() 222 testutil.create_request('/')230 self.app.get('/') 223 231 hub.begin() 224 232 u = TG_User.by_user_name('samIam') 225 233 u.password = 'password' … … 234 242 config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 235 243 # force new config values to load 236 244 startup.startTurboGears() 237 testutil.create_request('/')245 self.app.get('/') 238 246 hub.begin() 239 247 u = TG_User.by_user_name('samIam') 240 248 u.password = u'garçon' … … 248 256 config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 249 257 # force new config values to load 250 258 startup.startTurboGears() 251 testutil.create_request('/')259 self.app.get('/') 252 260 hub.begin() 253 261 u = TG_User.by_user_name('samIam') 254 262 u.password = 'password' … … 263 271 config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 264 272 # force new config values to load 265 273 startup.startTurboGears() 266 testutil.create_request('/')274 self.app.get('/') 267 275 hub.begin() 268 276 u = TG_User.by_user_name('samIam') 269 277 u.password = u'garçon' … … 280 288 config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 281 289 # force new config values to load 282 290 startup.startTurboGears() 283 testutil.create_request('/')291 self.app.get('/') 284 292 hub.begin() 285 293 u = TG_User.by_user_name('samIam') 286 294 u.password = u'garçon'.encode('UTF-8') … … 295 303 config.update({'identity.soprovider.encryption_algorithm':'sha1'}) 296 304 # force new config values to load 297 305 startup.startTurboGears() 298 testutil.create_request('/')306 self.app.get('/') 299 307 hub.begin() 300 308 u = TG_User.by_user_name('samIam') 301 309 u.set_password_raw('password') … … 308 316 config.update({'identity.soprovider.encryption_algorithm':'sha1'}) 309 317 # force new config values to load 310 318 startup.startTurboGears() 311 testutil.create_request('/')319 self.app.get('/') 312 320 hub.begin() 313 321 u = TG_User.by_user_name('samIam') 314 322 u.set_password_raw(u'garçon') … … 324 332 'identity.tests.test_identity.mycustomencrypt'}) 325 333 # force new config values to load 326 334 startup.startTurboGears() 327 testutil.create_request('/')335 self.app.get('/') 328 336 hub.begin() 329 337 u = TG_User.by_user_name('samIam') 330 338 u.password = 'password' … … 335 343 336 344 def test_anonymous_browsing(self): 337 345 """Test if we can show up anonymously.""" 338 testutil.create_request('/')339 assert identity.current.anonymous346 response = self.app.get('/is_anonymous') 347 assert 'is_anonymous' in response 340 348 341 349 def test_deny_anonymous(self): 342 350 """Test that we have secured an url from anonymous users.""" 343 testutil.create_request('/logged_in_only') 344 firstline = cherrypy.response.body[0] 345 assert 'identity_failed_answer' in firstline, firstline 351 response = self.app.get('/logged_in_only') 352 assert 'identity_failed_answer' in response 346 353 347 354 def test_deny_anonymous_viewable(self): 348 355 """Test that a logged in user can see an resource blocked 349 356 from anonymous users.""" 350 testutil.create_request('/logged_in_only?'357 response = self.app.get('/logged_in_only?' 351 358 'user_name=samIam&password=secret&login=Login') 352 firstline = cherrypy.response.body[0] 353 assert 'logged_in_only' in firstline, firstline 359 assert 'logged_in_only' in response 354 360 355 361 def test_logout(self): 356 362 """Test that logout works and session is gets invalid afterwards.""" 357 testutil.create_request('/in_peon_group?'363 response = self.app.get('/in_peon_group?' 358 364 'user_name=samIam&password=secret&login=Login') 359 self.assertEquals("samIam", cherrypy.serving.request.identity.user_name) 360 session_id = re.match("Set-Cookie: (.*?); Path.*", 361 str(cherrypy.response.simple_cookie)).group(1) 362 testutil.create_request('/logout', headers={'Cookie': session_id }) 363 self.assertEquals(None, cherrypy.serving.request.identity.user_name) 364 assert cherrypy.serving.request.identity.anonymous 365 session_id = response.headers['Set-Cookie'] 366 response = self.app.get('/logout', headers={'Cookie': session_id }) 367 response = self.app.get('/is_anonymous', headers={'Cookie': session_id}) 368 assert response.body == 'is_anonymous' 365 369 366 370 def test_logout_with_set_identity(self): 367 371 """Test that logout works even when there is no visit_key … … 522 526 def setUp(self): 523 527 self._identity_on = config.get('identity.on', False) 524 528 config.update({'identity.on': False}) 525 try:526 self._provider = cherrypy.request.identityProvider527 except AttributeError:528 self._provider= None529 cherrypy.request.identityProvider = None530 529 startup.startTurboGears() 531 530 testutil.DBTest.setUp(self) 532 531 533 532 def tearDown(self): 534 533 testutil.DBTest.tearDown(self) 535 534 startup.stopTurboGears() 536 cherrypy.request.identityProvider = self._provider537 535 config.update({'identity.on': self._identity_on}) 538 536 539 537 def test_create_user(self): -
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() 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() 46 48 47 def test_form_translation():48 """Form input is translated into properly converted parameters"""49 root = MyRoot()50 cherrypy.root = root51 testutil.create_request("/testform?name=ed&date=11/05/2005&age=5")52 assert root.name == "ed"53 assert root.age == 554 49 55 def test_form_translation_new_style(): 56 """Form input is translated into properly converted parameters""" 57 root = MyRoot() 58 cherrypy.root = root 59 testutil.create_request("/testform_new_style?name=ed&date=11/05/2005&age=5&") 60 assert root.name == "ed" 61 assert root.age == 5 50 class TestFormControllers(testutil.TGWebTest): 62 51 63 def test_invalid_form_with_error_handling(): 64 """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 52 def test_form_translation(self): 53 """Form input is translated into properly converted parameters""" 54 root = MyRoot() 55 cherrypy.root = root 56 self.app.get("/testform?name=ed&date=11/05/2005&age=5") 57 assert root.name == "ed" 58 assert root.age == 5 68 59 69 def test_css_should_appear(): 70 """CSS should appear when asked for""" 71 testutil.create_request("/") 72 assert "calendar-system.css" in cherrypy.response.body[0] 60 def test_form_translation_new_style(self): 61 """Form input is translated into properly converted parameters""" 62 root = MyRoot() 63 cherrypy.root = root 64 self.app.get("/testform_new_style?name=ed&date=11/05/2005&age=5&") 65 assert root.name == "ed" 66 assert root.age == 5 73 67 74 def test_javascript_should_appear(): 75 """JavaScript should appear when asked for""" 76 testutil.create_request("/") 77 assert "calendar.js" in cherrypy.response.body[0] 68 def test_invalid_form_with_error_handling(self): 69 """Invalid forms can be handled by the method""" 70 root = cherrypy.root 71 self.app.get("/testform?name=ed&age=edalso&date=11/05/2005") 72 assert root.has_errors 78 73 79 def test_include_mochikit(): 80 """JSLinks (and MochiKit especially) can be included easily""" 81 testutil.create_request("/usemochi") 82 assert "MochiKit.js" in cherrypy.response.body[0] 74 def test_css_should_appear(self): 75 """CSS should appear when asked for""" 76 cherrypy.root = MyRoot() 77 response = self.app.get("/") 78 assert "calendar-system.css" in response 83 79 84 def test_suppress_mochikit(): 85 """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 # 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 80 def test_javascript_should_appear(self): 81 """JavaScript should appear when asked for""" 82 cherrypy.root = MyRoot() 83 response = self.app.get("/") 84 assert "calendar.js" in response 95 85 96 def test_mochikit_everywhere(): 97 """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] 86 def test_include_mochikit(self): 87 """JSLinks (and MochiKit especially) can be included easily""" 88 cherrypy.root = MyRoot() 89 response = self.app.get("/usemochi") 90 assert "MochiKit.js" in response 102 91 103 def test_mochikit_nowhere(): 104 """Setting tg.mochikit_suppress will prevent including it everywhere""" 105 config.update({"global": {"tg.mochikit_all": True}}) 106 config.update({"global": {"tg.mochikit_suppress": True}}) 107 testutil.create_request("/") 108 config.update({"global": {"tg.mochikit_all": False}}) 109 config.update({"global": {"tg.mochikit_suppress": False}}) 110 assert "MochiKit.js" not in cherrypy.response.body[0] 92 def test_suppress_mochikit(self): 93 """MochiKit inclusion can be suppressed""" 94 cherrypy.root = MyRoot() 95 config.update({"global": {"tg.mochikit_suppress": True}}) 96 response = self.app.get("/usemochi") 97 suppressed_body = response.body 98 # repair the fixture 99 config.update({"global": {"tg.mochikit_suppress": False}}) 100 response = self.app.get("/usemochi") 101 included_body = response.body 102 assert "MochiKit.js" not in suppressed_body 103 assert "MochiKit.js" in included_body 111 104 112 def test_include_widgets(): 113 """Any widget can be included everywhere by setting tg.include_widgets""" 114 config.update({"global": {"tg.include_widgets": ["mochikit"]}}) 115 testutil.create_request("/") 116 config.update({"global": {"tg.include_widgets": []}}) 117 assert "MochiKit.js" in cherrypy.response.body[0] 105 def test_mochikit_everywhere(self): 106 """MochiKit can be included everywhere by setting tg.mochikit_all""" 107 cherrypy.root = MyRoot() 108 config.update({"global": {"tg.mochikit_all": True}}) 109 response = self.app.get("/") 110 config.update({"global": {"tg.mochikit_all": False}}) 111 assert "MochiKit.js" in response 118 112 113 def test_mochikit_nowhere(self): 114 """Setting tg.mochikit_suppress will prevent including it everywhere""" 115 cherrypy.root = MyRoot() 116 config.update({"global": {"tg.mochikit_all": True}}) 117 config.update({"global": {"tg.mochikit_suppress": True}}) 118 response = self.app.get("/") 119 config.update({"global": {"tg.mochikit_all": False}}) 120 config.update({"global": {"tg.mochikit_suppress": False}}) 121 assert "MochiKit.js" not in response 119 122 123 def test_include_widgets(self): 124 """Any widget can be included everywhere by setting tg.include_widgets""" 125 cherrypy.root = MyRoot() 126 config.update({"global": {"tg.include_widgets": ["mochikit"]}}) 127 response = self.app.get("/") 128 config.update({"global": {"tg.include_widgets": []}}) 129 assert "MochiKit.js" in response 130 131 120 132 class State(object): 121 133 counter = 0 122 134 -
turbogears/tests/test_errorhandling.py
old new 208 208 return dict(title="Nested") 209 209 210 210 211 class TestErrorHandler( unittest.TestCase):211 class TestErrorHandler(testutil.TGWebTest): 212 212 213 213 def setUp(self): 214 testutil.TGWebTest.setUp(self) 214 215 cherrypy.root = MyRoot() 215 216 cherrypy.root.nestedcontroller = NestedController() 216 217 217 218 def test_defaultErrorHandler(self): 218 219 """Default error handler.""" 219 testutil.create_request("/defaulterror?bar=abc")220 self.failUnless("Default error handler" in cherrypy.response.body[0])221 testutil.create_request("/defaulterror?bar=true")222 self.failUnless("Default error provider" in cherrypy.response.body[0])220 response = self.app.get("/defaulterror?bar=abc") 221 self.failUnless("Default error handler" in response) 222 response = self.app.get("/defaulterror?bar=true") 223 self.failUnless("Default error provider" in response) 223 224 224 225 def test_specialisedErrorHandler(self): 225 226 """Error handler specialisation.""" 226 testutil.create_request("/specialisederror?bar=abc&baz=a@b.com")227 self.failUnless("Default error handler" in cherrypy.response.body[0])228 testutil.create_request("/specialisederror?baz=abc&bar=1")227 response = self.app.get("/specialisederror?bar=abc&baz=a@b.com") 228 self.failUnless("Default error handler" in response) 229 response = self.app.get("/specialisederror?baz=abc&bar=1") 229 230 self.failUnless("Specialised error handler" in 230 cherrypy.response.body[0])231 testutil.create_request("/specialisederror?bar=1&baz=a@b.com")231 response) 232 response = self.app.get("/specialisederror?bar=1&baz=a@b.com") 232 233 self.failUnless("Specialised error provider" in 233 cherrypy.response.body[0])234 response) 234 235 235 236 def test_exceptionErrorHandler(self): 236 237 """Error handler for exceptions.""" 237 testutil.create_request("/exceptionerror")238 self.failUnless("Default error handler" in cherrypy.response.body[0])238 response = self.app.get("/exceptionerror") 239 self.failUnless("Default error handler" in response) 239 240 240 241 def test_recursiveErrorHandler(self): 241 242 """Recursive error handler.""" 242 testutil.create_request("/recursiveerror?bar=abc")243 self.failUnless("Recursive error handler" in cherrypy.response.body[0])244 testutil.create_request("/recursiveerror?bar=1")243 response = self.app.get("/recursiveerror?bar=abc") 244 self.failUnless("Recursive error handler" in response) 245 response = self.app.get("/recursiveerror?bar=1") 245 246 self.failUnless("Recursive error provider" in 246 cherrypy.response.body[0])247 response) 247 248 248 249 def test_implicitErrorHandler(self): 249 250 """Implicit error handling.""" 250 testutil.create_request("/impliciterror?bar=abc")251 response = self.app.get("/impliciterror?bar=abc") 251 252 self.failUnless("Implicit error handler" in 252 cherrypy.response.body[0])253 testutil.create_request("/impliciterror?bar=1")253 response) 254 response = self.app.get("/impliciterror?bar=1") 254 255 self.failUnless("Implicit error provider" in 255 cherrypy.response.body[0])256 response) 256 257 257 258 def test_normalMethodErrorHandler(self): 258 259 """Normal method as an error handler.""" 259 testutil.create_request("/normalmethodcaller?bar=abc")260 self.failUnless("Normal method" in cherrypy.response.body[0])261 testutil.create_request("/normalmethodcaller?bar=true")262 self.failUnless("Normal method caller" in cherrypy.response.body[0])260 response = self.app.get("/normalmethodcaller?bar=abc") 261 self.failUnless("Normal method" in response) 262 response = self.app.get("/normalmethodcaller?bar=true") 263 self.failUnless("Normal method caller" in response) 263 264 264 265 def test_infiniteRecursionPrevention(self): 265 266 """Infinite recursion prevention.""" 266 testutil.create_request("/infiniteloop")267 self.failUnless("Exception 2" in cherrypy.response.body[0])267 response = self.app.get("/infiniteloop") 268 self.failUnless("Exception 2" in response) 268 269 269 270 def test_positionalArgs(self): 270 271 """Positional argument validation.""" 271 testutil.create_request("/positionalargs/first/23/third?bar=abc")272 self.failUnless("Default error handler" in cherrypy.response.body[0])273 testutil.create_request("/positionalargs/first/abc/third?bar=false")274 self.failUnless("Default error handler" in cherrypy.response.body[0])275 testutil.create_request("/positionalargs/first/abc/third?bar=abc")276 self.failUnless("Default error handler" in cherrypy.response.body[0])277 testutil.create_request("/positionalargs/first/23/third?bar=true")278 self.failUnless("Positional arguments" in cherrypy.response.body[0])272 response = self.app.get("/positionalargs/first/23/third?bar=abc") 273 self.failUnless("Default error handler" in response) 274 response = self.app.get("/positionalargs/first/abc/third?bar=false") 275 self.failUnless("Default error handler" in response) 276 response = self.app.get("/positionalargs/first/abc/third?bar=abc") 277 self.failUnless("Default error handler" in response) 278 response = self.app.get("/positionalargs/first/23/third?bar=true") 279 self.failUnless("Positional arguments" in response) 279 280 self.failUnless(cherrypy.root.first == "first") 280 281 self.failUnless(cherrypy.root.second == 23) 281 282 self.failUnless(cherrypy.root.third == "third") 282 283 283 284 def test_missingArgs(self): 284 285 """Arguments required in validation missing.""" 285 testutil.create_request("/missingargs")286 self.failUnless("Default error handler" in cherrypy.response.body[0])287 testutil.create_request("/missingargs?bar=12")288 self.failUnless("Missing args provider" in cherrypy.response.body[0])286 response = self.app.get("/missingargs") 287 self.failUnless("Default error handler" in response) 288 response = self.app.get("/missingargs?bar=12") 289 self.failUnless("Missing args provider" in response) 289 290 290 291 def test_nohandler(self): 291 292 """No error hanlder declared.""" 292 testutil.create_request("/nohandler")293 self.failUnless("Exception raised" in cherrypy.response.body[0])293 response = self.app.get("/nohandler") 294 self.failUnless("Exception raised" in response) 294 295 295 296 def test_bindArgs(self): 296 297 """Arguments can be bond to an error handler.""" 297 testutil.create_request("/bindargs")298 self.failUnless("123" in cherrypy.response.body[0])298 response = self.app.get("/bindargs") 299 self.failUnless("123" in response) 299 300 300 301 def test_notExposed(self): 301 302 """Validation error handling is decoupled from expose.""" 302 testutil.create_request("/notexposedcaller?foo=a&bar=rab&baz=c")303 self.failUnless("Not exposed error" in cherrypy.response.body[0])304 self.failUnless("rab" in cherrypy.response.body[0])303 response = self.app.get("/notexposedcaller?foo=a&bar=rab&baz=c") 304 self.failUnless("Not exposed error" in response) 305 self.failUnless("rab" in response) 305 306 306 307 def test_continuations(self): 307 308 """Continuations via error handling mechanism.""" 308 testutil.create_request("/continuationcaller?bar=a")309 self.failUnless("Continuation caller" in cherrypy.response.body[0])309 response = self.app.get("/continuationcaller?bar=a") 310 self.failUnless("Continuation caller" in response) 310 311 self.failUnless(cherrypy.root.continuation == True) 311 312 312 313 def test_nested(self): 313 314 """Potentially ambiguous cases.""" 314 testutil.create_request("/nest?bar=a")315 self.failUnless("Default error handler" in cherrypy.response.body[0])316 testutil.create_request("/nestedcontroller/nest?bar=a")317 self.failUnless("Nested" in cherrypy.response.body[0])315 response = self.app.get("/nest?bar=a") 316 self.failUnless("Default error handler" in response) 317 response = self.app.get("/nestedcontroller/nest?bar=a") 318 self.failUnless("Nested" in response) 318 319 319 320 def test_failsafe(self): 320 321 """Failsafe values for erroneous input.""" 321 testutil.create_request("/failsafenone?bar=a&baz=b")322 self.failUnless('"bar": "a"' in cherrypy.response.body[0])323 self.failUnless('"baz": "b"' in cherrypy.response.body[0])324 testutil.create_request("/failsafevaluesdict?bar=a&baz=b")325 self.failUnless('"bar": 1' in cherrypy.response.body[0])326 self.failUnless('"baz": 2' in cherrypy.response.body[0])327 testutil.create_request("/failsafevaluesatom?bar=a&baz=b")328 self.failUnless('"bar": 13' in cherrypy.response.body[0])329 self.failUnless('"baz": 13' in cherrypy.response.body[0])330 testutil.create_request("/failsafemaperrors?bar=a&baz=b")322 response = self.app.get("/failsafenone?bar=a&baz=b") 323 self.failUnless('"bar": "a"' in response) 324 self.failUnless('"baz": "b"' in response) 325 response = self.app.get("/failsafevaluesdict?bar=a&baz=b") 326 self.failUnless('"bar": 1' in response) 327 self.failUnless('"baz": 2' in response) 328 response = self.app.get("/failsafevaluesatom?bar=a&baz=b") 329 self.failUnless('"bar": 13' in response) 330 self.failUnless('"baz": 13' in response) 331 response = self.app.get("/failsafemaperrors?bar=a&baz=b") 331 332 self.failUnless('"bar": "Please enter an integer value"' in 332 cherrypy.response.body[0])333 response) 333 334 self.failUnless('"baz": "Please enter an integer value"' in 334 cherrypy.response.body[0])335 testutil.create_request("/failsafeformencode?bar=a&baz=b")336 self.failUnless('"bar": 1' in cherrypy.response.body[0])337 self.failUnless('"baz": 2' in cherrypy.response.body[0])338 testutil.create_request("/failsafedefaults?bar=a&baz=b")339 self.failUnless('"bar": 1' in cherrypy.response.body[0])340 self.failUnless('"baz": 2' in cherrypy.response.body[0])335 response) 336 response = self.app.get("/failsafeformencode?bar=a&baz=b") 337 self.failUnless('"bar": 1' in response) 338 self.failUnless('"baz": 2' in response) 339 response = self.app.get("/failsafedefaults?bar=a&baz=b") 340 self.failUnless('"bar": 1' in response,response) 341 self.failUnless('"baz": 2' in response) -
turbogears/tests/test_sqlalchemy.py
old new 9 9 from turbogears.database import metadata, session, mapper, \ 10 10 bind_metadata, get_metadata 11 11 from turbogears.controllers import RootController 12 from turbogears.testutil import create_request, sqlalchemy_cleanup, \12 from turbogears.testutil import sqlalchemy_cleanup, TGWebTest, \ 13 13 capture_log, print_log 14 14 15 15 … … 162 162 return "No exceptions occurred" 163 163 164 164 165 def test_implicit_trans_no_error(): 166 """If a controller runs sucessfully, the transaction is commited.""" 167 capture_log("turbogears.database") 168 cherrypy.root = MyRoot() 169 create_request("/no_error?name=A.%20Dent") 170 output = cherrypy.response.body[0] 171 print output 172 print_log() 173 q = session.query(Person) 174 arthur = q.filter_by(name="A. Dent").first() 175 assert 'someconfirmhandler' in output, \ 176 'The no error should have redirected to someconfirmhandler' 177 assert arthur is not None, 'Person arthur should have been saved!' 178 assert arthur.name == "A. Dent", 'Person arthur should be named "A. Dent"' 165 class TestSQLAlchemy(TGWebTest): 179 166 180 def test_raise_sa_exception(): 181 """If a controller causes an SA exception, it is raised properly.""" 182 capture_log("turbogears.database") 183 cherrypy.root = MyRoot() 184 create_request("/create_person?id=20") 185 output = cherrypy.response.body[0] 186 print_log() 187 print output 188 assert 'No exceptions occurred' in output 189 assert cherrypy.response.status.startswith("200") 190 create_request("/create_person?id=20") 191 output = cherrypy.response.body[0] 192 assert cherrypy.response.status.startswith("500") 193 print output 194 assert 'KARL25' not in output, \ 195 'Exception should NOT have been handled by our handler' 196 assert 'DBAPIError' in output, \ 197 'The page should have displayed an SQLAlchemy exception' 167 def test_implicit_trans_no_error(self): 168 """If a controller runs sucessfully, the transaction is commited.""" 169 #capture_log("turbogears.database") 170 cherrypy.root = MyRoot() 171 response = self.app.get("/no_error?name=A.%20Dent") 172 output = response.body 173 #print output 174 #print_log() 175 q = session.query(Person) 176 arthur = q.filter_by(name="A. Dent").first() 177 assert 'someconfirmhandler' in output, \ 178 'The no error should have redirected to someconfirmhandler' 179 assert arthur is not None, 'Person arthur should have been saved!' 180 assert arthur.name == "A. Dent", 'Person arthur should be named "A. Dent"' 198 181 199 def test_user_exception(): 200 """If a controller raises an exception, transactions are rolled back.""" 201 capture_log("turbogears.database") 202 cherrypy.root = MyRoot() 203 create_request("/create_person?id=19&docom=0&doerr=1&name=Martin%20GAL") 204 output = cherrypy.response.body[0] 205 print_log() 206 print output 207 assert 'KARL25' in output, \ 208 'The exception handler should have answered us' 209 p = session.query(Person).get(19) 210 assert p is None, \ 211 'This Person should have been rolled back: %s' % p 182 def test_raise_sa_exception(self): 183 """If a controller causes an SA exception, it is raised properly.""" 184 #capture_log("turbogears.database") 185 cherrypy.root = MyRoot() 186 response = self.app.get("/create_person?id=20", status=200) 187 output = response.body 188 #print_log() 189 print output 190 assert 'No exceptions occurred' in output 191 response = self.app.get("/create_person?id=20", status=500) 192 output = response.body 193 print output 194 assert 'KARL25' not in output, \ 195 'Exception should NOT have been handled by our handler' 196 assert 'DBAPIError' in output, \ 197 'The page should have displayed an SQLAlchemy exception' 212 198 213 def test_user_redirect(): 214 """If a controller redirects, transactions are committed.""" 215 cherrypy.root = MyRoot() 216 create_request("/create_person?id=22&doerr=2") 217 assert session.query(Person).get(22) is not None, \ 218 'The controller only redirected, the Person should have been saved' 199 def test_user_exception(self): 200 """If a controller raises an exception, transactions are rolled back.""" 201 #capture_log("turbogears.database") 202 cherrypy.root = MyRoot() 203 response = self.app.get("/create_person?id=19&docom=0&doerr=1&name=Martin%20GAL") 204 output = response.body 205 #print_log() 206 print output 207 assert 'KARL25' in output, \ 208 'The exception handler should have answered us' 209 p = session.query(Person).get(19) 210 assert p is None, \ 211 'This Person should have been rolled back: %s' % p 219 212 220 def test_cntrl_commit(): 221 """It's safe to commit a transaction in the controller.""" 222 cherrypy.root = MyRoot() 223 create_request("/create_person?id=23&docom=1") 224 assert 'InvalidRequestError' not in cherrypy.response.body[0] 225 assert session.query(Person).get(23) is not None, \ 226 'The Person 23 should have been saved during commit inside controller' 213 def test_user_redirect(self): 214 """If a controller redirects, transactions are committed.""" 215 cherrypy.root = MyRoot() 216 self.app.get("/create_person?id=22&doerr=2") 217 assert session.query(Person).get(22) is not None, \ 218 'The controller only redirected, the Person should have been saved' 227 219 228 def test_cntrl_commit2(): 229 """A commit inside the controller is not rolled back by the exception.""" 230 cherrypy.root = MyRoot() 231 create_request("/create_person?id=24&docom=1&doerr=1") 232 assert 'InvalidRequestError' not in cherrypy.response.body[0] 233 assert session.query(Person).get(24) is not None, \ 234 'The Person 24 should have been saved during commit' \ 235 ' inside controller and not rolled back' 220 def test_cntrl_commit(self): 221 """It's safe to commit a transaction in the controller.""" 222 cherrypy.root = MyRoot() 223 response = self.app.get("/create_person?id=23&docom=1") 224 assert 'InvalidRequestError' not in response 225 assert session.query(Person).get(23) is not None, \ 226 'The Person 23 should have been saved during commit inside controller' 236 227 237 def test_cntrl_flush(): 238 """It's safe to flush in the controller.""" 239 cherrypy.root = MyRoot() 240 create_request("/create_person?id=25&doflush=1") 241 print cherrypy.response.body[0] 242 assert 'No exceptions occurred' in cherrypy.response.body[0] 243 create_request("/create_person?id=25&doflush=0") 244 assert cherrypy.response.status.startswith("500") 245 assert 'IntegrityError' in cherrypy.response.body[0] 246 create_request("/create_person?id=25&doflush=1") 247 assert cherrypy.response.status.startswith("200") 248 assert 'IntegrityError' in cherrypy.response.body[0] 249 create_request("/create_person?id=25&doflush=2") 250 assert cherrypy.response.status.startswith("200") 251 assert 'No exceptions occurred' in cherrypy.response.body[0] 228 def test_cntrl_commit2(self): 229 """A commit inside the controller is not rolled back by the exception.""" 230 cherrypy.root = MyRoot() 231 response = self.app.get("/create_person?id=24&docom=1&doerr=1") 232 assert 'InvalidRequestError' not in response 233 assert session.query(Person).get(24) is not None, \ 234 'The Person 24 should have been saved during commit' \ 235 ' inside controller and not rolled back' 252 236 237 def test_cntrl_flush(self): 238 """It's safe to flush in the controller.""" 239 cherrypy.root = MyRoot() 240 response = self.app.get("/create_person?id=25&doflush=1") 241 assert 'No exceptions occurred' in response 242 response = self.app.get("/create_person?id=25&doflush=0", status=500) 243 assert 'IntegrityError' in response 244 response = self.app.get("/create_person?id=25&doflush=1") 245 assert 'IntegrityError' in response 246 response = self.app.get("/create_person?id=25&doflush=2") 247 assert 'No exceptions occurred' in response 253 248 249 254 250 # Exception handling with rollback 255 251 256 252 class RbRoot(RootController): … … 292 288 session.rollback() 293 289 raise Exception('test') 294 290 291 class TestExceptionRollback(TGWebTest): 295 292 296 def test_exc_rollback():297 """An exception within a controller method causes a rollback.293 def test_exc_rollback(self): 294 """An exception within a controller method causes a rollback. 298 295 299 Try to create a user that should rollback because of an exception300 so user 25 should not exist, but user 26 should be present since it301 is created by the exception handler.296 Try to create a user that should rollback because of an exception 297 so user 25 should not exist, but user 26 should be present since it 298 is created by the exception handler. 302 299 303 """ 304 cherrypy.root = RbRoot() 305 create_request('/doerr?id=26') 306 output = cherrypy.response.body[0] 307 print output 308 assert 'KARL27' in output, 'Exception handler should have answered' 309 assert session.query(User).get(26) is None 310 assert session.query(User).get(27) is not None 300 """ 301 cherrypy.root = RbRoot() 302 response = self.app.get('/doerr?id=26') 303 assert 'KARL27' in response, 'Exception handler should have answered' 304 assert session.query(User).get(26) is None 305 assert session.query(User).get(27) is not None 311 306 312 def test_exc_rollback2():313 """An exception within a controller method causes a rollback.307 def test_exc_rollback2(self): 308 """An exception within a controller method causes a rollback. 314 309 315 Try to create a user that should rollback because of an exception316 so user XX should not exist.310 Try to create a user that should rollback because of an exception 311 so user XX should not exist. 317 312 318 """ 319 cherrypy.root = RbRoot() 320 create_request('/doerr?id=XX') 321 output = cherrypy.response.body[0] 322 assert 'KARL27' in output, 'Exception handler should have answered' 323 assert session.query(User).get('XX') is None 313 """ 314 cherrypy.root = RbRoot() 315 response = self.app.get('/doerr?id=XX') 316 assert 'KARL27' in response, 'Exception handler should have answered' 317 assert session.query(User).get('XX') is None 324 318 325 def test_exc_done_rollback(): 326 """No problems with error handler if controller manually rollbacks.""" 327 cherrypy.root = RbRoot() 328 create_request('/doerr?id=28&dorb=1') 329 output = cherrypy.response.body[0] 330 assert 'KARL27' in output, 'Exception handler should have answered' 331 assert session.query(User).get(28) is None 332 assert session.query(User).get(29) is not None 319 def test_exc_done_rollback(self): 320 """No problems with error handler if controller manually rollbacks.""" 321 cherrypy.root = RbRoot() 322 response = self.app.get('/doerr?id=28&dorb=1') 323 assert 'KARL27' in response, 'Exception handler should have answered' 324 assert session.query(User).get(28) is None 325 assert session.query(User).get(29) is not None 333 326 334 327 335 328 # Session freshness tests … … 352 345 assert session.query(Test).get(1).val == 'b' 353 346 return dict() 354 347 348 class TestSessionFreshness(TGWebTest): 355 349 356 def test_session_freshness():357 """Check for session freshness.350 def test_session_freshness(self): 351 """Check for session freshness. 358 352 359 Changes made to the data in thread B should be reflected in thread A.353 Changes made to the data in thread B should be reflected in thread A. 360 354 361 """362 test_table.insert().execute(dict(id=1, val='a'))363 cherrypy.root = FreshRoot()364 create_request("/test1")365 assert cherrypy.response.status.startswith("200")366 assert 'AssertionError' not in cherrypy.response.body[0]367 # Call test2 in a different thread368 class ThreadB(threading.Thread):369 def run(self):370 create_request("/test2")371 assert cherrypy.response.status.startswith("200")372 assert 'AssertionError' not in cherrypy.response.body[0]373 thrdb = ThreadB()374 thrdb.start()375 thrdb.join()376 create_request("/test3")377 assert cherrypy.response.status.startswith("200")378 assert 'AssertionError' not in cherrypy.response.body[0]355 """ 356 test_table.insert().execute(dict(id=1, val='a')) 357 cherrypy.root = FreshRoot() 358 response = self.app.get("/test1") 359 assert 'AssertionError' not in response 360 # Call test2 in a different thread 361 class ThreadB(threading.Thread): 362 def __init__(self, app): 363 threading.Thread.__init__(self) 364 self.app = app 365 def run(self): 366 response = self.app.get("/test2") 367 assert 'AssertionError' not in response 368 thrdb = ThreadB(app=self.app) 369 thrdb.start() 370 thrdb.join() 371 response = self.app.get("/test3") 372 assert 'AssertionError' not in response -
turbogears/tests/test_expose.py
old new 1 1 import cherrypy 2 2 import simplejson 3 3 4 from turbogears import controllers, expose 5 from turbogears.testutil import create_request 4 from turbogears import controllers, expose, testutil 6 5 7 6 8 7 class ExposeRoot(controllers.RootController): … … 19 18 return dict(title="Foobar", mybool=False, someval="foo") 20 19 21 20 22 def test_gettinghtml(): 23 cherrypy.root = ExposeRoot() 24 create_request("/with_json") 25 body = cherrypy.response.body[0] 26 assert "Paging all foo" in body 21 class TestExposeRoot(testutil.TGWebTest): 27 22 28 def test_gettingjson(): 29 cherrypy.root = ExposeRoot() 30 create_request("/with_json?tg_format=json") 31 body = cherrypy.response.body[0] 32 assert '"title": "Foobar"' in body 23 def test_gettinghtml(self): 24 cherrypy.root = ExposeRoot() 25 response = self.app.get("/with_json") 26 assert "Paging all foo" in response 33 27 34 def test_gettingjsonviaaccept(): 35 cherrypy.root = ExposeRoot() 36 create_request("/with_json_via_accept", 37 headers=dict(Accept="text/javascript")) 38 body = cherrypy.response.body[0] 39 assert '"title": "Foobar"' in body 28 def test_gettingjson(self): 29 cherrypy.root = ExposeRoot() 30 response = self.app.get("/with_json?tg_format=json") 31 assert '"title": "Foobar"' in response 40 32 41 def test_getting_json_with_accept_but_using_tg_format():42 cherrypy.root = ExposeRoot()43 create_request("/with_json_via_accept?tg_format=json")44 body = cherrypy.response.body[0]45 assert '"title": "Foobar"' in body33 def test_gettingjsonviaaccept(self): 34 cherrypy.root = ExposeRoot() 35 response = self.app.get("/with_json_via_accept", 36 headers=dict(Accept="text/javascript")) 37 assert '"title": "Foobar"' in response 46 38 47 def test_getting_plaintext(): 48 cherrypy.root = ExposeRoot() 49 create_request("/with_json_via_accept", 50 headers=dict(Accept="text/plain")) 51 print cherrypy.response.body[0] 52 assert cherrypy.response.body[0] == "This is a plain text for foo." 39 def test_getting_json_with_accept_but_using_tg_format(self): 40 cherrypy.root = ExposeRoot() 41 response = self.app.get("/with_json_via_accept?tg_format=json") 42 assert '"title": "Foobar"' in response 53 43 54 def test_allow_json(): 44 def test_getting_plaintext(self): 45 cherrypy.root = ExposeRoot() 46 response = self.app.get("/with_json_via_accept", 47 headers=dict(Accept="text/plain")) 48 assert response.body == "This is a plain text for foo." 55 49 56 class NewRoot(controllers.RootController): 57 @expose(template="turbogears.tests.doesnotexist", allow_json=True) 58 def test(self): 59 return dict(title="Foobar", mybool=False, someval="niggles") 50 def test_allow_json(self): 60 51 61 cherrypy.root = NewRoot() 62 create_request("/test", headers= dict(accept="text/javascript")) 63 body = cherrypy.response.body[0] 64 values = simplejson.loads(body) 65 assert values == dict(title="Foobar", mybool=False, someval="niggles", 66 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) 71 assert values == dict(title="Foobar", mybool=False, someval="niggles", 72 tg_flash=None) 73 assert cherrypy.response.headers["Content-Type"] == "text/javascript" 52 class NewRoot(controllers.RootController): 53 @expose(template="turbogears.tests.doesnotexist", allow_json=True) 54 def test(self): 55 return dict(title="Foobar", mybool=False, someval="niggles") 56 57 cherrypy.root = NewRoot() 58 response = self.app.get("/test", headers= dict(accept="text/javascript")) 59 values = simplejson.loads(response.body) 60 assert values == dict(title="Foobar", mybool=False, someval="niggles", 61 tg_flash=None) 62 assert response.content_type == "text/javascript" 63 response = self.app.get("/test?tg_format=json") 64 values = simplejson.loads(response.body) 65 assert values == dict(title="Foobar", mybool=False, someval="niggles", 66 tg_flash=None) 67 assert response.content_type == "text/javascript" -
turbogears/tests/test_controllers.py
old new 1 1 import unittest 2 import simplejson 2 3 import formencode 3 4 import cherrypy 4 5 import pkg_resources … … 18 19 19 20 @expose() 20 21 def index(self): 21 pass22 return dict() 22 23 23 24 def validation_error_handler(self, tg_source, tg_errors, *args, **kw): 24 25 self.functionname = tg_source.__name__ … … 48 49 "turbogears.tests", "test_controllers.py")) 49 50 50 51 @expose() 51 def unicode(self): 52 cherrypy.response.headers["Content-Type"] = "text/html" 52 def unicode(self, response=None): 53 # TODO: fix me? make response a strict parameter? or can we use cp safely 54 if response is None: 55 response = cherrypy.response 56 response.headers["Content-Type"] = "text/html" 53 57 return u'\u00bfHabla espa\u00f1ol?' 54 58 55 59 @expose() … … 171 175 def flash_redirected(self): 172 176 return dict(title="Foobar", mybool=False, someval="niggles") 173 177 178 @expose() 179 def redirect(self): 180 redirect("/foo") 181 182 @expose() 183 def raise_redirect(self): 184 raise redirect("/foo") 185 174 186 @expose(html="turbogears.tests.simple", allow_json=True) 175 187 def flash_redirect_with_trouble_chars(self): 176 188 flash(u"$foo, k\xe4se;\tbar!") … … 220 232 return "redirected OK" 221 233 222 234 223 class TestRoot( unittest.TestCase):235 class TestRoot(testutil.TGWebTest): 224 236 225 237 def setUp(self): 238 testutil.TGWebTest.setUp(self) 226 239 cherrypy.root = None 227 240 cherrypy.tree.mount_points = {} 228 241 cherrypy.tree.mount(MyRoot(), "/") 229 242 cherrypy.tree.mount(SubApp(), "/subthing") 230 243 231 244 def tearDown(self): 245 testutil.TGWebTest.tearDown(self) 232 246 cherrypy.root = None 233 247 cherrypy.tree.mount_points = {} 234 248 235 249 def test_js_files(self): 236 250 """Can access the JavaScript files""" 237 testutil.create_request("/tg_js/MochiKit.js") 238 assert cherrypy.response.headers[ 239 "Content-Type"] == "application/x-javascript" 240 assert cherrypy.response.status == "200 OK" 251 response = self.app.get("/tg_js/MochiKit.js", status=200) 252 assert response.headers["Content-Type"] == "application/x-javascript" 241 253 242 254 def test_json_output(self): 243 testutil.create_request("/test?tg_format=json") 244 import simplejson 245 values = simplejson.loads(cherrypy.response.body[0]) 255 response = self.app.get("/test?tg_format=json") 256 values = simplejson.loads(response.body) 246 257 assert values == dict(title="Foobar", mybool=False, 247 258 someval="niggles", tg_flash=None) 248 assert cherrypy.response.headers["Content-Type"] == "text/javascript"259 assert response.headers["Content-Type"] == "text/javascript" 249 260 250 261 def test_implied_json(self): 251 testutil.create_request("/impliedjson?tg_format=json")252 assert '"title": "Blah"' in cherrypy.response.body[0]262 response = self.app.get("/impliedjson?tg_format=json") 263 assert '"title": "Blah"' in response 253 264 254 265 def test_allow_json(self): 255 testutil.create_request("/allowjson?tg_format=json") 256 assert cherrypy.response.status.startswith("500") 257 assert cherrypy.response.headers["Content-Type"] == "text/html" 266 response = self.app.get("/allowjson?tg_format=json", status=500) 267 assert response.headers["Content-Type"] == "text/html" 258 268 259 269 def test_allow_json_config(self): 260 270 """JSON output can be enabled via config.""" … … 265 275 return dict(title="Foobar", mybool=False, someval="foo", 266 276 tg_html="turbogears.tests.simple") 267 277 cherrypy.root = JSONRoot() 268 testutil.create_request('/allowjsonconfig?tg_format=json')269 assert cherrypy.response.headers["Content-Type"] == "text/javascript"278 response = self.app.get('/allowjsonconfig?tg_format=json') 279 assert response.headers["Content-Type"] == "text/javascript" 270 280 config.update({'tg.allow_json': False}) 271 281 272 282 def test_allow_json_config_false(self): … … 278 288 return dict(title="Foobar", mybool=False, someval="foo", 279 289 tg_html="turbogears.tests.simple") 280 290 cherrypy.root = JSONRoot() 281 testutil.create_request('/allowjson?tg_format=json') 282 assert cherrypy.response.status.startswith("404") 283 assert cherrypy.response.headers["Content-Type"] == "text/html" 291 response = self.app.get('/allowjson?tg_format=json', status=404) 292 assert response.headers["Content-Type"] == "text/html" 284 293 config.update({'tg.allow_json': False}) 285 294 286 295 def test_json_error(self): … … 293 302 assert '"someval": "errors"' in cherrypy.response.body[0] 294 303 295 304 def test_invalid_return(self): 296 testutil.create_request("/invalid") 297 assert cherrypy.response.status.startswith("500") 305 response = self.app.get("/invalid", status=500) 298 306 299 307 def test_strict_parameters(self): 300 308 config.update({"tg.strict_parameters": True}) 301 testutil.create_request(302 "/save?submit=save&firstname=Foo&lastname=Bar&badparam=1" )303 assert cherrypy.response.status.startswith("500")309 response = self.app.get( 310 "/save?submit=save&firstname=Foo&lastname=Bar&badparam=1", 311 status=500) 304 312 assert not hasattr(cherrypy.root, "errors") 305 313 306 314 def test_throw_out_random(self): 307 315 """Can append random value to the URL to avoid caching problems.""" 308 testutil.create_request("/test?tg_random=1")309 assert "Paging all niggles" in cherrypy.response.body[0]316 response = self.app.get("/test?tg_random=1") 317 assert "Paging all niggles" in response 310 318 config.update({"tg.strict_parameters": True}) 311 testutil.create_request("/test?tg_random=1") 312 assert cherrypy.response.status.startswith("200") 313 assert "Paging all niggles" in cherrypy.response.body[0] 314 testutil.create_request("/test?tg_not_random=1") 315 assert cherrypy.response.status.startswith("500") 319 response = self.app.get("/test?tg_random=1", status=200) 320 assert "Paging all niggles" in response 321 response = self.app.get("/test?tg_not_random=1", status=500) 316 322 assert not hasattr(cherrypy.root, "errors") 317 323 318 324 def test_ignore_parameters(self): 319 325 config.update({"tg.strict_parameters": True}) 320 testutil.create_request("/test?ignore_me=1") 321 assert cherrypy.response.status.startswith("500") 326 response = self.app.get("/test?ignore_me=1", status=500) 322 327 assert not hasattr(cherrypy.root, "errors") 323 328 config.update({"tg.ignore_parameters": ['ignore_me', 'me_too']}) 324 testutil.create_request("/test?ignore_me=1") 325 assert "Paging all niggles" in cherrypy.response.body[0] 326 testutil.create_request("/test?me_too=1") 327 assert cherrypy.response.status.startswith("200") 328 assert "Paging all niggles" in cherrypy.response.body[0] 329 testutil.create_request("/test?me_not=1") 330 assert cherrypy.response.status.startswith("500") 329 response = self.app.get("/test?ignore_me=1") 330 assert "Paging all niggles" in response 331 response = self.app.get("/test?me_too=1", status=200) 332 assert "Paging all niggles" in response 333 response = self.app.get("/test?me_not=1", status=500) 331 334 assert not hasattr(cherrypy.root, "errors") 332 335 333 336 def test_retrieve_dict_directly(self): 334 d = testutil.call(cherrypy.root.returnjson)335 assert d["title"] == "Foobar"337 response = self.app.get('/returnjson') 338 assert response.namespace["title"] == "Foobar" 336 339 337 340 def test_templateOutput(self): 338 testutil.create_request("/test")339 assert "Paging all niggles" in cherrypy.response.body[0]341 response = self.app.get("/test") 342 assert "Paging all niggles" in response 340 343 341 344 def test_safari_unicode_fix(self): 342 testutil.create_request("/unicode", headers={'User-Agent':345 response = self.app.get("/unicode", headers={'User-Agent': 343 346 "Apple WebKit Safari/412.2"}) 344 firstline = cherrypy.response.body[0].split('\n')[0]347 firstline = response.body.split('\n')[0] 345 348 assert firstline == "¿Habla español?" 346 349 assert isinstance(firstline, str) 347 350 348 351 def test_default_format(self): 349 352 """The default format can be set via expose""" 350 testutil.create_request("/returnjson") 351 firstline = cherrypy.response.body[0] 352 assert '"title": "Foobar"' in firstline 353 testutil.create_request("/returnjson?tg_format=html") 354 assert cherrypy.response.status.startswith("500") 355 firstline = cherrypy.response.body[0] 356 assert '"title": "Foobar"' not in firstline 353 response = self.app.get("/returnjson") 354 assert '"title": "Foobar"' in response 355 response = self.app.get("/returnjson?tg_format=html", status=500) 357 356 358 357 def test_content_type(self): 359 358 """The content-type can be set via expose""" 360 testutil.create_request("/contenttype")361 assert cherrypy.response.headers["Content-Type"] == "xml/atom"359 response = self.app.get("/contenttype") 360 assert response.headers["Content-Type"] == "xml/atom" 362 361 363 362 def test_returned_template_name(self): 364 testutil.create_request("/returnedtemplate")365 data = cherrypy.response.body[0].lower()363 response = self.app.get("/returnedtemplate") 364 data = response.body.lower() 366 365 assert "<body>" in data 367 366 assert 'groovy test template' in data 368 367 369 368 def test_returned_template_short(self): 370 testutil.create_request("/returnedtemplate_short")371 assert "Paging all foo" in cherrypy.response.body[0]369 response = self.app.get("/returnedtemplate_short") 370 assert "Paging all foo" in response 372 371 373 372 def test_expose_template_short(self): 374 testutil.create_request("/exposetemplate_short")375 assert "Paging all foo" in cherrypy.response.body[0]373 response = self.app.get("/exposetemplate_short") 374 assert "Paging all foo" in response 376 375 377 376 def test_validation(self): 378 377 """Data can be converted and validated""" 379 testutil.create_request("/istrue?value=true")378 response = self.app.get("/istrue?value=true") 380 379 assert cherrypy.root.value is True 381 testutil.create_request("/istrue?value=false")380 response = self.app.get("/istrue?value=false") 382 381 assert cherrypy.root.value is False 383 382 cherrypy.root = MyRoot() 384 testutil.create_request("/istrue?value=foo")383 response = self.app.get("/istrue?value=foo") 385 384 assert not hasattr(cherrypy.root, "value") 386 385 assert cherrypy.root.functionname == "istrue" 387 testutil.create_request("/save?submit=send&firstname=John&lastname=Doe")386 response = self.app.get("/save?submit=send&firstname=John&lastname=Doe") 388 387 assert cherrypy.root.fullname == "John Doe" 389 388 assert cherrypy.root.submit == "send" 390 testutil.create_request("/save?submit=send&firstname=Arthur")389 response = self.app.get("/save?submit=send&firstname=Arthur") 391 390 assert cherrypy.root.fullname == "Arthur Miller" 392 testutil.create_request("/save?submit=send&firstname=Arthur&lastname=")391 response = self.app.get("/save?submit=send&firstname=Arthur&lastname=") 393 392 assert cherrypy.root.fullname == "Arthur " 394 testutil.create_request("/save?submit=send&firstname=D&lastname=")393 response = self.app.get("/save?submit=send&firstname=D&lastname=") 395 394 assert len(cherrypy.root.errors) == 1 396 395 assert cherrypy.root.errors.has_key("firstname") 397 396 assert "characters" in cherrypy.root.errors["firstname"].msg.lower() 398 testutil.create_request("/save?submit=send&firstname=&lastname=")397 response = self.app.get("/save?submit=send&firstname=&lastname=") 399 398 assert len(cherrypy.root.errors) == 1 400 399 assert cherrypy.root.errors.has_key("firstname") 401 400 402 401 def test_validation_chained(self): 403 402 """Validation is not repeated if it already happened""" 404 403 cherrypy.root.value = None 405 testutil.create_request("/errorchain?value=true")404 self.app.get("/errorchain?value=true") 406 405 assert cherrypy.root.value is None 407 testutil.create_request("/errorchain?value=notbool")406 self.app.get("/errorchain?value=notbool") 408 407 assert cherrypy.root.value == 'notbool' 409 408 410 409 def test_validation_nested(self): 411 410 """Validation is not repeated in nested method call""" 412 411 cherrypy.root.value = None 413 testutil.create_request("/nestedcall?value=true")412 response = self.app.get("/nestedcall?value=true") 414 413 assert cherrypy.root.value == 'True' 415 testutil.create_request("/nestedcall?value=false")414 self.app.get("/nestedcall?value=false") 416 415 assert cherrypy.root.value == 'False' 417 416 418 417 def test_validation_with_schema(self): 419 418 """Data can be converted/validated with formencode.Schema instance""" 420 testutil.create_request("/save2?submit=send&firstname=Joe&lastname=Doe")419 response = self.app.get("/save2?submit=send&firstname=Joe&lastname=Doe") 421 420 assert cherrypy.root.fullname == "Joe Doe" 422 421 assert cherrypy.root.submit == "send" 423 testutil.create_request("/save2?submit=send&firstname=Arthur&lastname=")422 response = self.app.get("/save2?submit=send&firstname=Arthur&lastname=") 424 423 assert cherrypy.root.fullname == "Arthur " 425 testutil.create_request("/save2?submit=send&firstname=&lastname=")424 response = self.app.get("/save2?submit=send&firstname=&lastname=") 426 425 assert len(cherrypy.root.errors) == 1 427 426 assert cherrypy.root.errors.has_key("firstname") 428 testutil.create_request("/save2?submit=send&firstname=D&lastname=")427 response = self.app.get("/save2?submit=send&firstname=D&lastname=") 429 428 assert len(cherrypy.root.errors) == 1 430 429 assert cherrypy.root.errors.has_key("firstname") 431 430 432 431 def test_other_template(self): 433 432 """'tg_html' in a returned dict will use the template specified there""" 434 testutil.create_request("/useother")435 assert "This is the other template" in cherrypy.response.body[0]433 response = self.app.get("/useother") 434 assert "This is the other template" in response 436 435 437 436 def test_cheetah_template(self): 438 437 """Cheetah templates can be used as well""" 439 testutil.create_request("/usecheetah") 440 body = cherrypy.response.body[0] 441 assert "This is the Cheetah test template." in body 442 assert "Paging all chimps." in body 438 response = self.app.get("/usecheetah") 439 assert "This is the Cheetah test template." in response 440 assert "Paging all chimps." in response 443 441 444 442 def test_run_with_trans(self): 445 443 """run_with_transaction is called only on topmost exposed method""" 446 444 oldrwt = database.run_with_transaction 447 445 database.run_with_transaction = cherrypy.root.rwt 448 testutil.create_request("/nestedcall?value=true")446 self.app.get("/nestedcall?value=true") 449 447 database.run_with_transaction = oldrwt 450 448 assert cherrypy.root.value 451 449 assert cherrypy.root.rwt_called == 1 452 450 453 451 def test_positional(self): 454 452 """Positional parameters should work""" 455 testutil.create_request("/pos/foo")453 response = self.app.get("/pos/foo") 456 454 assert cherrypy.root.posvalue == "foo" 457 455 458 456 def test_flash_plain(self): 459 457 """flash with strings should work""" 460 testutil.create_request("/flash_plain?tg_format=json") 461 import simplejson 462 values = simplejson.loads(cherrypy.response.body[0]) 458 response = self.app.get("/flash_plain?tg_format=json") 459 values = simplejson.loads(response.body) 463 460 assert values["tg_flash"] == "plain" 464 assert not cherrypy.response.simple_cookie.has_key("tg_flash")461 assert not response.headers.has_key("tg_flash") 465 462 466 463 def test_flash_unicode(self): 467 464 """flash with unicode objects should work""" 468 testutil.create_request("/flash_unicode?tg_format=json") 469 import simplejson 470 values = simplejson.loads(cherrypy.response.body[0]) 465 response = self.app.get("/flash_unicode?tg_format=json") 466 values = simplejson.loads(response.body) 471 467 assert values["tg_flash"] == u"\xfcnicode" 472 assert not cherrypy.response.simple_cookie.has_key("tg_flash")468 assert not response.headers.has_key("tg_flash") 473 469 474 470 def test_flash_on_redirect(self): 475 471 """flash must survive a redirect""" 476 testutil.create_request("/flash_redirect?tg_format=json") 477 assert cherrypy.response.status.startswith("302") 478 testutil.create_request(cherrypy.response.headers["Location"], 479 headers=dict(Cookie=cherrypy.response.simple_cookie.output( 480 header="").strip())) 481 import simplejson 482 values = simplejson.loads(cherrypy.response.body[0]) 472 response = self.app.get("/flash_redirect?tg_format=json", status=302) 473 response = self.app.get(response.location, 474 headers=dict(Cookie=response.headers['Set-Cookie'])) 475 values = simplejson.loads(response.body) 483 476 assert values["tg_flash"] == u"redirect \xfcnicode" 484 477 485 478 def test_flash_redirect_with_trouble_chars(self): 486 479 """flash redirect with chars that can cause troubles in cookies""" 487 testutil.create_request("/flash_redirect_with_trouble_chars?tg_format=json") 488 assert cherrypy.response.status.startswith("302") 489 value = cherrypy.response.simple_cookie["tg_flash"].value 490 assert '$' not in value 491 assert ',' not in value and ';' not in value 492 assert ' ' not in value and '\t' not in value 493 assert 'foo' in value and 'bar' in value 494 assert u'k\xe4se'.encode('utf-8') in value 495 assert '!' in value 496 testutil.create_request(cherrypy.response.headers["Location"], 497 headers=dict(Cookie=cherrypy.response.simple_cookie.output( 498 header="").strip())) 499 import simplejson 500 values = simplejson.loads(cherrypy.response.body[0]) 480 response = self.app.get("/flash_redirect_with_trouble_chars?tg_format=json", status=302) 481 response = self.app.get(response.location, 482 headers=dict(Cookie=response.headers['Set-Cookie'])) 483 values = simplejson.loads(response.body) 501 484 assert values["tg_flash"] == u"$foo, k\xe4se;\tbar!" 502 485 503 486 def test_double_flash(self): … … 505 488 # Here we are calling method that sets a flash message. However flash 506 489 # cookie is still there. Turbogears should discard old flash message 507 490 # from cookie and use new one, set by flash_plain(). 508 testutil.create_request("/flash_plain?tg_format=json",491 response = self.app.get("/flash_plain?tg_format=json", 509 492 headers=dict(Cookie='tg_flash="old flash"; Path=/;')) 510 import simplejson 511 values = simplejson.loads(cherrypy.response.body[0]) 493 values = simplejson.loads(response.body) 512 494 assert values["tg_flash"] == "plain" 513 assert cherrypy.response.simple_cookie.has_key("tg_flash"), \495 assert response.cookies_set.has_key("tg_flash"), \ 514 496 "Cookie clearing request should be present" 515 flashcookie = cherrypy.response.simple_cookie['tg_flash']516 assert flashcookie['expires'] == 0517 497 518 498 def test_set_kid_outputformat_in_config(self): 519 499 """the outputformat for kid can be set in the config""" 520 500 config.update({'kid.outputformat': 'xhtml'}) 521 testutil.create_request('/test') 522 response = cherrypy.response.body[0] 501 response = self.app.get('/test') 523 502 assert '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML ' in response 524 503 config.update({'kid.outputformat': 'html'}) 525 testutil.create_request('/test') 526 response = cherrypy.response.body[0] 504 response = self.app.get('/test') 527 505 assert '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML ' in response 528 506 assert ' This is the groovy test ' in response 529 507 config.update({'kid.outputformat': 'html compact'}) 530 testutil.create_request('/test') 531 response = cherrypy.response.body[0] 508 response = self.app.get('/test') 532 509 assert '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML ' in response 533 510 assert 'This is the groovy test ' in response 534 511 assert ' ' not in response … … 536 513 def test_fileserving(self): 537 514 #outputcap = StringIO() 538 515 #sys.stdout = outputcap 539 testutil.create_request("/servefile")516 response = self.app.get("/servefile") 540 517 assert cherrypy.root.servedit 541 518 assert not cherrypy.root.serve_exceptions 542 519 #assert "AssertionError" not in outputcap.getvalue() 543 520 544 521 def test_internal_redirect(self): 545 522 """regression test for #1022, #1407 and #1598""" 546 testutil.create_request("/internal_redirect") 547 firstline = cherrypy.response.body[0] 548 assert "redirected OK" in firstline 523 response = self.app.get("/internal_redirect") 524 assert "redirected OK" in response 549 525 550 526 def test_internal_redirect_nested_variables(self): 551 527 """regression test for #1022, #1407 and #1598""" 552 testutil.create_request(528 response = self.app.get( 553 529 "/internal_redirect?a=1&a-1.b=2&a-2.c=3&a-2.c-1=4") 554 firstline = cherrypy.response.body[0] 555 assert "redirected OK" in firstline 530 assert "redirected OK" in response 556 531 557 532 def test_exc_value(self): 558 533 """Exception is handled gracefully by the right exception handler.""" 559 testutil.create_request("/raise_value_exc")560 assert 'handling_value' in cherrypy.response.body[0]534 response = self.app.get("/raise_value_exc") 535 assert 'handling_value' in response 561 536 562 537 def test_exc_index(self): 563 538 """Exception is handled gracefully by the right exception handler.""" 564 testutil.create_request("/raise_index_exc")565 assert 'handling_index' in cherrypy.response.body[0]539 response = self.app.get("/raise_index_exc") 540 assert 'handling_index' in response 566 541 567 542 def test_exc_all(self): 568 543 """Test a controller that is protected by multiple exception handlers. … … 571 546 by their respective handlers without problem... 572 547 573 548 """ 574 testutil.create_request("/raise_all_exc?num=1")575 assert 'handling_value' in cherrypy.response.body[0]576 testutil.create_request("/raise_all_exc?num=2")577 assert 'handling_index' in cherrypy.response.body[0]578 testutil.create_request("/raise_all_exc?num=3")579 assert 'handling_key' in cherrypy.response.body[0]549 response = self.app.get("/raise_all_exc?num=1") 550 assert 'handling_value' in response 551 response = self.app.get("/raise_all_exc?num=2") 552 assert 'handling_index' in response 553 response = self.app.get("/raise_all_exc?num=3") 554 assert 'handling_key' in response 580 555 581 556 582 class TestURLs( unittest.TestCase):557 class TestURLs(testutil.TGWebTest): 583 558 584 559 def setUp(self): 560 testutil.TGWebTest.setUp(self) 585 561 cherrypy.tree.mount_points = {} 586 562 cherrypy.root = MyRoot() 587 563 cherrypy.root.subthing = SubApp() 588 564 cherrypy.root.subthing.subsubthing = SubApp() 589 565 590 566 def test_basic_urls(self): 591 testutil.create_request("/")567 self.app.get("/") 592 568 assert "/foo" == url("/foo") 593 569 assert "foo/bar" == url(["foo", "bar"]) 594 570 assert url("/foo", bar=1, baz=2) in \ … … 602 578 assert url("/foo") == "/foo" 603 579 604 580 def test_approots(self): 605 testutil.create_request("/subthing/") 581 config.update({"server.webpath": "/subthing"}) 582 self.app.get("/subthing/") 606 583 assert url("foo") == "foo" 607 584 assert url("/foo") == "/subthing/foo" 608 585 609 586 def test_lower_approots(self): 610 testutil.create_request("/subthing/subsubthing/") 587 config.update({"server.webpath": "/subthing/subsubthing"}) 588 self.app.get("/subthing/subsubthing/") 611 589 assert url("/foo") == "/subthing/subsubthing/foo" 612 590 613 def test_approots_With_path(self): 614 config.update({"server.webpath": "/coolsite/root"}) 615 startup.startTurboGears() 616 testutil.create_request("/coolsite/root/subthing/") 591 def test_approots_with_path(self): 592 config.update({"server.webpath": "/coolsite/root/subthing"}) 593 self.app.get("/subthing/") 617 594 assert url("/foo") == "/coolsite/root/subthing/foo" 618 595 619 596 def test_redirect(self): 620 597 config.update({"server.webpath": "/coolsite/root"}) 621 startup.startTurboGears() 622 testutil.create_request("/coolsite/root/subthing/") 623 try: 624 redirect("/foo") 625 assert False, "redirect exception should have been raised" 626 except cherrypy.HTTPRedirect, e: 627 assert "http://localhost/coolsite/root/subthing/foo" in e.urls 628 try: 629 raise redirect("/foo") 630 assert False, "redirect exception should have been raised" 631 except cherrypy.HTTPRedirect, e: 632 assert "http://localhost/coolsite/root/subthing/foo" in e.urls 598 response = self.app.get("/redirect") 599 assert response.location == 'http://localhost:80/coolsite/root/foo' 600 self.app.get("/raise_redirect") 601 assert response.location == 'http://localhost:80/coolsite/root/foo' 633 602 634 603 def test_multi_values(self): 635 testutil.create_request("/")604 self.app.get("/") 636 605 assert url("/foo", bar=[1, 2]) in \ 637 606 ["/foo?bar=1&bar=2", "/foo?bar=2&bar=1"] 638 607 assert url("/foo", bar=("asdf", "qwer")) in \ … … 640 609 641 610 def test_unicode(self): 642 611 """url() can handle unicode parameters""" 643 testutil.create_request("/")612 self.app.get("/") 644 613 assert url('/', x=u'\N{LATIN SMALL LETTER A WITH GRAVE}' 645 614 u'\N{LATIN SMALL LETTER E WITH GRAVE}' 646 615 u'\N{LATIN SMALL LETTER I WITH GRAVE}' … … 650 619 651 620 def test_list(self): 652 621 """url() can handle list parameters, with unicode too""" 653 testutil.create_request("/")622 self.app.get("/") 654 623 assert url('/', foo=['bar', u'\N{LATIN SMALL LETTER A WITH GRAVE}'] 655 624 ) == '/?foo=bar&foo=%C3%A0' 656 625 657 626 def tearDown(self): 627 testutil.TGWebTest.tearDown(self) 658 628 config.update({"server.webpath": ""}) 659 startup.startTurboGears()660 629 661 630 662 def test_index_trailing_slash(): 663 """If there is no trailing slash on an index method call, redirect""" 664 cherrypy.root = SubApp() 665 cherrypy.root.foo = SubApp() 666 testutil.create_request("/foo") 667 assert cherrypy.response.status.startswith("302") 631 def test_index_trailing_slash(self): 632 """If there is no trailing slash on an index method call, redirect""" 633 cherrypy.root = SubApp() 634 cherrypy.root.foo = SubApp() 635 self.app.get("/foo", status=302) 668 636 669 def test_can_use_internally_defined_arguments():670 """Can use argument names that are internally used by TG in controllers"""637 def test_can_use_internally_defined_arguments(self): 638 """Can use argument names that are internally used by TG in controllers""" 671 639 672 class App(controllers.RootController):640 class App(controllers.RootController): 673 641 674 @expose()675 def index(self, **kw):676 return "\n".join(["%s:%s" % i for i in kw.iteritems()])642 @expose() 643 def index(self, **kw): 644 return "\n".join(["%s:%s" % i for i in kw.iteritems()]) 677 645 678 cherrypy.root = App() 679 testutil.create_request("/?format=foo&template=bar&fragment=boo") 680 output = cherrypy.response.body[0] 681 assert "format:foo" in output 682 assert "template:bar" in output 683 assert "fragment:boo" in output 646 cherrypy.root = App() 647 response = self.app.get("/?format=foo&template=bar&fragment=boo") 648 assert "format:foo" in response 649 assert "template:bar" in response 650 assert "fragment:boo" in response 684 651 685 def test_url_kwargs_overwrite_tgparams():686 """Check keys in tgparams in call to url overwrite kw args"""687 params = {'spamm': 'eggs'}688 assert 'spamm=ham' in url('/foo', params, spamm='ham')652 def test_url_kwargs_overwrite_tgparams(self): 653 """Check keys in tgparams in call to url overwrite kw args""" 654 params = {'spamm': 'eggs'} 655 assert 'spamm=ham' in url('/foo', params, spamm='ham') 689 656 690 def test_url_doesnt_change_tgparams():691 """Test that url() does not change the dict passed as second arg"""692 params = {'spamm': 'eggs'}693 assert 'foo' in url('/foo', params, spamm='ham')694 assert params['spamm'] == 'eggs'657 def test_url_doesnt_change_tgparams(self): 658 """Test that url() does not change the dict passed as second arg""" 659 params = {'spamm': 'eggs'} 660 assert 'foo' in url('/foo', params, spamm='ham') 661 assert params['spamm'] == 'eggs' -
turbogears/tests/test_catwalk.py
old new 40 40 pass 41 41 index = turbogears.expose()(index) 42 42 43 class Browse( unittest.TestCase):43 class Browse(testutil.TGWebTest): 44 44 def setUp(self): 45 testutil.TGWebTest.setUp(self) 45 46 browse_data(browse) 46 47 cherrypy.root = MyRoot() 47 48 48 49 def test_wrong_filter_format(self): 49 50 cherrypy.root.catwalk = CatWalk(browse) 50 testutil.create_request("/catwalk/browse/?object_name=Song&filters=Guantanemera&tg_format=json") 51 response = cherrypy.response.body[0] 51 response = self.app.get("/catwalk/browse/?object_name=Song&filters=Guantanemera&tg_format=json") 52 52 assert 'filter_format_error' in response 53 53 54 54 def test_wrong_filter_column(self): 55 55 cherrypy.root.catwalk = CatWalk(browse) 56 testutil.create_request("/catwalk/browse/?object_name=Song&filters=guacamole:2&tg_format=json") 57 response = cherrypy.response.body[0] 56 response = self.app.get("/catwalk/browse/?object_name=Song&filters=guacamole:2&tg_format=json") 58 57 assert 'filter_column_error' in response 59 58 60 59 def test_filters(self): 61 60 cherrypy.root.catwalk = CatWalk(browse) 62 testutil.create_request("/catwalk/browse/?object_name=Song&tg_format=json") 63 response = cherrypy.response.body[0] 64 values = simplejson.loads(response) 61 response = self.app.get("/catwalk/browse/?object_name=Song&tg_format=json") 62 values = simplejson.loads(response.body) 65 63 assert values['total'] == 15 * 15 * 15 #without the filters we get all songs (3375) 66 testutil.create_request("/catwalk/browse/?object_name=Song&filters=album:1&tg_format=json") 67 response = cherrypy.response.body[0] 68 values = simplejson.loads(response) 64 response = self.app.get("/catwalk/browse/?object_name=Song&filters=album:1&tg_format=json") 65 values = simplejson.loads(response.body) 69 66 assert values['total'] == 15 #filter by album id (only 15 songs) 70 67 71 68 def test_response_fields(self): 72 69 #Check that the response contains the expected keys 73 70 cherrypy.root.catwalk = CatWalk(browse) 74 testutil.create_request("/catwalk/browse/?object_name=Artist&start=3&page_size=20&tg_format=json") 75 response = cherrypy.response.body[0] 76 values = simplejson.loads(response) 71 response = self.app.get("/catwalk/browse/?object_name=Artist&start=3&page_size=20&tg_format=json") 72 values = simplejson.loads(response.body) 77 73 assert values.has_key('headers') 78 74 assert values.has_key('rows') 79 75 assert values.has_key('start') … … 87 83 #Control that the count for related and multiple joins match 88 84 #the number of related instances when accessed as a field 89 85 cherrypy.root.catwalk = CatWalk(browse) 90 testutil.create_request("/catwalk/browse/?object_name=Artist&tg_format=json") 91 response = cherrypy.response.body[0] 92 values = simplejson.loads(response) 86 response = self.app.get("/catwalk/browse/?object_name=Artist&tg_format=json") 87 values = simplejson.loads(response.body) 93 88 artist = browse.Artist.get(1) 94 89 assert int(values['rows'][0]['genres']) == len(list(artist.genres)) 95 90 assert int(values['rows'][0]['albums']) == len(list(artist.albums)) … … 97 92 def test_rows_column_number(self): 98 93 #Control that the number of columns match the number of fields in the model 99 94 cherrypy.root.catwalk = CatWalk(browse) 100 testutil.create_request("/catwalk/browse/?object_name=Artist&tg_format=json") 101 response = cherrypy.response.body[0] 102 values = simplejson.loads(response) 95 response = self.app.get("/catwalk/browse/?object_name=Artist&tg_format=json") 96 values = simplejson.loads(response.body) 103 97 assert len(values['rows'][0]) == 4 104 98 105 99 def test_rows_limit(self): 106 100 #Update the limit of rows for the query and control the number of rows returned 107 101 cherrypy.root.catwalk = CatWalk(browse) 108 testutil.create_request("/catwalk/browse/?object_name=Artist&tg_format=json") 109 response = cherrypy.response.body[0] 110 values = simplejson.loads(response) 102 response = self.app.get("/catwalk/browse/?object_name=Artist&tg_format=json") 103 values = simplejson.loads(response.body) 111 104 assert values.has_key('rows') 112 105 assert len(values['rows']) == 10 113 testutil.create_request("/catwalk/browse/?object_name=Artist&page_size=15&tg_format=json") 114 response = cherrypy.response.body[0] 115 values = simplejson.loads(response) 106 response = self.app.get("/catwalk/browse/?object_name=Artist&page_size=15&tg_format=json") 107 values = simplejson.loads(response.body) 116 108 assert values.has_key('rows') 117 109 assert len(values['rows']) == 15 118 110 119 111 def test_header_labels(self): 120 112 #Check that the returned header labels match the the model 121 113 cherrypy.root.catwalk = CatWalk(browse) 122 testutil.create_request("/catwalk/browse/?object_name=Artist&tg_format=json") 123 response = cherrypy.response.body[0] 124 values = simplejson.loads(response) 114 response = self.app.get("/catwalk/browse/?object_name=Artist&tg_format=json") 115 values = simplejson.loads(response.body) 125 116 assert len(values['headers']) == 5 126 117 for header in values['headers']: 127 118 assert header['name'] in ['id','name','albums','genres', 'plays_instruments'] 128 119 129 120 130 class TestJoinedOperations( testutil.DBTest):121 class TestJoinedOperations(testutil.DBWebTest): 131 122 model = browse 132 123 133 124 def setUp(self): 134 125 cherrypy.root = MyRoot() 135 126 cherrypy.root.catwalk = CatWalk(browse) 136 testutil.DB Test.setUp(self)127 testutil.DBWebTest.setUp(self) 137 128 browse_data(browse) 138 129 139 130 def test_addremove_related_joins(self): 140 131 # check the update_join function when nondefault add/remove are used 141 132 artist = self.model.Artist.get(1) 142 133 assert len(artist.plays_instruments) == 0 143 testutil.create_request("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1%2C2&tg_format=json")134 response = self.app.get("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1%2C2&tg_format=json") 144 135 assert len(artist.plays_instruments) == 2 145 testutil.create_request("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1&tg_format=json")136 response = self.app.get("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1&tg_format=json") 146 137 assert len(artist.plays_instruments) == 1, str(artist.plays_instruments) -
turbogears/tests/test_paginate.py
old new 4 4 from urllib import quote 5 5 import warnings 6 6 7 from turbogears import config, expose, database 7 from turbogears import config, expose, database, testutil 8 8 from turbogears.controllers import RootController, url 9 9 from turbogears.database import get_engine, metadata, session, mapper 10 10 from turbogears.paginate import paginate, sort_ordering, sort_data 11 from turbogears.testutil import create_request,sqlalchemy_cleanup11 from turbogears.testutil import sqlalchemy_cleanup 12 12 from turbojson.jsonify import jsonify 13 13 14 14 import cherrypy … … 183 183 return result 184 184 185 185 186 class TestSpy( unittest.TestCase):186 class TestSpy(testutil.TGWebTest): 187 187 """Never trust a spy""" 188 188 189 189 class MyRoot(RootController): … … 218 218 219 219 220 220 def setUp(self): 221 testutil.TGWebTest.setUp(self) 221 222 cherrypy.root = self.MyRoot() 222 223 223 224 def test_spy(self): 224 create_request('/spy') 225 body = cherrypy.response.body[0] 226 Spy.assert_ok(body, 'current_page', 1) 225 response = self.app.get('/spy') 226 Spy.assert_ok(response.body, 'current_page', 1) 227 227 try: 228 Spy.assert_ok( body, 'current_page', 2)228 Spy.assert_ok(response.body, 'current_page', 2) 229 229 raise Exception("above test should have failed") 230 230 except AssertionError: 231 231 pass 232 232 233 233 def test_correct_expectation(self): 234 create_request('/spy_correct_expectation') 235 body = cherrypy.response.body[0] 236 assert "ok: [paginate" in body 234 response = self.app.get('/spy_correct_expectation') 235 assert "ok: [paginate" in response 237 236 238 237 def test_wrong_expectation(self): 239 create_request('/spy_wrong_expectation') 240 body = cherrypy.response.body[0] 241 assert "fail: expected page_count=9, got page_count=10" in body 238 response = self.app.get('/spy_wrong_expectation') 239 assert "fail: expected page_count=9, got page_count=10" in response 242 240 243 241 def test_invalid_expectation(self): 244 create_request('/spy_invalid_expectation') 245 body = cherrypy.response.body[0] 246 assert "fail: paginate does not have 'foobar' attribute" in body 242 response = self.app.get('/spy_invalid_expectation') 243 assert "fail: paginate does not have 'foobar' attribute" in response 247 244 248 245 def test_raw_expectation(self): 249 create_request('/spy_correct_expectation')250 Spy.assert_ok( cherrypy.response.body[0], 'var_name', 'data')251 Spy.assert_ok( cherrypy.response.body[0], 'var_name', "'data'", raw=True)246 response = self.app.get('/spy_correct_expectation') 247 Spy.assert_ok(response.body, 'var_name', 'data') 248 Spy.assert_ok(response.body, 'var_name', "'data'", raw=True) 252 249 253 250 254 class TestPagination( unittest.TestCase):251 class TestPagination(testutil.TGWebTest): 255 252 """Base class for all Paginate TestCases""" 256 253 257 def request(self, url ):258 create_request(url)259 self.body = cherrypy.response.body[0]254 def request(self, url, status=200): 255 response = self.app.get(url, status=status) 256 self.body = response.body 260 257 if "fail: " in self.body: 261 258 print self.body 262 259 assert False, "Spy alert! Check body output for details..." … … 343 340 344 341 345 342 def setUp(self): 343 testutil.TGWebTest.setUp(self) 346 344 cherrypy.root = self.MyRoot() 347 345 348 346 def test_pagination_old_style(self): … … 439 437 Spy.assert_ok(self.body, 'pages', xrange(4, 8)) 440 438 441 439 def test_invalid_dynamic_limit(self): 442 self.request("/invalid_dynamic") 443 assert cherrypy.response.status.startswith("500") 440 self.request("/invalid_dynamic", status=500) 444 441 assert 'paginate: dynamic_limit (foobar) not found in output dict' in self.body 445 442 446 443 def test_dynamic_limit(self): … … 754 751 755 752 756 753 def setUp(self): 754 testutil.TGWebTest.setUp(self) 757 755 cherrypy.root = self.MyRoot() 758 756 759 757 def assert_order(self, *args): … … 826 824 827 825 def test_invalid_default_reversed(self): 828 826 for method in "Q", "QA", "SR", "SO", "SL": 829 self.request("/wrong_reversed/?method=%s" % method) 830 assert cherrypy.response.status.startswith("500") 827 self.request("/wrong_reversed/?method=%s" % method, status=500) 831 828 assert ('paginate: default_reversed (deprecated) only allowed' 832 829 ' when default_order is a basestring') in self.body 833 830 -
turbogears/testutil.py
old new 18 18 except ImportError: 19 19 sqlalchemy = None 20 20 21 from webtest import TestApp 22 21 23 from turbogears import startup, config, update_config, \ 22 24 controllers, database, validators 23 25 from turbogears.identity import current_provider … … 201 203 item.dropTable(ifExists=True) 202 204 203 205 206 class TGWebTest(unittest.TestCase): 207 """A WebTest enabled unit testing class. 208 209 This allows testers to subclass us and use self.app to make WebTest calls. 210 """ 211 def setUp(self): 212 from cherrypy._cpwsgi import wsgiApp 213 start_cp() 214 startup.startTurboGears() 215 self.app = TestApp(wsgiApp) 216 217 def tearDown(self): 218 startup.stopTurboGears() 219 del self.app 220 221 def login_user(self, user): 222 """ Log a specified user object into the system """ 223 self.app.post(config.get('identity.failure_url'), { 224 'user_name' : user.user_name, 225 'password' : user.password, 226 'login' : 'Login', 227 }) 228 229 230 class DBWebTest(TGWebTest, DBTest): 231 """A database driven WebTest enabled unit testing class. 232 233 This class will automatically setup and tear down your database, along 234 with TurboGears and WebTest before and after each unit test. 235 """ 236 def setUp(self): 237 DBTest.setUp(self) 238 TGWebTest.setUp(self) 239 240 def tearDown(self): 241 TGWebTest.tearDown(self) 242 DBTest.tearDown(self) 243 244 204 245 def reset_cp(): 205 246 cherrypy.root = None 206 247 … … 307 348 308 349 __all__ = ["call", "create_request", "DBTest", 309 350 "attach_identity", "set_identity_user", 310 "capture_log", "print_log", "get_log", "sqlalchemy_cleanup"] 351 "capture_log", "print_log", "get_log", "sqlalchemy_cleanup", 352 "TGWebTest", "DBWebTest"] -
turbogears/view/base.py
old new 107 107 @type template: string 108 108 109 109 """ 110 if hasattr(cherrypy.request, 'wsgi_environ'): 111 if 'paste.testing' in cherrypy.request.wsgi_environ: 112 cherrypy.request.wsgi_environ['paste.testing_variables']['namespace'] = info 110 113 template = info.pop("tg_template", template) 111 114 if not info.has_key("tg_flash"): 112 115 if config.get("tg.empty_flash", True):