Ticket #1762: webtest-ken.patch
| File webtest-ken.patch, 134.9 KB (added by kskuhlman, 4 years ago) |
|---|
-
setup.py
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
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
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
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
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
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 self.failUnless("Nested" in cherrypy.response.body[0])305 response = testutil.go("/nest?bar=a") 306 self.failUnless("Default error handler" in response) 307 response = testutil.go("/nestedcontroller/nest?bar=a") 308 self.failUnless("Nested" in response) 318 309 319 310 def test_failsafe(self): 320 311 """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") 331 self.failUnless('"bar": "Please enter an integer value"' in 332 cherrypy.response.body[0]) 333 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]) 312 response = testutil.go("/failsafenone?bar=a&baz=b") 313 self.failUnless('"bar": "a"' in response) 314 self.failUnless('"baz": "b"' in response) 315 response = testutil.go("/failsafevaluesdict?bar=a&baz=b") 316 self.failUnless('"bar": 1' in response) 317 self.failUnless('"baz": 2' in response) 318 response = testutil.go("/failsafevaluesatom?bar=a&baz=b") 319 self.failUnless('"bar": 13' in response) 320 self.failUnless('"baz": 13' in response) 321 response = testutil.go("/failsafemaperrors?bar=a&baz=b") 322 self.failUnless('"bar": "Please enter an integer value"' in response) 323 self.failUnless('"baz": "Please enter an integer value"' in response) 324 response = testutil.go("/failsafeformencode?bar=a&baz=b") 325 self.failUnless('"bar": 1' in response) 326 self.failUnless('"baz": 2' in response) 327 response = testutil.go("/failsafedefaults?bar=a&baz=b") 328 self.failUnless('"bar": 1' in response) 329 self.failUnless('"baz": 2' in response) -
turbogears/tests/test_sqlalchemy.py
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 import testutil 13 from turbogears.testutil import go, sqlalchemy_cleanup, \ 13 14 capture_log, print_log 14 15 15 16 … … 135 136 will be marked with this name :) 136 137 137 138 """ 138 cherrypy.response.code = 501139 139 msg = "KARL25 responding\n" 140 140 msg += "user with id: '%s' should not be saved.\n" % id 141 141 msg += "An exception occurred: %r (%s)" % ((tg_exceptions,)*2) … … 165 165 def test_implicit_trans_no_error(): 166 166 """If a controller runs sucessfully, the transaction is commited.""" 167 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 168 testutil.start_server(root = MyRoot()) 169 response = go("/no_error?name=A.%20Dent") 172 170 print_log() 173 171 q = session.query(Person) 174 172 arthur = q.filter_by(name="A. Dent").first() 175 assert 'someconfirmhandler' in output, \173 assert 'someconfirmhandler' in response, \ 176 174 'The no error should have redirected to someconfirmhandler' 177 175 assert arthur is not None, 'Person arthur should have been saved!' 178 176 assert arthur.name == "A. Dent", 'Person arthur should be named "A. Dent"' … … 180 178 def test_raise_sa_exception(): 181 179 """If a controller causes an SA exception, it is raised properly.""" 182 180 capture_log("turbogears.database") 183 cherrypy.root = MyRoot() 184 create_request("/create_person?id=20") 185 output = cherrypy.response.body[0] 181 testutil.start_server(root = MyRoot()) 182 response = go("/create_person?id=20") 186 183 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, \ 184 assert 'No exceptions occurred' in response 185 response = go("/create_person?id=20", status=500) 186 assert 'KARL25' not in response, \ 195 187 'Exception should NOT have been handled by our handler' 196 assert 'DBAPIError' in output, \188 assert 'DBAPIError' in response, \ 197 189 'The page should have displayed an SQLAlchemy exception' 198 190 199 191 def test_user_exception(): 200 192 """If a controller raises an exception, transactions are rolled back.""" 201 193 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] 194 testutil.start_server(MyRoot()) 195 response = go("/create_person?id=19&docom=0&doerr=1&name=Martin%20GAL") 205 196 print_log() 206 print output 207 assert 'KARL25' in output, \ 197 assert 'KARL25' in response, \ 208 198 'The exception handler should have answered us' 209 199 p = session.query(Person).get(19) 210 200 assert p is None, \ … … 212 202 213 203 def test_user_redirect(): 214 204 """If a controller redirects, transactions are committed.""" 215 cherrypy.root = MyRoot()216 create_request("/create_person?id=22&doerr=2")205 testutil.start_server(MyRoot()) 206 go("/create_person?id=22&doerr=2") 217 207 assert session.query(Person).get(22) is not None, \ 218 208 'The controller only redirected, the Person should have been saved' 219 209 220 210 def test_cntrl_commit(): 221 211 """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]212 testutil.start_server(MyRoot()) 213 response = go("/create_person?id=23&docom=1") 214 assert 'InvalidRequestError' not in response 225 215 assert session.query(Person).get(23) is not None, \ 226 216 'The Person 23 should have been saved during commit inside controller' 227 217 228 218 def test_cntrl_commit2(): 229 219 """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]220 testutil.start_server(MyRoot()) 221 response = go("/create_person?id=24&docom=1&doerr=1") 222 assert 'InvalidRequestError' not in response 233 223 assert session.query(Person).get(24) is not None, \ 234 224 'The Person 24 should have been saved during commit' \ 235 225 ' inside controller and not rolled back' 236 226 237 227 def test_cntrl_flush(): 238 228 """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] 229 testutil.start_server(MyRoot()) 230 response = go("/create_person?id=25&doflush=1") 231 assert 'No exceptions occurred' in response 232 response = go("/create_person?id=25&doflush=0", status=500) 233 assert 'IntegrityError' in response 234 response = go("/create_person?id=25&doflush=1") 235 assert 'IntegrityError' in response 236 response = go("/create_person?id=25&doflush=2") 237 assert 'No exceptions occurred' in response 252 238 253 239 254 240 # Exception handling with rollback … … 301 287 is created by the exception handler. 302 288 303 289 """ 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' 290 testutil.start_server(RbRoot()) 291 response = go('/doerr?id=26') 292 assert 'KARL27' in response, 'Exception handler should have answered' 309 293 assert session.query(User).get(26) is None 310 294 assert session.query(User).get(27) is not None 311 295 … … 316 300 so user XX should not exist. 317 301 318 302 """ 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' 303 testutil.start_server(RbRoot()) 304 response = go('/doerr?id=XX') 305 assert 'KARL27' in response, 'Exception handler should have answered' 323 306 assert session.query(User).get('XX') is None 324 307 325 308 def test_exc_done_rollback(): 326 309 """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' 310 testutil.start_server(RbRoot()) 311 response = go('/doerr?id=28&dorb=1') 312 assert 'KARL27' in response, 'Exception handler should have answered' 331 313 assert session.query(User).get(28) is None 332 314 assert session.query(User).get(29) is not None 333 315 … … 360 342 361 343 """ 362 344 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] 345 testutil.start_server(FreshRoot()) 346 response = go("/test1", status = 200) 347 assert 'AssertionError' not in response 367 348 # Call test2 in a different thread 368 349 class ThreadB(threading.Thread): 369 350 def run(self): 370 create_request("/test2") 371 assert cherrypy.response.status.startswith("200") 372 assert 'AssertionError' not in cherrypy.response.body[0] 351 response = go("/test2", status=200) 352 assert 'AssertionError' not in response 373 353 thrdb = ThreadB() 374 354 thrdb.start() 375 355 thrdb.join() 376 create_request("/test3") 377 assert cherrypy.response.status.startswith("200") 378 assert 'AssertionError' not in cherrypy.response.body[0] 356 response = go("/test3", status=200) 357 assert 'AssertionError' not in response -
turbogears/tests/test_expose.py
1 import cherrypy2 1 import simplejson 3 4 2 from turbogears import controllers, expose 5 from turbogears.testutil import create_request3 from turbogears.testutil import go, start_server 6 4 7 5 8 6 class ExposeRoot(controllers.RootController): … … 20 18 21 19 22 20 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 start_server(root = ExposeRoot()) 22 response = go("/with_json") 23 assert "Paging all foo" in response 27 24 28 25 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 26 start_server(root = ExposeRoot()) 27 response = go("/with_json?tg_format=json") 28 assert '"title": "Foobar"' in response 33 29 34 30 def test_gettingjsonviaaccept(): 35 cherrypy.root = ExposeRoot()36 create_request("/with_json_via_accept",31 start_server(root = ExposeRoot()) 32 response = go("/with_json_via_accept", 37 33 headers=dict(Accept="text/javascript")) 38 body = cherrypy.response.body[0] 39 assert '"title": "Foobar"' in body 34 assert '"title": "Foobar"' in response 40 35 41 36 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 body 37 start_server(root = ExposeRoot()) 38 response = go("/with_json_via_accept?tg_format=json") 39 assert '"title": "Foobar"' in response 46 40 47 41 def test_getting_plaintext(): 48 cherrypy.root = ExposeRoot()49 create_request("/with_json_via_accept",42 start_server(root = ExposeRoot()) 43 response = go("/with_json_via_accept", 50 44 headers=dict(Accept="text/plain")) 51 print cherrypy.response.body[0] 52 assert cherrypy.response.body[0] == "This is a plain text for foo." 45 assert response.body == "This is a plain text for foo." 53 46 54 47 def test_allow_json(): 55 48 … … 58 51 def test(self): 59 52 return dict(title="Foobar", mybool=False, someval="niggles") 60 53 61 cherrypy.root = NewRoot() 62 create_request("/test", headers= dict(accept="text/javascript")) 63 body = cherrypy.response.body[0] 64 values = simplejson.loads(body) 54 start_server(root = NewRoot()) 55 response = go("/test", headers= dict(accept="text/javascript")) 56 values = simplejson.loads(response.body) 65 57 assert values == dict(title="Foobar", mybool=False, someval="niggles", 66 58 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) 59 assert response.headers["Content-Type"] == "text/javascript" 60 response = go("/test?tg_format=json") 61 values = simplejson.loads(response.body) 71 62 assert values == dict(title="Foobar", mybool=False, someval="niggles", 72 63 tg_flash=None) 73 assert cherrypy.response.headers["Content-Type"] == "text/javascript"64 assert response.headers["Content-Type"] == "text/javascript" -
turbogears/tests/test_controllers.py
1 1 import unittest 2 import formencode 3 import cherrypy 4 import pkg_resources 2 import urllib 3 import turbogears 5 4 from turbogears import config, controllers, database, \ 6 5 error_handler, exception_handler, expose, flash, redirect, \ 7 6 startup, testutil, url, validate, validators 7 from turbogears.testutil import go 8 import simplejson 9 import formencode 10 import cherrypy 11 import pkg_resources 12 from nose.tools import eq_ 8 13 9 14 10 15 class SubApp(controllers.RootController): … … 13 18 def index(self): 14 19 return url("/Foo/") 15 20 21 @expose() 22 def foo(self): 23 return url("foo") 16 24 25 @expose() 26 def foo2(self): 27 return url("/foo") 28 29 @expose() 30 def redir(self): 31 turbogears.redirect("/foo") 32 33 @expose() 34 def redir2(self): 35 raise turbogears.redirect("/foo") 36 37 38 17 39 class MyRoot(controllers.RootController): 18 40 19 41 @expose() 20 42 def index(self): 21 pass43 return {} 22 44 23 45 def validation_error_handler(self, tg_source, tg_errors, *args, **kw): 24 self.functionname = tg_source.__name__25 self.values = kw26 46 self.errors = tg_errors 27 return "Error Message" 47 errors = {} 48 for (key, value) in tg_errors.items(): 49 if hasattr(value, 'msg'): 50 errors[key] = value.msg 51 else: 52 errors[key] = value 53 return dict(msg = "Error Message", values = kw, errors = errors) 28 54 29 55 @expose(html="turbogears.tests.simple", allow_json=True) 30 56 def test(self): … … 36 62 37 63 @expose() 38 64 def pos(self, posvalue): 39 self.posvalue = posvalue 40 return "" 65 return dict(posvalue = posvalue) 41 66 42 67 @expose() 43 def servefile(self, tg_exceptions=None): 44 self.servedit = True 45 self.serve_exceptions = tg_exceptions 68 def servefile(self): 46 69 return cherrypy.lib.cptools.serveFile( 47 70 pkg_resources.resource_filename( 48 71 "turbogears.tests", "test_controllers.py")) … … 70 93 @validate(validators={'value': validators.StringBoolean()}) 71 94 @error_handler(validation_error_handler) 72 95 def istrue(self, value): 73 self.value = value 74 return str(value) 96 return dict(value=str(value)) 75 97 76 98 @expose() 77 99 @validate(validators={'value': validators.StringBoolean()}) … … 117 139 "lastname": validators.String()}) 118 140 @error_handler(validation_error_handler) 119 141 def save(self, submit, firstname, lastname="Miller"): 120 self.submit = submit 121 self.firstname = firstname 122 self.lastname = lastname 123 self.fullname = "%s %s" % (self.firstname, self.lastname) 124 return self.fullname 142 submit = submit 143 firstname = firstname 144 lastname = lastname 145 fullname = "%s %s" % (firstname, lastname) 146 return dict(firstname = firstname, lastname = lastname, 147 fullname = fullname, submit = submit) 125 148 126 149 class Registration(formencode.Schema): 127 150 allow_extra_fields = True … … 145 168 rwt_called = 0 146 169 def rwt(self, func, *args, **kw): 147 170 self.rwt_called += 1 148 func(*args, **kw) 171 result = func(*args, **kw) 172 print result 173 result += 'rwt_called = %s' % self.rwt_called 174 return result 149 175 150 176 @expose(html="turbogears.tests.simple", allow_json=True) 151 177 def flash_plain(self): … … 223 249 class TestRoot(unittest.TestCase): 224 250 225 251 def setUp(self): 226 cherrypy.root = None 227 cherrypy.tree.mount_points = {} 228 cherrypy.tree.mount(MyRoot(), "/") 229 cherrypy.tree.mount(SubApp(), "/subthing") 252 testutil.mount(MyRoot()) 253 testutil.mount(SubApp(), '/subthing') 230 254 231 def tearDown(self):232 cherrypy.root = None233 cherrypy.tree.mount_points = {}234 235 255 def test_js_files(self): 236 256 """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" 257 response = testutil.go("/tg_js/MochiKit.js", status=200) 258 assert response.headers["Content-Type"] == "application/x-javascript" 241 259 242 260 def test_json_output(self): 243 testutil.create_request("/test?tg_format=json") 244 import simplejson 245 values = simplejson.loads(cherrypy.response.body[0]) 246 assert values == dict(title="Foobar", mybool=False, 247 someval="niggles", tg_flash=None) 248 assert cherrypy.response.headers["Content-Type"] == "text/javascript" 261 response = testutil.go("/test?tg_format=json") 262 values = simplejson.loads(response.body) 263 eq_(values, dict(title="Foobar", mybool=False, 264 someval="niggles", tg_flash=None)) 265 assert response.headers["Content-Type"] == "text/javascript" 249 266 250 267 def test_implied_json(self): 251 testutil.create_request("/impliedjson?tg_format=json")252 assert '"title": "Blah"' in cherrypy.response.body[0]268 response = testutil.go("/impliedjson?tg_format=json") 269 assert '"title": "Blah"' in response.body 253 270 254 271 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" 272 response = testutil.go("/allowjson?tg_format=json", status=500) 273 assert response.headers["Content-Type"] == "text/html", response.headers 258 274 259 275 def test_allow_json_config(self): 260 276 """JSON output can be enabled via config.""" … … 264 280 def allowjsonconfig(self): 265 281 return dict(title="Foobar", mybool=False, someval="foo", 266 282 tg_html="turbogears.tests.simple") 267 cherrypy.root = JSONRoot()268 testutil.create_request('/allowjsonconfig?tg_format=json')269 assert cherrypy.response.headers["Content-Type"] =="text/javascript"270 config.update({'tg.allow_json': False})283 testutil.mount(JSONRoot()) 284 response = testutil.go('/allowjsonconfig?tg_format=json') 285 assert response.headers["Content-Type"]=="text/javascript" 286 config.update({'tg.allow_json':False}) 271 287 272 288 def test_allow_json_config_false(self): 273 289 """Make sure JSON can still be restricted with a global config on.""" … … 277 293 def allowjsonconfig(self): 278 294 return dict(title="Foobar", mybool=False, someval="foo", 279 295 tg_html="turbogears.tests.simple") 280 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" 296 testutil.mount(JSONRoot()) 297 response = testutil.go('/allowjson?tg_format=json', status=404) 298 assert response.headers["Content-Type"]=="text/html" 284 299 config.update({'tg.allow_json': False}) 285 300 286 301 def test_json_error(self): 287 302 """The error handler should return JSON if requested.""" 288 testutil.create_request("/jsonerror")289 assert cherrypy.response.headers["Content-Type"] == "text/html; charset=utf-8"290 assert "Paging all errors" in cherrypy.response.body[0]291 testutil.create_request("/jsonerror?tg_format=json")292 assert cherrypy.response.headers["Content-Type"] == "text/javascript"293 assert '"someval": "errors"' in cherrypy.response.body[0]303 response = testutil.go("/jsonerror") 304 assert response.headers["Content-Type"] == "text/html; charset=utf-8" 305 assert "Paging all errors" in response 306 response = testutil.go("/jsonerror?tg_format=json") 307 assert response.headers["Content-Type"] == "text/javascript" 308 assert '"someval": "errors"' in response 294 309 295 310 def test_invalid_return(self): 296 testutil.create_request("/invalid") 297 assert cherrypy.response.status.startswith("500") 311 response = testutil.go("/invalid", status=500) 298 312 299 313 def test_strict_parameters(self): 300 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") 304 assert not hasattr(cherrypy.root, "errors") 314 config.update({"tg.strict_parameters" : True}) 315 response = testutil.go( 316 "/save?submit=save&firstname=Foo&lastname=Bar&badparam=1", 317 status = 500) 305 318 306 319 def test_throw_out_random(self): 307 320 """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]321 response = testutil.go("/test?tg_random=1") 322 assert "Paging all niggles" in response 310 323 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") 316 assert not hasattr(cherrypy.root, "errors") 324 response = testutil.go("/test?tg_random=1", status=200) 325 assert "Paging all niggles" in response 326 response = testutil.go("/test?tg_not_random=1", status=500) 317 327 318 328 def test_ignore_parameters(self): 319 329 config.update({"tg.strict_parameters": True}) 320 testutil.create_request("/test?ignore_me=1") 321 assert cherrypy.response.status.startswith("500") 322 assert not hasattr(cherrypy.root, "errors") 330 response = testutil.go("/test?ignore_me=1", status=500) 323 331 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") 331 assert not hasattr(cherrypy.root, "errors") 332 response = testutil.go("/test?ignore_me=1") 333 assert "Paging all niggles" in response 334 response = testutil.go("/test?me_too=1", status=200) 335 assert "Paging all niggles" in response 336 testutil.go("/test?me_not=1", status=500) 337 assert not response.raw.has_key('errors') 332 338 333 339 def test_retrieve_dict_directly(self): 334 d = testutil. call(cherrypy.root.returnjson)335 assert d ["title"] == "Foobar"340 d = testutil.go("/returnjson") 341 assert d.raw['title'] == "Foobar" 336 342 337 343 def test_templateOutput(self): 338 testutil.create_request("/test")339 assert "Paging all niggles" in cherrypy.response.body[0]344 response = testutil.go("/test") 345 assert "Paging all niggles" in response 340 346 347 def test_throw_out_random(self): 348 """A random value can be appended to the URL to avoid caching 349 problems.""" 350 response = testutil.go("/test?tg_random=1") 351 assert "Paging all niggles" in response 352 341 353 def test_safari_unicode_fix(self): 342 testutil.create_request("/unicode", headers={'User-Agent':343 "Apple WebKit Safari/412.2"} )344 firstline = cherrypy.response.body[0].split('\n')[0]354 response = go("/unicode", headers={'User-Agent' : 355 "Apple WebKit Safari/412.2"}, status='*') 356 firstline = response.body.split('\n')[0] 345 357 assert firstline == "¿Habla español?" 346 358 assert isinstance(firstline, str) 347 359 348 360 def test_default_format(self): 349 361 """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 362 response = testutil.go("/returnjson") 363 assert '"title": "Foobar"' in response 364 response = testutil.go("/returnjson?tg_format=html", status=500) 365 assert '"title": "Foobar"' not in response 357 366 358 367 def test_content_type(self): 359 368 """The content-type can be set via expose""" 360 testutil.create_request("/contenttype")361 assert cherrypy.response.headers["Content-Type"] == "xml/atom"369 response = testutil.go("/contenttype") 370 assert response.headers["Content-Type"] == "xml/atom" 362 371 363 372 def test_returned_template_name(self): 364 testutil.create_request("/returnedtemplate")365 data = cherrypy.response.body[0].lower()373 response = testutil.go("/returnedtemplate") 374 data = response.body.lower() 366 375 assert "<body>" in data 367 376 assert 'groovy test template' in data 368 377 369 378 def test_returned_template_short(self): 370 testutil.create_request("/returnedtemplate_short")371 assert "Paging all foo" in cherrypy.response.body[0]379 response = testutil.go("/returnedtemplate_short") 380 assert "Paging all foo" in response 372 381 373 382 def test_expose_template_short(self): 374 testutil.create_request("/exposetemplate_short")375 assert "Paging all foo" in cherrypy.response.body[0]383 response = testutil.go("/exposetemplate_short") 384 assert "Paging all foo" in response 376 385 377 386 def test_validation(self): 378 387 """Data can be converted and validated""" 379 testutil.create_request("/istrue?value=true") 380 assert cherrypy.root.value is True 381 testutil.create_request("/istrue?value=false") 382 assert cherrypy.root.value is False 383 cherrypy.root = MyRoot() 384 testutil.create_request("/istrue?value=foo") 385 assert not hasattr(cherrypy.root, "value") 386 assert cherrypy.root.functionname == "istrue" 387 testutil.create_request("/save?submit=send&firstname=John&lastname=Doe") 388 assert cherrypy.root.fullname == "John Doe" 389 assert cherrypy.root.submit == "send" 390 testutil.create_request("/save?submit=send&firstname=Arthur") 391 assert cherrypy.root.fullname == "Arthur Miller" 392 testutil.create_request("/save?submit=send&firstname=Arthur&lastname=") 393 assert cherrypy.root.fullname == "Arthur " 394 testutil.create_request("/save?submit=send&firstname=D&lastname=") 395 assert len(cherrypy.root.errors) == 1 396 assert cherrypy.root.errors.has_key("firstname") 397 assert "characters" in cherrypy.root.errors["firstname"].msg.lower() 398 testutil.create_request("/save?submit=send&firstname=&lastname=") 399 assert len(cherrypy.root.errors) == 1 400 assert cherrypy.root.errors.has_key("firstname") 388 response = testutil.go("/istrue?value=true") 389 assert response.raw['value'] == 'True' 390 response = testutil.go("/istrue?value=false") 391 assert response.raw['value'] == 'False' 392 testutil.start_server(root = MyRoot()) 393 response = testutil.go("/istrue?value=foo") 394 assert not response.raw.has_key('value') 401 395 396 response = testutil.go("/save?submit=send&firstname=John&lastname=Doe") 397 assert response.raw['fullname'] == "John Doe" 398 assert response.raw['submit'] == "send" 399 response = testutil.go("/save?submit=send&firstname=Arthur") 400 assert response.raw['fullname'] == "Arthur Miller" 401 response = testutil.go("/save?submit=send&firstname=Arthur&lastname=") 402 assert response.raw['fullname'] == "Arthur " 403 response = testutil.go("/save?submit=send&firstname=D&lastname=") 404 assert len(response.raw['errors'].keys()) == 1 405 assert response.raw['errors'].has_key("firstname") 406 assert "characters" in response.raw['errors']["firstname"].lower() 407 response = testutil.go("/save?submit=send&firstname=&lastname=") 408 assert len(response.raw['errors'].keys()) == 1 409 assert response.raw['errors'].has_key("firstname") 410 402 411 def test_validation_chained(self): 403 412 """Validation is not repeated if it already happened""" 404 cherrypy.root.value = None 405 testutil.create_request("/errorchain?value=true") 406 assert cherrypy.root.value is None 407 testutil.create_request("/errorchain?value=notbool") 408 assert cherrypy.root.value == 'notbool' 413 response = testutil.go("/errorchain?value=true") 414 assert not hasattr(response, 'raw') 415 response = testutil.go("/errorchain?value=notbool") 416 assert response.raw['value'] == 'notbool' 409 417 410 418 def test_validation_nested(self): 411 419 """Validation is not repeated in nested method call""" 412 cherrypy.root.value = None 413 testutil.create_request("/nestedcall?value=true") 414 assert cherrypy.root.value == 'True' 415 testutil.create_request("/nestedcall?value=false") 416 assert cherrypy.root.value == 'False' 420 response = testutil.go("/nestedcall?value=true") 421 assert response.raw['value'] == 'True' 422 response = testutil.go("/nestedcall?value=false") 423 assert response.raw['value'] == 'False' 417 424 418 425 def test_validation_with_schema(self): 419 """Data can be converted /validated with formencode.Schema instance"""420 testutil.create_request("/save2?submit=send&firstname=Joe&lastname=Doe")421 assert cherrypy.root.fullname== "Joe Doe"422 assert cherrypy.root.submit== "send"423 testutil.create_request("/save2?submit=send&firstname=Arthur&lastname=")424 assert cherrypy.root.fullname== "Arthur "425 testutil.create_request("/save2?submit=send&firstname=&lastname=")426 assert len( cherrypy.root.errors) == 1427 assert cherrypy.root.errors.has_key("firstname")428 testutil.create_request("/save2?submit=send&firstname=D&lastname=")429 assert len( cherrypy.root.errors) == 1430 assert cherrypy.root.errors.has_key("firstname")426 """Data can be converted and validated with formencode.Schema instance""" 427 response = testutil.go("/save2?submit=send&firstname=Joe&lastname=Doe") 428 assert response.raw['fullname'] == "Joe Doe" 429 assert response.raw['submit'] == "send" 430 response = testutil.go("/save2?submit=send&firstname=Arthur&lastname=") 431 assert response.raw['fullname'] == "Arthur " 432 response = testutil.go("/save2?submit=send&firstname=&lastname=") 433 assert len(response.raw['errors'].keys()) == 1 434 assert response.raw['errors'].has_key("firstname") 435 response = testutil.go("/save2?submit=send&firstname=D&lastname=") 436 assert len(response.raw['errors'].keys()) == 1 437 assert response.raw['errors'].has_key("firstname") 431 438 432 439 def test_other_template(self): 433 440 """'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]441 response = testutil.go("/useother") 442 assert "This is the other template" in response 436 443 437 444 def test_cheetah_template(self): 438 445 """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 446 response = testutil.go("/usecheetah") 447 assert "This is the Cheetah test template." in response 448 assert "Paging all chimps." in response 443 449 444 450 def test_run_with_trans(self): 445 451 """run_with_transaction is called only on topmost exposed method""" 446 452 oldrwt = database.run_with_transaction 447 453 database.run_with_transaction = cherrypy.root.rwt 448 testutil.create_request("/nestedcall?value=true")454 response = testutil.go("/nestedcall?value=true") 449 455 database.run_with_transaction = oldrwt 450 assert cherrypy.root.value451 assert cherrypy.root.rwt_called == 1456 assert response.raw['value'] 457 assert 'rwt_called = 1' in response 452 458 453 459 def test_positional(self): 454 460 """Positional parameters should work""" 455 testutil.create_request("/pos/foo")456 assert cherrypy.root.posvalue== "foo"461 response = testutil.go("/pos/foo") 462 assert response.raw['posvalue'] == "foo" 457 463 458 464 def test_flash_plain(self): 459 465 """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]) 466 response = testutil.go("/flash_plain?tg_format=json") 467 values = simplejson.loads(response.body) 463 468 assert values["tg_flash"] == "plain" 464 assert not cherrypy.response.simple_cookie.has_key("tg_flash")469 assert not response.cookies_set.has_key("tg_flash") 465 470 466 471 def test_flash_unicode(self): 467 472 """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]) 473 response = testutil.go("/flash_unicode?tg_format=json") 474 values = simplejson.loads(response.body) 471 475 assert values["tg_flash"] == u"\xfcnicode" 472 assert not cherrypy.response.simple_cookie.has_key("tg_flash")476 assert not response.cookies_set.has_key("tg_flash") 473 477 474 478 def test_flash_on_redirect(self): 475 479 """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]) 480 response = go("/flash_redirect?tg_format=json", status=302) 481 response = go(response.location, 482 headers = dict(Cookie=response.headers["Set-Cookie"])) 483 values = simplejson.loads(response.body) 483 484 assert values["tg_flash"] == u"redirect \xfcnicode" 484 485 485 486 def test_flash_redirect_with_trouble_chars(self): 486 487 """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]) 488 response = go("/flash_redirect_with_trouble_chars?tg_format=json", status=302) 489 response = go(response.location, 490 headers=dict(Cookie=response.headers["Set-Cookie"])) 491 values = simplejson.loads(response.body) 501 492 assert values["tg_flash"] == u"$foo, k\xe4se;\tbar!" 502 493 503 494 def test_double_flash(self): … … 505 496 # Here we are calling method that sets a flash message. However flash 506 497 # cookie is still there. Turbogears should discard old flash message 507 498 # from cookie and use new one, set by flash_plain(). 508 testutil.create_request("/flash_plain?tg_format=json", 509 headers=dict(Cookie='tg_flash="old flash"; Path=/;')) 510 import simplejson 511 values = simplejson.loads(cherrypy.response.body[0]) 499 response = go("/flash_plain?tg_format=json", 500 headers= {'Cookie':'tg_flash="old flash"; Path=/;'}) 501 values = simplejson.loads(response.body) 512 502 assert values["tg_flash"] == "plain" 513 assert cherrypy.response.simple_cookie.has_key("tg_flash"), \503 assert response.cookies_set.has_key("tg_flash"), \ 514 504 "Cookie clearing request should be present" 515 flashcookie = cherrypy.response.simple_cookie['tg_flash'] 516 assert flashcookie['expires'] == 0 505 eq_(response.cookies_set['tg_flash'], "") 517 506 518 507 def test_set_kid_outputformat_in_config(self): 519 508 """the outputformat for kid can be set in the config""" 520 509 config.update({'kid.outputformat': 'xhtml'}) 521 testutil.create_request('/test') 522 response = cherrypy.response.body[0] 510 response = testutil.go('/test') 523 511 assert '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML ' in response 524 512 config.update({'kid.outputformat': 'html'}) 525 testutil.create_request('/test') 526 response = cherrypy.response.body[0] 513 response = testutil.go('/test') 527 514 assert '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML ' in response 528 515 assert ' This is the groovy test ' in response 529 516 config.update({'kid.outputformat': 'html compact'}) 530 testutil.create_request('/test') 531 response = cherrypy.response.body[0] 517 response = testutil.go('/test') 532 518 assert '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML ' in response 533 519 assert 'This is the groovy test ' in response 534 520 assert ' ' not in response 535 521 536 522 def test_fileserving(self): 537 #outputcap = StringIO() 538 #sys.stdout = outputcap 539 testutil.create_request("/servefile") 540 assert cherrypy.root.servedit 541 assert not cherrypy.root.serve_exceptions 542 #assert "AssertionError" not in outputcap.getvalue() 523 response = testutil.go("/servefile") 524 assert "test_fileserving" in response 543 525 544 526 def test_internal_redirect(self): 545 527 """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 528 response = testutil.go("/internal_redirect") 529 assert "redirected OK" in response 549 530 550 531 def test_internal_redirect_nested_variables(self): 551 532 """regression test for #1022, #1407 and #1598""" 552 testutil.create_request(533 response = testutil.go( 553 534 "/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 535 assert "redirected OK" in response 556 536 557 537 def test_exc_value(self): 558 538 """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]539 response = testutil.go("/raise_value_exc") 540 assert 'handling_value' in response 561 541 562 542 def test_exc_index(self): 563 543 """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]544 response = testutil.go("/raise_index_exc") 545 assert 'handling_index' in response 566 546 567 547 def test_exc_all(self): 568 548 """Test a controller that is protected by multiple exception handlers. … … 571 551 by their respective handlers without problem... 572 552 573 553 """ 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]554 response = testutil.go("/raise_all_exc?num=1") 555 assert 'handling_value' in response 556 response = testutil.go("/raise_all_exc?num=2") 557 assert 'handling_index' in response 558 response = testutil.go("/raise_all_exc?num=3") 559 assert 'handling_key' in response 580 560 581 561 582 562 class TestURLs(unittest.TestCase): 583 563 584 564 def setUp(self): 585 cherrypy.tree.mount_points = {} 586 cherrypy.root = MyRoot() 587 cherrypy.root.subthing = SubApp() 588 cherrypy.root.subthing.subsubthing = SubApp() 565 testutil.mount(MyRoot()) 566 testutil.mount(SubApp(), '/subthing') 567 testutil.mount(SubApp(), '/subthing/subsubthing') 589 568 590 569 def test_basic_urls(self): 591 testutil. create_request("/")570 testutil.go("/") 592 571 assert "/foo" == url("/foo") 593 572 assert "foo/bar" == url(["foo", "bar"]) 594 573 assert url("/foo", bar=1, baz=2) in \ … … 602 581 assert url("/foo") == "/foo" 603 582 604 583 def test_approots(self): 605 testutil.create_request("/subthing/") 606 assert url("foo") == "foo" 607 assert url("/foo") == "/subthing/foo" 584 response = testutil.go("/subthing/foo") 585 self.failUnlessEqual("foo", response.body) 586 587 response = testutil.go("/subthing/foo2") 588 self.failUnlessEqual("/subthing/foo", response.body) 608 589 609 590 def test_lower_approots(self): 610 testutil.create_request("/subthing/subsubthing/") 611 assert url("/foo") == "/subthing/subsubthing/foo" 591 config.update({"server.webpath" : "/XXX"}) 592 response = testutil.go("/subthing/subsubthing/") 593 eq_("/XXX/subthing/subsubthing/Foo/", response.body) 612 594 613 def test_approots_ With_path(self):614 config.update({"server.webpath" : "/coolsite/root"})615 startup.startTurboGears()616 testutil.create_request("/coolsite/root/subthing/")617 assert url("/foo") == "/coolsite/root/subthing/foo"595 def test_approots_with_path(self): 596 config.update({"server.webpath" : "/coolsite/root"}) 597 testutil.start_server() 598 response = testutil.go("/coolsite/root/subthing/") 599 self.failUnlessEqual("/coolsite/root/subthing/Foo/", response.body) 618 600 619 601 def test_redirect(self): 620 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 602 config.update({"server.webpath" : "/coolsite/root"}) 603 testutil.start_server() 604 response = go("/coolsite/root/subthing/redir") 605 eq_(response.location, 'http://localhost:80/coolsite/root/subthing/foo') 633 606 607 response = go("/coolsite/root/subthing/redir2") 608 eq_(response.location, 'http://localhost:80/coolsite/root/subthing/foo') 609 634 610 def test_multi_values(self): 635 testutil. create_request("/")611 testutil.go("/") 636 612 assert url("/foo", bar=[1, 2]) in \ 637 613 ["/foo?bar=1&bar=2", "/foo?bar=2&bar=1"] 638 614 assert url("/foo", bar=("asdf", "qwer")) in \ … … 640 616 641 617 def test_unicode(self): 642 618 """url() can handle unicode parameters""" 643 testutil. create_request("/")619 testutil.go("/") 644 620 assert url('/', x=u'\N{LATIN SMALL LETTER A WITH GRAVE}' 645 621 u'\N{LATIN SMALL LETTER E WITH GRAVE}' 646 622 u'\N{LATIN SMALL LETTER I WITH GRAVE}' … … 650 626 651 627 def test_list(self): 652 628 """url() can handle list parameters, with unicode too""" 653 testutil. create_request("/")629 testutil.go("/") 654 630 assert url('/', foo=['bar', u'\N{LATIN SMALL LETTER A WITH GRAVE}'] 655 631 ) == '/?foo=bar&foo=%C3%A0' 656 632 657 633 def tearDown(self): 658 634 config.update({"server.webpath": ""}) 659 startup.startTurboGears()635 testutil.start_server() 660 636 661 637 662 638 def test_index_trailing_slash(): 663 639 """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")640 testutil.mount(SubApp()) 641 testutil.mount(SubApp(), '/noslash') 642 response = testutil.go("/noslash") 643 assert response.status.startswith("302") 668 644 645 669 646 def test_can_use_internally_defined_arguments(): 670 647 """Can use argument names that are internally used by TG in controllers""" 671 648 … … 675 652 def index(self, **kw): 676 653 return "\n".join(["%s:%s" % i for i in kw.iteritems()]) 677 654 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 655 testutil.mount(App()) 656 response = testutil.go("/?format=foo&template=bar&fragment=boo") 657 assert "format:foo" in response 658 assert "template:bar" in response 659 assert "fragment:boo" in response 684 660 685 661 def test_url_kwargs_overwrite_tgparams(): 686 662 """Check keys in tgparams in call to url overwrite kw args""" -
turbogears/tests/test_view.py
1 1 # -*- coding: utf-8 -*- 2 3 2 from turbogears import view, config, testutil 4 3 import cherrypy 5 4 import unittest … … 7 6 class TestView(unittest.TestCase): 8 7 9 8 def setUp(self): 10 testutil.start_ cp()9 testutil.start_server() 11 10 cherrypy.serving.request = testutil.DummyRequest() 12 11 cherrypy.serving.response = testutil.DummyResponse() 13 12 -
turbogears/tests/test_testutil.py
21 21 22 22 23 23 def test_browser_session(): 24 cherrypy.root = MyRoot() 24 testutil.stop_server() 25 testutil.start_server(MyRoot()) 25 26 bs = testutil.BrowsingSession() 26 27 bs.goto('/get_name') 27 28 assert bs.response == 'cookie not found' … … 30 31 assert bs.response == 'me' 31 32 32 33 def test_browser_session_for_two_users(): 33 cherrypy.root = MyRoot() 34 testutil.stop_server() 35 testutil.start_server(MyRoot()) 34 36 bs1 = testutil.BrowsingSession() 35 37 bs2 = testutil.BrowsingSession() 36 38 bs1.goto('/set_name?name=bs1') -
turbogears/tests/test_catwalk.py
3 3 from turbogears import testutil 4 4 from turbogears import controllers 5 5 from turbogears.toolbox.catwalk import CatWalk 6 import cherrypy7 6 import simplejson 8 7 from catwalk_models import browse 9 8 import timeit … … 43 42 class Browse(unittest.TestCase): 44 43 def setUp(self): 45 44 browse_data(browse) 46 cherrypy.root = MyRoot() 45 testutil.start_server() 46 testutil.mount(MyRoot(), "/") 47 testutil.mount(CatWalk(browse), '/catwalk') 47 48 49 def tearDown(self): 50 testutil.stop_server() 51 48 52 def test_wrong_filter_format(self): 49 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] 53 response = testutil.go("/catwalk/browse/?object_name=Song&filters=Guantanemera&tg_format=json") 52 54 assert 'filter_format_error' in response 53 55 54 56 def test_wrong_filter_column(self): 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] 57 response = testutil.go("/catwalk/browse/?object_name=Song&filters=guacamole:2&tg_format=json") 58 58 assert 'filter_column_error' in response 59 59 60 60 def test_filters(self): 61 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 = testutil.go("/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 = testutil.go("/catwalk/browse/?object_name=Song&filters=album:1&tg_format=json") 65 #values = simplejson.loads(response.body) 66 response.headers['Content-Type'] = 'application/json' 67 values = response.json 69 68 assert values['total'] == 15 #filter by album id (only 15 songs) 70 69 71 70 def test_response_fields(self): 72 71 #Check that the response contains the expected keys 73 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) 72 response = testutil.go("/catwalk/browse/?object_name=Artist&start=3&page_size=20&tg_format=json") 73 values = simplejson.loads(response.body) 77 74 assert values.has_key('headers') 78 75 assert values.has_key('rows') 79 76 assert values.has_key('start') … … 86 83 def test_rows_joins_count(self): 87 84 #Control that the count for related and multiple joins match 88 85 #the number of related instances when accessed as a field 89 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 = testutil.go("/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)) 96 91 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 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) 94 response = testutil.go("/catwalk/browse/?object_name=Artist&tg_format=json") 95 values = simplejson.loads(response.body) 103 96 assert len(values['rows'][0]) == 4 104 97 105 98 def test_rows_limit(self): 106 99 #Update the limit of rows for the query and control the number of rows returned 107 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) 100 response = testutil.go("/catwalk/browse/?object_name=Artist&tg_format=json") 101 values = simplejson.loads(response.body) 111 102 assert values.has_key('rows') 112 103 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 )104 105 response = testutil.go("/catwalk/browse/?object_name=Artist&page_size=15&tg_format=json") 106 values = simplejson.loads(response.body) 116 107 assert values.has_key('rows') 117 108 assert len(values['rows']) == 15 118 109 119 110 def test_header_labels(self): 120 111 #Check that the returned header labels match the the model 121 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) 112 response = testutil.go("/catwalk/browse/?object_name=Artist&tg_format=json") 113 values = simplejson.loads(response.body) 125 114 assert len(values['headers']) == 5 126 115 for header in values['headers']: 127 116 assert header['name'] in ['id','name','albums','genres', 'plays_instruments'] … … 131 120 model = browse 132 121 133 122 def setUp(self): 134 cherrypy.root = MyRoot() 135 cherrypy.root.catwalk = CatWalk(browse) 123 testutil.start_server() 124 testutil.mount(MyRoot(), "/") 125 testutil.mount(CatWalk(browse), '/catwalk') 136 126 testutil.DBTest.setUp(self) 137 127 browse_data(browse) 138 128 129 def tearDown(self): 130 testutil.stop_server() 131 testutil.DBTest.tearDown(self) 132 139 133 def test_addremove_related_joins(self): 140 134 # check the update_join function when nondefault add/remove are used 141 135 artist = self.model.Artist.get(1) 142 136 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")137 testutil.go("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1%2C2&tg_format=json") 144 138 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")139 testutil.go("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1&tg_format=json") 146 140 assert len(artist.plays_instruments) == 1, str(artist.plays_instruments) -
turbogears/tests/test_paginate.py
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 go, sqlalchemy_cleanup, start_server 12 12 from turbojson.jsonify import jsonify 13 13 14 14 import cherrypy … … 218 218 219 219 220 220 def setUp(self): 221 cherrypy.root = self.MyRoot()221 start_server(self.MyRoot()) 222 222 223 223 def test_spy(self): 224 create_request('/spy') 225 body = cherrypy.response.body[0] 226 Spy.assert_ok(body, 'current_page', 1) 224 response = go('/spy') 225 Spy.assert_ok(response, 'current_page', 1) 227 226 try: 228 Spy.assert_ok( body, 'current_page', 2)227 Spy.assert_ok(response, 'current_page', 2) 229 228 raise Exception("above test should have failed") 230 229 except AssertionError: 231 230 pass 232 231 233 232 def test_correct_expectation(self): 234 create_request('/spy_correct_expectation') 235 body = cherrypy.response.body[0] 236 assert "ok: [paginate" in body 233 response = go('/spy_correct_expectation') 234 assert "ok: [paginate" in response 237 235 238 236 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 237 response = go('/spy_wrong_expectation') 238 assert "fail: expected page_count=9, got page_count=10" in response 242 239 243 240 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 241 response = go('/spy_invalid_expectation') 242 assert "fail: paginate does not have 'foobar' attribute" in response 247 243 248 244 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)245 response = go('/spy_correct_expectation') 246 Spy.assert_ok(response, 'var_name', 'data') 247 Spy.assert_ok(response, 'var_name', "'data'", raw=True) 252 248 253 249 254 250 class TestPagination(unittest.TestCase): 255 251 """Base class for all Paginate TestCases""" 256 252 257 def request(self, url): 258 create_request(url) 259 self.body = cherrypy.response.body[0] 253 def request(self, url, status=None): 254 self.body = go(url, status=status).body 260 255 if "fail: " in self.body: 261 256 print self.body 262 assert False, "Spy alert! Check bodyoutput for details..."257 assert False, "Spy alert! Check response output for details..." 263 258 264 259 265 260 class TestBasicPagination(TestPagination): … … 343 338 344 339 345 340 def setUp(self): 346 cherrypy.root = self.MyRoot()341 start_server(root = self.MyRoot()) 347 342 348 343 def test_pagination_old_style(self): 349 344 self.request("/basic") … … 439 434 Spy.assert_ok(self.body, 'pages', xrange(4, 8)) 440 435 441 436 def test_invalid_dynamic_limit(self): 442 self.request("/invalid_dynamic") 443 assert cherrypy.response.status.startswith("500") 437 self.request("/invalid_dynamic", status=500) 444 438 assert 'paginate: dynamic_limit (foobar) not found in output dict' in self.body 445 439 446 440 def test_dynamic_limit(self): … … 754 748 755 749 756 750 def setUp(self): 757 cherrypy.root = self.MyRoot()751 start_server(root = self.MyRoot()) 758 752 759 753 def assert_order(self, *args): 760 754 expr = 'data="%s"' % ''.join(['[Address %r]' % x for x in args]) … … 826 820 827 821 def test_invalid_default_reversed(self): 828 822 for method in "Q", "QA", "SR", "SO", "SL": 829 self.request("/wrong_reversed/?method=%s" % method) 830 assert cherrypy.response.status.startswith("500") 823 self.request("/wrong_reversed/?method=%s" % method, status=500) 831 824 assert ('paginate: default_reversed (deprecated) only allowed' 832 825 ' when default_order is a basestring') in self.body 833 826 -
turbogears/qstemplates/quickstart/+package+/tests/test_controllers.py_tmpl
4 4 from ${package}.controllers import Root 5 5 import cherrypy 6 6 7 cherrypy.root = Root()7 testutil.mount(root = Root()) 8 8 9 9 class TestPages(unittest.TestCase): 10 10 11 11 def setUp(self): 12 t urbogears.startup.startTurboGears()12 testutil.start_server() 13 13 14 14 def tearDown(self): 15 15 """Tests for apps using identity need to stop CP/TG after each test to 16 16 stop the VisitManager thread. 17 17 See http://trac.turbogears.org/turbogears/ticket/1217 for details. 18 18 """ 19 t urbogears.startup.stopTurboGears()19 testutil.stop_server() 20 20 21 21 def test_method(self): 22 22 "the index method should return a string called now" 23 23 import types 24 res ult = testutil.call(cherrypy.root.index)25 assert type(res ult["now"]) == types.StringType24 response = testutil.go("/") 25 assert type(response.raw["now"]) == types.StringType 26 26 27 27 def test_indextitle(self): 28 28 "The indexpage should have the right title" 29 testutil.create_request("/") 30 response = cherrypy.response.body[0].lower() 31 assert "<title>welcome to turbogears</title>" in response 29 response = testutil.go("/") 30 assert "<title>welcome to turbogears</title>" in response.body.lower() 32 31 33 32 #if $identity != "none" 34 33 def test_logintitle(self): 35 34 "login page should have the right title" 36 testutil.create_request("/login") 37 response = cherrypy.response.body[0].lower() 38 assert "<title>login</title>" in response 35 response = testutil.go("/login") 36 assert "<title>login</title>" in response.body.lower() 39 37 #end if -
turbogears/testutil.py
4 4 import unittest 5 5 import Cookie 6 6 import cStringIO as StringIO 7 from turbogears.util import deprecated 8 from webtest import TestApp 7 9 8 10 import cherrypy 9 from cherrypy import _cphttptools 11 cherrypy_major_ver = int(cherrypy.__version__.split('.')[0]) 12 if cherrypy_major_ver < 3: 13 from cherrypy._cphttptools import Request, Response 14 else: 15 from cherrypy import Request, Response 10 16 11 17 try: 12 18 import sqlobject … … 50 56 config.update({'global': 51 57 {'autoreload.on': False, 'tg.new_style_logging': True}}) 52 58 59 def unmount(): 60 """Remove an application from the object traversal tree.""" 61 # There's no clean way to remove a subtree under CP2, so the only use case 62 # handled here is to remove the entire application. 63 # Supposedly, you can do a partial unmount with CP3 using: 64 # del cherrypy.tree.apps[path] 65 cherrypy.root = None 66 cherrypy.tree.mount_points = {} 53 67 54 def start_cp(): 55 if not config.get("cherrypy_started", False): 56 cherrypy.server.start(serverClass=None, initOnly=True) 57 config.update({"cherrypy_started" : True}) 68 def mount(app, path="/"): 69 """Mount an app at a path. Returns True if the server needs 70 to be restarted afterwards. 71 """ 72 current = cherrypy.tree.mount_points.get(path, None) 73 if current != app: 74 #Only mount the app if it's not already mounted 75 if current != None: 76 #If there's something else mounted at this path already, we'll 77 # have to unmount it first. CherryPy can't handle dynamic 78 # remounting. 79 unmount() 80 cherrypy.tree.mount(app, path) 81 if path == '/': 82 cherrypy.root = app 83 return get_app() 58 84 85 def start_server(root=None): 86 """Start the server if it's not already. Optionally mount an app first.""" 87 if root: 88 mount(root) 89 if not config.get("server_started"): 90 if cherrypy_major_ver < 3: 91 cherrypy.server.start(serverClass=None, initOnly=True) 92 else: 93 cherrypy.server.quickstart() 94 cherrypy.engine.start() 95 startup.startTurboGears() 96 config.update({"server_started" : True}) 59 97 98 start_cp = deprecated("start_cp has been superceded by start_server.") \ 99 (start_server) 100 101 102 def stop_server(): 103 if config.get("server_started", True): 104 startup.stopTurboGears() 105 config.update({"server_started" : False}) 106 unmount() 107 return 108 60 109 test_user = None 61 110 111 @deprecated() 62 112 def set_identity_user(user): 63 113 """Setup a user for configuring request's identity.""" 64 114 global test_user 65 115 test_user = user 66 116 67 117 118 @deprecated() 68 119 def attach_identity(req): 69 120 if config.get("identity.on", False): 70 121 req.identity = (test_user … … 72 123 or current_provider.anonymous_identity()) 73 124 74 125 126 @deprecated("Use testutil.go instead of create_request") 75 127 def create_request(request, method="GET", protocol="HTTP/1.1", 76 128 headers={}, rfile=None, clientAddress="127.0.0.1", 77 129 remoteHost="localhost", scheme="http"): 78 start_ cp()130 start_server() 79 131 if not rfile: 80 132 rfile = StringIO.StringIO("") 81 133 if type(headers) != dict: … … 86 138 if not hasattr(cherrypy.root, "started"): 87 139 startup.startTurboGears() 88 140 cherrypy.root.started = True 89 req = _cphttptools.Request(clientAddress, 80, remoteHost, scheme)141 req = Request(clientAddress, 80, remoteHost, scheme) 90 142 cherrypy.serving.request = req 91 143 attach_identity(req) 92 cherrypy.serving.response = _cphttptools.Response()144 cherrypy.serving.response = Response() 93 145 req.run(" ".join((method, request, protocol)), headerList, rfile) 146 return cherrypy.serving.response 94 147 148 createRequest = create_request 95 149 150 151 def get_app(): 152 """Return a WSGI application from cherrypy's root object.""" 153 if cherrypy_major_ver < 3: 154 app = cherrypy._cpwsgi.wsgiApp 155 else: 156 app = cherrypy.tree.mount(cherrypy.root, '/') 157 # app = cherrypy.wsgi.CPWSGIServer 158 return app 159 160 161 def go(request, headers={}, cookies={}, status=None): 162 """Visit a site with WebTest, returning the response.""" 163 start_server() 164 app = TestApp(get_app()) 165 response = app.get(request, headers=headers, status=status) 166 response.app = app 167 return response 168 169 96 170 class BrowsingSession(object): 97 171 98 172 def __init__(self): … … 103 177 def goto(self, *args, **kwargs): 104 178 if self.cookie: 105 179 headers = kwargs.setdefault('headers', {}) 106 headers['Cookie'] = self.cookie .output()107 create_request(*args, **kwargs)108 self.response = cherrypy.response.body[0]109 self.status = cherrypy.response.status110 if cherrypy.response.simple_cookie:111 self.cookie.update(cherrypy.response.simple_cookie)180 headers['Cookie'] = self.cookie_encoded 181 response = go(*args, **kwargs) 182 self.response = response.body 183 self.status = response.status 184 self.cookie = response.cookies_set 185 self.cookie_encoded = response.headers.get('Set-Cookie', '') 112 186 113 187 114 188 def _return_directly(output, *args): … … 140 214 class DummyResponse: 141 215 """A very simple dummy response.""" 142 216 headers = {} 217 143 218 144 219 @deprecated("Use testutil.go instead of call") 145 220 def call(method, *args, **kw): 146 start_ cp()221 start_server() 147 222 output, response = call_with_request(method, DummyRequest(), *args, **kw) 148 223 return output 149 224 150 225 226 @deprecated("Use testutil.go instead of call_with_request") 151 227 def call_with_request(method, request, *args, **kw): 152 228 """More fine-grained version of call method. 153 229 … … 156 232 """ 157 233 orig_proc_output = controllers._process_output 158 234 controllers._process_output = _return_directly 159 cherrypy.serving.response = _cphttptools.Response()235 cherrypy.serving.response = Response() 160 236 cherrypy.serving.request = request 161 237 if not hasattr(request, "identity"): 162 238 attach_identity(request) … … 201 277 item.dropTable(ifExists=True) 202 278 203 279 204 def reset_cp():205 cherrypy.root = None206 207 208 280 def catch_validation_errors(widget, value): 209 281 """Catch and unpack validation errors (for testing purposes).""" 210 282 try: … … 253 325 254 326 """ 255 327 global _currentcat 256 assert not _currentcat 328 assert not _currentcat, "_currentcat not cleared. Use print_log to reset." 257 329 if not isinstance(category, list) and not isinstance(category, tuple): 258 330 category = [category] 259 331 _currentcat = category … … 305 377 sqlalchemy.orm.clear_mappers() 306 378 307 379 308 __all__ = ["call", "create_request", "DBTest", 309 "attach_identity", "set_identity_user", 310 "capture_log", "print_log", "get_log", "sqlalchemy_cleanup"] 380 __all__ = ["call", "create_request", "DBTest", "attach_identity", 381 "set_identity_user", "capture_log", "print_log", "get_log", 382 "sqlalchemy_cleanup", "mount", "go", "start_server", "stop_server"] 383 -
turbogears/widgets/tests/test_nested_form_controllers.py
1 1 import turbogears 2 import cherrypy3 2 from turbogears import widgets 4 3 from turbogears import controllers 5 4 from turbogears import validators … … 17 16 18 17 class MyRoot(controllers.RootController): 19 18 def testform(self, p_data, tg_errors=None): 20 if tg_errors:21 self.has_errors = True22 self.name = p_data['name']23 self.age = p_data['age']19 has_errors = tg_errors is not None 20 name = p_data['name'] 21 age = p_data['age'] 22 return dict(has_errors = has_errors, name=name, age = age) 24 23 testform = turbogears.validate(form=myform)(testform) 25 testform = turbogears.expose( html="turbogears.tests.othertemplate")(24 testform = turbogears.expose(template="turbogears.tests.othertemplate")( 26 25 testform) 27 26 28 27 def set_errors(self): 29 self.has_errors = True 28 return dict(has_errors = True) 29 30 30 31 31 def testform_new_style(self, p_data): 32 self.name = p_data['name'] 33 self.age = p_data['age'] 32 name = p_data['name'] 33 age = p_data['age'] 34 return dict(name = name, age = age) 34 35 testform_new_style = turbogears.validate(form=myform)(testform_new_style) 35 36 testform_new_style = turbogears.error_handler(set_errors)(testform_new_style) 36 37 testform_new_style = turbogears.expose()(testform_new_style) … … 38 39 39 40 def test_form_translation_new_style(): 40 41 "Form input is translated into properly converted parameters" 41 root = MyRoot() 42 cherrypy.root = root 43 testutil.create_request("/testform_new_style?p_data.name=ed&p_data.age=5") 44 assert root.name == "ed" 45 print root.age 46 assert root.age == 5 42 testutil.mount(MyRoot()) 43 response = testutil.go("/testform_new_style?p_data.name=ed&p_data.age=5") 44 assert response.raw['name'] == "ed" 45 print response.raw['age'] 46 assert response.raw['age'] == 5 47 47 48 48 def test_invalid_form_with_error_handling(): 49 49 "Invalid forms can be handled by the method" 50 root = cherrypy.root51 testutil.create_request("/testform_new_style?p_data.name=ed&p_data.age=edalso")52 assert r oot.has_errors50 testutil.mount(MyRoot()) 51 response = testutil.go("/testform_new_style?p_data.name=ed&p_data.age=edalso") 52 assert response.raw['has_errors'] -
turbogears/widgets/tests/test_datagrid.py
2 2 from turbogears.widgets.datagrid import DataGrid 3 3 4 4 def setup_module(): 5 testutil.start_ cp()5 testutil.start_server() 6 6 7 7 class Foo: 8 8 -
turbogears/widgets/tests/test_link_inclusion.py
1 1 import turbogears 2 import cherrypy3 4 2 from turbogears import widgets, testutil 5 3 6 4 … … 21 19 return dict(form=form) 22 20 test = turbogears.expose(template="turbogears.widgets.tests.form")(test) 23 21 24 cherrypy.root = MyRoot() 25 testutil.create_request("/test") 26 output = cherrypy.response.body[0] 27 assert 'foo.js' in output 28 assert "alert('hello');" in output 29 assert 'foo.css' in output 22 testutil.start_server(root = MyRoot()) 23 response = testutil.go("/test") 24 assert 'foo.js' in response.body 25 assert "alert('hello');" in response.body 26 assert 'foo.css' in response.body 30 27 31 28 32 29 def test_calendardatepicker_js(): … … 37 34 return dict(widget=widgets.CalendarDatePicker(calendar_lang=lang)) 38 35 test = turbogears.expose(template="turbogears.widgets.tests.widget")(test) 39 36 40 cherrypy.root = MyRoot()37 testutil.start_server(root = MyRoot()) 41 38 42 39 # testing default language (en) 43 testutil.create_request("/test") 44 output = cherrypy.response.body[0] 45 assert 'calendar/calendar.js' in output 46 assert 'calendar/calendar-setup.js' in output 47 assert 'calendar/lang/calendar-en.js' in output 40 response = testutil.go("/test") 41 assert 'calendar/calendar.js' in response.body 42 assert 'calendar/calendar-setup.js' in response.body 43 assert 'calendar/lang/calendar-en.js' in response.body 48 44 49 45 # testing non-existing language 50 testutil.create_request("/test",46 response = testutil.go("/test", 51 47 headers={"Accept-Language": "x"}) 52 output = cherrypy.response.body[0] 53 assert 'calendar/lang/calendar-x.js' not in output 54 assert 'calendar/lang/calendar-en.js' in output 48 assert 'calendar/lang/calendar-x.js' not in response.body 49 assert 'calendar/lang/calendar-en.js' in response.body 55 50 56 51 # testing French language 57 testutil.create_request("/test",52 response = testutil.go("/test", 58 53 headers={"Accept-Language": "fr"}) 59 output = cherrypy.response.body[0] 60 assert 'calendar/lang/calendar-fr.js' in output 61 assert 'calendar/lang/calendar-en.js' not in output 62 assert 'charset="utf-8"' in output 54 assert 'calendar/lang/calendar-fr.js' in response.body 55 assert 'calendar/lang/calendar-en.js' not in response.body 56 assert 'charset="utf-8"' in response.body 63 57 64 58 # testing German language with any charset 65 testutil.create_request("/test",59 response = testutil.go("/test", 66 60 headers={"Accept-Language": "de", "Accept-Charset": "*"}) 67 output = cherrypy.response.body[0] 68 assert 'calendar/lang/calendar-de.js' in output 69 assert 'calendar/lang/calendar-en.js' not in output 70 assert 'charset="*"' not in output 61 assert 'calendar/lang/calendar-de.js' in response.body 62 assert 'calendar/lang/calendar-en.js' not in response.body 63 assert 'charset="*"' not in response.body 71 64 72 65 # testing Turkish language with non-existing charset 73 testutil.create_request("/test",66 response = testutil.go("/test", 74 67 headers={"Accept-Language": "tr", "Accept-Charset": "big5"}) 75 output = cherrypy.response.body[0] 76 assert 'calendar/lang/calendar-tr.js' in output 77 assert 'calendar/lang/calendar-en.js' not in output 78 assert 'charset="big5"' not in output 68 assert 'calendar/lang/calendar-tr.js' in response.body 69 assert 'calendar/lang/calendar-en.js' not in response.body 70 assert 'charset="big5"' not in response.body 79 71 80 72 win1254 = 'windows-1254' 81 73 from codecs import lookup … … 85 77 win1254 = 'cp1254' # cannot test name normalization here 86 78 87 79 # testing Turkish language with existing, not normalized charset 88 testutil.create_request("/test",80 response = testutil.go("/test", 89 81 headers={"Accept-Language": "tr", "Accept-Charset": win1254}) 90 output = cherrypy.response.body[0] 91 assert 'calendar/lang/calendar-tr-cp1254.js' in output 92 assert 'calendar/lang/calendar-en.js' not in output 93 assert 'charset="cp1254"' in output 82 assert 'calendar/lang/calendar-tr-cp1254.js' in response.body 83 assert 'calendar/lang/calendar-en.js' not in response.body 84 assert 'charset="cp1254"' in response.body 94 85 95 86 # testing more than one language and charset 96 testutil.create_request("/test", headers={"Accept-Language": "x,tr,de,fr",87 response = testutil.go("/test", headers={"Accept-Language": "x,tr,de,fr", 97 88 "Accept-Charset": "big5,%s,latin-1" % win1254}) 98 output = cherrypy.response.body[0] 99 assert 'calendar/lang/calendar-tr-cp1254.js' in output 100 assert 'calendar/lang/calendar-x.js' not in output 101 assert 'calendar/lang/calendar-en.js' not in output 102 assert 'charset="cp1254"' in output 103 assert 'charset="big5"' not in output 89 assert 'calendar/lang/calendar-tr-cp1254.js' in response.body 90 assert 'calendar/lang/calendar-x.js' not in response.body 91 assert 'calendar/lang/calendar-en.js' not in response.body 92 assert 'charset="cp1254"' in response.body 93 assert 'charset="big5"' not in response.body 104 94 105 95 # testing predetermined language (fr) 106 testutil.create_request("/test?lang=fr",96 response = testutil.go("/test?lang=fr", 107 97 headers={"Accept-Language": "de,en,tr"}) 108 output = cherrypy.response.body[0] 109 assert 'calendar/lang/calendar-fr.js' in output 110 assert 'calendar/lang/calendar-en.js' not in output 98 assert 'calendar/lang/calendar-fr.js' in response.body 99 assert 'calendar/lang/calendar-en.js' not in response.body 111 100 112 101 # testing predetermined non-existing language 113 testutil.create_request("/test?lang=x",102 response = testutil.go("/test?lang=x", 114 103 headers={"Accept-Language": "de,en,fr,tr"}) 115 output = cherrypy.response.body[0] 116 assert 'calendar/lang/calendar-de.js' in output 117 assert 'calendar/lang/calendar-x.js' not in output 118 assert 'calendar/lang/calendar-en.js' not in output 104 assert 'calendar/lang/calendar-de.js' in response.body 105 assert 'calendar/lang/calendar-x.js' not in response.body 106 assert 'calendar/lang/calendar-en.js' not in response.body -
turbogears/widgets/tests/test_new_validation.py
1 import cherrypy2 1 import turbogears.widgets as widgets 3 2 import turbogears.validators as validators 4 3 5 4 from turbogears.testutil import catch_validation_errors 6 5 7 class Request:8 validation_errors = {}9 10 oldrequest = None11 12 def setup_module():13 global oldrequest14 oldrequest = cherrypy.request15 cherrypy.request = Request()16 17 18 def teardown_module():19 global oldrequest20 cherrypy.request = oldrequest21 22 23 24 25 6 class SimpleSchema(validators.Schema): 26 7 phone = validators.Int() 27 8 -
turbogears/widgets/tests/test_forms.py
4 4 from turbogears import widgets, validators, controllers, expose, validate, \ 5 5 testutil 6 6 from turbogears import config 7 from turbogears.testutil import catch_validation_errors, create_request7 from turbogears.testutil import catch_validation_errors, go 8 8 import cherrypy 9 9 10 10 11 11 def setup_module(): 12 testutil.start_ cp()12 testutil.start_server() 13 13 cherrypy.serving.request = testutil.DummyRequest() 14 14 15 15 def test_rendering(): … … 167 167 @expose() 168 168 @validate(form=nestedform) 169 169 def checkform(self, foo): 170 self.foo =foo170 return foo 171 171 172 @expose() 173 def field_for(self): 174 cherrypy.request.validation_errors = dict(foo=dict(foo='error')) 175 template = """\ 176 <div xmlns:py="http://purl.org/kid/ns#"> 177 ${field_for('foo').fq_name}.appears 178 ${field_for('foo').error}_appears 179 ${field_for('foo').field_id}_appears 180 ${field_for('foo').display(value_for('foo'), **params_for('foo'))} 181 </div> 182 """ 183 textfield = widgets.TextField("foo") 184 fieldset = widgets.FieldSet("foo", fields=[textfield], template=template) 185 form = widgets.Form("form", fields=[fieldset], template=template) 172 186 187 # Good example below of how you can pass parameters and values to nested 188 # widgets. 189 value = dict(foo=dict(foo="HiYo!")) 190 params = dict(attrs=dict(foo=dict(foo=dict(size=100)))) 191 params['format'] = 'xhtml' 192 return form.render(value, **params) 193 194 173 195 def test_nested_variables(): 174 newroot = NestedController() 175 cherrypy.root = None 176 cherrypy.tree.mount_points = {} 177 cherrypy.tree.mount(newroot, "/") 196 testutil.start_server(NestedController()) 178 197 url = u"/checkform?foo.name=Kevin&foo.age=some%20Numero".encode("utf-8") 179 create_request(url)198 request = go(url) 180 199 assert config.get("decoding_filter.encoding", path="/") == "utf8" 181 assert newroot.foo 182 assert newroot.foo["name"] == "Kevin" 183 assert newroot.foo["age"] == u"some Numero" 200 assert request.raw["name"] == "Kevin" 201 assert request.raw["age"] == u"some Numero" 184 202 185 203 def test_field_for(): 186 cherrypy.request.validation_errors = dict(foo=dict(foo='error')) 187 template = """\ 188 <div xmlns:py="http://purl.org/kid/ns#"> 189 ${field_for('foo').fq_name}.appears 190 ${field_for('foo').error}_appears 191 ${field_for('foo').field_id}_appears 192 ${field_for('foo').display(value_for('foo'), **params_for('foo'))} 193 </div> 194 """ 195 textfield = widgets.TextField("foo") 196 fieldset = widgets.FieldSet("foo", fields=[textfield], template=template) 197 form = widgets.Form("form", fields=[fieldset], template=template) 198 # Good example below of how you can pass parameters and values to nested 199 # widgets. 200 value = dict(foo=dict(foo="HiYo!")) 201 params = dict(attrs=dict(foo=dict(foo=dict(size=100)))) 202 params['format'] = 'xhtml' 203 output = form.render(value, **params) 204 response = testutil.go('/field_for') 205 output = response.body 204 206 assert "form_foo_appears" in output 205 207 assert "form_foo_foo_appears" in output 206 208 assert "foo.appears" in output -
turbogears/widgets/tests/test_request_related_features.py
1 1 import re 2 2 import turbogears 3 3 import cherrypy 4 5 4 import turbogears.testutil as testutil 6 from turbogears import widgets, validators 5 from turbogears import widgets, validators, validate, expose, error_handler 7 6 8 7 def test_required_fields(): 9 8 """ … … 20 19 return dict(form=form) 21 20 test = turbogears.expose(template="turbogears.widgets.tests.form")(test) 22 21 23 cherrypy.root = MyRoot()24 testutil.create_request("/test")25 output = cherrypy.response.body[0].lower()22 testutil.mount(MyRoot()) 23 response = testutil.go("/test") 24 output = response.body.lower() 26 25 27 26 print output 28 27 name_p = 'name="comment"' … … 48 47 form2 = widgets.TableForm(name="form2", fields=MyFields()) 49 48 50 49 class MyRoot(turbogears.controllers.RootController): 51 def test(self): 52 return dict(form1=form1, form2=form2) 50 51 #@expose(template="turbogears.widgets.tests.two_forms") 52 #@validate(form=form1) 53 #@error_handler('test') 54 def test(self, age, email): 55 validated_form = cherrypy.request.validated_form.name 56 form1_valid = form1.is_validated 57 form2_valid = form2.is_validated 58 return dict(form1=form1, form2=form2, validated_form=validated_form, 59 form1_valid=form1_valid, form2_valid=form2_valid) 53 60 test = turbogears.expose(template="turbogears.widgets.tests.two_forms")(test) 54 61 test = turbogears.validate(form=form1)(test) 55 62 test = turbogears.error_handler(test)(test) 56 63 64 57 65 def test2(self): 58 return dict(form=form2) 66 validated_form = cherrypy.request.validated_form.name 67 form1_valid = form1.is_validated 68 form2_valid = form2.is_validated 69 return dict(form=form2, validated_form=validated_form, 70 form1_valid=form1_valid, form2_valid=form2_valid) 59 71 test2 = turbogears.expose(template="turbogears.widgets.tests.form")(test2) 60 72 test2 = turbogears.validate(form=form2)(test2) 61 73 test2 = turbogears.error_handler(test2)(test2) 62 74 63 75 def test3(self): 64 return dict(form=form1) 76 validated_form = cherrypy.request.validated_form.name 77 form1_valid = form1.is_validated 78 form2_valid = form2.is_validated 79 return dict(form=form1, validated_form=validated_form, 80 form1_valid=form1_valid, form2_valid=form2_valid) 65 81 test3 = turbogears.expose(template="turbogears.widgets.tests.form")(test3) 66 82 test3 = turbogears.validate(form=form2)(test3) 67 83 test3 = turbogears.error_handler(test3)(test3) 68 84 69 cherrypy.root = MyRoot() 70 testutil.create_request("/test?age=foo&email=bar") 71 output = cherrypy.response.body[0].lower() 72 iv = cherrypy.request.input_values 73 validation_errors = cherrypy.request.validation_errors 74 validated_form = cherrypy.request.validated_form 85 testutil.mount(MyRoot()) 86 response = testutil.go("/test?age=foo&email=bar") 87 output = response.body.lower() 75 88 76 print output 77 print iv 78 print validation_errors 79 print validated_form 80 assert form1 is validated_form 81 assert form1.is_validated 82 assert form2 is not validated_form 83 assert not form2.is_validated 89 assert response.raw['validated_form'] == 'form1' 90 assert response.raw['form1_valid'] 91 assert not response.raw['form2_valid'] 84 92 value_p = 'value="foo"' 85 93 id_p = 'id="form1_age"' 86 94 assert (re.compile('.*'.join([value_p, id_p])).search(output) or … … 92 100 re.compile('.*'.join([id_p, value_p])).search(output) 93 101 ) 94 102 95 cherrypy.root = MyRoot() 96 testutil.create_request("/test2?age=foo&email=bar") 97 output = cherrypy.response.body[0].lower() 98 iv = cherrypy.request.input_values 99 validation_errors = cherrypy.request.validation_errors 100 validated_form = cherrypy.request.validated_form 103 response = testutil.go("/test2?age=foo&email=bar") 104 output = response.body.lower() 101 105 102 print output 103 print iv 104 print validation_errors 105 print validated_form 106 assert form1 is not validated_form 107 assert not form1.is_validated 108 assert form2 is validated_form 109 assert form2.is_validated 106 assert response.raw['validated_form'] == 'form2' 107 assert not response.raw['form1_valid'] 108 assert response.raw['form2_valid'] 110 109 assert 'value="foo"' in output 111 110 assert '>bar<' in output 112 111 assert 'class="fielderror"' in output 113 112 114 cherrypy.root = MyRoot() 115 testutil.create_request("/test3?age=foo&email=bar") 116 output = cherrypy.response.body[0].lower() 117 iv = cherrypy.request.input_values 118 validation_errors = cherrypy.request.validation_errors 119 validated_form = cherrypy.request.validated_form 113 response = testutil.go("/test3?age=foo&email=bar") 114 output = response.body.lower() 120 115 121 print output 122 print iv 123 print validation_errors 124 print validated_form 125 assert form1 is not validated_form 126 assert not form1.is_validated 127 assert form2 is validated_form 128 assert form2.is_validated 116 assert response.raw['validated_form'] == 'form2' 117 assert not response.raw['form1_valid'] 118 assert response.raw['form2_valid'] 129 119 assert 'value="foo"' not in output 130 120 assert '>bar<' not in output 131 121 assert 'class="fielderror"' not in output … … 141 131 name="repeat", fields=MyFields(), repetitions=repetitions)]) 142 132 143 133 class MyRoot(turbogears.controllers.RootController): 144 @turbogears.expose(template="turbogears.widgets.tests.form")145 134 def test(self): 146 135 return dict(form=form) 136 test = turbogears.expose(template="turbogears.widgets.tests.form")(test) 147 137 148 @turbogears.expose(template="turbogears.widgets.tests.form")149 138 def test_value(self): 150 139 value = dict(repeat=[{'name':'foo', 'comment':'hello'}, 151 140 None, 152 141 None, 153 142 {'name':'bar', 'comment':'byebye'}]) 154 143 return dict(form=form, value=value) 144 test_value = turbogears.expose(template="turbogears.widgets.tests.form")(test_value) 155 145 156 146 def test_validation(self): 157 return dict(form=form)158 test_validation = turbogears.expose(159 template="turbogears.widgets.tests.form")(test_validation)147 validation_errors = cherrypy.request.validation_errors 148 return dict(form=form, validation_errors=validation_errors) 149 test_validation = turbogears.expose(template="turbogears.widgets.tests.form")(test_validation) 160 150 test_validation = turbogears.validate(form=form)(test_validation) 161 151 test_validation = turbogears.error_handler(test_validation)(test_validation) 162 152 163 cherrypy.root = MyRoot()164 testutil.create_request("/test")165 output = cherrypy.response.body[0].lower()153 testutil.mount(MyRoot()) 154 response = testutil.go("/test") 155 output = response.body.lower() 166 156 for i in range(repetitions): 167 157 assert 'id="form_repeat_%i"' % i in output 168 158 assert 'name="repeat-%i.name"' % i in output … … 170 160 assert 'name="repeat-%i.comment"' % i in output 171 161 assert 'id="form_repeat_%i_comment"' % i in output 172 162 173 cherrypy.root = MyRoot()174 testutil.create_request("/test_value")175 output = cherrypy.response.body[0].lower()163 testutil.mount(MyRoot()) 164 response = testutil.go("/test_value") 165 output = response.body.lower() 176 166 name_p = 'name="repeat-0.name"' 177 167 value_p = 'value="foo"' 178 168 assert (re.compile('.*'.join([value_p, name_p])).search(output) or … … 204 194 re.compile('.*'.join([name_p, value_p])).search(output) 205 195 ) 206 196 207 cherrypy.root = MyRoot()208 testutil.create_request("/test_validation?repeat-0.name=foo&repeat-1.name="197 testutil.mount(MyRoot()) 198 response = testutil.go("/test_validation?repeat-0.name=foo&repeat-1.name=" 209 199 "&repeat-2.name=bar&repeat-3.name=&repeat-4.name=") 210 output = cherrypy.response.body[0].lower()211 validation_errors = cherrypy.request.validation_errors200 output = response.body.lower() 201 validation_errors = response.raw['validation_errors'] 212 202 assert validation_errors.has_key("repeat") 213 203 assert isinstance(validation_errors["repeat"], list) 214 204 assert validation_errors["repeat"][0] is None -
turbogears/widgets/tests/test_widgets.py
4 4 from turbogears.testutil import catch_validation_errors 5 5 6 6 def setup_module(): 7 testutil.start_ cp()7 testutil.start_server() 8 8 cherrypy.serving.request = testutil.DummyRequest() 9 9 10 10 -
turbogears/widgets/tests/test_nested_widgets.py
1 1 import re 2 from turbogears.testutil import catch_validation_errors, start_ cp2 from turbogears.testutil import catch_validation_errors, start_server 3 3 import turbogears 4 4 from turbogears import testutil 5 import cherrypy6 5 import turbogears.widgets as widgets 7 6 import turbogears.validators as validators 8 7 from turbogears.widgets.meta import copy_schema 9 8 10 9 def setup_module(): 11 global oldrequest 12 start_cp() 10 start_server() 13 11 14 12 15 13 #XXX: We ignore missing keys to make passing value easier in tests … … 56 54 Checks if names fo the widgets are set correctly depending on their 57 55 path. 58 56 """ 59 cherrypy.root = self.MyRoot()60 testutil.create_request('/?test_id=sub2')61 output = cherrypy.response.body[0]57 testutil.mount(self.MyRoot()) 58 response = testutil.go('/?test_id=sub2') 59 output = response.body 62 60 value_p = 'value="22"' 63 61 name_p = 'name="sub.sub2.age"' 64 62 assert (re.compile('.*'.join([value_p, name_p])).search(output) or 65 63 re.compile('.*'.join([name_p, value_p])).search(output)) 66 64 67 testutil.create_request('/?test_id=sub')68 output = cherrypy.response.body[0]65 response = testutil.go('/?test_id=sub') 66 output = response.body 69 67 value_p = 'value="22"' 70 68 name_p = 'name="sub.age"' 71 69 id_p = 'id="myform_sub_age"' … … 74 72 assert (re.compile('.*'.join([value_p, id_p])).search(output) or 75 73 re.compile('.*'.join([id_p, value_p])).search(output)) 76 74 77 testutil.create_request('/?test_id=age')78 output = cherrypy.response.body[0]75 response = testutil.go('/?test_id=age') 76 output = response.body 79 77 value_p = 'value="22"' 80 78 name_p = 'name="age"' 81 79 assert (re.compile('.*'.join([value_p, name_p])).search(output) or -
turbogears/view/base.py
107 107 @type template: string 108 108 109 109 """ 110 environ = getattr(cherrypy.request, 'wsgi_environ', {}) 111 if environ.get('paste.testing', False): 112 cherrypy.request.wsgi_environ['paste.testing_variables']['raw'] = info 113 110 114 template = info.pop("tg_template", template) 111 115 if not info.has_key("tg_flash"): 112 116 if config.get("tg.empty_flash", True):