python-3.x - 为什么这段代码会引发 AssertionError?
问题描述
这是代码。
# mean_var_std.py
def calculate(list):
try:
if len(list) < 9:
raise ValueError
else:
return 0
except ValueError:
print("List must contain nine numbers.")
这是测试。
import unittest
import mean_var_std
# the test case
class UnitTests(unittest.TestCase):
def test_calculate_with_few_digits(self):
self.assertRaisesRegex(ValueError, "List must contain nine numbers.", mean_var_std.calculate, [2,6,2,8,4,0,1,])
if __name__ == "__main__":
unittest.main()
当我运行它时,我得到以下输出:
F
======================================================================
FAIL: test_calculate_with_few_digits (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/runner/fcc-mean-var-std-2/test_module.py", line 8, in test_calculate_with_few_digits
self.assertRaisesRegex(ValueError, "List must contain nine numbers.", mean_var_std.calculate, [2,6,2,8,4,0,1,])
AssertionError: ValueError not raised by calculate
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
输出表明代码没有引发 ValueError,但从代码中我们可以清楚地看到代码引发了 ValueError。为什么我的代码仍然未能通过单元测试?
解决方案
这是因为您在测试接收到 ValueError 之前捕获了它。删除try catch,它应该可以工作
# mean_var_std.py
def calculate(list):
if len(list) < 9:
print("List must contain nine numbers.")
raise ValueError
else:
return 0
推荐阅读
- azure - 获取 terraform 中可能的出站 IP 地址列表
- python - 如何在使用请求抓取时绕过 Google Recaptcha
- python - 使用 Google Cloud automl 中的 saved_model.pb 在 Python 中进行本地预测
- xamarin.forms - 无法在按钮单击中动态更改属性值
- flutter - flutter_webview_plugin 如何监听 url 更改为 javascript
- angular - 如何使用离子树视图 ionic 4 && angular 创建多个复选框
- android-studio - Flutter 未出现在 Android Studio 的语言和框架设置中
- jenkins - 将工作 A 的工作区 url 传递给 Jenkins 中的工作 B
- numpy - 填充和屏蔽批处理数据集
- delphi - DBRichText“Cambria Math”自动间距问题