1+ import json
2+ from datetime import date , datetime
13from typing import Any , Callable
4+ from uuid import UUID
25
36import httpx
47import llsd
811from starlette .types import Receive , Scope , Send
912
1013from llsd_asgi import LLSDMiddleware
14+ from llsd_asgi .middleware import JSONEncoder
1115from tests .utils import mock_receive , mock_send
1216
1317Format = Callable [[Any ], bytes ]
@@ -29,19 +33,22 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
2933 content_type = request .headers ["content-type" ]
3034 data = await request .json ()
3135 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 } "
3337
3438 response = PlainTextResponse (text )
3539 await response (scope , receive , send )
3640
3741 app = LLSDMiddleware (app )
3842
3943 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" ) }
4145 body = format (content )
4246 r = await client .post ("/" , content = body , headers = {"content-type" : content_type })
4347 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+ )
4552
4653
4754@pytest .mark .asyncio
@@ -199,3 +206,23 @@ async def test_quirks_exceptions(accept: str) -> None:
199206 assert r .status_code == 200
200207 assert r .headers ["content-type" ] == "application/json"
201208 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