【问题标题】:Why am I getting an Assertion Error in Python?为什么我在 Python 中收到断言错误?
【发布时间】:2020-01-09 20:51:52
【问题描述】:

我正在用 Python 测试一个函数。这是我写的函数。

def hypotenuse(a, b):
   math.sqrt(a**2 + b**2)

我使用了这个测试用例。

def test_hypotenuse_1(self):
   self.assertEqual(funcs.hypotenuse, 3, 4)

出现了这个断言错误。

======================================================================
FAIL: test_hypotenuse_1 (__main__.TestCases)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "funcs_tests.py", line 27, in test_hypotenuse_1
    self.assertEqual(funcs.hypotenuse, 3, 4)
AssertionError: <function hypotenuse at 0x7f397f2d79d8> != 3 : 4

我做错了什么?对不起,如果这是一个基本问题,我是第一次编码。

【问题讨论】:

  • 您可能必须致电 funcs.hypotenuse。你还必须从hypothenuse返回一些东西。

标签: python python-3.x unit-testing assertion


【解决方案1】:

您需要调用该函数,然后指定该调用的结果应该等于什么

def test_hypotenuse_1(self):
    self.assertEqual(funcs.hypotenuse(3, 4), 5)

这断言具有边 3 和 4 的三角形的斜边等于 5。

您的测试仍然会失败,因为hypotenuse() 没有返回结果。它必须是:

def hypotenuse(a, b):
    return math.sqrt(a**2 + b**2)

请注意,您通常不应该对这样的数学函数使用相等测试。它使用浮点运算,可能有舍入误差。您可以为此使用assertAlmostEqual() 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    相关资源
    最近更新 更多