From efda67cf1dffcb90eb668c3db00a1149f35c953b Mon Sep 17 00:00:00 2001 From: Alexander Shorin Date: Thu, 28 Aug 2014 14:33:30 +0400 Subject: [PATCH] Pass falsy data to ClientRequest.update_body_from_data handler While logic of processing only "true" values to form request body is ok for plain raw requests, it causes troubles when you inherit from ClientRequest to produce requests for some specific content type. For instance, it's ok to pass "falsy" `0`, `False`, `{}` data if you're implementing JsonClientRequest class that automatically encodes data inside update_body_from_data method. --- aiohttp/client.py | 7 ++++--- tests/test_client.py | 7 +++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/aiohttp/client.py b/aiohttp/client.py index 2e450391839..43c232c875e 100644 --- a/aiohttp/client.py +++ b/aiohttp/client.py @@ -205,9 +205,7 @@ def __init__(self, method, url, *, 'not supported at the same time.') data = files - if data: - self.update_body_from_data(data) - + self.update_body_from_data(data) self.update_transfer_encoding() self.update_expect_continue(expect100) @@ -361,6 +359,9 @@ def update_auth(self, auth): self.headers['AUTHORIZATION'] = auth.encode() def update_body_from_data(self, data): + if not data: + return + if isinstance(data, str): data = data.encode(self.encoding) diff --git a/tests/test_client.py b/tests/test_client.py index 35a1fac73a8..7f888211617 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -504,6 +504,13 @@ def test_post_data(self): self.assertEqual('application/x-www-form-urlencoded', req.headers['CONTENT-TYPE']) + @unittest.mock.patch('aiohttp.client.ClientRequest.update_body_from_data') + def test_pass_falsy_data(self, _): + req = ClientRequest( + 'post', 'http://python.org/', + data={}, loop=self.loop) + req.update_body_from_data.assert_called_once_with({}) + def test_get_with_data(self): for meth in ClientRequest.GET_METHODS: req = ClientRequest(