Ticket #1762: webtest_blended.patch
| File webtest_blended.patch, 141.7 kB (added by kskuhlman, 2 years ago) |
|---|
-
setup.py
old new 46 46 47 47 testtools = [ 48 48 "nose >= 0.9.3, <= 0.10.0a1", 49 "WebTest", 49 50 ] 50 51 51 52 tgtesttools = [ 52 53 "nose >= 0.9.3, <= 0.10.0a1", 54 "WebTest", 53 55 ] 54 56 55 57 # python 2.5 compatible list -
turbogears/identity/tests/test_identity.py
old new 55 55 56 56 @expose() 57 57 def index(self): 58 pass58 return dict() 59 59 60 60 @expose() 61 61 def identity_failed(self, **kw): … … 69 69 @expose() 70 70 @identity.require(in_group('peon')) 71 71 def in_peon_group(self): 72 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() … … 136 146 return 'wrong params: %s\nexpected unicode objects' \ 137 147 ' for all strings' % cherrypy.request.params 138 148 149 @expose() 150 def is_anonymous(self): 151 assert cherrypy.serving.request.identity.user_name == None 152 assert cherrypy.serving.request.identity.anonymous 153 assert identity.current.anonymous 154 return 'is_anonymous' 139 155 140 class TestIdentity(unittest.TestCase):141 156 157 158 class TestIdentity(testutil.TGWebTest): 159 142 160 def setUp(self): 143 161 # identity requires visit and a failure_url 144 162 test_config = {'global': { … … 151 169 self._original_config = original_config 152 170 config.configure_loggers(test_config) 153 171 config.update(test_config['global']) 154 cherrypy.root = IdentityRoot()155 startup.startTurboGears()172 testutil.mount(IdentityRoot()) 173 testutil.TGWebTest.setUp(self) 156 174 self.init_model() 157 175 158 176 def tearDown(self): 159 startup.stopTurboGears() 177 testutil.unmount() 178 testutil.TGWebTest.tearDown(self) 160 179 config.update(self._original_config) 161 180 162 181 def init_model(self): … … 181 200 182 201 def test_user_password_parameters(self): 183 202 """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 203 response = self.app.get('/new_user_setup?user_name=test&password=pw') 204 assert 'test pw' in response 187 205 188 206 def test_user_exists(self): 189 207 u = TG_User.by_user_name('samIam') … … 205 223 config.update({'identity.soprovider.encryption_algorithm': None}) 206 224 # force new config values to load 207 225 startup.startTurboGears() 208 testutil.create_request('/')226 self.app.get('/') 209 227 hub.begin() 210 228 u = TG_User.by_user_name('samIam') 211 229 u.password = u'garçon' … … 219 237 config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 220 238 # force new config values to load 221 239 startup.startTurboGears() 222 testutil.create_request('/')240 self.app.get('/') 223 241 hub.begin() 224 242 u = TG_User.by_user_name('samIam') 225 243 u.password = 'password' … … 234 252 config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 235 253 # force new config values to load 236 254 startup.startTurboGears() 237 testutil.create_request('/')255 self.app.get('/') 238 256 hub.begin() 239 257 u = TG_User.by_user_name('samIam') 240 258 u.password = u'garçon' … … 248 266 config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 249 267 # force new config values to load 250 268 startup.startTurboGears() 251 testutil.create_request('/')269 self.app.get('/') 252 270 hub.begin() 253 271 u = TG_User.by_user_name('samIam') 254 272 u.password = 'password' … … 263 281 config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 264 282 # force new config values to load 265 283 startup.startTurboGears() 266 testutil.create_request('/')284 self.app.get('/') 267 285 hub.begin() 268 286 u = TG_User.by_user_name('samIam') 269 287 u.password = u'garçon' … … 280 298 config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 281 299 # force new config values to load 282 300 startup.startTurboGears() 283 testutil.create_request('/')301 self.app.get('/') 284 302 hub.begin() 285 303 u = TG_User.by_user_name('samIam') 286 304 u.password = u'garçon'.encode('UTF-8') … … 295 313 config.update({'identity.soprovider.encryption_algorithm':'sha1'}) 296 314 # force new config values to load 297 315 startup.startTurboGears() 298 testutil.create_request('/')316 self.app.get('/') 299 317 hub.begin() 300 318 u = TG_User.by_user_name('samIam') 301 319 u.set_password_raw('password') … … 308 326 config.update({'identity.soprovider.encryption_algorithm':'sha1'}) 309 327 # force new config values to load 310 328 startup.startTurboGears() 311 testutil.create_request('/')329 self.app.get('/') 312 330 hub.begin() 313 331 u = TG_User.by_user_name('samIam') 314 332 u.set_password_raw(u'garçon') … … 324 342 'identity.tests.test_identity.mycustomencrypt'}) 325 343 # force new config values to load 326 344 startup.startTurboGears() 327 testutil.create_request('/')345 self.app.get('/') 328 346 hub.begin() 329 347 u = TG_User.by_user_name('samIam') 330 348 u.password = 'password' … … 335 353 336 354 def test_anonymous_browsing(self): 337 355 """Test if we can show up anonymously.""" 338 testutil.create_request('/')339 assert identity.current.anonymous356 response = self.app.get('/is_anonymous') 357 assert 'is_anonymous' in response 340 358 341 359 def test_deny_anonymous(self): 342 360 """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 361 response = self.app.get('/logged_in_only') 362 assert 'identity_failed_answer' in response 346 363 347 364 def test_deny_anonymous_viewable(self): 348 365 """Test that a logged in user can see an resource blocked 349 366 from anonymous users.""" 350 testutil.create_request('/logged_in_only?'367 response = self.app.get('/logged_in_only?' 351 368 'user_name=samIam&password=secret&login=Login') 352 firstline = cherrypy.response.body[0] 353 assert 'logged_in_only' in firstline, firstline 369 assert 'logged_in_only' in response 354 370 355 371 def test_logout(self): 356 372 """Test that logout works and session is gets invalid afterwards.""" 357 testutil.create_request('/in_peon_group?'373 response = self.app.get('/in_peon_group?' 358 374 '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 375 session_id = response.headers['Set-Cookie'] 376 response = self.app.get('/logout', headers={'Cookie': session_id }) 377 response = self.app.get('/is_anonymous', headers={'Cookie': session_id}) 378 assert response.body == 'is_anonymous' 365 379 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 380 def test_require_group(self): 379 381 """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 382 response = self.app.get('/in_peon_group') 383 assert 'identity_failed_answer' in response, response 383 384 384 385 def test_require_expose_required_permission(self): 385 386 """Test that the decorator exposes the correct permissions via _require 386 387 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 388 response = self.app.get('/test_exposed_require') 389 assert 'require is exposed' in response, response 390 390 391 391 def test_require_group_viewable(self): 392 392 """Test that a user with proper group membership can see a restricted url.""" 393 testutil.create_request('/in_peon_group?'393 response = self.app.get('/in_peon_group?' 394 394 'user_name=samIam&password=secret&login=Login') 395 firstline = cherrypy.response.body[0] 396 assert 'in_peon_group' in firstline, firstline 395 assert 'in_peon_group' in response, response 397 396 user = TG_User.by_user_name("samIam") 398 397 399 398 def test_require_group_viewable(self): 400 399 """Test that the current user and group properties are set correctly.""" 401 testutil.create_request('/in_peon_group?'400 response = self.app.get('/in_peon_group?' 402 401 'user_name=samIam&password=secret&login=Login') 403 402 user = TG_User.by_user_name("samIam") 404 403 group_ids = set((TG_Group.by_group_name("peon").id, 405 404 TG_Group.by_group_name("other").id)) 406 assert identity.current.user == user407 assert identity.current.user_name == user.user_name408 assert identity.current.user_id == user.id409 assert identity.current.groups == set(('peon', 'other'))410 assert identity.current.group_ids == group_ids411 405 412 406 def test_user_not_in_right_group(self): 413 """Test that a user is denied access if they aren't in the right group.""" 414 testutil.create_request('/in_admin_group?' 407 """Test that a user is denied access if they aren't in the right group. 408 """ 409 response = self.app.get('/in_admin_group?' 415 410 'user_name=samIam&password=secret&login=Login') 416 firstline = cherrypy.response.body[0] 417 assert 'identity_failed_answer' in firstline, firstline 411 assert 'identity_failed_answer' in response, response 418 412 419 413 def test_require_permission(self): 420 """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 414 """Test that an anonymous user is denied access to a permission 415 restricted url. 416 """ 417 response = self.app.get('/has_chopper_permission') 418 assert 'identity_failed_answer' in response, response 424 419 425 420 def test_require_permission_viewable(self): 426 421 """Test that a user with proper permissions can see a restricted url.""" 427 testutil.create_request('/has_chopper_permission?'422 response = self.app.get('/has_chopper_permission?' 428 423 'user_name=samIam&password=secret&login=Login') 429 firstline = cherrypy.response.body[0] 430 assert 'has_chopper_permission' in firstline, firstline 424 assert 'has_chopper_permission' in response 431 425 432 426 def test_user_lacks_permission(self): 433 """Test that a user is denied acces if they don't have the proper permission.""" 434 testutil.create_request('/has_boss_permission?' 427 """Test that a user is denied acces if they don't have the proper 428 permission. 429 """ 430 response = self.app.get('/has_boss_permission?' 435 431 'user_name=samIam&password=secret&login=Login') 436 firstline = cherrypy.response.body[0] 437 assert 'identity_failed_answer' in firstline, firstline 432 assert 'identity_failed_answer' in response, response 438 433 439 434 def test_user_info_available(self): 440 435 """Test that we can see user information inside our controller.""" 441 testutil.create_request('/user_email?'436 response = self.app.get('/user_email?' 442 437 'user_name=samIam&password=secret&login=Login') 443 firstline = cherrypy.response.body[0] 444 assert 'samiam@example.com' in firstline, firstline 438 assert 'samiam@example.com' in response, response 445 439 446 440 def test_bad_login(self): 447 441 """Test that we are denied access if we provide a bad login.""" 448 testutil.create_request('/logged_in_only?'442 response = self.app.get('/logged_in_only?' 449 443 'user_name=samIam&password=wrong&login=Login') 450 firstline = cherrypy.response.body[0] 451 assert 'identity_failed_answer' in firstline, firstline 444 assert 'identity_failed_answer' in response, response 452 445 453 446 def test_restricted_subdirectory(self): 454 447 """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 448 response = self.app.get('/peon_area/index') 449 assert 'identity_failed_answer' in response, response 458 450 459 451 def test_restricted_subdirectory_viewable(self): 460 452 """Test that we can access a restricted subdirectory 461 453 if we have proper credentials.""" 462 testutil.create_request('/peon_area/index?'454 response = self.app.get('/peon_area/index?' 463 455 'user_name=samIam&password=secret&login=Login') 464 firstline = cherrypy.response.body[0] 465 assert 'restricted_index' in firstline, firstline 456 assert 'restricted_index' in response, response 466 457 467 458 def test_decoratator_in_restricted_subdirectory(self): 468 459 """Test that we can require a different permission 469 460 in a protected subdirectory.""" 470 testutil.create_request('/peon_area/in_other_group?'461 response = self.app.get('/peon_area/in_other_group?' 471 462 'user_name=samIam&password=secret&login=Login') 472 firstline = cherrypy.response.body[0] 473 assert 'in_other_group' in firstline, firstline 463 assert 'in_other_group' in response, response 474 464 475 465 def test_decoratator_failure_in_restricted_subdirectory(self): 476 466 """Test that we can get an identity failure from a decorator 477 467 in a restricted subdirectory""" 478 testutil.create_request('/peon_area/in_admin_group?'468 response = self.app.get('/peon_area/in_admin_group?' 479 469 'user_name=samIam&password=secret&login=Login') 480 firstline = cherrypy.response.body[0] 481 assert 'identity_failed_answer' in firstline, firstline 470 assert 'identity_failed_answer' in response, response 482 471 483 472 def test_explicit_checks_in_restricted_subdirectory(self): 484 473 """Test that explicit permission checks in a protected 485 474 directory is handled as expected""" 486 testutil.create_request('/peon_area/in_other_group_explicit_check?'475 response = self.app.get('/peon_area/in_other_group_explicit_check?' 487 476 'user_name=samIam&password=secret&login=Login') 488 firstline = cherrypy.response.body[0] 489 assert 'in_other_group' in firstline, firstline 477 assert 'in_other_group' in response, response 490 478 491 479 def test_throwing_identity_exception_in_restricted_subdirectory(self): 492 480 """Test that throwing an IdentityException in a protected 493 481 directory is handled as expected""" 494 testutil.create_request('/peon_area/in_admin_group_explicit_check?'482 response = self.app.get('/peon_area/in_admin_group_explicit_check?' 495 483 'user_name=samIam&password=secret&login=Login') 496 firstline = cherrypy.response.body[0] 497 assert 'identity_failed' in firstline, firstline 484 assert 'identity_failed' in response, response 498 485 499 486 def test_decode_filter_whenidfails(self): 500 487 """Test that the decode filter doesn't break with nested 501 488 variables and Identity""" 502 489 params = urllib.quote(IdentityRoot._test_encoded_params.decode( 503 490 '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 491 response = self.app.get('/test_params?' + params) 492 assert 'identity_failed_answer' in response, response 507 493 508 494 def test_decode_filter_whenidworks(self): 509 495 """Test that the decode filter doesn't break with nested … … 511 497 params = urllib.quote(IdentityRoot._test_encoded_params.decode( 512 498 'utf-8').encode('latin-1'), '=&') 513 499 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 500 response = self.app.get('/test_params?' + params) 501 assert 'params ok' in response, response 517 502 518 503 519 504 class TestTGUser(testutil.DBTest): … … 522 507 def setUp(self): 523 508 self._identity_on = config.get('identity.on', False) 524 509 config.update({'identity.on': False}) 525 try:526 self._provider = cherrypy.request.identityProvider527 except AttributeError:528 self._provider= None529 cherrypy.request.identityProvider = None530 510 startup.startTurboGears() 531 511 testutil.DBTest.setUp(self) 532 512 533 513 def tearDown(self): 534 514 testutil.DBTest.tearDown(self) 535 515 startup.stopTurboGears() 536 cherrypy.request.identityProvider = self._provider537 516 config.update({'identity.on': self._identity_on}) 538 517 539 518 def test_create_user(self): -
turbogears/identity/tests/test_visit.py
old new 2 2 from unittest import TestCase 3 3 import cherrypy 4 4 from turbogears import config, controllers, expose, startup, testutil, visit 5 from Cookie import SimpleCookie 5 6 6 7 7 def cookie_header( morsel):8 def cookie_header(response): 8 9 """Returns a dict containing cookie information to pass to a server.""" 9 return {'Cookie': morsel.output(header="")[1:]}10 return dict(Cookie=response.headers['Set-Cookie']) 10 11 11 12 12 13 class VisitRoot(controllers.RootController): 13 14 14 15 @expose() 15 16 def index(self): 16 return dict() 17 new = None 18 if visit.current(): 19 new = visit.current().is_new 20 visit_on = config.get('visit.on') 21 return dict(new=new, visit_on=visit_on) 17 22 18 23 19 24 class TestVisit(TestCase): 20 25 21 26 def setUp(self): 27 testutil.stop_server(tg_only = True) 22 28 self._visit_on = config.get('visit.on', False) 23 29 config.update({'visit.on': True}) 24 30 self._visit_timeout = config.get('visit.timeout', 20) 25 31 config.update({'visit.timeout': 50}) 26 32 self.cookie_name = config.get("visit.cookie.name", 'tg-visit') 27 cherrypy.root = VisitRoot() 33 self.app = testutil.make_app(VisitRoot) 34 testutil.start_server() 28 35 29 36 def tearDown(self): 30 startup.stopTurboGears()37 testutil.stop_server(tg_only = True) 31 38 config.update({'visit.timeout': self._visit_timeout}) 32 39 config.update({'visit.on': self._visit_on}) 33 40 34 41 def test_visit_response(self): 35 42 """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)43 response = self.app.get("/") 44 assert response.cookies_set.has_key(self.cookie_name) 38 45 39 46 def test_new_visit(self): 40 47 """Test that we can see a new visit on the server.""" 41 testutil.create_request("/")42 assert visit.current().is_new48 response = self.app.get("/") 49 assert response.raw['new'] 43 50 44 51 def test_old_visit(self): 45 52 """Test if we can track a visitor over time.""" 46 testutil.create_request("/")53 response = self.app.get("/") 47 54 # 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_new 55 print "Headers", response.headers 56 print "Config", config.get('visit.on') 57 morsel = response.cookies_set[self.cookie_name] 58 response = self.app.get("/", headers=cookie_header(response)) 59 assert not response.raw['new'] 51 60 52 61 def test_cookie_expires(self): 53 62 """Test if the visit timeout mechanism works.""" 54 63 timeout = config.get('visit.timeout', 50) 64 _app = self.app 55 65 try: 56 66 # set expiration to one second for this test only 67 testutil.stop_server(tg_only = True) 57 68 config.update({'visit.timeout': 1.0/60}) 58 testutil.create_request("/") 59 morsel = cherrypy.response.simple_cookie[self.cookie_name] 69 self.app = testutil.make_app(VisitRoot) 70 testutil.start_server() 71 response = self.app.get("/") 72 morsel = response.cookies_set[self.cookie_name] 60 73 time.sleep(2) # 2 seconds 61 testutil.create_request("/", headers=cookie_header(morsel))74 response = self.app.get("/", headers=cookie_header(response)) 62 75 finally: 63 76 config.update({'visit.timeout': timeout}) 64 assert cherrypy.response.simple_cookie[ 65 self.cookie_name].value != morsel.value, \ 77 self.app = _app 78 assert response.cookies_set[ 79 self.cookie_name] != morsel, \ 66 80 'cookie values should not match' 67 assert visit.current().is_new, \81 assert response.raw['new'], \ 68 82 'this should be a new visit, as the cookie has expired' 69 83 70 84 def test_cookie_not_permanent(self): 71 85 """Check that by default the visit cookie is not permanent.""" 72 testutil.create_request('/') 73 morsel = cherrypy.response.simple_cookie[self.cookie_name] 86 response = self.app.get('/') 87 cookies = SimpleCookie(response.headers['Set-Cookie']) 88 morsel = cookies[self.cookie_name] 74 89 assert not morsel['expires'] and not morsel['max-age'] 75 90 76 91 def test_cookie_permanent(self): … … 78 93 permanent = config.get('visit.cookie.permanent', False) 79 94 try: 80 95 # set cookie permanent for this test only (needs restart) 81 startup.stopTurboGears()96 testutil.stop_server(tg_only = True) 82 97 config.update({'visit.cookie.permanent': True}) 83 startup.startTurboGears() 84 testutil.create_request('/') 85 morsel = cherrypy.response.simple_cookie[self.cookie_name] 98 app = testutil.make_app(VisitRoot) 99 testutil.start_server() 100 response = app.get('/') 101 cookies = SimpleCookie(response.headers['Set-Cookie']) 102 morsel = cookies[self.cookie_name] 86 103 finally: 87 104 config.update({'visit.cookie.permanent': permanent}) 88 assert morsel['max-age'] == 3000105 assert morsel['max-age'] == '3000' 89 106 expires = time.mktime(time.strptime(morsel['expires'], 90 107 '%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 108 should_expire = time.mktime(time.gmtime()) + int(morsel['max-age']) 109 assert abs(should_expire - expires) < 3, (should_expire, expires, should_expire - expires) 110 -
turbogears/visit/api.py
old new 251 251 max_age = self.cookie_max_age 252 252 if max_age: 253 253 # use 'expires' because MSIE ignores 'max-age' 254 cookies[self.cookie_name]['expires'] = time.strftime(254 cookies[self.cookie_name]['expires'] = '"%s"' % time.strftime( 255 255 "%a, %d-%b-%Y %H:%M:%S GMT", 256 256 time.gmtime(time.time() + max_age)) 257 257 # 'max-age' takes precedence on standard conformant browsers -
turbogears/tests/test_form_controllers.py
old new 1 from unittest import TestCase2 1 from datetime import datetime 2 from unittest import TestCase 3 3 import cherrypy 4 4 from turbogears import widgets, config, controllers, expose, mochikit, \ 5 5 validate, validators, testutil 6 from turbogears.testutil import mount, unmount, make_app 6 7 7 8 9 def setup_module(): 10 global app 11 app = make_app(MyRoot) 12 testutil.start_server() 13 14 def teardown_module(): 15 testutil.stop_server() 16 17 8 18 class MyFormFields(widgets.WidgetsList): 9 19 #XXX: Since allow_extra_fields should be removed from validators.Schema, 10 20 # we need a validator for every input-expecting widget … … 16 26 myform = widgets.TableForm(fields=MyFormFields()) 17 27 18 28 29 class State(object): 30 counter = 0 31 32 class AddingValidator(validators.FancyValidator): 33 def _to_python(self, value, state=None): 34 state.counter += 1 35 return value 36 37 class AddingSchema(validators.Schema): 38 a = AddingValidator() 39 b = AddingValidator() 40 41 class AddingNestedSchema(AddingSchema): 42 c = AddingSchema() 43 44 19 45 class MyRoot(controllers.RootController): 20 46 21 47 @expose(html="turbogears.tests.form") … … 31 57 def testform(self, name, date, age, tg_errors=None): 32 58 if tg_errors: 33 59 self.has_errors = True 34 self.name = name 35 self.age = age 36 self.date = date 60 return dict(name=name, user_age=age, birthdate=date) 37 61 38 62 @expose() 39 63 @validate(form=myform) 40 64 def testform_new_style(self, name, date, age): 41 65 if cherrypy.request.validation_errors: 42 66 self.has_errors = True 43 self.name = name 44 self.age = age 45 self.date = date 67 return dict(name=name, age=age, date=date) 46 68 69 @expose() 70 @validate(validators=AddingNestedSchema(), state_factory=State) 71 def validation(self, a, b, c): 72 return 'counter: %d' % cherrypy.request.validation_state.counter 73 47 74 def test_form_translation(): 48 75 """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 76 response = app.get("/testform?name=ed&date=11/05/2005&age=5") 77 assert response.raw['name'] == "ed" 78 assert response.raw['user_age'] == 5 54 79 55 80 def test_form_translation_new_style(): 56 81 """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 82 response = app.get("/testform_new_style?name=ed&date=11/05/2005&age=5&") 83 assert response.raw['name'] == "ed" 84 assert response.raw['age'] == 5 62 85 63 86 def test_invalid_form_with_error_handling(): 64 87 """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 88 response = app.get("/testform?name=ed&age=edalso&date=11/05/2005") 68 89 69 90 def test_css_should_appear(): 70 91 """CSS should appear when asked for""" 71 testutil.create_request("/")72 assert "calendar-system.css" in cherrypy.response.body[0]92 response = app.get("/") 93 assert "calendar-system.css" in response 73 94 74 95 def test_javascript_should_appear(): 75 96 """JavaScript should appear when asked for""" 76 testutil.create_request("/")77 assert "calendar.js" in cherrypy.response.body[0]97 response = app.get("/") 98 assert "calendar.js" in response 78 99 79 100 def test_include_mochikit(): 80 101 """JSLinks (and MochiKit especially) can be included easily""" 81 testutil.create_request("/usemochi")82 assert "MochiKit.js" in cherrypy.response.body[0]102 response = app.get("/usemochi") 103 assert "MochiKit.js" in response 83 104 84 105 def test_suppress_mochikit(): 85 106 """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] 107 config.update({"global":{"tg.mochikit_suppress" : True}}) 108 suppressed = app.get("/usemochi") 89 109 # 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 110 config.update({"global":{"tg.mochikit_suppress" : False}}) 95 111 112 included = app.get("/usemochi") 113 assert "MochiKit.js" not in suppressed.body 114 assert "MochiKit.js" in included.body 115 96 116 def test_mochikit_everywhere(): 97 117 """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]118 config.update({"global":{"tg.mochikit_all" : True}}) 119 response = app.get("/") 120 config.update({"global":{"tg.mochikit_all" : False}}) 121 assert "MochiKit.js" in response 102 122 103 123 def test_mochikit_nowhere(): 104 124 """Setting tg.mochikit_suppress will prevent including it everywhere""" 105 125 config.update({"global": {"tg.mochikit_all": True}}) 106 126 config.update({"global": {"tg.mochikit_suppress": True}}) 107 testutil.create_request("/")127 response = app.get("/") 108 128 config.update({"global": {"tg.mochikit_all": False}}) 109 129 config.update({"global": {"tg.mochikit_suppress": False}}) 110 assert "MochiKit.js" not in cherrypy.response.body[0]130 assert "MochiKit.js" not in response 111 131 112 132 def test_include_widgets(): 113 133 """Any widget can be included everywhere by setting tg.include_widgets""" 114 134 config.update({"global": {"tg.include_widgets": ["mochikit"]}}) 115 testutil.create_request("/")135 response = app.get("/") 116 136 config.update({"global": {"tg.include_widgets": []}}) 117 assert "MochiKit.js" in cherrypy.response.body[0]137 assert "MochiKit.js" in response 118 138 139 def test_counter_is_incremented(): 140 # parameter values are irrelevant 141 url = '/validation?a=1&b=2&c.a=3&c.b=4' 142 response = app.get(url) 143 msg = "Validation state is not handled properly" 144 # 4 == 1 (a) + 1(b) + 1(c.a) + 1(c.b) 145 assert 'counter: 4' in response.body, msg 119 146 120 class State(object):121 counter = 0122 123 class AddingValidator(validators.FancyValidator):124 def _to_python(self, value, state=None):125 state.counter += 1126 return value127 128 class AddingSchema(validators.Schema):129 a = AddingValidator()130 b = AddingValidator()131 132 class AddingNestedSchema(AddingSchema):133 c = AddingSchema()134 135 136 class TestValidationState(TestCase):137 138 class Controller(controllers.RootController):139 140 @expose()141 @validate(validators=AddingNestedSchema(), state_factory=State)142 def validation(self, a, b, c):143 return 'counter: %d' % cherrypy.request.validation_state.counter144 145 def __init__(self, *args, **kw):146 super(TestValidationState, self).__init__(*args, **kw)147 148 def test_counter_is_incremented(self):149 cherrypy.root = self.Controller()150 # parameter values are irrelevant151 url = '/validation?a=1&b=2&c.a=3&c.b=4'152 testutil.create_request(url)153 body = cherrypy.response.body[0]154 msg = "Validation state is not handled properly"155 # 4 == 1 (a) + 1(b) + 1(c.a) + 1(c.b)156 self.failUnless('counter: 4' in body, msg) -
turbogears/tests/test_errorhandling.py
old new 1 1 import unittest 2 3 import cherrypy4 5 2 from turbogears.controllers import error_handler, exception_handler, \ 6 3 expose, validate, RootController, Controller 7 4 from turbogears.errorhandling import FailsafeSchema … … 16 13 else: 17 14 return str(errors) 18 15 16 def setup_module(): 17 testutil.unmount() 18 testutil.mount(MyRoot()) 19 testutil.mount(NestedController(), "/nestedcontroller") 20 testutil.start_server() 19 21 22 def teardown_module(): 23 testutil.unmount() 24 testutil.stop_server() 25 20 26 class MyRoot(RootController): 21 27 22 28 def defaulterrorhandler(self, tg_source, tg_errors, tg_exceptions, … … 94 100 "second": validators.Int(not_empty=True)}) 95 101 @error_handler(defaulterrorhandler) 96 102 def positionalargs(self, first, second, *args, **kw): 97 self.first = first98 self.second = second99 self.third = args[0]100 103 return dict(title="Positional arguments", first=first, second=second, 101 args=args, bar=kw["bar"])104 third=args[0], args=args, bar=kw["bar"]) 102 105 103 106 @expose() 104 107 @validate(validators={"bar": validators.Int(not_empty=True)}) … … 141 144 return self.notexposed(bar) 142 145 143 146 def continuation(self, tg_source): 144 self.continuation = True 145 return tg_source(self) 147 response = tg_source(self) 148 response['continuation'] = True 149 return response 146 150 147 151 @expose() 148 152 @validate(validators={"bar": validators.Int(not_empty=True)}) … … 208 212 return dict(title="Nested") 209 213 210 214 215 app = testutil.make_app() 216 211 217 class TestErrorHandler(unittest.TestCase): 212 218 213 def setUp(self):214 cherrypy.root = MyRoot()215 cherrypy.root.nestedcontroller = NestedController()216 217 219 def test_defaultErrorHandler(self): 218 220 """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])221 response = app.get("/defaulterror?bar=abc") 222 self.failUnless("Default error handler" in response) 223 response = app.get("/defaulterror?bar=true") 224 self.failUnless("Default error provider" in response) 223 225 224 226 def test_specialisedErrorHandler(self): 225 227 """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]) 228 response = app.get("/specialisederror?bar=abc&baz=a@b.com") 229 self.failUnless("Default error handler" in response) 230 response = app.get("/specialisederror?baz=abc&bar=1") 231 self.failUnless("Specialised error handler" in response) 232 response = app.get("/specialisederror?bar=1&baz=a@b.com") 233 self.failUnless("Specialised error provider" in response) 234 234 235 235 def test_exceptionErrorHandler(self): 236 236 """Error handler for exceptions.""" 237 testutil.create_request("/exceptionerror")238 self.failUnless("Default error handler" in cherrypy.response.body[0])237 response = app.get("/exceptionerror") 238 self.failUnless("Default error handler" in response) 239 239 240 240 def test_recursiveErrorHandler(self): 241 241 """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]) 242 response = app.get("/recursiveerror?bar=abc") 243 self.failUnless("Recursive error handler" in response) 244 response = app.get("/recursiveerror?bar=1") 245 self.failUnless("Recursive error provider" in response) 247 246 248 247 def test_implicitErrorHandler(self): 249 248 """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]) 249 response = app.get("/impliciterror?bar=abc") 250 self.failUnless("Implicit error handler" in response) 251 response = app.get("/impliciterror?bar=1") 252 self.failUnless("Implicit error provider" in response) 256 253 257 254 def test_normalMethodErrorHandler(self): 258 255 """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])256 response = app.get("/normalmethodcaller?bar=abc") 257 self.failUnless("Normal method" in response) 258 response = app.get("/normalmethodcaller?bar=true") 259 self.failUnless("Normal method caller" in response) 263 260 264 261 def test_infiniteRecursionPrevention(self): 265 262 """Infinite recursion prevention.""" 266 testutil.create_request("/infiniteloop")267 self.failUnless("Exception 2" in cherrypy.response.body[0])263 response = app.get("/infiniteloop") 264 self.failUnless("Exception 2" in response) 268 265 269 266 def test_positionalArgs(self): 270 267 """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")268 response = app.get("/positionalargs/first/23/third?bar=abc") 269 self.failUnless("Default error handler" in response) 270 response = app.get("/positionalargs/first/abc/third?bar=false") 271 self.failUnless("Default error handler" in response) 272 response = app.get("/positionalargs/first/abc/third?bar=abc") 273 self.failUnless("Default error handler" in response) 274 response = app.get("/positionalargs/first/23/third?bar=true") 275 self.failUnless("Positional arguments" in response) 276 self.failUnless(response.raw['first'] == "first") 277 self.failUnless(response.raw['second'] == 23) 278 self.failUnless(response.raw['third'] == "third") 282 279 283 280 def test_missingArgs(self): 284 281 """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])282 response = app.get("/missingargs") 283 self.failUnless("Default error handler" in response) 284 response = app.get("/missingargs?bar=12") 285 self.failUnless("Missing args provider" in response) 289 286 290 287 def test_nohandler(self): 291 288 """No error hanlder declared.""" 292 testutil.create_request("/nohandler")293 self.failUnless("Exception raised" in cherrypy.response.body[0])289 response = app.get("/nohandler") 290 self.failUnless("Exception raised" in response) 294 291 295 292 def test_bindArgs(self): 296 293 """Arguments can be bond to an error handler.""" 297 testutil.create_request("/bindargs")298 self.failUnless("123" in cherrypy.response.body[0])294 response = app.get("/bindargs") 295 self.failUnless("123" in response) 299 296 300 297 def test_notExposed(self): 301 298 """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])299 response = app.get("/notexposedcaller?foo=a&bar=rab&baz=c") 300 self.failUnless("Not exposed error" in response) 301 self.failUnless("rab" in response) 305 302 306 303 def test_continuations(self): 307 304 """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)305 response = app.get("/continuationcaller?bar=a") 306 self.failUnless("Continuation caller" in response) 307 self.failUnless(response.raw['continuation'] == True) 311 308 312 309 def test_nested(self): 313 310 """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])311 response = app.get("/nest?bar=a") 312 self.failUnless("Default error handler" in response) 313 response = app.get("/nestedcontroller/nest?bar=a") 314 self.failUnless("Nested" in response) 318 315 319 316 def test_failsafe(self): 320 317 """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]) 318 response = app.get("/failsafenone?bar=a&baz=b") 319 self.failUnless('"bar": "a"' in response) 320 self.failUnless('"baz": "b"' in response) 321 response = app.get("/failsafevaluesdict?bar=a&baz=b") 322 self.failUnless('"bar": 1' in response) 323 self.failUnless('"baz": 2' in response) 324 response = app.get("/failsafevaluesatom?bar=a&baz=b") 325 self.failUnless('"bar": 13' in response) 326 self.failUnless('"baz": 13' in response) 327 response = app.get("/failsafemaperrors?bar=a&baz=b") 328 self.failUnless('"bar": "Please enter an integer value"' in response) 329 self.failUnless('"baz": "Please enter an integer value"' in response) 330 response = app.get("/failsafeformencode?bar=a&baz=b") 331 self.failUnless('"bar": 1' in response) 332 self.failUnless('"baz": 2' in response) 333 response = app.get("/failsafedefaults?bar=a&baz=b") 334 self.failUnless('"bar": 1' in response) 335 self.failUnless('"baz": 2' in response) -
turbogears/tests/test_sqlalchemy.py
old new 9 9 from turbogears.database import metadata, session, mapper, \ 10 10 bind_metadata, get_metadata 11 11 from turbogears.controllers import RootController 12 from turbogears.testutil import create_request, sqlalchemy_cleanup, \13 capture_log, print_log 12 from turbogears.testutil import make_app, sqlalchemy_cleanup, \ 13 capture_log, print_log, start_server, stop_server 14 14 15 15 16 16 # Fixture … … 81 81 mapper(Address, addresses_table, properties=dict( 82 82 person=relation(Person, backref='addresses'))) 83 83 mapper(Test, test_table) 84 85 start_server() 84 86 85 87 def teardown_module(): 86 88 fresh_metadata = get_metadata('fresh') … … 91 93 if os.path.exists('freshtest.db'): 92 94 os.unlink('freshtest.db') 93 95 96 stop_server() 94 97 98 95 99 # Database tests 96 100 97 101 def test_query_in_session(): … … 135 139 will be marked with this name :) 136 140 137 141 """ 138 cherrypy.response.code = 501139 142 msg = "KARL25 responding\n" 140 143 msg += "user with id: '%s' should not be saved.\n" % id 141 144 msg += "An exception occurred: %r (%s)" % ((tg_exceptions,)*2) … … 165 168 def test_implicit_trans_no_error(): 166 169 """If a controller runs sucessfully, the transaction is commited.""" 167 170 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 171 app = make_app(MyRoot) 172 response = app.get("/no_error?name=A.%20Dent") 172 173 print_log() 173 174 q = session.query(Person) 174 175 arthur = q.filter_by(name="A. Dent").first() 175 assert 'someconfirmhandler' in output, \176 assert 'someconfirmhandler' in response, \ 176 177 'The no error should have redirected to someconfirmhandler' 177 178 assert arthur is not None, 'Person arthur should have been saved!' 178 179 assert arthur.name == "A. Dent", 'Person arthur should be named "A. Dent"' … … 180 181 def test_raise_sa_exception(): 181 182 """If a controller causes an SA exception, it is raised properly.""" 182 183 capture_log("turbogears.database") 183 cherrypy.root = MyRoot() 184 create_request("/create_person?id=20") 185 output = cherrypy.response.body[0] 184 app = make_app(MyRoot) 185 response = app.get("/create_person?id=20") 186 186 print_log() 187 print output 188 assert 'No exceptions occurred' in output 189 assert cherrypy.response.status.startswith("200") 190 create_request("/create_person?id=20") 191 output = cherrypy.response.body[0] 192 assert cherrypy.response.status.startswith("500") 193 print output 194 assert 'KARL25' not in output, \ 187 assert 'No exceptions occurred' in response 188 response = app.get("/create_person?id=20", status=500) 189 assert 'KARL25' not in response, \ 195 190 'Exception should NOT have been handled by our handler' 196 assert 'DBAPIError' in output, \191 assert 'DBAPIError' in response, \ 197 192 'The page should have displayed an SQLAlchemy exception' 198 193 199 194 def test_user_exception(): 200 195 """If a controller raises an exception, transactions are rolled back.""" 201 196 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] 197 app = make_app(MyRoot) 198 response = app.get("/create_person?id=19&docom=0&doerr=1&name=Martin%20GAL") 205 199 print_log() 206 print output 207 assert 'KARL25' in output, \ 200 assert 'KARL25' in response, \ 208 201 'The exception handler should have answered us' 209 202 p = session.query(Person).get(19) 210 203 assert p is None, \ … … 212 205 213 206 def test_user_redirect(): 214 207 """If a controller redirects, transactions are committed.""" 215 cherrypy.root = MyRoot()216 create_request("/create_person?id=22&doerr=2")208 app = make_app(MyRoot) 209 app.get("/create_person?id=22&doerr=2") 217 210 assert session.query(Person).get(22) is not None, \ 218 211 'The controller only redirected, the Person should have been saved' 219 212 220 213 def test_cntrl_commit(): 221 214 """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]215 app = make_app(MyRoot) 216 response = app.get("/create_person?id=23&docom=1") 217 assert 'InvalidRequestError' not in response 225 218 assert session.query(Person).get(23) is not None, \ 226 219 'The Person 23 should have been saved during commit inside controller' 227 220 228 221 def test_cntrl_commit2(): 229 222 """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]223 app = make_app(MyRoot) 224 response = app.get("/create_person?id=24&docom=1&doerr=1") 225 assert 'InvalidRequestError' not in response 233 226 assert session.query(Person).get(24) is not None, \ 234 227 'The Person 24 should have been saved during commit' \ 235 228 ' inside controller and not rolled back' 236 229 237 230 def test_cntrl_flush(): 238 231 """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] 232 app = make_app(MyRoot) 233 response = app.get("/create_person?id=25&doflush=1") 234 assert 'No exceptions occurred' in response 235 response = app.get("/create_person?id=25&doflush=0", status=500) 236 assert 'IntegrityError' in response 237 response = app.get("/create_person?id=25&doflush=1") 238 assert 'IntegrityError' in response 239 response = app.get("/create_person?id=25&doflush=2") 240 assert 'No exceptions occurred' in response 252 241 253 242 254 243 # Exception handling with rollback … … 301 290 is created by the exception handler. 302 291 303 292 """ 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' 293 app = make_app(RbRoot) 294 response = app.get('/doerr?id=26') 295 assert 'KARL27' in response, 'Exception handler should have answered' 309 296 assert session.query(User).get(26) is None 310 297 assert session.query(User).get(27) is not None 311 298 … … 316 303 so user XX should not exist. 317 304 318 305 """ 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' 306 app = make_app(RbRoot) 307 response = app.get('/doerr?id=XX') 308 assert 'KARL27' in response, 'Exception handler should have answered' 323 309 assert session.query(User).get('XX') is None 324 310 325 311 def test_exc_done_rollback(): 326 312 """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' 313 app = make_app(RbRoot) 314 response = app.get('/doerr?id=28&dorb=1') 315 assert 'KARL27' in response, 'Exception handler should have answered' 331 316 assert session.query(User).get(28) is None 332 317 assert session.query(User).get(29) is not None 333 318 … … 360 345 361 346 """ 362 347 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] 348 app = make_app(FreshRoot) 349 response = app.get("/test1", status = 200) 350 assert 'AssertionError' not in response 367 351 # Call test2 in a different thread 368 352 class ThreadB(threading.Thread): 369 353 def run(self): 370 create_request("/test2") 371 assert cherrypy.response.status.startswith("200") 372 assert 'AssertionError' not in cherrypy.response.body[0] 354 response = app.get("/test2", status=200) 355 assert 'AssertionError' not in response 373 356 thrdb = ThreadB() 374 357 thrdb.start() 375 358 thrdb.join() 376 create_request("/test3") 377 assert cherrypy.response.status.startswith("200") 378 assert 'AssertionError' not in cherrypy.response.body[0] 359 response = app.get("/test3", status=200) 360 assert 'AssertionError' not in response -
turbogears/tests/test_expose.py
old new 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 make_app, start_server, stop_server 6 4 5 def setup_module(): 6 start_server() 7 7 8 def teardown_module(): 9 stop_server() 10 11 8 12 class ExposeRoot(controllers.RootController): 9 13 10 14 @expose("turbogears.tests.simple") … … 20 24 21 25 22 26 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 27 app = make_app(ExposeRoot) 28 response = app.get("/with_json") 29 assert "Paging all foo" in response 27 30 28 31 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 32 app = make_app(ExposeRoot) 33 response = app.get("/with_json?tg_format=json") 34 assert '"title": "Foobar"' in response 33 35 34 36 def test_gettingjsonviaaccept(): 35 cherrypy.root = ExposeRoot()36 create_request("/with_json_via_accept",37 app = make_app(ExposeRoot) 38 response = app.get("/with_json_via_accept", 37 39 headers=dict(Accept="text/javascript")) 38 body = cherrypy.response.body[0] 39 assert '"title": "Foobar"' in body 40 assert '"title": "Foobar"' in response 40 41 41 42 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 43 app = make_app(ExposeRoot) 44 response = app.get("/with_json_via_accept?tg_format=json") 45 assert '"title": "Foobar"' in response 46 46 47 47 def test_getting_plaintext(): 48 cherrypy.root = ExposeRoot()49 create_request("/with_json_via_accept",48 app = make_app(ExposeRoot) 49 response = app.get("/with_json_via_accept", 50 50 headers=dict(Accept="text/plain")) 51 print cherrypy.response.body[0] 52 assert cherrypy.response.body[0] == "This is a plain text for foo." 51 assert response.body == "This is a plain text for foo." 53 52 54 53 def test_allow_json(): 55 54 … … 58 57 def test(self): 59 58 return dict(title="Foobar", mybool=False, someval="niggles") 60 59 61 cherrypy.root = NewRoot() 62 create_request("/test", headers= dict(accept="text/javascript")) 63 body = cherrypy.response.body[0] 64 values = simplejson.loads(body) 60 app = make_app(NewRoot) 61 response = app.get("/test", headers= dict(accept="text/javascript")) 62 values = simplejson.loads(response.body) 65 63 assert values == dict(title="Foobar", mybool=False, someval="niggles", 66 64 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) 65 assert response.headers["Content-Type"] == "text/javascript" 66 response = app.get("/test?tg_format=json") 67 values = simplejson.loads(response.body) 71 68 assert values == dict(title="Foobar", mybool=False, someval="niggles", 72 69 tg_flash=None) 73 assert cherrypy.response.headers["Content-Type"] == "text/javascript"70 assert response.headers["Content-Type"] == "text/javascript" -
turbogears/tests/test_controllers.py
old new 1 1 import unittest 2 import simplejson 2 3 import formencode 3 4 import cherrypy 4 5 import pkg_resources … … 18 19 19 20 @expose() 20 21 def index(self): 21 pass22 return dict() 22 23 23 24 def validation_error_handler(self, tg_source, tg_errors, *args, **kw): 24 self.functionname = tg_source.__name__ 25 self.values = kw 26 self.errors = tg_errors 27 return "Error Message" 25 errors = {} 26 for (key, value) in tg_errors.items(): 27 if hasattr(value, 'msg'): 28 errors[key] = value.msg 29 else: 30 errors[key] = value 31 return dict(msg = "Error Message", values = kw, errors = errors, 32 functionname = tg_source.__name__) 28 33 34 29 35 @expose(html="turbogears.tests.simple", allow_json=True) 30 36 def test(self): 31 37 return dict(title="Foobar", mybool=False, someval="niggles") … … 36 42 37 43 @expose() 38 44 def pos(self, posvalue): 39 self.posvalue = posvalue 40 return "" 45 return dict(posvalue = posvalue) 41 46 42 47 @expose() 43 48 def servefile(self, tg_exceptions=None): … … 48 53 "turbogears.tests", "test_controllers.py")) 49 54 50 55 @expose() 51 def unicode(self): 52 cherrypy.response.headers["Content-Type"] = "text/html" 56 def unicode(self, response=None): 57 if response is None: 58 response = cherrypy.response 59 response.headers["Content-Type"] = "text/html" 53 60 return u'\u00bfHabla espa\u00f1ol?' 54 61 55 62 @expose() … … 82 89 @validate(validators={'value': validators.StringBoolean()}) 83 90 @error_handler(istrue) 84 91 def errorchain(self, value): 85 return "No Error"92 return {'error' : "No Error", 'value' : self.value} 86 93 87 94 @expose(format="json", html="turbogears.tests.simple") 88 95 def returnjson(self): … … 117 124 "lastname": validators.String()}) 118 125 @error_handler(validation_error_handler) 119 126 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 127 fullname = "%s %s" % (firstname, lastname) 128 return dict(firstname = firstname, lastname = lastname, 129 fullname = fullname, submit = submit) 125 130 131 126 132 class Registration(formencode.Schema): 127 133 allow_extra_fields = True 128 134 firstname = validators.String(min=2, not_empty=True) … … 171 177 def flash_redirected(self): 172 178 return dict(title="Foobar", mybool=False, someval="niggles") 173 179 180 @expose() 181 def redirect(self): 182 redirect("/foo") 183 184 @expose() 185 def raise_redirect(self): 186 raise redirect("/foo") 187 174 188 @expose(html="turbogears.tests.simple", allow_json=True) 175 189 def flash_redirect_with_trouble_chars(self): 176 190 flash(u"$foo, k\xe4se;\tbar!") … … 220 234 return "redirected OK" 221 235 222 236 223 class TestRoot( unittest.TestCase):237 class TestRoot(testutil.TGWebTest): 224 238 225 239 def setUp(self): 226 cherrypy.root = None 227 cherrypy.tree.mount_points = {} 228 cherrypy.tree.mount(MyRoot(), "/") 229 cherrypy.tree.mount(SubApp(), "/subthing") 240 testutil.mount(MyRoot(), "/") 241 testutil.mount(SubApp(), "/subthing") 242 testutil.TGWebTest.setUp(self) 230 243 231 def tearDown(self): 232 cherrypy.root = None 233 cherrypy.tree.mount_points = {} 234 244 235 245 def test_js_files(self): 236 246 """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" 247 response = self.app.get("/tg_js/MochiKit.js", status=200) 248 assert response.headers["Content-Type"] == "application/x-javascript" 241 249 242 250 def test_json_output(self): 243 testutil.create_request("/test?tg_format=json") 244 import simplejson 245 values = simplejson.loads(cherrypy.response.body[0]) 251 response = self.app.get("/test?tg_format=json") 252 values = simplejson.loads(response.body) 246 253 assert values == dict(title="Foobar", mybool=False, 247 254 someval="niggles", tg_flash=None) 248 assert cherrypy.response.headers["Content-Type"] == "text/javascript"255 assert response.headers["Content-Type"] == "text/javascript" 249 256 250 257 def test_implied_json(self): 251 testutil.create_request("/impliedjson?tg_format=json")252 assert '"title": "Blah"' in cherrypy.response.body[0]258 response = self.app.get("/impliedjson?tg_format=json") 259 assert '"title": "Blah"' in response 253 260 254 261 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" 262 response = self.app.get("/allowjson?tg_format=json", status=500) 263 assert response.headers["Content-Type"] == "text/html" 258 264 259 265 def test_allow_json_config(self): 260 266 """JSON output can be enabled via config.""" … … 264 270 def allowjsonconfig(self): 265 271 return dict(title="Foobar", mybool=False, someval="foo", 266 272 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"273 app = testutil.make_app(JSONRoot) 274 response = app.get('/allowjsonconfig?tg_format=json') 275 assert response.headers["Content-Type"] == "text/javascript" 270 276 config.update({'tg.allow_json': False}) 271 277 272 278 def test_allow_json_config_false(self): … … 277 283 def allowjsonconfig(self): 278 284 return dict(title="Foobar", mybool=False, someval="foo", 279 285 tg_html="turbogears.tests.simple") 280 cherrypy.root = JSONRoot()281 testutil.create_request('/allowjsonconfig')282 assert cherrypy.response.status.startswith("200")283 testutil.create_request('/allowjsonconfig?tg_format=json')284 assert cherrypy.response.status.startswith("500")285 assert cherrypy.response.headers["Content-Type"] == "text/html"286 testutil.stop_server() 287 app = testutil.make_app(JSONRoot) 288 testutil.start_server() 289 response = app.get('/allowjsonconfig') 290 response = app.get('/allowjsonconfig?tg_format=json', status=500) 291 assert response.headers["Content-Type"] == "text/html" 286 292 config.update({'tg.allow_json': True}) 287 293 288 294 def test_json_error(self): 289 295 """The error handler should return JSON if requested.""" 290 testutil.create_request("/jsonerror") 291 assert cherrypy.response.headers["Content-Type"] == "text/html; charset=utf-8" 292 assert "Paging all errors" in cherrypy.response.body[0] 293 testutil.create_request("/jsonerror?tg_format=json") 294 assert cherrypy.response.headers["Content-Type"] == "text/javascript" 295 assert '"someval": "errors"' in cherrypy.response.body[0] 296 response = self.app.get("/jsonerror") 297 assert response.headers["Content-Type"] == "text/html; charset=utf-8" 298 assert "Paging all errors" in response.body 299 response = self.app.get("/jsonerror?tg_format=json") 300 print "Headers", response.headers 301 assert response.headers["Content-Type"] == "text/javascript" 302 print response.body 303 assert '"someval": "errors"' in response.body 296 304 297 305 def test_invalid_return(self): 298 testutil.create_request("/invalid") 299 assert cherrypy.response.status.startswith("500") 306 response = self.app.get("/invalid", status=500) 300 307 301 308 def test_strict_parameters(self): 302 309 config.update({"tg.strict_parameters": True}) 303 testutil.create_request(304 "/save?submit=save&firstname=Foo&lastname=Bar&badparam=1" )305 assert cherrypy.response.status.startswith("500")310 response = self.app.get( 311 "/save?submit=save&firstname=Foo&lastname=Bar&badparam=1", 312 status=500) 306 313 assert not hasattr(cherrypy.root, "errors") 307 314 308 315 def test_throw_out_random(self): 309 316 """Can append random value to the URL to avoid caching problems.""" 310 testutil.create_request("/test?tg_random=1")311 assert "Paging all niggles" in cherrypy.response.body[0]317 response = self.app.get("/test?tg_random=1") 318 assert "Paging all niggles" in response 312 319 config.update({"tg.strict_parameters": True}) 313 testutil.create_request("/test?tg_random=1") 314 assert cherrypy.response.status.startswith("200") 315 assert "Paging all niggles" in cherrypy.response.body[0] 316 testutil.create_request("/test?tg_not_random=1") 317 assert cherrypy.response.status.startswith("500") 320 response = self.app.get("/test?tg_random=1", status=200) 321 assert "Paging all niggles" in response 322 response = self.app.get("/test?tg_not_random=1", status=500) 318 323 assert not hasattr(cherrypy.root, "errors") 319 324 320 325 def test_ignore_parameters(self): 321 326 config.update({"tg.strict_parameters": True}) 322 testutil.create_request("/test?ignore_me=1") 323 assert cherrypy.response.status.startswith("500") 327 response = self.app.get("/test?ignore_me=1", status=500) 324 328 assert not hasattr(cherrypy.root, "errors") 325 329 config.update({"tg.ignore_parameters": ['ignore_me', 'me_too']}) 326 testutil.create_request("/test?ignore_me=1") 327 assert "Paging all niggles" in cherrypy.response.body[0] 328 testutil.create_request("/test?me_too=1") 329 assert cherrypy.response.status.startswith("200") 330 assert "Paging all niggles" in cherrypy.response.body[0] 331 testutil.create_request("/test?me_not=1") 332 assert cherrypy.response.status.startswith("500") 330 response = self.app.get("/test?ignore_me=1") 331 assert "Paging all niggles" in response 332 response = self.app.get("/test?me_too=1", status=200) 333 assert "Paging all niggles" in response 334 response = self.app.get("/test?me_not=1", status=500) 333 335 assert not hasattr(cherrypy.root, "errors") 334 336 335 337 def test_retrieve_dict_directly(self): 336 d = testutil.call(cherrypy.root.returnjson)337 assert d["title"] == "Foobar"338 response = self.app.get('/returnjson') 339 assert response.raw["title"] == "Foobar" 338 340 339 341 def test_templateOutput(self): 340 testutil.create_request("/test")341 assert "Paging all niggles" in cherrypy.response.body[0]342 response = self.app.get("/test") 343 assert "Paging all niggles" in response 342 344 343 345 def test_safari_unicode_fix(self): 344 testutil.create_request("/unicode", headers={'User-Agent':346 response = self.app.get("/unicode", headers={'User-Agent': 345 347 "Apple WebKit Safari/412.2"}) 346 firstline = cherrypy.response.body[0].split('\n')[0]348 firstline = response.body.split('\n')[0] 347 349 assert firstline == "¿Habla español?" 348 350 assert isinstance(firstline, str) 349 351 350 352 def test_default_format(self): 351 353 """The default format can be set via expose""" 352 testutil.create_request("/returnjson") 353 firstline = cherrypy.response.body[0] 354 assert '"title": "Foobar"' in firstline 355 testutil.create_request("/returnjson?tg_format=html") 356 assert cherrypy.response.status.startswith("500") 357 firstline = cherrypy.response.body[0] 358 assert '"title": "Foobar"' not in firstline 354 response = self.app.get("/returnjson") 355 assert '"title": "Foobar"' in response 356 response = self.app.get("/returnjson?tg_format=html", status=500) 359 357 360 358 def test_content_type(self): 361 359 """The content-type can be set via expose""" 362 testutil.create_request("/contenttype")363 assert cherrypy.response.headers["Content-Type"] == "xml/atom"360 response = self.app.get("/contenttype") 361 assert response.headers["Content-Type"] == "xml/atom" 364 362 365 363 def test_returned_template_name(self): 366 testutil.create_request("/returnedtemplate")367 data = cherrypy.response.body[0].lower()364 response = self.app.get("/returnedtemplate") 365 data = response.body.lower() 368 366 assert "<body>" in data 369 367 assert 'groovy test template' in data 370 368 371 369 def test_returned_template_short(self): 372 testutil.create_request("/returnedtemplate_short")373 assert "Paging all foo" in cherrypy.response.body[0]370 response = self.app.get("/returnedtemplate_short") 371 assert "Paging all foo" in response 374 372 375 373 def test_expose_template_short(self): 376 testutil.create_request("/exposetemplate_short")377 assert "Paging all foo" in cherrypy.response.body[0]374 response = self.app.get("/exposetemplate_short") 375 assert "Paging all foo" in response 378 376 379 377 def test_validation(self): 380 378 """Data can be converted and validated""" 381 testutil.create_request("/istrue?value=true") 382 assert cherrypy.root.value is True 383 testutil.create_request("/istrue?value=false") 384 assert cherrypy.root.value is False 385 cherrypy.root = MyRoot() 386 testutil.create_request("/istrue?value=foo") 387 assert not hasattr(cherrypy.root, "value") 388 assert cherrypy.root.functionname == "istrue" 389 testutil.create_request("/save?submit=send&firstname=John&lastname=Doe") 390 assert cherrypy.root.fullname == "John Doe" 391 assert cherrypy.root.submit == "send" 392 testutil.create_request("/save?submit=send&firstname=Arthur") 393 assert cherrypy.root.fullname == "Arthur Miller" 394 testutil.create_request("/save?submit=send&firstname=Arthur&lastname=") 395 assert cherrypy.root.fullname == "Arthur " 396 testutil.create_request("/save?submit=send&firstname=D&lastname=") 397 assert len(cherrypy.root.errors) == 1 398 assert cherrypy.root.errors.has_key("firstname") 399 assert "characters" in cherrypy.root.errors["firstname"].msg.lower() 400 testutil.create_request("/save?submit=send&firstname=&lastname=") 401 assert len(cherrypy.root.errors) == 1 402 assert cherrypy.root.errors.has_key("firstname") 379 response = self.app.get("/istrue?value=true") 380 assert response.body == 'True' 381 response = self.app.get("/istrue?value=false") 382 assert response.body == 'False' 403 383 384 app = testutil.make_app(MyRoot) 385 response = app.get("/istrue?value=foo") 386 assert response.raw['msg'] == 'Error Message' 387 388 response = app.get("/save?submit=send&firstname=John&lastname=Doe") 389 assert response.raw['fullname'] == "John Doe" 390 assert response.raw['submit'] == "send" 391 response = app.get("/save?submit=send&firstname=Arthur") 392 assert response.raw['fullname'] == "Arthur Miller" 393 response = app.get("/save?submit=send&firstname=Arthur&lastname=") 394 assert response.raw['fullname'] == "Arthur " 395 response = app.get("/save?submit=send&firstname=D&lastname=") 396 assert len(response.raw['errors'].keys()) == 1 397 assert response.raw['errors'].has_key("firstname") 398 assert "characters" in response.raw['errors']["firstname"].lower() 399 response = app.get("/save?submit=send&firstname=&lastname=") 400 assert len(response.raw['errors'].keys()) == 1 401 assert response.raw['errors'].has_key("firstname") 402 404 403 def test_validation_chained(self): 405 404 """Validation is not repeated if it already happened""" 406 405 cherrypy.root.value = None 407 testutil.create_request("/errorchain?value=true")406 response = self.app.get("/errorchain?value=true") 408 407 assert cherrypy.root.value is None 409 testutil.create_request("/errorchain?value=notbool") 408 assert response.raw['value'] is None 409 self.app.get("/errorchain?value=notbool") 410 410 assert cherrypy.root.value == 'notbool' 411 assert 'No Error' in response.body 412 assert response.raw['value'] is None 411 413 412 414 def test_validation_nested(self): 413 415 """Validation is not repeated in nested method call""" 414 416 cherrypy.root.value = None 415 testutil.create_request("/nestedcall?value=true")417 response = self.app.get("/nestedcall?value=true") 416 418 assert cherrypy.root.value == 'True' 417 testutil.create_request("/nestedcall?value=false")419 self.app.get("/nestedcall?value=false") 418 420 assert cherrypy.root.value == 'False' 419 421 420 422 def test_validation_with_schema(self): 421 423 """Data can be converted/validated with formencode.Schema instance""" 422 testutil.create_request("/save2?submit=send&firstname=Joe&lastname=Doe")423 assert cherrypy.root.fullname== "Joe Doe"424 assert cherrypy.root.submit== "send"425 testutil.create_request("/save2?submit=send&firstname=Arthur&lastname=")426 assert cherrypy.root.fullname== "Arthur "427 testutil.create_request("/save2?submit=send&firstname=&lastname=")428 assert len( cherrypy.root.errors) == 1429 assert cherrypy.root.errors.has_key("firstname")430 testutil.create_request("/save2?submit=send&firstname=D&lastname=")431 assert len( cherrypy.root.errors) == 1432 assert cherrypy.root.errors.has_key("firstname")424 response = self.app.get("/save2?submit=send&firstname=Joe&lastname=Doe") 425 assert response.raw['fullname'] == "Joe Doe" 426 assert response.raw['submit'] == "send" 427 response = self.app.get("/save2?submit=send&firstname=Arthur&lastname=") 428 assert response.raw['fullname'] == "Arthur " 429 response = self.app.get("/save2?submit=send&firstname=&lastname=") 430 assert len(response.raw['errors']) == 1 431 assert response.raw['errors'].has_key("firstname") 432 response = self.app.get("/save2?submit=send&firstname=D&lastname=") 433 assert len(response.raw['errors']) == 1 434 assert response.raw['errors'].has_key("firstname") 433 435 434 436 def test_other_template(self): 435 437 """'tg_html' in a returned dict will use the template specified there""" 436 testutil.create_request("/useother")437 assert "This is the other template" in cherrypy.response.body[0]438 response = self.app.get("/useother") 439 assert "This is the other template" in response 438 440 439 441 def test_cheetah_template(self): 440 442 """Cheetah templates can be used as well""" 441 testutil.create_request("/usecheetah") 442 body = cherrypy.response.body[0] 443 assert "This is the Cheetah test template." in body 444 assert "Paging all chimps." in body 443 response = self.app.get("/usecheetah") 444 assert "This is the Cheetah test template." in response 445 assert "Paging all chimps." in response 445 446 446 447 def test_run_with_trans(self): 447 448 """run_with_transaction is called only on topmost exposed method""" 448 449 oldrwt = database.run_with_transaction 449 450 database.run_with_transaction = cherrypy.root.rwt 450 testutil.create_request("/nestedcall?value=true")451 self.app.get("/nestedcall?value=true") 451 452 database.run_with_transaction = oldrwt 452 453 assert cherrypy.root.value 453 454 assert cherrypy.root.rwt_called == 1 454 455 455 456 def test_positional(self): 456 457 """Positional parameters should work""" 457 testutil.create_request("/pos/foo")458 assert cherrypy.root.posvalue== "foo"458 response = self.app.get("/pos/foo") 459 assert response.raw['posvalue'] == "foo" 459 460 460 461 def test_flash_plain(self): 461 462 """flash with strings should work""" 462 testutil.create_request("/flash_plain?tg_format=json") 463 import simplejson 464 values = simplejson.loads(cherrypy.response.body[0]) 463 response = self.app.get("/flash_plain?tg_format=json") 464 values = simplejson.loads(response.body) 465 465 assert values["tg_flash"] == "plain" 466 assert not cherrypy.response.simple_cookie.has_key("tg_flash")466 assert not response.headers.has_key("tg_flash") 467 467 468 468 def test_flash_unicode(self): 469 469 """flash with unicode objects should work""" 470 testutil.create_request("/flash_unicode?tg_format=json") 471 import simplejson 472 values = simplejson.loads(cherrypy.response.body[0]) 470 response = self.app.get("/flash_unicode?tg_format=json") 471 values = simplejson.loads(response.body) 473 472 assert values["tg_flash"] == u"\xfcnicode" 474 assert not cherrypy.response.simple_cookie.has_key("tg_flash")473 assert not response.headers.has_key("tg_flash") 475 474 476 475 def test_flash_on_redirect(self): 477 476 """flash must survive a redirect""" 478 testutil.create_request("/flash_redirect?tg_format=json") 479 assert cherrypy.response.status.startswith("302") 480 testutil.create_request(cherrypy.response.headers["Location"], 481 headers=dict(Cookie=cherrypy.response.simple_cookie.output( 482 header="").strip())) 483 import simplejson 484 values = simplejson.loads(cherrypy.response.body[0]) 477 response = self.app.get("/flash_redirect?tg_format=json", status=302) 478 response = self.app.get(response.location, 479 headers=dict(Cookie=response.headers['Set-Cookie'])) 480 values = simplejson.loads(response.body) 485 481 assert values["tg_flash"] == u"redirect \xfcnicode" 486 482 487 483 def test_flash_redirect_with_trouble_chars(self): 488 484 """flash redirect with chars that can cause troubles in cookies""" 489 testutil.create_request("/flash_redirect_with_trouble_chars?tg_format=json") 490 assert cherrypy.response.status.startswith("302") 491 value = cherrypy.response.simple_cookie["tg_flash"].value 492 assert '$' not in value 493 assert ',' not in value and ';' not in value 494 assert ' ' not in value and '\t' not in value 495 assert 'foo' in value and 'bar' in value 496 assert u'k\xe4se'.encode('utf-8') in value 497 assert '!' in value 498 testutil.create_request(cherrypy.response.headers["Location"], 499 headers=dict(Cookie=cherrypy.response.simple_cookie.output( 500 header="").strip())) 501 import simplejson 502 values = simplejson.loads(cherrypy.response.body[0]) 485 response = self.app.get("/flash_redirect_with_trouble_chars?tg_format=json", status=302) 486 response = self.app.get(response.location, 487 headers=dict(Cookie=response.headers['Set-Cookie'])) 488 values = simplejson.loads(response.body) 503 489 assert values["tg_flash"] == u"$foo, k\xe4se;\tbar!" 504 490 505 491 def test_double_flash(self): … … 507 493 # Here we are calling method that sets a flash message. However flash 508 494 # cookie is still there. Turbogears should discard old flash message 509 495 # from cookie and use new one, set by flash_plain(). 510 testutil.create_request("/flash_plain?tg_format=json",496 response = self.app.get("/flash_plain?tg_format=json", 511 497 headers=dict(Cookie='tg_flash="old flash"; Path=/;')) 512 import simplejson 513 values = simplejson.loads(cherrypy.response.body[0]) 498 values = simplejson.loads(response.body) 514 499 assert values["tg_flash"] == "plain" 515 assert cherrypy.response.simple_cookie.has_key("tg_flash"), \500 assert response.cookies_set.has_key("tg_flash"), \ 516 501 "Cookie clearing request should be present" 517 flashcookie = cherrypy.response.simple_cookie['tg_flash']518 assert flashcookie['expires'] == 0519 502 520 503 def test_set_kid_outputformat_in_config(self): 521 504 """the outputformat for kid can be set in the config""" 522 505 config.update({'kid.outputformat': 'xhtml'}) 523 testutil.create_request('/test') 524 response = cherrypy.response.body[0] 506 response = self.app.get('/test') 525 507 assert '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML ' in response 526 508 config.update({'kid.outputformat': 'html'}) 527 testutil.create_request('/test') 528 response = cherrypy.response.body[0] 509 response = self.app.get('/test') 529 510 assert '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML ' in response 530 511 assert ' This is the groovy test ' in response 531 512 config.update({'kid.outputformat': 'html compact'}) 532 testutil.create_request('/test') 533 response = cherrypy.response.body[0] 513 response = self.app.get('/test') 534 514 assert '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML ' in response 535 515 assert 'This is the groovy test ' in response 536 516 assert ' ' not in response … … 538 518 def test_fileserving(self): 539 519 #outputcap = StringIO() 540 520 #sys.stdout = outputcap 541 testutil.create_request("/servefile")521 response = self.app.get("/servefile") 542 522 assert cherrypy.root.servedit 543 523 assert not cherrypy.root.serve_exceptions 544 524 #assert "AssertionError" not in outputcap.getvalue() 545 525 546 526 def test_internal_redirect(self): 547 527 """regression test for #1022, #1407 and #1598""" 548 testutil.create_request("/internal_redirect") 549 firstline = cherrypy.response.body[0] 550 assert "redirected OK" in firstline 528 response = self.app.get("/internal_redirect") 529 assert "redirected OK" in response 551 530 552 531 def test_internal_redirect_nested_variables(self): 553 532 """regression test for #1022, #1407 and #1598""" 554 testutil.create_request(533 response = self.app.get( 555 534 "/internal_redirect?a=1&a-1.b=2&a-2.c=3&a-2.c-1=4") 556 firstline = cherrypy.response.body[0] 557 assert "redirected OK" in firstline 535 assert "redirected OK" in response 558 536 559 537 def test_exc_value(self): 560 538 """Exception is handled gracefully by the right exception handler.""" 561 testutil.create_request("/raise_value_exc")562 assert 'handling_value' in cherrypy.response.body[0]539 response = self.app.get("/raise_value_exc") 540 assert 'handling_value' in response 563 541 564 542 def test_exc_index(self): 565 543 """Exception is handled gracefully by the right exception handler.""" 566 testutil.create_request("/raise_index_exc")567 assert 'handling_index' in cherrypy.response.body[0]544 response = self.app.get("/raise_index_exc") 545 assert 'handling_index' in response 568 546 569 547 def test_exc_all(self): 570 548 """Test a controller that is protected by multiple exception handlers. … … 573 551 by their respective handlers without problem... 574 552 575 553 """ 576 testutil.create_request("/raise_all_exc?num=1")577 assert 'handling_value' in cherrypy.response.body[0]578 testutil.create_request("/raise_all_exc?num=2")579 assert 'handling_index' in cherrypy.response.body[0]580 testutil.create_request("/raise_all_exc?num=3")581 assert 'handling_key' in cherrypy.response.body[0]554 response = self.app.get("/raise_all_exc?num=1") 555 assert 'handling_value' in response 556 response = self.app.get("/raise_all_exc?num=2") 557 assert 'handling_index' in response 558 response = self.app.get("/raise_all_exc?num=3") 559 assert 'handling_key' in response 582 560 583 561 584 class TestURLs( unittest.TestCase):562 class TestURLs(testutil.TGWebTest): 585 563 586 564 def setUp(self): 587 cherrypy.tree.mount_points = {}588 cherrypy.root = MyRoot()589 cherrypy.root.subthing = SubApp()590 cherrypy.root.subthing.subsubthing = SubApp()565 testutil.TGWebTest.setUp(self) 566 testutil.mount(MyRoot()) 567 testutil.mount(SubApp(), '/subthing') 568 testutil.mount(SubApp(), '/subthing/subsubthing') 591 569 592 570 def test_basic_urls(self): 593 testutil.create_request("/")571 self.app.get("/") 594 572 assert "/foo" == url("/foo") 595 573 assert "foo/bar" == url(["foo", "bar"]) 596 574 assert url("/foo", bar=1, baz=2) in \ … … 604 582 assert url("/foo") == "/foo" 605 583 606 584 def test_approots(self): 607 testutil.create_request("/subthing/") 585 config.update({"server.webpath": "/subthing"}) 586 self.app.get("/subthing/") 608 587 assert url("foo") == "foo" 609 588 assert url("/foo") == "/subthing/foo" 610 589 611 590 def test_lower_approots(self): 612 testutil.create_request("/subthing/subsubthing/") 591 config.update({"server.webpath": "/subthing/subsubthing"}) 592 self.app.get("/subthing/subsubthing/") 613 593 assert url("/foo") == "/subthing/subsubthing/foo" 614 594 615 def test_approots_With_path(self): 616 config.update({"server.webpath": "/coolsite/root"}) 617 startup.startTurboGears() 618 testutil.create_request("/coolsite/root/subthing/") 595 def test_approots_with_path(self): 596 config.update({"server.webpath": "/coolsite/root/subthing"}) 597 self.app.get("/subthing/") 619 598 assert url("/foo") == "/coolsite/root/subthing/foo" 620 599 621 600 def test_redirect(self): 622 601 config.update({"server.webpath": "/coolsite/root"}) 623 startup.startTurboGears() 624 testutil.create_request("/coolsite/root/subthing/") 625 try: 626 redirect("/foo") 627 assert False, "redirect exception should have been raised" 628 except cherrypy.HTTPRedirect, e: 629 assert "http://localhost/coolsite/root/subthing/foo" in e.urls 630 try: 631 raise redirect("/foo") 632 assert False, "redirect exception should have been raised" 633 except cherrypy.HTTPRedirect, e: 634 assert "http://localhost/coolsite/root/subthing/foo" in e.urls 602 response = self.app.get("/redirect") 603 assert response.location == 'http://localhost:80/coolsite/root/foo' 604 self.app.get("/raise_redirect") 605 assert response.location == 'http://localhost:80/coolsite/root/foo' 635 606 636 607 def test_multi_values(self): 637 testutil.create_request("/")608 self.app.get("/") 638 609 assert url("/foo", bar=[1, 2]) in \ 639 610 ["/foo?bar=1&bar=2", "/foo?bar=2&bar=1"] 640 611 assert url("/foo", bar=("asdf", "qwer")) in \ … … 642 613 643 614 def test_unicode(self): 644 615 """url() can handle unicode parameters""" 645 testutil.create_request("/")616 self.app.get("/") 646 617 assert url('/', x=u'\N{LATIN SMALL LETTER A WITH GRAVE}' 647 618 u'\N{LATIN SMALL LETTER E WITH GRAVE}' 648 619 u'\N{LATIN SMALL LETTER I WITH GRAVE}' … … 652 623 653 624 def test_list(self): 654 625 """url() can handle list parameters, with unicode too""" 655 testutil.create_request("/")626 self.app.get("/") 656 627 assert url('/', foo=['bar', u'\N{LATIN SMALL LETTER A WITH GRAVE}'] 657 628 ) == '/?foo=bar&foo=%C3%A0' 658 629 659 630 def tearDown(self): 631 testutil.TGWebTest.tearDown(self) 660 632 config.update({"server.webpath": ""}) 661 startup.startTurboGears()662 633 663 634 664 def test_index_trailing_slash(): 665 """If there is no trailing slash on an index method call, redirect""" 666 cherrypy.root = SubApp() 667 cherrypy.root.foo = SubApp() 668 testutil.create_request("/foo") 669 assert cherrypy.response.status.startswith("302") 635 def test_index_trailing_slash(self): 636 """If there is no trailing slash on an index method call, redirect""" 637 testutil.mount(SubApp(), '/') 638 testutil.mount(SubApp(), '/foo') 639 self.app.get("/foo", status=302) 670 640 671 def test_can_use_internally_defined_arguments():672 """Can use argument names that are internally used by TG in controllers"""641 def test_can_use_internally_defined_arguments(self): 642 """Can use argument names that are internally used by TG in controllers""" 673 643 674 class App(controllers.RootController):644 class App(controllers.RootController): 675 645 676 @expose()677 def index(self, **kw):678 return "\n".join(["%s:%s" % i for i in kw.iteritems()])646 @expose() 647 def index(self, **kw): 648 return "\n".join(["%s:%s" % i for i in kw.iteritems()]) 679 649 680 cherrypy.root = App() 681 testutil.create_request("/?format=foo&template=bar&fragment=boo") 682 output = cherrypy.response.body[0] 683 assert "format:foo" in output 684 assert "template:bar" in output 685 assert "fragment:boo" in output 650 testutil.mount(App(), '/') 651 response = self.app.get("/?format=foo&template=bar&fragment=boo") 652 assert "format:foo" in response 653 assert "template:bar" in response 654 assert "fragment:boo" in response 686 655 687 def test_url_kwargs_overwrite_tgparams():688 """Check keys in tgparams in call to url overwrite kw args"""689 params = {'spamm': 'eggs'}690 assert 'spamm=ham' in url('/foo', params, spamm='ham')656 def test_url_kwargs_overwrite_tgparams(self): 657 """Check keys in tgparams in call to url overwrite kw args""" 658 params = {'spamm': 'eggs'} 659 assert 'spamm=ham' in url('/foo', params, spamm='ham') 691 660 692 def test_url_doesnt_change_tgparams():693 """Test that url() does not change the dict passed as second arg"""694 params = {'spamm': 'eggs'}695 assert 'foo' in url('/foo', params, spamm='ham')696 assert params['spamm'] == 'eggs'661 def test_url_doesnt_change_tgparams(self): 662 """Test that url() does not change the dict passed as second arg""" 663 params = {'spamm': 'eggs'} 664 assert 'foo' in url('/foo', params, spamm='ham') 665 assert params['spamm'] == 'eggs' -
turbogears/tests/test_view.py
old new 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
old new 4 4 from turbogears import controllers 5 5 from turbogears import testutil 6 6 7 def setup_module(): 8 testutil.unmount() 9 testutil.mount(MyRoot()) 10 testutil.start_server() 11 12 def teardown_module(): 13 testutil.unmount() 14 testutil.stop_server() 15 7 16 class MyRoot(controllers.RootController): 8 17 def set_name(self, name): 9 18 cookies = cherrypy.response.simple_cookie … … 21 30 22 31 23 32 def test_browser_session(): 24 cherrypy.root = MyRoot()25 33 bs = testutil.BrowsingSession() 26 34 bs.goto('/get_name') 27 35 assert bs.response == 'cookie not found' … … 30 38 assert bs.response == 'me' 31 39 32 40 def test_browser_session_for_two_users(): 33 cherrypy.root = MyRoot()34 41 bs1 = testutil.BrowsingSession() 35 42 bs2 = testutil.BrowsingSession() 36 43 bs1.goto('/set_name?name=bs1') -
turbogears/tests/test_catwalk.py
old new 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 … … 40 39 pass 41 40 index = turbogears.expose()(index) 42 41 42 43 def setup_module(): 44 #testutil.unmount() 45 testutil.mount(MyRoot(), "/") 46 testutil.mount(CatWalk(browse), '/catwalk') 47 testutil.start_server() 48 49 def teardown_module(): 50 #testutil.unmount() 51 testutil.stop_server() 52 53 54 #app = testutil.make_app() 55 43 56 class Browse(unittest.TestCase): 44 57 def setUp(self): 45 58 browse_data(browse) 46 cherrypy.root = MyRoot() 59 self.app = testutil.make_app() 60 #testutil.start_server() 61 #testutil.mount(MyRoot(), "/") 62 #testutil.mount(CatWalk(browse), '/catwalk') 47 63 64 def tearDown(self): 65 #testutil.stop_server() 66 pass 67 48 68 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] 69 response = self.app.get("/catwalk/browse/?object_name=Song&filters=Guantanemera&tg_format=json") 52 70 assert 'filter_format_error' in response 53 71 54 72 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] 73 response = self.app.get("/catwalk/browse/?object_name=Song&filters=guacamole:2&tg_format=json") 58 74 assert 'filter_column_error' in response 59 75 60 76 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) 77 response = self.app.get("/catwalk/browse/?object_name=Song&tg_format=json") 78 values = simplejson.loads(response.body) 65 79 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) 80 response = self.app.get("/catwalk/browse/?object_name=Song&filters=album:1&tg_format=json") 81 #values = simplejson.loads(response.body) 82 response.headers['Content-Type'] = 'application/json' 83 values = response.json 69 84 assert values['total'] == 15 #filter by album id (only 15 songs) 70 85 71 86 def test_response_fields(self): 72 87 #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) 88 response = self.app.get("/catwalk/browse/?object_name=Artist&start=3&page_size=20&tg_format=json") 89 values = simplejson.loads(response.body) 77 90 assert values.has_key('headers') 78 91 assert values.has_key('rows') 79 92 assert values.has_key('start') … … 86 99 def test_rows_joins_count(self): 87 100 #Control that the count for related and multiple joins match 88 101 #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) 102 response = self.app.get("/catwalk/browse/?object_name=Artist&tg_format=json") 103 values = simplejson.loads(response.body) 93 104 artist = browse.Artist.get(1) 94 105 assert int(values['rows'][0]['genres']) == len(list(artist.genres)) 95 106 assert int(values['rows'][0]['albums']) == len(list(artist.albums)) 96 107 97 108 def test_rows_column_number(self): 98 109 #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) 110 response = self.app.get("/catwalk/browse/?object_name=Artist&tg_format=json") 111 values = simplejson.loads(response.body) 103 112 assert len(values['rows'][0]) == 4 104 113 105 114 def test_rows_limit(self): 106 115 #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) 116 response = self.app.get("/catwalk/browse/?object_name=Artist&tg_format=json") 117 values = simplejson.loads(response.body) 111 118 assert values.has_key('rows') 112 119 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 )120 121 response = self.app.get("/catwalk/browse/?object_name=Artist&page_size=15&tg_format=json") 122 values = simplejson.loads(response.body) 116 123 assert values.has_key('rows') 117 124 assert len(values['rows']) == 15 118 125 119 126 def test_header_labels(self): 120 127 #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) 128 response = self.app.get("/catwalk/browse/?object_name=Artist&tg_format=json") 129 values = simplejson.loads(response.body) 125 130 assert len(values['headers']) == 5 126 131 for header in values['headers']: 127 132 assert header['name'] in ['id','name','albums','genres', 'plays_instruments'] … … 131 136 model = browse 132 137 133 138 def setUp(self): 134 cherrypy.root = MyRoot() 135 cherrypy.root.catwalk = CatWalk(browse) 139 #testutil.start_server() 140 testutil.mount(MyRoot(), "/") 141 testutil.mount(CatWalk(browse), '/catwalk') 136 142 testutil.DBTest.setUp(self) 137 143 browse_data(browse) 144 self.app = testutil.make_app() 138 145 146 def tearDown(self): 147 #testutil.stop_server() 148 testutil.DBTest.tearDown(self) 149 139 150 def test_addremove_related_joins(self): 140 151 # check the update_join function when nondefault add/remove are used 141 152 artist = self.model.Artist.get(1) 142 153 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")154 self.app.get("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1%2C2&tg_format=json") 144 155 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")156 self.app.get("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1&tg_format=json") 146 157 assert len(artist.plays_instruments) == 1, str(artist.plays_instruments) -
turbogears/tests/test_paginate.py
old new 4 4 from urllib import quote 5 5 import warnings 6 6 7 from turbogears import config, expose, database 7 from turbogears import config, expose, database, testutil 8 8 from turbogears.controllers import RootController, url 9 9 from turbogears.database import get_engine, metadata, session, mapper 10 10 from turbogears.paginate import paginate, sort_ordering, sort_data 11 from turbogears.testutil import create_request,sqlalchemy_cleanup11 from turbogears.testutil import sqlalchemy_cleanup 12 12 from turbojson.jsonify import jsonify 13 13 14 14 import cherrypy … … 183 183 return result 184 184 185 185 186 class TestSpy( unittest.TestCase):186 class TestSpy(testutil.TGWebTest): 187 187 """Never trust a spy""" 188 188 189 189 class MyRoot(RootController): … … 218 218 219 219 220 220 def setUp(self): 221 cherrypy.root = self.MyRoot() 221 testutil.TGWebTest.setUp(self) 222 self.app = testutil.make_app(self.MyRoot) 222 223 223 224 def test_spy(self): 224 create_request('/spy') 225 body = cherrypy.response.body[0] 226 Spy.assert_ok(body, 'current_page', 1) 225 response = self.app.get('/spy') 226 Spy.assert_ok(response.body, 'current_page', 1) 227 227 try: 228 Spy.assert_ok( body, 'current_page', 2)228 Spy.assert_ok(response.body, 'current_page', 2) 229 229 raise Exception("above test should have failed") 230 230 except AssertionError: 231 231 pass 232 232 233 233 def test_correct_expectation(self): 234 create_request('/spy_correct_expectation') 235 body = cherrypy.response.body[0] 236 assert "ok: [paginate" in body 234 response = self.app.get('/spy_correct_expectation') 235 assert "ok: [paginate" in response 237 236 238 237 def test_wrong_expectation(self): 239 create_request('/spy_wrong_expectation') 240 body = cherrypy.response.body[0] 241 assert "fail: expected page_count=9, got page_count=10" in body 238 response = self.app.get('/spy_wrong_expectation') 239 assert "fail: expected page_count=9, got page_count=10" in response 242 240 243 241 def test_invalid_expectation(self): 244 create_request('/spy_invalid_expectation') 245 body = cherrypy.response.body[0] 246 assert "fail: paginate does not have 'foobar' attribute" in body 242 response = self.app.get('/spy_invalid_expectation') 243 assert "fail: paginate does not have 'foobar' attribute" in response 247 244 248 245 def test_raw_expectation(self): 249 create_request('/spy_correct_expectation')250 Spy.assert_ok( cherrypy.response.body[0], 'var_name', 'data')251 Spy.assert_ok( cherrypy.response.body[0], 'var_name', "'data'", raw=True)246 response = self.app.get('/spy_correct_expectation') 247 Spy.assert_ok(response.body, 'var_name', 'data') 248 Spy.assert_ok(response.body, 'var_name', "'data'", raw=True) 252 249 253 250 254 class TestPagination( unittest.TestCase):251 class TestPagination(testutil.TGWebTest): 255 252 """Base class for all Paginate TestCases""" 256 253 257 def request(self, url ):258 create_request(url)259 self.body = cherrypy.response.body[0]254 def request(self, url, status=200): 255 response = self.app.get(url, status=status) 256 self.body = response.body 260 257 if "fail: " in self.body: 261 258 print self.body 262 259 assert False, "Spy alert! Check body output for details..." … … 343 340 344 341 345 342 def setUp(self): 346 cherrypy.root = self.MyRoot() 343 testutil.TGWebTest.setUp(self) 344 self.app = testutil.make_app(self.MyRoot) 347 345 348 346 def test_pagination_old_style(self): 349 347 self.request("/basic") … … 439 437 Spy.assert_ok(self.body, 'pages', xrange(4, 8)) 440 438 441 439 def test_invalid_dynamic_limit(self): 442 self.request("/invalid_dynamic") 443 assert cherrypy.response.status.startswith("500") 440 self.request("/invalid_dynamic", status=500) 444 441 assert 'paginate: dynamic_limit (foobar) not found in output dict' in self.body 445 442 446 443 def test_dynamic_limit(self): … … 754 751 755 752 756 753 def setUp(self): 757 cherrypy.root = self.MyRoot() 754 testutil.TGWebTest.setUp(self) 755 self.app = testutil.make_app(self.MyRoot) 758 756 759 757 def assert_order(self, *args): 760 758 expr = 'data="%s"' % ''.join(['[Address %r]' % x for x in args]) … … 826 824 827 825 def test_invalid_default_reversed(self): 828 826 for method in "Q", "QA", "SR", "SO", "SL": 829 self.request("/wrong_reversed/?method=%s" % method) 830 assert cherrypy.response.status.startswith("500") 827 self.request("/wrong_reversed/?method=%s" % method, status=500) 831 828 assert ('paginate: default_reversed (deprecated) only allowed' 832 829 ' when default_order is a basestring') in self.body 833 830 -
turbogears/qstemplates/quickstart/+package+/tests/test_controllers.py_tmpl
old new 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
old new 6 6 import cStringIO as StringIO 7 7 8 8 import cherrypy 9 from cherrypy import _cphttptools9 from webtest import TestApp 10 10 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 16 17 print cherrypy_major_ver 18 19 11 20 try: 12 21 import sqlobject 13 22 from sqlobject.inheritance import InheritableSQLObject … … 21 30 from turbogears import startup, config, update_config, \ 22 31 controllers, database, validators 23 32 from turbogears.identity import current_provider 24 from turbogears.util import get_model 33 from turbogears.util import get_model, deprecated 25 34 26 35 cwd = os.getcwd() 27 36 … … 51 60 {'autoreload.on': False, 'tg.new_style_logging': True}}) 52 61 53 62 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}) 63 def start_server(): 64 """Start the server if it's not already.""" 65 if not config.get("cp_started"): 66 if cherrypy_major_ver < 3: 67 cherrypy.server.start(serverClass=None, initOnly=True) 68 else: 69 cherrypy.server.quickstart() 70 cherrypy.engine.start() 71 config.update({"cp_started" : True}) 58 72 73 if not config.get("server_started"): 74 startup.startTurboGears() 75 config.update({"server_started" : True}) 59 76 77 start_cp = deprecated('start_cp is superceded by start_server')(start_server) 78 79 80 def stop_server(tg_only = False): 81 """Stop the server and unmount the application. \ 82 Use tg_only = True to leave CherryPy running (for faster tests). 83 """ 84 unmount() 85 if config.get("cp_started") and not tg_only: 86 cherrypy.server.stop() 87 config.update({"cp_started" : False}) 88 89 if config.get("server_started"): 90 startup.stopTurboGears() 91 config.update({"server_started" : False}) 92 93 94 60 95 test_user = None 61 96 97 @deprecated() 62 98 def set_identity_user(user): 63 99 """Setup a user for configuring request's identity.""" 64 100 global test_user 65 101 test_user = user 66 102 67 103 104 @deprecated() 68 105 def attach_identity(req): 69 106 if config.get("identity.on", False): 70 107 req.identity = (test_user 71 108 and current_provider.authenticated_identity(test_user) 72 109 or current_provider.anonymous_identity()) 73 110 74 111 @deprecated("create_request is deprecated. See TestMigration on the TG Wiki") 75 112 def create_request(request, method="GET", protocol="HTTP/1.1", 76 113 headers={}, rfile=None, clientAddress="127.0.0.1", 77 114 remoteHost="localhost", scheme="http"): 78 start_ cp()115 start_server() 79 116 if not rfile: 80 117 rfile = StringIO.StringIO("") 81 118 if type(headers) != dict: … … 86 123 if not hasattr(cherrypy.root, "started"): 87 124 startup.startTurboGears() 88 125 cherrypy.root.started = True 89 req = _cphttptools.Request(clientAddress, 80, remoteHost, scheme)126 req = Request(clientAddress, 80, remoteHost, scheme) 90 127 cherrypy.serving.request = req 91 128 attach_identity(req) 92 cherrypy.serving.response = _cphttptools.Response()129 cherrypy.serving.response = Response() 93 130 req.run(" ".join((method, request, protocol)), headerList, rfile) 131 return cherrypy.serving.response 94 132 133 createRequest = create_request 95 134 135 136 def make_wsgiapp(): 137 """Return a WSGI application from cherrypy's root object.""" 138 if cherrypy_major_ver < 3: 139 wsgiapp = cherrypy._cpwsgi.wsgiApp 140 else: 141 #This is untested but should work.. if not, one of the others will 142 wsgiapp = cherrpy.root 143 #wsgiapp = cherrypy.tree.mount(cherrypy.root, '/') 144 #wsgiapp = cherrypy.wsgi.CPWSGIServer 145 return wsgiapp 146 147 148 def make_app(controller=None): 149 """Return a WebTest.TestApp instance from Cherrypy. 150 If a Controller object is provided, it will be mounted at the root level. 151 If not, it'll look for an already mounted root. 152 """ 153 if controller: 154 wsgiapp = mount(controller(), '/') 155 else: 156 wsgiapp = make_wsgiapp() 157 testapp = TestApp(wsgiapp) 158 159 return testapp 160 161 162 class TGWebTest(unittest.TestCase): 163 """A WebTest enabled unit testing class. 164 165 This allows testers to subclass us and use self.app to make WebTest calls. 166 """ 167 def setUp(self): 168 start_server() 169 self.app = make_app() 170 171 def tearDown(self): 172 stop_server(tg_only = True) 173 del self.app 174 175 def login_user(self, user): 176 """ Log a specified user object into the system """ 177 self.app.post(config.get('identity.failure_url'), { 178 'user_name' : user.user_name, 179 'password' : user.password, 180 'login' : 'Login', 181 }) 182 183 96 184 class BrowsingSession(object): 97 185 98 186 def __init__(self): 99 187 self.visit = None 100 188 self.response, self.status = None, None 101 189 self.cookie = Cookie.SimpleCookie() 190 self.app = make_app() 102 191 103 192 def goto(self, *args, **kwargs): 104 193 if self.cookie: 105 194 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)195 headers['Cookie'] = self.cookie_encoded 196 response = self.app.get(*args, **kwargs) 197 self.response = response.body 198 self.status = response.status 199 self.cookie = response.cookies_set 200 self.cookie_encoded = response.headers.get('Set-Cookie', '') 112 201 113 202 114 203 def _return_directly(output, *args): … … 142 231 headers = {} 143 232 144 233 234 @deprecated("Please see the TestMigration page in the TG wiki.") 145 235 def call(method, *args, **kw): 146 start_ cp()236 start_server() 147 237 output, response = call_with_request(method, DummyRequest(), *args, **kw) 148 238 return output 149 239 150 240 241 @deprecated("Please see the TestMigration page in the TG wiki.") 151 242 def call_with_request(method, request, *args, **kw): 152 243 """More fine-grained version of call method. 153 244 … … 156 247 """ 157 248 orig_proc_output = controllers._process_output 158 249 controllers._process_output = _return_directly 159 cherrypy.serving.response = _cphttptools.Response()250 cherrypy.serving.response = Response() 160 251 cherrypy.serving.request = request 161 252 if not hasattr(request, "identity"): 162 253 attach_identity(request) … … 200 291 and item != InheritableSQLObject: 201 292 item.dropTable(ifExists=True) 202 293 203 204 def reset_cp(): 294 def unmount(): 295 """Remove an application from the object traversal tree.""" 296 # There's no clean way to remove a subtree under CP2, so the only use case 297 # handled here is to remove the entire application. 298 # Supposedly, you can do a partial unmount with CP3 using: 299 # del cherrypy.tree.apps[path] 205 300 cherrypy.root = None 301 cherrypy.tree.mount_points = {} 206 302 303 reset_cp = deprecated('reset_cp has been superceded by unmount.')(unmount) 207 304 305 306 def mount(controller, path="/"): 307 """Mount a controller at a path. Returns a wsgi application.""" 308 if path == '/': 309 cherrypy.root = controller 310 else: 311 cherrypy.tree.mount(controller, path) 312 return make_wsgiapp() 313 208 314 def catch_validation_errors(widget, value): 209 315 """Catch and unpack validation errors (for testing purposes).""" 210 316 try: … … 253 359 254 360 """ 255 361 global _currentcat 256 assert not _currentcat 362 assert not _currentcat, "_currentcat not cleared. Use get_log to reset." 257 363 if not isinstance(category, list) and not isinstance(category, tuple): 258 364 category = [category] 259 365 _currentcat = category … … 307 413 308 414 __all__ = ["call", "create_request", "DBTest", 309 415 "attach_identity", "set_identity_user", 310 "capture_log", "print_log", "get_log", "sqlalchemy_cleanup"] 416 "capture_log", "print_log", "get_log", "sqlalchemy_cleanup", 417 "make_wsgiapp", "make_app", "TGWebTest", "start_server", 418 "stop_server", "mount", "unmount"] -
turbogears/widgets/tests/test_nested_form_controllers.py
old new 1 1 import turbogears 2 import cherrypy3 2 from turbogears import widgets 4 3 from turbogears import controllers 5 4 from turbogears import validators 6 5 from turbogears import testutil 7 6 7 8 def setup_module(): 9 global app 10 app = testutil.make_app(MyRoot) 11 testutil.start_server() 12 13 def teardown_module(): 14 testutil.stop_server() 15 16 8 17 myform = widgets.TableForm(fields = [ 9 18 widgets.FieldSet( 10 19 name = "p_data", … … 17 26 18 27 class MyRoot(controllers.RootController): 19 28 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']29 has_errors = tg_errors is not None 30 name = p_data['name'] 31 age = p_data['age'] 32 return dict(has_errors = has_errors, name=name, age = age) 24 33 testform = turbogears.validate(form=myform)(testform) 25 testform = turbogears.expose( html="turbogears.tests.othertemplate")(34 testform = turbogears.expose(template="turbogears.tests.othertemplate")( 26 35 testform) 27 36 28 37 def set_errors(self): 29 self.has_errors = True 38 return dict(has_errors = True) 39 30 40 31 41 def testform_new_style(self, p_data): 32 self.name = p_data['name'] 33 self.age = p_data['age'] 42 name = p_data['name'] 43 age = p_data['age'] 44 return dict(name = name, age = age) 34 45 testform_new_style = turbogears.validate(form=myform)(testform_new_style) 35 46 testform_new_style = turbogears.error_handler(set_errors)(testform_new_style) 36 47 testform_new_style = turbogears.expose()(testform_new_style) 37 48 38 49 50 39 51 def test_form_translation_new_style(): 40 52 "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 53 response = app.get("/testform_new_style?p_data.name=ed&p_data.age=5") 54 assert response.raw['name'] == "ed" 55 print response.raw['age'] 56 assert response.raw['age'] == 5 47 57 48 58 def test_invalid_form_with_error_handling(): 49 59 "Invalid forms can be handled by the method" 50 r oot = cherrypy.root51 testutil.create_request("/testform_new_style?p_data.name=ed&p_data.age=edalso")52 assert root.has_errors 60 response = app.get("/testform_new_style?p_data.name=ed&p_data.age=edalso") 61 assert response.raw['has_errors'] 62 -
turbogears/widgets/tests/test_datagrid.py
old new 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
old new 1 1 import turbogears 2 import cherrypy3 4 2 from turbogears import widgets, testutil 5 3 4 def setup_module(): 5 testutil.start_server() 6 6 7 def teardown_module(): 8 testutil.stop_server() 9 10 7 11 def test_table_widget_js(): 8 12 """ 9 13 The TableForm Widget can require JavaScript and CSS resources. Addresses … … 21 25 return dict(form=form) 22 26 test = turbogears.expose(template="turbogears.widgets.tests.form")(test) 23 27 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 28 app = testutil.make_app(MyRoot) 29 response = app.get("/test") 30 assert 'foo.js' in response.body 31 assert "alert('hello');" in response.body 32 assert 'foo.css' in response.body 30 33 31 34 32 35 def test_calendardatepicker_js(): … … 37 40 return dict(widget=widgets.CalendarDatePicker(calendar_lang=lang)) 38 41 test = turbogears.expose(template="turbogears.widgets.tests.widget")(test) 39 42 40 cherrypy.root = MyRoot()43 app = testutil.make_app(MyRoot) 41 44 42 45 # 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 46 response = app.get("/test") 47 assert 'calendar/calendar.js' in response.body 48 assert 'calendar/calendar-setup.js' in response.body 49 assert 'calendar/lang/calendar-en.js' in response.body 48 50 49 51 # testing non-existing language 50 testutil.create_request("/test", 51 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 52 response = app.get("/test", headers={"Accept-Language": "x"}) 53 assert 'calendar/lang/calendar-x.js' not in response.body 54 assert 'calendar/lang/calendar-en.js' in response.body 55 55 56 56 # testing French language 57 testutil.create_request("/test", 58 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 57 response = app.get("/test", headers={"Accept-Language": "fr"}) 58 assert 'calendar/lang/calendar-fr.js' in response.body 59 assert 'calendar/lang/calendar-en.js' not in response.body 60 assert 'charset="utf-8"' in response.body 63 61 64 62 # testing German language with any charset 65 testutil.create_request("/test",63 response = app.get("/test", 66 64 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 65 assert 'calendar/lang/calendar-de.js' in response.body 66 assert 'calendar/lang/calendar-en.js' not in response.body 67 assert 'charset="*"' not in response.body 71 68 72 69 # testing Turkish language with non-existing charset 73 testutil.create_request("/test",70 response = app.get("/test", 74 71 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 72 assert 'calendar/lang/calendar-tr.js' in response.body 73 assert 'calendar/lang/calendar-en.js' not in response.body 74 assert 'charset="big5"' not in response.body 79 75 80 76 win1254 = 'windows-1254' 81 77 from codecs import lookup … … 85 81 win1254 = 'cp1254' # cannot test name normalization here 86 82 87 83 # testing Turkish language with existing, not normalized charset 88 testutil.create_request("/test",84 response = app.get("/test", 89 85 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 86 assert 'calendar/lang/calendar-tr-cp1254.js' in response.body 87 assert 'calendar/lang/calendar-en.js' not in response.body 88 assert 'charset="cp1254"' in response.body 94 89 95 90 # testing more than one language and charset 96 testutil.create_request("/test", headers={"Accept-Language": "x,tr,de,fr",91 response = app.get("/test", headers={"Accept-Language": "x,tr,de,fr", 97 92 "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 93 assert 'calendar/lang/calendar-tr-cp1254.js' in response.body 94 assert 'calendar/lang/calendar-x.js' not in response.body 95 assert 'calendar/lang/calendar-en.js' not in response.body 96 assert 'charset="cp1254"' in response.body 97 assert 'charset="big5"' not in response.body 104 98 105 99 # testing predetermined language (fr) 106 testutil.create_request("/test?lang=fr",100 response = app.get("/test?lang=fr", 107 101 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 102 assert 'calendar/lang/calendar-fr.js' in response.body 103 assert 'calendar/lang/calendar-en.js' not in response.body 111 104 112 105 # testing predetermined non-existing language 113 testutil.create_request("/test?lang=x",106 response = app.get("/test?lang=x", 114 107 headers={"Accept-Language": "de,en,fr,tr"}) 115 output = cherrypy.response.body[0]116 assert 'calendar/lang/calendar- de.js' in output117 assert 'calendar/lang/calendar- x.js' not in output118 assert 'calendar/lang/calendar-en.js' not in output 108 assert 'calendar/lang/calendar-de.js' in response.body 109 assert 'calendar/lang/calendar-x.js' not in response.body 110 assert 'calendar/lang/calendar-en.js' not in response.body 111 -
turbogears/widgets/tests/test_new_validation.py
old new 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
old new 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, make_app 8 8 import cherrypy 9 9 10 10 11 11 def setup_module(): 12 testutil.start_cp() 13 cherrypy.serving.request = testutil.DummyRequest() 12 testutil.start_server() 14 13 14 def teardown_module(): 15 testutil.stop_server() 16 17 15 18 def test_rendering(): 16 19 """Forms can be rendered""" 17 20 form = widgets.TableForm(fields=[widgets.TextField("name", label="Your Name")]) … … 166 169 167 170 @expose() 168 171 @validate(form=nestedform) 169 def checkform(self, foo): 170 self.foo = foo 172 def checkform(self, foo=None): 173 #def checkform(self, foo=None, *args, **kw): 174 #raise Exception('HolyHell: %s: %s. kw: %s' % (foo, args, kw)) 175 return foo 171 176 177 @expose() 178 def field_for(self): 179 cherrypy.request.validation_errors = dict(foo=dict(foo='error')) 180 template = """\ 181 <div xmlns:py="http://purl.org/kid/ns#"> 182 ${field_for('foo').fq_name}.appears 183 ${field_for('foo').error}_appears 184 ${field_for('foo').field_id}_appears 185 ${field_for('foo').display(value_for('foo'), **params_for('foo'))} 186 </div> 187 """ 188 textfield = widgets.TextField("foo") 189 fieldset = widgets.FieldSet("foo", fields=[textfield], template=template) 190 form = widgets.Form("form", fields=[fieldset], template=template) 172 191 192 # Good example below of how you can pass parameters and values to nested 193 # widgets. 194 value = dict(foo=dict(foo="HiYo!")) 195 params = dict(attrs=dict(foo=dict(foo=dict(size=100)))) 196 params['format'] = 'xhtml' 197 return form.render(value, **params) 198 199 173 200 def test_nested_variables(): 174 newroot = NestedController()175 cherrypy.root = None176 cherrypy.tree.mount_points = {}177 cherrypy.tree.mount(newroot, "/")178 201 url = u"/checkform?foo.name=Kevin&foo.age=some%20Numero".encode("utf-8") 179 create_request(url) 202 testutil.stop_server(tg_only = True) 203 app = testutil.make_app(NestedController) 204 testutil.start_server() 205 206 request = app.get(url) 180 207 assert config.get("decoding_filter.encoding", path="/") == "utf8" 181 assert newroot.foo182 assert newroot.foo["name"] == "Kevin"183 assert newroot.foo["age"] == u"some Numero"208 print "raw", request.raw 209 assert request.raw["name"] == "Kevin" 210 assert request.raw["age"] == u"some Numero" 184 211 185 212 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 assert "form_foo_appears" in output 205 assert "form_foo_foo_appears" in output 206 assert "foo.appears" in output 207 assert "foo.foo.appears" in output 208 assert "error_appears" in output 209 assert "textfield" in output 210 assert "HiYo!" in output 211 assert "size=\"100\"" in output 213 app = make_app(NestedController) 214 response = app.get('/field_for') 215 assert "form_foo_appears" in response 216 assert "form_foo_foo_appears" in response 217 assert "foo.appears" in response 218 assert "foo.foo.appears" in response 219 assert "error_appears" in response 220 assert "textfield" in response 221 assert "HiYo!" in response 222 assert "size=\"100\"" in response -
turbogears/widgets/tests/test_request_related_features.py
old new 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 7 def setup_module(): 8 testutil.start_server() 9 10 def teardown_module(): 11 testutil.stop_server() 12 13 8 14 def test_required_fields(): 9 15 """ 10 16 Required field are automatically discovered from the form validator and marked … … 20 26 return dict(form=form) 21 27 test = turbogears.expose(template="turbogears.widgets.tests.form")(test) 22 28 23 cherrypy.root = MyRoot()24 testutil.create_request("/test")25 output = cherrypy.response.body[0].lower()29 app = testutil.make_app(MyRoot) 30 response = app.get("/test") 31 output = response.body.lower() 26 32 27 33 print output 28 34 name_p = 'name="comment"' … … 48 54 form2 = widgets.TableForm(name="form2", fields=MyFields()) 49 55 50 56 class MyRoot(turbogears.controllers.RootController): 51 def test(self): 52 return dict(form1=form1, form2=form2) 57 58 #@expose(template="turbogears.widgets.tests.two_forms") 59 #@validate(form=form1) 60 #@error_handler('test') 61 def test(self, age, email): 62 validated_form = cherrypy.request.validated_form.name 63 form1_valid = form1.is_validated 64 form2_valid = form2.is_validated 65 return dict(form1=form1, form2=form2, validated_form=validated_form, 66 form1_valid=form1_valid, form2_valid=form2_valid) 53 67 test = turbogears.expose(template="turbogears.widgets.tests.two_forms")(test) 54 68 test = turbogears.validate(form=form1)(test) 55 69 test = turbogears.error_handler(test)(test) 56 70 71 57 72 def test2(self): 58 return dict(form=form2) 73 validated_form = cherrypy.request.validated_form.name 74 form1_valid = form1.is_validated 75 form2_valid = form2.is_validated 76 return dict(form=form2, validated_form=validated_form, 77 form1_valid=form1_valid, form2_valid=form2_valid) 59 78 test2 = turbogears.expose(template="turbogears.widgets.tests.form")(test2) 60 79 test2 = turbogears.validate(form=form2)(test2) 61 80 test2 = turbogears.error_handler(test2)(test2) 62 81 63 82 def test3(self): 64 return dict(form=form1) 83 validated_form = cherrypy.request.validated_form.name 84 form1_valid = form1.is_validated 85 form2_valid = form2.is_validated 86 return dict(form=form1, validated_form=validated_form, 87 form1_valid=form1_valid, form2_valid=form2_valid) 65 88 test3 = turbogears.expose(template="turbogears.widgets.tests.form")(test3) 66 89 test3 = turbogears.validate(form=form2)(test3) 67 90 test3 = turbogears.error_handler(test3)(test3) 68 91 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 92 app = testutil.make_app(MyRoot) 75 93 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 94 response = app.get("/test?age=foo&email=bar") 95 output = response.body.lower() 96 97 assert response.raw['validated_form'] == 'form1' 98 assert response.raw['form1_valid'] 99 assert not response.raw['form2_valid'] 84 100 value_p = 'value="foo"' 85 101 id_p = 'id="form1_age"' 86 102 assert (re.compile('.*'.join([value_p, id_p])).search(output) or … … 92 108 re.compile('.*'.join([id_p, value_p])).search(output) 93 109 ) 94 110 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 111 response = app.get("/test2?age=foo&email=bar") 112 output = response.body.lower() 101 113 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 114 assert response.raw['validated_form'] == 'form2' 115 assert not response.raw['form1_valid'] 116 assert response.raw['form2_valid'] 110 117 assert 'value="foo"' in output 111 118 assert '>bar<' in output 112 119 assert 'class="fielderror"' in output 113 120 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 121 response = app.get("/test3?age=foo&email=bar") 122 output = response.body.lower() 120 123 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 124 assert response.raw['validated_form'] == 'form2' 125 assert not response.raw['form1_valid'] 126 assert response.raw['form2_valid'] 129 127 assert 'value="foo"' not in output 130 128 assert '>bar<' not in output 131 129 assert 'class="fielderror"' not in output … … 141 139 name="repeat", fields=MyFields(), repetitions=repetitions)]) 142 140 143 141 class MyRoot(turbogears.controllers.RootController): 144 @turbogears.expose(template="turbogears.widgets.tests.form")145 142 def test(self): 146 143 return dict(form=form) 144 test = turbogears.expose(template="turbogears.widgets.tests.form")(test) 147 145 148 @turbogears.expose(template="turbogears.widgets.tests.form")149 146 def test_value(self): 150 147 value = dict(repeat=[{'name':'foo', 'comment':'hello'}, 151 148 None, 152 149 None, 153 150 {'name':'bar', 'comment':'byebye'}]) 154 151 return dict(form=form, value=value) 152 test_value = turbogears.expose(template="turbogears.widgets.tests.form")(test_value) 155 153 156 154 def test_validation(self): 157 return dict(form=form)158 test_validation = turbogears.expose(159 template="turbogears.widgets.tests.form")(test_validation)155 validation_errors = cherrypy.request.validation_errors 156 return dict(form=form, validation_errors=validation_errors) 157 test_validation = turbogears.expose(template="turbogears.widgets.tests.form")(test_validation) 160 158 test_validation = turbogears.validate(form=form)(test_validation) 161 159 test_validation = turbogears.error_handler(test_validation)(test_validation) 162 160 163 cherrypy.root = MyRoot()164 testutil.create_request("/test")165 output = cherrypy.response.body[0].lower()161 app = testutil.make_app(MyRoot) 162 response = app.get("/test") 163 output = response.body.lower() 166 164 for i in range(repetitions): 167 165 assert 'id="form_repeat_%i"' % i in output 168 166 assert 'name="repeat-%i.name"' % i in output … … 170 168 assert 'name="repeat-%i.comment"' % i in output 171 169 assert 'id="form_repeat_%i_comment"' % i in output 172 170 173 cherrypy.root = MyRoot() 174 testutil.create_request("/test_value") 175 output = cherrypy.response.body[0].lower() 171 response = app.get("/test_value") 172 output = response.body.lower() 176 173 name_p = 'name="repeat-0.name"' 177 174 value_p = 'value="foo"' 178 175 assert (re.compile('.*'.join([value_p, name_p])).search(output) or … … 204 201 re.compile('.*'.join([name_p, value_p])).search(output) 205 202 ) 206 203 207 cherrypy.root = MyRoot() 208 testutil.create_request("/test_validation?repeat-0.name=foo&repeat-1.name=" 204 #FIXME: Why is stopping the server necessary here? 205 testutil.stop_server(tg_only = True) 206 app = testutil.make_app(MyRoot) 207 testutil.start_server() 208 209 response = app.get("/test_validation?repeat-0.name=foo&repeat-1.name=" 209 210 "&repeat-2.name=bar&repeat-3.name=&repeat-4.name=") 210 output = cherrypy.response.body[0].lower() 211 validation_errors = cherrypy.request.validation_errors 211 output = response.body.lower() 212 print "Raw", response.raw 213 validation_errors = response.raw['validation_errors'] 212 214 assert validation_errors.has_key("repeat") 213 215 assert isinstance(validation_errors["repeat"], list) 214 216 assert validation_errors["repeat"][0] is None -
turbogears/widgets/tests/test_widgets.py
old new 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 def teardown_module(): 11 testutil.stop_server() 10 12 13 11 14 def test_rendering_without_engine(): 12 15 """Helpful error when rendering widgets with no templating engine loaded""" 13 16 from turbogears import view -
turbogears/widgets/tests/test_nested_widgets.py
old new 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 app = testutil.make_app(self.MyRoot) 58 response = app.get('/?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 = app.get('/?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 = app.get('/?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
old new 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):