Skip to content

Commit c6dfb30

Browse files
committed
Add tests, including one for using stdlib json
1 parent 383d92c commit c6dfb30

File tree

1 file changed

+35
-7
lines changed

1 file changed

+35
-7
lines changed

test/test_streams.py

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import sys
99
from unittest import mock
1010
import pytest
11+
import json
1112

1213
from pylsp_jsonrpc.streams import JsonRpcStreamReader, JsonRpcStreamWriter
1314

@@ -31,7 +32,6 @@ def reader(rfile):
3132
def writer(wfile):
3233
return JsonRpcStreamWriter(wfile, sort_keys=True)
3334

34-
3535
def test_reader(rfile, reader):
3636
rfile.write(
3737
b'Content-Length: 49\r\n'
@@ -84,13 +84,41 @@ def test_writer(wfile, writer):
8484
}
8585
writer.write(data)
8686

87-
raw_result = wfile.getvalue().decode()
88-
raw_result_lines = raw_result.split()
87+
assert wfile.getvalue() == (
88+
b'Content-Length: 44\r\n'
89+
b'Content-Type: application/vscode-jsonrpc; charset=utf8\r\n'
90+
b'\r\n'
91+
b'{"id":"hello","method":"method","params":{}}'
92+
)
8993

90-
assert raw_result_lines[0].split(":") == "Content-Length"
91-
assert raw_result_lines[1] == 'Content-Type: application/vscode-jsonrpc; charset=utf8'
92-
assert raw_result_lines[2] == ''
93-
assert json.loads(raw_result_lines[3]) == data
94+
95+
def test_writer_builtin_json(wfile):
96+
"""Test the stream writer using the standard json lib."""
97+
data = {
98+
'id': 'hello',
99+
'method': 'method',
100+
'params': {}
101+
}
102+
orig_modules = sys.modules
103+
try:
104+
# Pretend orjson wasn't imported when initializing the writer.
105+
sys.modules = {'json': json}
106+
std_json_writer = JsonRpcStreamWriter(wfile, sort_keys=True)
107+
finally:
108+
sys.modules = orig_modules
109+
110+
with mock.patch('pylsp_jsonrpc.streams.json') as streams_json:
111+
# Mock the imported json's dumps function to use the stdlib's dumps,
112+
# whether orjson is available or not.
113+
streams_json.dumps = json.dumps
114+
std_json_writer.write(data)
115+
116+
assert wfile.getvalue() == (
117+
b'Content-Length: 44\r\n'
118+
b'Content-Type: application/vscode-jsonrpc; charset=utf8\r\n'
119+
b'\r\n'
120+
b'{"id":"hello","method":"method","params":{}}'
121+
)
94122

95123

96124
class JsonDatetime(datetime.datetime):

0 commit comments

Comments
 (0)