Skip to content

Commit

Permalink
Separate invalid request and parse error logic
Browse files Browse the repository at this point in the history
Previously parse error was hidden by invalid request the logic is now
fixed to handle both case and test files are updated.

Signed-off-by: Vasudev Kamath <kamathvasudev@gmail.com>
  • Loading branch information
copyninja committed May 1, 2014
1 parent 8654785 commit c760b7e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 18 deletions.
21 changes: 8 additions & 13 deletions silpa/api/jsonrpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,14 @@ def __init__(self, data):
self.error_response = None
try:
self.request = JsonRpcRequest(**json.loads(data))
except TypeError as e:
error = JsonRpcError(code=INVALID_REQUEST,
message="Not a valid JSON-RPC request",
data='')
error_dict = dict(zip(error._fields, error))
self.error_response = JsonRpcErrorResponse(jsonrpc="2.0",
error=error_dict,
id='')
except Exception as e:
# Unable to parse json
error = JsonRpcError(code=PARSE_ERRORS, message=e.message,
Expand All @@ -72,19 +80,6 @@ def __init__(self, data):
error._fields,
error)),
id='')
else:
# successfully parsed now verify request
if self.request.jsonrpc != "2.0" or len(self.request.method) == 0 \
or len(self.request.params) == 0 or \
len(str(self.request.id)) == 0:
# not valid request
error = JsonRpcError(code=INVALID_REQUEST,
message="Not a valid JSON-RPC request",
data='')
error_dict = dict(zip(error._fields, error))
self.error_response = JsonRpcErrorResponse(jsonrpc="2.0",
error=error_dict,
id='')

def __call__(self):
# process request here
Expand Down
13 changes: 8 additions & 5 deletions tests/api/jsonrpc_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,17 @@ def test_methodnot_found(self):
id=random.randint(1, 1000))
self.assertJsonRpcMethodNotFound(self.jpost('/api/JSONRPC', data=data))

def test_request_parseerror(self):
# notice missing jsonrpc key? this is invalid request but our
# code will trigger parse error as we can't convert this to
# JsonRpcRequest object
def test_invalidrequest(self):
data = dict(method='transliteration.transliterate',
params=['Hello World!', 'kn_IN'],
id=random.randint(1, 1000))
self.assertJsonRpcParseErrors(self.jpost('/api/JSONRPC', data=data))
self.assertJsonRpcInvalidRequest(self.jpost('/api/JSONRPC', data=data))

def test_request_parseerror(self):
self.assertJsonRpcParseErrors(self.post('/api/JSONRPC', data='''
{"jsonrpc": "2.0", "method": "transliteration.transliterate", "params":
[
'''))

def test_result_jsonrpc(self):
data = dict(jsonrpc='2.0',
Expand Down

0 comments on commit c760b7e

Please sign in to comment.