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 Pythonutils

Ran 1 test in 0.009s
FAILED (errors=1)
Error
Traceback (most recent call last):
File "Pythonutils__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 "Pythonlibunittestcase.py", line 60, in testPartExecutor
yield
File "Pythonlibunittestcase.py", line 676, in run
self._callTestMethod(testMethod)
File "Pythonlibunittestcase.py", line 633, in _callTestMethod
method()
File "Pythonutilstest_utils.py", line 8, in test_random_value
self.assertRaises(AssertionError, utils.random_value, 2.0, 3)
File "Pythonlibunittestcase.py", line 816, in assertRaises
return context.handle('assertRaises', args, kwargs)
File "Pythonlibunittestcase.py", line 202, in handle
callable_obj(*args, **kwargs)
File "Pythonutils__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中工作。

相关内容

  • 没有找到相关文章

最新更新