Skip to content

Commit a7fa5e9

Browse files
authored
Merge pull request #171 from abhirajadhikary06/fix/empty-request-body
fix(request_handler): preserve falsy non-None request bodies
2 parents 0f7fe6d + 1fb76b7 commit a7fa5e9

2 files changed

Lines changed: 44 additions & 1 deletion

File tree

‎src/typesense/request_handler.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ def build_request_kwargs(
318318
self.normalize_params(params)
319319
request_kwargs["params"] = params
320320

321-
if body := kwargs.get("data"):
321+
if (body := kwargs.get("data")) is not None:
322322
request_kwargs["content"] = (
323323
body if isinstance(body, (str, bytes)) else json.dumps(body)
324324
)

‎tests/api_call_test.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,32 @@ def test_normalize_params_with_no_booleans() -> None:
179179
assert parameter_dict == {"key1": "value", "key2": 123}
180180

181181

182+
@pytest.mark.parametrize(
183+
("data", "expected_content"),
184+
[
185+
({}, "{}"),
186+
("", ""),
187+
(b"", b""),
188+
],
189+
)
190+
def test_build_request_kwargs_preserves_empty_body(
191+
fake_config: Configuration,
192+
data: typing.Union[typing.Dict[str, typing.Any], str, bytes],
193+
expected_content: typing.Union[str, bytes],
194+
) -> None:
195+
"""Test that falsy non-None bodies such as {} and '' are preserved."""
196+
handler = RequestHandler(fake_config)
197+
request_kwargs = handler.build_request_kwargs(data=data)
198+
assert request_kwargs["content"] == expected_content
199+
200+
201+
def test_build_request_kwargs_omits_none_body(fake_config: Configuration) -> None:
202+
"""Test that a None body does not set content."""
203+
handler = RequestHandler(fake_config)
204+
request_kwargs = handler.build_request_kwargs(data=None)
205+
assert "content" not in request_kwargs
206+
207+
182208
def test_additional_headers(fake_api_call: ApiCall) -> None:
183209
"""Test the `make_request` method with additional headers from the config."""
184210
api_call = ApiCall(
@@ -347,6 +373,23 @@ def test_post_as_text(
347373
assert post_result == "response text"
348374

349375

376+
def test_post_with_empty_dict_body(fake_api_call: ApiCall) -> None:
377+
"""Test that POST sends '{}' when body={} is passed."""
378+
with respx.mock:
379+
route = respx.post("http://nearest:8108/analytics/flush").mock(
380+
return_value=httpx.Response(200, json={"ok": True}),
381+
)
382+
result = fake_api_call.post(
383+
"/analytics/flush",
384+
body={},
385+
as_json=True,
386+
entity_type=typing.Dict[str, bool],
387+
)
388+
389+
assert result == {"ok": True}
390+
assert route.calls.last.request.content == b"{}"
391+
392+
350393
def test_put_as_json(
351394
fake_api_call: ApiCall,
352395
) -> None:

0 commit comments

Comments
 (0)