简体   繁体   English

为什么我在 Python 中遇到断言错误?

[英]Why am I getting an Assertion Error in Python?

I am testing a function in Python.我正在用 Python 测试一个函数。 This is the function I wrote.这是我写的函数。

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

I used this test case.我使用了这个测试用例。

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

This assertion error came up.这个断言错误出现了。

======================================================================
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

What did I do wrong?我做错了什么? Sorry if this is a basic question I am a first-time coder.对不起,如果这是一个基本问题,我是第一次编码。

You need to call the function, and then specify what the result of that call is supposed to be equal to您需要调用该函数,然后指定该调用的结果应该等于什么

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

This asserts that the hypotenuse of a triangle with sides 3 and 4 is equal to 5.这断言具有边 3 和边 4 的三角形的斜边等于 5。

Your test will still fail because hypotenuse() doesn't return the result.您的测试仍然会失败,因为hypotenuse()不返回结果。 It needs to be:它必须是:

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

Note that you should generally not use equality testing for a mathematical function like this.请注意,您通常不应该对这样的数学函数使用相等测试。 It uses floating point arithmetic, which can have roundoff error.它使用浮点运算,可能有舍入误差。 You can use the assertAlmostEqual() function for this.您可以assertAlmostEqual()使用assertAlmostEqual()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM