Skip to content

Commit

Permalink
Add basic support for unions using sdfChoice
Browse files Browse the repository at this point in the history
  • Loading branch information
christiansandberg committed Nov 21, 2024
1 parent 4ae194f commit b893f19
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
13 changes: 7 additions & 6 deletions onedm/sdf/from_type.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Conversion from native types to sdfData."""

from typing import Type
from typing import Any, Type

from pydantic import TypeAdapter
from pydantic.json_schema import GenerateJsonSchema
Expand Down Expand Up @@ -59,11 +59,12 @@ def enum_schema(self, schema: core_schema.EnumSchema):
del definition["enum"]
return definition

def literal_schema(self, schema: core_schema.LiteralSchema):
definition = super().literal_schema(schema)
if "const" in definition and "enum" in definition:
# Don't need both
del definition["enum"]
def union_schema(self, schema: core_schema.UnionSchema):
definition = super().union_schema(schema)
definition["sdfChoice"] = {
f"choice-{i}": choice for i, choice in enumerate(definition["anyOf"], start=1)
}
del definition["anyOf"]
return definition

def bytes_schema(self, schema: core_schema.BytesSchema):
Expand Down
10 changes: 10 additions & 0 deletions tests/sdf/test_from_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,16 @@ class MyEnum(str, enum.Enum):
assert not data.nullable


def test_union():
data = data_from_type(int | str)

assert len(data.choices) == 2
assert "choice-1" in data.choices
assert "choice-2" in data.choices
assert data.choices["choice-1"].type == "integer"
assert data.choices["choice-2"].type == "string"


def test_const():
data = data_from_type(Literal["const"])

Expand Down

0 comments on commit b893f19

Please sign in to comment.