Python enum.EnumMeta() Examples

The following are 30 code examples of enum.EnumMeta(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module enum , or try the search function .
Example #1
Source File: test_enum.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_inspect_getmembers(self):
        values = dict((
                ('__class__', EnumMeta),
                ('__doc__', 'An enumeration.'),
                ('__members__', self.Color.__members__),
                ('__module__', __name__),
                ('blue', self.Color.blue),
                ('green', self.Color.green),
                ('name', Enum.__dict__['name']),
                ('red', self.Color.red),
                ('value', Enum.__dict__['value']),
                ))
        result = dict(inspect.getmembers(self.Color))
        self.assertEqual(values.keys(), result.keys())
        failed = False
        for k in values.keys():
            if result[k] != values[k]:
                print()
                print('\n%s\n     key: %s\n  result: %s\nexpected: %s\n%s\n' %
                        ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
                failed = True
        if failed:
            self.fail("result does not equal expected, see print above") 
Example #2
Source File: validations.py    From PyPCAPKit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def enum_check(*args, stacklevel=2):
    """Check if arguments are of *enumeration protocol* type (``enum.EnumMeta`` and/or ``aenum.EnumMeta``).

    Args:
        *args: Arguments to check.
        stacklevel (int): Stack level to fetch originated function name.

    Raises:
        EnumError: If any of the arguments is **NOT** *enumeration protocol* type
            (``enum.EnumMeta`` and/or ``aenum.EnumMeta``).

    """
    for var in args:
        if not isinstance(var, (enum.EnumMeta, aenum.EnumMeta)):
            name = type(var).__name__
            func = inspect.stack()[stacklevel][3]
            raise EnumError(f'Function {func} expected enumeration, {name} got instead.') 
Example #3
Source File: test_failure_reasons.py    From stories with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_expand_substory_protocol_enum_with_enum(r, f):
    """We expand protocol of composed story, if substory and parent story define
    protocol with enum class."""

    class T(f.ChildWithEnum, f.EnumMethod):
        pass

    class J(f.ShrinkParentWithEnum, f.NormalParentMethod):
        def __init__(self):
            self.x = T().x

    # Substory DI.

    assert isinstance(J().a.failures, enum.EnumMeta)
    assert set(J().a.failures.__members__.keys()) == {"foo", "bar", "baz", "quiz"}

    with pytest.raises(FailureError) as exc_info:
        r(J().a)()
    assert repr(exc_info.value) == "FailureError(<Errors.foo: 1>)"

    result = r(J().a.run)()
    assert result.failed_because(J().a.failures.foo) 
Example #4
Source File: test_failure_reasons.py    From stories with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_expand_substory_protocol_enum_with_null(r, f):
    """We expand protocol of composed story, if substory define protocol with enum class
    and parent story does not define protocol."""

    class T(f.ChildWithEnum, f.NormalMethod):
        pass

    class J(f.ParentWithNull, f.NormalParentMethod):
        def __init__(self):
            self.x = T().x

    # Substory DI.

    assert isinstance(J().a.failures, enum.EnumMeta)
    assert set(J().a.failures.__members__.keys()) == {"foo", "bar", "baz"}

    result = r(J().a)()
    assert result is None

    result = r(J().a.run)()
    assert result.is_success
    assert result.value is None 
Example #5
Source File: test_enum.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_inspect_getmembers(self):
        values = dict((
                ('__class__', EnumMeta),
                ('__doc__', None),
                ('__members__', self.Color.__members__),
                ('__module__', __name__),
                ('blue', self.Color.blue),
                ('green', self.Color.green),
                ('name', Enum.__dict__['name']),
                ('red', self.Color.red),
                ('value', Enum.__dict__['value']),
                ))
        result = dict(inspect.getmembers(self.Color))
        self.assertEqual(values.keys(), result.keys())
        failed = False
        for k in values.keys():
            if result[k] != values[k]:
                print()
                print('\n%s\n     key: %s\n  result: %s\nexpected: %s\n%s\n' %
                        ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
                failed = True
        if failed:
            self.fail("result does not equal expected, see print above") 
Example #6
Source File: test_failure_reasons.py    From stories with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_substory_protocol_match_with_enum(r, f):
    """We should allow to use stories composition, if parent story protocol is a
    superset of the substory protocol."""

    class T(f.ChildWithEnum, f.EnumMethod):
        pass

    class J(f.WideParentWithEnum, f.NormalParentMethod):
        def __init__(self):
            self.x = T().x

    # Substory DI.

    assert isinstance(J().a.failures, enum.EnumMeta)
    assert set(J().a.failures.__members__.keys()) == {"foo", "bar", "baz", "quiz"}

    with pytest.raises(FailureError) as exc_info:
        r(J().a)()
    assert repr(exc_info.value) == "FailureError(<Errors.foo: 1>)"

    result = r(J().a.run)()
    assert result.failed_because(J().a.failures.foo) 
Example #7
Source File: test_enum.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_inspect_getmembers(self):
        values = dict((
                ('__class__', EnumMeta),
                ('__doc__', 'An enumeration.'),
                ('__members__', self.Color.__members__),
                ('__module__', __name__),
                ('blue', self.Color.blue),
                ('green', self.Color.green),
                ('name', Enum.__dict__['name']),
                ('red', self.Color.red),
                ('value', Enum.__dict__['value']),
                ))
        result = dict(inspect.getmembers(self.Color))
        self.assertEqual(values.keys(), result.keys())
        failed = False
        for k in values.keys():
            if result[k] != values[k]:
                print()
                print('\n%s\n     key: %s\n  result: %s\nexpected: %s\n%s\n' %
                        ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
                failed = True
        if failed:
            self.fail("result does not equal expected, see print above") 
Example #8
Source File: test.py    From uroboroSQL-formatter with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_multiple_mixin_mro(self):
        class auto_enum(EnumMeta):
            def __new__(metacls, cls, bases, classdict):
                original_dict = classdict
                classdict = enum._EnumDict()
                for k, v in original_dict.items():
                    classdict[k] = v
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v == ():
                        v = i
                    else:
                        i = v
                    i += 1
                    temp[k] = v
                for k, v in classdict.items():
                    if k not in names:
                        temp[k] = v
                return super(auto_enum, metacls).__new__(
                        metacls, cls, bases, temp)

        AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})

        AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})

        class TestAutoNumber(AutoNumberedEnum):
            a = ()
            b = 3
            c = ()

        class TestAutoInt(AutoIntEnum):
            a = ()
            b = 3
            c = () 
Example #9
Source File: test_failure_reasons.py    From stories with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_deny_story_reason_substory_protocol_with_enum(r, f):
    """We deny to use Failure reason from the substory protocol in the parent story
    method."""

    class T(f.ChildWithEnum, f.NormalMethod):
        pass

    class J(f.ParentWithNull, f.EnumParentMethod):
        def __init__(self):
            self.x = T().x

    # Substory DI.

    expected = """
Failure(<Errors.foo: 1>) can not be used in a story without failure protocol.

Function returned value: J.before

Use 'failures' story method to define failure protocol.
    """.strip()

    assert isinstance(J().a.failures, enum.EnumMeta)
    assert set(J().a.failures.__members__.keys()) == {"foo", "bar", "baz"}

    with pytest.raises(FailureProtocolError) as exc_info:
        r(J().a)()
    assert str(exc_info.value) == expected

    with pytest.raises(FailureProtocolError) as exc_info:
        r(J().a.run)()
    assert str(exc_info.value) == expected 
Example #10
Source File: base.py    From gs-quant with Apache License 2.0 5 votes vote down vote up
def _missing_(cls: EnumMeta, key):
        return next((m for m in cls.__members__.values() if m.value.lower() == key.lower()), None) 
Example #11
Source File: base.py    From gs-quant with Apache License 2.0 5 votes vote down vote up
def get_enum_value(enum_type: EnumMeta, value: Union[EnumBase, str]):
    if value in (None,):
        return None

    if isinstance(value, enum_type):
        return value

    try:
        enum_value = enum_type(value)
    except ValueError:
        _logger.warning('Setting value to {}, which is not a valid entry in {}'.format(value, enum_type))
        enum_value = value

    return enum_value 
Example #12
Source File: test_enum.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_inspect_classify_class_attrs(self):
        # indirectly test __objclass__
        from inspect import Attribute
        values = [
                Attribute(name='__class__', kind='data',
                    defining_class=object, object=EnumMeta),
                Attribute(name='__doc__', kind='data',
                    defining_class=self.Color, object='An enumeration.'),
                Attribute(name='__members__', kind='property',
                    defining_class=EnumMeta, object=EnumMeta.__members__),
                Attribute(name='__module__', kind='data',
                    defining_class=self.Color, object=__name__),
                Attribute(name='blue', kind='data',
                    defining_class=self.Color, object=self.Color.blue),
                Attribute(name='green', kind='data',
                    defining_class=self.Color, object=self.Color.green),
                Attribute(name='red', kind='data',
                    defining_class=self.Color, object=self.Color.red),
                Attribute(name='name', kind='data',
                    defining_class=Enum, object=Enum.__dict__['name']),
                Attribute(name='value', kind='data',
                    defining_class=Enum, object=Enum.__dict__['value']),
                ]
        values.sort(key=lambda item: item.name)
        result = list(inspect.classify_class_attrs(self.Color))
        result.sort(key=lambda item: item.name)
        failed = False
        for v, r in zip(values, result):
            if r != v:
                print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
                failed = True
        if failed:
            self.fail("result does not equal expected, see print above") 
Example #13
Source File: test_failure_reasons.py    From stories with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_expand_sequential_substory_protocol_enum_with_null(r, f):
    """If parent story consist from sequential substories, we should merge their failure
    protocols together."""

    class T(f.ChildWithEnum, f.EnumMethod):
        pass

    class E(f.NextChildWithNull, f.NormalMethod):
        pass

    class J(f.SequenceParentWithNull, f.NormalParentMethod):
        def __init__(self):
            self.x = T().x
            self.y = E().y

    # Substory DI.

    assert isinstance(J().a.failures, enum.EnumMeta)
    assert set(J().a.failures.__members__.keys()) == {"foo", "bar", "baz"}

    with pytest.raises(FailureError) as exc_info:
        r(J().a)()
    assert repr(exc_info.value) == "FailureError(<Errors.foo: 1>)"

    result = r(J().a.run)()
    assert result.failed_because(J().a.failures.foo) 
Example #14
Source File: facade.py    From python-libmaas with GNU Affero General Public License v3.0 5 votes vote down vote up
def maas(origin):
        attrs = (
            (name, getattr(origin.MAAS, name))
            for name in dir(origin.MAAS)
            if not name.startswith("_")
        )
        return {
            name: attr
            for name, attr in attrs
            if isinstance(attr, enum.EnumMeta) or name.startswith(("get_", "set_"))
        } 
Example #15
Source File: test.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def test_multiple_mixin_mro(self):
        class auto_enum(EnumMeta):
            def __new__(metacls, cls, bases, classdict):
                original_dict = classdict
                classdict = enum._EnumDict()
                for k, v in original_dict.items():
                    classdict[k] = v
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v == ():
                        v = i
                    else:
                        i = v
                    i += 1
                    temp[k] = v
                for k, v in classdict.items():
                    if k not in names:
                        temp[k] = v
                return super(auto_enum, metacls).__new__(
                        metacls, cls, bases, temp)

        AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})

        AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})

        class TestAutoNumber(AutoNumberedEnum):
            a = ()
            b = 3
            c = ()

        class TestAutoInt(AutoIntEnum):
            a = ()
            b = 3
            c = () 
Example #16
Source File: core.py    From transitions with MIT License 5 votes vote down vote up
def listify(obj):
    """Wraps a passed object into a list in case it has not been a list, tuple before.
    Returns an empty list in case ``obj`` is None.
    Args:
        obj: instance to be converted into a list.
    Returns:
        list: May also return a tuple in case ``obj`` has been a tuple before.
    """
    if obj is None:
        return []

    return obj if isinstance(obj, (list, tuple, EnumMeta)) else [obj] 
Example #17
Source File: test_enum.py    From transitions with MIT License 5 votes vote down vote up
def test_if_enum_has_string_behavior(self):
        class States(str, enum.Enum):
            __metaclass__ = enum.EnumMeta

            RED = 'red'
            YELLOW = 'yellow'

        m = self.machine_cls(states=States, auto_transitions=False, initial=States.RED)
        m.add_transition('switch_to_yellow', States.RED, States.YELLOW)

        m.switch_to_yellow()
        assert m.is_YELLOW() is True 
Example #18
Source File: util.py    From py-good with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def primitive_type(schema):
    """ Get schema type for the primitive argument.

    Note: it does treats markers & schemas as callables!

    :param schema: Value of a primitive type
    :type schema: *
    :return: const.COMPILED_TYPE.*
    :rtype: str|None
    """
    schema_type = type(schema)

    # Literal
    if schema_type in const.literal_types:
        return const.COMPILED_TYPE.LITERAL
    # Enum
    elif Enum is not None and isinstance(schema, (EnumMeta, Enum)):
        return const.COMPILED_TYPE.ENUM
    # Type
    elif issubclass(schema_type, type):
        return const.COMPILED_TYPE.TYPE
    # Mapping
    elif isinstance(schema, abc.Mapping):
        return const.COMPILED_TYPE.MAPPING
    # Iterable
    elif isinstance(schema, abc.Iterable):
        return const.COMPILED_TYPE.ITERABLE
    # Callable
    elif callable(schema):
        return const.COMPILED_TYPE.CALLABLE
    # Not detected
    else:
        return None 
Example #19
Source File: utils.py    From cadence-python with MIT License 5 votes vote down vote up
def json_to_data_class(value, cls):
    if type(value) in primitives:
        return value
    elif value is None:
        return None
    elif isinstance(cls, EnumMeta):
        return cls.value_for(value)
    elif "List[" in str(cls):
        l = []
        for v in value:
            l.append(json_to_data_class(v, cls.__args__[0]))
        return l
    elif "Dict[" in str(cls):
        d = {}
        value_type = cls.__args__[1]
        for k, v in value:
            d[k] = json_to_data_class(v, value_type)
        return d
    else:
        assert isinstance(value, dict)
        obj = cls()
        hints = typing.get_type_hints(cls)
        for k, v in value.items():
            value_type = hints.get(k)
            setattr(obj, k, json_to_data_class(v, value_type))
        return obj 
Example #20
Source File: properties.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def __set__(self, instance, value):
        choices = self.choices
        if callable(choices) and type(choices) is not enum.EnumMeta:
            choices = choices()

        try:
            if value in choices:
                setattr(instance, self.attr_name, value)
                return
        except TypeError:
            pass

        raise ValueError("Unknown error") 
Example #21
Source File: test_failure_reasons.py    From stories with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_reasons_defined_with_enum(r, f):
    """We can use enum class to define story failure protocol."""

    class T(f.ChildWithEnum, f.EnumMethod):
        pass

    class J(f.ParentWithEnum, f.NormalParentMethod):
        def __init__(self):
            self.x = T().x

    # Simple.

    assert isinstance(T().x.failures, enum.EnumMeta)
    assert set(T().x.failures.__members__.keys()) == {"foo", "bar", "baz"}

    with pytest.raises(FailureError) as exc_info:
        r(T().x)()
    assert repr(exc_info.value) == "FailureError(<Errors.foo: 1>)"

    result = r(T().x.run)()
    assert not result.is_success
    assert result.is_failure
    assert result.failed_because(T().x.failures.foo)

    # Substory DI.

    assert isinstance(J().a.failures, enum.EnumMeta)
    assert set(J().a.failures.__members__.keys()) == {"foo", "bar", "baz"}

    with pytest.raises(FailureError) as exc_info:
        r(J().a)()
    assert repr(exc_info.value) == "FailureError(<Errors.foo: 1>)"

    result = r(J().a.run)()
    assert not result.is_success
    assert result.is_failure
    assert result.failed_because(J().a.failures.foo) 
Example #22
Source File: test_enum.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_multiple_mixin_mro(self):
        class auto_enum(EnumMeta):
            def __new__(metacls, cls, bases, classdict):
                original_dict = classdict
                classdict = enum._EnumDict()
                for k, v in original_dict.items():
                    classdict[k] = v
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v == ():
                        v = i
                    else:
                        i = v
                    i += 1
                    temp[k] = v
                for k, v in classdict.items():
                    if k not in names:
                        temp[k] = v
                return super(auto_enum, metacls).__new__(
                        metacls, cls, bases, temp)

        AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})

        AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})

        class TestAutoNumber(AutoNumberedEnum):
            a = ()
            b = 3
            c = ()

        class TestAutoInt(AutoIntEnum):
            a = ()
            b = 3
            c = () 
Example #23
Source File: test_enum.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_inspect_classify_class_attrs(self):
        # indirectly test __objclass__
        from inspect import Attribute
        values = [
                Attribute(name='__class__', kind='data',
                    defining_class=object, object=EnumMeta),
                Attribute(name='__doc__', kind='data',
                    defining_class=self.Color, object='An enumeration.'),
                Attribute(name='__members__', kind='property',
                    defining_class=EnumMeta, object=EnumMeta.__members__),
                Attribute(name='__module__', kind='data',
                    defining_class=self.Color, object=__name__),
                Attribute(name='blue', kind='data',
                    defining_class=self.Color, object=self.Color.blue),
                Attribute(name='green', kind='data',
                    defining_class=self.Color, object=self.Color.green),
                Attribute(name='red', kind='data',
                    defining_class=self.Color, object=self.Color.red),
                Attribute(name='name', kind='data',
                    defining_class=Enum, object=Enum.__dict__['name']),
                Attribute(name='value', kind='data',
                    defining_class=Enum, object=Enum.__dict__['value']),
                ]
        values.sort(key=lambda item: item.name)
        result = list(inspect.classify_class_attrs(self.Color))
        result.sort(key=lambda item: item.name)
        failed = False
        for v, r in zip(values, result):
            if r != v:
                print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
                failed = True
        if failed:
            self.fail("result does not equal expected, see print above") 
Example #24
Source File: primitives.py    From PyKMIP with Apache License 2.0 5 votes vote down vote up
def validate(self):
        """
        Verify that the value of the Enumeration is valid.

        Raises:
            TypeError: if the enum is not of type Enum
            ValueError: if the value is not of the expected Enum subtype or if
                the value cannot be represented by an unsigned 32-bit integer
        """
        if not isinstance(self.enum, enumeration.EnumMeta):
            raise TypeError(
                'enumeration type {0} must be of type EnumMeta'.format(
                    self.enum))
        if self.value is not None:
            if not isinstance(self.value, self.enum):
                raise TypeError(
                    'enumeration {0} must be of type {1}'.format(
                        self.value, self.enum))
            if type(self.value.value) not in six.integer_types:
                raise TypeError('enumeration value must be an int')
            else:
                if self.value.value > Enumeration.MAX:
                    raise ValueError(
                        'enumeration value greater than accepted max')
                elif self.value.value < Enumeration.MIN:
                    raise ValueError(
                        'enumeration value less than accepted min') 
Example #25
Source File: test_enum.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_inspect_classify_class_attrs(self):
        # indirectly test __objclass__
        from inspect import Attribute
        values = [
                Attribute(name='__class__', kind='data',
                    defining_class=object, object=EnumMeta),
                Attribute(name='__doc__', kind='data',
                    defining_class=self.Color, object=None),
                Attribute(name='__members__', kind='property',
                    defining_class=EnumMeta, object=EnumMeta.__members__),
                Attribute(name='__module__', kind='data',
                    defining_class=self.Color, object=__name__),
                Attribute(name='blue', kind='data',
                    defining_class=self.Color, object=self.Color.blue),
                Attribute(name='green', kind='data',
                    defining_class=self.Color, object=self.Color.green),
                Attribute(name='red', kind='data',
                    defining_class=self.Color, object=self.Color.red),
                Attribute(name='name', kind='data',
                    defining_class=Enum, object=Enum.__dict__['name']),
                Attribute(name='value', kind='data',
                    defining_class=Enum, object=Enum.__dict__['value']),
                ]
        values.sort(key=lambda item: item.name)
        result = list(inspect.classify_class_attrs(self.Color))
        result.sort(key=lambda item: item.name)
        failed = False
        for v, r in zip(values, result):
            if r != v:
                print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
                failed = True
        if failed:
            self.fail("result does not equal expected, see print above") 
Example #26
Source File: converter.py    From graphene-sqlalchemy with MIT License 5 votes vote down vote up
def convert_choice_to_enum(type, column, registry=None):
    name = "{}_{}".format(column.table.name, column.name).upper()
    if isinstance(type.choices, EnumMeta):
        # type.choices may be Enum/IntEnum, in ChoiceType both presented as EnumMeta
        # do not use from_enum here because we can have more than one enum column in table
        return Enum(name, list((v.name, v.value) for v in type.choices))
    else:
        return Enum(name, type.choices) 
Example #27
Source File: test_failure_reasons.py    From stories with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_deny_substory_reason_parent_story_protocol_with_enum(r, f):
    """We deny to use Failure reason from the parent story protocol in the substory
    method."""

    class T(f.ChildWithNull, f.EnumMethod):
        pass

    class J(f.ParentWithEnum, f.NormalParentMethod):
        def __init__(self):
            self.x = T().x

    # Substory DI.

    expected = """
Failure(<Errors.foo: 1>) can not be used in a story without failure protocol.

Function returned value: T.one

Use 'failures' story method to define failure protocol.
    """.strip()

    assert isinstance(J().a.failures, enum.EnumMeta)
    assert set(J().a.failures.__members__.keys()) == {"foo", "bar", "baz"}

    with pytest.raises(FailureProtocolError) as exc_info:
        r(J().a)()
    assert str(exc_info.value) == expected

    with pytest.raises(FailureProtocolError) as exc_info:
        r(J().a.run)()
    assert str(exc_info.value) == expected 
Example #28
Source File: test_failure_reasons.py    From stories with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_deny_failure_substory_without_protocol_story_protocol_with_enum(r, f):
    """Substory defined without failure protocol can not return Failure, if this
    substory was composed with parent story defined with enum as failure protocol."""

    class T(f.ChildWithNull, f.NullMethod):
        pass

    class J(f.ParentWithEnum, f.NormalParentMethod):
        def __init__(self):
            self.x = T().x

    # Substory DI.

    expected = """
Failure() can not be used in a story composition.

Different types of failure protocol were used in parent and substory definitions.

Function returned value: T.one

Use 'failures' story method to define failure protocol.
    """.strip()

    assert isinstance(J().a.failures, enum.EnumMeta)
    assert set(J().a.failures.__members__.keys()) == {"foo", "bar", "baz"}

    with pytest.raises(FailureProtocolError) as exc_info:
        r(J().a)()
    assert str(exc_info.value) == expected

    with pytest.raises(FailureProtocolError) as exc_info:
        r(J().a.run)()
    assert str(exc_info.value) == expected 
Example #29
Source File: test_failure_reasons.py    From stories with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_deny_failure_story_without_protocol_substory_protocol_with_enum(r, f):
    """Story defined without failure protocol can not return Failure, if this story was
    composed with substory defined with enum as failure protocol."""

    class T(f.ChildWithEnum, f.NormalMethod):
        pass

    class J(f.ParentWithNull, f.NullParentMethod):
        def __init__(self):
            self.x = T().x

    # Substory DI.

    expected = """
Failure() can not be used in a story composition.

Different types of failure protocol were used in parent and substory definitions.

Function returned value: J.before

Use 'failures' story method to define failure protocol.
    """.strip()

    assert isinstance(J().a.failures, enum.EnumMeta)
    assert set(J().a.failures.__members__.keys()) == {"foo", "bar", "baz"}

    with pytest.raises(FailureProtocolError) as exc_info:
        r(J().a)()
    assert str(exc_info.value) == expected

    with pytest.raises(FailureProtocolError) as exc_info:
        r(J().a.run)()
    assert str(exc_info.value) == expected 
Example #30
Source File: test.py    From tandem with Apache License 2.0 5 votes vote down vote up
def test_multiple_mixin_mro(self):
        class auto_enum(EnumMeta):
            def __new__(metacls, cls, bases, classdict):
                original_dict = classdict
                classdict = enum._EnumDict()
                for k, v in original_dict.items():
                    classdict[k] = v
                temp = type(classdict)()
                names = set(classdict._member_names)
                i = 0
                for k in classdict._member_names:
                    v = classdict[k]
                    if v == ():
                        v = i
                    else:
                        i = v
                    i += 1
                    temp[k] = v
                for k, v in classdict.items():
                    if k not in names:
                        temp[k] = v
                return super(auto_enum, metacls).__new__(
                        metacls, cls, bases, temp)

        AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})

        AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})

        class TestAutoNumber(AutoNumberedEnum):
            a = ()
            b = 3
            c = ()

        class TestAutoInt(AutoIntEnum):
            a = ()
            b = 3
            c = ()