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
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
"""Unit tests for OpenAPI models."""

import pytest

from fastmcp.experimental.utilities.openapi.models import (
    HTTPRoute,
    ParameterInfo,
    RequestBodyInfo,
    ResponseInfo,
)


class TestParameterInfo:
    """Test ParameterInfo model."""

    def test_basic_parameter_creation(self):
        """Test creating a basic parameter."""
        param = ParameterInfo(
            name="id",
            location="path",
            required=True,
            schema={"type": "integer"},
        )

        assert param.name == "id"
        assert param.location == "path"
        assert param.required is True
        assert param.schema_ == {"type": "integer"}
        assert param.description is None
        assert param.explode is None
        assert param.style is None

    def test_parameter_with_all_fields(self):
        """Test creating parameter with all optional fields."""
        param = ParameterInfo(
            name="filter",
            location="query",
            required=False,
            schema={"type": "object", "properties": {"name": {"type": "string"}}},
            description="Filter criteria",
            explode=True,
            style="deepObject",
        )

        assert param.name == "filter"
        assert param.location == "query"
        assert param.required is False
        assert param.description == "Filter criteria"
        assert param.explode is True
        assert param.style == "deepObject"

    @pytest.mark.parametrize("location", ["path", "query", "header", "cookie"])
    def test_valid_parameter_locations(self, location):
        """Test that all valid parameter locations are accepted."""
        param = ParameterInfo(
            name="test",
            location=location,  # type: ignore
            required=False,
            schema={"type": "string"},
        )
        assert param.location == location

    def test_parameter_defaults(self):
        """Test parameter default values."""
        param = ParameterInfo(
            name="test",
            location="query",
            schema={"type": "string"},
        )

        # required should default to False for non-path parameters
        assert param.required is False
        assert param.description is None
        assert param.explode is None
        assert param.style is None

    def test_parameter_with_empty_schema(self):
        """Test parameter with empty schema."""
        param = ParameterInfo(
            name="test",
            location="query",
            schema={},
        )

        assert param.schema_ == {}


class TestRequestBodyInfo:
    """Test RequestBodyInfo model."""

    def test_basic_request_body(self):
        """Test creating a basic request body."""
        request_body = RequestBodyInfo(
            required=True,
            description="User data",
        )

        assert request_body.required is True
        assert request_body.description == "User data"
        assert request_body.content_schema == {}

    def test_request_body_with_content_schema(self):
        """Test request body with content schema."""
        content_schema = {
            "application/json": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "email": {"type": "string"},
                },
                "required": ["name"],
            }
        }

        request_body = RequestBodyInfo(
            required=True,
            content_schema=content_schema,
        )

        assert request_body.content_schema == content_schema

    def test_request_body_defaults(self):
        """Test request body default values."""
        request_body = RequestBodyInfo()

        assert request_body.required is False
        assert request_body.description is None
        assert request_body.content_schema == {}

    def test_request_body_multiple_content_types(self):
        """Test request body with multiple content types."""
        content_schema = {
            "application/json": {
                "type": "object",
                "properties": {"name": {"type": "string"}},
            },
            "application/xml": {
                "type": "object",
                "properties": {"name": {"type": "string"}},
            },
        }

        request_body = RequestBodyInfo(content_schema=content_schema)

        assert len(request_body.content_schema) == 2
        assert "application/json" in request_body.content_schema
        assert "application/xml" in request_body.content_schema


class TestResponseInfo:
    """Test ResponseInfo model."""

    def test_basic_response(self):
        """Test creating a basic response."""
        response = ResponseInfo(description="Success response")

        assert response.description == "Success response"
        assert response.content_schema == {}

    def test_response_with_content_schema(self):
        """Test response with content schema."""
        content_schema = {
            "application/json": {
                "type": "object",
                "properties": {
                    "id": {"type": "integer"},
                    "message": {"type": "string"},
                },
            }
        }

        response = ResponseInfo(
            description="User created",
            content_schema=content_schema,
        )

        assert response.description == "User created"
        assert response.content_schema == content_schema

    def test_response_required_description(self):
        """Test that response description is required."""
        # Should not raise an error - description has a default
        response = ResponseInfo()
        assert response.description is None


class TestHTTPRoute:
    """Test HTTPRoute model."""

    def test_basic_route_creation(self):
        """Test creating a basic HTTP route."""
        route = HTTPRoute(
            path="/users/{id}",
            method="GET",
            operation_id="get_user",
        )

        assert route.path == "/users/{id}"
        assert route.method == "GET"
        assert route.operation_id == "get_user"
        assert route.summary is None
        assert route.description is None
        assert route.tags == []
        assert route.parameters == []
        assert route.request_body is None
        assert route.responses == {}

    def test_route_with_all_fields(self):
        """Test creating route with all fields."""
        parameters = [
            ParameterInfo(
                name="id",
                location="path",
                required=True,
                schema={"type": "integer"},
            )
        ]

        request_body = RequestBodyInfo(
            required=True,
            content_schema={
                "application/json": {
                    "type": "object",
                    "properties": {"name": {"type": "string"}},
                }
            },
        )

        responses = {
            "200": ResponseInfo(
                description="Success",
                content_schema={
                    "application/json": {
                        "type": "object",
                        "properties": {"id": {"type": "integer"}},
                    }
                },
            )
        }

        route = HTTPRoute(
            path="/users/{id}",
            method="PUT",
            operation_id="update_user",
            summary="Update user",
            description="Update user by ID",
            tags=["users"],
            parameters=parameters,
            request_body=request_body,
            responses=responses,
            request_schemas={"User": {"type": "object"}},
            extensions={"x-custom": "value"},
        )

        assert route.path == "/users/{id}"
        assert route.method == "PUT"
        assert route.operation_id == "update_user"
        assert route.summary == "Update user"
        assert route.description == "Update user by ID"
        assert route.tags == ["users"]
        assert len(route.parameters) == 1
        assert route.request_body is not None
        assert "200" in route.responses
        assert "User" in route.request_schemas
        assert route.extensions["x-custom"] == "value"

    def test_route_pre_calculated_fields(self):
        """Test route with pre-calculated fields."""
        route = HTTPRoute(
            path="/test",
            method="GET",
            operation_id="test",
            flat_param_schema={
                "type": "object",
                "properties": {"id": {"type": "integer"}},
            },
            parameter_map={"id": {"location": "path", "openapi_name": "id"}},
        )

        assert route.flat_param_schema["type"] == "object"
        assert "id" in route.flat_param_schema["properties"]
        assert "id" in route.parameter_map
        assert route.parameter_map["id"]["location"] == "path"

    @pytest.mark.parametrize(
        "method", ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]
    )
    def test_valid_http_methods(self, method):
        """Test that all valid HTTP methods are accepted."""
        route = HTTPRoute(
            path="/test",
            method=method,  # type: ignore
            operation_id="test",
        )
        assert route.method == method

    def test_route_with_empty_collections(self):
        """Test route with empty collections."""
        route = HTTPRoute(
            path="/test",
            method="GET",
            operation_id="test",
            tags=[],
            parameters=[],
            responses={},
            request_schemas={},
            extensions={},
        )

        assert route.tags == []
        assert route.parameters == []
        assert route.responses == {}
        assert route.request_schemas == {}
        assert route.response_schemas == {}
        assert route.extensions == {}

    def test_route_defaults(self):
        """Test route default values."""
        route = HTTPRoute(
            path="/test",
            method="GET",
            operation_id="test",
        )

        assert route.summary is None
        assert route.description is None
        assert route.tags == []
        assert route.parameters == []
        assert route.request_body is None
        assert route.responses == {}
        assert route.request_schemas == {}
        assert route.response_schemas == {}
        assert route.extensions == {}
        assert route.flat_param_schema == {}
        assert route.parameter_map == {}


class TestModelValidation:
    """Test model validation and error cases."""

    def test_parameter_info_validation(self):
        """Test ParameterInfo validation."""
        # Valid parameter
        param = ParameterInfo(
            name="test",
            location="query",
            schema={"type": "string"},
        )
        assert param.name == "test"

    def test_route_validation(self):
        """Test HTTPRoute validation."""
        # Valid route
        route = HTTPRoute(
            path="/test",
            method="GET",
            operation_id="test",
        )
        assert route.path == "/test"

    def test_nested_model_validation(self):
        """Test validation of nested models."""
        # Create route with nested models
        param = ParameterInfo(
            name="id",
            location="path",
            required=True,
            schema={"type": "integer"},
        )

        request_body = RequestBodyInfo(required=True)

        route = HTTPRoute(
            path="/test/{id}",
            method="POST",
            operation_id="test",
            parameters=[param],
            request_body=request_body,
        )

        assert len(route.parameters) == 1
        assert route.parameters[0].name == "id"
        assert route.request_body is not None
        assert route.request_body.required is True


class TestModelSerialization:
    """Test model serialization and deserialization."""

    def test_parameter_info_serialization(self):
        """Test ParameterInfo serialization."""
        param = ParameterInfo(
            name="filter",
            location="query",
            required=False,
            schema={"type": "object"},
            description="Filter criteria",
            explode=True,
            style="deepObject",
        )

        # Test model_dump with alias
        data = param.model_dump(by_alias=True)

        assert data["name"] == "filter"
        assert data["location"] == "query"
        assert data["required"] is False
        assert data["schema"] == {"type": "object"}  # Using alias
        assert data["description"] == "Filter criteria"
        assert data["explode"] is True
        assert data["style"] == "deepObject"

    def test_route_serialization(self):
        """Test HTTPRoute serialization."""
        param = ParameterInfo(
            name="id",
            location="path",
            required=True,
            schema={"type": "integer"},
        )

        route = HTTPRoute(
            path="/users/{id}",
            method="GET",
            operation_id="get_user",
            parameters=[param],
        )

        # Test model_dump
        data = route.model_dump()

        assert data["path"] == "/users/{id}"
        assert data["method"] == "GET"
        assert data["operation_id"] == "get_user"
        assert len(data["parameters"]) == 1
        assert data["parameters"][0]["name"] == "id"

    def test_model_reconstruction(self):
        """Test reconstructing models from serialized data."""
        # Create original parameter
        original_param = ParameterInfo(
            name="test",
            location="query",
            schema={"type": "string"},
            description="Test parameter",
        )

        # Serialize and reconstruct using by_alias
        data = original_param.model_dump(by_alias=True)
        reconstructed_param = ParameterInfo(**data)

        assert reconstructed_param.name == original_param.name
        assert reconstructed_param.location == original_param.location
        assert reconstructed_param.schema_ == original_param.schema_
        assert reconstructed_param.description == original_param.description