1
+ import json
2
+ from datetime import date , datetime
1
3
from typing import Any , Callable
4
+ from uuid import UUID
2
5
3
6
import httpx
4
7
import llsd
8
11
from starlette .types import Receive , Scope , Send
9
12
10
13
from llsd_asgi import LLSDMiddleware
14
+ from llsd_asgi .middleware import JSONEncoder
11
15
from tests .utils import mock_receive , mock_send
12
16
13
17
Format = Callable [[Any ], bytes ]
@@ -29,19 +33,22 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
29
33
content_type = request .headers ["content-type" ]
30
34
data = await request .json ()
31
35
message = data ["message" ]
32
- text = f"content_type={ content_type !r} message={ message !r} "
36
+ text = f"content_type={ content_type !r} message={ message !r} id= { data [ 'id' ]!r } "
33
37
34
38
response = PlainTextResponse (text )
35
39
await response (scope , receive , send )
36
40
37
41
app = LLSDMiddleware (app )
38
42
39
43
async with httpx .AsyncClient (app = app , base_url = "http://testserver" ) as client :
40
- content = {"message" : "Hello, world!" }
44
+ content = {"message" : "Hello, world!" , "id" : UUID ( "380cbef3-74de-411b-bf5c-9ad98b376b41" ) }
41
45
body = format (content )
42
46
r = await client .post ("/" , content = body , headers = {"content-type" : content_type })
43
47
assert r .status_code == 200
44
- assert r .text == "content_type='application/json' message='Hello, world!'"
48
+ assert (
49
+ r .text
50
+ == "content_type='application/json' message='Hello, world!' id='380cbef3-74de-411b-bf5c-9ad98b376b41'"
51
+ )
45
52
46
53
47
54
@pytest .mark .asyncio
@@ -199,3 +206,23 @@ async def test_quirks_exceptions(accept: str) -> None:
199
206
assert r .status_code == 200
200
207
assert r .headers ["content-type" ] == "application/json"
201
208
assert r .json () == {"message" : "Hello, world!" }
209
+
210
+
211
+ @pytest .mark .asyncio
212
+ @pytest .mark .parametrize (
213
+ "input,expected" ,
214
+ [
215
+ (datetime (2024 , 1 , 1 , 0 , 0 , 0 ), '"2024-01-01T00:00:00.000000Z"' ),
216
+ (date (2024 , 1 , 1 ), '"2024-01-01T00:00:00.000000Z"' ),
217
+ (UUID ("c72736e5-e9e4-4779-b46b-b49467e425ff" ), '"c72736e5-e9e4-4779-b46b-b49467e425ff"' ),
218
+ (b"Hello" , '"SGVsbG8="' ),
219
+ ],
220
+ )
221
+ async def test_json_encoder (input : Any , expected : Any ):
222
+ assert json .dumps (input , cls = JSONEncoder ) == expected
223
+
224
+
225
+ @pytest .mark .asyncio
226
+ async def test_json_encoder_calls_default ():
227
+ with pytest .raises (TypeError ):
228
+ json .dumps (object (), cls = JSONEncoder )
0 commit comments