Python Web Framework Series – Pylons: Part 2 Controllers, Views and Testing

We last left off with Getting Started and having created our “pylonsforum” project and generated our first controller.

Source for home.py

import logging 

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

from pylonsforum.lib.base import BaseController, render 

log = logging.getLogger(__name__) 

class HomeController(BaseController): 

    def index(self): 
        # Return a rendered template 
        #return render(‘/home.mako’) 
        # or, return a response 
        return ‘Hello World

Source for test_home.py

 

from pylonsforum.tests import * 

class TestHomeController(TestController): 

    def test_index(self): 
        response = self.app.get(url(controller=‘home’, action=‘index’)) 
        # Test response…

 

 

Some Testing Setup

Now this is optional but these are some things I got out of the Pylons Book with test setup, mainly I wanted to refresh the test database on every go.

first open up test.ini in the top level of your project and change the [app:main] section to the following:


 

[app:main]
#use = config:development.ini
use = egg:pylonsforum
full_stack = true
cache_dir = % (here)s/data
beaker.session.key = pylonsforum
beaker.session.secret = somesecret

sqlalchemy.url = sqlite:///%(here)s/test.db

 

 


Then open up websetup.py in the pylonsforum directory and change it to so:

“”"Setup the pylonsforum application”"”
import logging
from pylonsforum import model
import os.path

from pylonsforum.config.environment import load_environment

log = logging.getLogger(__name__)

def setup_app(command, conf, vars):
    load_environment(conf.global_conf, conf.local_conf)
    # Load the models
    from pylonsforum.model import meta
    meta.metadata.bind = meta.engine
    filename = os.path.split(conf.filename)[-1]
    if filename == ‘test.ini’:
        # Permanently drop any existing tables
        log.info(“Dropping existing tables…”)
        meta.metadata.drop_all(checkfirst=True)
    # Continue as before
    # Create the tables if they aren’t there already
    meta.metadata.create_all(checkfirst=True)
    log.info(“Successfully set up.”)

 

 

this will ensure a proper refresh of the database each time you run a test.

 

Testing

Now that we’re setup lets get onto testing (test first).

So far my study has found pylons to emphasize functional tests over unit tests. Hopefully, those with more experience will correct me. On the plus side nothing is stopping you from unit tests, and the functional test support is really nice giving you access to the response object including your view.

The response object there will let you examine the html returned based on the conditions you’ve set. lets not get to advanced yet and just change test_index to look for a specific page title so change the test_index test to the following

  def test_index_title(self):
      response = self.app.get(url(controller=‘home’, action=‘index’))
      assert “<title>Pylons Forum</title>” in response
      # Test response…

so what we have here is a test asserting that our web response is able to find “<title>Pylons Forum</title>” in the page somewhere. running the following command from the top level directory where test.ini is located:

nosetests --with-pylons=test.ini

will results in the following failed test result:

 Picture 2

Controller and view review

Pylons has a return based controller/action behavior. So it can return a number of objects for now we can focus on raw text and rendering a view.

As you can see from the comments rendering a view is as simple as placing one in the template directory

edit home.py index action to look like so:

 

  def index(self):
    return render(‘index.mako’)

 

 

then create a file in the templates directory called index.mako that looks like so

 

<!DOCTYPE html PUBLIC ”-//W3C//DTD XHTML 1.0 Transitional//EN” ”http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<head>
<title>Pylons Forum</title>
</head>
<body>
<div id=“recentposts” style=“float: right” >
<table>
<thead><tr><th>subject</th><th>author</th><th>date submitted</th></tr></thead>
<tbody>
<tr><td>jkruse</td><td>Re: Whats Up</td><td>06/01/2009</td></tr>
<tr><td>rsvihla</td><td>Whats Up</td><td>06/01/2009</td></tr>
<tr><td>thondo</td><td>Re: Looking for new work</td><td>05/25/2009</td></tr>
<tr><td>jkruse</td><td>Re: Looking for new work</td><td>5/20/2009</td></tr>
<tr><td>usmith</td><td>Looking for new work</td><td>05/01/2009</td></tr>
</tbody>
</table>
</div>
</body>

 

 

Now that we’ve created our view and our action rendering said view, lets run our test again and see what we get:

Picture 4

 

In Closing

This whirlwind tour of testing, views and controllers is at an end. Stay tuned for more in depth coverage of controllers and views in the next post.

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Ryan Svihla

I consider myself a full stack polyglot, and I have been writing a lot of JS and Ruby as of late. Currently, I'm a solutions architect at DataStax
This entry was posted in Pylons, Python. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • mhanney

    Thank you for documenting your Pylons study Ryan. This is great stuff! I’m very much looking forward to the rest of the series.

    What is your motivation for looking at Pylons on Windows? Open source, new/alternative perspectives, dissatisfaction with the ASP.NET web frameworks, migrating away from a Windows Web Platform, forced to deploy on Windows but prefer to code in Python, or some other reason entirely?

    Thanks,
    Michael.

  • http://www.lostechies.com/members/rssvihla/default.aspx Ryan Svihla

    @mhanney

    Its for the audience largely. Most of this blog community and viewer base has a .Net bent.

    I was a Nix (FreeBSD and several flavors of Linux) sysadmin for several years before I learned .Net, so I’ve always enjoyed Python from a systems administration perspective.

    Approaching it with the eyes of a software developer has been entertaining for me and also why I’m focusing on Python Web Frameworks for the time being in my home play time.

    Thanks for the comment!

  • http://rajaseelan.com Raja

    Holy Cow!!! Good stuff man. I just bought the Pylons Book, but this seems to be a good summary before I start w/ the book :)