Skip to content

Commit

Permalink
Enum tests + fix
Browse files Browse the repository at this point in the history
  • Loading branch information
brentyi committed Oct 5, 2021
1 parent a6570f6 commit 189f612
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 6 deletions.
10 changes: 5 additions & 5 deletions dcargs/_arguments.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import dataclasses
import enum
from typing import (TYPE_CHECKING, Any, Callable, List, Optional, Set, Type,
Union)
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Set, Type, Union

from typing_extensions import Literal # Python 3.7 compat

Expand Down Expand Up @@ -106,8 +105,6 @@ def _choices_from_literals(arg: ArgumentDefinition) -> None:
"""For literal types, set choices."""
field = arg.field

if hasattr(field.type, "__origin__"):
print(field.type.__origin__)
if hasattr(field.type, "__origin__") and field.type.__origin__ is Literal:
choices = set(field.type.__args__)
assert (
Expand All @@ -119,12 +116,15 @@ def _choices_from_literals(arg: ArgumentDefinition) -> None:

def _enums_as_strings(arg: ArgumentDefinition) -> None:
"""For enums, use string representations."""
if type(arg.type) is type and issubclass(arg.type, enum.Enum):
if isinstance(arg.type, type) and issubclass(arg.type, enum.Enum):
if arg.choices is None:
arg.choices = set(x.name for x in arg.type)
else:
arg.choices = set(x.name for x in arg.choices)

arg.type = str
if arg.default is not None:
arg.default = arg.default.name # default should be a string type


def _use_comment_as_helptext(arg: ArgumentDefinition) -> None:
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setup(
name="dcargs",
version="0.0",
version="0.0.1",
description="Portable, reusable, strongly typed CLIs from dataclass definitions",
long_description=long_description,
long_description_content_type="text/markdown",
Expand Down
21 changes: 21 additions & 0 deletions tests/test_dcargs.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import dataclasses
import enum
import io
from contextlib import redirect_stdout
from typing import Optional, Union
Expand Down Expand Up @@ -62,6 +63,26 @@ class A:
assert dcargs.parse(A, args=[]) == A(x=None)


def test_enum():
class Color(enum.Enum):
RED = enum.auto()
GREEN = enum.auto()
BLUE = enum.auto()

@dataclasses.dataclass
class EnumClassA:
color: Color

@dataclasses.dataclass
class EnumClassB:
color: Color = Color.GREEN

assert dcargs.parse(EnumClassA, args=["--color", "RED"]) == EnumClassA(
color=Color.RED
)
assert dcargs.parse(EnumClassB) == EnumClassB()


def test_literal():
@dataclasses.dataclass
class A:
Expand Down

0 comments on commit 189f612

Please sign in to comment.