Skip to content

Commit 9ff66f1

Browse files
Maiky Guanaesfgmacedo
authored andcommitted
feat(schematics) Creates ChoicesEnumType
1 parent 9ba2969 commit 9ff66f1

File tree

5 files changed

+42
-0
lines changed

5 files changed

+42
-0
lines changed

AUTHORS.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ Contributors
1515
* Leandro Gomes <[email protected]>
1616
* Tomas Fagerbekk <[email protected]>
1717
* Lefteris Karapetsas <[email protected]>
18+
* Maiky Guanaes <[email protected]>
1819

1920

2021
Tools

choicesenum/schematics/__init__.py

Whitespace-only changes.

choicesenum/schematics/types.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# coding: utf-8
2+
from __future__ import absolute_import, unicode_literals
3+
4+
from choicesenum import ChoicesEnum
5+
from schematics.types import BaseType, ValidationError
6+
7+
8+
class ChoicesEnumType(BaseType):
9+
def __init__(self, type_):
10+
if not issubclass(type_, ChoicesEnum):
11+
raise ValidationError(self.Messages.INVALID_TYPE)
12+
super(ChoicesEnumType, self).__init__(type_)
13+
self.type = type_
14+
15+
def to_native(self, value, context=None):
16+
return self.type(value)
17+
18+
def to_primitive(self, value, context=None):
19+
return self.type(value).value
20+
21+
class Messages:
22+
INVALID_TYPE = 'Expected a ChoicesEnum sub type'

requirements_test.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ pytest==3.10.1
44
pytest-cov==2.6.0
55
pytest-watch==4.2.0
66
pytest-sugar==0.9.2
7+
schematics==1.1.3

tests/test_schematics_types.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# coding: utf-8
2+
from __future__ import absolute_import, unicode_literals
3+
4+
import pytest
5+
from schematics.exceptions import ValidationError
6+
from choicesenum.schematics.types import ChoicesEnumType
7+
8+
9+
def test_choices_enum_type(http_statuses):
10+
state = ChoicesEnumType(http_statuses)
11+
assert state.to_native(200) is http_statuses.OK
12+
assert state.to_primitive(200) == http_statuses.OK.value
13+
14+
15+
def test_choices_enum_type_should_throw_exception():
16+
with pytest.raises(ValidationError) as e:
17+
ChoicesEnumType(object)
18+
assert e.value.message[0] == ChoicesEnumType.Messages.INVALID_TYPE

0 commit comments

Comments
 (0)