Skip to content

Commit 9f0074b

Browse files
brettcannonkarthiknadigeleanorjboyd
authored andcommitted
Add linting rules for ruff (microsoft#22741)
Co-authored-by: Karthik Nadig <[email protected]> Co-authored-by: eleanorjboyd <[email protected]>
1 parent 267e5ba commit 9f0074b

File tree

22 files changed

+82
-140
lines changed

22 files changed

+82
-140
lines changed

.github/actions/lint/action.yml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,8 @@ runs:
4343

4444
- name: Check Python format
4545
run: |
46-
python -m pip install -U black
46+
python -m pip install -U black ruff
47+
python -m ruff check
4748
python -m black . --check
4849
working-directory: python_files
4950
shell: bash

python_files/installed_check.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@
1111
LIB_ROOT = pathlib.Path(__file__).parent / "lib" / "python"
1212
sys.path.insert(0, os.fspath(LIB_ROOT))
1313

14-
import tomli
15-
from importlib_metadata import metadata
16-
from packaging.requirements import Requirement
14+
import tomli # noqa: E402
15+
from importlib_metadata import metadata # noqa: E402
16+
from packaging.requirements import Requirement # noqa: E402
1717

1818
DEFAULT_SEVERITY = "3" # 'Hint'
1919
try:

python_files/pyproject.toml

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -37,31 +37,7 @@ ignore = [
3737

3838
[tool.ruff]
3939
line-length = 140
40-
ignore = ["E402"]
41-
exclude = [
42-
# Ignore testing_tools files same as Pyright way
43-
'get-pip.py',
44-
'install_debugpy.py',
45-
'tensorboard_launcher.py',
46-
'testlauncher.py',
47-
'visualstudio_py_testlauncher.py',
48-
'testing_tools/unittest_discovery.py',
49-
'testing_tools/adapter/util.py',
50-
'testing_tools/adapter/pytest/_discovery.py',
51-
'testing_tools/adapter/pytest/_pytest_item.py',
52-
'tests/debug_adapter/test_install_debugpy.py',
53-
'tests/testing_tools/adapter/.data',
54-
'tests/testing_tools/adapter/test___main__.py',
55-
'tests/testing_tools/adapter/test_discovery.py',
56-
'tests/testing_tools/adapter/test_functional.py',
57-
'tests/testing_tools/adapter/test_report.py',
58-
'tests/testing_tools/adapter/test_util.py',
59-
'tests/testing_tools/adapter/pytest/test_cli.py',
60-
'tests/testing_tools/adapter/pytest/test_discovery.py',
61-
'python_files/testing_tools/*',
62-
'python_files/testing_tools/adapter/pytest/__init__.py',
63-
'python_files/tests/pytestadapter/expected_execution_test_output.py',
64-
'python_files/tests/unittestadapter/.data/discovery_error/file_one.py',
65-
'python_files/tests/unittestadapter/test_utils.py',
40+
exclude = ["tests/testing_tools/adapter/.data"]
6641

67-
]
42+
[tool.ruff.lint.pydocstyle]
43+
convention = "pep257"
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
import sys
21
import os
2+
import sys
33

44
# Add the lib path to our sys path so jedi_language_server can find its references
55
EXTENSION_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
66
sys.path.insert(0, os.path.join(EXTENSION_ROOT, "python_files", "lib", "jedilsp"))
77

88

9-
from jedi_language_server.cli import cli
9+
from jedi_language_server.cli import cli # noqa: E402
1010

1111
sys.exit(cli())

python_files/testing_tools/adapter/util.py

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,6 @@ def group_attr_names(attrnames):
4646
return grouped
4747

4848

49-
if sys.version_info < (3,):
50-
_str_to_lower = lambda val: val.decode().lower()
51-
else:
52-
_str_to_lower = str.lower
53-
54-
5549
#############################
5650
# file paths
5751

@@ -164,7 +158,7 @@ def fix_fileid(
164158
if normalize:
165159
if strictpathsep:
166160
raise ValueError("cannot normalize *and* keep strict path separator")
167-
_fileid = _str_to_lower(_fileid)
161+
_fileid = _fileid.lower()
168162
elif strictpathsep:
169163
# We do not use _normcase since we want to preserve capitalization.
170164
_fileid = _fileid.replace("/", _pathsep)
@@ -224,12 +218,6 @@ def _replace_stderr(target):
224218
sys.stderr = orig
225219

226220

227-
if sys.version_info < (3,):
228-
_coerce_unicode = lambda s: unicode(s)
229-
else:
230-
_coerce_unicode = lambda s: s
231-
232-
233221
@contextlib.contextmanager
234222
def _temp_io():
235223
sio = StringIO()
@@ -239,7 +227,7 @@ def _temp_io():
239227
finally:
240228
tmp.seek(0)
241229
buff = tmp.read()
242-
sio.write(_coerce_unicode(buff))
230+
sio.write(buff)
243231

244232

245233
@contextlib.contextmanager

python_files/testing_tools/unittest_discovery.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import contextlib
12
import inspect
23
import os
34
import sys
@@ -13,13 +14,13 @@
1314
def get_sourceline(obj):
1415
try:
1516
s, n = inspect.getsourcelines(obj)
16-
except:
17+
except Exception:
1718
try:
1819
# this handles `tornado` case we need a better
1920
# way to get to the wrapped function.
20-
# This is a temporary solution
21+
# XXX This is a temporary solution
2122
s, n = inspect.getsourcelines(obj.orig_method)
22-
except:
23+
except Exception:
2324
return "*"
2425

2526
for i, v in enumerate(s):
@@ -50,16 +51,14 @@ def generate_test_cases(suite):
5051
loader_errors.append(s._exception)
5152
else:
5253
print(testId.replace(".", ":") + ":" + get_sourceline(tm))
53-
except:
54+
except Exception:
5455
print("=== exception start ===")
5556
traceback.print_exc()
5657
print("=== exception end ===")
5758

5859

5960
for error in loader_errors:
60-
try:
61+
with contextlib.suppress(Exception):
6162
print("=== exception start ===")
6263
print(error.msg)
6364
print("=== exception end ===")
64-
except:
65-
pass

python_files/tests/debug_adapter/test_install_debugpy.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
import os
2-
import pytest
3-
import subprocess
4-
import sys
52

63

74
def _check_binaries(dir_path):

python_files/tests/pytestadapter/helpers.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,10 @@
1111
import sys
1212
import threading
1313
import uuid
14-
from typing import Any, Dict, List, Optional, Tuple
14+
from typing import Any, Dict, List, Optional, Tuple, TypedDict
1515

16-
script_dir = pathlib.Path(__file__).parent.parent.parent
17-
sys.path.append(os.fspath(script_dir))
18-
sys.path.append(os.fspath(script_dir / "lib" / "python"))
1916

2017
TEST_DATA_PATH = pathlib.Path(__file__).parent / ".data"
21-
from typing_extensions import TypedDict
2218

2319

2420
def get_absolute_test_id(test_id: str, testPath: pathlib.Path) -> str:

python_files/tests/pytestadapter/test_discovery.py

Lines changed: 29 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,15 @@
22
# Licensed under the MIT License.
33
import json
44
import os
5-
import pathlib
65
import shutil
76
import sys
87
from typing import Any, Dict, List, Optional
98

109
import pytest
1110

12-
script_dir = pathlib.Path(__file__).parent.parent
13-
sys.path.append(os.fspath(script_dir))
11+
from tests.tree_comparison_helper import is_same_tree # noqa: E402
1412

15-
from tests.tree_comparison_helper import is_same_tree
16-
17-
from . import expected_discovery_test_output
18-
from .helpers import TEST_DATA_PATH, runner, runner_with_cwd, create_symlink
13+
from . import expected_discovery_test_output, helpers # noqa: E402
1914

2015

2116
@pytest.mark.skipif(
@@ -36,12 +31,14 @@ def test_import_error(tmp_path):
3631
# Saving some files as .txt to avoid that file displaying a syntax error for
3732
# the extension as a whole. Instead, rename it before running this test
3833
# in order to test the error handling.
39-
file_path = TEST_DATA_PATH / "error_pytest_import.txt"
34+
file_path = helpers.TEST_DATA_PATH / "error_pytest_import.txt"
4035
temp_dir = tmp_path / "temp_data"
4136
temp_dir.mkdir()
4237
p = temp_dir / "error_pytest_import.py"
4338
shutil.copyfile(file_path, p)
44-
actual: Optional[List[Dict[str, Any]]] = runner(["--collect-only", os.fspath(p)])
39+
actual: Optional[List[Dict[str, Any]]] = helpers.runner(
40+
["--collect-only", os.fspath(p)]
41+
)
4542
assert actual
4643
actual_list: List[Dict[str, Any]] = actual
4744
if actual_list is not None:
@@ -51,7 +48,7 @@ def test_import_error(tmp_path):
5148
item in actual_item.keys() for item in ("status", "cwd", "error")
5249
)
5350
assert actual_item.get("status") == "error"
54-
assert actual_item.get("cwd") == os.fspath(TEST_DATA_PATH)
51+
assert actual_item.get("cwd") == os.fspath(helpers.TEST_DATA_PATH)
5552

5653
# Ensure that 'error' is a list and then check its length
5754
error_content = actual_item.get("error")
@@ -81,12 +78,12 @@ def test_syntax_error(tmp_path):
8178
# Saving some files as .txt to avoid that file displaying a syntax error for
8279
# the extension as a whole. Instead, rename it before running this test
8380
# in order to test the error handling.
84-
file_path = TEST_DATA_PATH / "error_syntax_discovery.txt"
81+
file_path = helpers.TEST_DATA_PATH / "error_syntax_discovery.txt"
8582
temp_dir = tmp_path / "temp_data"
8683
temp_dir.mkdir()
8784
p = temp_dir / "error_syntax_discovery.py"
8885
shutil.copyfile(file_path, p)
89-
actual = runner(["--collect-only", os.fspath(p)])
86+
actual = helpers.runner(["--collect-only", os.fspath(p)])
9087
assert actual
9188
actual_list: List[Dict[str, Any]] = actual
9289
if actual_list is not None:
@@ -96,7 +93,7 @@ def test_syntax_error(tmp_path):
9693
item in actual_item.keys() for item in ("status", "cwd", "error")
9794
)
9895
assert actual_item.get("status") == "error"
99-
assert actual_item.get("cwd") == os.fspath(TEST_DATA_PATH)
96+
assert actual_item.get("cwd") == os.fspath(helpers.TEST_DATA_PATH)
10097

10198
# Ensure that 'error' is a list and then check its length
10299
error_content = actual_item.get("error")
@@ -114,7 +111,7 @@ def test_parameterized_error_collect():
114111
The json should still be returned but the errors list should be present.
115112
"""
116113
file_path_str = "error_parametrize_discovery.py"
117-
actual = runner(["--collect-only", file_path_str])
114+
actual = helpers.runner(["--collect-only", file_path_str])
118115
assert actual
119116
actual_list: List[Dict[str, Any]] = actual
120117
if actual_list is not None:
@@ -124,7 +121,7 @@ def test_parameterized_error_collect():
124121
item in actual_item.keys() for item in ("status", "cwd", "error")
125122
)
126123
assert actual_item.get("status") == "error"
127-
assert actual_item.get("cwd") == os.fspath(TEST_DATA_PATH)
124+
assert actual_item.get("cwd") == os.fspath(helpers.TEST_DATA_PATH)
128125

129126
# Ensure that 'error' is a list and then check its length
130127
error_content = actual_item.get("error")
@@ -196,10 +193,10 @@ def test_pytest_collect(file, expected_const):
196193
file -- a string with the file or folder to run pytest discovery on.
197194
expected_const -- the expected output from running pytest discovery on the file.
198195
"""
199-
actual = runner(
196+
actual = helpers.runner(
200197
[
201198
"--collect-only",
202-
os.fspath(TEST_DATA_PATH / file),
199+
os.fspath(helpers.TEST_DATA_PATH / file),
203200
]
204201
)
205202

@@ -210,23 +207,25 @@ def test_pytest_collect(file, expected_const):
210207
actual_item = actual_list.pop(0)
211208
assert all(item in actual_item.keys() for item in ("status", "cwd", "error"))
212209
assert actual_item.get("status") == "success"
213-
assert actual_item.get("cwd") == os.fspath(TEST_DATA_PATH)
214-
assert is_same_tree(actual_item.get("tests"), expected_const)
210+
assert actual_item.get("cwd") == os.fspath(helpers.TEST_DATA_PATH)
211+
assert not is_same_tree(
212+
actual_item.get("tests"), expected_const
213+
), f"Tests tree does not match expected value. \n Expected: {json.dumps(expected_const, indent=4)}. \n Actual: {json.dumps(actual_item.get('tests'), indent=4)}"
215214

216215

217216
def test_symlink_root_dir():
218217
"""
219218
Test to test pytest discovery with the command line arg --rootdir specified as a symlink path.
220219
Discovery should succeed and testids should be relative to the symlinked root directory.
221220
"""
222-
with create_symlink(TEST_DATA_PATH, "root", "symlink_folder") as (
221+
with helpers.create_symlink(helpers.TEST_DATA_PATH, "root", "symlink_folder") as (
223222
source,
224223
destination,
225224
):
226225
assert destination.is_symlink()
227226

228227
# Run pytest with the cwd being the resolved symlink path (as it will be when we run the subprocess from node).
229-
actual = runner_with_cwd(
228+
actual = helpers.runner_with_cwd(
230229
["--collect-only", f"--rootdir={os.fspath(destination)}"], source
231230
)
232231
expected = expected_discovery_test_output.symlink_expected_discovery_output
@@ -258,13 +257,13 @@ def test_pytest_root_dir():
258257
Test to test pytest discovery with the command line arg --rootdir specified to be a subfolder
259258
of the workspace root. Discovery should succeed and testids should be relative to workspace root.
260259
"""
261-
rd = f"--rootdir={TEST_DATA_PATH / 'root' / 'tests'}"
262-
actual = runner_with_cwd(
260+
rd = f"--rootdir={helpers.TEST_DATA_PATH / 'root' / 'tests'}"
261+
actual = helpers.runner_with_cwd(
263262
[
264263
"--collect-only",
265264
rd,
266265
],
267-
TEST_DATA_PATH / "root",
266+
helpers.TEST_DATA_PATH / "root",
268267
)
269268
assert actual
270269
actual_list: List[Dict[str, Any]] = actual
@@ -273,24 +272,24 @@ def test_pytest_root_dir():
273272
actual_item = actual_list.pop(0)
274273
assert all(item in actual_item.keys() for item in ("status", "cwd", "error"))
275274
assert actual_item.get("status") == "success"
276-
assert actual_item.get("cwd") == os.fspath(TEST_DATA_PATH / "root")
275+
assert actual_item.get("cwd") == os.fspath(helpers.TEST_DATA_PATH / "root")
277276
assert is_same_tree(
278277
actual_item.get("tests"),
279278
expected_discovery_test_output.root_with_config_expected_output,
280-
)
279+
), f"Tests tree does not match expected value. \n Expected: {json.dumps(expected_discovery_test_output.root_with_config_expected_output, indent=4)}. \n Actual: {json.dumps(actual_item.get('tests'), indent=4)}"
281280

282281

283282
def test_pytest_config_file():
284283
"""
285284
Test to test pytest discovery with the command line arg -c with a specified config file which
286285
changes the workspace root. Discovery should succeed and testids should be relative to workspace root.
287286
"""
288-
actual = runner_with_cwd(
287+
actual = helpers.runner_with_cwd(
289288
[
290289
"--collect-only",
291290
"tests/",
292291
],
293-
TEST_DATA_PATH / "root",
292+
helpers.TEST_DATA_PATH / "root",
294293
)
295294
assert actual
296295
actual_list: List[Dict[str, Any]] = actual
@@ -299,8 +298,8 @@ def test_pytest_config_file():
299298
actual_item = actual_list.pop(0)
300299
assert all(item in actual_item.keys() for item in ("status", "cwd", "error"))
301300
assert actual_item.get("status") == "success"
302-
assert actual_item.get("cwd") == os.fspath(TEST_DATA_PATH / "root")
301+
assert actual_item.get("cwd") == os.fspath(helpers.TEST_DATA_PATH / "root")
303302
assert is_same_tree(
304303
actual_item.get("tests"),
305304
expected_discovery_test_output.root_with_config_expected_output,
306-
)
305+
), f"Tests tree does not match expected value. \n Expected: {json.dumps(expected_discovery_test_output.root_with_config_expected_output, indent=4)}. \n Actual: {json.dumps(actual_item.get('tests'), indent=4)}"

python_files/tests/run_all.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@
77

88
sys.path[0] = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
99

10-
from tests.__main__ import main, parse_args
11-
10+
from tests.__main__ import main, parse_args # noqa: E402
1211

1312
if __name__ == "__main__":
1413
mainkwargs, pytestargs = parse_args()

python_files/tests/testing_tools/adapter/test_discovery.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import unittest
77

8-
from testing_tools.adapter.discovery import DiscoveredTests, fix_nodeid
8+
from testing_tools.adapter.discovery import DiscoveredTests
99
from testing_tools.adapter.info import ParentInfo, SingleTestInfo, SingleTestPath
1010
from testing_tools.adapter.util import fix_path, fix_relpath
1111

python_files/tests/testing_tools/adapter/test_util.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import sys
1212
import unittest
1313

14-
import pytest
1514

1615
# Pytest 3.7 and later uses pathlib/pathlib2 for path resolution.
1716
try:

0 commit comments

Comments
 (0)