2

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.

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

4 Comments

ok that works Thanks. So in def assertRaises(self, excClass, callableObj=None, *args, **kwargs): "Regular Expressions" and x are my ** args?
@Dumbkid_trying, Yes, they are. I added commented to the answer code.
Thanks. That makes perfect sense now.
@Dumbkid_trying, BTW, (m.start(), m.end()) could be expressed as m.span().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.