Python: Unit Test That Asserts Custom Exception Is Raised Fails When Try-Except Is Involved

The problem is that you’ve nested the definition of your exception class inside an enum:

class Weekdays(Enum):
    MONDAY = 'mon'
    TUESDAY = 'tue'
    WEDNESDAY = 'wed'        
    THURSDAY = 'thu'        
    FRIDAY = 'fri'        

    class InvalidValue(Exception):
        pass

enum’s (through metaclass chicanery) make their class attributes singleton instances of the enum class, with the value you assigned to the attribute in the definition inside the .value of that enum instance. Just like the other class attributes you defined in your enum. So, consider:

In [1]: from enum import Enum

In [2]:
   ...: class Weekdays(Enum):
   ...:     MONDAY = 'mon'
   ...:     TUESDAY = 'tue'
   ...:     WEDNESDAY = 'wed'
   ...:     THURSDAY = 'thu'
   ...:     FRIDAY = 'fri'
   ...:
   ...:     class InvalidValue(Exception):
   ...:         pass
   ...:

In [3]: Weekdays.MONDAY
Out[3]: <Weekdays.MONDAY: 'mon'>

In [4]: Weekdays.MONDAY.value
Out[4]: 'mon'

In [5]: Weekdays.InvalidValue
Out[5]: <Weekdays.InvalidValue: <class '__main__.Weekdays.InvalidValue'>>

In [6]: Weekdays.InvalidValue.value
Out[6]: __main__.Weekdays.InvalidValue

So, you could use:

with self.assertRaises(Weekdays.InvalidValue.value):
    ...

And in similarly, in parse, you need:

raise Weekdays.InvalidValue.value() from e

But you are better off just defining InvalidValue at the module level.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top