Unit testing beginner question

A

Andrius

Hello,

would be gratefull for the explonation.

I did a simple test case:

def setUp(self):
self.testListNone = None

def testListSlicing(self):
self.assertRaises(TypeError, self.testListNone[:1])

and I am expecting test to pass, but I am getting exception:
Traceback (most recent call last):
self.assertRaises(TypeError, self.testListNone[:1])
TypeError: 'NoneType' object is unsubscriptable

I thought that assertRaises will pass since TypeError exception will
be raised?

Ta,
Andrius
 
I

Ian Kelly

and I am expecting test to pass, but I am getting exception:
Traceback (most recent call last):
   self.assertRaises(TypeError, self.testListNone[:1])
TypeError: 'NoneType' object is unsubscriptable

I thought that assertRaises will pass since TypeError exception will
be raised?

The second argument to assertRaises must be a function that
assertRaises will call. assertRaises can't catch the error above
because it is raised when the argument is evaluated, before
assertRaises has even been called.

This would work:

self.assertRaises(TypeError, lambda: self.testListNone[:1])

Cheers,
Ian
 
R

Roy Smith

Ian Kelly said:
This would work:

self.assertRaises(TypeError, lambda: self.testListNone[:1])

If you're using the version of unittest from python 2.7, there's an even
nicer way to write this:

with self.assertRaises(TypeError):
self.testListNone[:1]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top