Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - test a property throws exception

Given:

def test_to_check_exception_is_thrown(self):
    # Arrange
    c = Class()
    # Act and Assert
    self.assertRaises(NameError, c.do_something)

If do_something throws an exception the test passes.

But I have a property, and when I replace c.do_something with c.name = "Name" I get an error about my Test Module not being imported and Eclipse highlights the equals symbol.

How do I test a property throws an exception?

Edit:

setattr and getattr are new to me. They've certainly helped in this case, thanks.

like image 533
Finglas Avatar asked Jan 14 '10 17:01

Finglas


2 Answers

Since Python 2.7 and 3.1 assertRaises() can be used as a context manager. See here for Python 2 and here for Python3.

So you can write your test with the with instruction like this:

def test_to_check_exception_is_thrown(self):
    c = Class()
    with self.assertRaises(NameError):
        c.name = "Name"
like image 87
Raphael Ahrens Avatar answered Sep 30 '22 13:09

Raphael Ahrens


assertRaises expects a callable object. You can create a function and pass it:

obj = Class()
def setNameTest():
    obj.name = "Name"        
self.assertRaises(NameError, setNameTest)

Another possibility is to use setattr:

self.assertRaises(NameError, setattr, obj, "name", "Name")

Your original code raises a syntax error because assignment is a statement and cannot be placed inside an expression.

like image 37
interjay Avatar answered Sep 30 '22 14:09

interjay