Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: improved parsing of Error object (#3984)

Myles Scolnickb53eb0c7365f
diff --git a/marimo/_messaging/cell_output.py b/marimo/_messaging/cell_output.py
index 0ef7167499..d656c987e6 100644
--- a/marimo/_messaging/cell_output.py
+++ b/marimo/_messaging/cell_output.py
@@ -4,7 +4,6 @@
from __future__ import annotations
import time
-from collections.abc import Sequence # noqa: TC003
from dataclasses import asdict, dataclass, field
from enum import Enum
from typing import Any, Union
@@ -33,7 +32,7 @@ class CellOutput:
# descriptive name about the kind of output: e.g., stdout, stderr, ...
channel: CellChannel
mimetype: KnownMimeType
- data: Union[str, Sequence[Error], dict[str, Any]]
+ data: Union[str, list[Error], dict[str, Any]]
timestamp: float = field(default_factory=lambda: time.time())
def __repr__(self) -> str:
diff --git a/marimo/_utils/parse_dataclass.py b/marimo/_utils/parse_dataclass.py
index c9987858ef..c3799a5731 100644
--- a/marimo/_utils/parse_dataclass.py
+++ b/marimo/_utils/parse_dataclass.py
@@ -2,7 +2,9 @@
from __future__ import annotations
import dataclasses
+import datetime
import json
+import sys
from enum import Enum
from typing import (
Any,
@@ -15,6 +17,12 @@ from typing import (
get_type_hints,
)
+# Import NotRequired from typing_extensions for Python < 3.11
+if sys.version_info < (3, 11):
+ from typing_extensions import NotRequired
+else:
+ from typing import NotRequired
+
T = TypeVar("T")
@@ -31,19 +39,62 @@ class DataclassParser:
self.allow_unknown_keys = allow_unknown_keys
def _build_value(self, value: Any, cls: type[T]) -> T:
+ # Handle basic types
+ if cls is float and isinstance(value, (int, float)):
+ return float(value) # type: ignore[return-value]
+ if cls is int and isinstance(value, int):
+ return int(value) # type: ignore[return-value]
+ if cls is str and isinstance(value, str):
+ return str(value) # type: ignore[return-value]
+ if cls is bool and isinstance(value, bool):
+ return bool(value) # type: ignore[return-value]
+ if cls is bytes and isinstance(value, bytes):
+ return bytes(value) # type: ignore[return-value]
+
+ # Handle date and datetime types
+ if cls is datetime.date and isinstance(value, str):
+ return datetime.datetime.fromisoformat(value).date() # type: ignore[return-value]
+ if cls is datetime.datetime and isinstance(value, str):
+ return datetime.datetime.fromisoformat(value) # type: ignore[return-value]
+
+ if cls is Any: # type: ignore[comparison-overlap]
+ return value # type: ignore[no-any-return]
+
+ # Already a dataclass
+ if dataclasses.is_dataclass(value):
+ return value # type: ignore[return-value]
+
+ # Handle container types
# origin_cls is not None if cls is a container (such as list,
# tuple, set, ...)
origin_cls = get_origin(cls)
+
+ # Handle NewType - check if cls has __supertype__ attribute
+ if hasattr(cls, "__supertype__"):
+ # NewType returns its argument at runtime, but we need to validate
+ # against the supertype
+ supertype = cls.__supertype__ # type: ignore
+ return cls(self._build_value(value, supertype)) # type: ignore
+
+ # Handle NotRequired type
+ if origin_cls is NotRequired:
+ (arg_type,) = get_args(cls)
+ if value is None:
+ return None # type: ignore[return-value]
+ return self._build_value(value, arg_type) # type: ignore[no-any-return]
+
if origin_cls is Optional:
(arg_type,) = get_args(cls)
if value is None:
return None # type: ignore[return-value]
else:
return self._build_value(value, arg_type) # type: ignore # noqa: E501
- elif origin_cls in (list, set):
+ elif origin_cls in (list, set) and isinstance(
+ value, (tuple, list, set)
+ ):
(arg_type,) = get_args(cls)
return origin_cls(self._build_value(v, arg_type) for v in value) # type: ignore # noqa: E501
- elif origin_cls is tuple:
+ elif origin_cls is tuple and isinstance(value, (tuple, list)):
arg_types = get_args(cls)
if len(arg_types) == 2 and isinstance(
arg_types[1], type(Ellipsis)
@@ -55,7 +106,7 @@ class DataclassParser:
return origin_cls( # type: ignore # noqa: E501
self._build_value(v, t) for v, t in zip(value, arg_types)
)
- elif origin_cls is dict:
+ elif origin_cls is dict and isinstance(value, dict):
key_type, value_type = get_args(cls)
return origin_cls( # type: ignore[no-any-return]
**{
@@ -97,8 +148,14 @@ class DataclassParser:
return cls(value) # type: ignore[return-value]
elif dataclasses.is_dataclass(cls):
return self.build_dataclass(value, cls) # type: ignore[return-value]
- else:
- return value # type: ignore[no-any-return]
+
+ try:
+ if isinstance(value, cls):
+ return value # type: ignore[no-any-return]
+ except TypeError:
+ pass
+
+ raise ValueError(f"Value '{value}' does not fit '{cls}'")
def build_dataclass(self, values: dict[Any, Any], cls: type[T]) -> T:
"""Returns instance of dataclass [cls] instantiated from [values]."""
diff --git a/tests/_messaging/test_cell_output.py b/tests/_messaging/test_cell_output.py
new file mode 100644
index 0000000000..fe8daf883e
--- /dev/null
+++ b/tests/_messaging/test_cell_output.py
@@ -0,0 +1,99 @@
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from marimo._messaging.cell_output import CellChannel, CellOutput
+from marimo._messaging.errors import MarimoSyntaxError
+from marimo._messaging.ops import serialize
+from marimo._plugins.core.json_encoder import WebComponentEncoder
+from marimo._utils.parse_dataclass import parse_raw
+
+
+def as_json(obj: Any):
+ return WebComponentEncoder.json_dumps(obj)
+
+
+timestamp = 0
+
+stderr_output = CellOutput(
+ channel=CellChannel.STDERR,
+ mimetype="text/plain",
+ data="Error!",
+ timestamp=0,
+)
+
+stdout_output = CellOutput(
+ channel=CellChannel.STDOUT,
+ mimetype="text/plain",
+ data="Hello!",
+ timestamp=0,
+)
+
+error_output = CellOutput(
+ channel=CellChannel.MARIMO_ERROR,
+ mimetype="application/vnd.marimo+error",
+ data=[MarimoSyntaxError(msg="Syntax Error!")],
+ timestamp=0,
+)
+
+data_output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data={
+ "text/plain": "hi",
+ "text/markdown": "# hi",
+ },
+ timestamp=0,
+)
+
+
+def test_serialize_cell_output():
+ output = serialize(stderr_output)
+ assert output == {
+ "channel": "stderr",
+ "mimetype": "text/plain",
+ "data": "Error!",
+ "timestamp": 0,
+ }
+
+ output = serialize(stdout_output)
+ assert output == {
+ "channel": "stdout",
+ "mimetype": "text/plain",
+ "data": "Hello!",
+ "timestamp": 0,
+ }
+
+ output = serialize(error_output)
+ assert output == {
+ "channel": "marimo-error",
+ "mimetype": "application/vnd.marimo+error",
+ "data": [
+ {
+ "msg": "Syntax Error!",
+ "type": "syntax",
+ }
+ ],
+ "timestamp": 0,
+ }
+
+ output = serialize(data_output)
+ assert output == {
+ "channel": "output",
+ "mimetype": "application/vnd.marimo+mimebundle",
+ "data": {
+ "text/plain": "hi",
+ "text/markdown": "# hi",
+ },
+ "timestamp": 0,
+ }
+
+
+ "subject", [stderr_output, stdout_output, error_output, data_output]
+)
+def test_identity(subject: CellOutput):
+ serialized = serialize(subject)
+ assert subject == parse_raw(serialized, CellOutput)
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index c8d6dc2cdf..67e7ac71a0 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -9,6 +9,7 @@ from marimo._ast.app import App, InternalApp
from marimo._config.config import DEFAULT_CONFIG
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.ops import CellOp
+from marimo._plugins.core.json_encoder import WebComponentEncoder
from marimo._server.export import (
export_as_wasm,
run_app_then_export_as_ipynb,
@@ -397,7 +398,7 @@ def _print_messages(messages: list[CellOp]) -> str:
"status": message.status,
}
)
- return json.dumps(result, indent=2)
+ return json.dumps(result, indent=2, cls=WebComponentEncoder)
def _as_list(data: Any) -> list[Any]:
diff --git a/tests/_utils/test_parse_dataclass.py b/tests/_utils/test_parse_dataclass.py
index 9ef6e2c2a4..5fc5385378 100644
--- a/tests/_utils/test_parse_dataclass.py
+++ b/tests/_utils/test_parse_dataclass.py
@@ -1,16 +1,34 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import datetime as dt
import json
-from dataclasses import asdict, dataclass
+import sys
+from dataclasses import asdict, dataclass, field
from enum import Enum
-from typing import Any, Literal, Optional, Union
+from typing import (
+ Any,
+ Generic,
+ Literal,
+ NewType,
+ Optional,
+ TypedDict,
+ TypeVar,
+ Union,
+)
import pytest
from marimo._runtime.requests import SetCellConfigRequest
+from marimo._types.ids import CellId_t
from marimo._utils.parse_dataclass import parse_raw
+# Import NotRequired for testing
+if sys.version_info < (3, 11):
+ from typing_extensions import NotRequired
+else:
+ from typing import NotRequired
+
@dataclass
class Config:
@@ -153,7 +171,10 @@ class TestParseRaw:
def test_set_cell_config(self) -> None:
config = SetCellConfigRequest(
- {"0": {"disabled": True}, "1": {"disabled": False}}
+ {
+ CellId_t("0"): {"disabled": True},
+ CellId_t("1"): {"disabled": False},
+ }
)
parsed = parse_raw(serialize(config), SetCellConfigRequest)
assert parsed == config
@@ -185,6 +206,41 @@ class TestParseRaw:
with pytest.raises(ValueError) as e:
parsed = parse_raw(serialize(nested), Nested)
+ def test_awkward_unions(self):
+ @dataclass
+ class Nested:
+ data: Union[str, bool, dict[str, Any], list[float], list[bytes]]
+
+ # str
+ nested = Nested(data="string")
+ parsed = parse_raw(serialize(nested), Nested)
+ assert parsed == nested
+
+ # bool
+ nested = Nested(data=True)
+ parsed = parse_raw(serialize(nested), Nested)
+ assert parsed == nested
+
+ # dict
+ nested = Nested(data={"first": "hi", "second": False})
+ parsed = parse_raw(serialize(nested), Nested)
+ assert parsed == nested
+
+ # list floats
+ nested = Nested(data=[1, 2])
+ parsed = parse_raw(serialize(nested), Nested)
+ assert parsed == nested
+
+ # not valid, list of strings
+ with pytest.raises(ValueError) as e:
+ parsed = parse_raw({"data": ["one", "two"]}, Nested)
+ assert "does not fit any type of the union" in str(e.value)
+
+ # not valid, int
+ with pytest.raises(ValueError) as e:
+ parsed = parse_raw({"data": 1}, Nested)
+ assert "does not fit any type of the union" in str(e.value)
+
def test_enums(self) -> None:
@dataclass
class Nested:
@@ -251,3 +307,527 @@ def test_with_unknown_keys() -> None:
parsed = parse_raw({"key": "value"}, Empty, allow_unknown_keys=True)
assert parsed == Empty()
+
+
+def test_newtype() -> None:
+ UserId = NewType("UserId", int)
+
+ @dataclass
+ class User:
+ id: UserId
+ name: str
+
+ # Need to use globals() to make the NewType available in the scope
+ globals()["UserId"] = UserId
+
+ parsed = parse_raw({"id": 123, "name": "John"}, User)
+ assert parsed == User(id=UserId(123), name="John")
+ assert isinstance(parsed.id, int)
+
+
+def test_nested_optional_fields() -> None:
+ @dataclass
+ class NestedOptional:
+ value: Optional[Config] = None
+
+ # Test with None value
+ parsed = parse_raw({}, NestedOptional)
+ assert parsed == NestedOptional(value=None)
+
+ # Test with actual value
+ parsed = parse_raw(
+ {"value": {"disabled": True, "gpu": False}}, NestedOptional
+ )
+ assert parsed == NestedOptional(value=Config(disabled=True, gpu=False))
+
+
+def test_mixed_container_types() -> None:
+ @dataclass
+ class MixedContainer:
+ data: list[Union[int, str, Config]]
+
+ mixed = MixedContainer(
+ data=[1, "string", Config(disabled=True, gpu=False)]
+ )
+
+ parsed = parse_raw(serialize(mixed), MixedContainer)
+ assert parsed == mixed
+
+
+def test_complex_nested_structures() -> None:
+ @dataclass
+ class ComplexNested:
+ mapping: dict[str, list[Optional[Config]]]
+
+ complex_data = ComplexNested(
+ mapping={
+ "first": [Config(disabled=True, gpu=False), None],
+ "second": [Config(disabled=False, gpu=True)],
+ }
+ )
+
+ parsed = parse_raw(serialize(complex_data), ComplexNested)
+ assert parsed == complex_data
+
+
+def test_invalid_enum_value() -> None:
+ @dataclass
+ class WithEnum:
+ animal: AnimalType
+
+ # Test with invalid enum value
+ with pytest.raises(ValueError) as e:
+ parse_raw({"animal": "fish"}, WithEnum)
+ assert "fish" in str(e.value)
+
+
+def test_literal_types() -> None:
+ @dataclass
+ class WithLiteral:
+ status: Literal["active", "inactive", "pending"]
+
+ # Valid literal value
+ parsed = parse_raw({"status": "active"}, WithLiteral)
+ assert parsed == WithLiteral(status="active")
+
+ # Invalid literal value
+ with pytest.raises(ValueError) as e:
+ parse_raw({"status": "deleted"}, WithLiteral)
+ assert "does not fit any type of the literal" in str(e.value)
+
+
+def test_missing_required_fields() -> None:
+ @dataclass
+ class Required:
+ name: str
+ age: int
+
+ # Missing required field
+ with pytest.raises(TypeError) as e:
+ parse_raw({"name": "John"}, Required)
+ assert (
+ "missing" in str(e.value).lower() or "required" in str(e.value).lower()
+ )
+
+
+def test_bytes_handling() -> None:
+ @dataclass
+ class WithBytes:
+ data: bytes
+
+ # We need to handle bytes specially since JSON doesn't support bytes directly
+ # This test verifies that bytes passed as a string are properly converted
+ original = WithBytes(data=b"hello")
+ serialized = json.dumps({"data": original.data.decode("utf-8")}).encode(
+ "utf-8"
+ )
+
+ # This should raise an error since JSON serialization of bytes doesn't work directly
+ with pytest.raises(ValueError):
+ parse_raw(serialized, WithBytes)
+
+
+def test_default_values() -> None:
+ @dataclass
+ class WithDefaults:
+ name: str
+ age: int = 30
+ active: bool = True
+
+ # Test with all values provided
+ parsed = parse_raw(
+ {"name": "John", "age": 25, "active": False}, WithDefaults
+ )
+ assert parsed == WithDefaults(name="John", age=25, active=False)
+
+ # Test with only required values
+ parsed = parse_raw({"name": "John"}, WithDefaults)
+ assert parsed == WithDefaults(name="John", age=30, active=True)
+
+
+def test_type_conversion() -> None:
+ @dataclass
+ class TypeConversion:
+ integer: int
+ floating: float
+ boolean: bool
+
+ parsed = parse_raw(
+ {"integer": 42, "floating": 3.14, "boolean": True}, TypeConversion
+ )
+ assert parsed.integer == 42
+ assert parsed.floating == 3.14
+ assert parsed.boolean is True
+
+
+def test_nested_union_with_none() -> None:
+ @dataclass
+ class NestedUnionWithNone:
+ value: Union[Config, None]
+
+ # Test with None
+ parsed = parse_raw({"value": None}, NestedUnionWithNone)
+ assert parsed.value is None
+
+ # Test with actual value
+ parsed = parse_raw(
+ {"value": {"disabled": True, "gpu": False}}, NestedUnionWithNone
+ )
+ assert parsed.value == Config(disabled=True, gpu=False)
+
+
+def test_forward_references() -> None:
+ # Define classes with forward references
+ @dataclass
+ class Node:
+ value: int
+ children: list[Node] = field(default_factory=list)
+
+ # Make Node available in globals for forward reference resolution
+ globals()["Node"] = Node
+
+ # Create a simple tree
+ leaf1 = Node(value=1)
+ leaf2 = Node(value=2)
+ root = Node(value=0, children=[leaf1, leaf2])
+
+ # Test serialization and parsing
+ parsed = parse_raw(serialize(root), Node)
+ assert parsed.value == 0
+ assert len(parsed.children) == 2
+ assert parsed.children[0].value == 1
+ assert parsed.children[1].value == 2
+
+
+def test_case_insensitive_enum() -> None:
+ class CaseInsensitiveEnum(str, Enum):
+ UPPER = "UPPER"
+ LOWER = "lower"
+ MIXED = "MiXeD"
+
+ # Make enum available in globals
+ globals()["CaseInsensitiveEnum"] = CaseInsensitiveEnum
+
+ @dataclass
+ class WithCaseEnum:
+ value: CaseInsensitiveEnum
+
+ # Test with exact case
+ parsed = parse_raw({"value": "UPPER"}, WithCaseEnum)
+ assert parsed.value == CaseInsensitiveEnum.UPPER
+
+ parsed = parse_raw({"value": "lower"}, WithCaseEnum)
+ assert parsed.value == CaseInsensitiveEnum.LOWER
+
+ # Test with different case (this will fail with current implementation)
+ with pytest.raises(ValueError):
+ parsed = parse_raw({"value": "upper"}, WithCaseEnum)
+
+
+def test_allow_unknown_keys_nested() -> None:
+ @dataclass
+ class Inner:
+ required: str
+
+ # Make Inner available in globals
+ globals()["Inner"] = Inner
+
+ @dataclass
+ class Outer:
+ inner: Inner
+
+ # Test with unknown keys in nested structure
+ data = {
+ "inner": {"required": "value", "unknown": "extra"},
+ "outer_unknown": "something",
+ }
+
+ # Should fail without allow_unknown_keys
+ with pytest.raises(ValueError) as e:
+ parsed = parse_raw(data, Outer)
+ assert "Unknown keys" in str(e.value)
+
+ # Should succeed with allow_unknown_keys
+ parsed = parse_raw(data, Outer, allow_unknown_keys=True)
+ assert parsed.inner.required == "value"
+
+
+def test_inheritance() -> None:
+ @dataclass
+ class Base:
+ id: int
+ name: str
+
+ @dataclass
+ class Derived(Base):
+ extra: bool
+
+ # Test parsing with inheritance
+ parsed = parse_raw({"id": 1, "name": "test", "extra": True}, Derived)
+ assert parsed == Derived(id=1, name="test", extra=True)
+
+ # Missing field from derived class
+ with pytest.raises(TypeError):
+ parsed = parse_raw({"id": 1, "name": "test"}, Derived)
+
+
[email protected](reason="Generic types are not supported yet")
+def test_generic_types() -> None:
+ T = TypeVar("T")
+
+ # Make T available in globals
+ globals()["T"] = T
+
+ @dataclass
+ class GenericContainer(Generic[T]):
+ value: T
+
+ @dataclass
+ class StringContainer(GenericContainer[str]):
+ pass
+
+ @dataclass
+ class IntContainer(GenericContainer[int]):
+ pass
+
+ # Test with string
+ parsed = parse_raw({"value": "test"}, StringContainer)
+ assert parsed == StringContainer(value="test")
+
+ # Test with int
+ parsed = parse_raw({"value": 42}, IntContainer)
+ assert parsed == IntContainer(value=42)
+
+
+def test_complex_union_discrimination() -> None:
+ @dataclass
+ class TypeA:
+ type: Literal["a"]
+ value_a: str
+
+ @dataclass
+ class TypeB:
+ type: Literal["b"]
+ value_b: int
+
+ @dataclass
+ class TypeC:
+ type: Literal["c"]
+ value_c: bool
+
+ # Make types available in globals
+ globals()["TypeA"] = TypeA
+ globals()["TypeB"] = TypeB
+ globals()["TypeC"] = TypeC
+
+ @dataclass
+ class Container:
+ data: Union[TypeA, TypeB, TypeC]
+
+ # Test with TypeA
+ parsed = parse_raw({"data": {"type": "a", "value_a": "test"}}, Container)
+ assert isinstance(parsed.data, TypeA)
+ assert parsed.data.value_a == "test"
+
+ # Test with TypeB
+ parsed = parse_raw({"data": {"type": "b", "value_b": 42}}, Container)
+ assert isinstance(parsed.data, TypeB)
+ assert parsed.data.value_b == 42
+
+ # Test with TypeC
+ parsed = parse_raw({"data": {"type": "c", "value_c": True}}, Container)
+ assert isinstance(parsed.data, TypeC)
+ assert parsed.data.value_c is True
+
+ # Test with invalid discriminator
+ with pytest.raises(ValueError):
+ parsed = parse_raw(
+ {"data": {"type": "d", "value": "invalid"}}, Container
+ )
+
+
+def test_empty_containers() -> None:
+ @dataclass
+ class EmptyContainers:
+ empty_list: list[str]
+ empty_dict: dict[str, int]
+ empty_tuple: tuple[int, ...]
+
+ # Test with empty containers
+ parsed = parse_raw(
+ {"empty_list": [], "empty_dict": {}, "empty_tuple": []},
+ EmptyContainers,
+ )
+ assert parsed.empty_list == []
+ assert parsed.empty_dict == {}
+ assert parsed.empty_tuple == ()
+
+
+def test_invalid_json() -> None:
+ @dataclass
+ class Simple:
+ value: str
+
+ # Test with invalid JSON
+ with pytest.raises(json.JSONDecodeError):
+ parse_raw(b"{invalid json}", Simple)
+
+
+def test_recursive_structure_limit() -> None:
+ @dataclass
+ class RecursiveNode:
+ value: int
+ next: Optional[RecursiveNode] = None
+
+ # Make RecursiveNode available in globals
+ globals()["RecursiveNode"] = RecursiveNode
+
+ # Create a deeply nested structure
+ current = None
+ for i in range(100): # Create a chain of 100 nodes
+ current = RecursiveNode(value=i, next=current)
+
+ # This should work fine
+ parsed = parse_raw(serialize(current), RecursiveNode)
+
+ # Verify the structure
+ count = 0
+ node = parsed
+ while node is not None:
+ count += 1
+ node = node.next
+ assert count == 100
+
+
+ sys.version_info >= (3, 11), reason="Not supported in Python >= 3.11"
+)
+def test_not_required_types() -> None:
+ class WithNotRequired(TypedDict):
+ required: str
+ optional: NotRequired[str]
+ optional_dict: NotRequired[dict[str, str]]
+ optional_list: NotRequired[list[str]]
+
+ # Test with all fields provided
+ data: dict[str, Any] = {
+ "required": "value",
+ "optional": "optional_value",
+ "optionalDict": {"key": "value"},
+ "optionalList": ["item"],
+ }
+ parsed = parse_raw(data, WithNotRequired)
+ assert parsed["required"] == "value"
+ assert parsed["optional"] == "optional_value"
+ assert parsed["optional_dict"] == {"key": "value"}
+ assert parsed["optional_list"] == ["item"]
+
+ # Test with only required fields
+ data = {"required": "value"}
+ parsed = parse_raw(data, WithNotRequired)
+ assert parsed["required"] == "value"
+ assert not hasattr(parsed, "optional") or parsed["optional"] is None
+ assert (
+ not hasattr(parsed, "optional_dict") or parsed["optional_dict"] is None
+ )
+ assert (
+ not hasattr(parsed, "optional_list") or parsed["optional_list"] is None
+ )
+
+ # Test with empty values for container types
+ data = {
+ "required": "value",
+ "optional": None,
+ "optionalDict": {},
+ "optionalList": [],
+ }
+ parsed = parse_raw(data, WithNotRequired)
+ assert parsed["required"] == "value"
+ assert parsed["optional"] is None
+ assert parsed["optional_dict"] == {}
+ assert parsed["optional_list"] == []
+
+
+def test_date_and_datetime_types() -> None:
+ @dataclass
+ class DateTimeTypes:
+ date_value: dt.date
+ datetime_value: dt.datetime
+ optional_date: Optional[dt.date] = None
+ optional_datetime: Optional[dt.datetime] = None
+
+ # Test with ISO format strings
+ data = {
+ "dateValue": "2023-01-15",
+ "datetimeValue": "2023-01-15T14:30:45",
+ "optionalDate": "2023-02-20",
+ "optionalDatetime": "2023-02-20T18:15:30",
+ }
+
+ parsed = parse_raw(data, DateTimeTypes)
+
+ assert isinstance(parsed.date_value, dt.date)
+ assert parsed.date_value == dt.date(2023, 1, 15)
+
+ assert isinstance(parsed.datetime_value, dt.datetime)
+ assert parsed.datetime_value == dt.datetime(2023, 1, 15, 14, 30, 45)
+
+ assert isinstance(parsed.optional_date, dt.date)
+ assert parsed.optional_date == dt.date(2023, 2, 20)
+
+ assert isinstance(parsed.optional_datetime, dt.datetime)
+ assert parsed.optional_datetime == dt.datetime(2023, 2, 20, 18, 15, 30)
+
+ # Test with None values for optional fields
+ data = {
+ "dateValue": "2023-01-15",
+ "datetimeValue": "2023-01-15T14:30:45",
+ "optionalDate": None,
+ "optionalDatetime": None,
+ }
+
+ parsed = parse_raw(data, DateTimeTypes)
+
+ assert isinstance(parsed.date_value, dt.date)
+ assert parsed.date_value == dt.date(2023, 1, 15)
+
+ assert isinstance(parsed.datetime_value, dt.datetime)
+ assert parsed.datetime_value == dt.datetime(2023, 1, 15, 14, 30, 45)
+
+ assert parsed.optional_date is None
+ assert parsed.optional_datetime is None
+
+ # Test with nested structures containing dates and datetimes
+ @dataclass
+ class NestedDateTimes:
+ dates: list[dt.date]
+ datetimes: dict[str, dt.datetime]
+
+ nested_data = {
+ "dates": ["2023-01-15", "2023-02-20", "2023-03-25"],
+ "datetimes": {
+ "morning": "2023-01-15T08:00:00",
+ "noon": "2023-01-15T12:00:00",
+ "evening": "2023-01-15T18:00:00",
+ },
+ }
+
+ nested_parsed = parse_raw(nested_data, NestedDateTimes)
+
+ assert all(isinstance(d, dt.date) for d in nested_parsed.dates)
+ assert nested_parsed.dates[0] == dt.date(2023, 1, 15)
+ assert nested_parsed.dates[1] == dt.date(2023, 2, 20)
+ assert nested_parsed.dates[2] == dt.date(2023, 3, 25)
+
+ assert all(
+ isinstance(d, dt.datetime) for d in nested_parsed.datetimes.values()
+ )
+ assert nested_parsed.datetimes["morning"] == dt.datetime(
+ 2023, 1, 15, 8, 0, 0
+ )
+ assert nested_parsed.datetimes["noon"] == dt.datetime(
+ 2023, 1, 15, 12, 0, 0
+ )
+ assert nested_parsed.datetimes["evening"] == dt.datetime(
+ 2023, 1, 15, 18, 0, 0
+ )