-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathtest_ruff_lint.py
More file actions
296 lines (240 loc) · 8.54 KB
/
test_ruff_lint.py
File metadata and controls
296 lines (240 loc) · 8.54 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
# Copyright 2017-2020 Palantir Technologies, Inc.
# Copyright 2021- Python Language Server Contributors.
import os
import stat
import sys
import tempfile
from unittest.mock import Mock, patch
import pytest
from pylsp import lsp, uris
from pylsp.config.config import Config
from pylsp.workspace import Document, Workspace
import pylsp_ruff.plugin as ruff_lint
DOC_URI = uris.from_fs_path(__file__)
DOC = r"""import pylsp
t = "TEST"
def using_const():
a = 8 + 9
return t
"""
DOC_INVALID = r"""
a =
"""
@pytest.fixture()
def workspace(tmp_path):
"""Return a workspace."""
ws = Workspace(tmp_path.absolute().as_uri(), Mock())
ws._config = Config(ws.root_uri, {}, 0, {})
return ws
def temp_document(doc_text, workspace):
with tempfile.NamedTemporaryFile(
mode="w", dir=workspace.root_path, delete=False
) as temp_file:
name = temp_file.name
temp_file.write(doc_text)
doc = Document(uris.from_fs_path(name), workspace)
return name, doc
def test_ruff_unsaved(workspace):
doc = Document("", workspace, DOC)
diags = ruff_lint.pylsp_lint(workspace, doc)
msg = "Local variable `a` is assigned to but never used"
unused_var = [d for d in diags if d["message"] == msg][0]
assert unused_var["source"] == "ruff"
assert unused_var["code"] == "F841"
assert unused_var["range"]["start"] == {"line": 5, "character": 4}
assert unused_var["range"]["end"] == {"line": 5, "character": 5}
assert unused_var["severity"] == lsp.DiagnosticSeverity.Error
assert unused_var["tags"] == [lsp.DiagnosticTag.Unnecessary]
def test_ruff_lint(workspace):
name, doc = temp_document(DOC, workspace)
try:
diags = ruff_lint.pylsp_lint(workspace, doc)
msg = "Local variable `a` is assigned to but never used"
unused_var = [d for d in diags if d["message"] == msg][0]
assert unused_var["source"] == "ruff"
assert unused_var["code"] == "F841"
assert unused_var["range"]["start"] == {"line": 5, "character": 4}
assert unused_var["range"]["end"] == {"line": 5, "character": 5}
assert unused_var["severity"] == lsp.DiagnosticSeverity.Error
assert unused_var["tags"] == [lsp.DiagnosticTag.Unnecessary]
finally:
os.remove(name)
def test_ruff_invalid(workspace):
name, doc = temp_document(DOC_INVALID, workspace)
try:
diags = ruff_lint.pylsp_lint(workspace, doc)
assert len(diags) == 1
diag = diags[0]
assert diag["source"] == "ruff"
assert diag["code"] == "invalid-syntax"
assert diag["message"] == "Expected an expression"
assert diag["range"]["start"] == {"line": 1, "character": 4}
assert diag["range"]["end"] == {"line": 2, "character": 0}
assert diag["severity"] == lsp.DiagnosticSeverity.Error
assert diag["tags"] == []
finally:
os.remove(name)
def test_ruff_config_param(workspace):
with patch("pylsp_ruff.plugin.Popen") as popen_mock:
mock_instance = popen_mock.return_value
mock_instance.communicate.return_value = [bytes(), bytes()]
ruff_conf = "/tmp/pyproject.toml"
workspace._config.update(
{
"plugins": {
"ruff": {
"config": ruff_conf,
"extendSelect": ["D", "F"],
"extendIgnore": ["E"],
}
}
}
)
_name, doc = temp_document(DOC, workspace)
ruff_lint.pylsp_lint(workspace, doc)
(call_args,) = popen_mock.call_args[0]
assert "ruff" in call_args
assert f"--config={ruff_conf}" in call_args
assert "--extend-select=D,F" in call_args
assert "--extend-ignore=E" in call_args
def test_ruff_executable_param(workspace):
with patch("pylsp_ruff.plugin.Popen") as popen_mock:
with tempfile.NamedTemporaryFile() as ruff_exe:
mock_instance = popen_mock.return_value
mock_instance.communicate.return_value = [bytes(), bytes()]
ruff_executable = ruff_exe.name
# chmod +x the file
st = os.stat(ruff_executable)
os.chmod(ruff_executable, st.st_mode | stat.S_IEXEC)
workspace._config.update(
{"plugins": {"ruff": {"executable": ruff_executable}}}
)
_name, doc = temp_document(DOC, workspace)
ruff_lint.pylsp_lint(workspace, doc)
(call_args,) = popen_mock.call_args[0]
assert ruff_executable in call_args
def get_ruff_settings(workspace, doc, config_str):
"""Write a ``pyproject.toml``, load it in the workspace, and return the ruff
settings.
This function creates a ``pyproject.toml``; you'll have to delete it yourself.
"""
with open(
os.path.join(workspace.root_path, "pyproject.toml"), "w+", encoding="utf-8"
) as f:
f.write(config_str)
return ruff_lint.load_settings(workspace, doc.path)
def test_ruff_settings(workspace):
config_str = r"""[tool.ruff]
ignore = ["F841"]
exclude = [
"blah/__init__.py",
"file_2.py"
]
extend-select = ["D"]
[tool.ruff.per-file-ignores]
"test_something.py" = ["F401"]
"""
doc_str = r"""
print('hi')
import os
def f():
a = 2
"""
doc_uri = uris.from_fs_path(os.path.join(workspace.root_path, "__init__.py"))
workspace.put_document(doc_uri, doc_str)
ruff_settings = get_ruff_settings(
workspace, workspace.get_document(doc_uri), config_str
)
# Check that user config is ignored
empty_keys = [
"config",
"line_length",
"exclude",
"select",
"ignore",
"per_file_ignores",
]
for k in empty_keys:
assert getattr(ruff_settings, k) is None
with patch("pylsp_ruff.plugin.Popen") as popen_mock:
mock_instance = popen_mock.return_value
mock_instance.communicate.return_value = [bytes(), bytes()]
doc = workspace.get_document(doc_uri)
diags = ruff_lint.pylsp_lint(workspace, doc)
call_args = popen_mock.call_args[0][0]
assert call_args == [
str(sys.executable),
"-m",
"ruff",
"check",
"--quiet",
"--exit-zero",
"--output-format=json",
"--extension=ipynb:python",
"--no-fix",
"--force-exclude",
f"--stdin-filename={os.path.join(workspace.root_path, '__init__.py')}",
"--",
"-",
]
workspace._config.update(
{
"plugins": {
"ruff": {
"extendIgnore": ["D104"],
"severities": {"E402": "E", "D": "I", "D1": "H"},
}
}
}
)
diags = ruff_lint.pylsp_lint(workspace, doc)
_list = []
for diag in diags:
_list.append(diag["code"])
# Assert that ignore, extend-ignore and extend-select is working as intended
assert "E402" in _list
assert "D103" in _list
assert "D104" not in _list
assert "F841" not in _list
# Check custom severities
for diag in diags:
if diag["code"] == "E402":
assert diag["severity"] == 1
if diag["code"] == "D103":
assert diag["severity"] == 4 # Should take "D1" over "D"
# Excludes
doc_uri = uris.from_fs_path(os.path.join(workspace.root_path, "blah/__init__.py"))
workspace.put_document(doc_uri, doc_str)
ruff_settings = get_ruff_settings(
workspace, workspace.get_document(doc_uri), config_str
)
doc = workspace.get_document(doc_uri)
diags = ruff_lint.pylsp_lint(workspace, doc)
assert diags == []
# For per-file-ignores
doc_uri_per_file_ignores = uris.from_fs_path(
os.path.join(workspace.root_path, "blah/test_something.py")
)
workspace.put_document(doc_uri_per_file_ignores, doc_str)
doc = workspace.get_document(doc_uri)
diags = ruff_lint.pylsp_lint(workspace, doc)
for diag in diags:
assert diag["code"] != "F401"
os.unlink(os.path.join(workspace.root_path, "pyproject.toml"))
def test_notebook_input(workspace):
doc_str = r"""
print('hi')
import os
def f():
a = 2
"""
# attribute the python code to a notebook file name per jupyterlab-lsp
doc_uri = uris.from_fs_path(os.path.join(workspace.root_path, "Untitled.ipynb"))
workspace.put_document(doc_uri, doc_str)
doc = workspace.get_document(doc_uri)
diags = ruff_lint.pylsp_lint(workspace, doc)
diag_codes = [diag["code"] for diag in diags]
assert "invalid-syntax" not in diag_codes
assert "E402" in diag_codes
assert "F401" in diag_codes
assert "F841" in diag_codes