python - assertRaises 仅在 unittest 中捕获基本异常
问题描述
我在 PyCharm 上工作,这是我的项目结构:
Python
| utils
| | __init__.py
| | test_utils.py
| main.py
在 utils/__init__.py
:
# -*- coding : utf-8 -*-
"""
Created on 15/10/2020
"""
import random
import datetime
def random_value(min_x, max_x):
# Verification of the type of parameters
try:
assert(type(min_x) is type(max_x))
except AssertionError:
raise TypeError('Limits for x must be of the same type')
# Verification of the inferiority of min_x in front of max_x
try:
assert(min_x < max_x)
except AssertionError:
raise ValueError('min_x has to be lower than max_x')
# Definition of result
x = None
# If we want float
if isinstance(min_x, float):
x = random.uniform(min_x, max_x)
# If we want int
elif isinstance(min_x, int):
x = random.randint(min_x, max_x)
# If we want datetime.datetime
elif isinstance(min_x, datetime.datetime):
x = min_x + datetime.timedelta(seconds=random.randint(0, int((max_x - min_x).total_seconds())), )
# In other cases, raise of exception
else:
raise TypeError('min_x and max_x type is not compatible with function')
return x
在utils/test_utils.py
import unittest
import utils
import datetime
class UtilsTest(unittest.TestCase):
def test_random_value(self):
self.assertRaises(TypeError, utils.random_value, 2.0, 3)
self.assertAlmostEqual(utils.random_value(1.0, 1.5), 1.25, delta=0.25)
self.assertIn(utils.random_value(1, 3), [1, 2, 3])
start = datetime.datetime(1998, 5, 5)
end = datetime.datetime(1998, 5, 10)
x = utils.random_value(start, end)
self.assertIsInstance(x, datetime.datetime)
self.assertTrue((start <= x) and (x <= end))
if __name__ == '__main__':
unittest.main()
当我跑去utils/test_utils.py
测试时utils/__init__.py
,我遇到了第一个错误self.assertRaises(TypeError, utils.random_value, 2.0, 3)
:
Testing started at 10:23 ...
Python/utils/test_utils.py"
Launching unittests with arguments python -m unittest Python/utils/test_utils.py in Python\utils
Ran 1 test in 0.009s
FAILED (errors=1)
Error
Traceback (most recent call last):
File "Python\utils\__init__.py", line 18, in random_value
assert(type(min_x) is type(max_x))
AssertionError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Python\lib\unittest\case.py", line 60, in testPartExecutor
yield
File "Python\lib\unittest\case.py", line 676, in run
self._callTestMethod(testMethod)
File "Python\lib\unittest\case.py", line 633, in _callTestMethod
method()
File "Python\utils\test_utils.py", line 8, in test_random_value
self.assertRaises(AssertionError, utils.random_value, 2.0, 3)
File "Python\lib\unittest\case.py", line 816, in assertRaises
return context.handle('assertRaises', args, kwargs)
File "Python\lib\unittest\case.py", line 202, in handle
callable_obj(*args, **kwargs)
File "Python\utils\__init__.py", line 20, in random_value
raise TypeError('Limits for x must be of the same type')
TypeError: Limits for x must be of the same type
Process finished with exit code 1
Assertion failed
Assertion failed
Assertion failed
Assertion failed
Assertion failed
Assertion failed
但是当我使用 时self.assertRaises(Exception, utils.random_value, 2.0, 3)
,它可以工作......(并且它不适用于AssertionError
)。
为什么 assertRaises 只捕获基本异常?
解决方案
我找到了一个解决方案:
assertRaises((AssertionError, TypeError), utils.random_value, 2.0, 3)
但是@jonrsharpe 给了我一个更好的建议:
在utils/__init__.py
:
更换结构:
try:
assert(type(min_x) is type(max_x))
except AssertionError:
raise TypeError
经过:
if not (type(min_x) is type(max_x)):
raise TypeError
因此该命令assertRaises(TypeError, utils.random_value, 2.0, 3)
适用于utils/test_utils.py
.
推荐阅读
- java - 使用 JAX-RS 和 Liferay (Apache CXF) 实现 PATCH 端点
- r - 特定行的条件句
- c++ - 插入一个基本的单链表节点似乎破坏了我的 C++ 代码?
- benchmarking - 每秒 web-gRPC 性能速率
- c++ - 在 fork() 之后,我的程序中不断得到相同的 pid
- python - 如何在 Spring 中执行 pyomo 模型脚本?
- java - Spring REST - 资源不存在时的正确 PUT 功能
- firebase - 在 Firebase Cloud Function 上合并两个数组
- c# - Net core 3.1 api 的 Swagger UI 非常慢
- javascript - 通过单击随机添加多个图像