Testing modules within cherrypy

I was wondering how unittests may be implemented within cherrypy to test not cherrypy itself but the modules included. I wanted tests to be run every time when new changes were introduced, that means when the server reloads.

There are some information about unittesting in cherrypy (e.g. https://stackoverflow.com/questions/14260101/unittesting-cherrypy-webapp), however, none directly addressed my issue.

I decided to prepare single file named unittests.py (remember not to name your file as unittest.py as there will be problem with library import) with unittests and TextTestRunner setup. TextTestRunner does not interrupt the reload of the server as standard unittest.main() does.

import unittest
from module import function1, function2

class MyTestClass(unittest.TestCase):

    def test_search(self):
        self.assertEqual(function1(input1), output1)
        self.assertEqual(function2(input2), output2)

def start():
    suite = unittest.TestSuite()
    runner = unittest.TextTestRunner()

and in the main cherrypy file, besides import, I added single line (unittests.start()):

import unittests

if __name__ == "__main__":
    cherrypy.quickstart(Page(), config="config.conf")

Every time the server reloaded the tests were run and I could check whether everything is correct.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s