TestCase helpers

 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 4 years, 8 months ago
  2. Django load global fixtures test helper by vaz 2 years, 8 months ago
  3. sql to dict by amitu 5 years ago
  4. change settings locally in an individual test by akaihola 3 years, 8 months ago
  5. local django test by jedie 6 years, 10 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...

#

(Forgotten your password?)