how to write django test meant to fail?

If you're expecting Thing(name='1234') to raise an exception, there are two ways to deal with this.

One is to use Django's assertRaises (actually from unittest/unittest2):

def mytest(self):
    self.assertRaises(FooException, Thing, name='1234')

This fails unless Thing(name='1234') raises a FooException error. Another way is to catch the expected exception and raise one if it doesn't happen, like this:

def mytest(self):
    try:
        thing = Thing(name='1234')
        self.fail("your message here")
    except FooException:
        pass

Obviously, replace the FooException with the one you expect to get from creating the object with too long a string. ValidationError?

A third option (as of Python 2.7) is to use assertRaises as a context manager, which makes for cleaner, more readable code:

def mytest(self):
    with self.assertRaises(FooException):
        thing = Thing(name='1234')

Sadly, this doesn't allow for custom test failure messages, so document your tests well. See https://hg.python.org/cpython/file/2.7/Lib/unittest/case.py#l97 for more details.


In my previous project i had to do something like test driven development, so i have written some test case which must catch certain types of error. If it don't gets the error then i have messed up something. Here i share my code.

from django.test import TestCase
from django.contrib.auth.models import User

class ModelTest(TestCase):

def test_create_user_with_email(self):

    with self.assertRaises(TypeError):
        email = "[email protected]"
        password = 'testpass1'

        user = User.objects.create_user(
            email = email,
            password = password,)

        self.assertEqual(user.email, email)
        self.assertTrue(user.check_password(password))

You can see i have tried to create a user with email and password but default Django user model need "username" and "password" arguments to create user. So here my testcase must raise "TypeError". And that what i tried to do here.