Repository navigation
Expand file tree
/
Copy pathtest_process_runner.py
More file actions
387 lines (325 loc) · 12.1 KB
/
Copy pathtest_process_runner.py
File metadata and controls
387 lines (325 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Tests for vscode_common_python_lsp.process_runner."""
import os
import sys
import unittest
from dataclasses import dataclass
from unittest.mock import MagicMock
from vscode_common_python_lsp.process_runner import (
resolve_bundle_path,
run_message_loop,
update_environ_path,
update_sys_path,
)
class TestUpdateSysPath(unittest.TestCase):
"""Tests for update_sys_path."""
def test_use_bundled_inserts_at_front(self):
original = sys.path[:]
test_dir = os.path.dirname(__file__)
# Remove if already present
if test_dir in sys.path:
sys.path.remove(test_dir)
try:
update_sys_path(test_dir, "useBundled")
assert sys.path[0] == test_dir
finally:
sys.path[:] = original
def test_other_strategy_appends(self):
original = sys.path[:]
test_dir = os.path.dirname(__file__)
if test_dir in sys.path:
sys.path.remove(test_dir)
try:
update_sys_path(test_dir, "fromEnvironment")
assert sys.path[-1] == test_dir
finally:
sys.path[:] = original
def test_skips_duplicate(self):
original = sys.path[:]
test_dir = os.path.dirname(__file__)
# Ensure it's in sys.path
if test_dir not in sys.path:
sys.path.append(test_dir)
count_before = sys.path.count(test_dir)
try:
update_sys_path(test_dir, "useBundled")
assert sys.path.count(test_dir) == count_before
finally:
sys.path[:] = original
def test_skips_nonexistent_dir(self):
original = sys.path[:]
fake_dir = "/nonexistent/dir/that/does/not/exist"
try:
update_sys_path(fake_dir, "useBundled")
assert fake_dir not in sys.path
finally:
sys.path[:] = original
class TestUpdateEnvironPath(unittest.TestCase):
"""Tests for update_environ_path."""
def test_adds_scripts_to_path(self):
import sysconfig
scripts = sysconfig.get_path("scripts")
if not scripts:
self.skipTest("sysconfig does not report scripts path")
# Remove scripts from PATH if present
original_env = os.environ.copy()
path_var = "PATH" if "PATH" in os.environ else "Path"
paths = os.environ.get(path_var, "").split(os.pathsep)
paths = [p for p in paths if p != scripts]
os.environ[path_var] = os.pathsep.join(paths)
try:
update_environ_path()
new_paths = os.environ[path_var].split(os.pathsep)
assert scripts in new_paths
assert new_paths[0] == scripts
finally:
os.environ.clear()
os.environ.update(original_env)
def test_does_not_duplicate(self):
import sysconfig
scripts = sysconfig.get_path("scripts")
if not scripts:
self.skipTest("sysconfig does not report scripts path")
original_env = os.environ.copy()
path_var = "PATH" if "PATH" in os.environ else "Path"
# Ensure scripts is already in PATH
os.environ[path_var] = scripts + os.pathsep + os.environ.get(path_var, "")
try:
count_before = os.environ[path_var].split(os.pathsep).count(scripts)
update_environ_path()
count_after = os.environ[path_var].split(os.pathsep).count(scripts)
assert count_after == count_before
finally:
os.environ.clear()
os.environ.update(original_env)
@dataclass
class _MockResult:
"""Minimal result object for testing."""
stdout: str
stderr: str
class TestRunMessageLoop(unittest.TestCase):
"""Tests for run_message_loop."""
def _make_rpc(self, messages):
"""Create a mock RPC that yields messages in order."""
rpc = MagicMock()
rpc.receive_data = MagicMock(side_effect=messages)
return rpc
def test_exit_message_stops_loop(self):
rpc = self._make_rpc([{"method": "exit"}])
run_message_loop(rpc, MagicMock(), _MockResult)
rpc.receive_data.assert_called_once()
def test_run_message_calls_run_fn(self):
run_fn = MagicMock(return_value=_MockResult("output", ""))
messages = [
{
"id": "1",
"method": "run",
"module": "black",
"argv": ["--check", "."],
"useStdin": False,
"cwd": "/tmp",
"source": "code",
},
{"method": "exit"},
]
rpc = self._make_rpc(messages)
run_message_loop(rpc, run_fn, _MockResult)
run_fn.assert_called_once_with(
module="black",
argv=["--check", "."],
use_stdin=False,
cwd="/tmp",
source="code",
)
def test_run_sends_response_with_result(self):
run_fn = MagicMock(return_value=_MockResult("formatted code", ""))
messages = [
{
"id": "1",
"method": "run",
"module": "black",
"argv": [],
"useStdin": False,
"cwd": "/tmp",
},
{"method": "exit"},
]
rpc = self._make_rpc(messages)
run_message_loop(rpc, run_fn, _MockResult)
sent = rpc.send_data.call_args[0][0]
assert sent["id"] == "1"
assert sent["result"] == "formatted code"
assert sent["error"] == ""
assert "exception" not in sent
def test_run_sends_error_response(self):
run_fn = MagicMock(return_value=_MockResult("", "some error"))
messages = [
{
"id": "2",
"method": "run",
"module": "flake8",
"argv": [],
"useStdin": False,
"cwd": "/tmp",
},
{"method": "exit"},
]
rpc = self._make_rpc(messages)
run_message_loop(rpc, run_fn, _MockResult)
sent = rpc.send_data.call_args[0][0]
assert sent["id"] == "2"
assert sent["error"] == "some error"
def test_run_handles_exception(self):
run_fn = MagicMock(side_effect=RuntimeError("boom"))
messages = [
{
"id": "3",
"method": "run",
"module": "pylint",
"argv": [],
"useStdin": False,
"cwd": "/tmp",
},
{"method": "exit"},
]
rpc = self._make_rpc(messages)
run_message_loop(rpc, run_fn, _MockResult)
sent = rpc.send_data.call_args[0][0]
assert sent["id"] == "3"
assert sent["exception"] is True
# Traceback includes non-deterministic file paths and line numbers
assert "boom" in sent["error"]
def test_source_defaults_to_none(self):
"""When message has no 'source' key, run_fn gets source=None."""
run_fn = MagicMock(return_value=_MockResult("", ""))
messages = [
{
"id": "4",
"method": "run",
"module": "isort",
"argv": [],
"useStdin": False,
"cwd": "/tmp",
},
{"method": "exit"},
]
rpc = self._make_rpc(messages)
run_message_loop(rpc, run_fn, _MockResult)
call_kwargs = run_fn.call_args[1]
assert call_kwargs["source"] is None
def test_preserves_sys_path(self):
"""sys.path is restored after each run."""
original_path = sys.path[:]
run_fn = MagicMock(return_value=_MockResult("", ""))
messages = [
{
"id": "5",
"method": "run",
"module": "test",
"argv": [],
"useStdin": False,
"cwd": "/tmp",
},
{"method": "exit"},
]
rpc = self._make_rpc(messages)
run_message_loop(rpc, run_fn, _MockResult)
assert sys.path == original_path
def test_empty_stdout_includes_result_key(self):
"""When stdout is empty string, result key should still be present."""
run_fn = MagicMock(return_value=_MockResult("", ""))
messages = [
{
"id": "6",
"method": "run",
"module": "black",
"argv": [],
"useStdin": False,
"cwd": "/tmp",
},
{"method": "exit"},
]
rpc = self._make_rpc(messages)
run_message_loop(rpc, run_fn, _MockResult)
sent = rpc.send_data.call_args[0][0]
assert "result" in sent
assert sent["result"] == ""
def test_unknown_method_sends_error_response(self):
"""Unknown RPC methods should send an error response, not hang."""
messages = [
{"id": "7", "method": "unknown_method"},
{"method": "exit"},
]
rpc = self._make_rpc(messages)
run_message_loop(rpc, MagicMock(), _MockResult)
sent = rpc.send_data.call_args[0][0]
assert sent["id"] == "7"
assert "Unknown method: unknown_method" in sent["error"]
class TestBootstrapSysPath(unittest.TestCase):
"""Tests for resolve_bundle_path (and its alias bootstrap_sys_path)."""
def test_adds_tool_and_libs_dirs(self):
"""resolve_bundle_path adds both tool/ and libs/ to sys.path."""
import tempfile
original = sys.path[:]
with tempfile.TemporaryDirectory() as tmp:
# Create the expected directory layout:
# <tmp>/tool/lsp_server.py
# <tmp>/libs/
tool_dir = os.path.join(tmp, "tool")
libs_dir = os.path.join(tmp, "libs")
os.makedirs(tool_dir)
os.makedirs(libs_dir)
script = os.path.join(tool_dir, "lsp_server.py")
open(script, "w").close()
try:
result = resolve_bundle_path(script)
assert result == tmp
assert tool_dir in sys.path
assert libs_dir in sys.path
# Both should be at the front of sys.path (before original entries)
assert sys.path.index(tool_dir) < len(original)
assert sys.path.index(libs_dir) < len(original)
finally:
sys.path[:] = original
def test_returns_bundle_dir_path(self):
"""resolve_bundle_path returns the bundle directory."""
import tempfile
original = sys.path[:]
with tempfile.TemporaryDirectory() as tmp:
tool_dir = os.path.join(tmp, "tool")
libs_dir = os.path.join(tmp, "libs")
os.makedirs(tool_dir)
os.makedirs(libs_dir)
script = os.path.join(tool_dir, "lsp_server.py")
open(script, "w").close()
try:
result = resolve_bundle_path(script)
assert result == tmp
finally:
sys.path[:] = original
def test_respects_ls_import_strategy_env(self):
"""When LS_IMPORT_STRATEGY=fromEnvironment, libs are appended."""
import tempfile
original = sys.path[:]
original_env = os.environ.copy()
with tempfile.TemporaryDirectory() as tmp:
tool_dir = os.path.join(tmp, "tool")
libs_dir = os.path.join(tmp, "libs")
os.makedirs(tool_dir)
os.makedirs(libs_dir)
script = os.path.join(tool_dir, "lsp_server.py")
open(script, "w").close()
os.environ["LS_IMPORT_STRATEGY"] = "fromEnvironment"
try:
len_before = len(sys.path)
resolve_bundle_path(script)
assert libs_dir in sys.path
# libs should be appended after existing entries
assert sys.path.index(libs_dir) >= len_before
finally:
sys.path[:] = original
os.environ.clear()
os.environ.update(original_env)
if __name__ == "__main__":
unittest.main()