簡體   English   中英

assertRaises 只在單元測試中捕獲基本異常

[英]assertRaises only catch base Exception in 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM