1. michilu
  2. WebTest

Commits

Gael Pasgrimaud  committed 9830374

add *_json methods

  • Participants
  • Parent commits 4b6c013
  • Branches default

Comments (0)

Files changed (3)

File tests/test_testing.py

View file
  • Ignore whitespace
 from webtest.compat import print_stderr
 from tests.compat import unittest
 from tests.compat import u
+import webbrowser
+
 
 
 def test_print_unicode():
         res.mustcontain('a=1')
         res = self.app.post('/', params=[('a','1')])
         res.mustcontain('a=1')
+        res = self.app.post_json('/', params=dict(a=1))
+        res.mustcontain('{"a": 1}')
+
+    def test_put_params(self):
+        res = self.app.put('/', params=dict(a=1))
+        res.mustcontain('a=1')
+        res = self.app.put_json('/', params=dict(a=1))
+        res.mustcontain('{"a": 1}')
 
     def test_delete_params(self):
         res = self.app.delete('/', params=dict(a=1))
         res.mustcontain('a=1')
+        res = self.app.delete_json('/', params=dict(a=1))
+        res.mustcontain('{"a": 1}')
 
     def test_options(self):
         res = self.app.options('/')
         self.assertRaises(Exception, self.app.get, '/?error=t')
         self.assertRaises(webtest.AppError, self.app.get, '/?status=404%20Not%20Found')
 
+    def test_showbrowser(self):
+        open_new = webbrowser.open_new
+        self.filename = ''
+        def open_new(f):
+            self.filename = f
+        webbrowser.open_new = open_new
+        res = self.app.get('/')
+        res.showbrowser()
+        assert self.filename.startswith('file://'), self.filename
+
     def test_303(self):
         res = self.app.get('/?status=303%20Redirect&header-location=/foo')
         self.assertEqual(res.status_int, 303)

File webtest/app.py

View file
  • Ignore whitespace
 from webtest.compat import to_string
 from webtest.compat import to_bytes
 from webtest.compat import join_bytes
+from webtest.compat import dumps
+from webtest.compat import loads
 from webtest.compat import PY3
 from webob import Request, Response
 
         for s in strings:
             if not s in self:
                 print_stderr("Actual response (no %r):" % s)
-                print_stderr(self)
+                print_stderr(str(self))
                 raise IndexError(
                     "Body does not contain string %r" % s)
         for no_s in no:
             if no_s in self:
                 print_stderr("Actual response (has %r)" % no_s)
-                print_stderr(self)
+                print_stderr(str(self))
                 raise IndexError(
                     "Body contains bad string %r" % no_s)
 
             raise AttributeError(
                 "Not a JSON response body (content-type: %s)"
                 % self.content_type)
-        try:
-            from simplejson import loads
-        except ImportError:
-            try:
-                from json import loads
-            except ImportError:
-                raise ImportError(
-                    "You must have simplejson installed to use response.json")
+        if loads is None:
+            raise ImportError(
+                "You must have simplejson installed to use response.json")
         return loads(self.testbody)
 
     json = property(json, doc=json.__doc__)
                                  expect_errors=expect_errors,
                                  content_type=content_type)
 
+    def post_json(self, url, params='', headers=None, extra_environ=None,
+                  status=None, expect_errors=False):
+        """
+        Do a POST request.  Very like the ``.get()`` method.
+        ``params`` are dumps to json and put in the body of the request.
+        Content-Type is set to ``application/json``.
+
+        Returns a ``webob.Response`` object.
+        """
+        content_type = 'application/json'
+        if params:
+            params = dumps(params)
+        return self._gen_request('POST', url, params=params, headers=headers,
+                                 extra_environ=extra_environ, status=status,
+                                 upload_files=None,
+                                 expect_errors=expect_errors,
+                                 content_type=content_type)
+
     def put(self, url, params='', headers=None, extra_environ=None,
             status=None, upload_files=None, expect_errors=False,
             content_type=None):
         """
-        Do a PUT request.  Very like the ``.put()`` method.
+        Do a PUT request.  Very like the ``.post()`` method.
         ``params`` are put in the body of the request, if params is a
         tuple, dictionary, list, or iterator it will be urlencoded and
         placed in the body as with a POST, if it is string it will not
                                  expect_errors=expect_errors,
                                  content_type=content_type)
 
+    def put_json(self, url, params='', headers=None, extra_environ=None,
+            status=None, expect_errors=False):
+        """
+        Do a PUT request.  Very like the ``.post()`` method.
+        ``params`` are dumps to json and put in the body of the request.
+        Content-Type is set to ``application/json``.
+
+        Returns a ``webob.Response`` object.
+        """
+        content_type = 'application/json'
+        if params:
+            params = dumps(params)
+        return self._gen_request('PUT', url, params=params, headers=headers,
+                                 extra_environ=extra_environ, status=status,
+                                 upload_files=None,
+                                 expect_errors=expect_errors,
+                                 content_type=content_type)
+
     def delete(self, url, params='', headers=None, extra_environ=None,
-               status=None, expect_errors=False):
+               status=None, expect_errors=False, content_type=None):
         """
         Do a DELETE request.  Very like the ``.get()`` method.
 
         return self._gen_request('DELETE', url, params=params, headers=headers,
                                  extra_environ=extra_environ, status=status,
                                  upload_files=None,
-                                 expect_errors=expect_errors)
+                                 expect_errors=expect_errors,
+                                 content_type=content_type)
+
+    def delete_json(self, url, params='', headers=None, extra_environ=None,
+               status=None, expect_errors=False):
+        """
+        Do a DELETE request.  Very like the ``.get()`` method.
+        Content-Type is set to ``application/json``.
+
+        Returns a ``webob.Response`` object.
+        """
+        if params:
+            warnings.warn(('You are not supposed to send a body in a '
+                           'DELETE request. Most web servers will ignore it'),
+                           lint.WSGIWarning)
+        content_type = 'application/json'
+        if params:
+            params = dumps(params)
+        return self._gen_request('DELETE', url, params=params, headers=headers,
+                                 extra_environ=extra_environ, status=status,
+                                 upload_files=None,
+                                 expect_errors=expect_errors,
+                                 content_type=content_type)
 
     def options(self, url, headers=None, extra_environ=None,
                status=None, expect_errors=False):

File webtest/compat.py

View file
  • Ignore whitespace
     string_types = (str,)
     text_type = str
     binary_type = bytes
+    from json import loads
+    from json import dumps
     from io import StringIO
     from io import BytesIO
     from urllib.parse import urlencode
         from StringIO import StringIO
     BytesIO = StringIO
     import urlparse
+    try:
+        from json import loads
+        from json import dumps
+    except ImportError:
+        try:
+            from simplejson import loads
+            from simplejson import dumps
+        except ImportError:
+            loads = None
+            dumps = None
 
     def to_bytes(s):
         return str(s)