respx icon indicating copy to clipboard operation
respx copied to clipboard

Fix possible types for json parameter to Route.respond

Open viccie30 opened this issue 11 months ago • 6 comments

According to the Python documentation, more than just strings, dicts, and lists can be encoded to JSON.

viccie30 avatar Jan 22 '25 17:01 viccie30

You're right @viccie30, though we need to align with the httpx api here, rather than python's, since thats what we're mocking.

Looks like httpx is typing json as Any, probably due to the option of switching in custom json library over build-int 🤔

Also, the python docs you're referring to touches encoding, e.g. python accepts tuples when dumping to json, but the response we're talking about here is about a loaded/decoded json ...

>>> json.loads(json.dumps(("httpx", "respx")))
['httpx', 'respx']

lundberg avatar Jan 24 '25 07:01 lundberg

Looks like we've diverged from httpx on the request/encoding side as well .. also typed as Any

lundberg avatar Jan 24 '25 08:01 lundberg

Also, the python docs you're referring to touches encoding, e.g. python accepts tuples when dumping to json, but the response we're talking about here is about a loaded/decoded json ...

Oh right, because this is mocking the returned value of httpx.Response's json property.

I think you're right therefore to copy httpx's annotations.

viccie30 avatar Jan 24 '25 10:01 viccie30

I think you're right therefore to copy httpx's annotations.

Yes, let's change to Any for the respond/response.

About the request/encoding side, I think we're fine with current typing. We're mimicking httpx api there as well, but we're not patching/mocking, but rather pattern matching encoded request json.

lundberg avatar Jan 24 '25 11:01 lundberg

The current state of the art: https://github.com/python/typing/issues/182#issuecomment-1320974824

g-as avatar Jan 24 '25 16:01 g-as

The current state of the art: python/typing#182 (comment)

Might be worth discussing, but since json.loads is typed to return Any, it may be incorrect to type it as your linked suggestion @g-as, even though I agree it would be neat.

Sticking with how httpx is typed is probably what we're "forced" to do .. maybe take your suggestion to a httpx and discuss the Any choice vs Json type there?

lundberg avatar Jan 27 '25 09:01 lundberg