Reputation: 9501
I am trying to do some unit testing on a little regex def.
x = "TEST TEST TEST. Regular Expressions. TEST TEST TEST"
def find_start_end(phrase,sample_set):
m = re.search(phrase, sample_set)
start = m.start()
end = m.end()
return (start,end)
#print(start,end)
if __name__ =="__main__":
print(find_start_end("Regular Expressions", x))
This returns (16,35)....
My testing Unit is....
import unittest
class TestAlpha(unittest.TestCase):
def test_1(self):
x = "Regular Expressions"
self.assertEqual((0, 19), find_start_end("Regular Expressions", x))
def test_2(self):
x = "TEST TEST TEST. Regular Expression. TEST TEST TEST"
self.assertRaises(AttributeError, find_start_end("Regular Expressions", x))
if __name__ == "__main__":
unittest.main()
Test 1 passes fine, my question is on test_2 how do I test for the AttributeError: 'NoneType' object has no attribute 'start'
.
I was trying to use assertRaises
, but I am not sure what I am doing wrong. I am open to any suggestions that would work better. Just trying to figure out how to test for the NoneType
. I am very new to regular expressions.
Upvotes: 2
Views: 2676
Reputation: 369284
The code is using TestCase.assertRaises
wrong way.
Replace following line:
self.assertRaises(AttributeError, find_start_end("Regular Expressions", x))
with:
# Do not call `find_start_end` directly,
# but pass the function and its arguments to assertRaises
self.assertRaises(AttributeError, find_start_end, "Regular Expressions", x)
or:
# Use assertRaises as context manager
with self.assertRaises(AttributeError)
find_start_end("Regular Expressions", x)
Upvotes: 3