2013-02-05 59 views
2

我明顯對如何在python中引發異常有一些基本的誤解。我包括了我正在嘗試(和失敗)要做的最簡單的例子。我正在嘗試創建一個新的異常,並正確測試它是否正常工作。如何在python中創建/實現/測試新的異常?

import random 
import unittest 

# Create new class of exception 
class LearningError(Exception): 
    pass 

# Create function 
def addition_no_four(first, second): 
    """Add two numbers (as long as it isn't 4).""" 
    if (first == 4) or (second == 4): 
     raise LearningError("We don't take 4s!") 
    return first + second 

# Properly working example code that tests raising errors 
class TestSequenceFunctions(unittest.TestCase): 
    def setUp(self): 
     self.seq = range(10) 
    def test_shuffle(self): 
     random.shuffle(self.seq) 
     self.seq.sort() 
     self.assertEqual(self.seq, range(10)) 
     self.assertRaises(TypeError, random.shuffle, (1,2,3)) 

# My code which tests 
class TestAddition(unittest.TestCase): 
    def test_addition(self): 
     """Test whether it works for 2 numbers (not 4).""" 
     first = 2 
     second = 5 
     self.assertEqual(addition_no_four(first, second), 7) 
    def test_raise(self): 
     """Learn how to create an exception and test its implementation.""" 
     self.assertRaises(LearningError, addition_no_four(2, 4)) 

if __name__ == "__main__": 
    unittest.main() 

哪個失敗,出現以下消息:

Traceback (most recent call last): 
    File "test.py", line 34, in test_raise 
    self.assertRaises(LearningError, addition_no_four(2, 4)) 
    File "test.py", line 12, in addition_no_four 
    raise LearningError("We don't take 4s!") 
LearningError: We don't take 4s! 

---------------------------------------------------------------------- 
Ran 3 tests in 0.000s 

FAILED (errors=1) 

這不會發生(即,示例代碼正確測試前一個異常什麼我需要改變,以使這種事情發生?

回答

3

有隻是一個小的變化。當你使用assertRaises,一定調用函數直接,而是它的參數需要作爲參數傳遞ŧ o assertRaises。這允許assertRaises測試方法在調用函數之前設置try /除外。

def test_raise(self): 
    """Learn how to create an exception and test its implementation.""" 
    self.assertRaises(LearningError, addition_no_four, 2, 4) 

您還可以通過使用assertRaises作爲內容管理器繞過這個問題:

def test_raise(self): 
    """Learn how to create an exception and test its implementation.""" 
    with self.assertRaises(LearningError): 
     addition_no_four(2, 4) 
+0

謝謝!我感覺自己即將失去理智。我想/希望這將是一個簡單的解決方案! – JBWhitmore