AssertRaises fails even though exception is raised

Viewed 2496

I am running into the following rather strange problem:

I am developing a django app and in my models class I am defining an exception that should be raised when a validation fails:

class MissingValueException(Exception):
"""Raise when a required attribute is missing."""
def __init__(self, message):
    super(MissingValueException, self).__init__()
    self.message = message

def __str__(self):
    return repr(self.message)

This code is called from a publication class in a validation method:

def validate_required_fields(self):
    # Here is the validation code.
    if all_fields_present:
        return True
    else:
        raise MissingValueException(errors)

In my unit test I create a case where the exception should be raised:

def test_raise_exception_incomplete_publication(self):
    publication = Publication(publication_type="book")
    self.assertRaises(MissingValueException, publication.validate_required_fields)

This produces the following output:

======================================================================
ERROR: test_raise_exception_incomplete_publication (core_knowledge_platform.core_web_service.tests.logic_tests.BusinessLogicTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/media/data/Dokumente/Code/master_project/core_knowledge_platform/../core_knowledge_platform/core_web_service/tests/logic_tests.py", line 45, in test_raise_exception_incomplete_publication
    self.assertRaises(MissingValueException, method, )
File "/usr/lib/python2.7/unittest/case.py", line 465, in assertRaises
    callableObj(*args, **kwargs)
File "/media/data/Dokumente/Code/master_project/core_knowledge_platform/../core_knowledge_platform/core_web_service/models.py", line 150, in validate_required_fields
    raise MissingValueException(errors)
MissingValueException: 'Publication of type book is missing field publisherPublication of type book is missing field titlePublication of type book is missing field year'

So it looks like the exception is raised (which is the case - I even checked it in an interactive IPython session), but it seems that assertRaises is not catching it.

Anyone has any idea why this might happen?

Thanks

1 Answers
Related