Skip to content

Commit

Permalink
Correct parsing for union
Browse files Browse the repository at this point in the history
  • Loading branch information
Rémy Lavainne committed Jul 19, 2024
1 parent 0ecb9ca commit efa3811
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/pyckson/parsers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,5 +104,8 @@ def __init__(self, value_parsers: list[Parser]):
def parse(self, json_value):
for parser in self.value_parsers:
if hasattr(parser, 'cls') and isinstance(json_value, parser.cls):
return parser.parse(json_value)
try:
return parser.parse(json_value)
except:
pass
raise TypeError(f'{json_value} is not compatible with Union type in Pyckson.')
8 changes: 8 additions & 0 deletions tests/parsers/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ def test_should_not_raise_if_parser_does_not_have_cls(self):

assert_that(result).is_equal_to(5)

def test_should_parse_list_of_list_in_union(self):
parser = UnionParser([ListParser(BasicParserWithCast(int)), ListParser(ListParser(BasicParserWithCast(int)))])

result = parser.parse([[5], [6]])

assert result == [[5], [6]]



class TestListParser:
def test_should_accept_list(self):
Expand Down

0 comments on commit efa3811

Please sign in to comment.