if request content-type is application/json, request data should be dumped

This commit is contained in:
debugtalk
2017-08-28 19:18:06 +08:00
parent 94a55827e7
commit 530f5bc89c
3 changed files with 28 additions and 4 deletions
+1 -1
View File
@@ -1 +1 @@
__version__ = '0.5.1' __version__ = '0.5.2'
+13 -2
View File
@@ -1,17 +1,27 @@
import json
import logging import logging
import re import re
import time import time
import requests import requests
from ate.exception import ParamsError
from requests import Request, Response from requests import Request, Response
from requests.exceptions import (InvalidSchema, InvalidURL, MissingSchema, from requests.exceptions import (InvalidSchema, InvalidURL, MissingSchema,
RequestException) RequestException)
from ate.exception import ParamsError
absolute_http_url_regexp = re.compile(r"^https?://", re.I) absolute_http_url_regexp = re.compile(r"^https?://", re.I)
def process_kwargs(method, **kwargs):
if method == "POST":
# if request content-type is application/json, request data should be dumped
content_type = kwargs.get("headers", {}).get("content-type", "")
if content_type.startswith("application/json") and "data" in kwargs:
kwargs["data"] = json.dumps(kwargs["data"])
return kwargs
class ApiResponse(Response): class ApiResponse(Response):
def raise_for_status(self): def raise_for_status(self):
@@ -142,6 +152,7 @@ class HttpSession(requests.Session):
Safe mode has been removed from requests 1.x. Safe mode has been removed from requests 1.x.
""" """
try: try:
kwargs = process_kwargs(method, **kwargs)
return requests.Session.request(self, method, url, **kwargs) return requests.Session.request(self, method, url, **kwargs)
except (MissingSchema, InvalidSchema, InvalidURL): except (MissingSchema, InvalidSchema, InvalidURL):
raise raise
+14 -1
View File
@@ -1,4 +1,4 @@
from ate.client import HttpSession from ate.client import HttpSession, process_kwargs
from tests.base import ApiServerUnittest from tests.base import ApiServerUnittest
class TestHttpClient(ApiServerUnittest): class TestHttpClient(ApiServerUnittest):
@@ -35,3 +35,16 @@ class TestHttpClient(ApiServerUnittest):
resp = self.api_client.post(url, json=data, headers=self.headers) resp = self.api_client.post(url, json=data, headers=self.headers)
self.assertEqual(201, resp.status_code) self.assertEqual(201, resp.status_code)
self.assertEqual(True, resp.json()['success']) self.assertEqual(True, resp.json()['success'])
def test_process_kwargs(self):
kwargs = {
"headers": {
"content-type": "application/json; charset=utf-8"
},
"data": {
"a": 1,
"b": 2
}
}
kwargs = process_kwargs("POST", **kwargs)
self.assertEqual(kwargs["data"], '{"a": 1, "b": 2}')