2014-01-06 80 views
2

我想在一些正則表達式def上做一些單元測試。Python正則表達式單元測試

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。我對正則表達式很陌生。

回答

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) 
+0

OK的作品感謝。所以在def assertRaises(self,excClass,callableObj = None,* args,** kwargs):「正則表達式」和x是我的**參數? –

+0

@Dumbkid_trying,是的,他們是。我添加了對答案代碼的評論。 – falsetru

+0

謝謝。這現在非常合理。 –