unittest self.assertRaises 无法识别异常 | python 3.10.2

unittest self.assertRaises fails to recognise exception | python 3.10.2

以下测试在 python 3.10.2.

中失败

为什么会这样?

如果我在 'check_battery_level'.

中引发通用 'Exception' 实例,

'self.assertRaises' 也无法捕获

import psutil
import unittest

from unittest.mock import patch, Mock



class LowBattery(Exception):
    def __str__(self):
        return "Battery level critically low"



def check_battery_level(min_percent: float=10) -> None:
    """Check whether or not battery level is below a defined threshold
    
    :param min_percent: raise excpetion should battery level below min_percent
                        threshold
    :raises: LowBattery exception
    
    >>> check_battery_level(min_percent=0)
    False
    """
    
    battery = psutil.sensors_battery()
    
    if battery and battery < min_percent:
        raise LowBattery()


class TestCheckBatteryLevel(unittest.TestCase):
    def test__battery_level_low_raises_exception(self):
        with patch("psutil.sensors_battery", return_value=9):
            self.assertRaises(LowBattery, check_battery_level())
            


unittest.main()

输出:

ERROR: test__battery_level_ok (__main__.TestCheckBatteryLevel)
raise LowBattery()
LowBattery: Battery level critically low

我在 self.assertRaises 中调用函数而不是传入。

替换:

self.assertRaises(LowBattery, check_battery_level())

与:

self.assertRaises(LowBattery, check_battery_level)