Ticket #1762: TurboGears-1.1-WebTest.patch

File TurboGears-1.1-WebTest.patch, 83.8 kB (added by lmacken, 6 months ago)

Updated again with some minor cleanups

  • setup.py

    old new  
    2424    "TurboCheetah >= 1.0", 
    2525    "TurboJson >= 1.1.2", 
    2626    "tgMochiKit >= 0.1alpha", 
     27    "WebTest", 
    2728] 
    2829 
    2930# for when we get rid of Kid & SQLObject dependency 
  • 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): 
     
    137137                ' for all strings' % cherrypy.request.params 
    138138 
    139139 
    140 class TestIdentity(unittest.TestCase): 
     140class TestIdentity(testutil.TGWebTest): 
    141141 
    142142    def setUp(self): 
    143143        # identity requires visit and a failure_url 
     
    152152        config.configure_loggers(test_config) 
    153153        config.update(test_config['global']) 
    154154        cherrypy.root = IdentityRoot() 
    155         startup.startTurboGears(
     155        testutil.TGWebTest.setUp(self
    156156        self.init_model() 
    157157 
    158158    def tearDown(self): 
    159         startup.stopTurboGears(
     159        testutil.TGWebTest.tearDown(self
    160160        config.update(self._original_config) 
    161161 
    162162    def init_model(self): 
     
    181181 
    182182    def test_user_password_parameters(self): 
    183183        """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 
     184        response = self.app.get('/new_user_setup?user_name=test&password=pw') 
     185        assert 'test pw' in response 
    187186 
    188187    def test_user_exists(self): 
    189188        u = TG_User.by_user_name('samIam') 
     
    205204        config.update({'identity.soprovider.encryption_algorithm': None}) 
    206205        # force new config values to load 
    207206        startup.startTurboGears() 
    208         testutil.create_request('/') 
     207        self.app.get('/') 
    209208        hub.begin() 
    210209        u = TG_User.by_user_name('samIam') 
    211210        u.password = u'garçon' 
     
    219218        config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 
    220219        # force new config values to load 
    221220        startup.startTurboGears() 
    222         testutil.create_request('/') 
     221        self.app.get('/') 
    223222        hub.begin() 
    224223        u = TG_User.by_user_name('samIam') 
    225224        u.password = 'password' 
     
    234233        config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 
    235234        # force new config values to load 
    236235        startup.startTurboGears() 
    237         testutil.create_request('/') 
     236        self.app.get('/') 
    238237        hub.begin() 
    239238        u = TG_User.by_user_name('samIam') 
    240239        u.password = u'garçon' 
     
    248247        config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 
    249248        # force new config values to load 
    250249        startup.startTurboGears() 
    251         testutil.create_request('/') 
     250        self.app.get('/') 
    252251        hub.begin() 
    253252        u = TG_User.by_user_name('samIam') 
    254253        u.password = 'password' 
     
    263262        config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 
    264263        # force new config values to load 
    265264        startup.startTurboGears() 
    266         testutil.create_request('/') 
     265        self.app.get('/') 
    267266        hub.begin() 
    268267        u = TG_User.by_user_name('samIam') 
    269268        u.password = u'garçon' 
     
    280279        config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 
    281280        # force new config values to load 
    282281        startup.startTurboGears() 
    283         testutil.create_request('/') 
     282        self.app.get('/') 
    284283        hub.begin() 
    285284        u = TG_User.by_user_name('samIam') 
    286285        u.password = u'garçon'.encode('UTF-8') 
     
    295294        config.update({'identity.soprovider.encryption_algorithm':'sha1'}) 
    296295        # force new config values to load 
    297296        startup.startTurboGears() 
    298         testutil.create_request('/') 
     297        self.app.get('/') 
    299298        hub.begin() 
    300299        u = TG_User.by_user_name('samIam') 
    301300        u.set_password_raw('password') 
     
    308307        config.update({'identity.soprovider.encryption_algorithm':'sha1'}) 
    309308        # force new config values to load 
    310309        startup.startTurboGears() 
    311         testutil.create_request('/') 
     310        self.app.get('/') 
    312311        hub.begin() 
    313312        u = TG_User.by_user_name('samIam') 
    314313        u.set_password_raw(u'garçon') 
     
    324323                'identity.tests.test_identity.mycustomencrypt'}) 
    325324        # force new config values to load 
    326325        startup.startTurboGears() 
    327         testutil.create_request('/') 
     326        self.app.get('/') 
    328327        hub.begin() 
    329328        u = TG_User.by_user_name('samIam') 
    330329        u.password = 'password' 
     
    335334 
    336335    def test_anonymous_browsing(self): 
    337336        """Test if we can show up anonymously.""" 
    338         testutil.create_request('/') 
     337        self.app.get('/') 
    339338        assert identity.current.anonymous 
    340339 
    341340    def test_deny_anonymous(self): 
    342341        """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 
     342        response = self.app.get('/logged_in_only') 
     343        assert 'identity_failed_answer' in response 
    346344 
    347345    def test_deny_anonymous_viewable(self): 
    348346        """Test that a logged in user can see an resource blocked 
    349347        from anonymous users.""" 
    350         testutil.create_request('/logged_in_only?' 
     348        response = self.app.get('/logged_in_only?' 
    351349            'user_name=samIam&password=secret&login=Login') 
    352         firstline = cherrypy.response.body[0] 
    353         assert 'logged_in_only' in firstline, firstline 
     350        assert 'logged_in_only' in response 
    354351 
    355352    def test_logout(self): 
    356353        """Test that logout works and session is gets invalid afterwards.""" 
    357         testutil.create_request('/in_peon_group?' 
     354        response = self.app.get('/in_peon_group?' 
    358355            'user_name=samIam&password=secret&login=Login') 
     356        assert False 
    359357        self.assertEquals("samIam", cherrypy.serving.request.identity.user_name) 
    360358        session_id = re.match("Set-Cookie: (.*?); Path.*", 
    361359            str(cherrypy.response.simple_cookie)).group(1) 
  • turbogears/tests/test_form_controllers.py

    old new  
    3434        self.name = name 
    3535        self.age = age 
    3636        self.date = date 
     37        return dict() 
    3738 
    3839    @expose() 
    3940    @validate(form=myform) 
     
    4344        self.name = name 
    4445        self.age = age 
    4546        self.date = date 
     47        return dict() 
    4648 
    47 def test_form_translation(): 
    48     """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 
    5449 
    55 def test_form_translation_new_style(): 
    56     """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 
     50class TestFormControllers(testutil.TGWebTest): 
    6251 
    63 def test_invalid_form_with_error_handling(): 
    64     """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 
     52    def test_form_translation(self): 
     53        """Form input is translated into properly converted parameters""" 
     54        root = MyRoot() 
     55        cherrypy.root = root 
     56        self.app.get("/testform?name=ed&date=11/05/2005&age=5") 
     57        assert root.name == "ed" 
     58        assert root.age == 5 
    6859 
    69 def test_css_should_appear(): 
    70     """CSS should appear when asked for""" 
    71     testutil.create_request("/") 
    72     assert "calendar-system.css" in cherrypy.response.body[0] 
     60    def test_form_translation_new_style(self): 
     61        """Form input is translated into properly converted parameters""" 
     62        root = MyRoot() 
     63        cherrypy.root = root 
     64        self.app.get("/testform_new_style?name=ed&date=11/05/2005&age=5&") 
     65        assert root.name == "ed" 
     66        assert root.age == 5 
    7367 
    74 def test_javascript_should_appear(): 
    75     """JavaScript should appear when asked for""" 
    76     testutil.create_request("/") 
    77     assert "calendar.js" in cherrypy.response.body[0] 
     68    def test_invalid_form_with_error_handling(self): 
     69        """Invalid forms can be handled by the method""" 
     70        root = cherrypy.root 
     71        self.app.get("/testform?name=ed&age=edalso&date=11/05/2005") 
     72        assert root.has_errors 
    7873 
    79 def test_include_mochikit(): 
    80     """JSLinks (and MochiKit especially) can be included easily""" 
    81     testutil.create_request("/usemochi") 
    82     assert "MochiKit.js" in cherrypy.response.body[0] 
     74    def test_css_should_appear(self): 
     75        """CSS should appear when asked for""" 
     76        cherrypy.root = MyRoot() 
     77        response = self.app.get("/") 
     78        assert "calendar-system.css" in response 
    8379 
    84 def test_suppress_mochikit(): 
    85     """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] 
    89     # 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 
     80    def test_javascript_should_appear(self): 
     81        """JavaScript should appear when asked for""" 
     82        cherrypy.root = MyRoot() 
     83        response = self.app.get("/") 
     84        assert "calendar.js" in response 
    9585 
    96 def test_mochikit_everywhere(): 
    97     """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] 
     86    def test_include_mochikit(self): 
     87        """JSLinks (and MochiKit especially) can be included easily""" 
     88        cherrypy.root = MyRoot() 
     89        response = self.app.get("/usemochi") 
     90        assert "MochiKit.js" in response 
    10291 
    103 def test_mochikit_nowhere(): 
    104     """Setting tg.mochikit_suppress will prevent including it everywhere""" 
    105     config.update({"global": {"tg.mochikit_all": True}}) 
    106     config.update({"global": {"tg.mochikit_suppress": True}}) 
    107     testutil.create_request("/") 
    108     config.update({"global": {"tg.mochikit_all": False}}) 
    109     config.update({"global": {"tg.mochikit_suppress": False}}) 
    110     assert "MochiKit.js" not in cherrypy.response.body[0] 
     92    def test_suppress_mochikit(self): 
     93        """MochiKit inclusion can be suppressed""" 
     94        cherrypy.root = MyRoot() 
     95        config.update({"global": {"tg.mochikit_suppress": True}}) 
     96        response = self.app.get("/usemochi") 
     97        suppressed_body = response.body 
     98        # repair the fixture 
     99        config.update({"global": {"tg.mochikit_suppress": False}}) 
     100        response = self.app.get("/usemochi") 
     101        included_body = response.body 
     102        assert "MochiKit.js" not in suppressed_body 
     103        assert "MochiKit.js" in included_body 
    111104 
    112 def test_include_widgets(): 
    113     """Any widget can be included everywhere by setting tg.include_widgets""" 
    114     config.update({"global": {"tg.include_widgets": ["mochikit"]}}) 
    115     testutil.create_request("/") 
    116     config.update({"global": {"tg.include_widgets": []}}) 
    117     assert "MochiKit.js" in cherrypy.response.body[0] 
     105    def test_mochikit_everywhere(self): 
     106        """MochiKit can be included everywhere by setting tg.mochikit_all""" 
     107        cherrypy.root = MyRoot() 
     108        config.update({"global": {"tg.mochikit_all": True}}) 
     109        response = self.app.get("/") 
     110        config.update({"global": {"tg.mochikit_all": False}}) 
     111        assert "MochiKit.js" in response 
    118112 
     113    def test_mochikit_nowhere(self): 
     114        """Setting tg.mochikit_suppress will prevent including it everywhere""" 
     115        cherrypy.root = MyRoot() 
     116        config.update({"global": {"tg.mochikit_all": True}}) 
     117        config.update({"global": {"tg.mochikit_suppress": True}}) 
     118        response = self.app.get("/") 
     119        config.update({"global": {"tg.mochikit_all": False}}) 
     120        config.update({"global": {"tg.mochikit_suppress": False}}) 
     121        assert "MochiKit.js" not in response 
    119122 
     123    def test_include_widgets(self): 
     124        """Any widget can be included everywhere by setting tg.include_widgets""" 
     125        cherrypy.root = MyRoot() 
     126        config.update({"global": {"tg.include_widgets": ["mochikit"]}}) 
     127        response = self.app.get("/") 
     128        config.update({"global": {"tg.include_widgets": []}}) 
     129        assert "MochiKit.js" in response 
     130 
     131 
    120132class State(object): 
    121133    counter = 0 
    122134 
  • turbogears/tests/test_errorhandling.py

    old new  
    208208        return dict(title="Nested") 
    209209 
    210210 
    211 class TestErrorHandler(unittest.TestCase): 
     211class TestErrorHandler(testutil.TGWebTest): 
    212212 
    213213    def setUp(self): 
     214        testutil.TGWebTest.setUp(self) 
    214215        cherrypy.root = MyRoot() 
    215216        cherrypy.root.nestedcontroller = NestedController() 
    216217 
    217218    def test_defaultErrorHandler(self): 
    218219        """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]
     220        response = self.app.get("/defaulterror?bar=abc") 
     221        self.failUnless("Default error handler" in response
     222        response = self.app.get("/defaulterror?bar=true") 
     223        self.failUnless("Default error provider" in response
    223224 
    224225    def test_specialisedErrorHandler(self): 
    225226        """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") 
     227        response = self.app.get("/specialisederror?bar=abc&baz=a@b.com") 
     228        self.failUnless("Default error handler" in response
     229        response = self.app.get("/specialisederror?baz=abc&bar=1") 
    229230        self.failUnless("Specialised error handler" in 
    230                         cherrypy.response.body[0]
    231         testutil.create_request("/specialisederror?bar=1&baz=a@b.com") 
     231                        response
     232        response = self.app.get("/specialisederror?bar=1&baz=a@b.com") 
    232233        self.failUnless("Specialised error provider" in 
    233                         cherrypy.response.body[0]
     234                        response
    234235 
    235236    def test_exceptionErrorHandler(self): 
    236237        """Error handler for exceptions.""" 
    237         testutil.create_request("/exceptionerror") 
    238         self.failUnless("Default error handler" in cherrypy.response.body[0]
     238        response = self.app.get("/exceptionerror") 
     239        self.failUnless("Default error handler" in response
    239240 
    240241    def test_recursiveErrorHandler(self): 
    241242        """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") 
     243        response = self.app.get("/recursiveerror?bar=abc") 
     244        self.failUnless("Recursive error handler" in response
     245        response = self.app.get("/recursiveerror?bar=1") 
    245246        self.failUnless("Recursive error provider" in 
    246                         cherrypy.response.body[0]
     247                        response
    247248 
    248249    def test_implicitErrorHandler(self): 
    249250        """Implicit error handling.""" 
    250         testutil.create_request("/impliciterror?bar=abc") 
     251        response = self.app.get("/impliciterror?bar=abc") 
    251252        self.failUnless("Implicit error handler" in 
    252                         cherrypy.response.body[0]
    253         testutil.create_request("/impliciterror?bar=1") 
     253                        response
     254        response = self.app.get("/impliciterror?bar=1") 
    254255        self.failUnless("Implicit error provider" in 
    255                         cherrypy.response.body[0]
     256                        response
    256257 
    257258    def test_normalMethodErrorHandler(self): 
    258259        """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]
     260        response = self.app.get("/normalmethodcaller?bar=abc") 
     261        self.failUnless("Normal method" in response
     262        response = self.app.get("/normalmethodcaller?bar=true") 
     263        self.failUnless("Normal method caller" in response
    263264 
    264265    def test_infiniteRecursionPrevention(self): 
    265266        """Infinite recursion prevention.""" 
    266         testutil.create_request("/infiniteloop") 
    267         self.failUnless("Exception 2" in cherrypy.response.body[0]
     267        response = self.app.get("/infiniteloop") 
     268        self.failUnless("Exception 2" in response
    268269 
    269270    def test_positionalArgs(self): 
    270271        """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]
     272        response = self.app.get("/positionalargs/first/23/third?bar=abc") 
     273        self.failUnless("Default error handler" in response
     274        response = self.app.get("/positionalargs/first/abc/third?bar=false") 
     275        self.failUnless("Default error handler" in response
     276        response = self.app.get("/positionalargs/first/abc/third?bar=abc") 
     277        self.failUnless("Default error handler" in response
     278        response = self.app.get("/positionalargs/first/23/third?bar=true") 
     279        self.failUnless("Positional arguments" in response
    279280        self.failUnless(cherrypy.root.first == "first") 
    280281        self.failUnless(cherrypy.root.second == 23) 
    281282        self.failUnless(cherrypy.root.third == "third") 
    282283 
    283284    def test_missingArgs(self): 
    284285        """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]
     286        response = self.app.get("/missingargs") 
     287        self.failUnless("Default error handler" in response
     288        response = self.app.get("/missingargs?bar=12") 
     289        self.failUnless("Missing args provider" in response
    289290 
    290291    def test_nohandler(self): 
    291292        """No error hanlder declared.""" 
    292         testutil.create_request("/nohandler") 
    293         self.failUnless("Exception raised" in cherrypy.response.body[0]
     293        response = self.app.get("/nohandler") 
     294        self.failUnless("Exception raised" in response
    294295 
    295296    def test_bindArgs(self): 
    296297        """Arguments can be bond to an error handler.""" 
    297         testutil.create_request("/bindargs") 
    298         self.failUnless("123" in cherrypy.response.body[0]
     298        response = self.app.get("/bindargs") 
     299        self.failUnless("123" in response
    299300 
    300301    def test_notExposed(self): 
    301302        """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]
     303        response = self.app.get("/notexposedcaller?foo=a&bar=rab&baz=c") 
     304        self.failUnless("Not exposed error" in response
     305        self.failUnless("rab" in response
    305306 
    306307    def test_continuations(self): 
    307308        """Continuations via error handling mechanism.""" 
    308         testutil.create_request("/continuationcaller?bar=a") 
    309         self.failUnless("Continuation caller" in cherrypy.response.body[0]
     309        response = self.app.get("/continuationcaller?bar=a") 
     310        self.failUnless("Continuation caller" in response
    310311        self.failUnless(cherrypy.root.continuation == True) 
    311312 
    312313    def test_nested(self): 
    313314        """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]
     315        response = self.app.get("/nest?bar=a") 
     316        self.failUnless("Default error handler" in response
     317        response = self.app.get("/nestedcontroller/nest?bar=a") 
     318        self.failUnless("Nested" in response
    318319 
    319320    def test_failsafe(self): 
    320321        """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") 
     322        response = self.app.get("/failsafenone?bar=a&baz=b") 
     323        self.failUnless('"bar": "a"' in response
     324        self.failUnless('"baz": "b"' in response
     325        response = self.app.get("/failsafevaluesdict?bar=a&baz=b") 
     326        self.failUnless('"bar": 1' in response
     327        self.failUnless('"baz": 2' in response
     328        response = self.app.get("/failsafevaluesatom?bar=a&baz=b") 
     329        self.failUnless('"bar": 13' in response
     330        self.failUnless('"baz": 13' in response
     331        response = self.app.get("/failsafemaperrors?bar=a&baz=b") 
    331332        self.failUnless('"bar": "Please enter an integer value"' in 
    332                         cherrypy.response.body[0]
     333                        response
    333334        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]
     335                        response
     336        response = self.app.get("/failsafeformencode?bar=a&baz=b") 
     337        self.failUnless('"bar": 1' in response
     338        self.failUnless('"baz": 2' in response
     339        response = self.app.get("/failsafedefaults?bar=a&baz=b") 
     340        self.failUnless('"bar": 1' in response,response
     341        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, \ 
     12from turbogears.testutil import sqlalchemy_cleanup, TGWebTest, \ 
    1313    capture_log, print_log 
    1414 
    1515 
     
    162162        return "No exceptions occurred" 
    163163 
    164164 
    165 def test_implicit_trans_no_error(): 
    166     """If a controller runs sucessfully, the transaction is commited.""" 
    167     capture_log("turbogears.database") 
    168     cherrypy.root = MyRoot() 
    169     create_request("/no_error?name=A.%20Dent") 
    170     output = cherrypy.response.body[0] 
    171     print output 
    172     print_log() 
    173     q = session.query(Person) 
    174     arthur = q.filter_by(name="A. Dent").first() 
    175     assert 'someconfirmhandler' in output, \ 
    176         'The no error should have redirected to someconfirmhandler' 
    177     assert arthur is not None, 'Person arthur should have been saved!' 
    178     assert arthur.name == "A. Dent", 'Person arthur should be named "A. Dent"' 
     165class TestSQLAlchemy(TGWebTest): 
    179166 
    180 def test_raise_sa_exception(): 
    181     """If a controller causes an SA exception, it is raised properly.""" 
    182     capture_log("turbogears.database") 
    183     cherrypy.root = MyRoot() 
    184     create_request("/create_person?id=20") 
    185     output = cherrypy.response.body[0] 
    186     print_log() 
    187     print output 
    188     assert 'No exceptions occurred' in output 
    189     assert cherrypy.response.status.startswith("200") 
    190     create_request("/create_person?id=20") 
    191     output = cherrypy.response.body[0] 
    192     assert cherrypy.response.status.startswith("500") 
    193     print output 
    194     assert 'KARL25' not in output, \ 
    195         'Exception should NOT have been handled by our handler' 
    196     assert 'DBAPIError' in output, \ 
    197         'The page should have displayed an SQLAlchemy exception' 
     167    def test_implicit_trans_no_error(self): 
     168        """If a controller runs sucessfully, the transaction is commited.""" 
     169        #capture_log("turbogears.database") 
     170        cherrypy.root = MyRoot() 
     171        response = self.app.get("/no_error?name=A.%20Dent") 
     172        output = response.body 
     173        #print output 
     174        #print_log() 
     175        q = session.query(Person) 
     176        arthur = q.filter_by(name="A. Dent").first() 
     177        assert 'someconfirmhandler' in output, \ 
     178            'The no error should have redirected to someconfirmhandler' 
     179        assert arthur is not None, 'Person arthur should have been saved!' 
     180        assert arthur.name == "A. Dent", 'Person arthur should be named "A. Dent"' 
    198181 
    199 def test_user_exception(): 
    200     """If a controller raises an exception, transactions are rolled back.""" 
    201     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] 
    205     print_log() 
    206     print output 
    207     assert 'KARL25' in output, \ 
    208         'The exception handler should have answered us' 
    209     p = session.query(Person).get(19) 
    210     assert p is None, \ 
    211         'This Person should have been rolled back: %s' % p 
     182    def test_raise_sa_exception(self): 
     183        """If a controller causes an SA exception, it is raised properly.""" 
     184        #capture_log("turbogears.database") 
     185        cherrypy.root = MyRoot() 
     186        response = self.app.get("/create_person?id=20", status=200) 
     187        output = response.body 
     188        #print_log() 
     189        print output 
     190        assert 'No exceptions occurred' in output 
     191        response = self.app.get("/create_person?id=20", status=500) 
     192        output = response.body 
     193        print output 
     194        assert 'KARL25' not in output, \ 
     195            'Exception should NOT have been handled by our handler' 
     196        assert 'DBAPIError' in output, \ 
     197            'The page should have displayed an SQLAlchemy exception' 
    212198 
    213 def test_user_redirect(): 
    214     """If a controller redirects, transactions are committed.""" 
    215     cherrypy.root = MyRoot() 
    216     create_request("/create_person?id=22&doerr=2") 
    217     assert session.query(Person).get(22) is not None, \ 
    218         'The controller only redirected, the Person should have been saved' 
     199    def test_user_exception(self): 
     200        """If a controller raises an exception, transactions are rolled back.""" 
     201        #capture_log("turbogears.database") 
     202        cherrypy.root = MyRoot() 
     203        response = self.app.get("/create_person?id=19&docom=0&doerr=1&name=Martin%20GAL") 
     204        output = response.body 
     205        #print_log() 
     206        print output 
     207        assert 'KARL25' in output, \ 
     208            'The exception handler should have answered us' 
     209        p = session.query(Person).get(19) 
     210        assert p is None, \ 
     211            'This Person should have been rolled back: %s' % p 
    219212 
    220 def test_cntrl_commit(): 
    221     """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] 
    225     assert session.query(Person).get(23) is not None, \ 
    226         'The Person 23 should have been saved during commit inside controller' 
     213    def test_user_redirect(self): 
     214        """If a controller redirects, transactions are committed.""" 
     215        cherrypy.root = MyRoot() 
     216        self.app.get("/create_person?id=22&doerr=2") 
     217        assert session.query(Person).get(22) is not None, \ 
     218            'The controller only redirected, the Person should have been saved' 
    227219 
    228 def test_cntrl_commit2(): 
    229     """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] 
    233     assert session.query(Person).get(24) is not None, \ 
    234         'The Person 24 should have been saved during commit' \ 
    235         ' inside controller and not rolled back' 
     220    def test_cntrl_commit(self): 
     221        """It's safe to commit a transaction in the controller.""" 
     222        cherrypy.root = MyRoot() 
     223        response = self.app.get("/create_person?id=23&docom=1") 
     224        assert 'InvalidRequestError' not in response 
     225        assert session.query(Person).get(23) is not None, \ 
     226            'The Person 23 should have been saved during commit inside controller' 
    236227 
    237 def test_cntrl_flush(): 
    238     """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] 
     228    def test_cntrl_commit2(self): 
     229        """A commit inside the controller is not rolled back by the exception.""" 
     230        cherrypy.root = MyRoot() 
     231        response = self.app.get("/create_person?id=24&docom=1&doerr=1") 
     232        assert 'InvalidRequestError' not in response 
     233        assert session.query(Person).get(24) is not None, \ 
     234            'The Person 24 should have been saved during commit' \ 
     235            ' inside controller and not rolled back' 
    252236 
     237    def test_cntrl_flush(self): 
     238        """It's safe to flush in the controller.""" 
     239        cherrypy.root = MyRoot() 
     240        response = self.app.get("/create_person?id=25&doflush=1") 
     241        assert 'No exceptions occurred' in response 
     242        response = self.app.get("/create_person?id=25&doflush=0", status=500) 
     243        assert 'IntegrityError' in response 
     244        response = self.app.get("/create_person?id=25&doflush=1") 
     245        assert 'IntegrityError' in response 
     246        response = self.app.get("/create_person?id=25&doflush=2") 
     247        assert 'No exceptions occurred' in response 
    253248 
     249 
    254250# Exception handling with rollback 
    255251 
    256252class RbRoot(RootController): 
     
    292288            session.rollback() 
    293289        raise Exception('test') 
    294290 
     291class TestExceptionRollback(TGWebTest): 
    295292 
    296 def test_exc_rollback(): 
    297     """An exception within a controller method causes a rollback. 
     293    def test_exc_rollback(self): 
     294        """An exception within a controller method causes a rollback. 
    298295 
    299     Try to create a user that should rollback because of an exception 
    300     so user 25 should not exist, but user 26 should be present since it 
    301     is created by the exception handler. 
     296        Try to create a user that should rollback because of an exception 
     297        so user 25 should not exist, but user 26 should be present since it 
     298        is created by the exception handler. 
    302299 
    303     """ 
    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' 
    309     assert session.query(User).get(26) is None 
    310     assert session.query(User).get(27) is not None 
     300        """ 
     301        cherrypy.root = RbRoot() 
     302        response = self.app.get('/doerr?id=26') 
     303        assert 'KARL27' in response, 'Exception handler should have answered' 
     304        assert session.query(User).get(26) is None 
     305        assert session.query(User).get(27) is not None 
    311306 
    312 def test_exc_rollback2(): 
    313     """An exception within a controller method causes a rollback. 
     307    def test_exc_rollback2(self): 
     308        """An exception within a controller method causes a rollback. 
    314309 
    315     Try to create a user that should rollback because of an exception 
    316     so user XX should not exist. 
     310        Try to create a user that should rollback because of an exception 
     311        so user XX should not exist. 
    317312 
    318     """ 
    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' 
    323     assert session.query(User).get('XX') is None 
     313        """ 
     314        cherrypy.root = RbRoot() 
     315        response = self.app.get('/doerr?id=XX') 
     316        assert 'KARL27' in response, 'Exception handler should have answered' 
     317        assert session.query(User).get('XX') is None 
    324318 
    325 def test_exc_done_rollback(): 
    326     """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' 
    331     assert session.query(User).get(28) is None 
    332     assert session.query(User).get(29) is not None 
     319    def test_exc_done_rollback(self): 
     320        """No problems with error handler if controller manually rollbacks.""" 
     321        cherrypy.root = RbRoot() 
     322        response = self.app.get('/doerr?id=28&dorb=1') 
     323        assert 'KARL27' in response, 'Exception handler should have answered' 
     324        assert session.query(User).get(28) is None 
     325        assert session.query(User).get(29) is not None 
    333326 
    334327 
    335328# Session freshness tests 
     
    352345        assert session.query(Test).get(1).val == 'b' 
    353346        return dict() 
    354347 
     348class TestSessionFreshness(TGWebTest): 
    355349 
    356 def test_session_freshness(): 
    357     """Check for session freshness. 
     350    def test_session_freshness(self): 
     351        """Check for session freshness. 
    358352 
    359     Changes made to the data in thread B should be reflected in thread A. 
     353        Changes made to the data in thread B should be reflected in thread A. 
    360354 
    361     """ 
    362     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] 
    367     # Call test2 in a different thread 
    368     class ThreadB(threading.Thread): 
    369         def run(self): 
    370             create_request("/test2") 
    371             assert cherrypy.response.status.startswith("200") 
    372             assert 'AssertionError' not in cherrypy.response.body[0] 
    373     thrdb = ThreadB() 
    374     thrdb.start(
    375     thrdb.join() 
    376     create_request("/test3"
    377     assert cherrypy.response.status.startswith("200") 
    378     assert 'AssertionError' not in cherrypy.response.body[0] 
     355        """ 
     356        test_table.insert().execute(dict(id=1, val='a')) 
     357        cherrypy.root = FreshRoot() 
     358        response = self.app.get("/test1") 
     359        assert 'AssertionError' not in response 
     360        # Call test2 in a different thread 
     361        class ThreadB(threading.Thread): 
     362            def __init__(self, app): 
     363                threading.Thread.__init__(self) 
     364                self.app = app 
     365            def run(self): 
     366                response = self.app.get("/test2") 
     367                assert 'AssertionError' not in response 
     368        thrdb = ThreadB(app=self.app
     369        thrdb.start() 
     370        thrdb.join(
     371        response = self.app.get("/test3") 
     372        assert 'AssertionError' not in response 
  • turbogears/tests/test_expose.py

    old new  
    11import cherrypy 
    22import simplejson 
    33 
    4 from turbogears import controllers, expose 
    5 from turbogears.testutil import create_request 
     4from turbogears import controllers, expose, testutil 
    65 
    76 
    87class ExposeRoot(controllers.RootController): 
     
    1918        return dict(title="Foobar", mybool=False, someval="foo") 
    2019 
    2120 
    22 def test_gettinghtml(): 
    23     cherrypy.root = ExposeRoot() 
    24     create_request("/with_json") 
    25     body = cherrypy.response.body[0] 
    26     assert "Paging all foo" in body 
     21class TestExposeRoot(testutil.TGWebTest): 
    2722 
    28 def test_gettingjson(): 
    29     cherrypy.root = ExposeRoot() 
    30     create_request("/with_json?tg_format=json") 
    31     body = cherrypy.response.body[0] 
    32     assert '"title": "Foobar"' in body 
     23    def test_gettinghtml(self): 
     24        cherrypy.root = ExposeRoot() 
     25        response = self.app.get("/with_json") 
     26        assert "Paging all foo" in response 
    3327 
    34 def test_gettingjsonviaaccept(): 
    35     cherrypy.root = ExposeRoot() 
    36     create_request("/with_json_via_accept", 
    37             headers=dict(Accept="text/javascript")) 
    38     body = cherrypy.response.body[0] 
    39     assert '"title": "Foobar"' in body 
     28    def test_gettingjson(self): 
     29        cherrypy.root = ExposeRoot() 
     30        response = self.app.get("/with_json?tg_format=json") 
     31        assert '"title": "Foobar"' in response 
    4032 
    41 def test_getting_json_with_accept_but_using_tg_format(): 
    42     cherrypy.root = ExposeRoot() 
    43     create_request("/with_json_via_accept?tg_format=json") 
    44     body = cherrypy.response.body[0] 
    45     assert '"title": "Foobar"' in body 
     33    def test_gettingjsonviaaccept(self): 
     34        cherrypy.root = ExposeRoot() 
     35        response = self.app.get("/with_json_via_accept", 
     36                headers=dict(Accept="text/javascript")) 
     37        assert '"title": "Foobar"' in response 
    4638 
    47 def test_getting_plaintext(): 
    48     cherrypy.root = ExposeRoot() 
    49     create_request("/with_json_via_accept", 
    50         headers=dict(Accept="text/plain")) 
    51     print cherrypy.response.body[0] 
    52     assert cherrypy.response.body[0] == "This is a plain text for foo." 
     39    def test_getting_json_with_accept_but_using_tg_format(self): 
     40        cherrypy.root = ExposeRoot() 
     41        response = self.app.get("/with_json_via_accept?tg_format=json") 
     42        assert '"title": "Foobar"' in response 
    5343 
    54 def test_allow_json(): 
     44    def test_getting_plaintext(self): 
     45        cherrypy.root = ExposeRoot() 
     46        response = self.app.get("/with_json_via_accept", 
     47                headers=dict(Accept="text/plain")) 
     48        assert response.body == "This is a plain text for foo." 
    5549 
    56     class NewRoot(controllers.RootController): 
    57         @expose(template="turbogears.tests.doesnotexist", allow_json=True) 
    58         def test(self): 
    59             return dict(title="Foobar", mybool=False, someval="niggles") 
     50    def test_allow_json(self): 
    6051 
    61     cherrypy.root = NewRoot() 
    62     create_request("/test", headers= dict(accept="text/javascript")) 
    63     body = cherrypy.response.body[0] 
    64     values = simplejson.loads(body) 
    65     assert values == dict(title="Foobar", mybool=False, someval="niggles", 
    66         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) 
    71     assert values == dict(title="Foobar", mybool=False, someval="niggles", 
    72         tg_flash=None) 
    73     assert cherrypy.response.headers["Content-Type"] == "text/javascript" 
     52        class NewRoot(controllers.RootController): 
     53            @expose(template="turbogears.tests.doesnotexist", allow_json=True) 
     54            def test(self): 
     55                return dict(title="Foobar", mybool=False, someval="niggles") 
     56 
     57        cherrypy.root = NewRoot() </