Python 测试过程中的AssertionError没有清除错误消息
这可能很简单 我写过这门课Python 测试过程中的AssertionError没有清除错误消息,python,Python,这可能很简单 我写过这门课 class Pants : def __init__(self, pants_color, waist_size, length, price): self.color = pants_color self.waist_size = waist_size self.length = length self.price = price def change_price(self, new_
class Pants :
def __init__(self, pants_color, waist_size, length, price):
self.color = pants_color
self.waist_size = waist_size
self.length = length
self.price = price
def change_price(self, new_price):
self.price = new_price
def discount(self, discount):
self.price = self.price * (1 - discount)
我正在对它进行以下测试:
def check_results():
pants = Pants('red', 35, 36, 15.12)
assert pants.color == 'red'
assert pants.waist_size == 35
assert pants.length == 36
assert pants.price == 15.12
pants.change_price(10) == 10
assert pants.price == 10
assert pants.discount(.1) == 9
print('You made it to the end of the check. Nice job!')
check_results()
出于某种原因,我一直看到一条没有实际错误的错误消息,它只是说AssertionError:
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-5-50abebbadc01> in <module>()
13 print('You made it to the end of the check. Nice job!')
14
---> 15 check_results()
<ipython-input-5-50abebbadc01> in check_results()
9 assert pants.price == 10
10
---> 11 assert pants.discount(.1) == 9
12
13 print('You made it to the end of the check. Nice job!')
AssertionError:
---------------------------------------------------------------------------
AssertionError回溯(上次最近的调用)
在()
13打印('你到了支票的末尾。干得好!')
14
--->15检查结果()
在check_results()中
9.价格==10
10
--->11.折扣(.1)=9
12
13打印('你到了支票的末尾。干得好!')
断言者错误:
是的,显然我不得不添加一个退货
,而不仅仅是设置新的价格。
我还是要分享这一点,以防其他人遇到它
def discount(self, discount):
return self.price * (1 - discount)
assert
只打印您给出的错误消息,例如:
assert pants.discount(.1) == 9, "Pants discount should be {}, was {}".format(9, pants.discount(0.1))
将给出错误
AssertionError: Pants discount should be 9, was None
建议为每个assert语句放置一条消息。或者,您可以从
UnitTest
模块中使用inherit fromUnitTest
,并使用specialityassertEquals
方法,该方法具有内置的漂亮错误打印。调用pants.discount
然后断言self.price
具有预期值可能更有意义。返回值只是为了使测试正常工作是浪费的,并且违反了命令/查询分离。