Ticket #1762: webtest-ken.patch

File webtest-ken.patch, 134.9 kB (added by kskuhlman, 4 months ago)

Ken's attempt

  • setup.py

    old new  
    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

    old new  
    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

    old new  
    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

    old new  
    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

    old new  
    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

    old new  
    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