1
我真的不明白這是什麼錯誤是指試圖斷言有關異常的東西,但得到一個AttributeError?
AttributeError("'_AssertRaisesContext' object has no attribute 'exception'",).
我想寫接受兩個參數,a和b的函數的功率和計算冪,B和養TypeError
與如果輸入是其他輸入或浮點數,則消息Argument must be integer or float
。
這是我的代碼:
def power(a, b):
try :
if b == 0:
return 1
elif b == 1:
return a;
else:
return a*pow(a, b-1)
except TypeError :
print ('Argument must be integer or float')
,這使用,以測試它的代碼IM:
from unittest import TestCase
class PowerTestCases(TestCase):
def test_returns_correct_power(self):
base, exp = 2, 3
res = power(base, exp)
self.assertEqual(res, 8, msg='Expected {}, got {}'.format(8, res))
def test_return_1_when_exp_is_0(self):
base, exp = 4, 0
res = power(base, exp)
self.assertEqual(res, 1, msg='A number power 0 should be 1')
def test_return_0_when_base_is_0(self):
base, exp = 0, 10
res = power(base, exp)
self.assertEqual(res, 0, msg='O power any number should be 0')
def test_non_digit_argument(self):
with self.assertRaises(TypeError) as context:
base, exp = 'base', 'exp'
res = power(base, exp)
self.assertEqual(
'Argument must be interfer or float',
context.exception.message,
'Only digits are allowed as input'
)
[不靈蟒蛇unittest.TestCase.assertRaises](可能的重複http://stackoverflow.com/問題/ 39450098/python-unittest-testcase-assertraises-not-working) –
你的函數_不會引發異常。它只是將一些字符串打印到標準輸出,並且如果傳遞了錯誤的類型,則返回'None'。詳情請參閱重複。 –