Ticket #1762: webtest_blended.patch

File webtest_blended.patch, 141.7 kB (added by kskuhlman, 2 years ago)

Patch including a blending of Luke & Ken's approaches.

  • 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 dict() 
    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() 
     
    136146            return 'wrong params: %s\nexpected unicode objects' \ 
    137147                ' for all strings' % cherrypy.request.params 
    138148 
     149    @expose() 
     150    def is_anonymous(self): 
     151        assert cherrypy.serving.request.identity.user_name == None 
     152        assert cherrypy.serving.request.identity.anonymous 
     153        assert identity.current.anonymous 
     154        return 'is_anonymous' 
    139155 
    140 class TestIdentity(unittest.TestCase): 
    141156 
     157 
     158class TestIdentity(testutil.TGWebTest): 
     159 
    142160    def setUp(self): 
    143161        # identity requires visit and a failure_url 
    144162        test_config = {'global': { 
     
    151169        self._original_config = original_config 
    152170        config.configure_loggers(test_config) 
    153171        config.update(test_config['global']) 
    154         cherrypy.root = IdentityRoot(
    155         startup.startTurboGears(
     172        testutil.mount(IdentityRoot()
     173        testutil.TGWebTest.setUp(self
    156174        self.init_model() 
    157175 
    158176    def tearDown(self): 
    159         startup.stopTurboGears() 
     177        testutil.unmount() 
     178        testutil.TGWebTest.tearDown(self) 
    160179        config.update(self._original_config) 
    161180 
    162181    def init_model(self): 
     
    181200 
    182201    def test_user_password_parameters(self): 
    183202        """Controller can receive user_name and password parameters.""" 
    184         testutil.create_request('/new_user_setup?user_name=test&password=pw') 
    185         firstline = cherrypy.response.body[0] 
    186         assert 'test pw' in firstline, firstline 
     203        response = self.app.get('/new_user_setup?user_name=test&password=pw') 
     204        assert 'test pw' in response 
    187205 
    188206    def test_user_exists(self): 
    189207        u = TG_User.by_user_name('samIam') 
     
    205223        config.update({'identity.soprovider.encryption_algorithm': None}) 
    206224        # force new config values to load 
    207225        startup.startTurboGears() 
    208         testutil.create_request('/') 
     226        self.app.get('/') 
    209227        hub.begin() 
    210228        u = TG_User.by_user_name('samIam') 
    211229        u.password = u'garçon' 
     
    219237        config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 
    220238        # force new config values to load 
    221239        startup.startTurboGears() 
    222         testutil.create_request('/') 
     240        self.app.get('/') 
    223241        hub.begin() 
    224242        u = TG_User.by_user_name('samIam') 
    225243        u.password = 'password' 
     
    234252        config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 
    235253        # force new config values to load 
    236254        startup.startTurboGears() 
    237         testutil.create_request('/') 
     255        self.app.get('/') 
    238256        hub.begin() 
    239257        u = TG_User.by_user_name('samIam') 
    240258        u.password = u'garçon' 
     
    248266        config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 
    249267        # force new config values to load 
    250268        startup.startTurboGears() 
    251         testutil.create_request('/') 
     269        self.app.get('/') 
    252270        hub.begin() 
    253271        u = TG_User.by_user_name('samIam') 
    254272        u.password = 'password' 
     
    263281        config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 
    264282        # force new config values to load 
    265283        startup.startTurboGears() 
    266         testutil.create_request('/') 
     284        self.app.get('/') 
    267285        hub.begin() 
    268286        u = TG_User.by_user_name('samIam') 
    269287        u.password = u'garçon' 
     
    280298        config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 
    281299        # force new config values to load 
    282300        startup.startTurboGears() 
    283         testutil.create_request('/') 
     301        self.app.get('/') 
    284302        hub.begin() 
    285303        u = TG_User.by_user_name('samIam') 
    286304        u.password = u'garçon'.encode('UTF-8') 
     
    295313        config.update({'identity.soprovider.encryption_algorithm':'sha1'}) 
    296314        # force new config values to load 
    297315        startup.startTurboGears() 
    298         testutil.create_request('/') 
     316        self.app.get('/') 
    299317        hub.begin() 
    300318        u = TG_User.by_user_name('samIam') 
    301319        u.set_password_raw('password') 
     
    308326        config.update({'identity.soprovider.encryption_algorithm':'sha1'}) 
    309327        # force new config values to load 
    310328        startup.startTurboGears() 
    311         testutil.create_request('/') 
     329        self.app.get('/') 
    312330        hub.begin() 
    313331        u = TG_User.by_user_name('samIam') 
    314332        u.set_password_raw(u'garçon') 
     
    324342                'identity.tests.test_identity.mycustomencrypt'}) 
    325343        # force new config values to load 
    326344        startup.startTurboGears() 
    327         testutil.create_request('/') 
     345        self.app.get('/') 
    328346        hub.begin() 
    329347        u = TG_User.by_user_name('samIam') 
    330348        u.password = 'password' 
     
    335353 
    336354    def test_anonymous_browsing(self): 
    337355        """Test if we can show up anonymously.""" 
    338         testutil.create_request('/') 
    339         assert identity.current.anonymous 
     356        response = self.app.get('/is_anonymous') 
     357        assert 'is_anonymous' in response 
    340358 
    341359    def test_deny_anonymous(self): 
    342360        """Test that we have secured an url from anonymous users.""" 
    343         testutil.create_request('/logged_in_only') 
    344         firstline = cherrypy.response.body[0] 
    345         assert 'identity_failed_answer' in firstline, firstline 
     361        response = self.app.get('/logged_in_only') 
     362        assert 'identity_failed_answer' in response 
    346363 
    347364    def test_deny_anonymous_viewable(self): 
    348365        """Test that a logged in user can see an resource blocked 
    349366        from anonymous users.""" 
    350         testutil.create_request('/logged_in_only?' 
     367        response = self.app.get('/logged_in_only?' 
    351368            'user_name=samIam&password=secret&login=Login') 
    352         firstline = cherrypy.response.body[0] 
    353         assert 'logged_in_only' in firstline, firstline 
     369        assert 'logged_in_only' in response 
    354370 
    355371    def test_logout(self): 
    356372        """Test that logout works and session is gets invalid afterwards.""" 
    357         testutil.create_request('/in_peon_group?' 
     373        response = self.app.get('/in_peon_group?' 
    358374            'user_name=samIam&password=secret&login=Login') 
    359         self.assertEquals("samIam", cherrypy.serving.request.identity.user_name) 
    360         session_id = re.match("Set-Cookie: (.*?); Path.*", 
    361             str(cherrypy.response.simple_cookie)).group(1) 
    362         testutil.create_request('/logout', headers={'Cookie': session_id }) 
    363         self.assertEquals(None, cherrypy.serving.request.identity.user_name) 
    364         assert cherrypy.serving.request.identity.anonymous 
     375        session_id = response.headers['Set-Cookie'] 
     376        response = self.app.get('/logout', headers={'Cookie': session_id }) 
     377        response = self.app.get('/is_anonymous', headers={'Cookie': session_id}) 
     378        assert response.body == 'is_anonymous' 
    365379 
    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  
    378380    def test_require_group(self): 
    379381        """Test that a anonymous user""" 
    380         testutil.create_request('/in_peon_group') 
    381         firstline = cherrypy.response.body[0] 
    382         assert 'identity_failed_answer' in firstline, firstline 
     382        response = self.app.get('/in_peon_group') 
     383        assert 'identity_failed_answer' in response, response 
    383384 
    384385    def test_require_expose_required_permission(self): 
    385386        """Test that the decorator exposes the correct permissions via _require 
    386387        attribute on the actual method.""" 
    387         testutil.create_request('/test_exposed_require') 
    388         firstline= cherrypy.response.body[0] 
    389         assert 'require is exposed' in firstline, firstline 
     388        response = self.app.get('/test_exposed_require') 
     389        assert 'require is exposed' in response, response 
    390390 
    391391    def test_require_group_viewable(self): 
    392392        """Test that a user with proper group membership can see a restricted url.""" 
    393         testutil.create_request('/in_peon_group?' 
     393        response = self.app.get('/in_peon_group?' 
    394394            'user_name=samIam&password=secret&login=Login') 
    395         firstline = cherrypy.response.body[0] 
    396         assert 'in_peon_group' in firstline, firstline 
     395        assert 'in_peon_group' in response, response 
    397396        user = TG_User.by_user_name("samIam") 
    398397 
    399398    def test_require_group_viewable(self): 
    400399        """Test that the current user and group properties are set correctly.""" 
    401         testutil.create_request('/in_peon_group?' 
     400        response = self.app.get('/in_peon_group?' 
    402401            'user_name=samIam&password=secret&login=Login') 
    403402        user = TG_User.by_user_name("samIam") 
    404403        group_ids = set((TG_Group.by_group_name("peon").id, 
    405404            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 
    411405 
    412406    def test_user_not_in_right_group(self): 
    413         """Test that a user is denied access if they aren't in the right group.""" 
    414         testutil.create_request('/in_admin_group?' 
     407        """Test that a user is denied access if they aren't in the right group. 
     408        """ 
     409        response = self.app.get('/in_admin_group?' 
    415410            'user_name=samIam&password=secret&login=Login') 
    416         firstline = cherrypy.response.body[0] 
    417         assert 'identity_failed_answer' in firstline, firstline 
     411        assert 'identity_failed_answer' in response, response 
    418412 
    419413    def test_require_permission(self): 
    420         """Test that an anonymous user is denied access to a permission restricted url.""" 
    421         testutil.create_request('/has_chopper_permission') 
    422         firstline = cherrypy.response.body[0] 
    423         assert 'identity_failed_answer' in firstline, firstline 
     414        """Test that an anonymous user is denied access to a permission  
     415        restricted url. 
     416        """ 
     417        response = self.app.get('/has_chopper_permission') 
     418        assert 'identity_failed_answer' in response, response 
    424419 
    425420    def test_require_permission_viewable(self): 
    426421        """Test that a user with proper permissions can see a restricted url.""" 
    427         testutil.create_request('/has_chopper_permission?' 
     422        response = self.app.get('/has_chopper_permission?' 
    428423            'user_name=samIam&password=secret&login=Login') 
    429         firstline = cherrypy.response.body[0] 
    430         assert 'has_chopper_permission' in firstline, firstline 
     424        assert 'has_chopper_permission' in response 
    431425 
    432426    def test_user_lacks_permission(self): 
    433         """Test that a user is denied acces if they don't have the proper permission.""" 
    434         testutil.create_request('/has_boss_permission?' 
     427        """Test that a user is denied acces if they don't have the proper  
     428        permission. 
     429        """ 
     430        response = self.app.get('/has_boss_permission?' 
    435431            'user_name=samIam&password=secret&login=Login') 
    436         firstline = cherrypy.response.body[0] 
    437         assert 'identity_failed_answer' in firstline, firstline 
     432        assert 'identity_failed_answer' in response, response 
    438433 
    439434    def test_user_info_available(self): 
    440435        """Test that we can see user information inside our controller.""" 
    441         testutil.create_request('/user_email?' 
     436        response = self.app.get('/user_email?' 
    442437            'user_name=samIam&password=secret&login=Login') 
    443         firstline = cherrypy.response.body[0] 
    444         assert 'samiam@example.com' in firstline, firstline 
     438        assert 'samiam@example.com' in response, response 
    445439 
    446440    def test_bad_login(self): 
    447441        """Test that we are denied access if we provide a bad login.""" 
    448         testutil.create_request('/logged_in_only?' 
     442        response = self.app.get('/logged_in_only?' 
    449443            'user_name=samIam&password=wrong&login=Login') 
    450         firstline = cherrypy.response.body[0] 
    451         assert 'identity_failed_answer' in firstline, firstline 
     444        assert 'identity_failed_answer' in response, response 
    452445 
    453446    def test_restricted_subdirectory(self): 
    454447        """Test that we can restrict access to a whole subdirectory.""" 
    455         testutil.create_request('/peon_area/index') 
    456         firstline = cherrypy.response.body[0] 
    457         assert 'identity_failed_answer' in firstline, firstline 
     448        response = self.app.get('/peon_area/index') 
     449        assert 'identity_failed_answer' in response, response 
    458450 
    459451    def test_restricted_subdirectory_viewable(self): 
    460452        """Test that we can access a restricted subdirectory 
    461453        if we have proper credentials.""" 
    462         testutil.create_request('/peon_area/index?' 
     454        response = self.app.get('/peon_area/index?' 
    463455            'user_name=samIam&password=secret&login=Login') 
    464         firstline = cherrypy.response.body[0] 
    465         assert 'restricted_index' in firstline, firstline 
     456        assert 'restricted_index' in response, response 
    466457 
    467458    def test_decoratator_in_restricted_subdirectory(self): 
    468459        """Test that we can require a different permission 
    469460        in a protected subdirectory.""" 
    470         testutil.create_request('/peon_area/in_other_group?' 
     461        response = self.app.get('/peon_area/in_other_group?' 
    471462            'user_name=samIam&password=secret&login=Login') 
    472         firstline = cherrypy.response.body[0] 
    473         assert 'in_other_group' in firstline, firstline 
     463        assert 'in_other_group' in response, response 
    474464 
    475465    def test_decoratator_failure_in_restricted_subdirectory(self): 
    476466        """Test that we can get an identity failure from a decorator 
    477467        in a restricted subdirectory""" 
    478         testutil.create_request('/peon_area/in_admin_group?' 
     468        response = self.app.get('/peon_area/in_admin_group?' 
    479469            'user_name=samIam&password=secret&login=Login') 
    480         firstline = cherrypy.response.body[0] 
    481         assert 'identity_failed_answer' in firstline, firstline 
     470        assert 'identity_failed_answer' in response, response 
    482471 
    483472    def test_explicit_checks_in_restricted_subdirectory(self): 
    484473        """Test that explicit permission checks in a protected 
    485474        directory is handled as expected""" 
    486         testutil.create_request('/peon_area/in_other_group_explicit_check?' 
     475        response = self.app.get('/peon_area/in_other_group_explicit_check?' 
    487476            'user_name=samIam&password=secret&login=Login') 
    488         firstline = cherrypy.response.body[0] 
    489         assert 'in_other_group' in firstline, firstline 
     477        assert 'in_other_group' in response, response 
    490478 
    491479    def test_throwing_identity_exception_in_restricted_subdirectory(self): 
    492480        """Test that throwing an IdentityException in a protected 
    493481        directory is handled as expected""" 
    494         testutil.create_request('/peon_area/in_admin_group_explicit_check?' 
     482        response = self.app.get('/peon_area/in_admin_group_explicit_check?' 
    495483            'user_name=samIam&password=secret&login=Login') 
    496         firstline = cherrypy.response.body[0] 
    497         assert 'identity_failed' in firstline, firstline 
     484        assert 'identity_failed' in response, response 
    498485 
    499486    def test_decode_filter_whenidfails(self): 
    500487        """Test that the decode filter doesn't break with nested 
    501488        variables and Identity""" 
    502489        params = urllib.quote(IdentityRoot._test_encoded_params.decode( 
    503490            'utf-8').encode('latin-1'), '=&') 
    504         testutil.create_request('/test_params?' + params) 
    505         firstline = cherrypy.response.body[0] 
    506         assert 'identity_failed_answer' in firstline, firstline 
     491        response = self.app.get('/test_params?' + params) 
     492        assert 'identity_failed_answer' in response, response 
    507493 
    508494    def test_decode_filter_whenidworks(self): 
    509495        """Test that the decode filter doesn't break with nested 
     
    511497        params = urllib.quote(IdentityRoot._test_encoded_params.decode( 
    512498            'utf-8').encode('latin-1'), '=&') 
    513499        params += '&user_name=samIam&password=secret&login=Login' 
    514         testutil.create_request('/test_params?' + params) 
    515         firstline = cherrypy.response.body[0] 
    516         assert 'params ok' in firstline, firstline 
     500        response = self.app.get('/test_params?' + params) 
     501        assert 'params ok' in response, response 
    517502 
    518503 
    519504class TestTGUser(testutil.DBTest): 
     
    522507    def setUp(self): 
    523508        self._identity_on = config.get('identity.on', False) 
    524509        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 
    530510        startup.startTurboGears() 
    531511        testutil.DBTest.setUp(self) 
    532512 
    533513    def tearDown(self): 
    534514        testutil.DBTest.tearDown(self) 
    535515        startup.stopTurboGears() 
    536         cherrypy.request.identityProvider = self._provider 
    537516        config.update({'identity.on': self._identity_on}) 
    538517 
    539518    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        visit_on = config.get('visit.on') 
     21        return dict(new=new, visit_on=visit_on) 
    1722 
    1823 
    1924class TestVisit(TestCase): 
    2025 
    2126    def setUp(self): 
     27        testutil.stop_server(tg_only = True) 
    2228        self._visit_on = config.get('visit.on', False) 
    2329        config.update({'visit.on': True}) 
    2430        self._visit_timeout = config.get('visit.timeout', 20) 
    2531        config.update({'visit.timeout': 50}) 
    2632        self.cookie_name = config.get("visit.cookie.name", 'tg-visit') 
    27         cherrypy.root = VisitRoot() 
     33        self.app = testutil.make_app(VisitRoot) 
     34        testutil.start_server() 
    2835 
    2936    def tearDown(self): 
    30         startup.stopTurboGears(
     37        testutil.stop_server(tg_only = True
    3138        config.update({'visit.timeout': self._visit_timeout}) 
    3239        config.update({'visit.on': self._visit_on}) 
    3340 
    3441    def test_visit_response(self): 
    3542        """Test if the visit cookie is set in cherrypy.response.""" 
    36         testutil.create_request("/") 
    37         assert cherrypy.response.simple_cookie.has_key(self.cookie_name) 
     43        response = self.app.get("/") 
     44        assert response.cookies_set.has_key(self.cookie_name) 
    3845 
    3946    def test_new_visit(self): 
    4047        """Test that we can see a new visit on the server.""" 
    41         testutil.create_request("/") 
    42         assert visit.current().is_new 
     48        response = self.app.get("/") 
     49        assert response.raw['new'] 
    4350 
    4451    def test_old_visit(self): 
    4552        """Test if we can track a visitor over time.""" 
    46         testutil.create_request("/") 
     53        response = self.app.get("/") 
    4754        # first visit's cookie 
    48         morsel = cherrypy.response.simple_cookie[self.cookie_name] 
    49         testutil.create_request("/", headers=cookie_header(morsel)) 
    50         assert not visit.current().is_new 
     55        print "Headers", response.headers 
     56        print "Config", config.get('visit.on') 
     57        morsel = response.cookies_set[self.cookie_name] 
     58        response = self.app.get("/", headers=cookie_header(response)) 
     59        assert not response.raw['new'] 
    5160 
    5261    def test_cookie_expires(self): 
    5362        """Test if the visit timeout mechanism works.""" 
    5463        timeout = config.get('visit.timeout', 50) 
     64        _app = self.app 
    5565        try: 
    5666            # set expiration to one second for this test only 
     67            testutil.stop_server(tg_only = True) 
    5768            config.update({'visit.timeout': 1.0/60}) 
    58             testutil.create_request("/") 
    59             morsel = cherrypy.response.simple_cookie[self.cookie_name] 
     69            self.app = testutil.make_app(VisitRoot) 
     70            testutil.start_server() 
     71            response = self.app.get("/") 
     72            morsel = response.cookies_set[self.cookie_name] 
    6073            time.sleep(2) # 2 seconds 
    61             testutil.create_request("/", headers=cookie_header(morsel)) 
     74            response = self.app.get("/", headers=cookie_header(response)) 
    6275        finally: 
    6376            config.update({'visit.timeout': timeout}) 
    64         assert cherrypy.response.simple_cookie[ 
    65                 self.cookie_name].value != morsel.value, \ 
     77            self.app = _app 
     78        assert response.cookies_set[ 
     79                self.cookie_name] != morsel, \ 
    6680            'cookie values should not match' 
    67         assert visit.current().is_new, \ 
     81        assert response.raw['new'], \ 
    6882            'this should be a new visit, as the cookie has expired' 
    6983 
    7084    def test_cookie_not_permanent(self): 
    7185        """Check that by default the visit cookie is not permanent.""" 
    72         testutil.create_request('/') 
    73         morsel = cherrypy.response.simple_cookie[self.cookie_name] 
     86        response = self.app.get('/') 
     87        cookies = SimpleCookie(response.headers['Set-Cookie']) 
     88        morsel = cookies[self.cookie_name] 
    7489        assert not morsel['expires'] and not morsel['max-age'] 
    7590 
    7691    def test_cookie_permanent(self): 
     
    7893        permanent = config.get('visit.cookie.permanent', False) 
    7994        try: 
    8095            # set cookie permanent for this test only (needs restart) 
    81             startup.stopTurboGears(
     96            testutil.stop_server(tg_only = True
    8297            config.update({'visit.cookie.permanent': True}) 
    83             startup.startTurboGears() 
    84             testutil.create_request('/') 
    85             morsel = cherrypy.response.simple_cookie[self.cookie_name] 
     98            app = testutil.make_app(VisitRoot) 
     99            testutil.start_server() 
     100            response = app.get('/') 
     101            cookies = SimpleCookie(response.headers['Set-Cookie']) 
     102            morsel = cookies[self.cookie_name] 
    86103        finally: 
    87104            config.update({'visit.cookie.permanent': permanent}) 
    88         assert morsel['max-age'] == 3000 
     105        assert morsel['max-age'] == '3000' 
    89106        expires = time.mktime(time.strptime(morsel['expires'], 
    90107            '%a, %d-%b-%Y %H:%M:%S GMT')[:8] + (0,)) 
    91         should_expire = time.mktime(time.gmtime()) + morsel['max-age'] 
    92         assert abs(should_expire - expires) < 3 
     108        should_expire = time.mktime(time.gmtime()) + int(morsel['max-age']) 
     109        assert abs(should_expire - expires) < 3, (should_expire, expires, should_expire - expires) 
     110 
  • turbogears/visit/api.py

    old new  
    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  
    1 from unittest import TestCase 
    21from datetime import datetime 
     2from unittest import TestCase 
    33import cherrypy 
    44from turbogears import widgets, config, controllers, expose, mochikit, \ 
    55    validate, validators, testutil 
     6from turbogears.testutil import mount, unmount, make_app 
    67 
    78 
     9def setup_module(): 
     10    global app 
     11    app = make_app(MyRoot) 
     12    testutil.start_server() 
     13 
     14def teardown_module(): 
     15    testutil.stop_server() 
     16 
     17 
    818class MyFormFields(widgets.WidgetsList): 
    919    #XXX: Since allow_extra_fields should be removed from validators.Schema, 
    1020    #     we need a validator for every input-expecting widget 
     
    1626myform = widgets.TableForm(fields=MyFormFields()) 
    1727 
    1828 
     29class State(object): 
     30    counter = 0 
     31 
     32class AddingValidator(validators.FancyValidator): 
     33    def _to_python(self, value, state=None): 
     34        state.counter += 1 
     35        return value 
     36 
     37class AddingSchema(validators.Schema): 
     38    a = AddingValidator() 
     39    b = AddingValidator() 
     40 
     41class AddingNestedSchema(AddingSchema): 
     42    c = AddingSchema() 
     43 
     44 
    1945class MyRoot(controllers.RootController): 
    2046 
    2147    @expose(html="turbogears.tests.form") 
     
    3157    def testform(self, name, date, age, tg_errors=None): 
    3258        if tg_errors: 
    3359            self.has_errors = True 
    34         self.name = name 
    35         self.age = age 
    36         self.date = date 
     60        return dict(name=name, user_age=age, birthdate=date) 
    3761 
    3862    @expose() 
    3963    @validate(form=myform) 
    4064    def testform_new_style(self, name, date, age): 
    4165        if cherrypy.request.validation_errors: 
    4266            self.has_errors = True 
    43         self.name = name 
    44         self.age = age 
    45         self.date = date 
     67        return dict(name=name, age=age, date=date) 
    4668 
     69    @expose() 
     70    @validate(validators=AddingNestedSchema(), state_factory=State) 
     71    def validation(self, a, b, c): 
     72        return 'counter: %d' % cherrypy.request.validation_state.counter 
     73 
    4774def test_form_translation(): 
    4875    """Form input is translated into properly converted parameters""" 
    49     root = MyRoot() 
    50     cherrypy.root = root 
    51     testutil.create_request("/testform?name=ed&date=11/05/2005&age=5") 
    52     assert root.name == "ed" 
    53     assert root.age == 5 
     76    response = app.get("/testform?name=ed&date=11/05/2005&age=5") 
     77    assert response.raw['name'] == "ed" 
     78    assert response.raw['user_age'] == 5 
    5479 
    5580def test_form_translation_new_style(): 
    5681    """Form input is translated into properly converted parameters""" 
    57     root = MyRoot() 
    58     cherrypy.root = root 
    59     testutil.create_request("/testform_new_style?name=ed&date=11/05/2005&age=5&") 
    60     assert root.name == "ed" 
    61     assert root.age == 5 
     82    response = app.get("/testform_new_style?name=ed&date=11/05/2005&age=5&") 
     83    assert response.raw['name'] == "ed" 
     84    assert response.raw['age'] == 5 
    6285 
    6386def test_invalid_form_with_error_handling(): 
    6487    """Invalid forms can be handled by the method""" 
    65     root = cherrypy.root 
    66     testutil.create_request("/testform?name=ed&age=edalso&date=11/05/2005") 
    67     assert root.has_errors 
     88    response = app.get("/testform?name=ed&age=edalso&date=11/05/2005") 
    6889 
    6990def test_css_should_appear(): 
    7091    """CSS should appear when asked for""" 
    71     testutil.create_request("/") 
    72     assert "calendar-system.css" in cherrypy.response.body[0] 
     92    response = app.get("/") 
     93    assert "calendar-system.css" in response 
    7394 
    7495def test_javascript_should_appear(): 
    7596    """JavaScript should appear when asked for""" 
    76     testutil.create_request("/") 
    77     assert "calendar.js" in cherrypy.response.body[0] 
     97    response = app.get("/") 
     98    assert "calendar.js" in response 
    7899 
    79100def test_include_mochikit(): 
    80101    """JSLinks (and MochiKit especially) can be included easily""" 
    81     testutil.create_request("/usemochi") 
    82     assert "MochiKit.js" in cherrypy.response.body[0] 
     102    response = app.get("/usemochi") 
     103    assert "MochiKit.js" in response 
    83104 
    84105def test_suppress_mochikit(): 
    85106    """MochiKit inclusion can be suppressed""" 
    86     config.update({"global": {"tg.mochikit_suppress": True}}) 
    87     testutil.create_request("/usemochi") 
    88     suppressed_body = cherrypy.response.body[0] 
     107    config.update({"global":{"tg.mochikit_suppress" : True}}) 
     108    suppressed = app.get("/usemochi") 
    89109    # repair the fixture 
    90     config.update({"global": {"tg.mochikit_suppress": False}}) 
    91     testutil.create_request("/usemochi") 
    92     included_body = cherrypy.response.body[0] 
    93     assert "MochiKit.js" not in suppressed_body 
    94     assert "MochiKit.js" in included_body 
     110    config.update({"global":{"tg.mochikit_suppress" : False}}) 
    95111 
     112    included = app.get("/usemochi") 
     113    assert "MochiKit.js" not in suppressed.body 
     114    assert "MochiKit.js" in included.body 
     115 
    96116def test_mochikit_everywhere(): 
    97117    """MochiKit can be included everywhere by setting tg.mochikit_all""" 
    98     config.update({"global": {"tg.mochikit_all": True}}) 
    99     testutil.create_request("/") 
    100     config.update({"global": {"tg.mochikit_all": False}}) 
    101     assert "MochiKit.js" in cherrypy.response.body[0] 
     118    config.update({"global":{"tg.mochikit_all" : True}}) 
     119    response = app.get("/") 
     120    config.update({"global":{"tg.mochikit_all" : False}}) 
     121    assert "MochiKit.js" in response 
    102122 
    103123def test_mochikit_nowhere(): 
    104124    """Setting tg.mochikit_suppress will prevent including it everywhere""" 
    105125    config.update({"global": {"tg.mochikit_all": True}}) 
    106126    config.update({"global": {"tg.mochikit_suppress": True}}) 
    107     testutil.create_request("/") 
     127    response = app.get("/") 
    108128    config.update({"global": {"tg.mochikit_all": False}}) 
    109129    config.update({"global": {"tg.mochikit_suppress": False}}) 
    110     assert "MochiKit.js" not in cherrypy.response.body[0] 
     130    assert "MochiKit.js" not in response 
    111131 
    112132def test_include_widgets(): 
    113133    """Any widget can be included everywhere by setting tg.include_widgets""" 
    114134    config.update({"global": {"tg.include_widgets": ["mochikit"]}}) 
    115     testutil.create_request("/") 
     135    response = app.get("/") 
    116136    config.update({"global": {"tg.include_widgets": []}}) 
    117     assert "MochiKit.js" in cherrypy.response.body[0] 
     137    assert "MochiKit.js" in response 
    118138 
     139def test_counter_is_incremented(): 
     140    # parameter values are irrelevant 
     141    url = '/validation?a=1&b=2&c.a=3&c.b=4' 
     142    response = app.get(url) 
     143    msg = "Validation state is not handled properly" 
     144    # 4 == 1 (a) + 1(b) + 1(c.a) + 1(c.b) 
     145    assert 'counter: 4' in response.body, msg 
    119146 
    120 class State(object): 
    121     counter = 0 
    122  
    123 class AddingValidator(validators.FancyValidator): 
    124     def _to_python(self, value, state=None): 
    125         state.counter += 1 
    126         return value 
    127  
    128 class AddingSchema(validators.Schema): 
    129     a = AddingValidator() 
    130     b = AddingValidator() 
    131  
    132 class AddingNestedSchema(AddingSchema): 
    133     c = AddingSchema() 
    134  
    135  
    136 class TestValidationState(TestCase): 
    137  
    138     class Controller(controllers.RootController): 
    139  
    140         @expose() 
    141         @validate(validators=AddingNestedSchema(), state_factory=State) 
    142         def validation(self, a, b, c): 
    143             return 'counter: %d' % cherrypy.request.validation_state.counter 
    144  
    145     def __init__(self, *args, **kw): 
    146         super(TestValidationState, self).__init__(*args, **kw) 
    147  
    148     def test_counter_is_incremented(self): 
    149         cherrypy.root = self.Controller() 
    150         # parameter values are irrelevant 
    151         url = '/validation?a=1&b=2&c.a=3&c.b=4' 
    152         testutil.create_request(url) 
    153         body = cherrypy.response.body[0] 
    154         msg = "Validation state is not handled properly" 
    155         # 4 == 1 (a) + 1(b) + 1(c.a) + 1(c.b) 
    156         self.failUnless('counter: 4' in body, msg) 
  • turbogears/tests/test_errorhandling.py

    old new  
    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 
     
    1613    else: 
    1714        return str(errors) 
    1815 
     16def setup_module(): 
     17    testutil.unmount() 
     18    testutil.mount(MyRoot()) 
     19    testutil.mount(NestedController(), "/nestedcontroller") 
     20    testutil.start_server() 
    1921 
     22def teardown_module(): 
     23    testutil.unmount() 
     24    testutil.stop_server() 
     25 
    2026class MyRoot(RootController): 
    2127 
    2228    def defaulterrorhandler(self, tg_source, tg_errors, tg_exceptions, 
     
    94100        "second": validators.Int(not_empty=True)}) 
    95101    @error_handler(defaulterrorhandler) 
    96102    def positionalargs(self, first, second, *args, **kw): 
    97         self.first = first 
    98         self.second = second 
    99         self.third = args[0] 
    100103        return dict(title="Positional arguments", first=first, second=second, 
    101                     args=args, bar=kw["bar"]) 
     104                    third=args[0], args=args, bar=kw["bar"]) 
    102105 
    103106    @expose() 
    104107    @validate(validators={"bar": validators.Int(not_empty=True)}) 
     
    141144        return self.notexposed(bar) 
    142145 
    143146    def continuation(self, tg_source): 
    144         self.continuation = True 
    145         return tg_source(self) 
     147        response = tg_source(self) 
     148        response['continuation'] = True 
     149        return response 
    146150 
    147151    @expose() 
    148152    @validate(validators={"bar": validators.Int(not_empty=True)}) 
     
    208212        return dict(title="Nested") 
    209213 
    210214 
     215app = testutil.make_app() 
     216 
    211217class TestErrorHandler(unittest.TestCase): 
    212218 
    213     def setUp(self): 
    214         cherrypy.root = MyRoot() 
    215         cherrypy.root.nestedcontroller = NestedController() 
    216  
    217219    def test_defaultErrorHandler(self): 
    218220        """Default error handler.""" 
    219         testutil.create_request("/defaulterror?bar=abc") 
    220         self.failUnless("Default error handler" in cherrypy.response.body[0]
    221         testutil.create_request("/defaulterror?bar=true") 
    222         self.failUnless("Default error provider" in cherrypy.response.body[0]
     221        response = app.get("/defaulterror?bar=abc") 
     222        self.failUnless("Default error handler" in response
     223        response = app.get("/defaulterror?bar=true") 
     224        self.failUnless("Default error provider" in response
    223225 
    224226    def test_specialisedErrorHandler(self): 
    225227        """Error handler specialisation.""" 
    226         testutil.create_request("/specialisederror?bar=abc&baz=a@b.com") 
    227         self.failUnless("Default error handler" in cherrypy.response.body[0]) 
    228         testutil.create_request("/specialisederror?baz=abc&bar=1") 
    229         self.failUnless("Specialised error handler" in 
    230                         cherrypy.response.body[0]) 
    231         testutil.create_request("/specialisederror?bar=1&baz=a@b.com") 
    232         self.failUnless("Specialised error provider" in 
    233                         cherrypy.response.body[0]) 
     228        response = app.get("/specialisederror?bar=abc&baz=a@b.com") 
     229        self.failUnless("Default error handler" in response) 
     230        response = app.get("/specialisederror?baz=abc&bar=1") 
     231        self.failUnless("Specialised error handler" in response) 
     232        response = app.get("/specialisederror?bar=1&baz=a@b.com") 
     233        self.failUnless("Specialised error provider" in response) 
    234234 
    235235    def test_exceptionErrorHandler(self): 
    236236        """Error handler for exceptions.""" 
    237         testutil.create_request("/exceptionerror") 
    238         self.failUnless("Default error handler" in cherrypy.response.body[0]
     237        response = app.get("/exceptionerror") 
     238        self.failUnless("Default error handler" in response
    239239 
    240240    def test_recursiveErrorHandler(self): 
    241241        """Recursive error handler.""" 
    242         testutil.create_request("/recursiveerror?bar=abc") 
    243         self.failUnless("Recursive error handler" in cherrypy.response.body[0]) 
    244         testutil.create_request("/recursiveerror?bar=1") 
    245         self.failUnless("Recursive error provider" in 
    246                         cherrypy.response.body[0]) 
     242        response = app.get("/recursiveerror?bar=abc") 
     243        self.failUnless("Recursive error handler" in response) 
     244        response = app.get("/recursiveerror?bar=1") 
     245        self.failUnless("Recursive error provider" in response) 
    247246 
    248247    def test_implicitErrorHandler(self): 
    249248        """Implicit error handling.""" 
    250         testutil.create_request("/impliciterror?bar=abc") 
    251         self.failUnless("Implicit error handler" in 
    252                         cherrypy.response.body[0]) 
    253         testutil.create_request("/impliciterror?bar=1") 
    254         self.failUnless("Implicit error provider" in 
    255                         cherrypy.response.body[0]) 
     249        response = app.get("/impliciterror?bar=abc") 
     250        self.failUnless("Implicit error handler" in response) 
     251        response = app.get("/impliciterror?bar=1") 
     252        self.failUnless("Implicit error provider" in response) 
    256253 
    257254    def test_normalMethodErrorHandler(self): 
    258255        """Normal method as an error handler.""" 
    259         testutil.create_request("/normalmethodcaller?bar=abc") 
    260         self.failUnless("Normal method" in cherrypy.response.body[0]
    261         testutil.create_request("/normalmethodcaller?bar=true") 
    262         self.failUnless("Normal method caller" in cherrypy.response.body[0]
     256        response = app.get("/normalmethodcaller?bar=abc") 
     257        self.failUnless("Normal method" in response
     258        response = app.get("/normalmethodcaller?bar=true") 
     259        self.failUnless("Normal method caller" in response
    263260 
    264261    def test_infiniteRecursionPrevention(self): 
    265262        """Infinite recursion prevention.""" 
    266         testutil.create_request("/infiniteloop") 
    267         self.failUnless("Exception 2" in cherrypy.response.body[0]
     263        response = app.get("/infiniteloop") 
     264        self.failUnless("Exception 2" in response
    268265 
    269266    def test_positionalArgs(self): 
    270267        """Positional argument validation.""" 
    271         testutil.create_request("/positionalargs/first/23/third?bar=abc") 
    272         self.failUnless("Default error handler" in cherrypy.response.body[0]
    273         testutil.create_request("/positionalargs/first/abc/third?bar=false") 
    274         self.failUnless("Default error handler" in cherrypy.response.body[0]
    275         testutil.create_request("/positionalargs/first/abc/third?bar=abc") 
    276         self.failUnless("Default error handler" in cherrypy.response.body[0]
    277         testutil.create_request("/positionalargs/first/23/third?bar=true") 
    278         self.failUnless("Positional arguments" in cherrypy.response.body[0]
    279         self.failUnless(cherrypy.root.first == "first") 
    280         self.failUnless(cherrypy.root.second == 23) 
    281         self.failUnless(cherrypy.root.third == "third") 
     268        response = app.get("/positionalargs/first/23/third?bar=abc") 
     269        self.failUnless("Default error handler" in response
     270        response = app.get("/positionalargs/first/abc/third?bar=false") 
     271        self.failUnless("Default error handler" in response
     272        response = app.get("/positionalargs/first/abc/third?bar=abc") 
     273        self.failUnless("Default error handler" in response
     274        response = app.get("/positionalargs/first/23/third?bar=true") 
     275        self.failUnless("Positional arguments" in response
     276        self.failUnless(response.raw['first'] == "first") 
     277        self.failUnless(response.raw['second'] == 23) 
     278        self.failUnless(response.raw['third'] == "third") 
    282279 
    283280    def test_missingArgs(self): 
    284281        """Arguments required in validation missing.""" 
    285         testutil.create_request("/missingargs") 
    286         self.failUnless("Default error handler" in cherrypy.response.body[0]
    287         testutil.create_request("/missingargs?bar=12") 
    288         self.failUnless("Missing args provider" in cherrypy.response.body[0]
     282        response = app.get("/missingargs") 
     283        self.failUnless("Default error handler" in response
     284        response = app.get("/missingargs?bar=12") 
     285        self.failUnless("Missing args provider" in response
    289286 
    290287    def test_nohandler(self): 
    291288        """No error hanlder declared.""" 
    292         testutil.create_request("/nohandler") 
    293         self.failUnless("Exception raised" in cherrypy.response.body[0]
     289        response = app.get("/nohandler") 
     290        self.failUnless("Exception raised" in response
    294291 
    295292    def test_bindArgs(self): 
    296293        """Arguments can be bond to an error handler.""" 
    297         testutil.create_request("/bindargs") 
    298         self.failUnless("123" in cherrypy.response.body[0]
     294        response = app.get("/bindargs") 
     295        self.failUnless("123" in response
    299296 
    300297    def test_notExposed(self): 
    301298        """Validation error handling is decoupled from expose.""" 
    302         testutil.create_request("/notexposedcaller?foo=a&bar=rab&baz=c") 
    303         self.failUnless("Not exposed error" in cherrypy.response.body[0]
    304         self.failUnless("rab" in cherrypy.response.body[0]
     299        response = app.get("/notexposedcaller?foo=a&bar=rab&baz=c") 
     300        self.failUnless("Not exposed error" in response
     301        self.failUnless("rab" in response
    305302 
    306303    def test_continuations(self): 
    307304        """Continuations via error handling mechanism.""" 
    308         testutil.create_request("/continuationcaller?bar=a") 
    309         self.failUnless("Continuation caller" in cherrypy.response.body[0]
    310         self.failUnless(cherrypy.root.continuation == True) 
     305        response = app.get("/continuationcaller?bar=a") 
     306        self.failUnless("Continuation caller" in response
     307        self.failUnless(response.raw['continuation'] == True) 
    311308 
    312309    def test_nested(self): 
    313310        """Potentially ambiguous cases.""" 
    314         testutil.create_request("/nest?bar=a") 
    315         self.failUnless("Default error handler" in cherrypy.response.body[0]
    316         testutil.create_request("/nestedcontroller/nest?bar=a") 
    317         self.failUnless("Nested" in cherrypy.response.body[0]
     311        response = app.get("/nest?bar=a") 
     312        self.failUnless("Default error handler" in response
     313        response = app.get("/nestedcontroller/nest?bar=a") 
     314        self.failUnless("Nested" in response
    318315 
    319316    def test_failsafe(self): 
    320317        """Failsafe values for erroneous input.""" 
    321         testutil.create_request("/failsafenone?bar=a&baz=b") 
    322         self.failUnless('"bar": "a"' in cherrypy.response.body[0]) 
    323         self.failUnless('"baz": "b"' in cherrypy.response.body[0]) 
    324         testutil.create_request("/failsafevaluesdict?bar=a&baz=b") 
    325         self.failUnless('"bar": 1' in cherrypy.response.body[0]) 
    326         self.failUnless('"baz": 2' in cherrypy.response.body[0]) 
    327         testutil.create_request("/failsafevaluesatom?bar=a&baz=b") 
    328         self.failUnless('"bar": 13' in cherrypy.response.body[0]) 
    329         self.failUnless('"baz": 13' in cherrypy.response.body[0]) 
    330         testutil.create_request("/failsafemaperrors?bar=a&baz=b") 
    331         self.failUnless('"bar": "Please enter an integer value"' in 
    332                         cherrypy.response.body[0]) 
    333         self.failUnless('"baz": "Please enter an integer value"' in 
    334                         cherrypy.response.body[0]) 
    335         testutil.create_request("/failsafeformencode?bar=a&baz=b") 
    336         self.failUnless('"bar": 1' in cherrypy.response.body[0]) 
    337         self.failUnless('"baz": 2' in cherrypy.response.body[0]) 
    338         testutil.create_request("/failsafedefaults?bar=a&baz=b") 
    339         self.failUnless('"bar": 1' in cherrypy.response.body[0]) 
    340         self.failUnless('"baz": 2' in cherrypy.response.body[0]) 
     318        response = app.get("/failsafenone?bar=a&baz=b") 
     319        self.failUnless('"bar": "a"' in response) 
     320        self.failUnless('"baz": "b"' in response) 
     321        response = app.get("/failsafevaluesdict?bar=a&baz=b") 
     322        self.failUnless('"bar": 1' in response) 
     323        self.failUnless('"baz": 2' in response) 
     324        response = app.get("/failsafevaluesatom?bar=a&baz=b") 
     325        self.failUnless('"bar": 13' in response) 
     326        self.failUnless('"baz": 13' in response) 
     327        response = app.get("/failsafemaperrors?bar=a&baz=b") 
     328        self.failUnless('"bar": "Please enter an integer value"' in response) 
     329        self.failUnless('"baz": "Please enter an integer value"' in response) 
     330        response = app.get("/failsafeformencode?bar=a&baz=b") 
     331        self.failUnless('"bar": 1' in response) 
     332        self.failUnless('"baz": 2' in response) 
     333        response = app.get("/failsafedefaults?bar=a&baz=b") 
     334        self.failUnless('"bar": 1' in response) 
     335        self.failUnless('"baz": 2' in response) 
  • turbogears/tests/test_sqlalchemy.py

    old new  
    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, \ 
    13     capture_log, print_log 
     12from turbogears.testutil import make_app, sqlalchemy_cleanup, \ 
     13    capture_log, print_log, start_server, stop_server 
    1414 
    1515 
    1616# Fixture 
     
    8181    mapper(Address, addresses_table, properties=dict( 
    8282        person=relation(Person, backref='addresses'))) 
    8383    mapper(Test, test_table) 
     84   
     85    start_server() 
    8486 
    8587def teardown_module(): 
    8688    fresh_metadata = get_metadata('fresh') 
     
    9193    if os.path.exists('freshtest.db'): 
    9294        os.unlink('freshtest.db') 
    9395 
     96    stop_server() 
    9497 
     98 
    9599# Database tests 
    96100 
    97101def test_query_in_session(): 
     
    135139        will be marked with this name :) 
    136140 
    137141        """ 
    138         cherrypy.response.code = 501 
    139142        msg = "KARL25 responding\n" 
    140143        msg += "user with id: '%s' should not be saved.\n" % id 
    141144        msg += "An exception occurred: %r (%s)" % ((tg_exceptions,)*2) 
     
    165168def test_implicit_trans_no_error(): 
    166169    """If a controller runs sucessfully, the transaction is commited.""" 
    167170    capture_log("turbogears.database") 
    168     cherrypy.root = MyRoot() 
    169     create_request("/no_error?name=A.%20Dent") 
    170     output = cherrypy.response.body[0] 
    171     print output 
     171    app = make_app(MyRoot) 
     172    response = app.get("/no_error?name=A.%20Dent") 
    172173    print_log() 
    173174    q = session.query(Person) 
    174175    arthur = q.filter_by(name="A. Dent").first() 
    175     assert 'someconfirmhandler' in output, \ 
     176    assert 'someconfirmhandler' in response, \ 
    176177        'The no error should have redirected to someconfirmhandler' 
    177178    assert arthur is not None, 'Person arthur should have been saved!' 
    178179    assert arthur.name == "A. Dent", 'Person arthur should be named "A. Dent"' 
     
    180181def test_raise_sa_exception(): 
    181182    """If a controller causes an SA exception, it is raised properly.""" 
    182183    capture_log("turbogears.database") 
    183     cherrypy.root = MyRoot() 
    184     create_request("/create_person?id=20") 
    185     output = cherrypy.response.body[0] 
     184    app = make_app(MyRoot) 
     185    response = app.get("/create_person?id=20") 
    186186    print_log() 
    187     print output 
    188     assert 'No exceptions occurred' in output 
    189     assert cherrypy.response.status.startswith("200") 
    190     create_request("/create_person?id=20") 
    191     output = cherrypy.response.body[0] 
    192     assert cherrypy.response.status.startswith("500") 
    193     print output 
    194     assert 'KARL25' not in output, \ 
     187    assert 'No exceptions occurred' in response 
     188    response = app.get("/create_person?id=20", status=500) 
     189    assert 'KARL25' not in response, \ 
    195190        'Exception should NOT have been handled by our handler' 
    196     assert 'DBAPIError' in output, \ 
     191    assert 'DBAPIError' in response, \ 
    197192        'The page should have displayed an SQLAlchemy exception' 
    198193 
    199194def test_user_exception(): 
    200195    """If a controller raises an exception, transactions are rolled back.""" 
    201196    capture_log("turbogears.database") 
    202     cherrypy.root = MyRoot() 
    203     create_request("/create_person?id=19&docom=0&doerr=1&name=Martin%20GAL") 
    204     output = cherrypy.response.body[0] 
     197    app = make_app(MyRoot) 
     198    response = app.get("/create_person?id=19&docom=0&doerr=1&name=Martin%20GAL") 
    205199    print_log() 
    206     print output 
    207     assert 'KARL25' in output, \ 
     200    assert 'KARL25' in response, \ 
    208201        'The exception handler should have answered us' 
    209202    p = session.query(Person).get(19) 
    210203    assert p is None, \ 
     
    212205 
    213206def test_user_redirect(): 
    214207    """If a controller redirects, transactions are committed.""" 
    215     cherrypy.root = MyRoot(
    216     create_request("/create_person?id=22&doerr=2") 
     208    app = make_app(MyRoot
     209    app.get("/create_person?id=22&doerr=2") 
    217210    assert session.query(Person).get(22) is not None, \ 
    218211        'The controller only redirected, the Person should have been saved' 
    219212 
    220213def test_cntrl_commit(): 
    221214    """It's safe to commit a transaction in the controller.""" 
    222     cherrypy.root = MyRoot(
    223     create_request("/create_person?id=23&docom=1") 
    224     assert 'InvalidRequestError' not in cherrypy.response.body[0] 
     215    app = make_app(MyRoot
     216    response = app.get("/create_person?id=23&docom=1") 
     217    assert 'InvalidRequestError' not in response 
    225218    assert session.query(Person).get(23) is not None, \ 
    226219        'The Person 23 should have been saved during commit inside controller' 
    227220 
    228221def test_cntrl_commit2(): 
    229222    """A commit inside the controller is not rolled back by the exception.""" 
    230     cherrypy.root = MyRoot(
    231     create_request("/create_person?id=24&docom=1&doerr=1") 
    232     assert 'InvalidRequestError' not in cherrypy.response.body[0] 
     223    app = make_app(MyRoot
     224    response = app.get("/create_person?id=24&docom=1&doerr=1") 
     225    assert 'InvalidRequestError' not in response 
    233226    assert session.query(Person).get(24) is not None, \ 
    234227        'The Person 24 should have been saved during commit' \ 
    235228        ' inside controller and not rolled back' 
    236229 
    237230def test_cntrl_flush(): 
    238231    """It's safe to flush in the controller.""" 
    239     cherrypy.root = MyRoot() 
    240     create_request("/create_person?id=25&doflush=1") 
    241     print cherrypy.response.body[0] 
    242     assert 'No exceptions occurred' in cherrypy.response.body[0] 
    243     create_request("/create_person?id=25&doflush=0") 
    244     assert cherrypy.response.status.startswith("500") 
    245     assert 'IntegrityError' in cherrypy.response.body[0] 
    246     create_request("/create_person?id=25&doflush=1") 
    247     assert cherrypy.response.status.startswith("200") 
    248     assert 'IntegrityError' in cherrypy.response.body[0] 
    249     create_request("/create_person?id=25&doflush=2") 
    250     assert cherrypy.response.status.startswith("200") 
    251     assert 'No exceptions occurred' in cherrypy.response.body[0] 
     232    app = make_app(MyRoot) 
     233    response = app.get("/create_person?id=25&doflush=1") 
     234    assert 'No exceptions occurred' in response 
     235    response = app.get("/create_person?id=25&doflush=0", status=500) 
     236    assert 'IntegrityError' in response 
     237    response = app.get("/create_person?id=25&doflush=1") 
     238    assert 'IntegrityError' in response 
     239    response = app.get("/create_person?id=25&doflush=2") 
     240    assert 'No exceptions occurred' in response 
    252241 
    253242 
    254243# Exception handling with rollback 
     
    301290    is created by the exception handler. 
    302291 
    303292    """ 
    304     cherrypy.root = RbRoot() 
    305     create_request('/doerr?id=26') 
    306     output = cherrypy.response.body[0] 
    307     print output 
    308     assert 'KARL27' in output, 'Exception handler should have answered' 
     293    app = make_app(RbRoot) 
     294    response = app.get('/doerr?id=26') 
     295    assert 'KARL27' in response, 'Exception handler should have answered' 
    309296    assert session.query(User).get(26) is None 
    310297    assert session.query(User).get(27) is not None 
    311298 
     
    316303    so user XX should not exist. 
    317304 
    318305    """ 
    319     cherrypy.root = RbRoot() 
    320     create_request('/doerr?id=XX') 
    321     output = cherrypy.response.body[0] 
    322     assert 'KARL27' in output, 'Exception handler should have answered' 
     306    app = make_app(RbRoot) 
     307    response = app.get('/doerr?id=XX') 
     308    assert 'KARL27' in response, 'Exception handler should have answered' 
    323309    assert session.query(User).get('XX') is None 
    324310 
    325311def test_exc_done_rollback(): 
    326312    """No problems with error handler if controller manually rollbacks.""" 
    327     cherrypy.root = RbRoot() 
    328     create_request('/doerr?id=28&dorb=1') 
    329     output = cherrypy.response.body[0] 
    330     assert 'KARL27' in output, 'Exception handler should have answered' 
     313    app = make_app(RbRoot) 
     314    response = app.get('/doerr?id=28&dorb=1') 
     315    assert 'KARL27' in response, 'Exception handler should have answered' 
    331316    assert session.query(User).get(28) is None 
    332317    assert session.query(User).get(29) is not None 
    333318 
     
    360345 
    361346    """ 
    362347    test_table.insert().execute(dict(id=1, val='a')) 
    363     cherrypy.root = FreshRoot() 
    364     create_request("/test1") 
    365     assert cherrypy.response.status.startswith("200") 
    366     assert 'AssertionError' not in cherrypy.response.body[0] 
     348    app = make_app(FreshRoot) 
     349    response = app.get("/test1", status = 200) 
     350    assert 'AssertionError' not in response 
    367351    # Call test2 in a different thread 
    368352    class ThreadB(threading.Thread): 
    369353        def run(self): 
    370             create_request("/test2") 
    371             assert cherrypy.response.status.startswith("200") 
    372             assert 'AssertionError' not in cherrypy.response.body[0] 
     354            response = app.get("/test2", status=200) 
     355            assert 'AssertionError' not in response 
    373356    thrdb = ThreadB() 
    374357    thrdb.start() 
    375358    thrdb.join() 
    376     create_request("/test3") 
    377     assert cherrypy.response.status.startswith("200") 
    378     assert 'AssertionError' not in cherrypy.response.body[0] 
     359    response = app.get("/test3", status=200) 
     360    assert 'AssertionError' not in response 
  • turbogears/tests/test_expose.py

    old new  
    1 import cherrypy 
    21import simplejson 
    3  
    42from turbogears import controllers, expose 
    5 from turbogears.testutil import create_request 
     3from turbogears.testutil import make_app, start_server, stop_server 
    64 
     5def setup_module(): 
     6    start_server() 
    77 
     8def teardown_module(): 
     9    stop_server() 
     10 
     11 
    812class ExposeRoot(controllers.RootController): 
    913 
    1014    @expose("turbogears.tests.simple") 
     
    2024 
    2125 
    2226def test_gettinghtml(): 
    23     cherrypy.root = ExposeRoot() 
    24     create_request("/with_json") 
    25     body = cherrypy.response.body[0] 
    26     assert "Paging all foo" in body 
     27    app = make_app(ExposeRoot) 
     28    response = app.get("/with_json") 
     29    assert "Paging all foo" in response 
    2730 
    2831def test_gettingjson(): 
    29     cherrypy.root = ExposeRoot() 
    30     create_request("/with_json?tg_format=json") 
    31     body = cherrypy.response.body[0] 
    32     assert '"title": "Foobar"' in body 
     32    app = make_app(ExposeRoot) 
     33    response = app.get("/with_json?tg_format=json") 
     34    assert '"title": "Foobar"' in response 
    3335 
    3436def test_gettingjsonviaaccept(): 
    35     cherrypy.root = ExposeRoot(
    36     create_request("/with_json_via_accept", 
     37    app = make_app(ExposeRoot
     38    response = app.get("/with_json_via_accept", 
    3739            headers=dict(Accept="text/javascript")) 
    38     body = cherrypy.response.body[0] 
    39     assert '"title": "Foobar"' in body 
     40    assert '"title": "Foobar"' in response 
    4041 
    4142def test_getting_json_with_accept_but_using_tg_format(): 
    42     cherrypy.root = ExposeRoot() 
    43     create_request("/with_json_via_accept?tg_format=json") 
    44     body = cherrypy.response.body[0] 
    45     assert '"title": "Foobar"' in body 
     43    app = make_app(ExposeRoot) 
     44    response = app.get("/with_json_via_accept?tg_format=json") 
     45    assert '"title": "Foobar"' in response 
    4646 
    4747def test_getting_plaintext(): 
    48     cherrypy.root = ExposeRoot(
    49     create_request("/with_json_via_accept", 
     48    app = make_app(ExposeRoot
     49    response = app.get("/with_json_via_accept", 
    5050        headers=dict(Accept="text/plain")) 
    51     print cherrypy.response.body[0] 
    52     assert cherrypy.response.body[0] == "This is a plain text for foo." 
     51    assert response.body == "This is a plain text for foo." 
    5352 
    5453def test_allow_json(): 
    5554 
     
    5857        def test(self): 
    5958            return dict(title="Foobar", mybool=False, someval="niggles") 
    6059 
    61     cherrypy.root = NewRoot() 
    62     create_request("/test", headers= dict(accept="text/javascript")) 
    63     body = cherrypy.response.body[0] 
    64     values = simplejson.loads(body) 
     60    app = make_app(NewRoot) 
     61    response = app.get("/test", headers= dict(accept="text/javascript")) 
     62    values = simplejson.loads(response.body) 
    6563    assert values == dict(title="Foobar", mybool=False, someval="niggles", 
    6664        tg_flash=None) 
    67     assert cherrypy.response.headers["Content-Type"] == "text/javascript" 
    68     create_request("/test?tg_format=json") 
    69     body = cherrypy.response.body[0] 
    70     values = simplejson.loads(body) 
     65    assert response.headers["Content-Type"] == "text/javascript" 
     66    response = app.get("/test?tg_format=json") 
     67    values = simplejson.loads(response.body) 
    7168    assert values == dict(title="Foobar", mybool=False, someval="niggles", 
    7269        tg_flash=None) 
    73     assert cherrypy.response.headers["Content-Type"] == "text/javascript" 
     70    assert response.headers["Content-Type"] == "text/javascript" 
  • turbogears/tests/test_controllers.py

    old new  
    11import unittest 
     2import simplejson 
    23import formencode 
    34import cherrypy 
    45import pkg_resources 
     
    1819 
    1920    @expose() 
    2021    def index(self): 
    21         pass 
     22        return dict() 
    2223 
    2324    def validation_error_handler(self, tg_source, tg_errors, *args, **kw): 
    24         self.functionname = tg_source.__name__ 
    25         self.values = kw 
    26         self.errors = tg_errors 
    27         return "Error Message" 
     25        errors = {} 
     26        for (key, value) in tg_errors.items(): 
     27           if hasattr(value, 'msg'): 
     28               errors[key] = value.msg 
     29           else: 
     30               errors[key] = value 
     31        return dict(msg = "Error Message", values = kw, errors = errors,  
     32                    functionname = tg_source.__name__) 
    2833 
     34 
    2935    @expose(html="turbogears.tests.simple", allow_json=True) 
    3036    def test(self): 
    3137        return dict(title="Foobar", mybool=False, someval="niggles") 
     
    3642 
    3743    @expose() 
    3844    def pos(self, posvalue): 
    39         self.posvalue = posvalue 
    40         return "" 
     45        return dict(posvalue = posvalue) 
    4146 
    4247    @expose() 
    4348    def servefile(self, tg_exceptions=None): 
     
    4853                "turbogears.tests", "test_controllers.py")) 
    4954 
    5055    @expose() 
    51     def unicode(self): 
    52         cherrypy.response.headers["Content-Type"] = "text/html" 
     56    def unicode(self, response=None): 
     57        if response is None: 
     58            response = cherrypy.response 
     59        response.headers["Content-Type"] = "text/html" 
    5360        return u'\u00bfHabla espa\u00f1ol?' 
    5461 
    5562    @expose() 
     
    8289    @validate(validators={'value': validators.StringBoolean()}) 
    8390    @error_handler(istrue) 
    8491    def errorchain(self, value): 
    85         return "No Error" 
     92        return {'error' : "No Error", 'value' : self.value} 
    8693 
    8794    @expose(format="json", html="turbogears.tests.simple") 
    8895    def returnjson(self): 
     
    117124        "lastname": validators.String()}) 
    118125    @error_handler(validation_error_handler) 
    119126    def save(self, submit, firstname, lastname="Miller"): 
    120         self.submit = submit 
    121         self.firstname = firstname 
    122         self.lastname = lastname 
    123         self.fullname = "%s %s" % (self.firstname, self.lastname) 
    124         return self.fullname 
     127        fullname = "%s %s" % (firstname, lastname) 
     128        return dict(firstname = firstname, lastname = lastname, 
     129            fullname = fullname, submit = submit) 
    125130 
     131 
    126132    class Registration(formencode.Schema): 
    127133        allow_extra_fields = True 
    128134        firstname = validators.String(min=2, not_empty=True) 
     
    171177    def flash_redirected(self): 
    172178        return dict(title="Foobar", mybool=False, someval="niggles") 
    173179 
     180    @expose() 
     181    def redirect(self): 
     182        redirect("/foo") 
     183 
     184    @expose() 
     185    def raise_redirect(self): 
     186        raise redirect("/foo") 
     187 
    174188    @expose(html="turbogears.tests.simple", allow_json=True) 
    175189    def flash_redirect_with_trouble_chars(self): 
    176190        flash(u"$foo, k\xe4se;\tbar!") 
     
    220234        return "redirected OK" 
    221235 
    222236 
    223 class TestRoot(unittest.TestCase): 
     237class TestRoot(testutil.TGWebTest): 
    224238 
    225239    def setUp(self): 
    226         cherrypy.root = None 
    227         cherrypy.tree.mount_points = {} 
    228         cherrypy.tree.mount(MyRoot(), "/") 
    229         cherrypy.tree.mount(SubApp(), "/subthing") 
     240        testutil.mount(MyRoot(), "/") 
     241        testutil.mount(SubApp(), "/subthing") 
     242        testutil.TGWebTest.setUp(self) 
    230243 
    231     def tearDown(self): 
    232         cherrypy.root = None 
    233         cherrypy.tree.mount_points = {} 
    234  
     244     
    235245    def test_js_files(self): 
    236246        """Can access the JavaScript files""" 
    237         testutil.create_request("/tg_js/MochiKit.js") 
    238         assert cherrypy.response.headers[ 
    239             "Content-Type"] == "application/x-javascript" 
    240         assert cherrypy.response.status == "200 OK" 
     247        response = self.app.get("/tg_js/MochiKit.js", status=200) 
     248        assert response.headers["Content-Type"] == "application/x-javascript" 
    241249 
    242250    def test_json_output(self): 
    243         testutil.create_request("/test?tg_format=json") 
    244         import simplejson 
    245         values = simplejson.loads(cherrypy.response.body[0]) 
     251        response = self.app.get("/test?tg_format=json") 
     252        values = simplejson.loads(response.body) 
    246253        assert values == dict(title="Foobar", mybool=False, 
    247254            someval="niggles", tg_flash=None) 
    248         assert cherrypy.response.headers["Content-Type"] == "text/javascript" 
     255        assert response.headers["Content-Type"] == "text/javascript" 
    249256 
    250257    def test_implied_json(self): 
    251         testutil.create_request("/impliedjson?tg_format=json") 
    252         assert '"title": "Blah"' in cherrypy.response.body[0] 
     258        response = self.app.get("/impliedjson?tg_format=json") 
     259        assert '"title": "Blah"' in response 
    253260 
    254261    def test_allow_json(self): 
    255         testutil.create_request("/allowjson?tg_format=json") 
    256         assert cherrypy.response.status.startswith("500") 
    257         assert cherrypy.response.headers["Content-Type"] == "text/html" 
     262        response = self.app.get("/allowjson?tg_format=json", status=500) 
     263        assert response.headers["Content-Type"] == "text/html" 
    258264 
    259265    def test_allow_json_config(self): 
    260266        """JSON output can be enabled via config.""" 
     
    264270            def allowjsonconfig(self): 
    265271                return dict(title="Foobar", mybool=False, someval="foo", 
    266272                     tg_html="turbogears.tests.simple") 
    267         cherrypy.root = JSONRoot(
    268         testutil.create_request('/allowjsonconfig?tg_format=json') 
    269         assert cherrypy.response.headers["Content-Type"] == "text/javascript" 
     273        app = testutil.make_app(JSONRoot
     274        response = app.get('/allowjsonconfig?tg_format=json') 
     275        assert response.headers["Content-Type"] == "text/javascript" 
    270276        config.update({'tg.allow_json': False}) 
    271277 
    272278    def test_allow_json_config_false(self): 
     
    277283            def allowjsonconfig(self): 
    278284                return dict(title="Foobar", mybool=False, someval="foo", 
    279285                     tg_html="turbogears.tests.simple") 
    280         cherrypy.root = JSONRoot() 
    281         testutil.create_request('/allowjsonconfig'
    282         assert cherrypy.response.status.startswith("200"
    283         testutil.create_request('/allowjsonconfig?tg_format=json') 
    284         assert cherrypy.response.status.startswith("500"
    285         assert cherrypy.response.headers["Content-Type"] == "text/html" 
     286        testutil.stop_server() 
     287        app = testutil.make_app(JSONRoot
     288        testutil.start_server(
     289        response = app.get('/allowjsonconfig') 
     290        response = app.get('/allowjsonconfig?tg_format=json', status=500
     291        assert response.headers["Content-Type"] == "text/html" 
    286292        config.update({'tg.allow_json': True}) 
    287293 
    288294    def test_json_error(self): 
    289295        """The error handler should return JSON if requested.""" 
    290         testutil.create_request("/jsonerror") 
    291         assert cherrypy.response.headers["Content-Type"] == "text/html; charset=utf-8" 
    292         assert "Paging all errors" in cherrypy.response.body[0] 
    293         testutil.create_request("/jsonerror?tg_format=json") 
    294         assert cherrypy.response.headers["Content-Type"] == "text/javascript" 
    295         assert '"someval": "errors"' in cherrypy.response.body[0] 
     296        response = self.app.get("/jsonerror") 
     297        assert response.headers["Content-Type"] == "text/html; charset=utf-8" 
     298        assert "Paging all errors" in response.body 
     299        response = self.app.get("/jsonerror?tg_format=json") 
     300        print "Headers", response.headers 
     301        assert response.headers["Content-Type"] == "text/javascript" 
     302        print response.body 
     303        assert '"someval": "errors"' in response.body 
    296304 
    297305    def test_invalid_return(self): 
    298         testutil.create_request("/invalid") 
    299         assert cherrypy.response.status.startswith("500") 
     306        response = self.app.get("/invalid", status=500) 
    300307 
    301308    def test_strict_parameters(self): 
    302309        config.update({"tg.strict_parameters": True}) 
    303         testutil.create_request( 
    304             "/save?submit=save&firstname=Foo&lastname=Bar&badparam=1") 
    305         assert cherrypy.response.status.startswith("500"
     310        response = self.app.get( 
     311            "/save?submit=save&firstname=Foo&lastname=Bar&badparam=1", 
     312            status=500
    306313        assert not hasattr(cherrypy.root, "errors") 
    307314 
    308315    def test_throw_out_random(self): 
    309316        """Can append random value to the URL to avoid caching problems.""" 
    310         testutil.create_request("/test?tg_random=1") 
    311         assert "Paging all niggles" in cherrypy.response.body[0] 
     317        response = self.app.get("/test?tg_random=1") 
     318        assert "Paging all niggles" in response 
    312319        config.update({"tg.strict_parameters": True}) 
    313         testutil.create_request("/test?tg_random=1") 
    314         assert cherrypy.response.status.startswith("200") 
    315         assert "Paging all niggles" in cherrypy.response.body[0] 
    316         testutil.create_request("/test?tg_not_random=1") 
    317         assert cherrypy.response.status.startswith("500") 
     320        response = self.app.get("/test?tg_random=1", status=200) 
     321        assert "Paging all niggles" in response 
     322        response = self.app.get("/test?tg_not_random=1", status=500) 
    318323        assert not hasattr(cherrypy.root, "errors") 
    319324 
    320325    def test_ignore_parameters(self): 
    321326        config.update({"tg.strict_parameters": True}) 
    322         testutil.create_request("/test?ignore_me=1") 
    323         assert cherrypy.response.status.startswith("500") 
     327        response = self.app.get("/test?ignore_me=1", status=500) 
    324328        assert not hasattr(cherrypy.root, "errors") 
    325329        config.update({"tg.ignore_parameters": ['ignore_me', 'me_too']}) 
    326         testutil.create_request("/test?ignore_me=1") 
    327         assert "Paging all niggles" in cherrypy.response.body[0] 
    328         testutil.create_request("/test?me_too=1") 
    329         assert cherrypy.response.status.startswith("200") 
    330         assert "Paging all niggles" in cherrypy.response.body[0] 
    331         testutil.create_request("/test?me_not=1") 
    332         assert cherrypy.response.status.startswith("500") 
     330        response = self.app.get("/test?ignore_me=1") 
     331        assert "Paging all niggles" in response 
     332        response = self.app.get("/test?me_too=1", status=200) 
     333        assert "Paging all niggles" in response 
     334        response = self.app.get("/test?me_not=1", status=500) 
    333335        assert not hasattr(cherrypy.root, "errors") 
    334336 
    335337    def test_retrieve_dict_directly(self): 
    336         d = testutil.call(cherrypy.root.returnjson
    337         assert d["title"] == "Foobar" 
     338        response = self.app.get('/returnjson'
     339        assert response.raw["title"] == "Foobar" 
    338340 
    339341    def test_templateOutput(self): 
    340         testutil.create_request("/test") 
    341         assert "Paging all niggles" in cherrypy.response.body[0] 
     342        response = self.app.get("/test") 
     343        assert "Paging all niggles" in response 
    342344 
    343345    def test_safari_unicode_fix(self): 
    344         testutil.create_request("/unicode", headers={'User-Agent': 
     346        response = self.app.get("/unicode", headers={'User-Agent': 
    345347            "Apple WebKit Safari/412.2"}) 
    346         firstline = cherrypy.response.body[0].split('\n')[0] 
     348        firstline = response.body.split('\n')[0] 
    347349        assert firstline == "&#xbf;Habla espa&#xf1;ol?" 
    348350        assert isinstance(firstline, str) 
    349351 
    350352    def test_default_format(self): 
    351353        """The default format can be set via expose""" 
    352         testutil.create_request("/returnjson") 
    353         firstline = cherrypy.response.body[0] 
    354         assert '"title": "Foobar"' in firstline 
    355         testutil.create_request("/returnjson?tg_format=html") 
    356         assert cherrypy.response.status.startswith("500") 
    357         firstline = cherrypy.response.body[0] 
    358         assert '"title": "Foobar"' not in firstline 
     354        response = self.app.get("/returnjson") 
     355        assert '"title": "Foobar"' in response 
     356        response = self.app.get("/returnjson?tg_format=html", status=500) 
    359357 
    360358    def test_content_type(self): 
    361359        """The content-type can be set via expose""" 
    362         testutil.create_request("/contenttype") 
    363         assert cherrypy.response.headers["Content-Type"] == "xml/atom" 
     360        response = self.app.get("/contenttype") 
     361        assert response.headers["Content-Type"] == "xml/atom" 
    364362 
    365363    def test_returned_template_name(self): 
    366         testutil.create_request("/returnedtemplate") 
    367         data = cherrypy.response.body[0].lower() 
     364        response = self.app.get("/returnedtemplate") 
     365        data = response.body.lower() 
    368366        assert "<body>" in data 
    369367        assert 'groovy test template' in data 
    370368 
    371369    def test_returned_template_short(self): 
    372         testutil.create_request("/returnedtemplate_short") 
    373         assert "Paging all foo" in cherrypy.response.body[0] 
     370        response = self.app.get("/returnedtemplate_short") 
     371        assert "Paging all foo" in response 
    374372 
    375373    def test_expose_template_short(self): 
    376         testutil.create_request("/exposetemplate_short") 
    377         assert "Paging all foo" in cherrypy.response.body[0] 
     374        response = self.app.get("/exposetemplate_short") 
     375        assert "Paging all foo" in response 
    378376 
    379377    def test_validation(self): 
    380378        """Data can be converted and validated""" 
    381         testutil.create_request("/istrue?value=true") 
    382         assert cherrypy.root.value is True 
    383         testutil.create_request("/istrue?value=false") 
    384         assert cherrypy.root.value is False 
    385         cherrypy.root = MyRoot() 
    386         testutil.create_request("/istrue?value=foo") 
    387         assert not hasattr(cherrypy.root, "value") 
    388         assert cherrypy.root.functionname == "istrue" 
    389         testutil.create_request("/save?submit=send&firstname=John&lastname=Doe") 
    390         assert cherrypy.root.fullname == "John Doe" 
    391         assert cherrypy.root.submit == "send" 
    392         testutil.create_request("/save?submit=send&firstname=Arthur") 
    393         assert cherrypy.root.fullname == "Arthur Miller" 
    394         testutil.create_request("/save?submit=send&firstname=Arthur&lastname=") 
    395         assert cherrypy.root.fullname == "Arthur " 
    396         testutil.create_request("/save?submit=send&firstname=D&lastname=") 
    397         assert len(cherrypy.root.errors) == 1 
    398         assert cherrypy.root.errors.has_key("firstname") 
    399         assert "characters" in cherrypy.root.errors["firstname"].msg.lower() 
    400         testutil.create_request("/save?submit=send&firstname=&lastname=") 
    401         assert len(cherrypy.root.errors) == 1 
    402         assert cherrypy.root.errors.has_key("firstname") 
     379        response = self.app.get("/istrue?value=true") 
     380        assert response.body == 'True' 
     381        response = self.app.get("/istrue?value=false") 
     382        assert response.body == 'False' 
    403383 
     384        app = testutil.make_app(MyRoot) 
     385        response = app.get("/istrue?value=foo") 
     386        assert response.raw['msg'] == 'Error Message' 
     387 
     388        response = app.get("/save?submit=send&firstname=John&lastname=Doe") 
     389        assert response.raw['fullname'] == "John Doe" 
     390        assert response.raw['submit'] == "send" 
     391        response = app.get("/save?submit=send&firstname=Arthur") 
     392        assert response.raw['fullname'] == "Arthur Miller" 
     393        response = app.get("/save?submit=send&firstname=Arthur&lastname=") 
     394        assert response.raw['fullname'] == "Arthur " 
     395        response = app.get("/save?submit=send&firstname=D&lastname=") 
     396        assert len(response.raw['errors'].keys()) == 1 
     397        assert response.raw['errors'].has_key("firstname") 
     398        assert "characters" in response.raw['errors']["firstname"].lower() 
     399        response = app.get("/save?submit=send&firstname=&lastname=") 
     400        assert len(response.raw['errors'].keys()) == 1 
     401        assert response.raw['errors'].has_key("firstname") 
     402 
    404403    def test_validation_chained(self): 
    405404        """Validation is not repeated if it already happened""" 
    406405        cherrypy.root.value = None 
    407         testutil.create_request("/errorchain?value=true") 
     406        response = self.app.get("/errorchain?value=true") 
    408407        assert cherrypy.root.value is None 
    409         testutil.create_request("/errorchain?value=notbool") 
     408        assert response.raw['value'] is None 
     409        self.app.get("/errorchain?value=notbool") 
    410410        assert cherrypy.root.value == 'notbool' 
     411        assert 'No Error' in response.body 
     412        assert response.raw['value'] is None 
    411413 
    412414    def test_validation_nested(self): 
    413415        """Validation is not repeated in nested method call""" 
    414416        cherrypy.root.value = None 
    415         testutil.create_request("/nestedcall?value=true") 
     417        response = self.app.get("/nestedcall?value=true") 
    416418        assert cherrypy.root.value == 'True' 
    417         testutil.create_request("/nestedcall?value=false") 
     419        self.app.get("/nestedcall?value=false") 
    418420        assert cherrypy.root.value == 'False' 
    419421 
    420422    def test_validation_with_schema(self): 
    421423        """Data can be converted/validated with formencode.Schema instance""" 
    422         testutil.create_request("/save2?submit=send&firstname=Joe&lastname=Doe") 
    423         assert cherrypy.root.fullname == "Joe Doe" 
    424         assert cherrypy.root.submit == "send" 
    425         testutil.create_request("/save2?submit=send&firstname=Arthur&lastname=") 
    426         assert cherrypy.root.fullname == "Arthur " 
    427         testutil.create_request("/save2?submit=send&firstname=&lastname=") 
    428         assert len(cherrypy.root.errors) == 1 
    429         assert cherrypy.root.errors.has_key("firstname") 
    430         testutil.create_request("/save2?submit=send&firstname=D&lastname=") 
    431         assert len(cherrypy.root.errors) == 1 
    432         assert cherrypy.root.errors.has_key("firstname") 
     424        response = self.app.get("/save2?submit=send&firstname=Joe&lastname=Doe") 
     425        assert response.raw['fullname'] == "Joe Doe" 
     426        assert response.raw['submit'] == "send" 
     427        response = self.app.get("/save2?submit=send&firstname=Arthur&lastname=") 
     428        assert response.raw['fullname'] == "Arthur " 
     429        response = self.app.get("/save2?submit=send&firstname=&lastname=") 
     430        assert len(response.raw['errors']) == 1 
     431        assert response.raw['errors'].has_key("firstname") 
     432        response = self.app.get("/save2?submit=send&firstname=D&lastname=") 
     433        assert len(response.raw['errors']) == 1 
     434        assert response.raw['errors'].has_key("firstname") 
    433435 
    434436    def test_other_template(self): 
    435437        """'tg_html' in a returned dict will use the template specified there""" 
    436         testutil.create_request("/useother") 
    437         assert "This is the other template" in cherrypy.response.body[0] 
     438        response = self.app.get("/useother") 
     439        assert "This is the other template" in response 
    438440 
    439441    def test_cheetah_template(self): 
    440442        """Cheetah templates can be used as well""" 
    441         testutil.create_request("/usecheetah") 
    442         body = cherrypy.response.body[0] 
    443         assert "This is the Cheetah test template." in body 
    444         assert "Paging all chimps." in body 
     443        response = self.app.get("/usecheetah") 
     444        assert "This is the Cheetah test template." in response 
     445        assert "Paging all chimps." in response 
    445446 
    446447    def test_run_with_trans(self): 
    447448        """run_with_transaction is called only on topmost exposed method""" 
    448449        oldrwt = database.run_with_transaction 
    449450        database.run_with_transaction = cherrypy.root.rwt 
    450         testutil.create_request("/nestedcall?value=true") 
     451        self.app.get("/nestedcall?value=true") 
    451452        database.run_with_transaction = oldrwt 
    452453        assert cherrypy.root.value 
    453454        assert cherrypy.root.rwt_called == 1 
    454455 
    455456    def test_positional(self): 
    456457        """Positional parameters should work""" 
    457         testutil.create_request("/pos/foo") 
    458         assert cherrypy.root.posvalue == "foo" 
     458        response = self.app.get("/pos/foo") 
     459        assert response.raw['posvalue'] == "foo" 
    459460 
    460461    def test_flash_plain(self): 
    461462        """flash with strings should work""" 
    462         testutil.create_request("/flash_plain?tg_format=json") 
    463         import simplejson 
    464         values = simplejson.loads(cherrypy.response.body[0]) 
     463        response = self.app.get("/flash_plain?tg_format=json") 
     464        values = simplejson.loads(response.body) 
    465465        assert values["tg_flash"] == "plain" 
    466         assert not cherrypy.response.simple_cookie.has_key("tg_flash") 
     466        assert not response.headers.has_key("tg_flash") 
    467467 
    468468    def test_flash_unicode(self): 
    469469        """flash with unicode objects should work""" 
    470         testutil.create_request("/flash_unicode?tg_format=json") 
    471         import simplejson 
    472         values = simplejson.loads(cherrypy.response.body[0]) 
     470        response = self.app.get("/flash_unicode?tg_format=json") 
     471        values = simplejson.loads(response.body) 
    473472        assert values["tg_flash"] == u"\xfcnicode" 
    474         assert not cherrypy.response.simple_cookie.has_key("tg_flash") 
     473        assert not response.headers.has_key("tg_flash") 
    475474 
    476475    def test_flash_on_redirect(self): 
    477476        """flash must survive a redirect""" 
    478         testutil.create_request("/flash_redirect?tg_format=json") 
    479         assert cherrypy.response.status.startswith("302") 
    480         testutil.create_request(cherrypy.response.headers["Location"], 
    481             headers=dict(Cookie=cherrypy.response.simple_cookie.output( 
    482                 header="").strip())) 
    483         import simplejson 
    484         values = simplejson.loads(cherrypy.response.body[0]) 
     477        response = self.app.get("/flash_redirect?tg_format=json", status=302) 
     478        response = self.app.get(response.location, 
     479            headers=dict(Cookie=response.headers['Set-Cookie'])) 
     480        values = simplejson.loads(response.body) 
    485481        assert values["tg_flash"] == u"redirect \xfcnicode" 
    486482 
    487483    def test_flash_redirect_with_trouble_chars(self): 
    488484        """flash redirect with chars that can cause troubles in cookies""" 
    489         testutil.create_request("/flash_redirect_with_trouble_chars?tg_format=json") 
    490         assert cherrypy.response.status.startswith("302") 
    491         value = cherrypy.response.simple_cookie["tg_flash"].value 
    492         assert '$' not in value 
    493         assert ',' not in value and ';' not in value 
    494         assert ' ' not in value and '\t' not in value 
    495         assert 'foo' in value and 'bar' in value 
    496         assert u'k\xe4se'.encode('utf-8') in value 
    497         assert '!' in value 
    498         testutil.create_request(cherrypy.response.headers["Location"], 
    499             headers=dict(Cookie=cherrypy.response.simple_cookie.output( 
    500                 header="").strip())) 
    501         import simplejson 
    502         values = simplejson.loads(cherrypy.response.body[0]) 
     485        response = self.app.get("/flash_redirect_with_trouble_chars?tg_format=json", status=302) 
     486        response = self.app.get(response.location, 
     487                                headers=dict(Cookie=response.headers['Set-Cookie'])) 
     488        values = simplejson.loads(response.body) 
    503489        assert values["tg_flash"] == u"$foo, k\xe4se;\tbar!" 
    504490 
    505491    def test_double_flash(self): 
     
    507493        # Here we are calling method that sets a flash message. However flash 
    508494        # cookie is still there. Turbogears should discard old flash message 
    509495        # from cookie and use new one, set by flash_plain(). 
    510         testutil.create_request("/flash_plain?tg_format=json", 
     496        response = self.app.get("/flash_plain?tg_format=json", 
    511497            headers=dict(Cookie='tg_flash="old flash"; Path=/;')) 
    512         import simplejson 
    513         values = simplejson.loads(cherrypy.response.body[0]) 
     498        values = simplejson.loads(response.body) 
    514499        assert values["tg_flash"] == "plain" 
    515         assert cherrypy.response.simple_cookie.has_key("tg_flash"), \ 
     500        assert response.cookies_set.has_key("tg_flash"), \ 
    516501                "Cookie clearing request should be present" 
    517         flashcookie = cherrypy.response.simple_cookie['tg_flash'] 
    518         assert flashcookie['expires'] == 0 
    519502 
    520503    def test_set_kid_outputformat_in_config(self): 
    521504        """the outputformat for kid can be set in the config""" 
    522505        config.update({'kid.outputformat': 'xhtml'}) 
    523         testutil.create_request('/test') 
    524         response = cherrypy.response.body[0] 
     506        response = self.app.get('/test') 
    525507        assert '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML ' in response 
    526508        config.update({'kid.outputformat': 'html'}) 
    527         testutil.create_request('/test') 
    528         response = cherrypy.response.body[0] 
     509        response = self.app.get('/test') 
    529510        assert  '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML ' in response 
    530511        assert '    This is the groovy test ' in response 
    531512        config.update({'kid.outputformat': 'html compact'}) 
    532         testutil.create_request('/test') 
    533         response = cherrypy.response.body[0] 
     513        response = self.app.get('/test') 
    534514        assert  '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML ' in response 
    535515        assert 'This is the groovy test ' in response 
    536516        assert '    ' not in response 
     
    538518    def test_fileserving(self): 
    539519        #outputcap = StringIO() 
    540520        #sys.stdout = outputcap 
    541         testutil.create_request("/servefile") 
     521        response = self.app.get("/servefile") 
    542522        assert cherrypy.root.servedit 
    543523        assert not cherrypy.root.serve_exceptions 
    544524        #assert "AssertionError" not in outputcap.getvalue() 
    545525 
    546526    def test_internal_redirect(self): 
    547527        """regression test for #1022, #1407 and #1598""" 
    548         testutil.create_request("/internal_redirect") 
    549         firstline = cherrypy.response.body[0] 
    550         assert "redirected OK" in firstline 
     528        response = self.app.get("/internal_redirect") 
     529        assert "redirected OK" in response 
    551530 
    552531    def test_internal_redirect_nested_variables(self): 
    553532        """regression test for #1022, #1407 and #1598""" 
    554         testutil.create_request( 
     533        response = self.app.get( 
    555534            "/internal_redirect?a=1&a-1.b=2&a-2.c=3&a-2.c-1=4") 
    556         firstline = cherrypy.response.body[0] 
    557         assert "redirected OK" in firstline 
     535        assert "redirected OK" in response 
    558536 
    559537    def test_exc_value(self): 
    560538        """Exception is handled gracefully by the right exception handler.""" 
    561         testutil.create_request("/raise_value_exc") 
    562         assert 'handling_value' in cherrypy.response.body[0] 
     539        response = self.app.get("/raise_value_exc") 
     540        assert 'handling_value' in response 
    563541 
    564542    def test_exc_index(self): 
    565543        """Exception is handled gracefully by the right exception handler.""" 
    566         testutil.create_request("/raise_index_exc") 
    567         assert 'handling_index' in cherrypy.response.body[0] 
     544        response = self.app.get("/raise_index_exc") 
     545        assert 'handling_index' in response 
    568546 
    569547    def test_exc_all(self): 
    570548        """Test a controller that is protected by multiple exception handlers. 
     
    573551        by their respective handlers without problem... 
    574552 
    575553        """ 
    576         testutil.create_request("/raise_all_exc?num=1") 
    577         assert 'handling_value' in cherrypy.response.body[0] 
    578         testutil.create_request("/raise_all_exc?num=2") 
    579         assert 'handling_index' in cherrypy.response.body[0] 
    580         testutil.create_request("/raise_all_exc?num=3") 
    581         assert 'handling_key' in cherrypy.response.body[0] 
     554        response = self.app.get("/raise_all_exc?num=1") 
     555        assert 'handling_value' in response 
     556        response = self.app.get("/raise_all_exc?num=2") 
     557        assert 'handling_index' in response 
     558        response = self.app.get("/raise_all_exc?num=3") 
     559        assert 'handling_key' in response 
    582560 
    583561 
    584 class TestURLs(unittest.TestCase): 
     562class TestURLs(testutil.TGWebTest): 
    585563 
    586564    def setUp(self): 
    587         cherrypy.tree.mount_points = {} 
    588         cherrypy.root = MyRoot(
    589         cherrypy.root.subthing = SubApp(
    590         cherrypy.root.subthing.subsubthing = SubApp(
     565        testutil.TGWebTest.setUp(self) 
     566        testutil.mount(MyRoot()
     567        testutil.mount(SubApp(), '/subthing'
     568        testutil.mount(SubApp(), '/subthing/subsubthing'
    591569 
    592570    def test_basic_urls(self): 
    593         testutil.create_request("/") 
     571        self.app.get("/") 
    594572        assert "/foo" == url("/foo") 
    595573        assert "foo/bar" == url(["foo", "bar"]) 
    596574        assert url("/foo", bar=1, baz=2) in \ 
     
    604582        assert url("/foo") == "/foo" 
    605583 
    606584    def test_approots(self): 
    607         testutil.create_request("/subthing/") 
     585        config.update({"server.webpath": "/subthing"}) 
     586        self.app.get("/subthing/") 
    608587        assert url("foo") == "foo" 
    609588        assert url("/foo") == "/subthing/foo" 
    610589 
    611590    def test_lower_approots(self): 
    612         testutil.create_request("/subthing/subsubthing/") 
     591        config.update({"server.webpath": "/subthing/subsubthing"}) 
     592        self.app.get("/subthing/subsubthing/") 
    613593        assert url("/foo") == "/subthing/subsubthing/foo" 
    614594 
    615     def test_approots_With_path(self): 
    616         config.update({"server.webpath": "/coolsite/root"}) 
    617         startup.startTurboGears() 
    618         testutil.create_request("/coolsite/root/subthing/") 
     595    def test_approots_with_path(self): 
     596        config.update({"server.webpath": "/coolsite/root/subthing"}) 
     597        self.app.get("/subthing/") 
    619598        assert url("/foo") == "/coolsite/root/subthing/foo" 
    620599 
    621600    def test_redirect(self): 
    622601        config.update({"server.webpath": "/coolsite/root"}) 
    623         startup.startTurboGears() 
    624         testutil.create_request("/coolsite/root/subthing/") 
    625         try: 
    626             redirect("/foo") 
    627             assert False, "redirect exception should have been raised" 
    628         except cherrypy.HTTPRedirect, e: 
    629             assert "http://localhost/coolsite/root/subthing/foo" in e.urls 
    630         try: 
    631             raise redirect("/foo") 
    632             assert False, "redirect exception should have been raised" 
    633         except cherrypy.HTTPRedirect, e: 
    634             assert "http://localhost/coolsite/root/subthing/foo" in e.urls 
     602        response = self.app.get("/redirect") 
     603        assert response.location == 'http://localhost:80/coolsite/root/foo' 
     604        self.app.get("/raise_redirect") 
     605        assert response.location == 'http://localhost:80/coolsite/root/foo' 
    635606 
    636607    def test_multi_values(self): 
    637         testutil.create_request("/") 
     608        self.app.get("/") 
    638609        assert url("/foo", bar=[1, 2]) in \ 
    639610            ["/foo?bar=1&bar=2", "/foo?bar=2&bar=1"] 
    640611        assert url("/foo", bar=("asdf", "qwer")) in \ 
     
    642613 
    643614    def test_unicode(self): 
    644615        """url() can handle unicode parameters""" 
    645         testutil.create_request("/") 
     616        self.app.get("/") 
    646617        assert url('/', x=u'\N{LATIN SMALL LETTER A WITH GRAVE}' 
    647618            u'\N{LATIN SMALL LETTER E WITH GRAVE}' 
    648619            u'\N{LATIN SMALL LETTER I WITH GRAVE}' 
     
    652623 
    653624    def test_list(self): 
    654625        """url() can handle list parameters, with unicode too""" 
    655         testutil.create_request("/") 
     626        self.app.get("/") 
    656627        assert url('/', foo=['bar', u'\N{LATIN SMALL LETTER A WITH GRAVE}'] 
    657628            ) == '/?foo=bar&foo=%C3%A0' 
    658629 
    659630    def tearDown(self): 
     631        testutil.TGWebTest.tearDown(self) 
    660632        config.update({"server.webpath": ""}) 
    661         startup.startTurboGears() 
    662633 
    663634 
    664 def test_index_trailing_slash(): 
    665     """If there is no trailing slash on an index method call, redirect""" 
    666     cherrypy.root = SubApp() 
    667     cherrypy.root.foo = SubApp() 
    668     testutil.create_request("/foo") 
    669     assert cherrypy.response.status.startswith("302") 
     635    def test_index_trailing_slash(self): 
     636        """If there is no trailing slash on an index method call, redirect""" 
     637        testutil.mount(SubApp(), '/') 
     638        testutil.mount(SubApp(), '/foo') 
     639        self.app.get("/foo", status=302) 
    670640 
    671 def test_can_use_internally_defined_arguments(): 
    672     """Can use argument names that are internally used by TG in controllers""" 
     641    def test_can_use_internally_defined_arguments(self): 
     642        """Can use argument names that are internally used by TG in controllers""" 
    673643 
    674     class App(controllers.RootController): 
     644        class App(controllers.RootController): 
    675645 
    676         @expose() 
    677         def index(self, **kw): 
    678             return "\n".join(["%s:%s" % i for i in kw.iteritems()]) 
     646            @expose() 
     647            def index(self, **kw): 
     648                return "\n".join(["%s:%s" % i for i in kw.iteritems()]) 
    679649 
    680     cherrypy.root = App() 
    681     testutil.create_request("/?format=foo&template=bar&fragment=boo") 
    682     output = cherrypy.response.body[0] 
    683     assert "format:foo" in output 
    684     assert "template:bar" in output 
    685     assert "fragment:boo" in output 
     650        testutil.mount(App(), '/') 
     651        response = self.app.get("/?format=foo&template=bar&fragment=boo") 
     652        assert "format:foo" in response 
     653        assert "template:bar" in response 
     654        assert "fragment:boo" in response 
    686655 
    687 def test_url_kwargs_overwrite_tgparams(): 
    688     """Check keys in tgparams in call to url overwrite kw args""" 
    689     params = {'spamm': 'eggs'} 
    690     assert 'spamm=ham' in url('/foo', params, spamm='ham') 
     656    def test_url_kwargs_overwrite_tgparams(self): 
     657        """Check keys in tgparams in call to url overwrite kw args""" 
     658        params = {'spamm': 'eggs'} 
     659        assert 'spamm=ham' in url('/foo', params, spamm='ham') 
    691660 
    692 def test_url_doesnt_change_tgparams(): 
    693     """Test that url() does not change the dict passed as second arg""" 
    694     params = {'spamm': 'eggs'} 
    695     assert 'foo' in url('/foo', params, spamm='ham') 
    696     assert params['spamm'] == 'eggs' 
     661    def test_url_doesnt_change_tgparams(self): 
     662        """Test that url() does not change the dict passed as second arg""" 
     663        params = {'spamm': 'eggs'} 
     664        assert 'foo' in url('/foo', params, spamm='ham') 
     665        assert params['spamm'] == 'eggs' 
  • turbogears/tests/test_view.py

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

    old new  
    44from turbogears import controllers 
    55from turbogears import testutil 
    66 
     7def setup_module(): 
     8    testutil.unmount() 
     9    testutil.mount(MyRoot()) 
     10    testutil.start_server() 
     11 
     12def teardown_module(): 
     13    testutil.unmount() 
     14    testutil.stop_server() 
     15 
    716class MyRoot(controllers.RootController): 
    817    def set_name(self, name): 
    918        cookies = cherrypy.response.simple_cookie 
     
    2130 
    2231 
    2332def test_browser_session(): 
    24     cherrypy.root = MyRoot() 
    2533    bs = testutil.BrowsingSession() 
    2634    bs.goto('/get_name') 
    2735    assert bs.response == 'cookie not found' 
     
    3038    assert bs.response == 'me' 
    3139 
    3240def test_browser_session_for_two_users(): 
    33     cherrypy.root = MyRoot() 
    3441    bs1 = testutil.BrowsingSession() 
    3542    bs2 = testutil.BrowsingSession() 
    3643    bs1.goto('/set_name?name=bs1') 
  • turbogears/tests/test_catwalk.py

    old new  
    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 
     
    4039        pass 
    4140    index = turbogears.expose()(index) 
    4241 
     42 
     43def setup_module(): 
     44    #testutil.unmount() 
     45    testutil.mount(MyRoot(), "/") 
     46    testutil.mount(CatWalk(browse), '/catwalk') 
     47    testutil.start_server() 
     48 
     49def teardown_module(): 
     50    #testutil.unmount() 
     51    testutil.stop_server() 
     52 
     53 
     54#app = testutil.make_app() 
     55 
    4356class Browse(unittest.TestCase): 
    4457    def setUp(self): 
    4558        browse_data(browse) 
    46         cherrypy.root = MyRoot() 
     59        self.app = testutil.make_app() 
     60        #testutil.start_server() 
     61        #testutil.mount(MyRoot(), "/") 
     62        #testutil.mount(CatWalk(browse), '/catwalk') 
    4763 
     64    def tearDown(self): 
     65        #testutil.stop_server() 
     66        pass 
     67 
    4868    def test_wrong_filter_format(self): 
    49         cherrypy.root.catwalk = CatWalk(browse) 
    50         testutil.create_request("/catwalk/browse/?object_name=Song&filters=Guantanemera&tg_format=json") 
    51         response = cherrypy.response.body[0] 
     69        response = self.app.get("/catwalk/browse/?object_name=Song&filters=Guantanemera&tg_format=json") 
    5270        assert 'filter_format_error' in response 
    5371 
    5472    def test_wrong_filter_column(self): 
    55         cherrypy.root.catwalk = CatWalk(browse) 
    56         testutil.create_request("/catwalk/browse/?object_name=Song&filters=guacamole:2&tg_format=json") 
    57         response = cherrypy.response.body[0] 
     73        response = self.app.get("/catwalk/browse/?object_name=Song&filters=guacamole:2&tg_format=json") 
    5874        assert 'filter_column_error' in response 
    5975 
    6076    def test_filters(self): 
    61         cherrypy.root.catwalk = CatWalk(browse) 
    62         testutil.create_request("/catwalk/browse/?object_name=Song&tg_format=json") 
    63         response = cherrypy.response.body[0] 
    64         values = simplejson.loads(response) 
     77        response = self.app.get("/catwalk/browse/?object_name=Song&tg_format=json") 
     78        values = simplejson.loads(response.body) 
    6579        assert values['total'] == 15 * 15 * 15 #without the filters we get all songs (3375) 
    66         testutil.create_request("/catwalk/browse/?object_name=Song&filters=album:1&tg_format=json") 
    67         response = cherrypy.response.body[0] 
    68         values = simplejson.loads(response) 
     80        response = self.app.get("/catwalk/browse/?object_name=Song&filters=album:1&tg_format=json") 
     81        #values = simplejson.loads(response.body) 
     82        response.headers['Content-Type'] = 'application/json' 
     83        values = response.json 
    6984        assert values['total'] == 15 #filter by album id (only 15 songs) 
    7085 
    7186    def test_response_fields(self): 
    7287        #Check that the response contains the expected keys 
    73         cherrypy.root.catwalk = CatWalk(browse) 
    74         testutil.create_request("/catwalk/browse/?object_name=Artist&start=3&page_size=20&tg_format=json") 
    75         response = cherrypy.response.body[0] 
    76         values = simplejson.loads(response) 
     88        response = self.app.get("/catwalk/browse/?object_name=Artist&start=3&page_size=20&tg_format=json") 
     89        values = simplejson.loads(response.body) 
    7790        assert values.has_key('headers') 
    7891        assert values.has_key('rows') 
    7992        assert values.has_key('start') 
     
    8699    def test_rows_joins_count(self): 
    87100        #Control that the count for related and multiple joins match 
    88101        #the number of related instances when accessed as a field 
    89         cherrypy.root.catwalk = CatWalk(browse) 
    90         testutil.create_request("/catwalk/browse/?object_name=Artist&tg_format=json") 
    91         response = cherrypy.response.body[0] 
    92         values = simplejson.loads(response) 
     102        response = self.app.get("/catwalk/browse/?object_name=Artist&tg_format=json") 
     103        values = simplejson.loads(response.body) 
    93104        artist = browse.Artist.get(1) 
    94105        assert int(values['rows'][0]['genres']) == len(list(artist.genres)) 
    95106        assert int(values['rows'][0]['albums']) == len(list(artist.albums)) 
    96107 
    97108    def test_rows_column_number(self): 
    98109        #Control that the number of columns match the number of fields in the model 
    99         cherrypy.root.catwalk = CatWalk(browse) 
    100         testutil.create_request("/catwalk/browse/?object_name=Artist&tg_format=json") 
    101         response = cherrypy.response.body[0] 
    102         values = simplejson.loads(response) 
     110        response = self.app.get("/catwalk/browse/?object_name=Artist&tg_format=json") 
     111        values = simplejson.loads(response.body) 
    103112        assert len(values['rows'][0]) == 4 
    104113 
    105114    def test_rows_limit(self): 
    106115        #Update the limit of rows for the query and control the number of rows returned 
    107         cherrypy.root.catwalk = CatWalk(browse) 
    108         testutil.create_request("/catwalk/browse/?object_name=Artist&tg_format=json") 
    109         response = cherrypy.response.body[0] 
    110         values = simplejson.loads(response) 
     116        response = self.app.get("/catwalk/browse/?object_name=Artist&tg_format=json") 
     117        values = simplejson.loads(response.body) 
    111118        assert values.has_key('rows') 
    112119        assert len(values['rows']) == 10 
    113         testutil.create_request("/catwalk/browse/?object_name=Artist&page_size=15&tg_format=json") 
    114         response = cherrypy.response.body[0] 
    115         values = simplejson.loads(response
     120 
     121        response = self.app.get("/catwalk/browse/?object_name=Artist&page_size=15&tg_format=json") 
     122        values = simplejson.loads(response.body
    116123        assert values.has_key('rows') 
    117124        assert len(values['rows']) == 15 
    118125 
    119126    def test_header_labels(self): 
    120127        #Check that the returned header labels match the the model 
    121         cherrypy.root.catwalk = CatWalk(browse) 
    122         testutil.create_request("/catwalk/browse/?object_name=Artist&tg_format=json") 
    123         response = cherrypy.response.body[0] 
    124         values = simplejson.loads(response) 
     128        response = self.app.get("/catwalk/browse/?object_name=Artist&tg_format=json") 
     129        values = simplejson.loads(response.body) 
    125130        assert len(values['headers']) == 5 
    126131        for header in values['headers']: 
    127132            assert header['name'] in ['id','name','albums','genres', 'plays_instruments'] 
     
    131136    model = browse 
    132137 
    133138    def setUp(self): 
    134         cherrypy.root = MyRoot() 
    135         cherrypy.root.catwalk = CatWalk(browse) 
     139        #testutil.start_server() 
     140        testutil.mount(MyRoot(), "/") 
     141        testutil.mount(CatWalk(browse), '/catwalk') 
    136142        testutil.DBTest.setUp(self) 
    137143        browse_data(browse) 
     144        self.app = testutil.make_app() 
    138145 
     146    def tearDown(self): 
     147        #testutil.stop_server() 
     148        testutil.DBTest.tearDown(self) 
     149 
    139150    def test_addremove_related_joins(self): 
    140151        # check the update_join function when nondefault add/remove are used 
    141152        artist = self.model.Artist.get(1) 
    142153        assert len(artist.plays_instruments) == 0 
    143         testutil.create_request("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1%2C2&tg_format=json") 
     154        self.app.get("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1%2C2&tg_format=json") 
    144155        assert len(artist.plays_instruments) == 2 
    145         testutil.create_request("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1&tg_format=json") 
     156        self.app.get("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1&tg_format=json") 
    146157        assert len(artist.plays_instruments) == 1, str(artist.plays_instruments) 
  • turbogears/tests/test_paginate.py

    old new  
    44from urllib import quote 
    55import warnings 
    66 
    7 from turbogears import config, expose, database 
     7from turbogears import config, expose, database, testutil 
    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 sqlalchemy_cleanup 
    1212from turbojson.jsonify import jsonify 
    1313 
    1414import cherrypy 
     
    183183    return result 
    184184 
    185185 
    186 class TestSpy(unittest.TestCase): 
     186class TestSpy(testutil.TGWebTest): 
    187187    """Never trust a spy""" 
    188188 
    189189    class MyRoot(RootController): 
     
    218218 
    219219 
    220220    def setUp(self): 
    221         cherrypy.root = self.MyRoot() 
     221        testutil.TGWebTest.setUp(self) 
     222        self.app = testutil.make_app(self.MyRoot) 
    222223 
    223224    def test_spy(self): 
    224         create_request('/spy') 
    225         body = cherrypy.response.body[0] 
    226         Spy.assert_ok(body, 'current_page', 1) 
     225        response = self.app.get('/spy') 
     226        Spy.assert_ok(response.body, 'current_page', 1) 
    227227        try: 
    228             Spy.assert_ok(body, 'current_page', 2) 
     228            Spy.assert_ok(response.body, 'current_page', 2) 
    229229            raise Exception("above test should have failed") 
    230230        except AssertionError: 
    231231            pass 
    232232 
    233233    def test_correct_expectation(self): 
    234         create_request('/spy_correct_expectation') 
    235         body = cherrypy.response.body[0] 
    236         assert "ok: [paginate" in body 
     234        response = self.app.get('/spy_correct_expectation') 
     235        assert "ok: [paginate" in response 
    237236 
    238237    def test_wrong_expectation(self): 
    239         create_request('/spy_wrong_expectation') 
    240         body = cherrypy.response.body[0] 
    241         assert "fail: expected page_count=9, got page_count=10" in body 
     238        response = self.app.get('/spy_wrong_expectation') 
     239        assert "fail: expected page_count=9, got page_count=10" in response 
    242240 
    243241    def test_invalid_expectation(self): 
    244         create_request('/spy_invalid_expectation') 
    245         body = cherrypy.response.body[0] 
    246         assert "fail: paginate does not have 'foobar' attribute" in body 
     242        response = self.app.get('/spy_invalid_expectation') 
     243        assert "fail: paginate does not have 'foobar' attribute" in response 
    247244 
    248245    def test_raw_expectation(self): 
    249         create_request('/spy_correct_expectation') 
    250         Spy.assert_ok(cherrypy.response.body[0], 'var_name', 'data') 
    251         Spy.assert_ok(cherrypy.response.body[0], 'var_name', "'data'", raw=True) 
     246        response = self.app.get('/spy_correct_expectation') 
     247        Spy.assert_ok(response.body, 'var_name', 'data') 
     248        Spy.assert_ok(response.body, 'var_name', "'data'", raw=True) 
    252249 
    253250 
    254 class TestPagination(unittest.TestCase): 
     251class TestPagination(testutil.TGWebTest): 
    255252    """Base class for all Paginate TestCases""" 
    256253 
    257     def request(self, url): 
    258         create_request(url
    259         self.body = cherrypy.response.body[0] 
     254    def request(self, url, status=200): 
     255        response = self.app.get(url, status=status
     256        self.body = response.body 
    260257        if "fail: " in self.body: 
    261258            print self.body 
    262259            assert False, "Spy alert! Check body output for details..." 
     
    343340 
    344341 
    345342    def setUp(self): 
    346         cherrypy.root = self.MyRoot() 
     343        testutil.TGWebTest.setUp(self) 
     344        self.app = testutil.make_app(self.MyRoot) 
    347345 
    348346    def test_pagination_old_style(self): 
    349347        self.request("/basic") 
     
    439437        Spy.assert_ok(self.body, 'pages', xrange(4, 8)) 
    440438 
    441439    def test_invalid_dynamic_limit(self): 
    442         self.request("/invalid_dynamic") 
    443         assert cherrypy.response.status.startswith("500") 
     440        self.request("/invalid_dynamic", status=500) 
    444441        assert 'paginate: dynamic_limit (foobar) not found in output dict' in self.body 
    445442 
    446443    def test_dynamic_limit(self): 
     
    754751 
    755752 
    756753    def setUp(self): 
    757         cherrypy.root = self.MyRoot() 
     754        testutil.TGWebTest.setUp(self) 
     755        self.app = testutil.make_app(self.MyRoot) 
    758756 
    759757    def assert_order(self, *args): 
    760758        expr = 'data="%s"' % ''.join(['[Address %r]' % x for x in args]) 
     
    826824 
    827825    def test_invalid_default_reversed(self): 
    828826        for method in "Q", "QA", "SR", "SO", "SL": 
    829             self.request("/wrong_reversed/?method=%s" % method) 
    830             assert cherrypy.response.status.startswith("500") 
     827            self.request("/wrong_reversed/?method=%s" % method, status=500) 
    831828            assert ('paginate: default_reversed (deprecated) only allowed' 
    832829                ' when default_order is a basestring') in self.body 
    833830 
  • turbogears/qstemplates/quickstart/+package+/tests/test_controllers.py_tmpl

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

    old new  
    66import cStringIO as StringIO 
    77 
    88import cherrypy 
    9 from cherrypy import _cphttptools 
     9from webtest import TestApp 
    1010 
     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 
     16 
     17print cherrypy_major_ver 
     18 
     19 
    1120try: 
    1221    import sqlobject 
    1322    from sqlobject.inheritance import InheritableSQLObject 
     
    2130from turbogears import startup, config, update_config, \ 
    2231    controllers, database, validators 
    2332from turbogears.identity import current_provider 
    24 from turbogears.util import get_model 
     33from turbogears.util import get_model, deprecated 
    2534 
    2635cwd = os.getcwd() 
    2736 
     
    5160        {'autoreload.on': False, 'tg.new_style_logging': True}}) 
    5261 
    5362 
    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}) 
     63def start_server(): 
     64    """Start the server if it's not already.""" 
     65    if not config.get("cp_started"): 
     66        if cherrypy_major_ver < 3: 
     67            cherrypy.server.start(serverClass=None, initOnly=True) 
     68        else: 
     69            cherrypy.server.quickstart() 
     70            cherrypy.engine.start() 
     71        config.update({"cp_started" : True}) 
    5872 
     73    if not config.get("server_started"): 
     74        startup.startTurboGears() 
     75        config.update({"server_started" : True}) 
    5976 
     77start_cp = deprecated('start_cp is superceded by start_server')(start_server) 
     78 
     79 
     80def stop_server(tg_only = False): 
     81    """Stop the server and unmount the application.  \ 
     82    Use tg_only = True to leave CherryPy running (for faster tests). 
     83    """ 
     84    unmount() 
     85    if config.get("cp_started") and not tg_only: 
     86       cherrypy.server.stop() 
     87       config.update({"cp_started" : False}) 
     88    
     89    if config.get("server_started"): 
     90        startup.stopTurboGears() 
     91        config.update({"server_started" : False}) 
     92 
     93 
     94 
    6095test_user = None 
    6196 
     97@deprecated() 
    6298def set_identity_user(user): 
    6399    """Setup a user for configuring request's identity.""" 
    64100    global test_user 
    65101    test_user = user 
    66102 
    67103 
     104@deprecated() 
    68105def attach_identity(req): 
    69106    if config.get("identity.on", False): 
    70107        req.identity = (test_user 
    71108            and current_provider.authenticated_identity(test_user) 
    72109            or current_provider.anonymous_identity()) 
    73110 
    74  
     111@deprecated("create_request is deprecated.  See TestMigration on the TG Wiki") 
    75112def create_request(request, method="GET", protocol="HTTP/1.1", 
    76113        headers={}, rfile=None, clientAddress="127.0.0.1", 
    77114        remoteHost="localhost", scheme="http"): 
    78     start_cp() 
     115    start_server() 
    79116    if not rfile: 
    80117        rfile = StringIO.StringIO("") 
    81118    if type(headers) != dict: 
     
    86123    if not hasattr(cherrypy.root, "started"): 
    87124        startup.startTurboGears() 
    88125        cherrypy.root.started = True 
    89     req = _cphttptools.Request(clientAddress, 80, remoteHost, scheme) 
     126    req = Request(clientAddress, 80, remoteHost, scheme) 
    90127    cherrypy.serving.request = req 
    91128    attach_identity(req) 
    92     cherrypy.serving.response = _cphttptools.Response() 
     129    cherrypy.serving.response = Response() 
    93130    req.run(" ".join((method, request, protocol)), headerList, rfile) 
     131    return cherrypy.serving.response 
    94132 
     133createRequest = create_request 
    95134 
     135 
     136def make_wsgiapp(): 
     137    """Return a WSGI application from cherrypy's root object.""" 
     138    if cherrypy_major_ver < 3: 
     139        wsgiapp = cherrypy._cpwsgi.wsgiApp 
     140    else: 
     141        #This is untested but should work.. if not, one of the others will 
     142        wsgiapp = cherrpy.root 
     143        #wsgiapp = cherrypy.tree.mount(cherrypy.root, '/') 
     144        #wsgiapp = cherrypy.wsgi.CPWSGIServer 
     145    return wsgiapp 
     146 
     147 
     148def make_app(controller=None): 
     149    """Return a WebTest.TestApp instance from Cherrypy. 
     150    If a Controller object is provided, it will be mounted at the root level. 
     151    If not, it'll look for an already mounted root. 
     152    """ 
     153    if controller: 
     154        wsgiapp = mount(controller(), '/') 
     155    else: 
     156        wsgiapp = make_wsgiapp() 
     157    testapp = TestApp(wsgiapp) 
     158 
     159    return testapp 
     160 
     161 
     162class TGWebTest(unittest.TestCase): 
     163    """A WebTest enabled unit testing class. 
     164 
     165    This allows testers to subclass us and use self.app to make WebTest calls. 
     166    """ 
     167    def setUp(self): 
     168        start_server() 
     169        self.app = make_app() 
     170 
     171    def tearDown(self): 
     172        stop_server(tg_only = True) 
     173        del self.app 
     174 
     175    def login_user(self, user): 
     176        """ Log a specified user object into the system """ 
     177        self.app.post(config.get('identity.failure_url'), { 
     178                'user_name' : user.user_name, 
     179                'password'  : user.password, 
     180                'login'     : 'Login', 
     181        }) 
     182 
     183 
    96184class BrowsingSession(object): 
    97185 
    98186    def __init__(self): 
    99187        self.visit = None 
    100188        self.response, self.status = None, None 
    101189        self.cookie = Cookie.SimpleCookie() 
     190        self.app = make_app() 
    102191 
    103192    def goto(self, *args, **kwargs): 
    104193        if self.cookie: 
    105194            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
     195            headers['Cookie'] = self.cookie_encoded 
     196        response = self.app.get(*args, **kwargs) 
     197        self.response = response.body 
     198        self.status = response.status 
     199        self.cookie = response.cookies_set 
     200        self.cookie_encoded = response.headers.get('Set-Cookie', ''
    112201 
    113202 
    114203def _return_directly(output, *args): 
     
    142231    headers = {} 
    143232 
    144233 
     234@deprecated("Please see the TestMigration page in the TG wiki.") 
    145235def call(method, *args, **kw): 
    146     start_cp() 
     236    start_server() 
    147237    output, response = call_with_request(method, DummyRequest(), *args, **kw) 
    148238    return output 
    149239 
    150240 
     241@deprecated("Please see the TestMigration page in the TG wiki.") 
    151242def call_with_request(method, request, *args, **kw): 
    152243    """More fine-grained version of call method. 
    153244 
     
    156247    """ 
    157248    orig_proc_output = controllers._process_output 
    158249    controllers._process_output = _return_directly 
    159     cherrypy.serving.response = _cphttptools.Response() 
     250    cherrypy.serving.response = Response() 
    160251    cherrypy.serving.request = request 
    161252    if not hasattr(request, "identity"): 
    162253        attach_identity(request) 
     
    200291                and item != InheritableSQLObject: 
    201292                item.dropTable(ifExists=True) 
    202293 
    203  
    204 def reset_cp(): 
     294def unmount(): 
     295    """Remove an application from the object traversal tree.""" 
     296    # There's no clean way to remove a subtree under CP2, so the only use case 
     297    #  handled here is to remove the entire application. 
     298    # Supposedly, you can do a partial unmount with CP3 using: 
     299    #  del cherrypy.tree.apps[path] 
    205300    cherrypy.root = None 
     301    cherrypy.tree.mount_points = {} 
    206302 
     303reset_cp = deprecated('reset_cp has been superceded by unmount.')(unmount) 
    207304 
     305 
     306def mount(controller, path="/"): 
     307    """Mount a controller at a path.  Returns a wsgi application.""" 
     308    if path == '/': 
     309        cherrypy.root = controller 
     310    else: 
     311        cherrypy.tree.mount(controller, path) 
     312    return make_wsgiapp() 
     313 
    208314def catch_validation_errors(widget, value): 
    209315    """Catch and unpack validation errors (for testing purposes).""" 
    210316    try: 
     
    253359 
    254360    """ 
    255361    global _currentcat 
    256     assert not _currentcat 
     362    assert not _currentcat, "_currentcat not cleared.  Use get_log to reset." 
    257363    if not isinstance(category, list) and not isinstance(category, tuple): 
    258364        category = [category] 
    259365    _currentcat = category 
     
    307413 
    308414__all__ = ["call", "create_request", "DBTest", 
    309415    "attach_identity", "set_identity_user", 
    310     "capture_log", "print_log", "get_log", "sqlalchemy_cleanup"] 
     416    "capture_log", "print_log", "get_log", "sqlalchemy_cleanup", 
     417    "make_wsgiapp", "make_app", "TGWebTest", "start_server", 
     418    "stop_server", "mount", "unmount"] 
  • turbogears/widgets/tests/test_nested_form_controllers.py

    old new  
    11import turbogears 
    2 import cherrypy 
    32from turbogears import widgets 
    43from turbogears import controllers 
    54from turbogears import validators 
    65from turbogears import testutil 
    76 
     7 
     8def setup_module(): 
     9    global app 
     10    app = testutil.make_app(MyRoot) 
     11    testutil.start_server() 
     12 
     13def teardown_module(): 
     14    testutil.stop_server() 
     15 
     16 
    817myform = widgets.TableForm(fields = [ 
    918    widgets.FieldSet( 
    1019        name = "p_data", 
     
    1726 
    1827class MyRoot(controllers.RootController): 
    1928    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'] 
     29        has_errors = tg_errors is not None 
     30        name = p_data['name'] 
     31        age = p_data['age'] 
     32        return dict(has_errors = has_errors, name=name, age = age) 
    2433    testform = turbogears.validate(form=myform)(testform) 
    25     testform = turbogears.expose(html="turbogears.tests.othertemplate")( 
     34    testform = turbogears.expose(template="turbogears.tests.othertemplate")( 
    2635                                 testform) 
    2736 
    2837    def set_errors(self): 
    29         self.has_errors = True 
     38        return dict(has_errors = True) 
     39         
    3040 
    3141    def testform_new_style(self, p_data): 
    32         self.name = p_data['name'] 
    33         self.age = p_data['age'] 
     42        name = p_data['name'] 
     43        age = p_data['age'] 
     44        return dict(name = name, age = age) 
    3445    testform_new_style = turbogears.validate(form=myform)(testform_new_style) 
    3546    testform_new_style = turbogears.error_handler(set_errors)(testform_new_style) 
    3647    testform_new_style = turbogears.expose()(testform_new_style) 
    3748 
    3849 
     50 
    3951def test_form_translation_new_style(): 
    4052    "Form input is translated into properly converted parameters" 
    41     root = MyRoot() 
    42     cherrypy.root = root 
    43     testutil.create_request("/testform_new_style?p_data.name=ed&p_data.age=5") 
    44     assert root.name == "ed" 
    45     print root.age 
    46     assert root.age == 5 
     53    response = app.get("/testform_new_style?p_data.name=ed&p_data.age=5") 
     54    assert response.raw['name'] == "ed" 
     55    print response.raw['age'] 
     56    assert response.raw['age'] == 5 
    4757 
    4858def test_invalid_form_with_error_handling(): 
    4959    "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 
     60    response = app.get("/testform_new_style?p_data.name=ed&p_data.age=edalso") 
     61    assert response.raw['has_errors'] 
     62 
  • turbogears/widgets/tests/test_datagrid.py

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

    old new  
    11import turbogears 
    2 import cherrypy 
    3  
    42from turbogears import widgets, testutil 
    53 
     4def setup_module(): 
     5    testutil.start_server() 
    66 
     7def teardown_module(): 
     8    testutil.stop_server() 
     9 
     10 
    711def test_table_widget_js(): 
    812    """ 
    913    The TableForm Widget can require JavaScript and CSS resources. Addresses 
     
    2125            return dict(form=form) 
    2226        test = turbogears.expose(template="turbogears.widgets.tests.form")(test) 
    2327 
    24     cherrypy.root = MyRoot() 
    25     testutil.create_request("/test") 
    26     output = cherrypy.response.body[0] 
    27     assert 'foo.js' in output 
    28     assert "alert('hello');" in output 
    29     assert 'foo.css' in output 
     28    app = testutil.make_app(MyRoot) 
     29    response = app.get("/test") 
     30    assert 'foo.js' in response.body 
     31    assert "alert('hello');" in response.body 
     32    assert 'foo.css' in response.body 
    3033 
    3134 
    3235def test_calendardatepicker_js(): 
     
    3740            return dict(widget=widgets.CalendarDatePicker(calendar_lang=lang)) 
    3841        test = turbogears.expose(template="turbogears.widgets.tests.widget")(test) 
    3942 
    40     cherrypy.root = MyRoot(
     43    app = testutil.make_app(MyRoot
    4144 
    4245    # testing default language (en) 
    43     testutil.create_request("/test") 
    44     output = cherrypy.response.body[0] 
    45     assert 'calendar/calendar.js' in output 
    46     assert 'calendar/calendar-setup.js' in output 
    47     assert 'calendar/lang/calendar-en.js' in output 
     46    response = app.get("/test") 
     47    assert 'calendar/calendar.js' in response.body 
     48    assert 'calendar/calendar-setup.js' in response.body 
     49    assert 'calendar/lang/calendar-en.js' in response.body 
    4850 
    4951    # testing non-existing language 
    50     testutil.create_request("/test", 
    51         headers={"Accept-Language": "x"}) 
    52     output = cherrypy.response.body[0] 
    53     assert 'calendar/lang/calendar-x.js' not in output 
    54     assert 'calendar/lang/calendar-en.js' in output 
     52    response = app.get("/test", headers={"Accept-Language": "x"}) 
     53    assert 'calendar/lang/calendar-x.js' not in response.body 
     54    assert 'calendar/lang/calendar-en.js' in response.body 
    5555 
    5656    # testing French language 
    57     testutil.create_request("/test", 
    58         headers={"Accept-Language": "fr"}) 
    59     output = cherrypy.response.body[0] 
    60     assert 'calendar/lang/calendar-fr.js' in output 
    61     assert 'calendar/lang/calendar-en.js' not in output 
    62     assert 'charset="utf-8"' in output 
     57    response = app.get("/test", headers={"Accept-Language": "fr"}) 
     58    assert 'calendar/lang/calendar-fr.js' in response.body 
     59    assert 'calendar/lang/calendar-en.js' not in response.body 
     60    assert 'charset="utf-8"' in response.body 
    6361 
    6462    # testing German language with any charset 
    65     testutil.create_request("/test", 
     63    response = app.get("/test",  
    6664        headers={"Accept-Language": "de", "Accept-Charset": "*"}) 
    67     output = cherrypy.response.body[0] 
    68     assert 'calendar/lang/calendar-de.js' in output 
    69     assert 'calendar/lang/calendar-en.js' not in output 
    70     assert 'charset="*"' not in output 
     65    assert 'calendar/lang/calendar-de.js' in response.body 
     66    assert 'calendar/lang/calendar-en.js' not in response.body 
     67    assert 'charset="*"' not in response.body 
    7168 
    7269    # testing Turkish language with non-existing charset 
    73     testutil.create_request("/test", 
     70    response = app.get("/test", 
    7471        headers={"Accept-Language": "tr", "Accept-Charset": "big5"}) 
    75     output = cherrypy.response.body[0] 
    76     assert 'calendar/lang/calendar-tr.js' in output 
    77     assert 'calendar/lang/calendar-en.js' not in output 
    78     assert 'charset="big5"' not in output 
     72    assert 'calendar/lang/calendar-tr.js' in response.body 
     73    assert 'calendar/lang/calendar-en.js' not in response.body 
     74    assert 'charset="big5"' not in response.body 
    7975 
    8076    win1254 = 'windows-1254' 
    8177    from codecs import lookup 
     
    8581        win1254 = 'cp1254' # cannot test name normalization here 
    8682 
    8783    # testing Turkish language with existing, not normalized charset 
    88     testutil.create_request("/test", 
     84    response = app.get("/test", 
    8985        headers={"Accept-Language": "tr", "Accept-Charset": win1254}) 
    90     output = cherrypy.response.body[0] 
    91     assert 'calendar/lang/calendar-tr-cp1254.js' in output 
    92     assert 'calendar/lang/calendar-en.js' not in output 
    93     assert 'charset="cp1254"' in output 
     86    assert 'calendar/lang/calendar-tr-cp1254.js' in response.body 
     87    assert 'calendar/lang/calendar-en.js' not in response.body 
     88    assert 'charset="cp1254"' in response.body 
    9489 
    9590    # testing more than one language and charset 
    96     testutil.create_request("/test", headers={"Accept-Language": "x,tr,de,fr", 
     91    response = app.get("/test", headers={"Accept-Language": "x,tr,de,fr", 
    9792        "Accept-Charset": "big5,%s,latin-1" % win1254}) 
    98     output = cherrypy.response.body[0] 
    99     assert 'calendar/lang/calendar-tr-cp1254.js' in output 
    100     assert 'calendar/lang/calendar-x.js' not in output 
    101     assert 'calendar/lang/calendar-en.js' not in output 
    102     assert 'charset="cp1254"' in output 
    103     assert 'charset="big5"' not in output 
     93    assert 'calendar/lang/calendar-tr-cp1254.js' in response.body 
     94    assert 'calendar/lang/calendar-x.js' not in response.body 
     95    assert 'calendar/lang/calendar-en.js' not in response.body 
     96    assert 'charset="cp1254"' in response.body 
     97    assert 'charset="big5"' not in response.body 
    10498 
    10599    # testing predetermined language (fr) 
    106     testutil.create_request("/test?lang=fr", 
     100    response = app.get("/test?lang=fr", 
    107101        headers={"Accept-Language": "de,en,tr"}) 
    108     output = cherrypy.response.body[0] 
    109     assert 'calendar/lang/calendar-fr.js' in output 
    110     assert 'calendar/lang/calendar-en.js' not in output 
     102    assert 'calendar/lang/calendar-fr.js' in response.body 
     103    assert 'calendar/lang/calendar-en.js' not in response.body 
    111104 
    112105    # testing predetermined non-existing language 
    113     testutil.create_request("/test?lang=x", 
     106    response = app.get("/test?lang=x", 
    114107        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 
     108    assert 'calendar/lang/calendar-de.js' in response.body 
     109    assert 'calendar/lang/calendar-x.js' not in response.body 
     110    assert 'calendar/lang/calendar-en.js' not in response.body 
     111 
  • turbogears/widgets/tests/test_new_validation.py

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

    old new  
    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, make_app 
    88import cherrypy 
    99 
    1010 
    1111def setup_module(): 
    12     testutil.start_cp() 
    13     cherrypy.serving.request = testutil.DummyRequest() 
     12    testutil.start_server() 
    1413 
     14def teardown_module(): 
     15    testutil.stop_server() 
     16 
     17 
    1518def test_rendering(): 
    1619    """Forms can be rendered""" 
    1720    form = widgets.TableForm(fields=[widgets.TextField("name", label="Your Name")]) 
     
    166169 
    167170    @expose() 
    168171    @validate(form=nestedform) 
    169     def checkform(self, foo): 
    170         self.foo = foo 
     172    def checkform(self, foo=None): 
     173    #def checkform(self, foo=None, *args, **kw): 
     174        #raise Exception('HolyHell: %s: %s. kw: %s' % (foo, args, kw)) 
     175        return foo 
    171176 
     177    @expose() 
     178    def field_for(self): 
     179        cherrypy.request.validation_errors = dict(foo=dict(foo='error')) 
     180        template = """\ 
     181        <div xmlns:py="http://purl.org/kid/ns#"> 
     182            ${field_for('foo').fq_name}.appears 
     183            ${field_for('foo').error}_appears 
     184            ${field_for('foo').field_id}_appears 
     185            ${field_for('foo').display(value_for('foo'), **params_for('foo'))} 
     186        </div> 
     187        """ 
     188        textfield = widgets.TextField("foo") 
     189        fieldset = widgets.FieldSet("foo", fields=[textfield], template=template) 
     190        form = widgets.Form("form", fields=[fieldset], template=template) 
    172191 
     192        # Good example below of how you can pass parameters and values to nested 
     193        # widgets. 
     194        value = dict(foo=dict(foo="HiYo!")) 
     195        params = dict(attrs=dict(foo=dict(foo=dict(size=100)))) 
     196        params['format'] = 'xhtml' 
     197        return form.render(value, **params) 
     198 
     199 
    173200def test_nested_variables(): 
    174     newroot = NestedController() 
    175     cherrypy.root = None 
    176     cherrypy.tree.mount_points = {} 
    177     cherrypy.tree.mount(newroot, "/") 
    178201    url = u"/checkform?foo.name=Kevin&foo.age=some%20Numero".encode("utf-8") 
    179     create_request(url) 
     202    testutil.stop_server(tg_only = True) 
     203    app = testutil.make_app(NestedController) 
     204    testutil.start_server() 
     205  
     206    request = app.get(url) 
    180207    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" 
     208    print "raw", request.raw 
     209    assert request.raw["name"] == "Kevin" 
     210    assert request.raw["age"] == u"some Numero" 
    184211 
    185212def test_field_for(): 
    186     cherrypy.request.validation_errors = dict(foo=dict(foo='error')) 
    187     template = """\ 
    188     <div xmlns:py="http://purl.org/kid/ns#"> 
    189         ${field_for('foo').fq_name}.appears 
    190         ${field_for('foo').error}_appears 
    191         ${field_for('foo').field_id}_appears 
    192         ${field_for('foo').display(value_for('foo'), **params_for('foo'))} 
    193     </div> 
    194     """ 
    195     textfield = widgets.TextField("foo") 
    196     fieldset = widgets.FieldSet("foo", fields=[textfield], template=template) 
    197     form = widgets.Form("form", fields=[fieldset], template=template) 
    198     # Good example below of how you can pass parameters and values to nested 
    199     # widgets. 
    200     value = dict(foo=dict(foo="HiYo!")) 
    201     params = dict(attrs=dict(foo=dict(foo=dict(size=100)))) 
    202     params['format'] = 'xhtml' 
    203     output = form.render(value, **params) 
    204     assert "form_foo_appears" in output 
    205     assert "form_foo_foo_appears" in output 
    206     assert "foo.appears" in output 
    207     assert "foo.foo.appears" in output 
    208     assert "error_appears" in output 
    209     assert "textfield" in output 
    210     assert "HiYo!" in output 
    211     assert "size=\"100\"" in output 
     213    app = make_app(NestedController) 
     214    response = app.get('/field_for') 
     215    assert "form_foo_appears" in response 
     216    assert "form_foo_foo_appears" in response 
     217    assert "foo.appears" in response 
     218    assert "foo.foo.appears" in response 
     219    assert "error_appears" in response 
     220    assert "textfield" in response 
     221    assert "HiYo!" in response 
     222    assert "size=\"100\"" in response 
  • turbogears/widgets/tests/test_request_related_features.py

    old new  
    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 
     7def setup_module(): 
     8    testutil.start_server() 
     9 
     10def teardown_module(): 
     11    testutil.stop_server() 
     12 
     13 
    814def test_required_fields(): 
    915    """ 
    1016    Required field are automatically discovered from the form validator and marked 
     
    2026            return dict(form=form) 
    2127        test = turbogears.expose(template="turbogears.widgets.tests.form")(test) 
    2228 
    23     cherrypy.root = MyRoot(
    24     testutil.create_request("/test") 
    25     output = cherrypy.response.body[0].lower() 
     29    app = testutil.make_app(MyRoot
     30    response = app.get("/test") 
     31    output = response.body.lower() 
    2632 
    2733    print output 
    2834    name_p = 'name="comment"' 
     
    4854    form2 = widgets.TableForm(name="form2", fields=MyFields()) 
    4955 
    5056    class MyRoot(turbogears.controllers.RootController): 
    51         def test(self): 
    52             return dict(form1=form1, form2=form2) 
     57        
     58        #@expose(template="turbogears.widgets.tests.two_forms")  
     59        #@validate(form=form1) 
     60        #@error_handler('test') 
     61        def test(self, age, email): 
     62            validated_form = cherrypy.request.validated_form.name 
     63            form1_valid = form1.is_validated 
     64            form2_valid = form2.is_validated 
     65            return dict(form1=form1, form2=form2, validated_form=validated_form, 
     66                        form1_valid=form1_valid, form2_valid=form2_valid) 
    5367        test = turbogears.expose(template="turbogears.widgets.tests.two_forms")(test) 
    5468        test = turbogears.validate(form=form1)(test) 
    5569        test = turbogears.error_handler(test)(test) 
    5670 
     71 
    5772        def test2(self): 
    58             return dict(form=form2) 
     73            validated_form = cherrypy.request.validated_form.name 
     74            form1_valid = form1.is_validated 
     75            form2_valid = form2.is_validated 
     76            return dict(form=form2, validated_form=validated_form, 
     77                        form1_valid=form1_valid, form2_valid=form2_valid) 
    5978        test2 = turbogears.expose(template="turbogears.widgets.tests.form")(test2) 
    6079        test2 = turbogears.validate(form=form2)(test2) 
    6180        test2 = turbogears.error_handler(test2)(test2) 
    6281 
    6382        def test3(self): 
    64             return dict(form=form1) 
     83            validated_form = cherrypy.request.validated_form.name 
     84            form1_valid = form1.is_validated 
     85            form2_valid = form2.is_validated 
     86            return dict(form=form1, validated_form=validated_form, 
     87                        form1_valid=form1_valid, form2_valid=form2_valid) 
    6588        test3 = turbogears.expose(template="turbogears.widgets.tests.form")(test3) 
    6689        test3 = turbogears.validate(form=form2)(test3) 
    6790        test3 = turbogears.error_handler(test3)(test3) 
    6891 
    69     cherrypy.root = MyRoot() 
    70     testutil.create_request("/test?age=foo&email=bar") 
    71     output = cherrypy.response.body[0].lower() 
    72     iv = cherrypy.request.input_values 
    73     validation_errors = cherrypy.request.validation_errors 
    74     validated_form = cherrypy.request.validated_form 
     92    app = testutil.make_app(MyRoot) 
    7593 
    76     print output 
    77     print iv 
    78     print validation_errors 
    79     print validated_form 
    80     assert form1 is validated_form 
    81     assert form1.is_validated 
    82     assert form2 is not validated_form 
    83     assert not form2.is_validated 
     94    response = app.get("/test?age=foo&email=bar") 
     95    output = response.body.lower() 
     96 
     97    assert response.raw['validated_form'] == 'form1' 
     98    assert response.raw['form1_valid'] 
     99    assert not response.raw['form2_valid'] 
    84100    value_p = 'value="foo"' 
    85101    id_p = 'id="form1_age"' 
    86102    assert (re.compile('.*'.join([value_p, id_p])).search(output) or 
     
    92108            re.compile('.*'.join([id_p, value_p])).search(output) 
    93109    ) 
    94110 
    95     cherrypy.root = MyRoot() 
    96     testutil.create_request("/test2?age=foo&email=bar") 
    97     output = cherrypy.response.body[0].lower() 
    98     iv = cherrypy.request.input_values 
    99     validation_errors = cherrypy.request.validation_errors 
    100     validated_form = cherrypy.request.validated_form 
     111    response = app.get("/test2?age=foo&email=bar") 
     112    output = response.body.lower() 
    101113 
    102     print output 
    103     print iv 
    104     print validation_errors 
    105     print validated_form 
    106     assert form1 is not validated_form 
    107     assert not form1.is_validated 
    108     assert form2 is validated_form 
    109     assert form2.is_validated 
     114    assert response.raw['validated_form'] == 'form2' 
     115    assert not response.raw['form1_valid'] 
     116    assert response.raw['form2_valid'] 
    110117    assert 'value="foo"' in output 
    111118    assert '>bar<' in output 
    112119    assert 'class="fielderror"' in output 
    113120 
    114     cherrypy.root = MyRoot() 
    115     testutil.create_request("/test3?age=foo&email=bar") 
    116     output = cherrypy.response.body[0].lower() 
    117     iv = cherrypy.request.input_values 
    118     validation_errors = cherrypy.request.validation_errors 
    119     validated_form = cherrypy.request.validated_form 
     121    response = app.get("/test3?age=foo&email=bar") 
     122    output = response.body.lower() 
    120123 
    121     print output 
    122     print iv 
    123     print validation_errors 
    124     print validated_form 
    125     assert form1 is not validated_form 
    126     assert not form1.is_validated 
    127     assert form2 is validated_form 
    128     assert form2.is_validated 
     124    assert response.raw['validated_form'] == 'form2' 
     125    assert not response.raw['form1_valid'] 
     126    assert response.raw['form2_valid'] 
    129127    assert 'value="foo"' not in output 
    130128    assert '>bar<' not in output 
    131129    assert 'class="fielderror"' not in output 
     
    141139            name="repeat", fields=MyFields(), repetitions=repetitions)]) 
    142140 
    143141    class MyRoot(turbogears.controllers.RootController): 
    144         @turbogears.expose(template="turbogears.widgets.tests.form") 
    145142        def test(self): 
    146143            return dict(form=form) 
     144        test = turbogears.expose(template="turbogears.widgets.tests.form")(test) 
    147145 
    148         @turbogears.expose(template="turbogears.widgets.tests.form") 
    149146        def test_value(self): 
    150147            value = dict(repeat=[{'name':'foo', 'comment':'hello'}, 
    151148                                 None, 
    152149                                 None, 
    153150                                 {'name':'bar', 'comment':'byebye'}]) 
    154151            return dict(form=form, value=value) 
     152        test_value = turbogears.expose(template="turbogears.widgets.tests.form")(test_value) 
    155153 
    156154        def test_validation(self): 
    157             return dict(form=form) 
    158         test_validation = turbogears.expose( 
    159              template="turbogears.widgets.tests.form")(test_validation) 
     155            validation_errors = cherrypy.request.validation_errors 
     156            return dict(form=form, validation_errors=validation_errors) 
     157        test_validation = turbogears.expose(template="turbogears.widgets.tests.form")(test_validation) 
    160158        test_validation = turbogears.validate(form=form)(test_validation) 
    161159        test_validation = turbogears.error_handler(test_validation)(test_validation) 
    162160 
    163     cherrypy.root = MyRoot(
    164     testutil.create_request("/test") 
    165     output = cherrypy.response.body[0].lower() 
     161    app = testutil.make_app(MyRoot
     162    response = app.get("/test") 
     163    output = response.body.lower() 
    166164    for i in range(repetitions): 
    167165        assert 'id="form_repeat_%i"' % i in output 
    168166        assert 'name="repeat-%i.name"' % i in output 
     
    170168        assert 'name="repeat-%i.comment"' % i in output 
    171169        assert 'id="form_repeat_%i_comment"' % i in output 
    172170 
    173     cherrypy.root = MyRoot() 
    174     testutil.create_request("/test_value") 
    175     output = cherrypy.response.body[0].lower() 
     171    response = app.get("/test_value") 
     172    output = response.body.lower() 
    176173    name_p = 'name="repeat-0.name"' 
    177174    value_p = 'value="foo"' 
    178175    assert (re.compile('.*'.join([value_p, name_p])).search(output) or 
     
    204201            re.compile('.*'.join([name_p, value_p])).search(output) 
    205202    ) 
    206203 
    207     cherrypy.root = MyRoot() 
    208     testutil.create_request("/test_validation?repeat-0.name=foo&repeat-1.name=" 
     204    #FIXME: Why is stopping the server necessary here? 
     205    testutil.stop_server(tg_only = True) 
     206    app = testutil.make_app(MyRoot) 
     207    testutil.start_server() 
     208 
     209    response = app.get("/test_validation?repeat-0.name=foo&repeat-1.name=" 
    209210        "&repeat-2.name=bar&repeat-3.name=&repeat-4.name=") 
    210     output = cherrypy.response.body[0].lower() 
    211     validation_errors = cherrypy.request.validation_errors 
     211    output = response.body.lower() 
     212    print "Raw", response.raw 
     213    validation_errors = response.raw['validation_errors'] 
    212214    assert validation_errors.has_key("repeat") 
    213215    assert isinstance(validation_errors["repeat"], list) 
    214216    assert validation_errors["repeat"][0] is None 
  • turbogears/widgets/tests/test_widgets.py

    old new  
    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 
     10def teardown_module(): 
     11    testutil.stop_server() 
    1012 
     13 
    1114def test_rendering_without_engine(): 
    1215    """Helpful error when rendering widgets with no templating engine loaded""" 
    1316    from turbogears import view 
  • turbogears/widgets/tests/test_nested_widgets.py

    old new  
    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        app = testutil.make_app(self.MyRoot
     58        response = app.get('/?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 = app.get('/?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 = app.get('/?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

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