2018-10-07 07:33:33 +00:00
|
|
|
# encoding: UTF-8
|
|
|
|
|
|
|
|
import json
|
|
|
|
import unittest
|
|
|
|
|
2018-10-09 10:04:05 +00:00
|
|
|
from simplejson import JSONDecodeError
|
|
|
|
|
2018-10-07 07:33:33 +00:00
|
|
|
from Promise import Promise
|
2018-10-09 10:04:05 +00:00
|
|
|
from vnpy.network.HttpClient import HttpClient
|
|
|
|
|
|
|
|
|
|
|
|
class FailedError(RuntimeError):
|
|
|
|
pass
|
2018-10-07 07:33:33 +00:00
|
|
|
|
|
|
|
|
2018-10-08 02:31:08 +00:00
|
|
|
class TestHttpClient(HttpClient):
|
2018-10-09 10:04:05 +00:00
|
|
|
|
2018-10-07 07:33:33 +00:00
|
|
|
def __init__(self):
|
|
|
|
urlBase = 'https://httpbin.org'
|
2018-10-08 02:31:08 +00:00
|
|
|
super(TestHttpClient, self).__init__()
|
2018-10-07 08:19:48 +00:00
|
|
|
self.init(urlBase)
|
2018-10-07 07:33:33 +00:00
|
|
|
|
|
|
|
self.p = Promise()
|
|
|
|
|
|
|
|
def beforeRequest(self, method, path, params, data):
|
|
|
|
data = json.dumps(data)
|
|
|
|
return method, path, params, data, {'Content-Type': 'application/json'}
|
|
|
|
|
|
|
|
def onError(self, exceptionType, exceptionValue, tb, req):
|
|
|
|
self.p.set_exception(exceptionValue)
|
|
|
|
|
2018-10-09 10:04:05 +00:00
|
|
|
def onFailed(self, httpStatusCode, data, req):
|
|
|
|
self.p.set_exception(FailedError("request failed"))
|
|
|
|
|
2018-10-07 07:33:33 +00:00
|
|
|
|
|
|
|
class RestfulClientTest(unittest.TestCase):
|
|
|
|
|
|
|
|
def setUp(self):
|
2018-10-08 02:31:08 +00:00
|
|
|
self.c = TestHttpClient()
|
2018-10-07 07:33:33 +00:00
|
|
|
self.c.start()
|
|
|
|
|
|
|
|
def tearDown(self):
|
|
|
|
self.c.stop()
|
|
|
|
|
|
|
|
def test_addReq_get(self):
|
|
|
|
args = {'user': 'username',
|
|
|
|
'pw': 'password'}
|
2018-10-09 10:04:05 +00:00
|
|
|
|
|
|
|
def callback(data, req):
|
|
|
|
self.c.p.set_result(data['args'])
|
2018-10-07 07:33:33 +00:00
|
|
|
|
|
|
|
self.c.addReq('GET', '/get', callback, params=args)
|
|
|
|
res = self.c.p.get(3)
|
|
|
|
|
|
|
|
self.assertEqual(args, res)
|
|
|
|
|
|
|
|
def test_addReq_post(self):
|
|
|
|
body = {'user': 'username',
|
|
|
|
'pw': 'password'}
|
|
|
|
|
2018-10-09 10:04:05 +00:00
|
|
|
def callback(data, req):
|
|
|
|
self.c.p.set_result(data['json'])
|
2018-10-07 07:33:33 +00:00
|
|
|
|
|
|
|
self.c.addReq('POST', '/post', callback, data=body)
|
|
|
|
res = self.c.p.get(3)
|
|
|
|
|
|
|
|
self.assertEqual(body, res)
|
2018-10-09 10:04:05 +00:00
|
|
|
|
|
|
|
def test_addReq_onFailed(self):
|
|
|
|
def callback(data, req):
|
|
|
|
pass
|
|
|
|
|
|
|
|
self.c.addReq('POST', '/status/201', callback)
|
|
|
|
with self.assertRaises(FailedError):
|
|
|
|
self.c.p.get(3)
|
|
|
|
|
|
|
|
def test_addReq_jsonParseError(self):
|
|
|
|
def callback(data, req):
|
|
|
|
pass
|
|
|
|
|
|
|
|
self.c.addReq('GET', '/image/svg', callback)
|
|
|
|
with self.assertRaises(JSONDecodeError):
|
|
|
|
self.c.p.get(3)
|
|
|
|
|