Archive for December, 2008

Testing Your Cherrypy App

December 7th, 2008 by ScottK | No Comments | Filed in CherryPy

When I started with CherryPy, luckily 3.1, I not only needed to learn how to work with it but also test my app as well. Others where using Nose and Twill with some success, the problem the other testing frameworks had seemed to surround the controller tests.

I discovered the testing framework within CherryPy and easily pulled it out to test my apps. There has never been a problem testing controllers, models, modules, etc. That is the what this CherryPy Example 4 is all about, testing your CherryPy app. You can find the follow along example here.

All the test case files will have to incorporate the cherrpy.test.helper class. This is in order for each of your test classes that must inherit the helper.CPWebCase class.

Controller Testing:

In the example program refer to the users_controller.py

@cherrypy.expose
    def index(self, format='html', **kwargs):
        if format == 'js':
            cherrypy.response.headers['Content-Type'] = "application/javascript"
            return "alert('format in JavaScript for index');"
        elif format == "xml":
            cherrypy.response.headers['Content-Type'] = "application/xml"
            return "Index"
        else:
            return "This is the Index in HTML"

This is the index action of the controller. We need to test it to make sure that it not only responds with XML/HTML/JavaScript accordingly.

def testIndexUSersWithXML(self):
    self.getPage("/users.xml", method='GET')
    self.assertStatus('200 OK')
    self.assertBody('Index')

def testIndexUSersWithHTML(self):
    self.getPage("/users", method='GET')
    self.assertStatus('200 OK')
    self.assertBody('This is the Index in HTML')

self.getPage is the call to the actively running application. assertStatus assures us that everything went ok. Of course you can also assert the other status as needed. assertBody test must match the entire response body. Generally I use assertInBody to make sure that what I’m looking for was returned rather than the whole response.

Prior to running the controller tests the controller does need to be registered with the dispatch. I’m still using the route_mapper as in CherryPy Example 3. So at the top of the controller test files I’ll include:

def setup_server():
    routes = [{"name" : "user", "path" : "user", "controller" : UsersController()}]

    conf = {'/': {
                    'request.dispatch' : rm.setup_routes(routes)
                 }
            }

    cherrypy.tree.mount(root=None, config=conf)

Then at the bottom of the file:

if __name__ == "__main__":

    setup_server()
    helper.testmain() //This calls for the program to run.

Outside of controllers, testing objects is pretty straight forward: assertEqual; assertNotEqual, etc. Again making sure that each test class inherits from helper.CPWebCase. test_user_model has the examples for testing a model.

As your application and test cases grows it becomes rather painful to keep running each file independently. I did this for a while with two dozen test files. Longing for a test runner I once again referred to the CherryPy module to see if they had something that would do this.

Sure enough the cherrypy.test has the method to run all your tests at once. However it required me to copy it and modify it. in the example tests folder you’ll find the test.py. This is the modified version of the cherrypy.test file.

The notable modification has to deal with the run function. Originally it contained a list of all the test cases to run at once. While this made it good as a test runner I also wanted to run singles as I was working on the model itself. So with the modification of test=None in the argument you can run the entire suite or just one test.

python test.py //Entire suite
pytnon test.py test_user_model //just the test_user_model.py file

All these tests are designed to be run in the tests folder using python test.py.

Testing CherryPy apps is really easy if you incorporate the CherryPy test suite. The мебелиCherryPy Example 4 has the necessary files in the tests folder to run them.

jsFactory for Building Quick JavaScript Objects With States

December 6th, 2008 by ScottK | No Comments | Filed in JavaScript

I know of , and use, two systems that allows me to test my JavaScript: jsUnit for Test Driven Development and JsSpec for Behavior Driven Development. I find that in order to setup the object in question I lacked the ability to quickly create objects in the states or values that I needed. So more lines where devoted to building the objects than actually needed to test them. This got rather menial.

I though to myself one day, why can’t JavaScript have a quick way to create objects or even DOM elements quickly and in the state that I need them in; other languages have this ability for testing.

So I created jsFactory and it allows me to call the jsFactory class with the name of the object I needed, filled in with my pre-defined field values as well as any special values. I has allowed me more time to test than build objects over an over again for testing.

It has become such an important library for me I want to give this out to everyone that are interested. You can download the library and example files here. jsFactory

Testing without jsFactory would look like this:

function build_person() {
    person = new Person();
    person._firstName  = "Scott";
    person._lastName = "Krutsinger";
    return person;
}

function testPerson() {
    person1 = build_person();
    //Get a second object to test against
    person2 = build_person();
    person2._firstName = "Marvin";
    person2._lastName = "Martian";
    //Test code
}

The function build_person does return a Person object in the state that we need, but when we need another person object then we still have to modify the field values. Which isn’t necessary with jsFactory:

function build_person() {
    return {
        _firstName : "Scott",
        _lastName : "Krutsinger"
    };
}

function testPerson() {
    person1 = jsFactory.create("Person");
    //Get a second object to test against
    person2 = jsFactory.create("Person", {"_firstName" : "Marvin", "_lastName" : "Martian"});
    //Test code
}

jsFactory is there to help us build objects in the testing state we need, whether this is predefined or specialized as we need. When the create method is called on jsFactory it goes through two processes: default field attribute assignment then the assignment of any fields that where present as arguments. jsFactory doesn’t actually care that it is being used in testing so using it for quick object builds in production code is also a way to use it as well.

jsFactory has another function included to build DOM elements quickly.

my_anchor = jsFactory.createHtmlElement("a", {"href" : "http://www.techraving.com", "target" : "_blank"});

my_anchor is a DOM element that I can use for testing or used in my application.  You can even specify that the created element attach itself to another element by id or the object alone:

div1_element = jsFactory.createHtmlElement("div", {"id" : "div1"});

//attach by id
my_anchor1 = jsFactory.createHtmlElement("a", {"href" : "http://www.techraving.com", "target" : "_blank"}, "div1");

//attach by element
my_anchor2 = jsFactory.createHtmlElement("a", {"href" : "http://www.techraving.com", "target" : "_blank"}, div1_element);

//div1 now has both my_anchor 1 & 2 as child elements!

Use this link to download JsFactory . It contains the jsFactory class as well as example for us. jsFactory has let me concentrate more on testing objects than building them and I hope it does the same for you.

Shouting From The Clouds

December 2nd, 2008 by ScottK | 1 Comment | Filed in JavaScript

A few months ago in Orlando a new idea in transportable widgets was introduced to the developer community. The name of this concept is CloudShout . During this years IZEAFest , CloudShout has developed into a fully functional system and introductory keys were given out to not only developers but blog owners as well.

Being in closed alpha at the moment CloudShout is once again opening looking for more developers and blog operators. Thus allowing me to give out invite keys to those that are interested.

Anyone who surfs, blogs, or develops for the web would find CloudShout highly useful. The idea behind the transportable widget is that you can go from site to site with a set of applications that you or others can use. Instant messaging, LastFM, even a nice game of checkers!

From the surfers point of view they would be able to instant message friends that are also online; as long as both are on CloudShout equipped sites. With your apps in hand you can extend your user experience in real time communication with your friends or the other site visitors.

The first site to adopt CloudShout is SocialSpark and since CloudShout is in closed alpha registration must be done at SocialSpark to gain the full profile potential.

After setting up a blogger profile you can simply surf about your business. Upon happening on a CloudShout equipped site you’ll notice your display name as well as other registered users. The nice thing is through polling requests you can watch others come and go from the site. Contact these users as you wish in a variety of ways.

Each user can choose from several applications to install to increase your or others enjoyment. The big benefit here is that you can install any apps on any CloudShout equipped site you are on. When viewing the profile of a person you can choose to install apps that they have and you want; never leaving the site you are on.

As a blog operator it’s nice to be able to instantly communicate with your visitor as they come and go. Visitors can leave you messages apart from comments, and the benefit of not exposing the owners email address as well. Blog specific apps can be installed, yes via the site, that will potentially have visitors stay longer.

For developers this is another opportunity to get your name out. Just as Netvibes, iPhone, Nokia, Facebook, etc, allow developers to create applications for their community to use, CloudShout is no exception. Using a predefined widget architecture developers can quickly develop applications and submit applications. After a review process the application, if approved, would be made available to the community at large.

I have keys to give out to those interested in developing and or using CloudShout as it is still in closed alpha. Leave me a comment and I will send keys out to the email you leave.

Tags: , , , ,