Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write unittest for variable assignment in python?

This is in Python 2.7. I have a class called class A, and there are some attributes that I want to throw an exception when being set by the user:

myA = A()
myA.myattribute = 9   # this should throw an error

I want to write a unittest that ensures that this throws an error.

After creating a test class and inheriting unittest.TestCase, I tried to write a test like this:

myA = A()
self.assertRaises(AttributeError, eval('myA.myattribute = 9'))

But, this throws a syntax error. However, if I try eval('myA.myattribute = 9'), it throws the attribute error, as it should.

How do I write a unittest to test this correctly?

Thanks.

like image 930
makansij Avatar asked Jul 28 '26 22:07

makansij


1 Answers

You can also use assertRaises as a context manager:

with self.assertRaises(AttributeError):
    myA.myattribute = 9

The documentation shows more examples for this if you are interested. The documentation for assertRaises has a lot more detail on this subject as well.

From that documentation:

If only the exception and possibly the msg arguments are given, return a context manager so that the code under test can be written inline rather than as a function:

with self.assertRaises(SomeException):
     do_something()

which is exactly what you are trying to do.

like image 93
enderland Avatar answered Jul 31 '26 11:07

enderland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!