/ justapi / crates / justapi-py / python / justapi / test_schema_validation.py
swadhinbiswas test: align with {"detail": ...} error envelope · 7/15/2026
503c9b7
226 lines · 7.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
"""Integration test for Phase 11 — JSON Schema validation (Schema class + Pydantic bridge).
"""
import json
import subprocess
import sys
import time
import urllib.request
import urllib.error

SERVER_SCRIPT = r'''
from justapi import JustAPIApp, Schema
import json

class UserSchema(Schema):
    name: str
    email: str
    age: int | None = None

async def create_user(request):
    body = json.loads(request["body"])
    return {
        "status": 201,
        "body": json.dumps({"id": 1, **body}).encode("utf-8"),
        "headers": [(b"content-type", b"application/json")],
    }

async def hello_handler(request):
    name = request["path_params"]["name"]
    return {"message": f"Hello {name}!"}

app = JustAPIApp()

app.get("/hello/{name}", hello_handler)
app.post("/users", create_user, schema=UserSchema)

# Pydantic bridge test
from pydantic import BaseModel
class ProductModel(BaseModel):
    name: str
    price: float

async def create_product(request):
    body = json.loads(request["body"])
    return {"status": 201, "body": json.dumps({"sku": 42, **body}).encode(), "headers": [(b"content-type", b"application/json")]}

app.post("/products", create_product, schema=ProductModel)

# Raw JSON Schema string test
raw_schema = json.dumps({
    "type": "object",
    "properties": {
        "title": {"type": "string"},
        "year": {"type": "integer"}
    },
    "required": ["title"],
    "additionalProperties": False
})

async def create_movie(request):
    body = json.loads(request["body"])
    return {"status": 201, "body": json.dumps({"id": 7, **body}).encode(), "headers": [(b"content-type", b"application/json")]}

app.post("/movies", create_movie, schema=raw_schema)

app.run("127.0.0.1:9869")
'''


def test_schema_validation():
    proc = subprocess.Popen(
        [sys.executable, "-c", SERVER_SCRIPT],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    addr = "127.0.0.1:9869"
    time.sleep(0.8)

    try:
        # 1. Basic route still works
        resp = urllib.request.urlopen(f"http://{addr}/hello/world")
        assert resp.status == 200, f"Expected 200, got {resp.status}"
        data = json.loads(resp.read())
        assert data == {"message": "Hello world!"}
        print("PASS: GET /hello/world -> 200")

        # 2. Schema class: valid POST
        payload = json.dumps({"name": "Alice", "email": "[email protected]", "age": 30}).encode()
        req = urllib.request.Request(
            f"http://{addr}/users",
            data=payload,
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        resp = urllib.request.urlopen(req)
        assert resp.status == 201, f"Expected 201, got {resp.status}"
        data = json.loads(resp.read())
        assert data["name"] == "Alice"
        assert data["email"] == "[email protected]"
        assert data["age"] == 30
        print("PASS: Schema class valid POST -> 201")

        # 3. Schema class: missing required field
        payload = json.dumps({"name": "Alice"}).encode()
        req = urllib.request.Request(
            f"http://{addr}/users",
            data=payload,
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        try:
            urllib.request.urlopen(req)
            assert False, "Expected 422"
        except urllib.error.HTTPError as e:
            assert e.code == 422, f"Expected 422, got {e.code}"
            error_data = json.loads(e.read())
            assert isinstance(error_data.get("detail"), str) and len(error_data["detail"]) > 0
            assert "email" in error_data["detail"].lower()
            print("PASS: Schema class missing field -> 422")

        # 4. Schema class: wrong type
        payload = json.dumps({"name": "Alice", "email": "[email protected]", "age": "not a number"}).encode()
        req = urllib.request.Request(
            f"http://{addr}/users",
            data=payload,
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        try:
            urllib.request.urlopen(req)
            assert False, "Expected 422"
        except urllib.error.HTTPError as e:
            assert e.code == 422
            print("PASS: Schema class wrong type -> 422")

        # 5. Pydantic bridge: valid POST
        payload = json.dumps({"name": "Widget", "price": 9.99}).encode()
        req = urllib.request.Request(
            f"http://{addr}/products",
            data=payload,
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        resp = urllib.request.urlopen(req)
        assert resp.status == 201
        data = json.loads(resp.read())
        assert data["name"] == "Widget"
        assert data["price"] == 9.99
        print("PASS: Pydantic bridge valid POST -> 201")

        # 6. Pydantic bridge: missing required field
        payload = json.dumps({"name": "Widget"}).encode()
        req = urllib.request.Request(
            f"http://{addr}/products",
            data=payload,
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        try:
            urllib.request.urlopen(req)
            assert False, "Expected 422"
        except urllib.error.HTTPError as e:
            assert e.code == 422
            print("PASS: Pydantic bridge missing field -> 422")

        # 7. Raw JSON Schema string: valid POST
        payload = json.dumps({"title": "Inception", "year": 2010}).encode()
        req = urllib.request.Request(
            f"http://{addr}/movies",
            data=payload,
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        resp = urllib.request.urlopen(req)
        assert resp.status == 201
        print("PASS: Raw JSON Schema valid POST -> 201")

        # 8. Raw JSON Schema string: missing required field
        payload = json.dumps({"year": 2010}).encode()
        req = urllib.request.Request(
            f"http://{addr}/movies",
            data=payload,
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        try:
            urllib.request.urlopen(req)
            assert False, "Expected 422"
        except urllib.error.HTTPError as e:
            assert e.code == 422
            print("PASS: Raw JSON Schema missing field -> 422")

        # 9. Invalid JSON body
        req = urllib.request.Request(
            f"http://{addr}/users",
            data=b"not json",
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        try:
            urllib.request.urlopen(req)
            assert False, "Expected 422"
        except urllib.error.HTTPError as e:
            assert e.code == 422
            error_data = json.loads(e.read())
            assert "Invalid JSON" in error_data["detail"]
            print("PASS: Invalid JSON body -> 422")

        print()
        print("=== All schema validation tests PASSED ===")

    finally:
        proc.terminate()
        try:
            stdout, stderr = proc.communicate(timeout=5)
            if stderr:
                decoded = stderr.decode()
                if decoded.strip():
                    print("Server stderr:", decoded)
        except subprocess.TimeoutExpired:
            proc.kill()
            proc.communicate()


if __name__ == "__main__":
    test_schema_validation()