I have two files "testable.py":
def joiner(x,y):
return x+y
"test_testable.py":
import unittest
import testable
class TestTestable(unittest.TestCase):
def setUp(self):
self.seq = ['a','b','1']
self.seq2 = ['b','c',1]
def test_joiner(self):
for each in self.seq:
for eachy in self.seq2:
self.assertRaises(TypeError,testable.joiner(each,eachy))
if __name__ == '__main__':
unittest.main()
Now when I run the test I get:
ERROR: test_joiner (test_testable.TestTestable)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/rajat/collective_knowledge/test_testable.py", line 16, in test_joiner
self.assertRaises(TypeError,testable.joiner(each,eachy),(each,eachy))
File "/home/rajat/collective_knowledge/testable.py", line 11, in joiner
return x+y
TypeError: cannot concatenate 'str' and 'int' objects
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
What am I doing wrong?
asked Jul 15, 2012 at 12:20
Rajat Saxena
3,9456 gold badges49 silver badges68 bronze badges
2 Answers 2
You're miss using assertRaises it should be:
self.assertRaises(TypeError,testable.joiner, (each,eachy))
Or just use it as a context manager if you're using python2.7 and above or unittest2:
with self.assertRaises(TypeError):
testable.joiner(each,eachy)
EDIT :
You should also replace self.seq2 = [1,2,3] for example.
answered Jul 15, 2012 at 12:24
mouad
70.5k18 gold badges117 silver badges106 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Rajat Saxena
FAIL: test_joiner (test_testable.TestTestable) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/rajat/collective_knowledge/test_testable.py", line 17, in test_joiner testable.joiner(each,eachy) AssertionError: TypeError not raised ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (failures=1)
mouad
That's because your testing data is wrong (at least from the test) b/c concatenating two strings is correct, the only one that will make your test succeed are the one with
'*' + 1, so i think you want to do: self.seq2 = [1,2,3]Rajat Saxena
oh thanks,Also can you suggest me a nice guide to unit testing(esp. for django)?
mouad
IMHO the doc (docs.djangoproject.com/en/dev/topics/testing) is a good reference.
Kamal
@Rajat You should write separate tests for valid inputs (positive tests) and invalid inputs (negative).
In
for each in self.seq:
for eachy in self.seq2
each could be 'a' and eachy could be 1
You can't add 'a' and 1 so the test fails.
answered Jul 15, 2012 at 12:25
Ramchandra Apte
4,1092 gold badges27 silver badges45 bronze badges
1 Comment
Rajat Saxena
Yeah,That's what I am testing.It should raise TypeError and my test code should tell that it's raised
lang-py