Warning: Can't synchronize with repository "(default)" (Unsupported version control system "svn": No module named svn). Look in the Trac log for more information.

Ticket #1762: webtest-ken.patch

File webtest-ken.patch, 134.9 KB (added by kskuhlman, 4 years ago)

Ken's attempt

  • setup.py

     
    4646 
    4747testtools =  [ 
    4848    "nose >= 0.9.3, <= 0.10.0a1", 
     49    "WebTest", 
    4950] 
    5051 
    5152tgtesttools =  [ 
    5253    "nose >= 0.9.3, <= 0.10.0a1", 
     54    "WebTest", 
    5355] 
    5456 
    5557# python 2.5 compatible list 
  • turbogears/identity/tests/test_identity.py

     
    5555 
    5656    @expose() 
    5757    def index(self): 
    58         pass 
     58        return 'identityroot index' 
    5959 
    6060    @expose() 
    6161    def identity_failed(self, **kw): 
     
    6969    @expose() 
    7070    @identity.require(in_group('peon')) 
    7171    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 
    7282        return 'in_peon_group' 
    7383 
    7484    @expose() 
     85    @identity.require(in_group('peon')) 
     86    def identity_current_set(self): 
     87        user = TG_User.by_user_name("samIam") 
     88        group_ids = set((TG_Group.by_group_name("peon").id, 
     89            TG_Group.by_group_name("other").id)) 
     90        assert identity.current.user == user 
     91        assert identity.current.user_name == user.user_name 
     92        assert identity.current.user_id == user.id 
     93        assert identity.current.groups == set(('peon', 'other')) 
     94        assert identity.current.group_ids == group_ids 
     95        assert "samIam" == cherrypy.serving.request.identity.user_name 
     96 
     97        return 'identity_current_set' 
     98 
     99 
     100    @expose() 
    75101    def test_exposed_require(self): 
    76102        if not hasattr(self.in_peon_group, '_require'): 
    77103            return 'no _require attr' 
     
    136162            return 'wrong params: %s\nexpected unicode objects' \ 
    137163                ' for all strings' % cherrypy.request.params 
    138164 
     165    @expose() 
     166    def is_anonymous(self): 
     167        assert cherrypy.serving.request.identity.user_name == None 
     168        assert cherrypy.serving.request.identity.anonymous 
     169        return 'is_anonymous' 
    139170 
    140171class TestIdentity(unittest.TestCase): 
    141172 
     
    151182        self._original_config = original_config 
    152183        config.configure_loggers(test_config) 
    153184        config.update(test_config['global']) 
    154         cherrypy.root = IdentityRoot() 
    155         startup.startTurboGears() 
     185        testutil.start_server(root = IdentityRoot()) 
    156186        self.init_model() 
    157187 
    158188    def tearDown(self): 
    159         startup.stopTurboGears() 
     189        testutil.stop_server() 
    160190        config.update(self._original_config) 
    161191 
    162192    def init_model(self): 
     
    181211 
    182212    def test_user_password_parameters(self): 
    183213        """Controller can receive user_name and password parameters.""" 
    184         testutil.create_request('/new_user_setup?user_name=test&password=pw') 
    185         firstline = cherrypy.response.body[0] 
    186         assert 'test pw' in firstline, firstline 
     214        response = testutil.go('/new_user_setup?user_name=test&password=pw') 
     215        assert 'test pw' in response, response 
    187216 
    188217    def test_user_exists(self): 
    189218        u = TG_User.by_user_name('samIam') 
     
    203232        """Test if we can set a user password which is encoded as unicode 
    204233        (no encryption algorithm).""" 
    205234        config.update({'identity.soprovider.encryption_algorithm': None}) 
    206         # force new config values to load 
    207         startup.startTurboGears() 
    208         testutil.create_request('/') 
    209235        hub.begin() 
    210236        u = TG_User.by_user_name('samIam') 
    211237        u.password = u'garçon' 
     
    217243    def test_user_password_hashed_sha(self): 
    218244        """Test if a sha hashed password is stored in the database.""" 
    219245        config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 
    220         # force new config values to load 
    221         startup.startTurboGears() 
    222         testutil.create_request('/') 
    223246        hub.begin() 
    224247        u = TG_User.by_user_name('samIam') 
    225248        u.password = 'password' 
     
    232255        """Test if a sha hashed password with unicode characters is stored 
    233256        in the database.""" 
    234257        config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 
    235         # force new config values to load 
    236         startup.startTurboGears() 
    237         testutil.create_request('/') 
    238258        hub.begin() 
    239259        u = TG_User.by_user_name('samIam') 
    240260        u.password = u'garçon' 
     
    246266    def test_user_password_hashed_md5(self): 
    247267        """Test if a md5 hashed password is stored in the database.""" 
    248268        config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 
    249         # force new config values to load 
    250         startup.startTurboGears() 
    251         testutil.create_request('/') 
    252269        hub.begin() 
    253270        u = TG_User.by_user_name('samIam') 
    254271        u.password = 'password' 
     
    261278        """Test if a md5 hashed password with unicode characters is stored 
    262279        in the database.""" 
    263280        config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 
    264         # force new config values to load 
    265         startup.startTurboGears() 
    266         testutil.create_request('/') 
    267281        hub.begin() 
    268282        u = TG_User.by_user_name('samIam') 
    269283        u.password = u'garçon' 
     
    278292        test ensures that the encryption algorithm does handle non-unicode 
    279293        parameters gracefully.""" 
    280294        config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 
    281         # force new config values to load 
    282         startup.startTurboGears() 
    283         testutil.create_request('/') 
    284295        hub.begin() 
    285296        u = TG_User.by_user_name('samIam') 
    286297        u.password = u'garçon'.encode('UTF-8') 
     
    293304        """Test that we can store raw values in the password field 
    294305        (without being hashed).""" 
    295306        config.update({'identity.soprovider.encryption_algorithm':'sha1'}) 
    296         # force new config values to load 
    297         startup.startTurboGears() 
    298         testutil.create_request('/') 
    299307        hub.begin() 
    300308        u = TG_User.by_user_name('samIam') 
    301309        u.set_password_raw('password') 
     
    306314 
    307315    def test_user_password_raw_unicode(self): 
    308316        config.update({'identity.soprovider.encryption_algorithm':'sha1'}) 
    309         # force new config values to load 
    310         startup.startTurboGears() 
    311         testutil.create_request('/') 
    312317        hub.begin() 
    313318        u = TG_User.by_user_name('samIam') 
    314319        u.set_password_raw(u'garçon') 
     
    322327        config.update({'identity.soprovider.encryption_algorithm': 'custom', 
    323328            'identity.custom_encryption': 
    324329                'identity.tests.test_identity.mycustomencrypt'}) 
    325         # force new config values to load 
    326         startup.startTurboGears() 
    327         testutil.create_request('/') 
    328330        hub.begin() 
    329331        u = TG_User.by_user_name('samIam') 
    330332        u.password = 'password' 
     
    335337 
    336338    def test_anonymous_browsing(self): 
    337339        """Test if we can show up anonymously.""" 
    338         testutil.create_request('/') 
    339         assert identity.current.anonymous 
     340        response = testutil.go('/is_anonymous') 
     341        assert 'is_anonymous' in response 
    340342 
    341343    def test_deny_anonymous(self): 
    342344        """Test that we have secured an url from anonymous users.""" 
    343         testutil.create_request('/logged_in_only') 
    344         firstline = cherrypy.response.body[0] 
    345         assert 'identity_failed_answer' in firstline, firstline 
     345        response = testutil.go('/logged_in_only') 
     346        assert 'identity_failed_answer' in response.body 
    346347 
    347348    def test_deny_anonymous_viewable(self): 
    348349        """Test that a logged in user can see an resource blocked 
    349350        from anonymous users.""" 
    350         testutil.create_request('/logged_in_only?' 
     351        response = testutil.go('/logged_in_only?' 
    351352            'user_name=samIam&password=secret&login=Login') 
    352         firstline = cherrypy.response.body[0] 
    353         assert 'logged_in_only' in firstline, firstline 
     353        assert 'logged_in_only' in response.body 
    354354 
    355355    def test_logout(self): 
    356         """Test that logout works and session is gets invalid afterwards.""" 
    357         testutil.create_request('/in_peon_group?' 
     356        """Test that logout works and session is invalid afterwards.""" 
     357        response = testutil.go('/identity_current_set?' 
    358358            'user_name=samIam&password=secret&login=Login') 
    359         self.assertEquals("samIam", cherrypy.serving.request.identity.user_name) 
    360         session_id = re.match("Set-Cookie: (.*?); Path.*", 
    361             str(cherrypy.response.simple_cookie)).group(1) 
    362         testutil.create_request('/logout', headers={'Cookie': session_id }) 
    363         self.assertEquals(None, cherrypy.serving.request.identity.user_name) 
    364         assert cherrypy.serving.request.identity.anonymous 
     359        session_id = response.headers['Set-Cookie'] 
     360        response = testutil.go('/logout', headers={'Cookie': session_id}) 
     361        response = testutil.go('/is_anonymous', headers={'Cookie' : session_id}) 
     362        assert response.body == 'is_anonymous' 
    365363 
    366     def test_logout_with_set_identity(self): 
    367         """Test that logout works even when there is no visit_key 
    368         (e.g. when testutils.set_identity_user is used).""" 
    369         request = testutil.DummyRequest() 
    370         old_user = testutil.test_user 
    371         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.anonymous 
    377  
    378364    def test_require_group(self): 
    379365        """Test that a anonymous user""" 
    380         testutil.create_request('/in_peon_group') 
    381         firstline = cherrypy.response.body[0] 
    382         assert 'identity_failed_answer' in firstline, firstline 
     366        response = testutil.go('/in_peon_group') 
     367        assert 'identity_failed_answer' in response.body 
    383368 
    384369    def test_require_expose_required_permission(self): 
    385370        """Test that the decorator exposes the correct permissions via _require 
    386371        attribute on the actual method.""" 
    387         testutil.create_request('/test_exposed_require') 
    388         firstline= cherrypy.response.body[0] 
    389         assert 'require is exposed' in firstline, firstline 
     372        response = testutil.go('/test_exposed_require') 
     373        assert 'require is exposed' in response.body 
    390374 
    391375    def test_require_group_viewable(self): 
    392376        """Test that a user with proper group membership can see a restricted url.""" 
    393         testutil.create_request('/in_peon_group?' 
     377        response = testutil.go('/in_peon_group?' 
    394378            'user_name=samIam&password=secret&login=Login') 
    395         firstline = cherrypy.response.body[0] 
    396         assert 'in_peon_group' in firstline, firstline 
    397         user = TG_User.by_user_name("samIam") 
     379        assert 'in_peon_group' in response.body 
    398380 
    399381    def test_require_group_viewable(self): 
    400382        """Test that the current user and group properties are set correctly.""" 
    401         testutil.create_request('/in_peon_group?' 
     383        response = testutil.go('/identity_current_set?' 
    402384            'user_name=samIam&password=secret&login=Login') 
    403         user = TG_User.by_user_name("samIam") 
    404         group_ids = set((TG_Group.by_group_name("peon").id, 
    405             TG_Group.by_group_name("other").id)) 
    406         assert identity.current.user == user 
    407         assert identity.current.user_name == user.user_name 
    408         assert identity.current.user_id == user.id 
    409         assert identity.current.groups == set(('peon', 'other')) 
    410         assert identity.current.group_ids == group_ids 
     385        assert response.body == 'identity_current_set' 
    411386 
    412387    def test_user_not_in_right_group(self): 
    413388        """Test that a user is denied access if they aren't in the right group.""" 
    414         testutil.create_request('/in_admin_group?' 
     389        response = testutil.go('/in_admin_group?' 
    415390            'user_name=samIam&password=secret&login=Login') 
    416         firstline = cherrypy.response.body[0] 
    417         assert 'identity_failed_answer' in firstline, firstline 
     391        assert 'identity_failed_answer' in response.body 
    418392 
    419393    def test_require_permission(self): 
    420394        """Test that an anonymous user is denied access to a permission restricted url.""" 
    421         testutil.create_request('/has_chopper_permission') 
    422         firstline = cherrypy.response.body[0] 
    423         assert 'identity_failed_answer' in firstline, firstline 
     395        response = testutil.go('/has_chopper_permission') 
     396        assert 'identity_failed_answer' in response.body 
    424397 
    425398    def test_require_permission_viewable(self): 
    426399        """Test that a user with proper permissions can see a restricted url.""" 
    427         testutil.create_request('/has_chopper_permission?' 
     400        response = testutil.go('/has_chopper_permission?' 
    428401            'user_name=samIam&password=secret&login=Login') 
    429         firstline = cherrypy.response.body[0] 
    430         assert 'has_chopper_permission' in firstline, firstline 
     402        assert 'has_chopper_permission' in response.body 
    431403 
    432404    def test_user_lacks_permission(self): 
    433405        """Test that a user is denied acces if they don't have the proper permission.""" 
    434         testutil.create_request('/has_boss_permission?' 
     406        response = testutil.go('/has_boss_permission?' 
    435407            'user_name=samIam&password=secret&login=Login') 
    436         firstline = cherrypy.response.body[0] 
    437         assert 'identity_failed_answer' in firstline, firstline 
     408        assert 'identity_failed_answer' in response.body 
    438409 
    439410    def test_user_info_available(self): 
    440411        """Test that we can see user information inside our controller.""" 
    441         testutil.create_request('/user_email?' 
     412        response = testutil.go('/user_email?' 
    442413            'user_name=samIam&password=secret&login=Login') 
    443         firstline = cherrypy.response.body[0] 
    444         assert 'samiam@example.com' in firstline, firstline 
     414        assert 'samiam@example.com' in response.body 
    445415 
    446416    def test_bad_login(self): 
    447417        """Test that we are denied access if we provide a bad login.""" 
    448         testutil.create_request('/logged_in_only?' 
     418        response = testutil.go('/logged_in_only?' 
    449419            'user_name=samIam&password=wrong&login=Login') 
    450         firstline = cherrypy.response.body[0] 
    451         assert 'identity_failed_answer' in firstline, firstline 
     420        assert 'identity_failed_answer' in response.body 
    452421 
    453422    def test_restricted_subdirectory(self): 
    454423        """Test that we can restrict access to a whole subdirectory.""" 
    455         testutil.create_request('/peon_area/index') 
    456         firstline = cherrypy.response.body[0] 
    457         assert 'identity_failed_answer' in firstline, firstline 
     424        response = testutil.go('/peon_area/index') 
     425        assert 'identity_failed_answer' in response.body 
    458426 
    459427    def test_restricted_subdirectory_viewable(self): 
    460428        """Test that we can access a restricted subdirectory 
    461429        if we have proper credentials.""" 
    462         testutil.create_request('/peon_area/index?' 
     430        response = testutil.go('/peon_area/index?' 
    463431            'user_name=samIam&password=secret&login=Login') 
    464         firstline = cherrypy.response.body[0] 
    465         assert 'restricted_index' in firstline, firstline 
     432        assert 'restricted_index' in response.body 
    466433 
    467434    def test_decoratator_in_restricted_subdirectory(self): 
    468435        """Test that we can require a different permission 
    469436        in a protected subdirectory.""" 
    470         testutil.create_request('/peon_area/in_other_group?' 
     437        response = testutil.go('/peon_area/in_other_group?' 
    471438            'user_name=samIam&password=secret&login=Login') 
    472         firstline = cherrypy.response.body[0] 
    473         assert 'in_other_group' in firstline, firstline 
     439        assert 'in_other_group' in response.body 
    474440 
    475441    def test_decoratator_failure_in_restricted_subdirectory(self): 
    476442        """Test that we can get an identity failure from a decorator 
    477443        in a restricted subdirectory""" 
    478         testutil.create_request('/peon_area/in_admin_group?' 
     444        response = testutil.go('/peon_area/in_admin_group?' 
    479445            'user_name=samIam&password=secret&login=Login') 
    480         firstline = cherrypy.response.body[0] 
    481         assert 'identity_failed_answer' in firstline, firstline 
     446        assert 'identity_failed_answer' in response.body 
    482447 
    483448    def test_explicit_checks_in_restricted_subdirectory(self): 
    484449        """Test that explicit permission checks in a protected 
    485450        directory is handled as expected""" 
    486         testutil.create_request('/peon_area/in_other_group_explicit_check?' 
     451        response = testutil.go('/peon_area/in_other_group_explicit_check?' 
    487452            'user_name=samIam&password=secret&login=Login') 
    488         firstline = cherrypy.response.body[0] 
    489         assert 'in_other_group' in firstline, firstline 
     453        assert 'in_other_group' in response.body 
    490454 
    491455    def test_throwing_identity_exception_in_restricted_subdirectory(self): 
    492456        """Test that throwing an IdentityException in a protected 
    493457        directory is handled as expected""" 
    494         testutil.create_request('/peon_area/in_admin_group_explicit_check?' 
     458        response = testutil.go('/peon_area/in_admin_group_explicit_check?' 
    495459            'user_name=samIam&password=secret&login=Login') 
    496         firstline = cherrypy.response.body[0] 
    497         assert 'identity_failed' in firstline, firstline 
     460        assert 'identity_failed' in response.body 
    498461 
    499462    def test_decode_filter_whenidfails(self): 
    500463        """Test that the decode filter doesn't break with nested 
    501464        variables and Identity""" 
    502465        params = urllib.quote(IdentityRoot._test_encoded_params.decode( 
    503466            'utf-8').encode('latin-1'), '=&') 
    504         testutil.create_request('/test_params?' + params) 
    505         firstline = cherrypy.response.body[0] 
    506         assert 'identity_failed_answer' in firstline, firstline 
     467        response = testutil.go('/test_params?' + params) 
     468        assert 'identity_failed_answer' in response.body 
    507469 
    508470    def test_decode_filter_whenidworks(self): 
    509471        """Test that the decode filter doesn't break with nested 
     
    511473        params = urllib.quote(IdentityRoot._test_encoded_params.decode( 
    512474            'utf-8').encode('latin-1'), '=&') 
    513475        params += '&user_name=samIam&password=secret&login=Login' 
    514         testutil.create_request('/test_params?' + params) 
    515         firstline = cherrypy.response.body[0] 
    516         assert 'params ok' in firstline, firstline 
     476        response = testutil.go('/test_params?' + params) 
     477        assert 'params ok' in response.body 
    517478 
    518479 
    519480class TestTGUser(testutil.DBTest): 
     
    522483    def setUp(self): 
    523484        self._identity_on = config.get('identity.on', False) 
    524485        config.update({'identity.on': False}) 
    525         try: 
    526             self._provider = cherrypy.request.identityProvider 
    527         except AttributeError: 
    528             self._provider= None 
    529         cherrypy.request.identityProvider = None 
    530         startup.startTurboGears() 
     486        testutil.start_server() 
    531487        testutil.DBTest.setUp(self) 
    532488 
    533489    def tearDown(self): 
    534490        testutil.DBTest.tearDown(self) 
    535         startup.stopTurboGears() 
    536         cherrypy.request.identityProvider = self._provider 
     491        testutil.stop_server() 
    537492        config.update({'identity.on': self._identity_on}) 
    538493 
    539494    def test_create_user(self): 
  • turbogears/identity/tests/test_visit.py

     
    22from unittest import TestCase 
    33import cherrypy 
    44from turbogears import config, controllers, expose, startup, testutil, visit 
     5from Cookie import SimpleCookie 
    56 
    67 
    7 def cookie_header(morsel): 
     8def cookie_header(response): 
    89    """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']) 
    1011 
    1112 
    1213class VisitRoot(controllers.RootController): 
    1314 
    1415    @expose() 
    1516    def index(self): 
    16         return dict() 
     17        new = None 
     18        if visit.current(): 
     19            new = visit.current().is_new 
     20        return dict(new=new) 
     21     
    1722 
    18  
    1923class TestVisit(TestCase): 
    2024 
    2125    def setUp(self): 
     
    2731        cherrypy.root = VisitRoot() 
    2832 
    2933    def tearDown(self): 
    30         startup.stopTurboGears() 
     34        testutil.stop_server() 
    3135        config.update({'visit.timeout': self._visit_timeout}) 
    3236        config.update({'visit.on': self._visit_on}) 
    3337 
    3438    def test_visit_response(self): 
    3539        """Test if the visit cookie is set in cherrypy.response.""" 
    36         testutil.create_request("/") 
    37         assert cherrypy.response.simple_cookie.has_key(self.cookie_name) 
     40        response = testutil.go("/") 
     41        assert response.cookies_set.has_key(self.cookie_name) 
    3842 
    3943    def test_new_visit(self): 
    4044        """Test that we can see a new visit on the server.""" 
    41         testutil.create_request("/") 
    42         assert visit.current().is_new 
     45        response = testutil.go("/") 
     46        assert response.raw['new'] 
    4347 
    4448    def test_old_visit(self): 
    4549        """Test if we can track a visitor over time.""" 
    46         testutil.create_request("/") 
     50        response = testutil.go("/") 
    4751        # 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 
     52        morsel = response.cookies_set[self.cookie_name] 
     53        response = testutil.go("/", headers=cookie_header(response)) 
     54        assert not response.raw['new'] 
    5155 
    5256    def test_cookie_expires(self): 
    5357        """Test if the visit timeout mechanism works.""" 
     
    5559        try: 
    5660            # set expiration to one second for this test only 
    5761            config.update({'visit.timeout': 1.0/60}) 
    58             testutil.create_request("/") 
    59             morsel = cherrypy.response.simple_cookie[self.cookie_name] 
     62            response = testutil.go("/") 
     63            morsel = response.cookies_set[self.cookie_name] 
    6064            time.sleep(2) # 2 seconds 
    61             testutil.create_request("/", headers=cookie_header(morsel)) 
     65            response = testutil.go("/", headers=cookie_header(response)) 
    6266        finally: 
    6367            config.update({'visit.timeout': timeout}) 
    64         assert cherrypy.response.simple_cookie[ 
    65                 self.cookie_name].value != morsel.value, \ 
     68        assert response.cookies_set[ 
     69                self.cookie_name] != morsel, \ 
    6670            'cookie values should not match' 
    67         assert visit.current().is_new, \ 
     71        assert response.raw['new'], \ 
    6872            'this should be a new visit, as the cookie has expired' 
    6973 
    7074    def test_cookie_not_permanent(self): 
    7175        """Check that by default the visit cookie is not permanent.""" 
    72         testutil.create_request('/') 
    73         morsel = cherrypy.response.simple_cookie[self.cookie_name] 
     76        response = testutil.go('/') 
     77        cookies = SimpleCookie(response.headers['Set-Cookie']) 
     78        morsel = cookies[self.cookie_name] 
    7479        assert not morsel['expires'] and not morsel['max-age'] 
    7580 
    7681    def test_cookie_permanent(self): 
     
    8085            # set cookie permanent for this test only (needs restart) 
    8186            startup.stopTurboGears() 
    8287            config.update({'visit.cookie.permanent': True}) 
    83             startup.startTurboGears() 
    84             testutil.create_request('/') 
    85             morsel = cherrypy.response.simple_cookie[self.cookie_name] 
     88            testutil.start_server() 
     89            response = testutil.go('/') 
     90            cookies = SimpleCookie(response.headers['Set-Cookie']) 
     91            morsel = cookies[self.cookie_name] 
    8692        finally: 
    8793            config.update({'visit.cookie.permanent': permanent}) 
    88         assert morsel['max-age'] == 3000 
     94        assert morsel['max-age'] == '3000' 
    8995        expires = time.mktime(time.strptime(morsel['expires'], 
    9096            '%a, %d-%b-%Y %H:%M:%S GMT')[:8] + (0,)) 
    91         should_expire = time.mktime(time.gmtime()) + morsel['max-age'] 
    92         assert abs(should_expire - expires) < 3 
     97        should_expire = time.mktime(time.gmtime()) + int(morsel['max-age']) 
     98        assert abs(should_expire - expires) < 3, (should_expire, expires, should_expire - expires) 
     99 
  • turbogears/visit/api.py

     
    251251        max_age = self.cookie_max_age 
    252252        if max_age: 
    253253            # use 'expires' because MSIE ignores 'max-age' 
    254             cookies[self.cookie_name]['expires'] = time.strftime( 
     254            cookies[self.cookie_name]['expires'] = '"%s"' % time.strftime( 
    255255                "%a, %d-%b-%Y %H:%M:%S GMT", 
    256256                time.gmtime(time.time() + max_age)) 
    257257            # 'max-age' takes precedence on standard conformant browsers 
  • turbogears/tests/test_form_controllers.py

     
    3131    def testform(self, name, date, age, tg_errors=None): 
    3232        if tg_errors: 
    3333            self.has_errors = True 
    34         self.name = name 
    35         self.age = age 
    36         self.date = date 
     34        return dict(name=name, user_age=age, birthdate=date) 
    3735 
    3836    @expose() 
    3937    @validate(form=myform) 
    4038    def testform_new_style(self, name, date, age): 
    4139        if cherrypy.request.validation_errors: 
    4240            self.has_errors = True 
    43         self.name = name 
    44         self.age = age 
    45         self.date = date 
     41        return dict(name=name, age=age, date=date) 
    4642 
    4743def test_form_translation(): 
    4844    """Form input is translated into properly converted parameters""" 
    49     root = MyRoot() 
    50     cherrypy.root = root 
    51     testutil.create_request("/testform?name=ed&date=11/05/2005&age=5") 
    52     assert root.name == "ed" 
    53     assert root.age == 5 
     45    testutil.start_server(root = MyRoot()) 
     46    response = testutil.go("/testform?name=ed&date=11/05/2005&age=5") 
     47    assert response.raw['name'] == "ed" 
     48    assert response.raw['user_age'] == 5 
    5449 
    5550def test_form_translation_new_style(): 
    5651    """Form input is translated into properly converted parameters""" 
    57     root = MyRoot() 
    58     cherrypy.root = root 
    59     testutil.create_request("/testform_new_style?name=ed&date=11/05/2005&age=5&") 
    60     assert root.name == "ed" 
    61     assert root.age == 5 
     52    testutil.start_server(root = MyRoot()) 
     53    response = testutil.go("/testform_new_style?name=ed&date=11/05/2005&age=5&") 
     54    assert response.raw['name'] == "ed" 
     55    assert response.raw['age'] == 5 
    6256 
    6357def test_invalid_form_with_error_handling(): 
    6458    """Invalid forms can be handled by the method""" 
    65     root = cherrypy.root 
    66     testutil.create_request("/testform?name=ed&age=edalso&date=11/05/2005") 
    67     assert root.has_errors 
     59    response = testutil.go("/testform?name=ed&age=edalso&date=11/05/2005") 
    6860 
    6961def test_css_should_appear(): 
    7062    """CSS should appear when asked for""" 
    71     testutil.create_request("/") 
    72     assert "calendar-system.css" in cherrypy.response.body[0] 
     63    testutil.start_server(root = MyRoot()) 
     64    response = testutil.go("/") 
     65    assert "calendar-system.css" in response 
    7366 
    7467def test_javascript_should_appear(): 
    7568    """JavaScript should appear when asked for""" 
    76     testutil.create_request("/") 
    77     assert "calendar.js" in cherrypy.response.body[0] 
     69    response = testutil.go("/") 
     70    assert "calendar.js" in response 
    7871 
    7972def test_include_mochikit(): 
    8073    """JSLinks (and MochiKit especially) can be included easily""" 
    81     testutil.create_request("/usemochi") 
    82     assert "MochiKit.js" in cherrypy.response.body[0] 
     74    response = testutil.go("/usemochi") 
     75    assert "MochiKit.js" in response 
    8376 
    8477def test_suppress_mochikit(): 
    8578    """MochiKit inclusion can be suppressed""" 
    86     config.update({"global": {"tg.mochikit_suppress": True}}) 
    87     testutil.create_request("/usemochi") 
    88     suppressed_body = cherrypy.response.body[0] 
     79    config.update({"global":{"tg.mochikit_suppress" : True}}) 
     80    suppressed = testutil.go("/usemochi") 
    8981    # repair the fixture 
    90     config.update({"global": {"tg.mochikit_suppress": False}}) 
    91     testutil.create_request("/usemochi") 
    92     included_body = cherrypy.response.body[0] 
    93     assert "MochiKit.js" not in suppressed_body 
    94     assert "MochiKit.js" in included_body 
     82    config.update({"global":{"tg.mochikit_suppress" : False}}) 
    9583 
     84    included = testutil.go("/usemochi") 
     85    assert "MochiKit.js" not in suppressed.body 
     86    assert "MochiKit.js" in included.body 
     87 
    9688def test_mochikit_everywhere(): 
    9789    """MochiKit can be included everywhere by setting tg.mochikit_all""" 
    98     config.update({"global": {"tg.mochikit_all": True}}) 
    99     testutil.create_request("/") 
    100     config.update({"global": {"tg.mochikit_all": False}}) 
    101     assert "MochiKit.js" in cherrypy.response.body[0] 
     90    config.update({"global":{"tg.mochikit_all" : True}}) 
     91    response = testutil.go("/") 
     92    config.update({"global":{"tg.mochikit_all" : False}}) 
     93    assert "MochiKit.js" in response 
    10294 
    10395def test_mochikit_nowhere(): 
    10496    """Setting tg.mochikit_suppress will prevent including it everywhere""" 
    10597    config.update({"global": {"tg.mochikit_all": True}}) 
    10698    config.update({"global": {"tg.mochikit_suppress": True}}) 
    107     testutil.create_request("/") 
     99    response = testutil.go("/") 
    108100    config.update({"global": {"tg.mochikit_all": False}}) 
    109101    config.update({"global": {"tg.mochikit_suppress": False}}) 
    110     assert "MochiKit.js" not in cherrypy.response.body[0] 
     102    assert "MochiKit.js" not in response 
    111103 
    112104def test_include_widgets(): 
    113105    """Any widget can be included everywhere by setting tg.include_widgets""" 
    114106    config.update({"global": {"tg.include_widgets": ["mochikit"]}}) 
    115     testutil.create_request("/") 
     107    response = testutil.go("/") 
    116108    config.update({"global": {"tg.include_widgets": []}}) 
    117     assert "MochiKit.js" in cherrypy.response.body[0] 
     109    assert "MochiKit.js" in response 
    118110 
    119111 
    120112class State(object): 
     
    146138        super(TestValidationState, self).__init__(*args, **kw) 
    147139 
    148140    def test_counter_is_incremented(self): 
    149         cherrypy.root = self.Controller() 
     141        testutil.start_server(root = self.Controller()) 
    150142        # parameter values are irrelevant 
    151143        url = '/validation?a=1&b=2&c.a=3&c.b=4' 
    152         testutil.create_request(url) 
    153         body = cherrypy.response.body[0] 
     144        response = testutil.go(url) 
    154145        msg = "Validation state is not handled properly" 
    155146        # 4 == 1 (a) + 1(b) + 1(c.a) + 1(c.b) 
    156         self.failUnless('counter: 4' in body, msg) 
     147        self.failUnless('counter: 4' in response, msg) 
  • turbogears/tests/test_errorhandling.py

     
    11import unittest 
    2  
    3 import cherrypy 
    4  
    52from turbogears.controllers import error_handler, exception_handler, \ 
    63                                   expose, validate, RootController, Controller 
    74from turbogears.errorhandling import FailsafeSchema 
     
    9491        "second": validators.Int(not_empty=True)}) 
    9592    @error_handler(defaulterrorhandler) 
    9693    def positionalargs(self, first, second, *args, **kw): 
    97         self.first = first 
    98         self.second = second 
    99         self.third = args[0] 
    10094        return dict(title="Positional arguments", first=first, second=second, 
    101                     args=args, bar=kw["bar"]) 
     95                    third=args[0], args=args, bar=kw["bar"]) 
    10296 
    10397    @expose() 
    10498    @validate(validators={"bar": validators.Int(not_empty=True)}) 
     
    141135        return self.notexposed(bar) 
    142136 
    143137    def continuation(self, tg_source): 
    144         self.continuation = True 
    145         return tg_source(self) 
     138        response = tg_source(self) 
     139        response['continuation'] = True 
     140        return response 
    146141 
    147142    @expose() 
    148143    @validate(validators={"bar": validators.Int(not_empty=True)}) 
     
    211206class TestErrorHandler(unittest.TestCase): 
    212207 
    213208    def setUp(self): 
    214         cherrypy.root = MyRoot() 
    215         cherrypy.root.nestedcontroller = NestedController() 
     209        testutil.mount(MyRoot()) 
     210        testutil.mount(NestedController(), "/nestedcontroller") 
     211        testutil.start_server() 
    216212 
    217213    def test_defaultErrorHandler(self): 
    218214        """Default error handler.""" 
    219         testutil.create_request("/defaulterror?bar=abc") 
    220         self.failUnless("Default error handler" in cherrypy.response.body[0]) 
    221         testutil.create_request("/defaulterror?bar=true") 
    222         self.failUnless("Default error provider" in cherrypy.response.body[0]) 
     215        response = testutil.go("/defaulterror?bar=abc") 
     216        self.failUnless("Default error handler" in response) 
     217        response = testutil.go("/defaulterror?bar=true") 
     218        self.failUnless("Default error provider" in response) 
    223219 
    224220    def test_specialisedErrorHandler(self): 
    225221        """Error handler specialisation.""" 
    226         testutil.create_request("/specialisederror?bar=abc&baz=a@b.com") 
    227         self.failUnless("Default error handler" in cherrypy.response.body[0]) 
    228         testutil.create_request("/specialisederror?baz=abc&bar=1") 
    229         self.failUnless("Specialised error handler" in 
    230                         cherrypy.response.body[0]) 
    231         testutil.create_request("/specialisederror?bar=1&baz=a@b.com") 
    232         self.failUnless("Specialised error provider" in 
    233                         cherrypy.response.body[0]) 
     222        response = testutil.go("/specialisederror?bar=abc&baz=a@b.com") 
     223        self.failUnless("Default error handler" in response) 
     224        response = testutil.go("/specialisederror?baz=abc&bar=1") 
     225        self.failUnless("Specialised error handler" in response) 
     226        response = testutil.go("/specialisederror?bar=1&baz=a@b.com") 
     227        self.failUnless("Specialised error provider" in response) 
    234228 
    235229    def test_exceptionErrorHandler(self): 
    236230        """Error handler for exceptions.""" 
    237         testutil.create_request("/exceptionerror") 
    238         self.failUnless("Default error handler" in cherrypy.response.body[0]) 
     231        response = testutil.go("/exceptionerror") 
     232        self.failUnless("Default error handler" in response) 
    239233 
    240234    def test_recursiveErrorHandler(self): 
    241235        """Recursive error handler.""" 
    242         testutil.create_request("/recursiveerror?bar=abc") 
    243         self.failUnless("Recursive error handler" in cherrypy.response.body[0]) 
    244         testutil.create_request("/recursiveerror?bar=1") 
    245         self.failUnless("Recursive error provider" in 
    246                         cherrypy.response.body[0]) 
     236        response = testutil.go("/recursiveerror?bar=abc") 
     237        self.failUnless("Recursive error handler" in response) 
     238        response = testutil.go("/recursiveerror?bar=1") 
     239        self.failUnless("Recursive error provider" in response) 
    247240 
    248241    def test_implicitErrorHandler(self): 
    249242        """Implicit error handling.""" 
    250         testutil.create_request("/impliciterror?bar=abc") 
    251         self.failUnless("Implicit error handler" in 
    252                         cherrypy.response.body[0]) 
    253         testutil.create_request("/impliciterror?bar=1") 
    254         self.failUnless("Implicit error provider" in 
    255                         cherrypy.response.body[0]) 
     243        response = testutil.go("/impliciterror?bar=abc") 
     244        self.failUnless("Implicit error handler" in response) 
     245        response = testutil.go("/impliciterror?bar=1") 
     246        self.failUnless("Implicit error provider" in response) 
    256247 
    257248    def test_normalMethodErrorHandler(self): 
    258249        """Normal method as an error handler.""" 
    259         testutil.create_request("/normalmethodcaller?bar=abc") 
    260         self.failUnless("Normal method" in cherrypy.response.body[0]) 
    261         testutil.create_request("/normalmethodcaller?bar=true") 
    262         self.failUnless("Normal method caller" in cherrypy.response.body[0]) 
     250        response = testutil.go("/normalmethodcaller?bar=abc") 
     251        self.failUnless("Normal method" in response) 
     252        response = testutil.go("/normalmethodcaller?bar=true") 
     253        self.failUnless("Normal method caller" in response) 
    263254 
    264255    def test_infiniteRecursionPrevention(self): 
    265256        """Infinite recursion prevention.""" 
    266         testutil.create_request("/infiniteloop") 
    267         self.failUnless("Exception 2" in cherrypy.response.body[0]) 
     257        response = testutil.go("/infiniteloop") 
     258        self.failUnless("Exception 2" in response) 
    268259 
    269260    def test_positionalArgs(self): 
    270261        """Positional argument validation.""" 
    271         testutil.create_request("/positionalargs/first/23/third?bar=abc") 
    272         self.failUnless("Default error handler" in cherrypy.response.body[0]) 
    273         testutil.create_request("/positionalargs/first/abc/third?bar=false") 
    274         self.failUnless("Default error handler" in cherrypy.response.body[0]) 
    275         testutil.create_request("/positionalargs/first/abc/third?bar=abc") 
    276         self.failUnless("Default error handler" in cherrypy.response.body[0]) 
    277         testutil.create_request("/positionalargs/first/23/third?bar=true") 
    278         self.failUnless("Positional arguments" in cherrypy.response.body[0]) 
    279         self.failUnless(cherrypy.root.first == "first") 
    280         self.failUnless(cherrypy.root.second == 23) 
    281         self.failUnless(cherrypy.root.third == "third") 
     262        response = testutil.go("/positionalargs/first/23/third?bar=abc") 
     263        self.failUnless("Default error handler" in response) 
     264        response = testutil.go("/positionalargs/first/abc/third?bar=false") 
     265        self.failUnless("Default error handler" in response) 
     266        response = testutil.go("/positionalargs/first/abc/third?bar=abc") 
     267        self.failUnless("Default error handler" in response) 
     268        response = testutil.go("/positionalargs/first/23/third?bar=true") 
     269        self.failUnless("Positional arguments" in response) 
     270        self.failUnless(response.raw['first'] == "first") 
     271        self.failUnless(response.raw['second'] == 23) 
     272        self.failUnless(response.raw['third'] == "third") 
    282273 
    283274    def test_missingArgs(self): 
    284275        """Arguments required in validation missing.""" 
    285         testutil.create_request("/missingargs") 
    286         self.failUnless("Default error handler" in cherrypy.response.body[0]) 
    287         testutil.create_request("/missingargs?bar=12") 
    288         self.failUnless("Missing args provider" in cherrypy.response.body[0]) 
     276        response = testutil.go("/missingargs") 
     277        self.failUnless("Default error handler" in response) 
     278        response = testutil.go("/missingargs?bar=12") 
     279        self.failUnless("Missing args provider" in response) 
    289280 
    290281    def test_nohandler(self): 
    291282        """No error hanlder declared.""" 
    292         testutil.create_request("/nohandler") 
    293         self.failUnless("Exception raised" in cherrypy.response.body[0]) 
     283        response = testutil.go("/nohandler") 
     284        self.failUnless("Exception raised" in response) 
    294285 
    295286    def test_bindArgs(self): 
    296287        """Arguments can be bond to an error handler.""" 
    297         testutil.create_request("/bindargs") 
    298         self.failUnless("123" in cherrypy.response.body[0]) 
     288        response = testutil.go("/bindargs") 
     289        self.failUnless("123" in response) 
    299290 
    300291    def test_notExposed(self): 
    301292        """Validation error handling is decoupled from expose.""" 
    302         testutil.create_request("/notexposedcaller?foo=a&bar=rab&baz=c") 
    303         self.failUnless("Not exposed error" in cherrypy.response.body[0]) 
    304         self.failUnless("rab" in cherrypy.response.body[0]) 
     293        response = testutil.go("/notexposedcaller?foo=a&bar=rab&baz=c") 
     294        self.failUnless("Not exposed error" in response) 
     295        self.failUnless("rab" in response) 
    305296 
    306297    def test_continuations(self): 
    307298        """Continuations via error handling mechanism.""" 
    308         testutil.create_request("/continuationcaller?bar=a") 
    309         self.failUnless("Continuation caller" in cherrypy.response.body[0]) 
    310         self.failUnless(cherrypy.root.continuation == True) 
     299        response = testutil.go("/continuationcaller?bar=a") 
     300        self.failUnless("Continuation caller" in response) 
     301        self.failUnless(response.raw['continuation'] == True) 
    311302 
    312303    def test_nested(self): 
    313304        """Potentially ambiguous cases.""" 
    314         testutil.create_request("/nest?bar=a") 
    315         self.failUnless("Default error handler" in cherrypy.response.body[0]) 
    316         testutil.create_request("/nestedcontroller/nest?bar=a") 
    317         self.failUnless("Nested" in cherrypy.response.body[0]) 
     305        response = testutil.go("/nest?bar=a") 
     306        self.failUnless("Default error handler" in response) 
     307        response = testutil.go("/nestedcontroller/nest?bar=a") 
     308        self.failUnless("Nested" in response) 
    318309 
    319310    def test_failsafe(self): 
    320311        """Failsafe values for erroneous input.""" 
    321         testutil.create_request("/failsafenone?bar=a&baz=b") 
    322         self.failUnless('"bar": "a"' in cherrypy.response.body[0]) 
    323         self.failUnless('"baz": "b"' in cherrypy.response.body[0]) 
    324         testutil.create_request("/failsafevaluesdict?bar=a&baz=b") 
    325         self.failUnless('"bar": 1' in cherrypy.response.body[0]) 
    326         self.failUnless('"baz": 2' in cherrypy.response.body[0]) 
    327         testutil.create_request("/failsafevaluesatom?bar=a&baz=b") 
    328         self.failUnless('"bar": 13' in cherrypy.response.body[0]) 
    329         self.failUnless('"baz": 13' in cherrypy.response.body[0]) 
    330         testutil.create_request("/failsafemaperrors?bar=a&baz=b") 
    331         self.failUnless('"bar": "Please enter an integer value"' in 
    332                         cherrypy.response.body[0]) 
    333         self.failUnless('"baz": "Please enter an integer value"' in 
    334                         cherrypy.response.body[0]) 
    335         testutil.create_request("/failsafeformencode?bar=a&baz=b") 
    336         self.failUnless('"bar": 1' in cherrypy.response.body[0]) 
    337         self.failUnless('"baz": 2' in cherrypy.response.body[0]) 
    338         testutil.create_request("/failsafedefaults?bar=a&baz=b") 
    339         self.failUnless('"bar": 1' in cherrypy.response.body[0]) 
    340         self.failUnless('"baz": 2' in cherrypy.response.body[0]) 
     312        response = testutil.go("/failsafenone?bar=a&baz=b") 
     313        self.failUnless('"bar": "a"' in response) 
     314        self.failUnless('"baz": "b"' in response) 
     315        response = testutil.go("/failsafevaluesdict?bar=a&baz=b") 
     316        self.failUnless('"bar": 1' in response) 
     317        self.failUnless('"baz": 2' in response) 
     318        response = testutil.go("/failsafevaluesatom?bar=a&baz=b") 
     319        self.failUnless('"bar": 13' in response) 
     320        self.failUnless('"baz": 13' in response) 
     321        response = testutil.go("/failsafemaperrors?bar=a&baz=b") 
     322        self.failUnless('"bar": "Please enter an integer value"' in response) 
     323        self.failUnless('"baz": "Please enter an integer value"' in response) 
     324        response = testutil.go("/failsafeformencode?bar=a&baz=b") 
     325        self.failUnless('"bar": 1' in response) 
     326        self.failUnless('"baz": 2' in response) 
     327        response = testutil.go("/failsafedefaults?bar=a&baz=b") 
     328        self.failUnless('"bar": 1' in response) 
     329        self.failUnless('"baz": 2' in response) 
  • turbogears/tests/test_sqlalchemy.py

     
    99from turbogears.database import metadata, session, mapper, \ 
    1010    bind_metadata, get_metadata 
    1111from turbogears.controllers import RootController 
    12 from turbogears.testutil import create_request, sqlalchemy_cleanup, \ 
     12from turbogears import testutil 
     13from turbogears.testutil import go, sqlalchemy_cleanup, \ 
    1314    capture_log, print_log 
    1415 
    1516 
     
    135136        will be marked with this name :) 
    136137 
    137138        """ 
    138         cherrypy.response.code = 501 
    139139        msg = "KARL25 responding\n" 
    140140        msg += "user with id: '%s' should not be saved.\n" % id 
    141141        msg += "An exception occurred: %r (%s)" % ((tg_exceptions,)*2) 
     
    165165def test_implicit_trans_no_error(): 
    166166    """If a controller runs sucessfully, the transaction is commited.""" 
    167167    capture_log("turbogears.database") 
    168     cherrypy.root = MyRoot() 
    169     create_request("/no_error?name=A.%20Dent") 
    170     output = cherrypy.response.body[0] 
    171     print output 
     168    testutil.start_server(root = MyRoot()) 
     169    response = go("/no_error?name=A.%20Dent") 
    172170    print_log() 
    173171    q = session.query(Person) 
    174172    arthur = q.filter_by(name="A. Dent").first() 
    175     assert 'someconfirmhandler' in output, \ 
     173    assert 'someconfirmhandler' in response, \ 
    176174        'The no error should have redirected to someconfirmhandler' 
    177175    assert arthur is not None, 'Person arthur should have been saved!' 
    178176    assert arthur.name == "A. Dent", 'Person arthur should be named "A. Dent"' 
     
    180178def test_raise_sa_exception(): 
    181179    """If a controller causes an SA exception, it is raised properly.""" 
    182180    capture_log("turbogears.database") 
    183     cherrypy.root = MyRoot() 
    184     create_request("/create_person?id=20") 
    185     output = cherrypy.response.body[0] 
     181    testutil.start_server(root = MyRoot()) 
     182    response = go("/create_person?id=20") 
    186183    print_log() 
    187     print output 
    188     assert 'No exceptions occurred' in output 
    189     assert cherrypy.response.status.startswith("200") 
    190     create_request("/create_person?id=20") 
    191     output = cherrypy.response.body[0] 
    192     assert cherrypy.response.status.startswith("500") 
    193     print output 
    194     assert 'KARL25' not in output, \ 
     184    assert 'No exceptions occurred' in response 
     185    response = go("/create_person?id=20", status=500) 
     186    assert 'KARL25' not in response, \ 
    195187        'Exception should NOT have been handled by our handler' 
    196     assert 'DBAPIError' in output, \ 
     188    assert 'DBAPIError' in response, \ 
    197189        'The page should have displayed an SQLAlchemy exception' 
    198190 
    199191def test_user_exception(): 
    200192    """If a controller raises an exception, transactions are rolled back.""" 
    201193    capture_log("turbogears.database") 
    202     cherrypy.root = MyRoot() 
    203     create_request("/create_person?id=19&docom=0&doerr=1&name=Martin%20GAL") 
    204     output = cherrypy.response.body[0] 
     194    testutil.start_server(MyRoot()) 
     195    response = go("/create_person?id=19&docom=0&doerr=1&name=Martin%20GAL") 
    205196    print_log() 
    206     print output 
    207     assert 'KARL25' in output, \ 
     197    assert 'KARL25' in response, \ 
    208198        'The exception handler should have answered us' 
    209199    p = session.query(Person).get(19) 
    210200    assert p is None, \ 
     
    212202 
    213203def test_user_redirect(): 
    214204    """If a controller redirects, transactions are committed.""" 
    215     cherrypy.root = MyRoot() 
    216     create_request("/create_person?id=22&doerr=2") 
     205    testutil.start_server(MyRoot()) 
     206    go("/create_person?id=22&doerr=2") 
    217207    assert session.query(Person).get(22) is not None, \ 
    218208        'The controller only redirected, the Person should have been saved' 
    219209 
    220210def test_cntrl_commit(): 
    221211    """It's safe to commit a transaction in the controller.""" 
    222     cherrypy.root = MyRoot() 
    223     create_request("/create_person?id=23&docom=1") 
    224     assert 'InvalidRequestError' not in cherrypy.response.body[0] 
     212    testutil.start_server(MyRoot()) 
     213    response = go("/create_person?id=23&docom=1") 
     214    assert 'InvalidRequestError' not in response 
    225215    assert session.query(Person).get(23) is not None, \ 
    226216        'The Person 23 should have been saved during commit inside controller' 
    227217 
    228218def test_cntrl_commit2(): 
    229219    """A commit inside the controller is not rolled back by the exception.""" 
    230     cherrypy.root = MyRoot() 
    231     create_request("/create_person?id=24&docom=1&doerr=1") 
    232     assert 'InvalidRequestError' not in cherrypy.response.body[0] 
     220    testutil.start_server(MyRoot()) 
     221    response = go("/create_person?id=24&docom=1&doerr=1") 
     222    assert 'InvalidRequestError' not in response 
    233223    assert session.query(Person).get(24) is not None, \ 
    234224        'The Person 24 should have been saved during commit' \ 
    235225        ' inside controller and not rolled back' 
    236226 
    237227def test_cntrl_flush(): 
    238228    """It's safe to flush in the controller.""" 
    239     cherrypy.root = MyRoot() 
    240     create_request("/create_person?id=25&doflush=1") 
    241     print cherrypy.response.body[0] 
    242     assert 'No exceptions occurred' in cherrypy.response.body[0] 
    243     create_request("/create_person?id=25&doflush=0") 
    244     assert cherrypy.response.status.startswith("500") 
    245     assert 'IntegrityError' in cherrypy.response.body[0] 
    246     create_request("/create_person?id=25&doflush=1") 
    247     assert cherrypy.response.status.startswith("200") 
    248     assert 'IntegrityError' in cherrypy.response.body[0] 
    249     create_request("/create_person?id=25&doflush=2") 
    250     assert cherrypy.response.status.startswith("200") 
    251     assert 'No exceptions occurred' in cherrypy.response.body[0] 
     229    testutil.start_server(MyRoot()) 
     230    response = go("/create_person?id=25&doflush=1") 
     231    assert 'No exceptions occurred' in response 
     232    response = go("/create_person?id=25&doflush=0", status=500) 
     233    assert 'IntegrityError' in response 
     234    response = go("/create_person?id=25&doflush=1") 
     235    assert 'IntegrityError' in response 
     236    response = go("/create_person?id=25&doflush=2") 
     237    assert 'No exceptions occurred' in response 
    252238 
    253239 
    254240# Exception handling with rollback 
     
    301287    is created by the exception handler. 
    302288 
    303289    """ 
    304     cherrypy.root = RbRoot() 
    305     create_request('/doerr?id=26') 
    306     output = cherrypy.response.body[0] 
    307     print output 
    308     assert 'KARL27' in output, 'Exception handler should have answered' 
     290    testutil.start_server(RbRoot()) 
     291    response = go('/doerr?id=26') 
     292    assert 'KARL27' in response, 'Exception handler should have answered' 
    309293    assert session.query(User).get(26) is None 
    310294    assert session.query(User).get(27) is not None 
    311295 
     
    316300    so user XX should not exist. 
    317301 
    318302    """ 
    319     cherrypy.root = RbRoot() 
    320     create_request('/doerr?id=XX') 
    321     output = cherrypy.response.body[0] 
    322     assert 'KARL27' in output, 'Exception handler should have answered' 
     303    testutil.start_server(RbRoot()) 
     304    response = go('/doerr?id=XX') 
     305    assert 'KARL27' in response, 'Exception handler should have answered' 
    323306    assert session.query(User).get('XX') is None 
    324307 
    325308def test_exc_done_rollback(): 
    326309    """No problems with error handler if controller manually rollbacks.""" 
    327     cherrypy.root = RbRoot() 
    328     create_request('/doerr?id=28&dorb=1') 
    329     output = cherrypy.response.body[0] 
    330     assert 'KARL27' in output, 'Exception handler should have answered' 
     310    testutil.start_server(RbRoot()) 
     311    response = go('/doerr?id=28&dorb=1') 
     312    assert 'KARL27' in response, 'Exception handler should have answered' 
    331313    assert session.query(User).get(28) is None 
    332314    assert session.query(User).get(29) is not None 
    333315 
     
    360342 
    361343    """ 
    362344    test_table.insert().execute(dict(id=1, val='a')) 
    363     cherrypy.root = FreshRoot() 
    364     create_request("/test1") 
    365     assert cherrypy.response.status.startswith("200") 
    366     assert 'AssertionError' not in cherrypy.response.body[0] 
     345    testutil.start_server(FreshRoot()) 
     346    response = go("/test1", status = 200) 
     347    assert 'AssertionError' not in response 
    367348    # Call test2 in a different thread 
    368349    class ThreadB(threading.Thread): 
    369350        def run(self): 
    370             create_request("/test2") 
    371             assert cherrypy.response.status.startswith("200") 
    372             assert 'AssertionError' not in cherrypy.response.body[0] 
     351            response = go("/test2", status=200) 
     352            assert 'AssertionError' not in response 
    373353    thrdb = ThreadB() 
    374354    thrdb.start() 
    375355    thrdb.join() 
    376     create_request("/test3") 
    377     assert cherrypy.response.status.startswith("200") 
    378     assert 'AssertionError' not in cherrypy.response.body[0] 
     356    response = go("/test3", status=200) 
     357    assert 'AssertionError' not in response 
  • turbogears/tests/test_expose.py

     
    1 import cherrypy 
    21import simplejson 
    3  
    42from turbogears import controllers, expose 
    5 from turbogears.testutil import create_request 
     3from turbogears.testutil import go, start_server 
    64 
    75 
    86class ExposeRoot(controllers.RootController): 
     
    2018 
    2119 
    2220def test_gettinghtml(): 
    23     cherrypy.root = ExposeRoot() 
    24     create_request("/with_json") 
    25     body = cherrypy.response.body[0] 
    26     assert "Paging all foo" in body 
     21    start_server(root = ExposeRoot()) 
     22    response = go("/with_json") 
     23    assert "Paging all foo" in response 
    2724 
    2825def test_gettingjson(): 
    29     cherrypy.root = ExposeRoot() 
    30     create_request("/with_json?tg_format=json") 
    31     body = cherrypy.response.body[0] 
    32     assert '"title": "Foobar"' in body 
     26    start_server(root = ExposeRoot()) 
     27    response = go("/with_json?tg_format=json") 
     28    assert '"title": "Foobar"' in response 
    3329 
    3430def test_gettingjsonviaaccept(): 
    35     cherrypy.root = ExposeRoot() 
    36     create_request("/with_json_via_accept", 
     31    start_server(root = ExposeRoot()) 
     32    response = go("/with_json_via_accept", 
    3733            headers=dict(Accept="text/javascript")) 
    38     body = cherrypy.response.body[0] 
    39     assert '"title": "Foobar"' in body 
     34    assert '"title": "Foobar"' in response 
    4035 
    4136def test_getting_json_with_accept_but_using_tg_format(): 
    42     cherrypy.root = ExposeRoot() 
    43     create_request("/with_json_via_accept?tg_format=json") 
    44     body = cherrypy.response.body[0] 
    45     assert '"title": "Foobar"' in body 
     37    start_server(root = ExposeRoot()) 
     38    response = go("/with_json_via_accept?tg_format=json") 
     39    assert '"title": "Foobar"' in response 
    4640 
    4741def test_getting_plaintext(): 
    48     cherrypy.root = ExposeRoot() 
    49     create_request("/with_json_via_accept", 
     42    start_server(root = ExposeRoot()) 
     43    response = go("/with_json_via_accept", 
    5044        headers=dict(Accept="text/plain")) 
    51     print cherrypy.response.body[0] 
    52     assert cherrypy.response.body[0] == "This is a plain text for foo." 
     45    assert response.body == "This is a plain text for foo." 
    5346 
    5447def test_allow_json(): 
    5548 
     
    5851        def test(self): 
    5952            return dict(title="Foobar", mybool=False, someval="niggles") 
    6053 
    61     cherrypy.root = NewRoot() 
    62     create_request("/test", headers= dict(accept="text/javascript")) 
    63     body = cherrypy.response.body[0] 
    64     values = simplejson.loads(body) 
     54    start_server(root = NewRoot()) 
     55    response = go("/test", headers= dict(accept="text/javascript")) 
     56    values = simplejson.loads(response.body) 
    6557    assert values == dict(title="Foobar", mybool=False, someval="niggles", 
    6658        tg_flash=None) 
    67     assert cherrypy.response.headers["Content-Type"] == "text/javascript" 
    68     create_request("/test?tg_format=json") 
    69     body = cherrypy.response.body[0] 
    70     values = simplejson.loads(body) 
     59    assert response.headers["Content-Type"] == "text/javascript" 
     60    response = go("/test?tg_format=json") 
     61    values = simplejson.loads(response.body) 
    7162    assert values == dict(title="Foobar", mybool=False, someval="niggles", 
    7263        tg_flash=None) 
    73     assert cherrypy.response.headers["Content-Type"] == "text/javascript" 
     64    assert response.headers["Content-Type"] == "text/javascript" 
  • turbogears/tests/test_controllers.py

     
    11import unittest 
    2 import formencode 
    3 import cherrypy 
    4 import pkg_resources 
     2import urllib 
     3import turbogears 
    54from turbogears import config, controllers, database, \ 
    65    error_handler, exception_handler, expose, flash, redirect, \ 
    76    startup, testutil, url, validate, validators 
     7from turbogears.testutil import go 
     8import simplejson 
     9import formencode 
     10import cherrypy 
     11import pkg_resources 
     12from nose.tools import eq_ 
    813 
    914 
    1015class SubApp(controllers.RootController): 
     
    1318    def index(self): 
    1419        return url("/Foo/") 
    1520 
     21    @expose() 
     22    def foo(self): 
     23        return url("foo") 
    1624 
     25    @expose() 
     26    def foo2(self): 
     27        return url("/foo") 
     28 
     29    @expose() 
     30    def redir(self): 
     31        turbogears.redirect("/foo") 
     32 
     33    @expose() 
     34    def redir2(self): 
     35        raise turbogears.redirect("/foo") 
     36 
     37 
     38 
    1739class MyRoot(controllers.RootController): 
    1840 
    1941    @expose() 
    2042    def index(self): 
    21         pass 
     43        return {} 
    2244 
    2345    def validation_error_handler(self, tg_source, tg_errors, *args, **kw): 
    24         self.functionname = tg_source.__name__ 
    25         self.values = kw 
    2646        self.errors = tg_errors 
    27         return "Error Message" 
     47        errors = {} 
     48        for (key, value) in tg_errors.items(): 
     49           if hasattr(value, 'msg'): 
     50               errors[key] = value.msg 
     51           else: 
     52               errors[key] = value 
     53        return dict(msg = "Error Message", values = kw, errors = errors) 
    2854 
    2955    @expose(html="turbogears.tests.simple", allow_json=True) 
    3056    def test(self): 
     
    3662 
    3763    @expose() 
    3864    def pos(self, posvalue): 
    39         self.posvalue = posvalue 
    40         return "" 
     65        return dict(posvalue = posvalue) 
    4166 
    4267    @expose() 
    43     def servefile(self, tg_exceptions=None): 
    44         self.servedit = True 
    45         self.serve_exceptions = tg_exceptions 
     68    def servefile(self): 
    4669        return cherrypy.lib.cptools.serveFile( 
    4770            pkg_resources.resource_filename( 
    4871                "turbogears.tests", "test_controllers.py")) 
     
    7093    @validate(validators={'value': validators.StringBoolean()}) 
    7194    @error_handler(validation_error_handler) 
    7295    def istrue(self, value): 
    73         self.value = value 
    74         return str(value) 
     96        return dict(value=str(value)) 
    7597 
    7698    @expose() 
    7799    @validate(validators={'value': validators.StringBoolean()}) 
     
    117139        "lastname": validators.String()}) 
    118140    @error_handler(validation_error_handler) 
    119141    def save(self, submit, firstname, lastname="Miller"): 
    120         self.submit = submit 
    121         self.firstname = firstname 
    122         self.lastname = lastname 
    123         self.fullname = "%s %s" % (self.firstname, self.lastname) 
    124         return self.fullname 
     142        submit = submit 
     143        firstname = firstname 
     144        lastname = lastname 
     145        fullname = "%s %s" % (firstname, lastname) 
     146        return dict(firstname = firstname, lastname = lastname,  
     147            fullname = fullname, submit = submit) 
    125148 
    126149    class Registration(formencode.Schema): 
    127150        allow_extra_fields = True 
     
    145168    rwt_called = 0 
    146169    def rwt(self, func, *args, **kw): 
    147170        self.rwt_called += 1 
    148         func(*args, **kw) 
     171        result = func(*args, **kw) 
     172        print result 
     173        result += 'rwt_called = %s' % self.rwt_called 
     174        return result 
    149175 
    150176    @expose(html="turbogears.tests.simple", allow_json=True) 
    151177    def flash_plain(self): 
     
    223249class TestRoot(unittest.TestCase): 
    224250 
    225251    def setUp(self): 
    226         cherrypy.root = None 
    227         cherrypy.tree.mount_points = {} 
    228         cherrypy.tree.mount(MyRoot(), "/") 
    229         cherrypy.tree.mount(SubApp(), "/subthing") 
     252        testutil.mount(MyRoot()) 
     253        testutil.mount(SubApp(), '/subthing') 
    230254 
    231     def tearDown(self): 
    232         cherrypy.root = None 
    233         cherrypy.tree.mount_points = {} 
    234  
    235255    def test_js_files(self): 
    236256        """Can access the JavaScript files""" 
    237         testutil.create_request("/tg_js/MochiKit.js") 
    238         assert cherrypy.response.headers[ 
    239             "Content-Type"] == "application/x-javascript" 
    240         assert cherrypy.response.status == "200 OK" 
     257        response = testutil.go("/tg_js/MochiKit.js", status=200) 
     258        assert response.headers["Content-Type"] == "application/x-javascript" 
    241259 
    242260    def test_json_output(self): 
    243         testutil.create_request("/test?tg_format=json") 
    244         import simplejson 
    245         values = simplejson.loads(cherrypy.response.body[0]) 
    246         assert values == dict(title="Foobar", mybool=False, 
    247             someval="niggles", tg_flash=None) 
    248         assert cherrypy.response.headers["Content-Type"] == "text/javascript" 
     261        response = testutil.go("/test?tg_format=json") 
     262        values = simplejson.loads(response.body) 
     263        eq_(values, dict(title="Foobar", mybool=False, 
     264            someval="niggles", tg_flash=None)) 
     265        assert response.headers["Content-Type"] == "text/javascript" 
    249266 
    250267    def test_implied_json(self): 
    251         testutil.create_request("/impliedjson?tg_format=json") 
    252         assert '"title": "Blah"' in cherrypy.response.body[0] 
     268        response = testutil.go("/impliedjson?tg_format=json") 
     269        assert '"title": "Blah"' in response.body 
    253270 
    254271    def test_allow_json(self): 
    255         testutil.create_request("/allowjson?tg_format=json") 
    256         assert cherrypy.response.status.startswith("500") 
    257         assert cherrypy.response.headers["Content-Type"] == "text/html" 
     272        response = testutil.go("/allowjson?tg_format=json", status=500) 
     273        assert response.headers["Content-Type"] == "text/html", response.headers 
    258274 
    259275    def test_allow_json_config(self): 
    260276        """JSON output can be enabled via config.""" 
     
    264280            def allowjsonconfig(self): 
    265281                return dict(title="Foobar", mybool=False, someval="foo", 
    266282                     tg_html="turbogears.tests.simple") 
    267         cherrypy.root = JSONRoot() 
    268         testutil.create_request('/allowjsonconfig?tg_format=json') 
    269         assert cherrypy.response.headers["Content-Type"] == "text/javascript" 
    270         config.update({'tg.allow_json': False}) 
     283        testutil.mount(JSONRoot()) 
     284        response = testutil.go('/allowjsonconfig?tg_format=json') 
     285        assert response.headers["Content-Type"]=="text/javascript" 
     286        config.update({'tg.allow_json':False}) 
    271287 
    272288    def test_allow_json_config_false(self): 
    273289        """Make sure JSON can still be restricted with a global config on.""" 
     
    277293            def allowjsonconfig(self): 
    278294                return dict(title="Foobar", mybool=False, someval="foo", 
    279295                     tg_html="turbogears.tests.simple") 
    280         cherrypy.root = JSONRoot() 
    281         testutil.create_request('/allowjson?tg_format=json') 
    282         assert cherrypy.response.status.startswith("404") 
    283         assert cherrypy.response.headers["Content-Type"] == "text/html" 
     296        testutil.mount(JSONRoot()) 
     297        response = testutil.go('/allowjson?tg_format=json', status=404) 
     298        assert response.headers["Content-Type"]=="text/html" 
    284299        config.update({'tg.allow_json': False}) 
    285300 
    286301    def test_json_error(self): 
    287302        """The error handler should return JSON if requested.""" 
    288         testutil.create_request("/jsonerror") 
    289         assert cherrypy.response.headers["Content-Type"] == "text/html; charset=utf-8" 
    290         assert "Paging all errors" in cherrypy.response.body[0] 
    291         testutil.create_request("/jsonerror?tg_format=json") 
    292         assert cherrypy.response.headers["Content-Type"] == "text/javascript" 
    293         assert '"someval": "errors"' in cherrypy.response.body[0] 
     303        response = testutil.go("/jsonerror") 
     304        assert response.headers["Content-Type"] == "text/html; charset=utf-8" 
     305        assert "Paging all errors" in response 
     306        response = testutil.go("/jsonerror?tg_format=json") 
     307        assert response.headers["Content-Type"] == "text/javascript" 
     308        assert '"someval": "errors"' in response 
    294309 
    295310    def test_invalid_return(self): 
    296         testutil.create_request("/invalid") 
    297         assert cherrypy.response.status.startswith("500") 
     311        response = testutil.go("/invalid", status=500) 
    298312 
    299313    def test_strict_parameters(self): 
    300         config.update({"tg.strict_parameters": True}) 
    301         testutil.create_request( 
    302             "/save?submit=save&firstname=Foo&lastname=Bar&badparam=1") 
    303         assert cherrypy.response.status.startswith("500") 
    304         assert not hasattr(cherrypy.root, "errors") 
     314        config.update({"tg.strict_parameters" : True}) 
     315        response = testutil.go( 
     316            "/save?submit=save&firstname=Foo&lastname=Bar&badparam=1",  
     317            status = 500) 
    305318 
    306319    def test_throw_out_random(self): 
    307320        """Can append random value to the URL to avoid caching problems.""" 
    308         testutil.create_request("/test?tg_random=1") 
    309         assert "Paging all niggles" in cherrypy.response.body[0] 
     321        response = testutil.go("/test?tg_random=1") 
     322        assert "Paging all niggles" in response 
    310323        config.update({"tg.strict_parameters": True}) 
    311         testutil.create_request("/test?tg_random=1") 
    312         assert cherrypy.response.status.startswith("200") 
    313         assert "Paging all niggles" in cherrypy.response.body[0] 
    314         testutil.create_request("/test?tg_not_random=1") 
    315         assert cherrypy.response.status.startswith("500") 
    316         assert not hasattr(cherrypy.root, "errors") 
     324        response = testutil.go("/test?tg_random=1", status=200) 
     325        assert "Paging all niggles" in response 
     326        response = testutil.go("/test?tg_not_random=1", status=500) 
    317327 
    318328    def test_ignore_parameters(self): 
    319329        config.update({"tg.strict_parameters": True}) 
    320         testutil.create_request("/test?ignore_me=1") 
    321         assert cherrypy.response.status.startswith("500") 
    322         assert not hasattr(cherrypy.root, "errors") 
     330        response = testutil.go("/test?ignore_me=1", status=500) 
    323331        config.update({"tg.ignore_parameters": ['ignore_me', 'me_too']}) 
    324         testutil.create_request("/test?ignore_me=1") 
    325         assert "Paging all niggles" in cherrypy.response.body[0] 
    326         testutil.create_request("/test?me_too=1") 
    327         assert cherrypy.response.status.startswith("200") 
    328         assert "Paging all niggles" in cherrypy.response.body[0] 
    329         testutil.create_request("/test?me_not=1") 
    330         assert cherrypy.response.status.startswith("500") 
    331         assert not hasattr(cherrypy.root, "errors") 
     332        response = testutil.go("/test?ignore_me=1") 
     333        assert "Paging all niggles" in response 
     334        response = testutil.go("/test?me_too=1", status=200) 
     335        assert "Paging all niggles" in response 
     336        testutil.go("/test?me_not=1", status=500) 
     337        assert not response.raw.has_key('errors') 
    332338 
    333339    def test_retrieve_dict_directly(self): 
    334         d = testutil.call(cherrypy.root.returnjson) 
    335         assert d["title"] == "Foobar" 
     340        d = testutil.go("/returnjson") 
     341        assert d.raw['title'] == "Foobar" 
    336342 
    337343    def test_templateOutput(self): 
    338         testutil.create_request("/test") 
    339         assert "Paging all niggles" in cherrypy.response.body[0] 
     344        response = testutil.go("/test") 
     345        assert "Paging all niggles" in response 
    340346 
     347    def test_throw_out_random(self): 
     348        """A random value can be appended to the URL to avoid caching 
     349        problems.""" 
     350        response = testutil.go("/test?tg_random=1") 
     351        assert "Paging all niggles" in response 
     352 
    341353    def test_safari_unicode_fix(self): 
    342         testutil.create_request("/unicode", headers={'User-Agent': 
    343             "Apple WebKit Safari/412.2"}) 
    344         firstline = cherrypy.response.body[0].split('\n')[0] 
     354        response = go("/unicode", headers={'User-Agent' : 
     355            "Apple WebKit Safari/412.2"}, status='*') 
     356        firstline = response.body.split('\n')[0] 
    345357        assert firstline == "&#xbf;Habla espa&#xf1;ol?" 
    346358        assert isinstance(firstline, str) 
    347359 
    348360    def test_default_format(self): 
    349361        """The default format can be set via expose""" 
    350         testutil.create_request("/returnjson") 
    351         firstline = cherrypy.response.body[0] 
    352         assert '"title": "Foobar"' in firstline 
    353         testutil.create_request("/returnjson?tg_format=html") 
    354         assert cherrypy.response.status.startswith("500") 
    355         firstline = cherrypy.response.body[0] 
    356         assert '"title": "Foobar"' not in firstline 
     362        response = testutil.go("/returnjson") 
     363        assert '"title": "Foobar"' in response 
     364        response = testutil.go("/returnjson?tg_format=html", status=500) 
     365        assert '"title": "Foobar"' not in response 
    357366 
    358367    def test_content_type(self): 
    359368        """The content-type can be set via expose""" 
    360         testutil.create_request("/contenttype") 
    361         assert cherrypy.response.headers["Content-Type"] == "xml/atom" 
     369        response = testutil.go("/contenttype") 
     370        assert response.headers["Content-Type"] == "xml/atom" 
    362371 
    363372    def test_returned_template_name(self): 
    364         testutil.create_request("/returnedtemplate") 
    365         data = cherrypy.response.body[0].lower() 
     373        response = testutil.go("/returnedtemplate") 
     374        data = response.body.lower() 
    366375        assert "<body>" in data 
    367376        assert 'groovy test template' in data 
    368377 
    369378    def test_returned_template_short(self): 
    370         testutil.create_request("/returnedtemplate_short") 
    371         assert "Paging all foo" in cherrypy.response.body[0] 
     379        response = testutil.go("/returnedtemplate_short") 
     380        assert "Paging all foo" in response 
    372381 
    373382    def test_expose_template_short(self): 
    374         testutil.create_request("/exposetemplate_short") 
    375         assert "Paging all foo" in cherrypy.response.body[0] 
     383        response = testutil.go("/exposetemplate_short") 
     384        assert "Paging all foo" in response 
    376385 
    377386    def test_validation(self): 
    378387        """Data can be converted and validated""" 
    379         testutil.create_request("/istrue?value=true") 
    380         assert cherrypy.root.value is True 
    381         testutil.create_request("/istrue?value=false") 
    382         assert cherrypy.root.value is False 
    383         cherrypy.root = MyRoot() 
    384         testutil.create_request("/istrue?value=foo") 
    385         assert not hasattr(cherrypy.root, "value") 
    386         assert cherrypy.root.functionname == "istrue" 
    387         testutil.create_request("/save?submit=send&firstname=John&lastname=Doe") 
    388         assert cherrypy.root.fullname == "John Doe" 
    389         assert cherrypy.root.submit == "send" 
    390         testutil.create_request("/save?submit=send&firstname=Arthur") 
    391         assert cherrypy.root.fullname == "Arthur Miller" 
    392         testutil.create_request("/save?submit=send&firstname=Arthur&lastname=") 
    393         assert cherrypy.root.fullname == "Arthur " 
    394         testutil.create_request("/save?submit=send&firstname=D&lastname=") 
    395         assert len(cherrypy.root.errors) == 1 
    396         assert cherrypy.root.errors.has_key("firstname") 
    397         assert "characters" in cherrypy.root.errors["firstname"].msg.lower() 
    398         testutil.create_request("/save?submit=send&firstname=&lastname=") 
    399         assert len(cherrypy.root.errors) == 1 
    400         assert cherrypy.root.errors.has_key("firstname") 
     388        response = testutil.go("/istrue?value=true") 
     389        assert response.raw['value'] == 'True' 
     390        response = testutil.go("/istrue?value=false") 
     391        assert response.raw['value'] == 'False' 
     392        testutil.start_server(root = MyRoot()) 
     393        response = testutil.go("/istrue?value=foo") 
     394        assert not response.raw.has_key('value') 
    401395 
     396        response = testutil.go("/save?submit=send&firstname=John&lastname=Doe") 
     397        assert response.raw['fullname'] == "John Doe" 
     398        assert response.raw['submit'] == "send" 
     399        response = testutil.go("/save?submit=send&firstname=Arthur") 
     400        assert response.raw['fullname'] == "Arthur Miller" 
     401        response = testutil.go("/save?submit=send&firstname=Arthur&lastname=") 
     402        assert response.raw['fullname'] == "Arthur " 
     403        response = testutil.go("/save?submit=send&firstname=D&lastname=") 
     404        assert len(response.raw['errors'].keys()) == 1 
     405        assert response.raw['errors'].has_key("firstname") 
     406        assert "characters" in response.raw['errors']["firstname"].lower() 
     407        response = testutil.go("/save?submit=send&firstname=&lastname=") 
     408        assert len(response.raw['errors'].keys()) == 1 
     409        assert response.raw['errors'].has_key("firstname") 
     410 
    402411    def test_validation_chained(self): 
    403412        """Validation is not repeated if it already happened""" 
    404         cherrypy.root.value = None 
    405         testutil.create_request("/errorchain?value=true") 
    406         assert cherrypy.root.value is None 
    407         testutil.create_request("/errorchain?value=notbool") 
    408         assert cherrypy.root.value == 'notbool' 
     413        response = testutil.go("/errorchain?value=true") 
     414        assert not hasattr(response, 'raw') 
     415        response = testutil.go("/errorchain?value=notbool") 
     416        assert response.raw['value'] == 'notbool' 
    409417 
    410418    def test_validation_nested(self): 
    411419        """Validation is not repeated in nested method call""" 
    412         cherrypy.root.value = None 
    413         testutil.create_request("/nestedcall?value=true") 
    414         assert cherrypy.root.value == 'True' 
    415         testutil.create_request("/nestedcall?value=false") 
    416         assert cherrypy.root.value == 'False' 
     420        response = testutil.go("/nestedcall?value=true") 
     421        assert response.raw['value'] == 'True' 
     422        response = testutil.go("/nestedcall?value=false") 
     423        assert response.raw['value'] == 'False' 
    417424 
    418425    def test_validation_with_schema(self): 
    419         """Data can be converted/validated with formencode.Schema instance""" 
    420         testutil.create_request("/save2?submit=send&firstname=Joe&lastname=Doe") 
    421         assert cherrypy.root.fullname == "Joe Doe" 
    422         assert cherrypy.root.submit == "send" 
    423         testutil.create_request("/save2?submit=send&firstname=Arthur&lastname=") 
    424         assert cherrypy.root.fullname == "Arthur " 
    425         testutil.create_request("/save2?submit=send&firstname=&lastname=") 
    426         assert len(cherrypy.root.errors) == 1 
    427         assert cherrypy.root.errors.has_key("firstname") 
    428         testutil.create_request("/save2?submit=send&firstname=D&lastname=") 
    429         assert len(cherrypy.root.errors) == 1 
    430         assert cherrypy.root.errors.has_key("firstname") 
     426        """Data can be converted and validated with formencode.Schema instance""" 
     427        response = testutil.go("/save2?submit=send&firstname=Joe&lastname=Doe") 
     428        assert response.raw['fullname'] == "Joe Doe" 
     429        assert response.raw['submit'] == "send" 
     430        response = testutil.go("/save2?submit=send&firstname=Arthur&lastname=") 
     431        assert response.raw['fullname'] == "Arthur " 
     432        response = testutil.go("/save2?submit=send&firstname=&lastname=") 
     433        assert len(response.raw['errors'].keys()) == 1 
     434        assert response.raw['errors'].has_key("firstname") 
     435        response = testutil.go("/save2?submit=send&firstname=D&lastname=") 
     436        assert len(response.raw['errors'].keys()) == 1 
     437        assert response.raw['errors'].has_key("firstname") 
    431438 
    432439    def test_other_template(self): 
    433440        """'tg_html' in a returned dict will use the template specified there""" 
    434         testutil.create_request("/useother") 
    435         assert "This is the other template" in cherrypy.response.body[0] 
     441        response = testutil.go("/useother") 
     442        assert "This is the other template" in response 
    436443 
    437444    def test_cheetah_template(self): 
    438445        """Cheetah templates can be used as well""" 
    439         testutil.create_request("/usecheetah") 
    440         body = cherrypy.response.body[0] 
    441         assert "This is the Cheetah test template." in body 
    442         assert "Paging all chimps." in body 
     446        response = testutil.go("/usecheetah") 
     447        assert "This is the Cheetah test template." in response 
     448        assert "Paging all chimps." in response 
    443449 
    444450    def test_run_with_trans(self): 
    445451        """run_with_transaction is called only on topmost exposed method""" 
    446452        oldrwt = database.run_with_transaction 
    447453        database.run_with_transaction = cherrypy.root.rwt 
    448         testutil.create_request("/nestedcall?value=true") 
     454        response = testutil.go("/nestedcall?value=true") 
    449455        database.run_with_transaction = oldrwt 
    450         assert cherrypy.root.value 
    451         assert cherrypy.root.rwt_called == 1 
     456        assert response.raw['value'] 
     457        assert 'rwt_called = 1' in response 
    452458 
    453459    def test_positional(self): 
    454460        """Positional parameters should work""" 
    455         testutil.create_request("/pos/foo") 
    456         assert cherrypy.root.posvalue == "foo" 
     461        response = testutil.go("/pos/foo") 
     462        assert response.raw['posvalue'] == "foo" 
    457463 
    458464    def test_flash_plain(self): 
    459465        """flash with strings should work""" 
    460         testutil.create_request("/flash_plain?tg_format=json") 
    461         import simplejson 
    462         values = simplejson.loads(cherrypy.response.body[0]) 
     466        response = testutil.go("/flash_plain?tg_format=json") 
     467        values = simplejson.loads(response.body) 
    463468        assert values["tg_flash"] == "plain" 
    464         assert not cherrypy.response.simple_cookie.has_key("tg_flash") 
     469        assert not response.cookies_set.has_key("tg_flash") 
    465470 
    466471    def test_flash_unicode(self): 
    467472        """flash with unicode objects should work""" 
    468         testutil.create_request("/flash_unicode?tg_format=json") 
    469         import simplejson 
    470         values = simplejson.loads(cherrypy.response.body[0]) 
     473        response = testutil.go("/flash_unicode?tg_format=json") 
     474        values = simplejson.loads(response.body) 
    471475        assert values["tg_flash"] == u"\xfcnicode" 
    472         assert not cherrypy.response.simple_cookie.has_key("tg_flash") 
     476        assert not response.cookies_set.has_key("tg_flash")  
    473477 
    474478    def test_flash_on_redirect(self): 
    475479        """flash must survive a redirect""" 
    476         testutil.create_request("/flash_redirect?tg_format=json") 
    477         assert cherrypy.response.status.startswith("302") 
    478         testutil.create_request(cherrypy.response.headers["Location"], 
    479             headers=dict(Cookie=cherrypy.response.simple_cookie.output( 
    480                 header="").strip())) 
    481         import simplejson 
    482         values = simplejson.loads(cherrypy.response.body[0]) 
     480        response = go("/flash_redirect?tg_format=json", status=302) 
     481        response = go(response.location,  
     482            headers = dict(Cookie=response.headers["Set-Cookie"])) 
     483        values = simplejson.loads(response.body) 
    483484        assert values["tg_flash"] == u"redirect \xfcnicode" 
    484485 
    485486    def test_flash_redirect_with_trouble_chars(self): 
    486487        """flash redirect with chars that can cause troubles in cookies""" 
    487         testutil.create_request("/flash_redirect_with_trouble_chars?tg_format=json") 
    488         assert cherrypy.response.status.startswith("302") 
    489         value = cherrypy.response.simple_cookie["tg_flash"].value 
    490         assert '$' not in value 
    491         assert ',' not in value and ';' not in value 
    492         assert ' ' not in value and '\t' not in value 
    493         assert 'foo' in value and 'bar' in value 
    494         assert u'k\xe4se'.encode('utf-8') in value 
    495         assert '!' in value 
    496         testutil.create_request(cherrypy.response.headers["Location"], 
    497             headers=dict(Cookie=cherrypy.response.simple_cookie.output( 
    498                 header="").strip())) 
    499         import simplejson 
    500         values = simplejson.loads(cherrypy.response.body[0]) 
     488        response = go("/flash_redirect_with_trouble_chars?tg_format=json", status=302) 
     489        response = go(response.location, 
     490                      headers=dict(Cookie=response.headers["Set-Cookie"])) 
     491        values = simplejson.loads(response.body) 
    501492        assert values["tg_flash"] == u"$foo, k\xe4se;\tbar!" 
    502493 
    503494    def test_double_flash(self): 
     
    505496        # Here we are calling method that sets a flash message. However flash 
    506497        # cookie is still there. Turbogears should discard old flash message 
    507498        # from cookie and use new one, set by flash_plain(). 
    508         testutil.create_request("/flash_plain?tg_format=json", 
    509             headers=dict(Cookie='tg_flash="old flash"; Path=/;')) 
    510         import simplejson 
    511         values = simplejson.loads(cherrypy.response.body[0]) 
     499        response = go("/flash_plain?tg_format=json", 
     500            headers= {'Cookie':'tg_flash="old flash"; Path=/;'}) 
     501        values = simplejson.loads(response.body) 
    512502        assert values["tg_flash"] == "plain" 
    513         assert cherrypy.response.simple_cookie.has_key("tg_flash"), \ 
     503        assert response.cookies_set.has_key("tg_flash"), \ 
    514504                "Cookie clearing request should be present" 
    515         flashcookie = cherrypy.response.simple_cookie['tg_flash'] 
    516         assert flashcookie['expires'] == 0 
     505        eq_(response.cookies_set['tg_flash'], "") 
    517506 
    518507    def test_set_kid_outputformat_in_config(self): 
    519508        """the outputformat for kid can be set in the config""" 
    520509        config.update({'kid.outputformat': 'xhtml'}) 
    521         testutil.create_request('/test') 
    522         response = cherrypy.response.body[0] 
     510        response = testutil.go('/test') 
    523511        assert '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML ' in response 
    524512        config.update({'kid.outputformat': 'html'}) 
    525         testutil.create_request('/test') 
    526         response = cherrypy.response.body[0] 
     513        response = testutil.go('/test') 
    527514        assert  '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML ' in response 
    528515        assert '    This is the groovy test ' in response 
    529516        config.update({'kid.outputformat': 'html compact'}) 
    530         testutil.create_request('/test') 
    531         response = cherrypy.response.body[0] 
     517        response = testutil.go('/test') 
    532518        assert  '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML ' in response 
    533519        assert 'This is the groovy test ' in response 
    534520        assert '    ' not in response 
    535521 
    536522    def test_fileserving(self): 
    537         #outputcap = StringIO() 
    538         #sys.stdout = outputcap 
    539         testutil.create_request("/servefile") 
    540         assert cherrypy.root.servedit 
    541         assert not cherrypy.root.serve_exceptions 
    542         #assert "AssertionError" not in outputcap.getvalue() 
     523        response = testutil.go("/servefile") 
     524        assert "test_fileserving" in response 
    543525 
    544526    def test_internal_redirect(self): 
    545527        """regression test for #1022, #1407 and #1598""" 
    546         testutil.create_request("/internal_redirect") 
    547         firstline = cherrypy.response.body[0] 
    548         assert "redirected OK" in firstline 
     528        response = testutil.go("/internal_redirect") 
     529        assert "redirected OK" in response 
    549530 
    550531    def test_internal_redirect_nested_variables(self): 
    551532        """regression test for #1022, #1407 and #1598""" 
    552         testutil.create_request( 
     533        response = testutil.go( 
    553534            "/internal_redirect?a=1&a-1.b=2&a-2.c=3&a-2.c-1=4") 
    554         firstline = cherrypy.response.body[0] 
    555         assert "redirected OK" in firstline 
     535        assert "redirected OK" in response 
    556536 
    557537    def test_exc_value(self): 
    558538        """Exception is handled gracefully by the right exception handler.""" 
    559         testutil.create_request("/raise_value_exc") 
    560         assert 'handling_value' in cherrypy.response.body[0] 
     539        response = testutil.go("/raise_value_exc") 
     540        assert 'handling_value' in response 
    561541 
    562542    def test_exc_index(self): 
    563543        """Exception is handled gracefully by the right exception handler.""" 
    564         testutil.create_request("/raise_index_exc") 
    565         assert 'handling_index' in cherrypy.response.body[0] 
     544        response = testutil.go("/raise_index_exc") 
     545        assert 'handling_index' in response 
    566546 
    567547    def test_exc_all(self): 
    568548        """Test a controller that is protected by multiple exception handlers. 
     
    571551        by their respective handlers without problem... 
    572552 
    573553        """ 
    574         testutil.create_request("/raise_all_exc?num=1") 
    575         assert 'handling_value' in cherrypy.response.body[0] 
    576         testutil.create_request("/raise_all_exc?num=2") 
    577         assert 'handling_index' in cherrypy.response.body[0] 
    578         testutil.create_request("/raise_all_exc?num=3") 
    579         assert 'handling_key' in cherrypy.response.body[0] 
     554        response = testutil.go("/raise_all_exc?num=1") 
     555        assert 'handling_value' in response 
     556        response = testutil.go("/raise_all_exc?num=2") 
     557        assert 'handling_index' in response 
     558        response = testutil.go("/raise_all_exc?num=3") 
     559        assert 'handling_key' in response 
    580560 
    581561 
    582562class TestURLs(unittest.TestCase): 
    583563 
    584564    def setUp(self): 
    585         cherrypy.tree.mount_points = {} 
    586         cherrypy.root = MyRoot() 
    587         cherrypy.root.subthing = SubApp() 
    588         cherrypy.root.subthing.subsubthing = SubApp() 
     565        testutil.mount(MyRoot()) 
     566        testutil.mount(SubApp(), '/subthing') 
     567        testutil.mount(SubApp(), '/subthing/subsubthing') 
    589568 
    590569    def test_basic_urls(self): 
    591         testutil.create_request("/") 
     570        testutil.go("/") 
    592571        assert "/foo" == url("/foo") 
    593572        assert "foo/bar" == url(["foo", "bar"]) 
    594573        assert url("/foo", bar=1, baz=2) in \ 
     
    602581        assert url("/foo") == "/foo" 
    603582 
    604583    def test_approots(self): 
    605         testutil.create_request("/subthing/") 
    606         assert url("foo") == "foo" 
    607         assert url("/foo") == "/subthing/foo" 
     584        response = testutil.go("/subthing/foo") 
     585        self.failUnlessEqual("foo", response.body) 
     586           
     587        response = testutil.go("/subthing/foo2") 
     588        self.failUnlessEqual("/subthing/foo", response.body) 
    608589 
    609590    def test_lower_approots(self): 
    610         testutil.create_request("/subthing/subsubthing/") 
    611         assert url("/foo") == "/subthing/subsubthing/foo" 
     591        config.update({"server.webpath" : "/XXX"}) 
     592        response = testutil.go("/subthing/subsubthing/") 
     593        eq_("/XXX/subthing/subsubthing/Foo/", response.body) 
    612594 
    613     def test_approots_With_path(self): 
    614         config.update({"server.webpath": "/coolsite/root"}) 
    615         startup.startTurboGears() 
    616         testutil.create_request("/coolsite/root/subthing/") 
    617         assert url("/foo") == "/coolsite/root/subthing/foo" 
     595    def test_approots_with_path(self): 
     596        config.update({"server.webpath" : "/coolsite/root"}) 
     597        testutil.start_server() 
     598        response = testutil.go("/coolsite/root/subthing/") 
     599        self.failUnlessEqual("/coolsite/root/subthing/Foo/", response.body) 
    618600 
    619601    def test_redirect(self): 
    620         config.update({"server.webpath": "/coolsite/root"}) 
    621         startup.startTurboGears() 
    622         testutil.create_request("/coolsite/root/subthing/") 
    623         try: 
    624             redirect("/foo") 
    625             assert False, "redirect exception should have been raised" 
    626         except cherrypy.HTTPRedirect, e: 
    627             assert "http://localhost/coolsite/root/subthing/foo" in e.urls 
    628         try: 
    629             raise redirect("/foo") 
    630             assert False, "redirect exception should have been raised" 
    631         except cherrypy.HTTPRedirect, e: 
    632             assert "http://localhost/coolsite/root/subthing/foo" in e.urls 
     602        config.update({"server.webpath" : "/coolsite/root"}) 
     603        testutil.start_server() 
     604        response = go("/coolsite/root/subthing/redir") 
     605        eq_(response.location, 'http://localhost:80/coolsite/root/subthing/foo') 
    633606 
     607        response = go("/coolsite/root/subthing/redir2") 
     608        eq_(response.location, 'http://localhost:80/coolsite/root/subthing/foo') 
     609 
    634610    def test_multi_values(self): 
    635         testutil.create_request("/") 
     611        testutil.go("/") 
    636612        assert url("/foo", bar=[1, 2]) in \ 
    637613            ["/foo?bar=1&bar=2", "/foo?bar=2&bar=1"] 
    638614        assert url("/foo", bar=("asdf", "qwer")) in \ 
     
    640616 
    641617    def test_unicode(self): 
    642618        """url() can handle unicode parameters""" 
    643         testutil.create_request("/") 
     619        testutil.go("/") 
    644620        assert url('/', x=u'\N{LATIN SMALL LETTER A WITH GRAVE}' 
    645621            u'\N{LATIN SMALL LETTER E WITH GRAVE}' 
    646622            u'\N{LATIN SMALL LETTER I WITH GRAVE}' 
     
    650626 
    651627    def test_list(self): 
    652628        """url() can handle list parameters, with unicode too""" 
    653         testutil.create_request("/") 
     629        testutil.go("/") 
    654630        assert url('/', foo=['bar', u'\N{LATIN SMALL LETTER A WITH GRAVE}'] 
    655631            ) == '/?foo=bar&foo=%C3%A0' 
    656632 
    657633    def tearDown(self): 
    658634        config.update({"server.webpath": ""}) 
    659         startup.startTurboGears() 
     635        testutil.start_server() 
    660636 
    661637 
    662638def test_index_trailing_slash(): 
    663639    """If there is no trailing slash on an index method call, redirect""" 
    664     cherrypy.root = SubApp() 
    665     cherrypy.root.foo = SubApp() 
    666     testutil.create_request("/foo") 
    667     assert cherrypy.response.status.startswith("302") 
     640    testutil.mount(SubApp()) 
     641    testutil.mount(SubApp(), '/noslash') 
     642    response = testutil.go("/noslash") 
     643    assert response.status.startswith("302") 
    668644 
     645 
    669646def test_can_use_internally_defined_arguments(): 
    670647    """Can use argument names that are internally used by TG in controllers""" 
    671648 
     
    675652        def index(self, **kw): 
    676653            return "\n".join(["%s:%s" % i for i in kw.iteritems()]) 
    677654 
    678     cherrypy.root = App() 
    679     testutil.create_request("/?format=foo&template=bar&fragment=boo") 
    680     output = cherrypy.response.body[0] 
    681     assert "format:foo" in output 
    682     assert "template:bar" in output 
    683     assert "fragment:boo" in output 
     655    testutil.mount(App()) 
     656    response = testutil.go("/?format=foo&template=bar&fragment=boo") 
     657    assert "format:foo" in response 
     658    assert "template:bar" in response 
     659    assert "fragment:boo" in response 
    684660 
    685661def test_url_kwargs_overwrite_tgparams(): 
    686662    """Check keys in tgparams in call to url overwrite kw args""" 
  • turbogears/tests/test_view.py

     
    11# -*- coding: utf-8 -*- 
    2  
    32from turbogears import view, config, testutil 
    43import cherrypy 
    54import unittest 
     
    76class TestView(unittest.TestCase): 
    87 
    98    def setUp(self): 
    10         testutil.start_cp() 
     9        testutil.start_server() 
    1110        cherrypy.serving.request = testutil.DummyRequest() 
    1211        cherrypy.serving.response = testutil.DummyResponse() 
    1312 
  • turbogears/tests/test_testutil.py

     
    2121 
    2222 
    2323def test_browser_session(): 
    24     cherrypy.root = MyRoot() 
     24    testutil.stop_server() 
     25    testutil.start_server(MyRoot()) 
    2526    bs = testutil.BrowsingSession() 
    2627    bs.goto('/get_name') 
    2728    assert bs.response == 'cookie not found' 
     
    3031    assert bs.response == 'me' 
    3132 
    3233def test_browser_session_for_two_users(): 
    33     cherrypy.root = MyRoot() 
     34    testutil.stop_server() 
     35    testutil.start_server(MyRoot()) 
    3436    bs1 = testutil.BrowsingSession() 
    3537    bs2 = testutil.BrowsingSession() 
    3638    bs1.goto('/set_name?name=bs1') 
  • turbogears/tests/test_catwalk.py

     
    33from turbogears import testutil 
    44from turbogears import controllers 
    55from turbogears.toolbox.catwalk import CatWalk 
    6 import cherrypy 
    76import simplejson 
    87from catwalk_models import browse 
    98import timeit 
     
    4342class Browse(unittest.TestCase): 
    4443    def setUp(self): 
    4544        browse_data(browse) 
    46         cherrypy.root = MyRoot() 
     45        testutil.start_server() 
     46        testutil.mount(MyRoot(), "/") 
     47        testutil.mount(CatWalk(browse), '/catwalk') 
    4748 
     49    def tearDown(self): 
     50        testutil.stop_server() 
     51 
    4852    def test_wrong_filter_format(self): 
    49         cherrypy.root.catwalk = CatWalk(browse) 
    50         testutil.create_request("/catwalk/browse/?object_name=Song&filters=Guantanemera&tg_format=json") 
    51         response = cherrypy.response.body[0] 
     53        response = testutil.go("/catwalk/browse/?object_name=Song&filters=Guantanemera&tg_format=json") 
    5254        assert 'filter_format_error' in response 
    5355 
    5456    def test_wrong_filter_column(self): 
    55         cherrypy.root.catwalk = CatWalk(browse) 
    56         testutil.create_request("/catwalk/browse/?object_name=Song&filters=guacamole:2&tg_format=json") 
    57         response = cherrypy.response.body[0] 
     57        response = testutil.go("/catwalk/browse/?object_name=Song&filters=guacamole:2&tg_format=json") 
    5858        assert 'filter_column_error' in response 
    5959 
    6060    def test_filters(self): 
    61         cherrypy.root.catwalk = CatWalk(browse) 
    62         testutil.create_request("/catwalk/browse/?object_name=Song&tg_format=json") 
    63         response = cherrypy.response.body[0] 
    64         values = simplejson.loads(response) 
     61        response = testutil.go("/catwalk/browse/?object_name=Song&tg_format=json") 
     62        values = simplejson.loads(response.body) 
    6563        assert values['total'] == 15 * 15 * 15 #without the filters we get all songs (3375) 
    66         testutil.create_request("/catwalk/browse/?object_name=Song&filters=album:1&tg_format=json") 
    67         response = cherrypy.response.body[0] 
    68         values = simplejson.loads(response) 
     64        response = testutil.go("/catwalk/browse/?object_name=Song&filters=album:1&tg_format=json") 
     65        #values = simplejson.loads(response.body) 
     66        response.headers['Content-Type'] = 'application/json' 
     67        values = response.json 
    6968        assert values['total'] == 15 #filter by album id (only 15 songs) 
    7069 
    7170    def test_response_fields(self): 
    7271        #Check that the response contains the expected keys 
    73         cherrypy.root.catwalk = CatWalk(browse) 
    74         testutil.create_request("/catwalk/browse/?object_name=Artist&start=3&page_size=20&tg_format=json") 
    75         response = cherrypy.response.body[0] 
    76         values = simplejson.loads(response) 
     72        response = testutil.go("/catwalk/browse/?object_name=Artist&start=3&page_size=20&tg_format=json") 
     73        values = simplejson.loads(response.body) 
    7774        assert values.has_key('headers') 
    7875        assert values.has_key('rows') 
    7976        assert values.has_key('start') 
     
    8683    def test_rows_joins_count(self): 
    8784        #Control that the count for related and multiple joins match 
    8885        #the number of related instances when accessed as a field 
    89         cherrypy.root.catwalk = CatWalk(browse) 
    90         testutil.create_request("/catwalk/browse/?object_name=Artist&tg_format=json") 
    91         response = cherrypy.response.body[0] 
    92         values = simplejson.loads(response) 
     86        response = testutil.go("/catwalk/browse/?object_name=Artist&tg_format=json") 
     87        values = simplejson.loads(response.body) 
    9388        artist = browse.Artist.get(1) 
    9489        assert int(values['rows'][0]['genres']) == len(list(artist.genres)) 
    9590        assert int(values['rows'][0]['albums']) == len(list(artist.albums)) 
    9691 
    9792    def test_rows_column_number(self): 
    9893        #Control that the number of columns match the number of fields in the model 
    99         cherrypy.root.catwalk = CatWalk(browse) 
    100         testutil.create_request("/catwalk/browse/?object_name=Artist&tg_format=json") 
    101         response = cherrypy.response.body[0] 
    102         values = simplejson.loads(response) 
     94        response = testutil.go("/catwalk/browse/?object_name=Artist&tg_format=json") 
     95        values = simplejson.loads(response.body) 
    10396        assert len(values['rows'][0]) == 4 
    10497 
    10598    def test_rows_limit(self): 
    10699        #Update the limit of rows for the query and control the number of rows returned 
    107         cherrypy.root.catwalk = CatWalk(browse) 
    108         testutil.create_request("/catwalk/browse/?object_name=Artist&tg_format=json") 
    109         response = cherrypy.response.body[0] 
    110         values = simplejson.loads(response) 
     100        response = testutil.go("/catwalk/browse/?object_name=Artist&tg_format=json") 
     101        values = simplejson.loads(response.body) 
    111102        assert values.has_key('rows') 
    112103        assert len(values['rows']) == 10 
    113         testutil.create_request("/catwalk/browse/?object_name=Artist&page_size=15&tg_format=json") 
    114         response = cherrypy.response.body[0] 
    115         values = simplejson.loads(response) 
     104 
     105        response = testutil.go("/catwalk/browse/?object_name=Artist&page_size=15&tg_format=json") 
     106        values = simplejson.loads(response.body) 
    116107        assert values.has_key('rows') 
    117108        assert len(values['rows']) == 15 
    118109 
    119110    def test_header_labels(self): 
    120111        #Check that the returned header labels match the the model 
    121         cherrypy.root.catwalk = CatWalk(browse) 
    122         testutil.create_request("/catwalk/browse/?object_name=Artist&tg_format=json") 
    123         response = cherrypy.response.body[0] 
    124         values = simplejson.loads(response) 
     112        response = testutil.go("/catwalk/browse/?object_name=Artist&tg_format=json") 
     113        values = simplejson.loads(response.body) 
    125114        assert len(values['headers']) == 5 
    126115        for header in values['headers']: 
    127116            assert header['name'] in ['id','name','albums','genres', 'plays_instruments'] 
     
    131120    model = browse 
    132121 
    133122    def setUp(self): 
    134         cherrypy.root = MyRoot() 
    135         cherrypy.root.catwalk = CatWalk(browse) 
     123        testutil.start_server() 
     124        testutil.mount(MyRoot(), "/") 
     125        testutil.mount(CatWalk(browse), '/catwalk') 
    136126        testutil.DBTest.setUp(self) 
    137127        browse_data(browse) 
    138128 
     129    def tearDown(self): 
     130        testutil.stop_server() 
     131        testutil.DBTest.tearDown(self) 
     132 
    139133    def test_addremove_related_joins(self): 
    140134        # check the update_join function when nondefault add/remove are used 
    141135        artist = self.model.Artist.get(1) 
    142136        assert len(artist.plays_instruments) == 0 
    143         testutil.create_request("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1%2C2&tg_format=json") 
     137        testutil.go("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1%2C2&tg_format=json") 
    144138        assert len(artist.plays_instruments) == 2 
    145         testutil.create_request("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1&tg_format=json") 
     139        testutil.go("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1&tg_format=json") 
    146140        assert len(artist.plays_instruments) == 1, str(artist.plays_instruments) 
  • turbogears/tests/test_paginate.py

     
    88from turbogears.controllers import RootController, url 
    99from turbogears.database import get_engine, metadata, session, mapper 
    1010from turbogears.paginate import paginate, sort_ordering, sort_data 
    11 from turbogears.testutil import create_request, sqlalchemy_cleanup 
     11from turbogears.testutil import go, sqlalchemy_cleanup, start_server 
    1212from turbojson.jsonify import jsonify 
    1313 
    1414import cherrypy 
     
    218218 
    219219 
    220220    def setUp(self): 
    221         cherrypy.root = self.MyRoot() 
     221        start_server(self.MyRoot()) 
    222222 
    223223    def test_spy(self): 
    224         create_request('/spy') 
    225         body = cherrypy.response.body[0] 
    226         Spy.assert_ok(body, 'current_page', 1) 
     224        response = go('/spy') 
     225        Spy.assert_ok(response, 'current_page', 1) 
    227226        try: 
    228             Spy.assert_ok(body, 'current_page', 2) 
     227            Spy.assert_ok(response, 'current_page', 2) 
    229228            raise Exception("above test should have failed") 
    230229        except AssertionError: 
    231230            pass 
    232231 
    233232    def test_correct_expectation(self): 
    234         create_request('/spy_correct_expectation') 
    235         body = cherrypy.response.body[0] 
    236         assert "ok: [paginate" in body 
     233        response = go('/spy_correct_expectation') 
     234        assert "ok: [paginate" in response 
    237235 
    238236    def test_wrong_expectation(self): 
    239         create_request('/spy_wrong_expectation') 
    240         body = cherrypy.response.body[0] 
    241         assert "fail: expected page_count=9, got page_count=10" in body 
     237        response = go('/spy_wrong_expectation') 
     238        assert "fail: expected page_count=9, got page_count=10" in response 
    242239 
    243240    def test_invalid_expectation(self): 
    244         create_request('/spy_invalid_expectation') 
    245         body = cherrypy.response.body[0] 
    246         assert "fail: paginate does not have 'foobar' attribute" in body 
     241        response = go('/spy_invalid_expectation') 
     242        assert "fail: paginate does not have 'foobar' attribute" in response 
    247243 
    248244    def test_raw_expectation(self): 
    249         create_request('/spy_correct_expectation') 
    250         Spy.assert_ok(cherrypy.response.body[0], 'var_name', 'data') 
    251         Spy.assert_ok(cherrypy.response.body[0], 'var_name', "'data'", raw=True) 
     245        response = go('/spy_correct_expectation') 
     246        Spy.assert_ok(response, 'var_name', 'data') 
     247        Spy.assert_ok(response, 'var_name', "'data'", raw=True) 
    252248 
    253249 
    254250class TestPagination(unittest.TestCase): 
    255251    """Base class for all Paginate TestCases""" 
    256252 
    257     def request(self, url): 
    258         create_request(url) 
    259         self.body = cherrypy.response.body[0] 
     253    def request(self, url, status=None): 
     254        self.body = go(url, status=status).body 
    260255        if "fail: " in self.body: 
    261256            print self.body 
    262             assert False, "Spy alert! Check body output for details..." 
     257            assert False, "Spy alert! Check response output for details..." 
    263258 
    264259 
    265260class TestBasicPagination(TestPagination): 
     
    343338 
    344339 
    345340    def setUp(self): 
    346         cherrypy.root = self.MyRoot() 
     341        start_server(root = self.MyRoot()) 
    347342 
    348343    def test_pagination_old_style(self): 
    349344        self.request("/basic") 
     
    439434        Spy.assert_ok(self.body, 'pages', xrange(4, 8)) 
    440435 
    441436    def test_invalid_dynamic_limit(self): 
    442         self.request("/invalid_dynamic") 
    443         assert cherrypy.response.status.startswith("500") 
     437        self.request("/invalid_dynamic", status=500) 
    444438        assert 'paginate: dynamic_limit (foobar) not found in output dict' in self.body 
    445439 
    446440    def test_dynamic_limit(self): 
     
    754748 
    755749 
    756750    def setUp(self): 
    757         cherrypy.root = self.MyRoot() 
     751        start_server(root = self.MyRoot()) 
    758752 
    759753    def assert_order(self, *args): 
    760754        expr = 'data="%s"' % ''.join(['[Address %r]' % x for x in args]) 
     
    826820 
    827821    def test_invalid_default_reversed(self): 
    828822        for method in "Q", "QA", "SR", "SO", "SL": 
    829             self.request("/wrong_reversed/?method=%s" % method) 
    830             assert cherrypy.response.status.startswith("500") 
     823            self.request("/wrong_reversed/?method=%s" % method, status=500) 
    831824            assert ('paginate: default_reversed (deprecated) only allowed' 
    832825                ' when default_order is a basestring') in self.body 
    833826 
  • turbogears/qstemplates/quickstart/+package+/tests/test_controllers.py_tmpl

     
    44from ${package}.controllers import Root 
    55import cherrypy 
    66 
    7 cherrypy.root = Root() 
     7testutil.mount(root = Root()) 
    88 
    99class TestPages(unittest.TestCase): 
    1010 
    1111    def setUp(self): 
    12         turbogears.startup.startTurboGears() 
     12        testutil.start_server() 
    1313 
    1414    def tearDown(self): 
    1515        """Tests for apps using identity need to stop CP/TG after each test to 
    1616        stop the VisitManager thread. 
    1717        See http://trac.turbogears.org/turbogears/ticket/1217 for details. 
    1818        """ 
    19         turbogears.startup.stopTurboGears() 
     19        testutil.stop_server() 
    2020 
    2121    def test_method(self): 
    2222        "the index method should return a string called now" 
    2323        import types 
    24         result = testutil.call(cherrypy.root.index) 
    25         assert type(result["now"]) == types.StringType 
     24        response = testutil.go("/") 
     25        assert type(response.raw["now"]) == types.StringType 
    2626 
    2727    def test_indextitle(self): 
    2828        "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() 
    3231 
    3332#if $identity != "none" 
    3433    def test_logintitle(self): 
    3534        "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() 
    3937#end if 
  • turbogears/testutil.py

     
    44import unittest 
    55import Cookie 
    66import cStringIO as StringIO 
     7from turbogears.util import deprecated 
     8from webtest import TestApp 
    79 
    810import cherrypy 
    9 from cherrypy import _cphttptools 
     11cherrypy_major_ver = int(cherrypy.__version__.split('.')[0]) 
     12if cherrypy_major_ver < 3: 
     13    from cherrypy._cphttptools import Request, Response 
     14else: 
     15    from cherrypy import Request, Response 
    1016 
    1117try: 
    1218    import sqlobject 
     
    5056config.update({'global': 
    5157        {'autoreload.on': False, 'tg.new_style_logging': True}}) 
    5258 
     59def unmount(): 
     60    """Remove an application from the object traversal tree.""" 
     61    # There's no clean way to remove a subtree under CP2, so the only use case 
     62    #  handled here is to remove the entire application. 
     63    # Supposedly, you can do a partial unmount with CP3 using: 
     64    #  del cherrypy.tree.apps[path] 
     65    cherrypy.root = None 
     66    cherrypy.tree.mount_points = {} 
    5367 
    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}) 
     68def mount(app, path="/"): 
     69    """Mount an app at a path.  Returns True if the server needs 
     70    to be restarted afterwards. 
     71    """ 
     72    current = cherrypy.tree.mount_points.get(path, None) 
     73    if current != app: 
     74        #Only mount the app if it's not already mounted 
     75        if current != None: 
     76            #If there's something else mounted at this path already, we'll 
     77            # have to unmount it first.  CherryPy can't handle dynamic  
     78            # remounting. 
     79            unmount() 
     80        cherrypy.tree.mount(app, path) 
     81    if path == '/': 
     82        cherrypy.root = app 
     83    return get_app() 
    5884 
     85def start_server(root=None): 
     86    """Start the server if it's not already.  Optionally mount an app first.""" 
     87    if root: 
     88        mount(root) 
     89    if not config.get("server_started"): 
     90        if cherrypy_major_ver < 3: 
     91            cherrypy.server.start(serverClass=None, initOnly=True) 
     92        else: 
     93            cherrypy.server.quickstart() 
     94            cherrypy.engine.start() 
     95    startup.startTurboGears() 
     96    config.update({"server_started" : True}) 
    5997 
     98start_cp = deprecated("start_cp has been superceded by start_server.") \ 
     99               (start_server) 
     100 
     101 
     102def stop_server(): 
     103    if config.get("server_started", True): 
     104        startup.stopTurboGears() 
     105        config.update({"server_started" : False}) 
     106        unmount() 
     107    return 
     108 
    60109test_user = None 
    61110 
     111@deprecated() 
    62112def set_identity_user(user): 
    63113    """Setup a user for configuring request's identity.""" 
    64114    global test_user 
    65115    test_user = user 
    66116 
    67117 
     118@deprecated() 
    68119def attach_identity(req): 
    69120    if config.get("identity.on", False): 
    70121        req.identity = (test_user 
     
    72123            or current_provider.anonymous_identity()) 
    73124 
    74125 
     126@deprecated("Use testutil.go instead of create_request") 
    75127def create_request(request, method="GET", protocol="HTTP/1.1", 
    76128        headers={}, rfile=None, clientAddress="127.0.0.1", 
    77129        remoteHost="localhost", scheme="http"): 
    78     start_cp() 
     130    start_server() 
    79131    if not rfile: 
    80132        rfile = StringIO.StringIO("") 
    81133    if type(headers) != dict: 
     
    86138    if not hasattr(cherrypy.root, "started"): 
    87139        startup.startTurboGears() 
    88140        cherrypy.root.started = True 
    89     req = _cphttptools.Request(clientAddress, 80, remoteHost, scheme) 
     141    req = Request(clientAddress, 80, remoteHost, scheme) 
    90142    cherrypy.serving.request = req 
    91143    attach_identity(req) 
    92     cherrypy.serving.response = _cphttptools.Response() 
     144    cherrypy.serving.response = Response() 
    93145    req.run(" ".join((method, request, protocol)), headerList, rfile) 
     146    return cherrypy.serving.response 
    94147 
     148createRequest = create_request 
    95149 
     150 
     151def get_app(): 
     152    """Return a WSGI application from cherrypy's root object.""" 
     153    if cherrypy_major_ver < 3: 
     154        app = cherrypy._cpwsgi.wsgiApp 
     155    else: 
     156        app = cherrypy.tree.mount(cherrypy.root, '/') 
     157        # app = cherrypy.wsgi.CPWSGIServer 
     158    return app 
     159 
     160 
     161def go(request, headers={}, cookies={}, status=None): 
     162    """Visit a site with WebTest, returning the response.""" 
     163    start_server() 
     164    app = TestApp(get_app()) 
     165    response = app.get(request, headers=headers, status=status) 
     166    response.app = app 
     167    return response 
     168 
     169 
    96170class BrowsingSession(object): 
    97171 
    98172    def __init__(self): 
     
    103177    def goto(self, *args, **kwargs): 
    104178        if self.cookie: 
    105179            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.status 
    110         if cherrypy.response.simple_cookie: 
    111             self.cookie.update(cherrypy.response.simple_cookie) 
     180            headers['Cookie'] = self.cookie_encoded 
     181        response = go(*args, **kwargs) 
     182        self.response = response.body 
     183        self.status = response.status 
     184        self.cookie = response.cookies_set 
     185        self.cookie_encoded = response.headers.get('Set-Cookie', '') 
    112186 
    113187 
    114188def _return_directly(output, *args): 
     
    140214class DummyResponse: 
    141215    """A very simple dummy response.""" 
    142216    headers = {} 
     217     
    143218 
    144  
     219@deprecated("Use testutil.go instead of call") 
    145220def call(method, *args, **kw): 
    146     start_cp() 
     221    start_server() 
    147222    output, response = call_with_request(method, DummyRequest(), *args, **kw) 
    148223    return output 
    149224 
    150225 
     226@deprecated("Use testutil.go instead of call_with_request") 
    151227def call_with_request(method, request, *args, **kw): 
    152228    """More fine-grained version of call method. 
    153229 
     
    156232    """ 
    157233    orig_proc_output = controllers._process_output 
    158234    controllers._process_output = _return_directly 
    159     cherrypy.serving.response = _cphttptools.Response() 
     235    cherrypy.serving.response = Response() 
    160236    cherrypy.serving.request = request 
    161237    if not hasattr(request, "identity"): 
    162238        attach_identity(request) 
     
    201277                item.dropTable(ifExists=True) 
    202278 
    203279 
    204 def reset_cp(): 
    205     cherrypy.root = None 
    206  
    207  
    208280def catch_validation_errors(widget, value): 
    209281    """Catch and unpack validation errors (for testing purposes).""" 
    210282    try: 
     
    253325 
    254326    """ 
    255327    global _currentcat 
    256     assert not _currentcat 
     328    assert not _currentcat, "_currentcat not cleared.  Use print_log to reset." 
    257329    if not isinstance(category, list) and not isinstance(category, tuple): 
    258330        category = [category] 
    259331    _currentcat = category 
     
    305377    sqlalchemy.orm.clear_mappers() 
    306378 
    307379 
    308 __all__ = ["call", "create_request", "DBTest", 
    309     "attach_identity", "set_identity_user", 
    310     "capture_log", "print_log", "get_log", "sqlalchemy_cleanup"] 
     380__all__ = ["call", "create_request", "DBTest", "attach_identity",  
     381    "set_identity_user", "capture_log", "print_log", "get_log", 
     382    "sqlalchemy_cleanup", "mount", "go", "start_server", "stop_server"] 
     383 
  • turbogears/widgets/tests/test_nested_form_controllers.py

     
    11import turbogears 
    2 import cherrypy 
    32from turbogears import widgets 
    43from turbogears import controllers 
    54from turbogears import validators 
     
    1716 
    1817class MyRoot(controllers.RootController): 
    1918    def testform(self, p_data, tg_errors=None): 
    20         if tg_errors: 
    21             self.has_errors = True 
    22         self.name = p_data['name'] 
    23         self.age = p_data['age'] 
     19        has_errors = tg_errors is not None 
     20        name = p_data['name'] 
     21        age = p_data['age'] 
     22        return dict(has_errors = has_errors, name=name, age = age) 
    2423    testform = turbogears.validate(form=myform)(testform) 
    25     testform = turbogears.expose(html="turbogears.tests.othertemplate")( 
     24    testform = turbogears.expose(template="turbogears.tests.othertemplate")( 
    2625                                 testform) 
    2726 
    2827    def set_errors(self): 
    29         self.has_errors = True 
     28        return dict(has_errors = True) 
     29         
    3030 
    3131    def testform_new_style(self, p_data): 
    32         self.name = p_data['name'] 
    33         self.age = p_data['age'] 
     32        name = p_data['name'] 
     33        age = p_data['age'] 
     34        return dict(name = name, age = age) 
    3435    testform_new_style = turbogears.validate(form=myform)(testform_new_style) 
    3536    testform_new_style = turbogears.error_handler(set_errors)(testform_new_style) 
    3637    testform_new_style = turbogears.expose()(testform_new_style) 
     
    3839 
    3940def test_form_translation_new_style(): 
    4041    "Form input is translated into properly converted parameters" 
    41     root = MyRoot() 
    42     cherrypy.root = root 
    43     testutil.create_request("/testform_new_style?p_data.name=ed&p_data.age=5") 
    44     assert root.name == "ed" 
    45     print root.age 
    46     assert root.age == 5 
     42    testutil.mount(MyRoot()) 
     43    response = testutil.go("/testform_new_style?p_data.name=ed&p_data.age=5") 
     44    assert response.raw['name'] == "ed" 
     45    print response.raw['age'] 
     46    assert response.raw['age'] == 5 
    4747 
    4848def test_invalid_form_with_error_handling(): 
    4949    "Invalid forms can be handled by the method" 
    50     root = cherrypy.root 
    51     testutil.create_request("/testform_new_style?p_data.name=ed&p_data.age=edalso") 
    52     assert root.has_errors 
     50    testutil.mount(MyRoot()) 
     51    response = testutil.go("/testform_new_style?p_data.name=ed&p_data.age=edalso") 
     52    assert response.raw['has_errors'] 
  • turbogears/widgets/tests/test_datagrid.py

     
    22from turbogears.widgets.datagrid import DataGrid 
    33 
    44def setup_module(): 
    5     testutil.start_cp()    
     5    testutil.start_server()    
    66 
    77class Foo: 
    88 
  • turbogears/widgets/tests/test_link_inclusion.py

     
    11import turbogears 
    2 import cherrypy 
    3  
    42from turbogears import widgets, testutil 
    53 
    64 
     
    2119            return dict(form=form) 
    2220        test = turbogears.expose(template="turbogears.widgets.tests.form")(test) 
    2321 
    24     cherrypy.root = MyRoot() 
    25     testutil.create_request("/test") 
    26     output = cherrypy.response.body[0] 
    27     assert 'foo.js' in output 
    28     assert "alert('hello');" in output 
    29     assert 'foo.css' in output 
     22    testutil.start_server(root = MyRoot()) 
     23    response = testutil.go("/test") 
     24    assert 'foo.js' in response.body 
     25    assert "alert('hello');" in response.body 
     26    assert 'foo.css' in response.body 
    3027 
    3128 
    3229def test_calendardatepicker_js(): 
     
    3734            return dict(widget=widgets.CalendarDatePicker(calendar_lang=lang)) 
    3835        test = turbogears.expose(template="turbogears.widgets.tests.widget")(test) 
    3936 
    40     cherrypy.root = MyRoot() 
     37    testutil.start_server(root = MyRoot()) 
    4138 
    4239    # testing default language (en) 
    43     testutil.create_request("/test") 
    44     output = cherrypy.response.body[0] 
    45     assert 'calendar/calendar.js' in output 
    46     assert 'calendar/calendar-setup.js' in output 
    47     assert 'calendar/lang/calendar-en.js' in output 
     40    response = testutil.go("/test") 
     41    assert 'calendar/calendar.js' in response.body 
     42    assert 'calendar/calendar-setup.js' in response.body 
     43    assert 'calendar/lang/calendar-en.js' in response.body 
    4844 
    4945    # testing non-existing language 
    50     testutil.create_request("/test", 
     46    response = testutil.go("/test", 
    5147        headers={"Accept-Language": "x"}) 
    52     output = cherrypy.response.body[0] 
    53     assert 'calendar/lang/calendar-x.js' not in output 
    54     assert 'calendar/lang/calendar-en.js' in output 
     48    assert 'calendar/lang/calendar-x.js' not in response.body 
     49    assert 'calendar/lang/calendar-en.js' in response.body 
    5550 
    5651    # testing French language 
    57     testutil.create_request("/test", 
     52    response = testutil.go("/test", 
    5853        headers={"Accept-Language": "fr"}) 
    59     output = cherrypy.response.body[0] 
    60     assert 'calendar/lang/calendar-fr.js' in output 
    61     assert 'calendar/lang/calendar-en.js' not in output 
    62     assert 'charset="utf-8"' in output 
     54    assert 'calendar/lang/calendar-fr.js' in response.body 
     55    assert 'calendar/lang/calendar-en.js' not in response.body 
     56    assert 'charset="utf-8"' in response.body 
    6357 
    6458    # testing German language with any charset 
    65     testutil.create_request("/test", 
     59    response = testutil.go("/test", 
    6660        headers={"Accept-Language": "de", "Accept-Charset": "*"}) 
    67     output = cherrypy.response.body[0] 
    68     assert 'calendar/lang/calendar-de.js' in output 
    69     assert 'calendar/lang/calendar-en.js' not in output 
    70     assert 'charset="*"' not in output 
     61    assert 'calendar/lang/calendar-de.js' in response.body 
     62    assert 'calendar/lang/calendar-en.js' not in response.body 
     63    assert 'charset="*"' not in response.body 
    7164 
    7265    # testing Turkish language with non-existing charset 
    73     testutil.create_request("/test", 
     66    response = testutil.go("/test", 
    7467        headers={"Accept-Language": "tr", "Accept-Charset": "big5"}) 
    75     output = cherrypy.response.body[0] 
    76     assert 'calendar/lang/calendar-tr.js' in output 
    77     assert 'calendar/lang/calendar-en.js' not in output 
    78     assert 'charset="big5"' not in output 
     68    assert 'calendar/lang/calendar-tr.js' in response.body 
     69    assert 'calendar/lang/calendar-en.js' not in response.body 
     70    assert 'charset="big5"' not in response.body 
    7971 
    8072    win1254 = 'windows-1254' 
    8173    from codecs import lookup 
     
    8577        win1254 = 'cp1254' # cannot test name normalization here 
    8678 
    8779    # testing Turkish language with existing, not normalized charset 
    88     testutil.create_request("/test", 
     80    response = testutil.go("/test", 
    8981        headers={"Accept-Language": "tr", "Accept-Charset": win1254}) 
    90     output = cherrypy.response.body[0] 
    91     assert 'calendar/lang/calendar-tr-cp1254.js' in output 
    92     assert 'calendar/lang/calendar-en.js' not in output 
    93     assert 'charset="cp1254"' in output 
     82    assert 'calendar/lang/calendar-tr-cp1254.js' in response.body 
     83    assert 'calendar/lang/calendar-en.js' not in response.body 
     84    assert 'charset="cp1254"' in response.body 
    9485 
    9586    # testing more than one language and charset 
    96     testutil.create_request("/test", headers={"Accept-Language": "x,tr,de,fr", 
     87    response = testutil.go("/test", headers={"Accept-Language": "x,tr,de,fr", 
    9788        "Accept-Charset": "big5,%s,latin-1" % win1254}) 
    98     output = cherrypy.response.body[0] 
    99     assert 'calendar/lang/calendar-tr-cp1254.js' in output 
    100     assert 'calendar/lang/calendar-x.js' not in output 
    101     assert 'calendar/lang/calendar-en.js' not in output 
    102     assert 'charset="cp1254"' in output 
    103     assert 'charset="big5"' not in output 
     89    assert 'calendar/lang/calendar-tr-cp1254.js' in response.body 
     90    assert 'calendar/lang/calendar-x.js' not in response.body 
     91    assert 'calendar/lang/calendar-en.js' not in response.body 
     92    assert 'charset="cp1254"' in response.body 
     93    assert 'charset="big5"' not in response.body 
    10494 
    10595    # testing predetermined language (fr) 
    106     testutil.create_request("/test?lang=fr", 
     96    response = testutil.go("/test?lang=fr", 
    10797        headers={"Accept-Language": "de,en,tr"}) 
    108     output = cherrypy.response.body[0] 
    109     assert 'calendar/lang/calendar-fr.js' in output 
    110     assert 'calendar/lang/calendar-en.js' not in output 
     98    assert 'calendar/lang/calendar-fr.js' in response.body 
     99    assert 'calendar/lang/calendar-en.js' not in response.body 
    111100 
    112101    # testing predetermined non-existing language 
    113     testutil.create_request("/test?lang=x", 
     102    response = testutil.go("/test?lang=x", 
    114103        headers={"Accept-Language": "de,en,fr,tr"}) 
    115     output = cherrypy.response.body[0] 
    116     assert 'calendar/lang/calendar-de.js' in output 
    117     assert 'calendar/lang/calendar-x.js' not in output 
    118     assert 'calendar/lang/calendar-en.js' not in output 
     104    assert 'calendar/lang/calendar-de.js' in response.body 
     105    assert 'calendar/lang/calendar-x.js' not in response.body 
     106    assert 'calendar/lang/calendar-en.js' not in response.body 
  • turbogears/widgets/tests/test_new_validation.py

     
    1 import cherrypy 
    21import turbogears.widgets as widgets 
    32import turbogears.validators as validators 
    43 
    54from turbogears.testutil import catch_validation_errors 
    65 
    7 class Request: 
    8     validation_errors = {} 
    9  
    10 oldrequest = None 
    11  
    12 def setup_module(): 
    13     global oldrequest 
    14     oldrequest = cherrypy.request 
    15     cherrypy.request = Request() 
    16  
    17  
    18 def teardown_module(): 
    19     global oldrequest 
    20     cherrypy.request = oldrequest 
    21  
    22  
    23  
    24  
    256class SimpleSchema(validators.Schema): 
    267    phone = validators.Int() 
    278 
  • turbogears/widgets/tests/test_forms.py

     
    44from turbogears import widgets, validators, controllers, expose, validate, \ 
    55                       testutil 
    66from turbogears import config 
    7 from turbogears.testutil import catch_validation_errors, create_request 
     7from turbogears.testutil import catch_validation_errors, go 
    88import cherrypy 
    99 
    1010 
    1111def setup_module(): 
    12     testutil.start_cp() 
     12    testutil.start_server() 
    1313    cherrypy.serving.request = testutil.DummyRequest() 
    1414 
    1515def test_rendering(): 
     
    167167    @expose() 
    168168    @validate(form=nestedform) 
    169169    def checkform(self, foo): 
    170         self.foo = foo 
     170        return foo 
    171171 
     172    @expose() 
     173    def field_for(self): 
     174        cherrypy.request.validation_errors = dict(foo=dict(foo='error')) 
     175        template = """\ 
     176        <div xmlns:py="http://purl.org/kid/ns#"> 
     177            ${field_for('foo').fq_name}.appears 
     178            ${field_for('foo').error}_appears 
     179            ${field_for('foo').field_id}_appears 
     180            ${field_for('foo').display(value_for('foo'), **params_for('foo'))} 
     181        </div> 
     182        """ 
     183        textfield = widgets.TextField("foo") 
     184        fieldset = widgets.FieldSet("foo", fields=[textfield], template=template) 
     185        form = widgets.Form("form", fields=[fieldset], template=template) 
    172186 
     187        # Good example below of how you can pass parameters and values to nested 
     188        # widgets. 
     189        value = dict(foo=dict(foo="HiYo!")) 
     190        params = dict(attrs=dict(foo=dict(foo=dict(size=100)))) 
     191        params['format'] = 'xhtml' 
     192        return form.render(value, **params) 
     193 
     194 
    173195def test_nested_variables(): 
    174     newroot = NestedController() 
    175     cherrypy.root = None 
    176     cherrypy.tree.mount_points = {} 
    177     cherrypy.tree.mount(newroot, "/") 
     196    testutil.start_server(NestedController()) 
    178197    url = u"/checkform?foo.name=Kevin&foo.age=some%20Numero".encode("utf-8") 
    179     create_request(url) 
     198    request = go(url) 
    180199    assert config.get("decoding_filter.encoding", path="/") == "utf8" 
    181     assert newroot.foo 
    182     assert newroot.foo["name"] == "Kevin" 
    183     assert newroot.foo["age"] == u"some Numero" 
     200    assert request.raw["name"] == "Kevin" 
     201    assert request.raw["age"] == u"some Numero" 
    184202 
    185203def test_field_for(): 
    186     cherrypy.request.validation_errors = dict(foo=dict(foo='error')) 
    187     template = """\ 
    188     <div xmlns:py="http://purl.org/kid/ns#"> 
    189         ${field_for('foo').fq_name}.appears 
    190         ${field_for('foo').error}_appears 
    191         ${field_for('foo').field_id}_appears 
    192         ${field_for('foo').display(value_for('foo'), **params_for('foo'))} 
    193     </div> 
    194     """ 
    195     textfield = widgets.TextField("foo") 
    196     fieldset = widgets.FieldSet("foo", fields=[textfield], template=template) 
    197     form = widgets.Form("form", fields=[fieldset], template=template) 
    198     # Good example below of how you can pass parameters and values to nested 
    199     # widgets. 
    200     value = dict(foo=dict(foo="HiYo!")) 
    201     params = dict(attrs=dict(foo=dict(foo=dict(size=100)))) 
    202     params['format'] = 'xhtml' 
    203     output = form.render(value, **params) 
     204    response = testutil.go('/field_for') 
     205    output = response.body 
    204206    assert "form_foo_appears" in output 
    205207    assert "form_foo_foo_appears" in output 
    206208    assert "foo.appears" in output 
  • turbogears/widgets/tests/test_request_related_features.py

     
    11import re 
    22import turbogears 
    33import cherrypy 
    4  
    54import turbogears.testutil as testutil 
    6 from turbogears import widgets, validators 
     5from turbogears import widgets, validators, validate, expose, error_handler 
    76 
    87def test_required_fields(): 
    98    """ 
     
    2019            return dict(form=form) 
    2120        test = turbogears.expose(template="turbogears.widgets.tests.form")(test) 
    2221 
    23     cherrypy.root = MyRoot() 
    24     testutil.create_request("/test") 
    25     output = cherrypy.response.body[0].lower() 
     22    testutil.mount(MyRoot()) 
     23    response = testutil.go("/test") 
     24    output = response.body.lower() 
    2625 
    2726    print output 
    2827    name_p = 'name="comment"' 
     
    4847    form2 = widgets.TableForm(name="form2", fields=MyFields()) 
    4948 
    5049    class MyRoot(turbogears.controllers.RootController): 
    51         def test(self): 
    52             return dict(form1=form1, form2=form2) 
     50        
     51        #@expose(template="turbogears.widgets.tests.two_forms")  
     52        #@validate(form=form1) 
     53        #@error_handler('test') 
     54        def test(self, age, email): 
     55            validated_form = cherrypy.request.validated_form.name 
     56            form1_valid = form1.is_validated 
     57            form2_valid = form2.is_validated 
     58            return dict(form1=form1, form2=form2, validated_form=validated_form, 
     59                        form1_valid=form1_valid, form2_valid=form2_valid) 
    5360        test = turbogears.expose(template="turbogears.widgets.tests.two_forms")(test) 
    5461        test = turbogears.validate(form=form1)(test) 
    5562        test = turbogears.error_handler(test)(test) 
    5663 
     64 
    5765        def test2(self): 
    58             return dict(form=form2) 
     66            validated_form = cherrypy.request.validated_form.name 
     67            form1_valid = form1.is_validated 
     68            form2_valid = form2.is_validated 
     69            return dict(form=form2, validated_form=validated_form, 
     70                        form1_valid=form1_valid, form2_valid=form2_valid) 
    5971        test2 = turbogears.expose(template="turbogears.widgets.tests.form")(test2) 
    6072        test2 = turbogears.validate(form=form2)(test2) 
    6173        test2 = turbogears.error_handler(test2)(test2) 
    6274 
    6375        def test3(self): 
    64             return dict(form=form1) 
     76            validated_form = cherrypy.request.validated_form.name 
     77            form1_valid = form1.is_validated 
     78            form2_valid = form2.is_validated 
     79            return dict(form=form1, validated_form=validated_form, 
     80                        form1_valid=form1_valid, form2_valid=form2_valid) 
    6581        test3 = turbogears.expose(template="turbogears.widgets.tests.form")(test3) 
    6682        test3 = turbogears.validate(form=form2)(test3) 
    6783        test3 = turbogears.error_handler(test3)(test3) 
    6884 
    69     cherrypy.root = MyRoot() 
    70     testutil.create_request("/test?age=foo&email=bar") 
    71     output = cherrypy.response.body[0].lower() 
    72     iv = cherrypy.request.input_values 
    73     validation_errors = cherrypy.request.validation_errors 
    74     validated_form = cherrypy.request.validated_form 
     85    testutil.mount(MyRoot()) 
     86    response = testutil.go("/test?age=foo&email=bar") 
     87    output = response.body.lower() 
    7588 
    76     print output 
    77     print iv 
    78     print validation_errors 
    79     print validated_form 
    80     assert form1 is validated_form 
    81     assert form1.is_validated 
    82     assert form2 is not validated_form 
    83     assert not form2.is_validated 
     89    assert response.raw['validated_form'] == 'form1' 
     90    assert response.raw['form1_valid'] 
     91    assert not response.raw['form2_valid'] 
    8492    value_p = 'value="foo"' 
    8593    id_p = 'id="form1_age"' 
    8694    assert (re.compile('.*'.join([value_p, id_p])).search(output) or 
     
    92100            re.compile('.*'.join([id_p, value_p])).search(output) 
    93101    ) 
    94102 
    95     cherrypy.root = MyRoot() 
    96     testutil.create_request("/test2?age=foo&email=bar") 
    97     output = cherrypy.response.body[0].lower() 
    98     iv = cherrypy.request.input_values 
    99     validation_errors = cherrypy.request.validation_errors 
    100     validated_form = cherrypy.request.validated_form 
     103    response = testutil.go("/test2?age=foo&email=bar") 
     104    output = response.body.lower() 
    101105 
    102     print output 
    103     print iv 
    104     print validation_errors 
    105     print validated_form 
    106     assert form1 is not validated_form 
    107     assert not form1.is_validated 
    108     assert form2 is validated_form 
    109     assert form2.is_validated 
     106    assert response.raw['validated_form'] == 'form2' 
     107    assert not response.raw['form1_valid'] 
     108    assert response.raw['form2_valid'] 
    110109    assert 'value="foo"' in output 
    111110    assert '>bar<' in output 
    112111    assert 'class="fielderror"' in output 
    113112 
    114     cherrypy.root = MyRoot() 
    115     testutil.create_request("/test3?age=foo&email=bar") 
    116     output = cherrypy.response.body[0].lower() 
    117     iv = cherrypy.request.input_values 
    118     validation_errors = cherrypy.request.validation_errors 
    119     validated_form = cherrypy.request.validated_form 
     113    response = testutil.go("/test3?age=foo&email=bar") 
     114    output = response.body.lower() 
    120115 
    121     print output 
    122     print iv 
    123     print validation_errors 
    124     print validated_form 
    125     assert form1 is not validated_form 
    126     assert not form1.is_validated 
    127     assert form2 is validated_form 
    128     assert form2.is_validated 
     116    assert response.raw['validated_form'] == 'form2' 
     117    assert not response.raw['form1_valid'] 
     118    assert response.raw['form2_valid'] 
    129119    assert 'value="foo"' not in output 
    130120    assert '>bar<' not in output 
    131121    assert 'class="fielderror"' not in output 
     
    141131            name="repeat", fields=MyFields(), repetitions=repetitions)]) 
    142132 
    143133    class MyRoot(turbogears.controllers.RootController): 
    144         @turbogears.expose(template="turbogears.widgets.tests.form") 
    145134        def test(self): 
    146135            return dict(form=form) 
     136        test = turbogears.expose(template="turbogears.widgets.tests.form")(test) 
    147137 
    148         @turbogears.expose(template="turbogears.widgets.tests.form") 
    149138        def test_value(self): 
    150139            value = dict(repeat=[{'name':'foo', 'comment':'hello'}, 
    151140                                 None, 
    152141                                 None, 
    153142                                 {'name':'bar', 'comment':'byebye'}]) 
    154143            return dict(form=form, value=value) 
     144        test_value = turbogears.expose(template="turbogears.widgets.tests.form")(test_value) 
    155145 
    156146        def test_validation(self): 
    157             return dict(form=form) 
    158         test_validation = turbogears.expose( 
    159              template="turbogears.widgets.tests.form")(test_validation) 
     147            validation_errors = cherrypy.request.validation_errors 
     148            return dict(form=form, validation_errors=validation_errors) 
     149        test_validation = turbogears.expose(template="turbogears.widgets.tests.form")(test_validation) 
    160150        test_validation = turbogears.validate(form=form)(test_validation) 
    161151        test_validation = turbogears.error_handler(test_validation)(test_validation) 
    162152 
    163     cherrypy.root = MyRoot() 
    164     testutil.create_request("/test") 
    165     output = cherrypy.response.body[0].lower() 
     153    testutil.mount(MyRoot()) 
     154    response = testutil.go("/test") 
     155    output = response.body.lower() 
    166156    for i in range(repetitions): 
    167157        assert 'id="form_repeat_%i"' % i in output 
    168158        assert 'name="repeat-%i.name"' % i in output 
     
    170160        assert 'name="repeat-%i.comment"' % i in output 
    171161        assert 'id="form_repeat_%i_comment"' % i in output 
    172162 
    173     cherrypy.root = MyRoot() 
    174     testutil.create_request("/test_value") 
    175     output = cherrypy.response.body[0].lower() 
     163    testutil.mount(MyRoot()) 
     164    response = testutil.go("/test_value") 
     165    output = response.body.lower() 
    176166    name_p = 'name="repeat-0.name"' 
    177167    value_p = 'value="foo"' 
    178168    assert (re.compile('.*'.join([value_p, name_p])).search(output) or 
     
    204194            re.compile('.*'.join([name_p, value_p])).search(output) 
    205195    ) 
    206196 
    207     cherrypy.root = MyRoot() 
    208     testutil.create_request("/test_validation?repeat-0.name=foo&repeat-1.name=" 
     197    testutil.mount(MyRoot()) 
     198    response = testutil.go("/test_validation?repeat-0.name=foo&repeat-1.name=" 
    209199        "&repeat-2.name=bar&repeat-3.name=&repeat-4.name=") 
    210     output = cherrypy.response.body[0].lower() 
    211     validation_errors = cherrypy.request.validation_errors 
     200    output = response.body.lower() 
     201    validation_errors = response.raw['validation_errors'] 
    212202    assert validation_errors.has_key("repeat") 
    213203    assert isinstance(validation_errors["repeat"], list) 
    214204    assert validation_errors["repeat"][0] is None 
  • turbogears/widgets/tests/test_widgets.py

     
    44from turbogears.testutil import catch_validation_errors 
    55 
    66def setup_module(): 
    7     testutil.start_cp() 
     7    testutil.start_server() 
    88    cherrypy.serving.request = testutil.DummyRequest() 
    99 
    1010 
  • turbogears/widgets/tests/test_nested_widgets.py

     
    11import re 
    2 from turbogears.testutil import catch_validation_errors, start_cp 
     2from turbogears.testutil import catch_validation_errors, start_server 
    33import turbogears 
    44from turbogears import testutil 
    5 import cherrypy 
    65import turbogears.widgets as widgets 
    76import turbogears.validators as validators 
    87from turbogears.widgets.meta import copy_schema 
    98 
    109def setup_module(): 
    11     global oldrequest 
    12     start_cp() 
     10    start_server() 
    1311 
    1412 
    1513#XXX: We ignore missing keys to make passing value easier in tests 
     
    5654        Checks if names fo the widgets are set correctly depending on their 
    5755        path. 
    5856        """ 
    59         cherrypy.root = self.MyRoot() 
    60         testutil.create_request('/?test_id=sub2') 
    61         output = cherrypy.response.body[0] 
     57        testutil.mount(self.MyRoot()) 
     58        response = testutil.go('/?test_id=sub2') 
     59        output = response.body 
    6260        value_p = 'value="22"' 
    6361        name_p = 'name="sub.sub2.age"' 
    6462        assert (re.compile('.*'.join([value_p, name_p])).search(output) or 
    6563                re.compile('.*'.join([name_p, value_p])).search(output)) 
    6664 
    67         testutil.create_request('/?test_id=sub') 
    68         output = cherrypy.response.body[0] 
     65        response = testutil.go('/?test_id=sub') 
     66        output = response.body 
    6967        value_p = 'value="22"' 
    7068        name_p = 'name="sub.age"' 
    7169        id_p = 'id="myform_sub_age"' 
     
    7472        assert (re.compile('.*'.join([value_p, id_p])).search(output) or 
    7573                re.compile('.*'.join([id_p, value_p])).search(output)) 
    7674 
    77         testutil.create_request('/?test_id=age') 
    78         output = cherrypy.response.body[0] 
     75        response = testutil.go('/?test_id=age') 
     76        output = response.body 
    7977        value_p = 'value="22"' 
    8078        name_p = 'name="age"' 
    8179        assert (re.compile('.*'.join([value_p, name_p])).search(output) or 
  • turbogears/view/base.py

     
    107107    @type template: string 
    108108 
    109109    """ 
     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 
    110114    template = info.pop("tg_template", template) 
    111115    if not info.has_key("tg_flash"): 
    112116        if config.get("tg.empty_flash", True):