How to assert if Python enum contains specific string key or value

531 Uncategorized Leave a Comment

To assert if Python enum contains specific string key or value, we need helper function.

class BaseEnum(Enum):
    @classmethod
    def has_name(cls, name):
        return name in cls._member_names_

    @classmethod
    def has_value(cls, value):
        return value in cls._value2member_map_

class StatusEnum(str, BaseEnum):
    PUBLISHED = 1
    PENDDING = 2

Then we can use it:

# assert name
StatusEnum.has_name("PUBLISHED")  # true
StatusEnum.has_name("ENABLED")     # false

# assert value
StatusEnum.has_value(2)    # true
StatusEnum.has_value(0)    # false

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *