|
1 | 1 | from typing import Literal |
| 2 | + |
2 | 3 | import pytest |
3 | 4 | from pydantic import BaseModel, ValidationError |
4 | 5 |
|
5 | | -from typeid.integrations.pydantic import TypeIDField |
6 | 6 | from typeid import TypeID |
7 | | - |
| 7 | +from typeid.integrations.pydantic import TypeIDField |
8 | 8 |
|
9 | 9 | USER_TYPEID_STR = str(TypeID("user")) |
10 | 10 | ORDER_TYPEID_STR = str(TypeID("order")) |
@@ -34,3 +34,53 @@ def test_json_serializes_as_string(): |
34 | 34 | m = M(id=USER_TYPEID_STR) |
35 | 35 | data = m.model_dump_json() |
36 | 36 | assert '"id":"' in data |
| 37 | + |
| 38 | + |
| 39 | +def test_json_schema_generation(): |
| 40 | + """Test that model_json_schema() works and produces correct schema.""" |
| 41 | + schema = M.model_json_schema() |
| 42 | + |
| 43 | + # Verify the schema structure exists |
| 44 | + assert "properties" in schema |
| 45 | + assert "id" in schema["properties"] |
| 46 | + |
| 47 | + id_schema = schema["properties"]["id"] |
| 48 | + |
| 49 | + # Verify it matches the documented expectations |
| 50 | + assert id_schema["type"] == "string" |
| 51 | + assert id_schema["format"] == "typeid" |
| 52 | + assert "user" in id_schema.get("description", "") |
| 53 | + assert "examples" in id_schema |
| 54 | + |
| 55 | + |
| 56 | +def test_json_schema_with_generate_definitions(): |
| 57 | + """ |
| 58 | + Test that TypeIDField works with Pydantic's generate_definitions(). |
| 59 | +
|
| 60 | + This mimics how FastAPI generates OpenAPI schemas and would catch |
| 61 | + the bug where __get_pydantic_json_schema__ was passing the wrong |
| 62 | + schema to the handler, causing FastAPI's OpenAPI generation to fail. |
| 63 | + """ |
| 64 | + from pydantic.json_schema import GenerateJsonSchema |
| 65 | + |
| 66 | + # Use the same method FastAPI uses internally |
| 67 | + generator = GenerateJsonSchema() |
| 68 | + _, definitions = generator.generate_definitions( |
| 69 | + inputs=[(M, "validation", M.__pydantic_core_schema__)], |
| 70 | + ) |
| 71 | + |
| 72 | + # Verify M is in definitions |
| 73 | + assert "M" in definitions |
| 74 | + |
| 75 | + # Check the id field schema |
| 76 | + m_schema = definitions["M"] |
| 77 | + assert "properties" in m_schema |
| 78 | + assert "id" in m_schema["properties"] |
| 79 | + |
| 80 | + id_schema = m_schema["properties"]["id"] |
| 81 | + |
| 82 | + # Verify TypeID-specific schema properties (same as test_json_schema_generation) |
| 83 | + assert id_schema["type"] == "string" |
| 84 | + assert id_schema["format"] == "typeid" |
| 85 | + assert "user" in id_schema.get("description", "") |
| 86 | + assert "examples" in id_schema |
0 commit comments