|
| 1 | +from typing import Optional, cast |
| 2 | + |
| 3 | +import pytest |
| 4 | +from pydantic import BaseModel, ValidationError |
| 5 | + |
| 6 | +from ninja import NinjaAPI, Schema |
| 7 | +from ninja.patch_schema import PatchedModel, PatchSchema |
| 8 | +from ninja.testing import TestClient |
| 9 | + |
| 10 | + |
| 11 | +class UserSchema(BaseModel): |
| 12 | + name: str |
| 13 | + email: str |
| 14 | + age: int |
| 15 | + avatar_url: Optional[str] = None |
| 16 | + |
| 17 | + |
| 18 | +class UserSchemaWithDefault(BaseModel): |
| 19 | + name: str = "Default" |
| 20 | + email: str |
| 21 | + age: int |
| 22 | + avatar_url: Optional[str] = None |
| 23 | + |
| 24 | + |
| 25 | +def test_patch_schema_basic(): |
| 26 | + PatchUserSchema = PatchSchema[UserSchema] |
| 27 | + |
| 28 | + # Test empty initialization |
| 29 | + patch_data = cast(PatchedModel, PatchUserSchema()) |
| 30 | + assert patch_data.model_dump() == {} |
| 31 | + |
| 32 | + # Test field initialization |
| 33 | + patch_data = cast(PatchedModel, PatchUserSchema(name="New Name")) |
| 34 | + assert patch_data.model_dump() == {"name": "New Name"} |
| 35 | + |
| 36 | + # Test multiple fields |
| 37 | + patch_data = cast( |
| 38 | + PatchedModel, PatchUserSchema( name="New Name", email="[email protected]") |
| 39 | + ) |
| 40 | + assert patch_data. model_dump() == { "name": "New Name", "email": "[email protected]"} |
| 41 | + |
| 42 | + |
| 43 | +def test_patch_schema_with_optional_fields(): |
| 44 | + PatchUserSchema = PatchSchema[UserSchema] |
| 45 | + |
| 46 | + # Test setting optional field to None |
| 47 | + patch_data = cast(PatchedModel, PatchUserSchema(avatar_url=None)) |
| 48 | + assert patch_data.model_dump() == {"avatar_url": None} |
| 49 | + |
| 50 | + # Test setting optional field to value |
| 51 | + patch_data = cast( |
| 52 | + PatchedModel, PatchUserSchema(avatar_url="https://example.com/avatar.png") |
| 53 | + ) |
| 54 | + assert patch_data.model_dump() == {"avatar_url": "https://example.com/avatar.png"} |
| 55 | + |
| 56 | + |
| 57 | +def test_patch_schema_none_validation(): |
| 58 | + PatchUserSchema = PatchSchema[UserSchema] |
| 59 | + |
| 60 | + # Non-optional fields should not allow None |
| 61 | + with pytest.raises(ValidationError) as exc_info: |
| 62 | + PatchUserSchema(name=None) |
| 63 | + |
| 64 | + assert "Field 'name' cannot be None" in str(exc_info.value) |
| 65 | + |
| 66 | + with pytest.raises(ValidationError) as exc_info: |
| 67 | + PatchUserSchema(email=None) |
| 68 | + |
| 69 | + assert "Field 'email' cannot be None" in str(exc_info.value) |
| 70 | + |
| 71 | + |
| 72 | +def test_patch_schema_with_defaults(): |
| 73 | + PatchUserSchemaWithDefault = PatchSchema[UserSchemaWithDefault] |
| 74 | + |
| 75 | + # Default values should not be included in the output unless explicitly set |
| 76 | + patch_data = cast(PatchedModel, PatchUserSchemaWithDefault()) |
| 77 | + assert patch_data.model_dump() == {} |
| 78 | + |
| 79 | + patch_data = cast(PatchedModel, PatchUserSchemaWithDefault(name="Custom Name")) |
| 80 | + assert patch_data.model_dump() == {"name": "Custom Name"} |
| 81 | + |
| 82 | + |
| 83 | +# API integration tests |
| 84 | +api = NinjaAPI() |
| 85 | +client = TestClient(api) |
| 86 | + |
| 87 | + |
| 88 | +class UserSchemaAPI(Schema): |
| 89 | + name: str |
| 90 | + email: str |
| 91 | + age: int |
| 92 | + avatar_url: Optional[str] = None |
| 93 | + |
| 94 | + |
| 95 | +@api.post("/users") |
| 96 | +def create_user(request, data: UserSchemaAPI): |
| 97 | + return data |
| 98 | + |
| 99 | + |
| 100 | +@api.patch("/users/{user_id}") |
| 101 | +def update_user(request, user_id: int, data: PatchSchema[UserSchemaAPI]): |
| 102 | + # Return the data and its type to verify it's working correctly |
| 103 | + return {"id": user_id, "data": data.model_dump(), "type": str(type(data).__name__)} |
| 104 | + |
| 105 | + |
| 106 | +def test_api_integration(): |
| 107 | + # First create a user |
| 108 | + create_response = client.post( |
| 109 | + "/users", json={ "name": "Test User", "email": "[email protected]", "age": 30} |
| 110 | + ) |
| 111 | + assert create_response.status_code == 200 |
| 112 | + |
| 113 | + # Test partial update with patch |
| 114 | + patch_response = client.patch("/users/1", json={"name": "Updated Name"}) |
| 115 | + assert patch_response.status_code == 200 |
| 116 | + assert patch_response.json() == { |
| 117 | + "id": 1, |
| 118 | + "data": {"name": "Updated Name"}, |
| 119 | + "type": f"Patched{UserSchemaAPI.__name__}", |
| 120 | + } |
| 121 | + |
| 122 | + # Test multiple fields update |
| 123 | + patch_response = client.patch("/users/1", json={"name": "New Name", "age": 31}) |
| 124 | + assert patch_response.status_code == 200 |
| 125 | + assert patch_response.json() == { |
| 126 | + "id": 1, |
| 127 | + "data": {"name": "New Name", "age": 31}, |
| 128 | + "type": f"Patched{UserSchemaAPI.__name__}", |
| 129 | + } |
| 130 | + |
| 131 | + # Test optional field set to null |
| 132 | + patch_response = client.patch("/users/1", json={"avatar_url": None}) |
| 133 | + assert patch_response.status_code == 200 |
| 134 | + assert patch_response.json() == { |
| 135 | + "id": 1, |
| 136 | + "data": {"avatar_url": None}, |
| 137 | + "type": f"Patched{UserSchemaAPI.__name__}", |
| 138 | + } |
| 139 | + |
| 140 | + # Test validation error when setting non-optional field to null |
| 141 | + error_response = client.patch("/users/1", json={"name": None}) |
| 142 | + assert error_response.status_code == 422 # Validation error |
| 143 | + |
| 144 | + |
| 145 | +def test_direct_instantiation_error(): |
| 146 | + with pytest.raises(TypeError) as exc_info: |
| 147 | + PatchSchema() |
| 148 | + |
| 149 | + assert "Cannot instantiate abstract PatchSchema class" in str(exc_info.value) |
| 150 | + |
| 151 | + |
| 152 | +def test_subclass_error(): |
| 153 | + with pytest.raises(TypeError) as exc_info: |
| 154 | + |
| 155 | + class MyPatchSchema(PatchSchema): |
| 156 | + pass |
| 157 | + |
| 158 | + assert "Cannot subclass" in str(exc_info.value) |
| 159 | + |
| 160 | + |
| 161 | +def test_openapi_schema(): |
| 162 | + """Test that the OpenAPI schema for a patched model is correctly generated.""" |
| 163 | + schema = api.get_openapi_schema() |
| 164 | + patched_schema = schema["components"]["schemas"][f"Patched{UserSchemaAPI.__name__}"] |
| 165 | + |
| 166 | + assert patched_schema["type"] == "object" |
| 167 | + assert "properties" in patched_schema |
| 168 | + |
| 169 | + # Check that name is optional in the schema |
| 170 | + assert "name" in patched_schema["properties"] |
| 171 | + |
| 172 | + # In Pydantic v2, optional fields use anyOf with multiple types including null |
| 173 | + name_prop = patched_schema["properties"]["name"] |
| 174 | + assert "anyOf" in name_prop |
| 175 | + assert any(item["type"] == "string" for item in name_prop["anyOf"]) |
| 176 | + assert any(item["type"] == "null" for item in name_prop["anyOf"]) |
| 177 | + |
| 178 | + # No required fields in patched schema |
| 179 | + assert "required" not in patched_schema or "name" not in patched_schema["required"] |
| 180 | + |
| 181 | + # Check that avatar_url is still optional |
| 182 | + assert "avatar_url" in patched_schema["properties"] |
| 183 | + avatar_prop = patched_schema["properties"]["avatar_url"] |
| 184 | + assert "anyOf" in avatar_prop |
| 185 | + assert any(item["type"] == "string" for item in avatar_prop["anyOf"]) |
| 186 | + assert any(item["type"] == "null" for item in avatar_prop["anyOf"]) |
0 commit comments