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
|
# Copyright 2017-2020 Palantir Technologies, Inc.
# Copyright 2021- Python Language Server Contributors.
import os
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
"""
@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_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:
mock_instance = popen_mock.return_value
mock_instance.communicate.return_value = [bytes(), bytes()]
ruff_executable = "/tmp/ruff"
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
assert ruff_settings.executable == "ruff"
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 == [
"ruff",
"--quiet",
"--format=json",
"--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", "D103": "I"},
}
}
}
)
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"] == 3
# 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"))
|