Reputation: 13
I really don't understand what this error refers to
AttributeError("'_AssertRaisesContext' object has no attribute 'exception'",).
I'm trying to write a function power that accepts two arguments, a and b and calculates a raised to the power b and raise a TypeError
with the message Argument must be integer or float
if the inputs are anything other that ints or floats.
this is my code:
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')
and this is the code im using to test it :
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'
)
Upvotes: 1
Views: 1271
Reputation: 1123810
You have two issues:
First of all, you are not actually raising an exception. print()
writes data to the stdout
file (usually connected to your terminal or console), that's not the same thing.
Use raise
:
raise TypeError('Argument must be integer or float')
Next, you are putting the assertion at the wrong indentation level. The point of the with assertRaises()
context manager is to catch the exception that the code in the with
block raises. Any further code in that block then doesn't get executed; the exception exited the block.
You'll need to make the assertion about the message after the block. That way the assertRaises
also notices if no exception was in fact raised and you get a more meaningful assertion error:
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'
)
Upvotes: 2