Skip to:

Tiago Cogumbreiro

O Irrepupável

Back to top

HTML Testing Friendly Functions

Following my thoughts yesterday I implemented the rest of it. Which basically means that I implemented a function responsible for submiting data to forms programatically. Its use cases are obvious, forms are usually what you want to test. This is its signature:

def form_submit(url, data, strip_data=True, by_index=0,
by_name=None)
And here is the test case associated with this function:
class SubmitRoot:
    @cherrypy.expose
    def index(self, **kwargs):
        self.form = kwargs
        return """
        <html>
<form method="GET"> <input type="text" name="username" /> <input type="text" name="password" /> <input type="hidden" name="id" value="12&amp;" /> <input type="submit" /> </form> </body></html> """ cherrypy.root = SubmitRoot() class TestFormSubmit(unittest.TestCase): def setUp(self): self.server = cherrypy.root def test_form_submit(self): url = "http://localhost:8080/" page = browse_url(url) assert page is not None assert page["data"] is not None page = form_submit(url, {"username": "foo", "password": "bar"}) self.assertEqual(self.server.form, {"username": "foo", "password": "bar", "id": "12&"}) if __name__ == '__main__': cherrypy.server.start_with_callback(unittest.main)

In the tests I use the browse_url and form_submit function. The problem is, we're missing cookies and page redirections. Another thing that's missing is javascript related, this probably needs another tool. To sum it up, with BeautifulSoup and the function I just written you can do some simple and effective web development.

And finally an example on a simple test app:

class TestRoot(unittest.TestCase):
    def test_index(self):
        cherrypy.root = Root()
        page = browse_url(URL % "/")
        soup = BeautifulSoup(page["data"])
        count = len(soup("div", {"class": "blog_entry"}))
        self.assertEqual(count, len(list(BlogEntry.select())))
        page = form_submit(URL % "/", {"title": "entry created from
test", "description": "entry created from test (description)"})
        soup = BeautifulSoup(page["data"])
        count2 = len(soup("div", {"class": "blog_entry"}))
        self.assertEqual(count2, len(list(BlogEntry.select())))
        self.assertEqual(count, count2)

Here's an interesting post from Ian Bicking which has some notes about the same problem.


Back to top