Ticket #1762: webtest-ken.patch
| File webtest-ken.patch, 134.9 kB (added by kskuhlman, 4 months ago) |
|---|
-
setup.py
old new 46 46 47 47 testtools = [ 48 48 "nose >= 0.9.3, <= 0.10.0a1", 49 "WebTest", 49 50 ] 50 51 51 52 tgtesttools = [ 52 53 "nose >= 0.9.3, <= 0.10.0a1", 54 "WebTest", 53 55 ] 54 56 55 57 # python 2.5 compatible list -
turbogears/identity/tests/test_identity.py
old new 55 55 56 56 @expose() 57 57 def index(self): 58 pass58 return 'identityroot index' 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 user = TG_User.by_user_name("samIam") 73 group_ids = set((TG_Group.by_group_name("peon").id, 74 TG_Group.by_group_name("other").id)) 75 assert identity.current.user == user 76 assert identity.current.user_name == user.user_name 77 assert identity.current.user_id == user.id 78 assert identity.current.groups == set(('peon', 'other')) 79 assert identity.current.group_ids == group_ids 80 assert "samIam" == cherrypy.serving.request.identity.user_name 81 72 82 return 'in_peon_group' 73 83 74 84 @expose() 85 @identity.require(in_group('peon')) 86 def identity_current_set(self): 87 user = TG_User.by_user_name("samIam") 88 group_ids = set((TG_Group.by_group_name("peon").id, 89 TG_Group.by_group_name("other").id)) 90 assert identity.current.user == user 91 assert identity.current.user_name == user.user_name 92 assert identity.current.user_id == user.id 93 assert identity.current.groups == set(('peon', 'other')) 94 assert identity.current.group_ids == group_ids 95 assert "samIam" == cherrypy.serving.request.identity.user_name 96 97 return 'identity_current_set' 98 99 100 @expose() 75 101 def test_exposed_require(self): 76 102 if not hasattr(self.in_peon_group, '_require'): 77 103 return 'no _require attr' … … 136 162 return 'wrong params: %s\nexpected unicode objects' \ 137 163 ' for all strings' % cherrypy.request.params 138 164 165 @expose() 166 def is_anonymous(self): 167 assert cherrypy.serving.request.identity.user_name == None 168 assert cherrypy.serving.request.identity.anonymous 169 return 'is_anonymous' 139 170 140 171 class TestIdentity(unittest.TestCase): 141 172 … … 151 182 self._original_config = original_config 152 183 config.configure_loggers(test_config) 153 184 config.update(test_config['global']) 154 cherrypy.root = IdentityRoot() 155 startup.startTurboGears() 185 testutil.start_server(root = IdentityRoot()) 156 186 self.init_model() 157 187 158 188 def tearDown(self): 159 startup.stopTurboGears()189 testutil.stop_server() 160 190 config.update(self._original_config) 161 191 162 192 def init_model(self): … … 181 211 182 212 def test_user_password_parameters(self): 183 213 """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 214 response = testutil.go('/new_user_setup?user_name=test&password=pw') 215 assert 'test pw' in response, response 187 216 188 217 def test_user_exists(self): 189 218 u = TG_User.by_user_name('samIam') … … 203 232 """Test if we can set a user password which is encoded as unicode 204 233 (no encryption algorithm).""" 205 234 config.update({'identity.soprovider.encryption_algorithm': None}) 206 # force new config values to load207 startup.startTurboGears()208 testutil.create_request('/')209 235 hub.begin() 210 236 u = TG_User.by_user_name('samIam') 211 237 u.password = u'garçon' … … 217 243 def test_user_password_hashed_sha(self): 218 244 """Test if a sha hashed password is stored in the database.""" 219 245 config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 220 # force new config values to load221 startup.startTurboGears()222 testutil.create_request('/')223 246 hub.begin() 224 247 u = TG_User.by_user_name('samIam') 225 248 u.password = 'password' … … 232 255 """Test if a sha hashed password with unicode characters is stored 233 256 in the database.""" 234 257 config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 235 # force new config values to load236 startup.startTurboGears()237 testutil.create_request('/')238 258 hub.begin() 239 259 u = TG_User.by_user_name('samIam') 240 260 u.password = u'garçon' … … 246 266 def test_user_password_hashed_md5(self): 247 267 """Test if a md5 hashed password is stored in the database.""" 248 268 config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 249 # force new config values to load250 startup.startTurboGears()251 testutil.create_request('/')252 269 hub.begin() 253 270 u = TG_User.by_user_name('samIam') 254 271 u.password = 'password' … … 261 278 """Test if a md5 hashed password with unicode characters is stored 262 279 in the database.""" 263 280 config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 264 # force new config values to load265 startup.startTurboGears()266 testutil.create_request('/')267 281 hub.begin() 268 282 u = TG_User.by_user_name('samIam') 269 283 u.password = u'garçon' … … 278 292 test ensures that the encryption algorithm does handle non-unicode 279 293 parameters gracefully.""" 280 294 config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 281 # force new config values to load282 startup.startTurboGears()283 testutil.create_request('/')284 295 hub.begin() 285 296 u = TG_User.by_user_name('samIam') 286 297 u.password = u'garçon'.encode('UTF-8') … … 293 304 """Test that we can store raw values in the password field 294 305 (without being hashed).""" 295 306 config.update({'identity.soprovider.encryption_algorithm':'sha1'}) 296 # force new config values to load297 startup.startTurboGears()298 testutil.create_request('/')299 307 hub.begin() 300 308 u = TG_User.by_user_name('samIam') 301 309 u.set_password_raw('password') … … 306 314 307 315 def test_user_password_raw_unicode(self): 308 316 config.update({'identity.soprovider.encryption_algorithm':'sha1'}) 309 # force new config values to load310 startup.startTurboGears()311 testutil.create_request('/')312 317 hub.begin() 313 318 u = TG_User.by_user_name('samIam') 314 319 u.set_password_raw(u'garçon') … … 322 327 config.update({'identity.soprovider.encryption_algorithm': 'custom', 323 328 'identity.custom_encryption': 324 329 'identity.tests.test_identity.mycustomencrypt'}) 325 # force new config values to load326 startup.startTurboGears()327 testutil.create_request('/')328 330 hub.begin() 329 331 u = TG_User.by_user_name('samIam') 330 332 u.password = 'password' … … 335 337 336 338 def test_anonymous_browsing(self): 337 339 """Test if we can show up anonymously.""" 338 testutil.create_request('/')339 assert identity.current.anonymous340 response = testutil.go('/is_anonymous') 341 assert 'is_anonymous' in response 340 342 341 343 def test_deny_anonymous(self): 342 344 """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 345 response = testutil.go('/logged_in_only') 346 assert 'identity_failed_answer' in response.body 346 347 347 348 def test_deny_anonymous_viewable(self): 348 349 """Test that a logged in user can see an resource blocked 349 350 from anonymous users.""" 350 testutil.create_request('/logged_in_only?'351 response = testutil.go('/logged_in_only?' 351 352 'user_name=samIam&password=secret&login=Login') 352 firstline = cherrypy.response.body[0] 353 assert 'logged_in_only' in firstline, firstline 353 assert 'logged_in_only' in response.body 354 354 355 355 def test_logout(self): 356 """Test that logout works and session is getsinvalid afterwards."""357 testutil.create_request('/in_peon_group?'356 """Test that logout works and session is invalid afterwards.""" 357 response = testutil.go('/identity_current_set?' 358 358 '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 359 session_id = response.headers['Set-Cookie'] 360 response = testutil.go('/logout', headers={'Cookie': session_id}) 361 response = testutil.go('/is_anonymous', headers={'Cookie' : session_id}) 362 assert response.body == 'is_anonymous' 365 363 366 def test_logout_with_set_identity(self):367 """Test that logout works even when there is no visit_key368 (e.g. when testutils.set_identity_user is used)."""369 request = testutil.DummyRequest()370 old_user = testutil.test_user371 user = TG_User.by_user_name("samIam")372 testutil.set_identity_user(user)373 testutil.attach_identity(request)374 testutil.set_identity_user(old_user)375 testutil.call_with_request(cherrypy.root.logout, request)376 assert request.identity.anonymous377 378 364 def test_require_group(self): 379 365 """Test that a anonymous user""" 380 testutil.create_request('/in_peon_group') 381 firstline = cherrypy.response.body[0] 382 assert 'identity_failed_answer' in firstline, firstline 366 response = testutil.go('/in_peon_group') 367 assert 'identity_failed_answer' in response.body 383 368 384 369 def test_require_expose_required_permission(self): 385 370 """Test that the decorator exposes the correct permissions via _require 386 371 attribute on the actual method.""" 387 testutil.create_request('/test_exposed_require') 388 firstline= cherrypy.response.body[0] 389 assert 'require is exposed' in firstline, firstline 372 response = testutil.go('/test_exposed_require') 373 assert 'require is exposed' in response.body 390 374 391 375 def test_require_group_viewable(self): 392 376 """Test that a user with proper group membership can see a restricted url.""" 393 testutil.create_request('/in_peon_group?'377 response = testutil.go('/in_peon_group?' 394 378 'user_name=samIam&password=secret&login=Login') 395 firstline = cherrypy.response.body[0] 396 assert 'in_peon_group' in firstline, firstline 397 user = TG_User.by_user_name("samIam") 379 assert 'in_peon_group' in response.body 398 380 399 381 def test_require_group_viewable(self): 400 382 """Test that the current user and group properties are set correctly.""" 401 testutil.create_request('/in_peon_group?'383 response = testutil.go('/identity_current_set?' 402 384 'user_name=samIam&password=secret&login=Login') 403 user = TG_User.by_user_name("samIam") 404 group_ids = set((TG_Group.by_group_name("peon").id, 405 TG_Group.by_group_name("other").id)) 406 assert identity.current.user == user 407 assert identity.current.user_name == user.user_name 408 assert identity.current.user_id == user.id 409 assert identity.current.groups == set(('peon', 'other')) 410 assert identity.current.group_ids == group_ids 385 assert response.body == 'identity_current_set' 411 386 412 387 def test_user_not_in_right_group(self): 413 388 """Test that a user is denied access if they aren't in the right group.""" 414 testutil.create_request('/in_admin_group?'389 response = testutil.go('/in_admin_group?' 415 390 'user_name=samIam&password=secret&login=Login') 416 firstline = cherrypy.response.body[0] 417 assert 'identity_failed_answer' in firstline, firstline 391 assert 'identity_failed_answer' in response.body 418 392 419 393 def test_require_permission(self): 420 394 """Test that an anonymous user is denied access to a permission restricted url.""" 421 testutil.create_request('/has_chopper_permission') 422 firstline = cherrypy.response.body[0] 423 assert 'identity_failed_answer' in firstline, firstline 395 response = testutil.go('/has_chopper_permission') 396 assert 'identity_failed_answer' in response.body 424 397 425 398 def test_require_permission_viewable(self): 426 399 """Test that a user with proper permissions can see a restricted url.""" 427 testutil.create_request('/has_chopper_permission?'400 response = testutil.go('/has_chopper_permission?' 428 401 'user_name=samIam&password=secret&login=Login') 429 firstline = cherrypy.response.body[0] 430 assert 'has_chopper_permission' in firstline, firstline 402 assert 'has_chopper_permission' in response.body 431 403 432 404 def test_user_lacks_permission(self): 433 405 """Test that a user is denied acces if they don't have the proper permission.""" 434 testutil.create_request('/has_boss_permission?'406 response = testutil.go('/has_boss_permission?' 435 407 'user_name=samIam&password=secret&login=Login') 436 firstline = cherrypy.response.body[0] 437 assert 'identity_failed_answer' in firstline, firstline 408 assert 'identity_failed_answer' in response.body 438 409 439 410 def test_user_info_available(self): 440 411 """Test that we can see user information inside our controller.""" 441 testutil.create_request('/user_email?'412 response = testutil.go('/user_email?' 442 413 'user_name=samIam&password=secret&login=Login') 443 firstline = cherrypy.response.body[0] 444 assert 'samiam@example.com' in firstline, firstline 414 assert 'samiam@example.com' in response.body 445 415 446 416 def test_bad_login(self): 447 417 """Test that we are denied access if we provide a bad login.""" 448 testutil.create_request('/logged_in_only?'418 response = testutil.go('/logged_in_only?' 449 419 'user_name=samIam&password=wrong&login=Login') 450 firstline = cherrypy.response.body[0] 451 assert 'identity_failed_answer' in firstline, firstline 420 assert 'identity_failed_answer' in response.body 452 421 453 422 def test_restricted_subdirectory(self): 454 423 """Test that we can restrict access to a whole subdirectory.""" 455 testutil.create_request('/peon_area/index') 456 firstline = cherrypy.response.body[0] 457 assert 'identity_failed_answer' in firstline, firstline 424 response = testutil.go('/peon_area/index') 425 assert 'identity_failed_answer' in response.body 458 426 459 427 def test_restricted_subdirectory_viewable(self): 460 428 """Test that we can access a restricted subdirectory 461 429 if we have proper credentials.""" 462 testutil.create_request('/peon_area/index?'430 response = testutil.go('/peon_area/index?' 463 431 'user_name=samIam&password=secret&login=Login') 464 firstline = cherrypy.response.body[0] 465 assert 'restricted_index' in firstline, firstline 432 assert 'restricted_index' in response.body 466 433 467 434 def test_decoratator_in_restricted_subdirectory(self): 468 435 """Test that we can require a different permission 469 436 in a protected subdirectory.""" 470 testutil.create_request('/peon_area/in_other_group?'437 response = testutil.go('/peon_area/in_other_group?' 471 438 'user_name=samIam&password=secret&login=Login') 472 firstline = cherrypy.response.body[0] 473 assert 'in_other_group' in firstline, firstline 439 assert 'in_other_group' in response.body 474 440 475 441 def test_decoratator_failure_in_restricted_subdirectory(self): 476 442 """Test that we can get an identity failure from a decorator 477 443 in a restricted subdirectory""" 478 testutil.create_request('/peon_area/in_admin_group?'444 response = testutil.go('/peon_area/in_admin_group?' 479 445 'user_name=samIam&password=secret&login=Login') 480 firstline = cherrypy.response.body[0] 481 assert 'identity_failed_answer' in firstline, firstline 446 assert 'identity_failed_answer' in response.body 482 447 483 448 def test_explicit_checks_in_restricted_subdirectory(self): 484 449 """Test that explicit permission checks in a protected 485 450 directory is handled as expected""" 486 testutil.create_request('/peon_area/in_other_group_explicit_check?'451 response = testutil.go('/peon_area/in_other_group_explicit_check?' 487 452 'user_name=samIam&password=secret&login=Login') 488 firstline = cherrypy.response.body[0] 489 assert 'in_other_group' in firstline, firstline 453 assert 'in_other_group' in response.body 490 454 491 455 def test_throwing_identity_exception_in_restricted_subdirectory(self): 492 456 """Test that throwing an IdentityException in a protected 493 457 directory is handled as expected""" 494 testutil.create_request('/peon_area/in_admin_group_explicit_check?'458 response = testutil.go('/peon_area/in_admin_group_explicit_check?' 495 459 'user_name=samIam&password=secret&login=Login') 496 firstline = cherrypy.response.body[0] 497 assert 'identity_failed' in firstline, firstline 460 assert 'identity_failed' in response.body 498 461 499 462 def test_decode_filter_whenidfails(self): 500 463 """Test that the decode filter doesn't break with nested 501 464 variables and Identity""" 502 465 params = urllib.quote(IdentityRoot._test_encoded_params.decode( 503 466 'utf-8').encode('latin-1'), '=&') 504 testutil.create_request('/test_params?' + params) 505 firstline = cherrypy.response.body[0] 506 assert 'identity_failed_answer' in firstline, firstline 467 response = testutil.go('/test_params?' + params) 468 assert 'identity_failed_answer' in response.body 507 469 508 470 def test_decode_filter_whenidworks(self): 509 471 """Test that the decode filter doesn't break with nested … … 511 473 params = urllib.quote(IdentityRoot._test_encoded_params.decode( 512 474 'utf-8').encode('latin-1'), '=&') 513 475 params += '&user_name=samIam&password=secret&login=Login' 514 testutil.create_request('/test_params?' + params) 515 firstline = cherrypy.response.body[0] 516 assert 'params ok' in firstline, firstline 476 response = testutil.go('/test_params?' + params) 477 assert 'params ok' in response.body 517 478 518 479 519 480 class TestTGUser(testutil.DBTest): … … 522 483 def setUp(self): 523 484 self._identity_on = config.get('identity.on', False) 524 485 config.update({'identity.on': False}) 525 try: 526 self._provider = cherrypy.request.identityProvider 527 except AttributeError: 528 self._provider= None 529 cherrypy.request.identityProvider = None 530 startup.startTurboGears() 486 testutil.start_server() 531 487 testutil.DBTest.setUp(self) 532 488 533 489 def tearDown(self): 534 490 testutil.DBTest.tearDown(self) 535 startup.stopTurboGears() 536 cherrypy.request.identityProvider = self._provider 491 testutil.stop_server() 537 492 config.update({'identity.on': self._identity_on}) 538 493 539 494 def test_create_user(self): -
turbogears/identity/tests/test_visit.py
old new 2 2 from unittest import TestCase 3 3 import cherrypy 4 4 from turbogears import config, controllers, expose, startup, testutil, visit 5 from Cookie import SimpleCookie 5 6 6 7 7 def cookie_header( morsel):8 def cookie_header(response): 8 9 """Returns a dict containing cookie information to pass to a server.""" 9 return {'Cookie': morsel.output(header="")[1:]}10 return dict(Cookie=response.headers['Set-Cookie']) 10 11 11 12 12 13 class VisitRoot(controllers.RootController): 13 14 14 15 @expose() 15 16 def index(self): 16 return dict() 17 new = None 18 if visit.current(): 19 new = visit.current().is_new 20 return dict(new=new) 21 17 22 18 19 23 class TestVisit(TestCase): 20 24 21 25 def setUp(self): … … 27 31 cherrypy.root = VisitRoot() 28 32 29 33 def tearDown(self): 30 startup.stopTurboGears()34 testutil.stop_server() 31 35 config.update({'visit.timeout': self._visit_timeout}) 32 36 config.update({'visit.on': self._visit_on}) 33 37 34 38 def test_visit_response(self): 35 39 """Test if the visit cookie is set in cherrypy.response.""" 36 testutil.create_request("/")37 assert cherrypy.response.simple_cookie.has_key(self.cookie_name)40 response = testutil.go("/") 41 assert response.cookies_set.has_key(self.cookie_name) 38 42 39 43 def test_new_visit(self): 40 44 """Test that we can see a new visit on the server.""" 41 testutil.create_request("/")42 assert visit.current().is_new45 response = testutil.go("/") 46 assert response.raw['new'] 43 47 44 48 def test_old_visit(self): 45 49 """Test if we can track a visitor over time.""" 46 testutil.create_request("/")50 response = testutil.go("/") 47 51 # first visit's cookie 48 morsel = cherrypy.response.simple_cookie[self.cookie_name]49 testutil.create_request("/", headers=cookie_header(morsel))50 assert not visit.current().is_new52 morsel = response.cookies_set[self.cookie_name] 53 response = testutil.go("/", headers=cookie_header(response)) 54 assert not response.raw['new'] 51 55 52 56 def test_cookie_expires(self): 53 57 """Test if the visit timeout mechanism works.""" … … 55 59 try: 56 60 # set expiration to one second for this test only 57 61 config.update({'visit.timeout': 1.0/60}) 58 testutil.create_request("/")59 morsel = cherrypy.response.simple_cookie[self.cookie_name]62 response = testutil.go("/") 63 morsel = response.cookies_set[self.cookie_name] 60 64 time.sleep(2) # 2 seconds 61 testutil.create_request("/", headers=cookie_header(morsel))65 response = testutil.go("/", headers=cookie_header(response)) 62 66 finally: 63 67 config.update({'visit.timeout': timeout}) 64 assert cherrypy.response.simple_cookie[65 self.cookie_name] .value != morsel.value, \68 assert response.cookies_set[ 69 self.cookie_name] != morsel, \ 66 70 'cookie values should not match' 67 assert visit.current().is_new, \71 assert response.raw['new'], \ 68 72 'this should be a new visit, as the cookie has expired' 69 73 70 74 def test_cookie_not_permanent(self): 71 75 """Check that by default the visit cookie is not permanent.""" 72 testutil.create_request('/') 73 morsel = cherrypy.response.simple_cookie[self.cookie_name] 76 response = testutil.go('/') 77 cookies = SimpleCookie(response.headers['Set-Cookie']) 78 morsel = cookies[self.cookie_name] 74 79 assert not morsel['expires'] and not morsel['max-age'] 75 80 76 81 def test_cookie_permanent(self): … … 80 85 # set cookie permanent for this test only (needs restart) 81 86 startup.stopTurboGears() 82 87 config.update({'visit.cookie.permanent': True}) 83 startup.startTurboGears() 84 testutil.create_request('/') 85 morsel = cherrypy.response.simple_cookie[self.cookie_name] 88 testutil.start_server() 89 response = testutil.go('/') 90 cookies = SimpleCookie(response.headers['Set-Cookie']) 91 morsel = cookies[self.cookie_name] 86 92 finally: 87 93 config.update({'visit.cookie.permanent': permanent}) 88 assert morsel['max-age'] == 300094 assert morsel['max-age'] == '3000' 89 95 expires = time.mktime(time.strptime(morsel['expires'], 90 96 '%a, %d-%b-%Y %H:%M:%S GMT')[:8] + (0,)) 91 should_expire = time.mktime(time.gmtime()) + morsel['max-age'] 92 assert abs(should_expire - expires) < 3 97 should_expire = time.mktime(time.gmtime()) + int(morsel['max-age']) 98 assert abs(should_expire - expires) < 3, (should_expire, expires, should_expire - expires) 99 -
turbogears/visit/api.py
old new 251 251 max_age = self.cookie_max_age 252 252 if max_age: 253 253 # use 'expires' because MSIE ignores 'max-age' 254 cookies[self.cookie_name]['expires'] = time.strftime(254 cookies[self.cookie_name]['expires'] = '"%s"' % time.strftime( 255 255 "%a, %d-%b-%Y %H:%M:%S GMT", 256 256 time.gmtime(time.time() + max_age)) 257 257 # 'max-age' takes precedence on standard conformant browsers -
turbogears/tests/test_form_controllers.py
old new 31 31 def testform(self, name, date, age, tg_errors=None): 32 32 if tg_errors: 33 33 self.has_errors = True 34 self.name = name 35 self.age = age 36 self.date = date 34 return dict(name=name, user_age=age, birthdate=date) 37 35 38 36 @expose() 39 37 @validate(form=myform) 40 38 def testform_new_style(self, name, date, age): 41 39 if cherrypy.request.validation_errors: 42 40 self.has_errors = True 43 self.name = name 44 self.age = age 45 self.date = date 41 return dict(name=name, age=age, date=date) 46 42 47 43 def test_form_translation(): 48 44 """Form input is translated into properly converted parameters""" 49 root = MyRoot() 50 cherrypy.root = root 51 testutil.create_request("/testform?name=ed&date=11/05/2005&age=5") 52 assert root.name == "ed" 53 assert root.age == 5 45 testutil.start_server(root = MyRoot()) 46 response = testutil.go("/testform?name=ed&date=11/05/2005&age=5") 47 assert response.raw['name'] == "ed" 48 assert response.raw['user_age'] == 5 54 49 55 50 def test_form_translation_new_style(): 56 51 """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 52 testutil.start_server(root = MyRoot()) 53 response = testutil.go("/testform_new_style?name=ed&date=11/05/2005&age=5&") 54 assert response.raw['name'] == "ed" 55 assert response.raw['age'] == 5 62 56 63 57 def test_invalid_form_with_error_handling(): 64 58 """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 59 response = testutil.go("/testform?name=ed&age=edalso&date=11/05/2005") 68 60 69 61 def test_css_should_appear(): 70 62 """CSS should appear when asked for""" 71 testutil.create_request("/") 72 assert "calendar-system.css" in cherrypy.response.body[0] 63 testutil.start_server(root = MyRoot()) 64 response = testutil.go("/") 65 assert "calendar-system.css" in response 73 66 74 67 def test_javascript_should_appear(): 75 68 """JavaScript should appear when asked for""" 76 testutil.create_request("/")77 assert "calendar.js" in cherrypy.response.body[0]69 response = testutil.go("/") 70 assert "calendar.js" in response 78 71 79 72 def test_include_mochikit(): 80 73 """JSLinks (and MochiKit especially) can be included easily""" 81 testutil.create_request("/usemochi")82 assert "MochiKit.js" in cherrypy.response.body[0]74 response = testutil.go("/usemochi") 75 assert "MochiKit.js" in response 83 76 84 77 def test_suppress_mochikit(): 85 78 """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] 79 config.update({"global":{"tg.mochikit_suppress" : True}}) 80 suppressed = testutil.go("/usemochi") 89 81 # 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 82 config.update({"global":{"tg.mochikit_suppress" : False}}) 95 83 84 included = testutil.go("/usemochi") 85 assert "MochiKit.js" not in suppressed.body 86 assert "MochiKit.js" in included.body 87 96 88 def test_mochikit_everywhere(): 97 89 """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]90 config.update({"global":{"tg.mochikit_all" : True}}) 91 response = testutil.go("/") 92 config.update({"global":{"tg.mochikit_all" : False}}) 93 assert "MochiKit.js" in response 102 94 103 95 def test_mochikit_nowhere(): 104 96 """Setting tg.mochikit_suppress will prevent including it everywhere""" 105 97 config.update({"global": {"tg.mochikit_all": True}}) 106 98 config.update({"global": {"tg.mochikit_suppress": True}}) 107 testutil.create_request("/")99 response = testutil.go("/") 108 100 config.update({"global": {"tg.mochikit_all": False}}) 109 101 config.update({"global": {"tg.mochikit_suppress": False}}) 110 assert "MochiKit.js" not in cherrypy.response.body[0]102 assert "MochiKit.js" not in response 111 103 112 104 def test_include_widgets(): 113 105 """Any widget can be included everywhere by setting tg.include_widgets""" 114 106 config.update({"global": {"tg.include_widgets": ["mochikit"]}}) 115 testutil.create_request("/")107 response = testutil.go("/") 116 108 config.update({"global": {"tg.include_widgets": []}}) 117 assert "MochiKit.js" in cherrypy.response.body[0]109 assert "MochiKit.js" in response 118 110 119 111 120 112 class State(object): … … 146 138 super(TestValidationState, self).__init__(*args, **kw) 147 139 148 140 def test_counter_is_incremented(self): 149 cherrypy.root = self.Controller()141 testutil.start_server(root = self.Controller()) 150 142 # parameter values are irrelevant 151 143 url = '/validation?a=1&b=2&c.a=3&c.b=4' 152 testutil.create_request(url) 153 body = cherrypy.response.body[0] 144 response = testutil.go(url) 154 145 msg = "Validation state is not handled properly" 155 146 # 4 == 1 (a) + 1(b) + 1(c.a) + 1(c.b) 156 self.failUnless('counter: 4' in body, msg)147 self.failUnless('counter: 4' in response, msg) -
turbogears/tests/test_errorhandling.py
old new 1 1 import unittest 2 3 import cherrypy4 5 2 from turbogears.controllers import error_handler, exception_handler, \ 6 3 expose, validate, RootController, Controller 7 4 from turbogears.errorhandling import FailsafeSchema … … 94 91 "second": validators.Int(not_empty=True)}) 95 92 @error_handler(defaulterrorhandler) 96 93 def positionalargs(self, first, second, *args, **kw): 97 self.first = first98 self.second = second99 self.third = args[0]100 94 return dict(title="Positional arguments", first=first, second=second, 101 args=args, bar=kw["bar"])95 third=args[0], args=args, bar=kw["bar"]) 102 96 103 97 @expose() 104 98 @validate(validators={"bar": validators.Int(not_empty=True)}) … … 141 135 return self.notexposed(bar) 142 136 143 137 def continuation(self, tg_source): 144 self.continuation = True 145 return tg_source(self) 138 response = tg_source(self) 139 response['continuation'] = True 140 return response 146 141 147 142 @expose() 148 143 @validate(validators={"bar": validators.Int(not_empty=True)}) … … 211 206 class TestErrorHandler(unittest.TestCase): 212 207 213 208 def setUp(self): 214 cherrypy.root = MyRoot() 215 cherrypy.root.nestedcontroller = NestedController() 209 testutil.mount(MyRoot()) 210 testutil.mount(NestedController(), "/nestedcontroller") 211 testutil.start_server() 216 212 217 213 def test_defaultErrorHandler(self): 218 214 """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])215 response = testutil.go("/defaulterror?bar=abc") 216 self.failUnless("Default error handler" in response) 217 response = testutil.go("/defaulterror?bar=true") 218 self.failUnless("Default error provider" in response) 223 219 224 220 def test_specialisedErrorHandler(self): 225 221 """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") 229 self.failUnless("Specialised error handler" in 230 cherrypy.response.body[0]) 231 testutil.create_request("/specialisederror?bar=1&baz=a@b.com") 232 self.failUnless("Specialised error provider" in 233 cherrypy.response.body[0]) 222 response = testutil.go("/specialisederror?bar=abc&baz=a@b.com") 223 self.failUnless("Default error handler" in response) 224 response = testutil.go("/specialisederror?baz=abc&bar=1") 225 self.failUnless("Specialised error handler" in response) 226 response = testutil.go("/specialisederror?bar=1&baz=a@b.com") 227 self.failUnless("Specialised error provider" in response) 234 228 235 229 def test_exceptionErrorHandler(self): 236 230 """Error handler for exceptions.""" 237 testutil.create_request("/exceptionerror")238 self.failUnless("Default error handler" in cherrypy.response.body[0])231 response = testutil.go("/exceptionerror") 232 self.failUnless("Default error handler" in response) 239 233 240 234 def test_recursiveErrorHandler(self): 241 235 """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") 245 self.failUnless("Recursive error provider" in 246 cherrypy.response.body[0]) 236 response = testutil.go("/recursiveerror?bar=abc") 237 self.failUnless("Recursive error handler" in response) 238 response = testutil.go("/recursiveerror?bar=1") 239 self.failUnless("Recursive error provider" in response) 247 240 248 241 def test_implicitErrorHandler(self): 249 242 """Implicit error handling.""" 250 testutil.create_request("/impliciterror?bar=abc") 251 self.failUnless("Implicit error handler" in 252 cherrypy.response.body[0]) 253 testutil.create_request("/impliciterror?bar=1") 254 self.failUnless("Implicit error provider" in 255 cherrypy.response.body[0]) 243 response = testutil.go("/impliciterror?bar=abc") 244 self.failUnless("Implicit error handler" in response) 245 response = testutil.go("/impliciterror?bar=1") 246 self.failUnless("Implicit error provider" in response) 256 247 257 248 def test_normalMethodErrorHandler(self): 258 249 """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])250 response = testutil.go("/normalmethodcaller?bar=abc") 251 self.failUnless("Normal method" in response) 252 response = testutil.go("/normalmethodcaller?bar=true") 253 self.failUnless("Normal method caller" in response) 263 254 264 255 def test_infiniteRecursionPrevention(self): 265 256 """Infinite recursion prevention.""" 266 testutil.create_request("/infiniteloop")267 self.failUnless("Exception 2" in cherrypy.response.body[0])257 response = testutil.go("/infiniteloop") 258 self.failUnless("Exception 2" in response) 268 259 269 260 def test_positionalArgs(self): 270 261 """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])279 self.failUnless( cherrypy.root.first== "first")280 self.failUnless( cherrypy.root.second== 23)281 self.failUnless( cherrypy.root.third== "third")262 response = testutil.go("/positionalargs/first/23/third?bar=abc") 263 self.failUnless("Default error handler" in response) 264 response = testutil.go("/positionalargs/first/abc/third?bar=false") 265 self.failUnless("Default error handler" in response) 266 response = testutil.go("/positionalargs/first/abc/third?bar=abc") 267 self.failUnless("Default error handler" in response) 268 response = testutil.go("/positionalargs/first/23/third?bar=true") 269 self.failUnless("Positional arguments" in response) 270 self.failUnless(response.raw['first'] == "first") 271 self.failUnless(response.raw['second'] == 23) 272 self.failUnless(response.raw['third'] == "third") 282 273 283 274 def test_missingArgs(self): 284 275 """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])276 response = testutil.go("/missingargs") 277 self.failUnless("Default error handler" in response) 278 response = testutil.go("/missingargs?bar=12") 279 self.failUnless("Missing args provider" in response) 289 280 290 281 def test_nohandler(self): 291 282 """No error hanlder declared.""" 292 testutil.create_request("/nohandler")293 self.failUnless("Exception raised" in cherrypy.response.body[0])283 response = testutil.go("/nohandler") 284 self.failUnless("Exception raised" in response) 294 285 295 286 def test_bindArgs(self): 296 287 """Arguments can be bond to an error handler.""" 297 testutil.create_request("/bindargs")298 self.failUnless("123" in cherrypy.response.body[0])288 response = testutil.go("/bindargs") 289 self.failUnless("123" in response) 299 290 300 291 def test_notExposed(self): 301 292 """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])293 response = testutil.go("/notexposedcaller?foo=a&bar=rab&baz=c") 294 self.failUnless("Not exposed error" in response) 295 self.failUnless("rab" in response) 305 296 306 297 def test_continuations(self): 307 298 """Continuations via error handling mechanism.""" 308 testutil.create_request("/continuationcaller?bar=a")309 self.failUnless("Continuation caller" in cherrypy.response.body[0])310 self.failUnless( cherrypy.root.continuation== True)299 response = testutil.go("/continuationcaller?bar=a") 300 self.failUnless("Continuation caller" in response) 301 self.failUnless(response.raw['continuation'] == True) 311 302 312 303 def test_nested(self): 313 304 """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