Update and provide fixes for mypy pre-commit (#12389)

* Update mypy to 1.6.1

* Fix mypy "Source file found twice under different module names" error

* Ignore type of intialized abstract class in tests

* Use more specific type ignore method-assign

* Type ignore for message.get_all

* Remove unused type ignore

* Add SizedBuffer type for xmlrpc.client.Transport subclass

* Add Self type for RequestHandlerClass in test

* Add type ignore for shutil.rmtree onexc handler

* Quote SizedBuffer

* Add news entry

* Remove no longer correct comment

* Update self import

* Also ignore type onerror=handler

* Update news entry

* Update news entry
This commit is contained in:
Damian Shaw 2023-11-07 04:39:01 -05:00 committed by GitHub
parent 68529081c2
commit 2a0acb595c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 38 additions and 32 deletions

View File

@ -28,20 +28,20 @@ repos:
args: [--fix, --exit-non-zero-on-fix] args: [--fix, --exit-non-zero-on-fix]
- repo: https://github.com/pre-commit/mirrors-mypy - repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.961 rev: v1.6.1
hooks: hooks:
- id: mypy - id: mypy
exclude: tests/data exclude: tests/data
args: ["--pretty", "--show-error-codes"] args: ["--pretty", "--show-error-codes"]
additional_dependencies: [ additional_dependencies: [
'keyring==23.0.1', 'keyring==24.2.0',
'nox==2021.6.12', 'nox==2023.4.22',
'pytest', 'pytest',
'types-docutils==0.18.3', 'types-docutils==0.20.0.3',
'types-setuptools==57.4.14', 'types-setuptools==68.2.0.0',
'types-freezegun==1.1.9', 'types-freezegun==1.1.10',
'types-six==1.16.15', 'types-six==1.16.21.9',
'types-pyyaml==6.0.12.2', 'types-pyyaml==6.0.12.12',
] ]
- repo: https://github.com/pre-commit/pygrep-hooks - repo: https://github.com/pre-commit/pygrep-hooks

1
news/12389.bugfix.rst Normal file
View File

@ -0,0 +1 @@
Update mypy to 1.6.1 and fix/ignore types

View File

@ -56,8 +56,7 @@ def distutils_scheme(
try: try:
d.parse_config_files() d.parse_config_files()
except UnicodeDecodeError: except UnicodeDecodeError:
# Typeshed does not include find_config_files() for some reason. paths = d.find_config_files()
paths = d.find_config_files() # type: ignore
logger.warning( logger.warning(
"Ignore distutils configs in %s due to encoding errors.", "Ignore distutils configs in %s due to encoding errors.",
", ".join(os.path.basename(p) for p in paths), ", ".join(os.path.basename(p) for p in paths),

View File

@ -64,10 +64,10 @@ def msg_to_json(msg: Message) -> Dict[str, Any]:
key = json_name(field) key = json_name(field)
if multi: if multi:
value: Union[str, List[str]] = [ value: Union[str, List[str]] = [
sanitise_header(v) for v in msg.get_all(field) sanitise_header(v) for v in msg.get_all(field) # type: ignore
] ]
else: else:
value = sanitise_header(msg.get(field)) value = sanitise_header(msg.get(field)) # type: ignore
if key == "keywords": if key == "keywords":
# Accept both comma-separated and space-separated # Accept both comma-separated and space-separated
# forms, for better compatibility with old data. # forms, for better compatibility with old data.

View File

@ -13,6 +13,8 @@ from pip._internal.network.utils import raise_for_status
if TYPE_CHECKING: if TYPE_CHECKING:
from xmlrpc.client import _HostType, _Marshallable from xmlrpc.client import _HostType, _Marshallable
from _typeshed import SizedBuffer
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -33,7 +35,7 @@ class PipXmlrpcTransport(xmlrpc.client.Transport):
self, self,
host: "_HostType", host: "_HostType",
handler: str, handler: str,
request_body: bytes, request_body: "SizedBuffer",
verbose: bool = False, verbose: bool = False,
) -> Tuple["_Marshallable", ...]: ) -> Tuple["_Marshallable", ...]:
assert isinstance(host, str) assert isinstance(host, str)

View File

@ -141,9 +141,9 @@ def rmtree(
) )
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):
# See https://docs.python.org/3.12/whatsnew/3.12.html#shutil. # See https://docs.python.org/3.12/whatsnew/3.12.html#shutil.
shutil.rmtree(dir, onexc=handler) shutil.rmtree(dir, onexc=handler) # type: ignore
else: else:
shutil.rmtree(dir, onerror=handler) shutil.rmtree(dir, onerror=handler) # type: ignore
def _onerror_ignore(*_args: Any) -> None: def _onerror_ignore(*_args: Any) -> None:

View File

@ -14,6 +14,7 @@ from hashlib import sha256
from pathlib import Path from pathlib import Path
from textwrap import dedent from textwrap import dedent
from typing import ( from typing import (
TYPE_CHECKING,
Any, Any,
AnyStr, AnyStr,
Callable, Callable,
@ -58,6 +59,9 @@ from tests.lib import (
from tests.lib.server import MockServer, make_mock_server from tests.lib.server import MockServer, make_mock_server
from tests.lib.venv import VirtualEnvironment, VirtualEnvironmentType from tests.lib.venv import VirtualEnvironment, VirtualEnvironmentType
if TYPE_CHECKING:
from pip._vendor.typing_extensions import Self
def pytest_addoption(parser: Parser) -> None: def pytest_addoption(parser: Parser) -> None:
parser.addoption( parser.addoption(
@ -941,7 +945,7 @@ def html_index_with_onetime_server(
""" """
class InDirectoryServer(http.server.ThreadingHTTPServer): class InDirectoryServer(http.server.ThreadingHTTPServer):
def finish_request(self, request: Any, client_address: Any) -> None: def finish_request(self: "Self", request: Any, client_address: Any) -> None:
self.RequestHandlerClass( self.RequestHandlerClass(
request, request,
client_address, client_address,

View File

@ -38,7 +38,7 @@ class ConfigurationMixin:
old() old()
# https://github.com/python/mypy/issues/2427 # https://github.com/python/mypy/issues/2427
self.configuration._load_config_files = overridden # type: ignore[assignment] self.configuration._load_config_files = overridden # type: ignore[method-assign]
@contextlib.contextmanager @contextlib.contextmanager
def tmpfile(self, contents: str) -> Iterator[str]: def tmpfile(self, contents: str) -> Iterator[str]:

View File

@ -19,12 +19,12 @@ from tests.lib.wheel import (
def test_message_from_dict_one_value() -> None: def test_message_from_dict_one_value() -> None:
message = message_from_dict({"a": "1"}) message = message_from_dict({"a": "1"})
assert set(message.get_all("a")) == {"1"} assert set(message.get_all("a")) == {"1"} # type: ignore
def test_message_from_dict_multiple_values() -> None: def test_message_from_dict_multiple_values() -> None:
message = message_from_dict({"a": ["1", "2"]}) message = message_from_dict({"a": ["1", "2"]})
assert set(message.get_all("a")) == {"1", "2"} assert set(message.get_all("a")) == {"1", "2"} # type: ignore
def message_from_bytes(contents: bytes) -> Message: def message_from_bytes(contents: bytes) -> Message:
@ -67,7 +67,7 @@ def test_make_metadata_file_custom_value_list() -> None:
f = default_make_metadata(updates={"a": ["1", "2"]}) f = default_make_metadata(updates={"a": ["1", "2"]})
assert f is not None assert f is not None
message = default_metadata_checks(f) message = default_metadata_checks(f)
assert set(message.get_all("a")) == {"1", "2"} assert set(message.get_all("a")) == {"1", "2"} # type: ignore
def test_make_metadata_file_custom_value_overrides() -> None: def test_make_metadata_file_custom_value_overrides() -> None:
@ -101,7 +101,7 @@ def default_wheel_metadata_checks(f: File) -> Message:
assert message.get_all("Wheel-Version") == ["1.0"] assert message.get_all("Wheel-Version") == ["1.0"]
assert message.get_all("Generator") == ["pip-test-suite"] assert message.get_all("Generator") == ["pip-test-suite"]
assert message.get_all("Root-Is-Purelib") == ["true"] assert message.get_all("Root-Is-Purelib") == ["true"]
assert set(message.get_all("Tag")) == {"py2-none-any", "py3-none-any"} assert set(message.get_all("Tag")) == {"py2-none-any", "py3-none-any"} # type: ignore
return message return message
@ -122,7 +122,7 @@ def test_make_wheel_metadata_file_custom_value_list() -> None:
f = default_make_wheel_metadata(updates={"a": ["1", "2"]}) f = default_make_wheel_metadata(updates={"a": ["1", "2"]})
assert f is not None assert f is not None
message = default_wheel_metadata_checks(f) message = default_wheel_metadata_checks(f)
assert set(message.get_all("a")) == {"1", "2"} assert set(message.get_all("a")) == {"1", "2"} # type: ignore
def test_make_wheel_metadata_file_custom_value_override() -> None: def test_make_wheel_metadata_file_custom_value_override() -> None:

View File

@ -23,7 +23,7 @@ def test_dist_get_direct_url_no_metadata(mock_read_text: mock.Mock) -> None:
class FakeDistribution(BaseDistribution): class FakeDistribution(BaseDistribution):
pass pass
dist = FakeDistribution() dist = FakeDistribution() # type: ignore
assert dist.direct_url is None assert dist.direct_url is None
mock_read_text.assert_called_once_with(DIRECT_URL_METADATA_NAME) mock_read_text.assert_called_once_with(DIRECT_URL_METADATA_NAME)
@ -35,7 +35,7 @@ def test_dist_get_direct_url_invalid_json(
class FakeDistribution(BaseDistribution): class FakeDistribution(BaseDistribution):
canonical_name = cast(NormalizedName, "whatever") # Needed for error logging. canonical_name = cast(NormalizedName, "whatever") # Needed for error logging.
dist = FakeDistribution() dist = FakeDistribution() # type: ignore
with caplog.at_level(logging.WARNING): with caplog.at_level(logging.WARNING):
assert dist.direct_url is None assert dist.direct_url is None
@ -84,7 +84,7 @@ def test_dist_get_direct_url_valid_metadata(mock_read_text: mock.Mock) -> None:
class FakeDistribution(BaseDistribution): class FakeDistribution(BaseDistribution):
pass pass
dist = FakeDistribution() dist = FakeDistribution() # type: ignore
direct_url = dist.direct_url direct_url = dist.direct_url
assert direct_url is not None assert direct_url is not None
mock_read_text.assert_called_once_with(DIRECT_URL_METADATA_NAME) mock_read_text.assert_called_once_with(DIRECT_URL_METADATA_NAME)

View File

@ -151,7 +151,7 @@ def test_base_command_provides_tempdir_helpers() -> None:
c = Command("fake", "fake") c = Command("fake", "fake")
# https://github.com/python/mypy/issues/2427 # https://github.com/python/mypy/issues/2427
c.run = Mock(side_effect=assert_helpers_set) # type: ignore[assignment] c.run = Mock(side_effect=assert_helpers_set) # type: ignore[method-assign]
assert c.main(["fake"]) == SUCCESS assert c.main(["fake"]) == SUCCESS
c.run.assert_called_once() c.run.assert_called_once()
@ -176,7 +176,7 @@ def test_base_command_global_tempdir_cleanup(kind: str, exists: bool) -> None:
c = Command("fake", "fake") c = Command("fake", "fake")
# https://github.com/python/mypy/issues/2427 # https://github.com/python/mypy/issues/2427
c.run = Mock(side_effect=create_temp_dirs) # type: ignore[assignment] c.run = Mock(side_effect=create_temp_dirs) # type: ignore[method-assign]
assert c.main(["fake"]) == SUCCESS assert c.main(["fake"]) == SUCCESS
c.run.assert_called_once() c.run.assert_called_once()
assert os.path.exists(Holder.value) == exists assert os.path.exists(Holder.value) == exists
@ -200,6 +200,6 @@ def test_base_command_local_tempdir_cleanup(kind: str, exists: bool) -> None:
c = Command("fake", "fake") c = Command("fake", "fake")
# https://github.com/python/mypy/issues/2427 # https://github.com/python/mypy/issues/2427
c.run = Mock(side_effect=create_temp_dirs) # type: ignore[assignment] c.run = Mock(side_effect=create_temp_dirs) # type: ignore[method-assign]
assert c.main(["fake"]) == SUCCESS assert c.main(["fake"]) == SUCCESS
c.run.assert_called_once() c.run.assert_called_once()

View File

@ -215,7 +215,7 @@ class TestConfigurationModification(ConfigurationMixin):
# Mock out the method # Mock out the method
mymock = MagicMock(spec=self.configuration._mark_as_modified) mymock = MagicMock(spec=self.configuration._mark_as_modified)
# https://github.com/python/mypy/issues/2427 # https://github.com/python/mypy/issues/2427
self.configuration._mark_as_modified = mymock # type: ignore[assignment] self.configuration._mark_as_modified = mymock # type: ignore[method-assign]
self.configuration.set_value("test.hello", "10") self.configuration.set_value("test.hello", "10")
@ -231,7 +231,7 @@ class TestConfigurationModification(ConfigurationMixin):
# Mock out the method # Mock out the method
mymock = MagicMock(spec=self.configuration._mark_as_modified) mymock = MagicMock(spec=self.configuration._mark_as_modified)
# https://github.com/python/mypy/issues/2427 # https://github.com/python/mypy/issues/2427
self.configuration._mark_as_modified = mymock # type: ignore[assignment] self.configuration._mark_as_modified = mymock # type: ignore[method-assign]
self.configuration.set_value("test.hello", "10") self.configuration.set_value("test.hello", "10")
@ -250,7 +250,7 @@ class TestConfigurationModification(ConfigurationMixin):
# Mock out the method # Mock out the method
mymock = MagicMock(spec=self.configuration._mark_as_modified) mymock = MagicMock(spec=self.configuration._mark_as_modified)
# https://github.com/python/mypy/issues/2427 # https://github.com/python/mypy/issues/2427
self.configuration._mark_as_modified = mymock # type: ignore[assignment] self.configuration._mark_as_modified = mymock # type: ignore[method-assign]
self.configuration.set_value("test.hello", "10") self.configuration.set_value("test.hello", "10")

View File

@ -252,7 +252,7 @@ class TestCheckDistRequiresPython:
def metadata(self) -> email.message.Message: def metadata(self) -> email.message.Message:
raise FileNotFoundError(metadata_name) raise FileNotFoundError(metadata_name)
dist = make_fake_dist(klass=NotWorkingFakeDist) dist = make_fake_dist(klass=NotWorkingFakeDist) # type: ignore
with pytest.raises(NoneMetadataError) as exc: with pytest.raises(NoneMetadataError) as exc:
_check_dist_requires_python( _check_dist_requires_python(

0
tools/__init__.py Normal file
View File