|
| 1 | +# Copyright 2026 Python Language Server Contributors. |
| 2 | + |
| 3 | +from concurrent import futures |
| 4 | +import pytest |
| 5 | + |
| 6 | +from pylsp_jsonrpc import exceptions |
| 7 | +from pylsp_jsonrpc.endpoint import Endpoint |
| 8 | + |
| 9 | + |
| 10 | +@pytest.mark.parametrize('code, error_type', [ |
| 11 | + (-32603, exceptions.JsonRpcInternalError), |
| 12 | + (-32602, exceptions.JsonRpcInvalidParams), |
| 13 | + (0, exceptions.JsonRpcException), |
| 14 | + (123, exceptions.JsonRpcException), |
| 15 | +]) |
| 16 | +def test_error_response_code(code, error_type): |
| 17 | + endpoint = Endpoint({}, lambda message: None, id_generator=lambda: 'request') |
| 18 | + try: |
| 19 | + future = endpoint.request('method') |
| 20 | + endpoint.consume({ |
| 21 | + 'jsonrpc': '2.0', |
| 22 | + 'id': 'request', |
| 23 | + 'error': {'code': code, 'message': 'remote failure', 'data': {'detail': 1}}, |
| 24 | + }) |
| 25 | + assert future.done() |
| 26 | + with pytest.raises(error_type) as exc_info: |
| 27 | + future.result(timeout=1) |
| 28 | + assert exc_info.type is error_type |
| 29 | + assert exc_info.value.to_dict() == { |
| 30 | + 'code': code, 'message': 'remote failure', 'data': {'detail': 1}, |
| 31 | + } |
| 32 | + finally: |
| 33 | + endpoint.shutdown() |
| 34 | + |
| 35 | + |
| 36 | +@pytest.mark.parametrize('mode', ['direct', 'future', 'callable']) |
| 37 | +def test_internal_handler_error_code(mode): |
| 38 | + messages = [] |
| 39 | + |
| 40 | + def fail(): |
| 41 | + raise RuntimeError('handler failure') |
| 42 | + |
| 43 | + def handler(_params): |
| 44 | + if mode == 'callable': |
| 45 | + return fail |
| 46 | + if mode == 'future': |
| 47 | + failed = futures.Future() |
| 48 | + failed.set_exception(RuntimeError('handler failure')) |
| 49 | + return failed |
| 50 | + return fail() |
| 51 | + |
| 52 | + endpoint = Endpoint({'method': handler}, messages.append) |
| 53 | + try: |
| 54 | + endpoint.consume({'jsonrpc': '2.0', 'id': 'request', 'method': 'method'}) |
| 55 | + endpoint.shutdown() |
| 56 | + assert len(messages) == 1 |
| 57 | + assert messages[0]['id'] == 'request' |
| 58 | + assert messages[0]['error']['code'] == -32603 |
| 59 | + assert messages[0]['error']['message'] == 'RuntimeError: handler failure' |
| 60 | + finally: |
| 61 | + endpoint.shutdown() |
| 62 | + |
| 63 | + |
| 64 | +def test_explicit_zero_code_is_preserved(): |
| 65 | + error = exceptions.JsonRpcException('application failure', code=0) |
| 66 | + assert error.to_dict() == {'message': 'application failure', 'code': 0} |
| 67 | + assert exceptions.JsonRpcInternalError('application failure', code=0).code == 0 |
| 68 | + assert exceptions.JsonRpcInternalError().code == -32603 |
0 commit comments