views:

460

answers:

2

I have defined a custom error but if I test if custom error gets raised, it fails.

My models.py:

class CustomError(Exception):
    """
    This exception is my custom error
    """

class Company(models.Model):
    name = models.CharField(max_length=200)

    def test_error(self):
    raise CustomError('hello')

and in my tests.py:

import unittest
from myapp.models import Company,Customer,Employee,Location,Product,ProductCategory,AllreadyPayedError,CustomError

class CompanyTestCase(unittest.TestCase):
    def setUp(self):
        self.company = Company.objects.create(name="lizto")

    def test2(self):
        self.assertRaises(CustomError, self.company.test_error)

The test fails with this output: ====================================================================== ERROR: test2 (myapp.api.tests.CompanyTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/......./tests.py", line 27, in test2 self.assertRaises(CustomError, self.company.test_error) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/unittest.py", line 320, in failUnlessRaises callableObj(*args, **kwargs) File " /Users/....../models.py", line 17, in test_error raise CustomError('hello') CustomError: hello

----------------------------------------------------------------------
Ran 18 tests in 1.122s

Anybody an idea what I should do to test if CustomError gets raised

+1  A: 

You could catch the error and assert that it occured.

eg: (untested)

def test2(self)
    error_occured = False
    try:
        self.company.test_error()
    except CustomError:
        error_occured = True

    self.assertTrue(error_ocurred)

Seems far from ideal but would unblock you.

Andy Hume
A: 

Thanks Andy for your answer the problem was however that I was using the wrong/different kinds of imports: In my settings in my INSTALLED_APPS I had myproj.myapp

After I changed:

from myapp.models import Company,CustomError

To:

from myproj.myapp.models import Company,CustomError

It worked as expected

Paul
That's not real solution. In addition - second approach is worse (stronger coupling with top-level module name).
gorsky