If you are using Python 2.7 or above, you can use the ability of assertRaises to be used as a context manager and do:
with self.assertRaises(TypeError):
self.testListNone[:1]
If you are using Python 2.6, another way beside the one given until now is to use unittest2 which is a back port of unittest's new features to Python 2.6, and you can make it work using the code above.
N.B: I'm a big fan of the new feature (SkipTest, test discovery, etc.) of unittest, so I intend to use unittest2 as much as I can. I advise to do the same, because there is a lot more than what unittest come with in Python 2.6 or lower.
Answer from mouad on Stack OverflowIf you are using Python 2.7 or above, you can use the ability of assertRaises to be used as a context manager and do:
with self.assertRaises(TypeError):
self.testListNone[:1]
If you are using Python 2.6, another way beside the one given until now is to use unittest2 which is a back port of unittest's new features to Python 2.6, and you can make it work using the code above.
N.B: I'm a big fan of the new feature (SkipTest, test discovery, etc.) of unittest, so I intend to use unittest2 as much as I can. I advise to do the same, because there is a lot more than what unittest come with in Python 2.6 or lower.
The problem is the TypeError gets raised 'before' assertRaises gets called since the arguments to assertRaises need to be evaluated before the method can be called. You need to pass a lambda expression like:
self.assertRaises(TypeError, lambda: self.testListNone[:1])
unit testing - python unittest assertRaises - Stack Overflow
How do I assert exception raise in init?
Unit test with exception
Python unittest an error-handling function
The ability to use unittest.TestCase.AssertRaises() as context manager was added in python 2.7. http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises
Check that you are really using 2.7 python.
Tested using pythonbrew:
$ pythonbrew use 2.7.2
$ python test.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
$ pythonbrew use 2.6.5
$ python test.py
.E.
======================================================================
ERROR: test_sample (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test.py", line 23, in test_sample
with self.assertRaises(ValueError):
TypeError: failUnlessRaises() takes at least 3 arguments (2 given)
----------------------------------------------------------------------
Ran 3 tests in 0.000s
FAILED (errors=1)