Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: parse enums by value #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
19 changes: 15 additions & 4 deletions validobj/tests/test_validation.py → tests/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,10 @@ def test_good_inp():
assert parse_input(good_inp, Db) == expected_res


def test_bad_inp():
for k in bad_inp:
with pytest.raises(ValidationError):
parse_input(*k)
@pytest.mark.parametrize(("value", "spec"), bad_inp)
def test_bad_inp(value, spec):
with pytest.raises(ValidationError):
parse_input(value, spec)


def test_not_supported():
Expand Down Expand Up @@ -149,6 +149,17 @@ def test_none():
with pytest.raises(ValidationError):
parse_input("Some value", None)


@pytest.mark.skipif(not HAVE_LITERAL, reason="Literal not found")
def test_literal():
assert parse_input(5, Literal[5, Literal[1, 3]]) == 5


def test_enum_by_value() -> None:
"""Enums are built also from value."""
assert parse_input("small", MemOptions) == MemOptions.SMALL


def test_enum_by_int_value() -> None:
"""Enums are built also from value."""
assert parse_input(1, Attributes) == Attributes.READ
11 changes: 5 additions & 6 deletions validobj/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,12 +176,11 @@ def _parse_dataclass(value, spec):


def _parse_single_enum(value, spec):
if not isinstance(value, str):
raise WrongTypeError(
f"Expecting value to be a string, not {_typename(type(value))!r}"
)
if not value in spec.__members__:
raise NotAnEnumItemError(value, spec)
if value not in spec.__members__:
try:
return spec(value)
except (ValueError, TypeError):
raise NotAnEnumItemError(value, spec)
return spec.__members__[value]


Expand Down