Skip to content
This repository was archived by the owner on Mar 8, 2020. It is now read-only.

Commit 8dfe832

Browse files
authored
Merge pull request #39 from juanjux/feature/remove_msgpack
Remove msgpack dependency
2 parents 34b290f + 8373b38 commit 8dfe832

File tree

6 files changed

+17
-187
lines changed

6 files changed

+17
-187
lines changed

native/python_package/python_driver/cli.py

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def get_processor_instance(format_: str, custom_inbuffer: InBuffer=None,
3131
"""
3232
conf = ProcessorConfigs.get(format_)
3333
if not conf:
34-
raise RequestInstantiationException('No RequestProcessor found for format %s' % format)
34+
raise RequestInstantiationException('No RequestProcessor found for format %s' % format_)
3535

3636
inbuffer = custom_inbuffer if custom_inbuffer else conf['inbuffer']
3737
outbuffer = custom_outbuffer if custom_outbuffer else conf['outbuffer']
@@ -41,24 +41,15 @@ def get_processor_instance(format_: str, custom_inbuffer: InBuffer=None,
4141

4242

4343
def main() -> None:
44-
"""
45-
If you pass the --json command line parameter the replies will be
46-
printed using pprint without wrapping them in the msgpack format which
47-
can be handy when debugging.
48-
"""
49-
50-
if len(sys.argv) > 1 and sys.argv[1] == '--msgpack':
51-
format_ = 'msgpack'
52-
else:
53-
format_ = 'json'
44+
format_ = 'json'
5445

5546
processor, inbuffer = get_processor_instance(format_)
5647
try:
5748
processor.process_requests(inbuffer)
5849
except UnicodeDecodeError:
5950
print_exc()
6051
print('Error while trying to decode the message, are you sure you are not '
61-
'using a different input format that the currently configured (%s)?' % format)
52+
'using a different input format that the currently configured (%s)?' % format_)
6253

6354

6455
if __name__ == '__main__':
Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,10 @@
11
import sys
2-
from python_driver.requestprocessor import RequestProcessorJSON, RequestProcessorMSGPack
2+
from python_driver.requestprocessor import RequestProcessorJSON
33

44
ProcessorConfigs = {
55
'json': {
66
'class': RequestProcessorJSON,
77
'inbuffer': sys.stdin,
88
'outbuffer': sys.stdout
99
},
10-
11-
'msgpack': {
12-
'class': RequestProcessorMSGPack,
13-
'inbuffer': sys.stdin.buffer,
14-
'outbuffer': sys.stdout.buffer
15-
}
1610
}

native/python_package/python_driver/requestprocessor.py

Lines changed: 0 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -251,54 +251,3 @@ def process_requests(self, inbuffer: InStrBuffer) -> None:
251251
"""
252252
for doc in self._extract_docs(inbuffer):
253253
self.process_request(doc)
254-
255-
256-
class RequestProcessorMSGPack(RequestProcessor):
257-
"""
258-
RequestProcessor subclass that operates deserializing and serializing responses
259-
using the MSGPACK format. Input and output packages
260-
"""
261-
def __init__(self, outbuffer: OutBytesBuffer) -> None:
262-
"""
263-
:param outbuffer: the output buffer. This must be a bytes-based file like object
264-
supporting the write(bytes) and flush() methods.
265-
"""
266-
super().__init__(outbuffer)
267-
268-
def _send_response(self, response: Response) -> None:
269-
from msgpack import dumps
270-
self.outbuffer.write(dumps(response))
271-
self.outbuffer.flush()
272-
273-
def _tostr_request(self, request: RawRequest) -> Request:
274-
"""
275-
Convert all byte-string keys and values to normal strings (non recursively since
276-
we only have one level)
277-
278-
:param request: dictionary that potentially can contain bytestring keys and values.
279-
:return: the converted dictionary
280-
"""
281-
try:
282-
newrequest = Request({})
283-
for key, value in request.items():
284-
if isinstance(value, bytes):
285-
value = value.decode()
286-
287-
if isinstance(key, bytes):
288-
key = key.decode()
289-
290-
newrequest[key] = value
291-
except AttributeError as exc:
292-
self.errors.append('Error trying to decode message, are you sure that the input ' +
293-
'format is msgpack?')
294-
raise AttributeError from exc
295-
return newrequest
296-
297-
def process_requests(self, inbuffer: InStrBuffer) -> None:
298-
"""
299-
:param inbuffer: file-like object based on bytes supporting the read() and
300-
iteration by lines
301-
"""
302-
from msgpack import Unpacker
303-
for request in Unpacker(inbuffer):
304-
self.process_request(request)
Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
msgpack-python==0.4.8
21
pydetector==0.8.1
32
-e git+git://github.com/python/mypy.git@0bb2d1680e8b9522108b38d203cb73021a617e64#egg=mypy-lang
43
typed-ast==1.0.1

native/python_package/setup.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@
3131
]
3232
},
3333
install_requires=[
34-
"msgpack-python==0.4.8",
3534
"pydetector==0.8.1"
3635
],
3736
classifiers=[

native/python_package/test/test_python_driver.py

Lines changed: 13 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,20 @@
11
import io
2+
import json
23
import os
4+
import subprocess
35
import sys
4-
import json
56
import unittest
6-
import subprocess
77
from os.path import join, abspath, dirname
88

9-
# msgpack is an optional dependency
10-
try:
11-
import msgpack
12-
except ImportError:
13-
TEST_MSGPACK = False
14-
else:
15-
TEST_MSGPACK = True
16-
179
sys.path.append('..')
1810
from python_driver import __version__, get_processor_instance
1911
from python_driver.requestprocessor import (
2012
Request, Response, RequestProcessorJSON, InBuffer, EmptyCodeException)
2113

22-
if TEST_MSGPACK:
23-
from python_driver.requestprocessor import RequestProcessorMSGPack
2414
from typing import Dict, Any, List, AnyStr, Optional, Iterator, cast
2515

2616
CURDIR = abspath(dirname(__file__))
2717

28-
29-
def convert_bytes(data: Any, to_bytes: bool=False) -> Any:
30-
"""
31-
Both in normal operation and with this tests data comes trough a bytestream so this is needed to
32-
recursively convert the msgpack incoming data (the pprint data is converted just decoding and using
33-
literal_eval)
34-
"""
35-
if type(data) in (list, tuple):
36-
newlist: List[Any] = []
37-
for item in data:
38-
newlist.append(convert_bytes(item, to_bytes))
39-
return newlist
40-
elif isinstance(data, dict):
41-
newdict: Dict[str, Any] = {}
42-
for key, value in data.items():
43-
newvalue = convert_bytes(value, to_bytes)
44-
newkey = convert_bytes(key, to_bytes)
45-
newdict[newkey] = newvalue
46-
return newdict
47-
elif isinstance(data, bytes) and not to_bytes:
48-
return data.decode()
49-
elif isinstance(data, str) and to_bytes:
50-
return data.encode()
51-
return data
52-
53-
5418
class TestTypeCheck(unittest.TestCase):
5519
def test_10_check(self) -> None:
5620
prevdir = os.getcwd()
@@ -64,7 +28,7 @@ def test_10_check(self) -> None:
6428

6529
class TestPythonDriverBase(unittest.TestCase):
6630
def _restart_data(self, format_: str='json') -> None:
67-
assert format_ in ('json', 'msgpack')
31+
assert format_ == 'json'
6832

6933
with open(join(CURDIR, 'data', 'helloworld.py')) as f:
7034
testcode = f.read()
@@ -94,27 +58,21 @@ def _extract_docs(inbuffer: InBuffer) -> Iterator[Response]:
9458
yield json.loads(line)
9559

9660
def _loadResults(self, format_: str) -> List[Response]:
97-
"""Read all msgpacks from the recvbuffer"""
61+
"""Read all msgs from the recvbuffer"""
9862
self.recvbuffer.seek(0)
9963

10064
res: List[Response] = []
101-
if format_ == 'json':
102-
res = [doc for doc in self._extract_docs(self.recvbuffer)]
103-
elif TEST_MSGPACK and format_ == 'msgpack':
104-
res = [convert_bytes(msg) for msg in msgpack.Unpacker(self.recvbuffer)]
65+
res = [doc for doc in self._extract_docs(self.recvbuffer)]
10566
return res
10667

10768

10869
class Test10ProcessRequestFunc(TestPythonDriverBase):
10970

11071
def _add_to_buffer(self, count: int, format_: str) -> None:
111-
"""Add count test msgpacks to the sendbuffer"""
72+
"""Add count test msgs to the sendbuffer"""
11273
for i in range(count):
11374
msg = ''
114-
if TEST_MSGPACK and format_ == 'msgpack':
115-
msg = msgpack.dumps(self.data)
116-
elif format_ == 'json':
117-
msg = json.dumps(self.data, ensure_ascii=False) + '\n'
75+
msg = json.dumps(self.data, ensure_ascii=False) + '\n'
11876
self.sendbuffer.write(msg)
11977

12078
self.sendbuffer.flush()
@@ -176,26 +134,13 @@ def test_010_normal_json(self) -> None:
176134
self.assertEqual(len(replies), 1)
177135
self._check_reply_dict(replies[0])
178136

179-
if TEST_MSGPACK:
180-
def test_020_normal_msgpack(self) -> None:
181-
replies = self._send_receive(1, 'msgpack')
182-
self.assertEqual(len(replies), 1)
183-
self._check_reply_dict(replies[0])
184-
185-
def test_030_normal_json_many(self) -> None:
137+
def test_020_normal_json_many(self) -> None:
186138
replies = self._send_receive(100, 'json')
187139
self.assertEqual(len(replies), 100)
188140
for reply in replies:
189141
self._check_reply_dict(reply)
190142

191-
if TEST_MSGPACK:
192-
def test_040_normal_msgpack_many(self) -> None:
193-
replies = self._send_receive(100, 'msgpack')
194-
self.assertEqual(len(replies), 100)
195-
for reply in replies:
196-
self._check_reply_dict(reply)
197-
198-
def test_050_error_print(self) -> None:
143+
def test_030_error_print(self) -> None:
199144
wrongcode = 'wtf lol'
200145

201146
replies = self._send_receive(1, 'json', {'content': wrongcode})
@@ -209,31 +154,7 @@ def test_050_error_print(self) -> None:
209154
replies = self._send_receive(1, 'json')
210155
self.assertEqual(len(replies), 1)
211156

212-
if TEST_MSGPACK:
213-
def test_060_error_msgpack(self) -> None:
214-
wrongcode = 'wtf lol'
215-
216-
replies = self._send_receive(1, 'msgpack', {'content': wrongcode})
217-
self.assertEqual(len(replies), 1)
218-
ast = replies[0].get('ast')
219-
self.assertIsNone(ast)
220-
self._check_reply_dict(replies[0], has_errors=True)
221-
222-
# Check that it still alive
223-
self._restart_data()
224-
replies = self._send_receive(1, 'json')
225-
self.assertEqual(len(replies), 1)
226-
227-
def test_070_broken_msgpack(self) -> None:
228-
self._restart_data('msgpack')
229-
brokendata = msgpack.dumps(self.data)[:-30]
230-
self.sendbuffer.write(brokendata)
231-
self.sendbuffer.flush()
232-
reply = self._send_receive(1, 'msgpack', restart_data=False)[0]
233-
self.assertEqual(reply['status'], 'fatal')
234-
self.assertEqual(len(reply['errors']), 1)
235-
236-
def test_080_broken_json(self) -> None:
157+
def test_040_broken_json(self) -> None:
237158
self._restart_data('json')
238159
brokendata = json.dumps(self.data, ensure_ascii=False)[:-30]
239160
self.sendbuffer.write(brokendata)
@@ -244,31 +165,8 @@ def test_080_broken_json(self) -> None:
244165

245166

246167
class Test20ReqProcMethods(TestPythonDriverBase):
247-
if TEST_MSGPACK:
248-
def test_10_check_input(self) -> None:
249-
self._restart_data('json')
250-
brequest = convert_bytes(self.data, to_bytes=True)
251-
processor = RequestProcessorMSGPack(self.recvbuffer)
252-
res = processor._parse_input_request(brequest)
253-
self.assertEqual(res[1], 'test.py')
254-
255-
def test_20_check_input_bad(self) -> None:
256-
self._restart_data('msgpack')
257-
del self.data['content']
258-
brequest = convert_bytes(self.data, to_bytes=True)
259-
processor = RequestProcessorMSGPack(self.recvbuffer)
260-
with self.assertRaises(EmptyCodeException) as _: # noqa: F841
261-
processor._parse_input_request(brequest)
262-
263-
def test_30_send_response_msgpack(self) -> None:
264-
self._restart_data('msgpack')
265-
processor = RequestProcessorMSGPack(self.recvbuffer)
266-
processor._send_response(cast(Response, self.data))
267-
res = self._loadResults('msgpack')
268-
self.assertEqual(len(res), 1)
269-
self.assertDictEqual(self.data, res[0])
270-
271-
def test_40_send_response_json(self) -> None:
168+
169+
def test_10_send_response_json(self) -> None:
272170
self._restart_data('json')
273171
processor = RequestProcessorJSON(self.recvbuffer)
274172
processor._send_response(cast(Response, self.data))
@@ -278,7 +176,7 @@ def test_40_send_response_json(self) -> None:
278176

279177
# process request already tested with TestPythonDriverBase
280178

281-
def test_50_return_error(self) -> None:
179+
def test_20_return_error(self) -> None:
282180
self._restart_data('json')
283181
processor = RequestProcessorJSON(self.recvbuffer)
284182
processor.errors = ['test error']

0 commit comments

Comments
 (0)