Friday, March 11, 2011

response status unit testing in pylons

controller code:
--------------------------------------------------------------------------
import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to

from samplebundle.lib.base import BaseController, render

log = logging.getLogger(__name__)

class WebflowcontrolsController(BaseController):

    def redirect_to_action(self):
        # Return a rendered template
        #return render('/webredirects.mako')
        # or, return a response
        redirect_to(controller='webflowcontrols', action='redirect_target')

    def redirect_target(self):
        # Return a rendered template
        #return render('/webredirects.mako')
        # or, return a response
        return 'redirect target'
    
    def abort_action(self, id):
        # Return a rendered template
        #return render('/webredirects.mako')
        # or, return a response
        if id == '404':
            abort(status_code=404)
        elif id == '400':
            abort(status_code=400)
        else:
            return "not abort"


unit testing code:
--------------------------------------------------------------------------
from samplebundle.tests import *

class TestWebflowcontrolsController(TestController):

    def test_redirect_to_action(self):
        response = self.app.get(url(controller='webflowcontrols', action='redirect_to_action'))
        assert not 'redirect target' in response
        assert '/webflowcontrols/redirect_target' in response.location
        assert 302 == response.status_int
        # Test response...

    def test_abort_action(self):
        #'status' is the integer status code you expect.
        #If you expect a 404 response, for instance, 
        #you must give status=404 or it will be an error.
        response = self.app.get(url(controller='webflowcontrols', 
                                    action='abort_action', 
                                    id="404"),
                                status=404
                                )
        assert response.status_int == 404

        response = self.app.get(url(controller='webflowcontrols', 
                                    action='abort_action', 
                                    id="400"),
                                status='*'
                                )
        assert response.status_int == 400

No comments:

Post a Comment