Skip to content

Commit

Permalink
feat(schematics) Creates ChoicesEnumType
Browse files Browse the repository at this point in the history
  • Loading branch information
maikyguanaes authored and fgmacedo committed Aug 27, 2019
1 parent 9ba2969 commit 9ff66f1
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions AUTHORS.rst
Expand Up @@ -15,6 +15,7 @@ Contributors
* Leandro Gomes <leandrogs99@gmail.com>
* Tomas Fagerbekk <tomas.a.fagerbekk@gmail.com>
* Lefteris Karapetsas <lefteris@refu.co>
* Maiky Guanaes <maiky.guanaes@gmail.com>


Tools
Expand Down
Empty file.
22 changes: 22 additions & 0 deletions choicesenum/schematics/types.py
@@ -0,0 +1,22 @@
# coding: utf-8
from __future__ import absolute_import, unicode_literals

from choicesenum import ChoicesEnum
from schematics.types import BaseType, ValidationError


class ChoicesEnumType(BaseType):
def __init__(self, type_):
if not issubclass(type_, ChoicesEnum):
raise ValidationError(self.Messages.INVALID_TYPE)
super(ChoicesEnumType, self).__init__(type_)
self.type = type_

def to_native(self, value, context=None):
return self.type(value)

def to_primitive(self, value, context=None):
return self.type(value).value

class Messages:
INVALID_TYPE = 'Expected a ChoicesEnum sub type'
1 change: 1 addition & 0 deletions requirements_test.txt
Expand Up @@ -4,3 +4,4 @@ pytest==3.10.1
pytest-cov==2.6.0
pytest-watch==4.2.0
pytest-sugar==0.9.2
schematics==1.1.3
18 changes: 18 additions & 0 deletions tests/test_schematics_types.py
@@ -0,0 +1,18 @@
# coding: utf-8
from __future__ import absolute_import, unicode_literals

import pytest
from schematics.exceptions import ValidationError
from choicesenum.schematics.types import ChoicesEnumType


def test_choices_enum_type(http_statuses):
state = ChoicesEnumType(http_statuses)
assert state.to_native(200) is http_statuses.OK
assert state.to_primitive(200) == http_statuses.OK.value


def test_choices_enum_type_should_throw_exception():
with pytest.raises(ValidationError) as e:
ChoicesEnumType(object)
assert e.value.message[0] == ChoicesEnumType.Messages.INVALID_TYPE

0 comments on commit 9ff66f1

Please sign in to comment.