Login

TestCase helpers

Author:
pbx
Posted:
March 27, 2007
Language:
Python
Version:
.96
Tags:
testing tests unittest
Score:
10 (after 10 ratings)

I use these helper methods in my unit tests. They turn many simple getting-and-posting tests into one-liners. Definitely a work in progress, and I can't be the only person who has done this sort of thing -- comments are more than welcome.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from django.test import TestCase
from django.test.client import Client

class ClientTest(TestCase):
    """
    Small test suite to demonstrate helper methods.
    You'd probably want to abstract these to your own subclass
    of django.test.TestCase so you could import and use it in
    each of your tests.py files.
    """

    def setUp(self):
        """This method is automatically called by the Django test framework."""
        self.client = Client()

    def GET(self, url, status=200, mimetype="text/html"):
        """Get a URL and require a specific status code before proceeding"""
        response = self.client.get(url)
        self.failUnlessEqual(response.status_code, status)
        self.failUnless(response.headers['Content-Type'].startswith(mimetype))
        return response

    def POST(self, url, params, status=200, mimetype="text/html"):
        """Make a POST and require a specific status code before proceeding"""
        response = self.client.post(url, params)
        self.failUnlessEqual(response.status_code, status)
        self.failUnless(response.headers['Content-Type'].startswith(mimetype))
        return response

    def test_examples(self):
        # Here we expect a 200 response, so we don't need to specify
        self.GET("/")
        # Here we specify we're looking for a 404
        self.GET("/boguspath/", status=404)
        # Here we're also interested in the mimetype
        self.GET("/robots.txt", mimetype="text/plain")
        # Here we test a post and see whether it redirects on success.
        sample = {
            'name': "Bob the Builder",
            'slogan': "Yes we can!",
            }
        response = self.POST("/", sample, status=302)
        # We'd also want to inspect the response to see *where* it
        # redirects to, etc.

More like this

  1. Choices helper by jacobian 5 years, 8 months ago
  2. Django load global fixtures test helper by vaz 3 years, 9 months ago
  3. sql to dict by amitu 6 years, 1 month ago
  4. Testing email sending by monikasulik 2 months ago
  5. change settings locally in an individual test by akaihola 4 years, 8 months ago

Comments

eopadoan (on June 4, 2007):

You can even add some shortcut methods like assertCanBeFound(url), assertTemporaryMoved(url), assertPermanentlyMoved(url), assertOKResponse(url), etc...

#

Please login first before commenting.