Login

TestCase helpers

Author:
pbx
Posted:
March 27, 2007
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 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.