Python Regexs单元测试

时间:2014-01-06 15:55:00

标签: python regex unit-testing

我正在尝试对一点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))

返回(16,35)....

我的测试单位是......

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()

测试1通过正常,我的问题是在test_2上如何测试AttributeError: 'NoneType' object has no attribute 'start'

我试图使用assertRaises,但我不确定我做错了什么。我愿意接受任何可以更好的建议。只是想弄清楚如何测试NoneType。我对正则表达式很新。

1 个答案:

答案 0 :(得分:3)

代码使用TestCase.assertRaises错误方式。

替换以下行:

self.assertRaises(AttributeError, find_start_end("Regular Expressions", x))

使用:

# 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)

或:

# Use assertRaises as context manager
with self.assertRaises(AttributeError)
    find_start_end("Regular Expressions", x)