Home > Mobile >  unittest self.assertRaises fails to recognise exception | python 3.10.2
unittest self.assertRaises fails to recognise exception | python 3.10.2

Time:04-26

The below test fails in python 3.10.2.

Why might that be?

'self.assertRaises' also fails to catch if I raise a generic 'Exception' instance in 'check_battery_level'.

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()

Output:

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

CodePudding user response:

I was calling the function within self.assertRaises instead of passing in.

Replace:

self.assertRaises(LowBattery, check_battery_level())

With:

self.assertRaises(LowBattery, check_battery_level)
  • Related