diff --git a/python/tests/test_schema_documentation.py b/python/tests/test_schema_documentation.py new file mode 100644 index 00000000..38753e33 --- /dev/null +++ b/python/tests/test_schema_documentation.py @@ -0,0 +1,48 @@ +from pathlib import Path +from textwrap import dedent +from types import ModuleType + +import pytest + +from typechat import Failure, Success, TypeChatValidator, python_type_to_typescript_schema + + +@pytest.mark.parametrize("example_index", [0, 1], ids=["Doc", "plain-string"]) +def test_documented_typeddict_examples(example_index: int) -> None: + root = Path(__file__).resolve().parents[2] + guide = root / "site" / "src" / "docs" / "python" / "basic-usage.md" + code_blocks = [block.split("```", 1)[0] for block in guide.read_text(encoding="utf-8").split("```py\n")[1:]] + examples = [block for block in code_blocks if "class Sentiment(TypedDict):" in block] + assert len(examples) == 2 + + schema = ModuleType("schema") + exec(examples[example_index], schema.__dict__) + sentiment_type = schema.__dict__["Sentiment"] + assert isinstance(sentiment_type, type) + + result = python_type_to_typescript_schema(sentiment_type) + assert result.errors == [] + assert result.typescript_type_reference == "Sentiment" + assert result.typescript_schema_str == dedent(""" + interface Sentiment { + // The sentiment of the user input. + sentiment: "negative" | "neutral" | "positive"; + } + """).lstrip() + + validator = TypeChatValidator[dict[str, str]](sentiment_type) + for sentiment in ("negative", "neutral", "positive"): + assert validator.validate_object({"sentiment": sentiment}) == Success({"sentiment": sentiment}) + + invalid = validator.validate_object({"sentiment": "mixed"}) + assert isinstance(invalid, Failure) + assert "sentiment" in invalid.message + assert "negative" in invalid.message + assert "neutral" in invalid.message + assert "positive" in invalid.message + assert invalid.value == {"sentiment": "mixed"} + + missing = validator.validate_object({}) + assert isinstance(missing, Failure) + assert "sentiment" in missing.message + assert "Field required" in missing.message diff --git a/site/src/docs/python/basic-usage.md b/site/src/docs/python/basic-usage.md index 039026c0..46bae5b5 100644 --- a/site/src/docs/python/basic-usage.md +++ b/site/src/docs/python/basic-usage.md @@ -169,8 +169,40 @@ We defined `Sentiment` as a `@dataclass` so we could have all of the convenience If we declared `Sentiment` as a `TypedDict`, TypeChat would provide us with a `dict`. That would mean that to access the value of `sentiment`, we would have to write `value["sentiment"]`. -Note that while we used [the built-in `typing` module](https://docs.python.org/3/library/typing.html), [`typing_extensions`](https://pypi.org/project/typing-extensions/) is supported as well. -TypeChat also understands constructs like `Annotated` and `Doc` to add comments to individual attributes. +Both [the built-in `typing` module](https://docs.python.org/3/library/typing.html) and [`typing_extensions`](https://pypi.org/project/typing-extensions/) are supported. +On Python 3.11, however, import `TypedDict` from `typing_extensions`: Pydantic requires it instead of `typing.TypedDict` on Python versions earlier than 3.12. +`Annotated` and `Literal` can still be imported from `typing`. + +Here is a complete `TypedDict` version of `schema.py`, with a `Doc` description for the field: + +```py +from typing import Annotated, Literal +from typing_extensions import Doc, TypedDict + +class Sentiment(TypedDict): + sentiment: Annotated[ + Literal["negative", "neutral", "positive"], + Doc("The sentiment of the user input."), + ] +``` + +Or use a plain string for the same field description: + +```py +from typing import Annotated, Literal +from typing_extensions import TypedDict + +class Sentiment(TypedDict): + sentiment: Annotated[ + Literal["negative", "neutral", "positive"], + "The sentiment of the user input.", + ] +``` + +Either `Doc` or a plain string in `Annotated` supplies documentation to the generated TypeScript schema. +Trailing inline comments on directly declared `TypedDict` and dataclass fields also supply schema documentation when their Python source is available. +Explicit `Annotated` documentation takes precedence over inline comments, even when that explicit documentation is empty. +If source is unavailable, conversion still uses the type annotations and explicit documentation, but cannot include inline comments. [`typing.NewType`](https://docs.python.org/3/library/typing.html#typing.NewType) (and `typing_extensions.NewType`) is also supported. TypeChat converts a NewType through its `__supertype__`, so the TypeScript schema uses the underlying JSON type: `NewType("UserId", str)` becomes `string`, and a NewType built on another NewType follows the chain.