[PATCH cwclientlib] Add a "post_json" method to CWProxy

Denis Laxalde denis.laxalde at logilab.fr
Thu Jun 7 17:15:38 CEST 2018


# HG changeset patch
# User Denis Laxalde <denis.laxalde at logilab.fr>
# Date 1528383855 -7200
#      Thu Jun 07 17:04:15 2018 +0200
# Node ID 8ce8450f36a50c8ff112eea942da817dae6bddde
# Parent  fb19340eb36ecc07a7552df34074cd7548a0f894
# Available At http://hg.logilab.org/review/cwclientlib/
#              hg pull http://hg.logilab.org/review/cwclientlib/ -r 8ce8450f36a5
# EXP-Topic post-json
Add a "post_json" method to CWProxy

This is basically a wrapper to requests.post(json=data). We cannot
actually reuse (extend) the existing "post" method of CWProxy because it
would not be backwards compatible.

diff --git a/cwclientlib/cwproxy.py b/cwclientlib/cwproxy.py
--- a/cwclientlib/cwproxy.py
+++ b/cwclientlib/cwproxy.py
@@ -188,6 +188,19 @@ class CWProxy(object):
             kwargs['files'] = data.pop('files')
         return self.handle_request('POST', path, **kwargs)
 
+    def post_json(self, path, payload):
+        """Perform a POST on the cubicweb instance with application/json
+        Content-Type.
+
+        :param path: the path part of the URL that will be GET
+        :param payload: native data to be sent as JSON (not encoded)
+        """
+        kwargs = {
+            'headers': {'Accept': 'application/json'},
+            'json': payload,
+        }
+        return self.handle_request('POST', path, **kwargs)
+
     def view(self, vid, **args):
         """Perform a GET on <base_url>/view with <vid> and <args>
 
diff --git a/cwclientlib/test/test_cwproxy.py b/cwclientlib/test/test_cwproxy.py
--- a/cwclientlib/test/test_cwproxy.py
+++ b/cwclientlib/test/test_cwproxy.py
@@ -17,6 +17,7 @@
 # along with cwclientlib. If not, see <http://www.gnu.org/licenses/>.
 
 from io import BytesIO
+import json
 from datetime import date, datetime, timedelta
 
 import pytz
@@ -212,6 +213,18 @@ class CWProxyClientTC(CubicWebWsgiTC):
         )
         self.assertIn('some content', bodylines)
 
+    def test_post_json(self):
+        data = {'foo': 1}
+        response = self.client.post_json('/foo/bar', data)
+        self.assertEqual(response.status_code, 404)
+        request = response.request
+        self.assertEqual(request.method, 'POST')
+        headers = request.headers
+        content_type = headers['Content-Type']
+        self.assertEqual(content_type, 'application/json')
+        body = request.body
+        self.assertEqual(json.loads(body), data)
+
 
 class UtilsTests(unittest.TestCase):
 


More information about the cubicweb-devel mailing list