Debian Codegraph @

tests/test_serialization_context.py

raw symbols SCIP
1 from unittest import mock
2
3 import pytest
4 from pydantic import model_serializer
5
6 from ninja import Router, Schema
7 from ninja.schema import pydantic_version
8 from ninja.testing import TestClient
9
10
11 def api_endpoint_test(request):
12 return {
13 "test1": "foo",
14 "test2": "bar",
15 }
16
17
18 @pytest.mark.skipif(
19 pydantic_version < [2, 7],
20 reason="Serialization context was introduced in Pydantic 2.7",
21 )
22 def test_request_is_passed_in_context_when_supported():
23 class SchemaWithCustomSerializer(Schema):
24 test1: str
25 test2: str
26
27 @model_serializer(mode="wrap")
28 def ser_model(self, handler, info):
29 assert "request" in info.context
30 assert info.context["request"].path == "/test" # check it is HttRequest
31 assert "response_status" in info.context
32
33 return handler(self)
34
35 router = Router()
36 router.add_api_operation(
37 "/test", ["GET"], api_endpoint_test, response=SchemaWithCustomSerializer
38 )
39
40 TestClient(router).get("/test")
41
42
43 @pytest.mark.parametrize(
44 ["pydantic_version"],
45 [
46 [[2, 0]],
47 [[2, 4]],
48 [[2, 6]],
49 ],
50 )
51 def test_no_serialisation_context_used_when_no_supported(pydantic_version):
52 class SchemaWithCustomSerializer(Schema):
53 test1: str
54 test2: str
55
56 @model_serializer(mode="wrap")
57 def ser_model(self, handler, info):
58 if hasattr(info, "context"):
59 # an actually newer Pydantic, but pydantic_version is still mocked, so no context is expected
60 assert info.context is None
61
62 return handler(self)
63
64 with mock.patch("ninja.operation.pydantic_version", pydantic_version):
65 router = Router()
66 router.add_api_operation(
67 "/test", ["GET"], api_endpoint_test, response=SchemaWithCustomSerializer
68 )
69
70 resp_json = TestClient(router).get("/test").json()
71
72 assert resp_json == {
73 "test1": "foo",
74 "test2": "bar",
75 }