Skip to content

Commit

Permalink
Use uuid4 for request IDs
Browse files Browse the repository at this point in the history
Fixes #7
  • Loading branch information
emlove committed May 3, 2021
1 parent a3e4f7a commit cab3124
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 31 deletions.
7 changes: 2 additions & 5 deletions jsonrpc_base/jsonrpc.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import inspect
import json
import logging
import random
import sys
import uuid

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -126,9 +125,7 @@ def __request(self, method_name, args=None, kwargs=None):
if kwargs.pop('_notification', False):
msg_id = None
else:
# some JSON-RPC servers complain when receiving str(uuid.uuid4()).
# Let's pick something simpler.
msg_id = random.randint(1, sys.maxsize)
msg_id = str(uuid.uuid4())

if args and kwargs:
raise ProtocolError(
Expand Down
32 changes: 6 additions & 26 deletions tests.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,14 @@
import contextlib
import json
import random
import sys

import pytest
from unittest.mock import Mock
from unittest import mock

import jsonrpc_base
from jsonrpc_base import Server, ProtocolError, TransportError

pytestmark = pytest.mark.asyncio


class DummyFile(object):
def write(self, x): pass


@contextlib.contextmanager
def block_stderr():
real_stderr = sys.stderr
sys.stderr = DummyFile()
yield
sys.stderr = real_stderr


class MockTransportError(ValueError):
"""Test exception representing a transport library error."""

Expand Down Expand Up @@ -56,12 +41,6 @@ def assertSameJSON(json1, json2):
assert json.loads(json1) == json.loads(json2)


@pytest.fixture(autouse=True)
def mock_rand():
"""Mock the build in rand method for determinism in tests."""
random.randint = Mock(return_value=1)


@pytest.fixture
def server():
"""Get the mock server object"""
Expand Down Expand Up @@ -205,6 +184,7 @@ def handler(message):
def test_calls(server):
# rpc call with positional parameters:
def handler1(message):
assert message.msg_id == "abcd-1234"
assert message.params == [42, 23]
return {
"jsonrpc": "2.0",
Expand All @@ -213,7 +193,8 @@ def handler1(message):
}

server._handler = handler1
assert server.subtract(42, 23) == 19
with mock.patch("uuid.uuid4", return_value="abcd-1234"):
assert server.subtract(42, 23) == 19

# rpc call with named parameters
def handler2(message):
Expand Down Expand Up @@ -320,9 +301,8 @@ def bad_handler():

# receive_request will normally print traceback when an exception is caught
# This isn't necessary for the test
with block_stderr():
response = server.receive_request(jsonrpc_base.Request(
'on_bad_handler', msg_id=1))
response = server.receive_request(jsonrpc_base.Request(
'on_bad_handler', msg_id=1))
assert response.error['code'] == -32000
assert response.error['message'] == 'Server Error: Bad Server Handler'

Expand Down

0 comments on commit cab3124

Please sign in to comment.