Skip to content

Commit

Permalink
Ruff: lint pytest
Browse files Browse the repository at this point in the history
  • Loading branch information
Avasam committed Aug 27, 2024
1 parent e55c19e commit d93e6e1
Show file tree
Hide file tree
Showing 14 changed files with 70 additions and 71 deletions.
4 changes: 2 additions & 2 deletions pkg_resources/tests/test_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,7 @@ def test_spaces_between_multiple_versions(self):
(req,) = parse_requirements('foo >= 1.0, < 3')

@pytest.mark.parametrize(
['lower', 'upper'],
'lower, upper',
[
('1.2-rc1', '1.2rc1'),
('0.4', '0.4.0'),
Expand All @@ -724,7 +724,7 @@ def testVersionEquality(self, lower, upper):
"""

@pytest.mark.parametrize(
['lower', 'upper'],
'lower, upper',
[
('2.1', '2.1.1'),
('2a1', '2b0'),
Expand Down
4 changes: 0 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,3 @@ formats = "zip"


[tool.setuptools_scm]


[tool.pytest-enabler.mypy]
# Disabled due to jaraco/skeleton#143
17 changes: 15 additions & 2 deletions ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,21 @@ extend-select = [

# local
"ANN2", # missing-return-type-*
"FA", # flake8-future-annotations
"F404", # late-future-import
"FA", # flake8-future-annotations
"I", # isort
"PT", # flake8-pytest-style
"PYI", # flake8-pyi
"TRY", # tryceratops
"UP", # pyupgrade
"TRY",
"YTT", # flake8-2020
]
ignore = [
"PT004", # deprecated https://github.com/astral-sh/ruff/issues/8796#issuecomment-2057143531
"PT005", # deprecated https://github.com/astral-sh/ruff/issues/8796#issuecomment-2057143531
"PT007", # temporarily disabled, TODO: configure and standardize to preference
"PT011", # temporarily disabled, TODO: tighten expected error
"PT012", # pytest-raises-with-multiple-statements, avoid extra dummy methods for a few lines, sometimes we explicitly assert in case of no error
"TRY003", # raise-vanilla-args, avoid multitude of exception classes
"TRY301", # raise-within-try, it's handy
"UP015", # redundant-open-modes, explicit is preferred
Expand Down Expand Up @@ -70,6 +76,13 @@ sections.delayed = ["distutils"]
[lint.flake8-annotations]
ignore-fully-untyped = true

[lint.flake8-pytest-style]
parametrize-names-type = "csv"
# These default to false in non-preview mode in Ruff 0.6,
# we'll be able to remove this config once raising our minimum version
fixture-parentheses = false
mark-parentheses = false

[format]
# Enable preview to get hugged parenthesis unwrapping and other nice surprises
# See https://github.com/jaraco/skeleton/pull/133#issuecomment-2239538373
Expand Down
4 changes: 3 additions & 1 deletion setuptools/command/install_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ def copy_tree(
preserve_symlinks=False,
level=1,
) -> list[str]:
assert preserve_mode and preserve_times and not preserve_symlinks
assert preserve_mode
assert preserve_times
assert not preserve_symlinks
exclude = self.get_exclusions()

if not exclude:
Expand Down
4 changes: 3 additions & 1 deletion setuptools/command/upload_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,9 @@ def upload_file(self, filename):
schema, netloc, url, params, query, fragments = urllib.parse.urlparse(
self.repository
)
assert not params and not query and not fragments
assert not params
assert not query
assert not fragments
if schema == 'http':
conn = http.client.HTTPConnection(netloc)
elif schema == 'https':
Expand Down
2 changes: 1 addition & 1 deletion setuptools/tests/config/test_apply_pyprojecttoml.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ def test_no_explicit_content_type_for_missing_extension(tmp_path):


@pytest.mark.parametrize(
('pyproject_text', 'expected_maintainers_meta_value'),
'pyproject_text, expected_maintainers_meta_value',
(
pytest.param(
PEP621_EXAMPLE,
Expand Down
19 changes: 9 additions & 10 deletions setuptools/tests/integration/test_pip_install_sdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,23 +104,22 @@ def venv_python(tmp_path):


@pytest.fixture(autouse=True)
def _prepare(tmp_path, venv_python, monkeypatch, request):
def _prepare(tmp_path, venv_python, monkeypatch):
download_path = os.getenv("DOWNLOAD_PATH", str(tmp_path))
os.makedirs(download_path, exist_ok=True)

# Environment vars used for building some of the packages
monkeypatch.setenv("USE_MYPYC", "1")

def _debug_info():
# Let's provide the maximum amount of information possible in the case
# it is necessary to debug the tests directly from the CI logs.
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Temporary directory:")
map(print, tmp_path.glob("*"))
print("Virtual environment:")
run([venv_python, "-m", "pip", "freeze"])
yield

request.addfinalizer(_debug_info)
# Let's provide the maximum amount of information possible in the case
# it is necessary to debug the tests directly from the CI logs.
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Temporary directory:")
map(print, tmp_path.glob("*"))
print("Virtual environment:")
run([venv_python, "-m", "pip", "freeze"])


@pytest.mark.parametrize('package, version', EXAMPLES)
Expand Down
10 changes: 7 additions & 3 deletions setuptools/tests/test_bdist_egg.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"""


@pytest.fixture(scope='function')
@pytest.fixture
def setup_context(tmpdir):
with (tmpdir / 'setup.py').open('w') as f:
f.write(SETUP_PY)
Expand All @@ -28,7 +28,9 @@ def setup_context(tmpdir):


class Test:
def test_bdist_egg(self, setup_context, user_override):
@pytest.mark.usefixtures("user_override")
@pytest.mark.usefixtures("setup_context")
def test_bdist_egg(self):
dist = Distribution(
dict(
script_name='setup.py',
Expand All @@ -50,7 +52,9 @@ def test_bdist_egg(self, setup_context, user_override):
os.environ.get('PYTHONDONTWRITEBYTECODE', False),
reason="Byte code disabled",
)
def test_exclude_source_files(self, setup_context, user_override):
@pytest.mark.usefixtures("user_override")
@pytest.mark.usefixtures("setup_context")
def test_exclude_source_files(self):
dist = Distribution(
dict(
script_name='setup.py',
Expand Down
15 changes: 8 additions & 7 deletions setuptools/tests/test_easy_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,14 +407,14 @@ def test_multiproc_atexit(self):
logging.basicConfig(level=logging.INFO, stream=sys.stderr)
log.info('this should not break')

@pytest.fixture()
@pytest.fixture
def foo_package(self, tmpdir):
egg_file = tmpdir / 'foo-1.0.egg-info'
with egg_file.open('w') as f:
f.write('Name: foo\n')
return str(tmpdir)

@pytest.fixture()
@pytest.fixture
def install_target(self, tmpdir):
target = str(tmpdir)
with mock.patch('sys.path', sys.path + [target]):
Expand Down Expand Up @@ -472,6 +472,12 @@ def distutils_package():
yield


@pytest.mark.usefixtures("distutils_package")
class TestDistutilsPackage:
def test_bdist_egg_available_on_distutils_pkg(self):
run_setup('setup.py', ['bdist_egg'])


@pytest.fixture
def mock_index():
# set up a server which will simulate an alternate package index.
Expand All @@ -484,11 +490,6 @@ def mock_index():
return p_index


class TestDistutilsPackage:
def test_bdist_egg_available_on_distutils_pkg(self, distutils_package):
run_setup('setup.py', ['bdist_egg'])


class TestInstallRequires:
def test_setup_install_includes_dependencies(self, tmp_path, mock_index):
"""
Expand Down
24 changes: 11 additions & 13 deletions setuptools/tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,25 +37,14 @@ def setup_module(module):


@pytest.fixture
def install_context(request, tmpdir, monkeypatch):
def install_context(tmpdir, monkeypatch):
"""Fixture to set up temporary installation directory."""
# Save old values so we can restore them.
new_cwd = tmpdir.mkdir('cwd')
user_base = tmpdir.mkdir('user_base')
user_site = tmpdir.mkdir('user_site')
install_dir = tmpdir.mkdir('install_dir')

def fin():
# undo the monkeypatch, particularly needed under
# windows because of kept handle on cwd
monkeypatch.undo()
new_cwd.remove()
user_base.remove()
user_site.remove()
install_dir.remove()

request.addfinalizer(fin)

# Change the environment and site settings to control where the
# files are installed and ensure we do not overwrite anything.
monkeypatch.chdir(new_cwd)
Expand All @@ -69,7 +58,16 @@ def fin():
dist = Distribution()
cmd = easy_install(dist)
cmd.install_dir = install_dir.strpath
return cmd

yield cmd

# undo the monkeypatch, particularly needed under
# windows because of kept handle on cwd
monkeypatch.undo()
new_cwd.remove()
user_base.remove()
user_site.remove()
install_dir.remove()


def _install_one(requirement, cmd, pkgname, modulename):
Expand Down
8 changes: 1 addition & 7 deletions setuptools/tests/test_manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,14 +485,8 @@ def test_process_template_line_invalid(self):
'prune',
'blarg',
):
try:
with pytest.raises(DistutilsTemplateError):
file_list.process_template_line(action)
except DistutilsTemplateError:
pass
except Exception:
assert False, "Incorrect error thrown"
else:
assert False, "Should have thrown an error"

def test_include(self, caplog):
caplog.set_level(logging.DEBUG)
Expand Down
23 changes: 6 additions & 17 deletions setuptools/tests/test_packageindex.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import http.client
import re
import urllib.error
import urllib.request
from inspect import cleandoc
Expand All @@ -24,11 +25,8 @@ def test_regex(self):
def test_bad_url_bad_port(self):
index = setuptools.package_index.PackageIndex()
url = 'http://127.0.0.1:0/nonesuch/test_package_index'
try:
with pytest.raises(Exception, match=re.escape(url)):
v = index.open_url(url)
except Exception as exc:
assert url in str(exc)
else:
assert isinstance(v, urllib.error.HTTPError)

def test_bad_url_typo(self):
Expand All @@ -37,15 +35,10 @@ def test_bad_url_typo(self):
# in its home URL
index = setuptools.package_index.PackageIndex(hosts=('www.example.com',))

url = (
'url:%20https://svn.plone.org/svn'
'/collective/inquant.contentmirror.plone/trunk'
)
try:
url = 'url:%20https://svn.plone.org/svn/collective/inquant.contentmirror.plone/trunk'

with pytest.raises(Exception, match=re.escape(url)):
v = index.open_url(url)
except Exception as exc:
assert url in str(exc)
else:
assert isinstance(v, urllib.error.HTTPError)

def test_bad_url_bad_status_line(self):
Expand All @@ -56,12 +49,8 @@ def _urlopen(*args):

index.opener = _urlopen
url = 'http://example.com'
try:
with pytest.raises(Exception, match=r'line'):
index.open_url(url)
except Exception as exc:
assert 'line' in str(exc)
else:
raise AssertionError('Should have raise here!')

def test_bad_url_double_scheme(self):
"""
Expand Down
5 changes: 3 additions & 2 deletions setuptools/tests/test_setuptools.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

@pytest.fixture(autouse=True)
def isolated_dir(tmpdir_cwd):
yield
return


def makeSetup(**args):
Expand Down Expand Up @@ -257,7 +257,8 @@ def can_symlink(tmpdir):
os.remove(link_fn)


def test_findall_missing_symlink(tmpdir, can_symlink):
@pytest.mark.usefixtures("can_symlink")
def test_findall_missing_symlink(tmpdir):
with tmpdir.as_cwd():
os.symlink('foo', 'bar')
found = list(setuptools.findall())
Expand Down
2 changes: 1 addition & 1 deletion setuptools/tests/test_wheel.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@


@pytest.mark.parametrize(
('filename', 'info'), WHEEL_INFO_TESTS, ids=[t[0] for t in WHEEL_INFO_TESTS]
'filename, info', WHEEL_INFO_TESTS, ids=[t[0] for t in WHEEL_INFO_TESTS]
)
def test_wheel_info(filename, info):
if inspect.isclass(info):
Expand Down

0 comments on commit d93e6e1

Please sign in to comment.