Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssertRaises fails even though exception is raised

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

like image 775
BergmannF Avatar asked Aug 07 '11 12:08

BergmannF


1 Answers

This could happen if your tests and your product code are importing your exception class through two different paths, so asserRaises doesn't realize that the exception you got was the one you were looking for.

Look at your imports, make sure that they are the same in both places. Having the same directories available in two different ways in your PYTHONPATH can make this happen. Symbolic links in those entries can also confuse things.

like image 70
Ned Batchelder Avatar answered Oct 12 '22 17:10

Ned Batchelder