Пример #1
0
def test_add_static_method():
    class FooClass:
        @staticmethod
        def foo():
            return "bar"

    assert Methods(FooClass.foo).items["foo"] is FooClass.foo
Пример #2
0
def test_add_static_method_custom_name():
    class FooClass:
        @staticmethod
        def foo():
            return "bar"

    assert Methods(custom=FooClass.foo).items["custom"] == FooClass.foo
Пример #3
0
def test_safe_call_success_response():
    response = safe_call(Request(method="ping", id=1),
                         Methods(ping),
                         debug=True)
    assert isinstance(response, SuccessResponse)
    assert response.result == "pong"
    assert response.id == 1
Пример #4
0
def test_dispatch_pure_invalid_json():
    """Unable to parse, must return an error"""
    response = dispatch_pure("{",
                             Methods(ping),
                             convert_camel_case=False,
                             context=NOCONTEXT,
                             debug=True)
    assert isinstance(response, InvalidJSONResponse)
Пример #5
0
def test_dispatch_pure_invalid_jsonrpc():
    """Invalid JSON-RPC, must return an error. (impossible to determine if notification)"""
    response = dispatch_pure("{}",
                             Methods(ping),
                             convert_camel_case=False,
                             context=NOCONTEXT,
                             debug=True)
    assert isinstance(response, InvalidJSONRPCResponse)
Пример #6
0
def test_add_function_via_decorator():
    methods = Methods()

    @methods.add
    def foo():
        pass

    assert methods.items["foo"] is foo
Пример #7
0
def test_dispatch_pure_notification():
    response = dispatch_pure(
        '{"jsonrpc": "2.0", "method": "ping"}',
        Methods(ping),
        convert_camel_case=False,
        context=NOCONTEXT,
        debug=True,
    )
    assert isinstance(response, NotificationResponse)
Пример #8
0
def test_dispatch_pure_notification_invalid_jsonrpc():
    response = dispatch_pure(
        '{"jsonrpc": "0", "method": "notify"}',
        Methods(ping),
        convert_camel_case=False,
        context=NOCONTEXT,
        debug=True,
    )
    assert isinstance(response, ErrorResponse)
Пример #9
0
def test_call_requests_with_context():
    def ping_with_context(context=None):
        assert context is sentinel.context

    call_requests(
        Request("ping_with_context", convert_camel_case=False),
        Methods(ping_with_context),
        debug=True,
    )
Пример #10
0
def test_get():
    def cat():
        pass

    def dog():
        pass

    methods = Methods(cat, dog)
    assert methods.items["cat"] == cat
    assert methods.items["dog"] == dog
Пример #11
0
def test_add_static_method_via_decorator():
    methods = Methods()

    class FooClass:
        @staticmethod
        @methods.add
        def foo():
            return "bar"

    assert methods.items["foo"] is FooClass.foo
Пример #12
0
def test_dispatch_pure_request():
    response = dispatch_pure(
        '{"jsonrpc": "2.0", "method": "ping", "id": 1}',
        Methods(ping),
        convert_camel_case=False,
        context=NOCONTEXT,
        debug=True,
    )
    assert isinstance(response, SuccessResponse)
    assert response.result == "pong"
    assert response.id == 1
Пример #13
0
def test_dispatch_pure_invalid_params():
    def foo(colour):
        assert colour in ("orange", "red", "yellow"), "Invalid colour"

    response = dispatch_pure(
        '{"jsonrpc": "2.0", "method": "foo", "params": ["blue"], "id": 1}',
        Methods(foo),
        convert_camel_case=False,
        context=NOCONTEXT,
        debug=True,
    )
    assert isinstance(response, InvalidParamsResponse)
Пример #14
0
def test_examples_empty_array():
    # This is an invalid JSON-RPC request, should return an error.
    response = dispatch_pure("[]",
                             Methods(ping),
                             convert_camel_case=False,
                             context=NOCONTEXT,
                             debug=True)
    assert isinstance(response, ErrorResponse)
    assert (
        str(response) ==
        '{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid JSON-RPC", "data": null}, "id": null}'
    )
Пример #15
0
def test_examples_invalid_json():
    response = dispatch_pure(
        '[{"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"}, {"jsonrpc": "2.0", "method"]',
        Methods(ping),
        convert_camel_case=False,
        context=NOCONTEXT,
        debug=True,
    )
    assert isinstance(response, ErrorResponse)
    assert (
        str(response) ==
        '{"jsonrpc": "2.0", "error": {"code": -32700, "message": "Invalid JSON", "data": "Expecting \':\' delimiter: line 1 column 96 (char 95)"}, "id": null}'
    )
Пример #16
0
def test_add_instance_method_custom_name():
    class Foo:
        def __init__(self, name):
            self.name = name

        def get_name(self):
            return self.name

    obj1 = Foo("a")
    obj2 = Foo("b")
    methods = Methods(custom1=obj1.get_name, custom2=obj2.get_name)
    # Can't use assertIs, so check the outcome is as expected
    assert methods.items["custom1"].__call__() == "a"
    assert methods.items["custom2"].__call__() == "b"
Пример #17
0
def test_examples_nameds():
    def subtract(**kwargs):
        return kwargs["minuend"] - kwargs["subtrahend"]

    response = dispatch_pure(
        '{"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 23, "minuend": 42}, "id": 3}',
        Methods(subtract),
        convert_camel_case=False,
        context=NOCONTEXT,
        debug=True,
    )
    assert isinstance(response, SuccessResponse)
    assert response.result == 19

    # Second example
    response = dispatch_pure(
        '{"jsonrpc": "2.0", "method": "subtract", "params": {"minuend": 42, "subtrahend": 23}, "id": 4}',
        Methods(subtract),
        convert_camel_case=False,
        context=NOCONTEXT,
        debug=True,
    )
    assert isinstance(response, SuccessResponse)
    assert response.result == 19
Пример #18
0
def test_examples_invalid_jsonrpc_batch():
    """
    We break the spec here, by not validating each request in the batch individually.
    The examples are expecting a batch response full of error responses.
    """
    response = dispatch_pure("[1]",
                             Methods(ping),
                             convert_camel_case=False,
                             context=NOCONTEXT,
                             debug=True)
    assert isinstance(response, InvalidJSONRPCResponse)
    assert (
        str(response) ==
        '{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid JSON-RPC", "data": null}, "id": null}'
    )
Пример #19
0
def test_examples_positionals():
    def subtract(minuend, subtrahend):
        return minuend - subtrahend

    response = dispatch_pure(
        '{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}',
        Methods(subtract),
        convert_camel_case=False,
        context=NOCONTEXT,
        debug=True,
    )
    assert isinstance(response, SuccessResponse)
    assert response.result == 19

    # Second example
    response = dispatch_pure(
        '{"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 2}',
        Methods(subtract),
        convert_camel_case=False,
        context=NOCONTEXT,
        debug=True,
    )
    assert isinstance(response, SuccessResponse)
    assert response.result == -19
Пример #20
0
def test_call_requests_batch_all_notifications():
    """Should return a BatchResponse response, an empty list"""
    response = call_requests(
        {
            Request(**{
                "jsonrpc": "2.0",
                "method": "notify_sum",
                "params": [1, 2, 4]
            }),
            Request(**{
                "jsonrpc": "2.0",
                "method": "notify_hello",
                "params": [7]
            }),
        },
        Methods(ping),
        debug=True,
    )
    assert str(response) == ""
Пример #21
0
def test_safe_call_invalid_args():
    response = safe_call(Request(method="ping", params=[1], id=1),
                         Methods(ping),
                         debug=True)
    assert isinstance(response, InvalidParamsResponse)
Пример #22
0
def test_safe_call_method_not_found():
    response = safe_call(Request(method="nonexistant", id=1),
                         Methods(ping),
                         debug=True)
    assert isinstance(response, MethodNotFoundResponse)
Пример #23
0
def test_safe_call_notification_failure():
    def fail():
        raise ValueError()

    response = safe_call(Request(method="foo"), Methods(fail), debug=True)
    assert isinstance(response, NotificationResponse)
Пример #24
0
def test_safe_call_notification():
    response = safe_call(Request(method="ping"), Methods(ping), debug=True)
    assert isinstance(response, NotificationResponse)
Пример #25
0
def test_add_partial_no_name():
    six = partial(lambda x: x + 1, 5)
    methods = Methods()
    with pytest.raises(AttributeError):
        methods.add(six)  # Partial has no __name__ !
Пример #26
0
def test_examples_mixed_requests_and_notifications():
    """
    We break the spec here. The examples put an invalid jsonrpc request in the mix here.
    but it's removed to test the rest, because we're not validating each request
    individually. Any invalid jsonrpc will respond with a single error message.

    The spec example includes this which invalidates the entire request:
        {"foo": "boo"},
    """
    methods = Methods(
        **{
            "sum": lambda *args: sum(args),
            "notify_hello": lambda *args: 19,
            "subtract": lambda *args: args[0] - sum(args[1:]),
            "get_data": lambda: ["hello", 5],
        })
    requests = serialize([
        {
            "jsonrpc": "2.0",
            "method": "sum",
            "params": [1, 2, 4],
            "id": "1"
        },
        {
            "jsonrpc": "2.0",
            "method": "notify_hello",
            "params": [7]
        },
        {
            "jsonrpc": "2.0",
            "method": "subtract",
            "params": [42, 23],
            "id": "2"
        },
        {
            "jsonrpc": "2.0",
            "method": "foo.get",
            "params": {
                "name": "myself"
            },
            "id": "5",
        },
        {
            "jsonrpc": "2.0",
            "method": "get_data",
            "id": "9"
        },
    ])
    response = dispatch_pure(requests,
                             methods,
                             convert_camel_case=False,
                             context=NOCONTEXT,
                             debug=True)
    expected = [
        {
            "jsonrpc": "2.0",
            "result": 7,
            "id": "1"
        },
        {
            "jsonrpc": "2.0",
            "result": 19,
            "id": "2"
        },
        {
            "jsonrpc": "2.0",
            "error": {
                "code": -32601,
                "message": "Method not found",
                "data": "foo.get"
            },
            "id": "5",
        },
        {
            "jsonrpc": "2.0",
            "result": ["hello", 5],
            "id": "9"
        },
    ]
    assert isinstance(response, BatchResponse)
    for r in response.deserialized():
        assert r in expected
Пример #27
0
def test_add_partial_custom_name():
    six = partial(lambda x: x + 1, 5)
    assert Methods(six=six).items["six"] is six
Пример #28
0
def test_add_partial_renamed():
    six = partial(lambda x: x + 1, 5)
    six.__name__ = "six"
    assert Methods(six).items["six"] is six
Пример #29
0
def test_dispatch_basic_logging():
    response = dispatch(
        '{"jsonrpc": "2.0", "method": "ping", "id": 1}',
        Methods(ping),
        basic_logging=True,
    )
Пример #30
0
def test_dispatch():
    response = dispatch('{"jsonrpc": "2.0", "method": "ping", "id": 1}',
                        Methods(ping))
    assert response.result == "pong"