Skip to content

Commit cbe33e1

Browse files
wallisyanJacksonTian
authored andcommitted
add http-debug code;add http-debug case;
modify test_http_response modify capital DEBUG; pop the DEBUG environment variable when test over modify http_response logger split get_response and http-debug
1 parent e01c17e commit cbe33e1

File tree

4 files changed

+136
-51
lines changed

4 files changed

+136
-51
lines changed

aliyun-python-sdk-core/aliyunsdkcore/http/http_response.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,20 @@
1818
# coding=utf-8
1919

2020
import os
21+
import logging
22+
2123
from aliyunsdkcore.vendored.requests import Request, Session
2224
from aliyunsdkcore.vendored.requests.packages import urllib3
2325
from aliyunsdkcore.http.http_request import HttpRequest
2426
from aliyunsdkcore.http import protocol_type as PT
2527

28+
from aliyunsdkcore.vendored.requests import status_codes
29+
30+
logger = logging.getLogger(__name__)
31+
logger.setLevel(logging.DEBUG)
32+
ch = logging.StreamHandler()
33+
logger.addHandler(ch)
34+
2635
DEFAULT_CONNECT_TIMEOUT = 5
2736

2837

@@ -61,6 +70,24 @@ def set_ssl_enable(self, enable):
6170
def get_ssl_enabled(self):
6271
return self.__ssl_enable
6372

73+
@staticmethod
74+
def prepare_http_debug(request, symbol):
75+
base = ''
76+
for key, value in request.headers.items():
77+
base += '\n%s %s : %s' % (symbol, key, value)
78+
return base
79+
80+
def do_http_debug(self, request, response):
81+
# logger the request
82+
request_base = '\n> %s %s HTTP/1.1' % (self.get_method().upper(), self.get_url())
83+
request_base += '\n> Host : %s' % self.get_host()
84+
logger.debug(request_base + self.prepare_http_debug(request, '>'))
85+
86+
# logger the response
87+
response_base = '\n< HTTP/1.1 %s %s' % (
88+
response.status_code, status_codes._codes.get(response.status_code)[0].upper())
89+
logger.debug(response_base + self.prepare_http_debug(response, '<'))
90+
6491
def get_response_object(self):
6592
with Session() as s:
6693
current_protocol = 'https://' if self.get_ssl_enabled() else 'http://'
@@ -87,7 +114,15 @@ def get_response_object(self):
87114
}
88115
# ignore the warning-InsecureRequestWarning
89116
urllib3.disable_warnings()
117+
90118
response = s.send(prepped, proxies=proxies,
91119
timeout=(DEFAULT_CONNECT_TIMEOUT, self._timeout),
92120
allow_redirects=False, verify=None, cert=None)
121+
122+
http_debug = os.environ.get('DEBUG')
123+
124+
if http_debug is not None and http_debug.lower() == 'sdk':
125+
# http debug information
126+
self.do_http_debug(prepped, response)
127+
93128
return response.status_code, response.headers, response.content

aliyun-python-sdk-core/tests/__init__.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,65 @@
33
# The unittest module got a significant overhaul
44
# in 2.7, so if we're in 2.6 we can use the backported
55
# version unittest2.
6+
import threading
7+
68
if sys.version_info[:2] == (2, 6):
79
import unittest2 as unittest
810
else:
911
import unittest
12+
13+
14+
# the version under py3 use the different package
15+
if sys.version_info[0] == 3:
16+
from http.server import SimpleHTTPRequestHandler
17+
from http.server import HTTPServer
18+
else:
19+
from SimpleHTTPServer import SimpleHTTPRequestHandler
20+
from BaseHTTPServer import HTTPServer
21+
22+
23+
class MyServer:
24+
_headers = {}
25+
_url = ''
26+
27+
def __enter__(self):
28+
class ServerHandler(SimpleHTTPRequestHandler):
29+
30+
def do_GET(_self):
31+
_self.protocol_version = 'HTTP/1.1'
32+
self._headers = _self.headers
33+
self._url = _self.path
34+
_self.send_response(200)
35+
_self.send_header("Content-type", "application/json")
36+
_self.end_headers()
37+
_self.wfile.write(b"{}")
38+
39+
self.server = HTTPServer(("", 51352), ServerHandler)
40+
41+
def thread_func():
42+
self.server.serve_forever()
43+
44+
thread = threading.Thread(target=thread_func)
45+
thread.start()
46+
return self
47+
48+
def __exit__(self, exc_type, exc_val, exc_tb):
49+
if self.server:
50+
self.server.shutdown()
51+
self.server = None
52+
53+
@property
54+
def headers(self):
55+
return self._headers
56+
57+
@property
58+
def url(self):
59+
return self._url
60+
61+
@property
62+
def content(self):
63+
class Response:
64+
def __init__(self, headers):
65+
self.headers = headers
66+
response = Response(self._headers)
67+
return response

aliyun-python-sdk-core/tests/http/test_http_response.py

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
# coding=utf-8
2+
import os
3+
import sys
24

3-
from tests import unittest
5+
from tests import unittest, MyServer
46

57
from aliyunsdkcore.http.http_response import HttpResponse
68
from aliyunsdkcore.http.protocol_type import HTTPS
79

810

11+
from aliyunsdkcore.client import AcsClient
12+
from aliyunsdkcore.request import CommonRequest
13+
14+
915
class TestHttpResponse(unittest.TestCase):
1016

1117
def test_http_request(self):
@@ -15,3 +21,38 @@ def test_http_request(self):
1521
self.assertTrue(res.get_ssl_enabled())
1622
res = HttpResponse(protocol=HTTPS)
1723
self.assertTrue(res.get_ssl_enabled())
24+
25+
@staticmethod
26+
def do_request(client, request):
27+
with MyServer() as s:
28+
client.do_action_with_exception(request)
29+
return s.content
30+
31+
@staticmethod
32+
def init_client():
33+
return AcsClient("access_key_id", "access_key_secret",
34+
timeout=120, port=51352)
35+
36+
def test_http_debug(self):
37+
os.environ.setdefault('DEBUG', 'SDK')
38+
39+
http_debug = os.environ.get('DEBUG')
40+
if http_debug is not None and http_debug.lower() == 'sdk':
41+
request = CommonRequest(
42+
domain="ecs.aliyuncs.com",
43+
version="2014-05-26",
44+
action_name="DescribeRegions")
45+
request.set_endpoint("localhost")
46+
make_request = HttpResponse(request.endpoint, '/')
47+
request.headers = {'User-Agent': 'ALIBABACloud'}
48+
49+
content = make_request.prepare_http_debug(request, '>')
50+
self.assertTrue('User-Agent' in content)
51+
52+
client = self.init_client()
53+
response = self.do_request(client, request)
54+
if sys.version_info[0] == 3:
55+
response = make_request.prepare_http_debug(response, '<')
56+
self.assertTrue('User-Agent' in response)
57+
58+
os.environ.pop('DEBUG', None)

aliyun-python-sdk-core/tests/test_user_agent.py

Lines changed: 1 addition & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,10 @@
11
# encoding:utf-8
2-
import sys
3-
import threading
42

5-
from tests import unittest
3+
from tests import unittest, MyServer
64

75
from aliyunsdkcore.client import AcsClient
86
from aliyunsdkcore.request import CommonRequest
97

10-
# the version under py3 use the different package
11-
if sys.version_info[0] == 3:
12-
from http.server import SimpleHTTPRequestHandler
13-
from http.server import HTTPServer
14-
else:
15-
from SimpleHTTPServer import SimpleHTTPRequestHandler
16-
from BaseHTTPServer import HTTPServer
17-
18-
19-
class MyServer:
20-
_headers = {}
21-
_url = ''
22-
23-
def __enter__(self):
24-
class ServerHandler(SimpleHTTPRequestHandler):
25-
26-
def do_GET(_self):
27-
_self.protocol_version = 'HTTP/1.1'
28-
self._headers = _self.headers
29-
self._url = _self.path
30-
_self.send_response(200)
31-
_self.send_header("Content-type", "application/json")
32-
_self.end_headers()
33-
_self.wfile.write(b"{}")
34-
35-
self.server = HTTPServer(("", 51352), ServerHandler)
36-
37-
def thread_func():
38-
self.server.serve_forever()
39-
40-
thread = threading.Thread(target=thread_func)
41-
thread.start()
42-
return self
43-
44-
def __exit__(self, exc_type, exc_val, exc_tb):
45-
if self.server:
46-
self.server.shutdown()
47-
self.server = None
48-
49-
@property
50-
def headers(self):
51-
return self._headers
52-
53-
@property
54-
def url(self):
55-
return self._url
56-
578

589
class UserAgentTest(unittest.TestCase):
5910

0 commit comments

Comments
 (0)