Cleanup with ruff check (#1182)

* Implement improvements suggested by ruff check.

* Add ruff check to CI.
This commit is contained in:
Felix Fontein
2025-10-28 06:58:15 +01:00
committed by GitHub
parent 3bade286f8
commit dbc7b0ec18
40 changed files with 247 additions and 232 deletions
@@ -226,7 +226,7 @@ class DockerApiTest(BaseAPIClientTest):
def test_retrieve_server_version(self) -> None:
client = APIClient(version="auto")
assert isinstance(client._version, str)
assert not (client._version == "auto")
assert client._version != "auto"
client.close()
def test_auto_retrieve_server_version(self) -> None:
@@ -323,8 +323,8 @@ class DockerApiTest(BaseAPIClientTest):
# mock a stream interface
raw_resp = urllib3.HTTPResponse(body=body)
setattr(raw_resp._fp, "chunked", True)
setattr(raw_resp._fp, "chunk_left", len(body.getvalue()) - 1)
raw_resp._fp.chunked = True
raw_resp._fp.chunk_left = len(body.getvalue()) - 1
# pass `decode=False` to the helper
raw_resp._fp.seek(0)
@@ -339,7 +339,7 @@ class DockerApiTest(BaseAPIClientTest):
assert result == content
# non-chunked response, pass `decode=False` to the helper
setattr(raw_resp._fp, "chunked", False)
raw_resp._fp.chunked = False
raw_resp._fp.seek(0)
resp = create_response(status_code=status_code, content=content, raw=raw_resp)
result = next(self.client._stream_helper(resp))
@@ -503,7 +503,7 @@ class TCPSocketStreamTest(unittest.TestCase):
cls.thread.join()
@classmethod
def get_handler_class(cls) -> t.Type[BaseHTTPRequestHandler]:
def get_handler_class(cls) -> type[BaseHTTPRequestHandler]:
stdout_data = cls.stdout_data
stderr_data = cls.stderr_data
@@ -581,7 +581,7 @@ fake_responses: dict[str | tuple[str, str], Callable] = {
f"{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/restart": post_fake_restart_container,
f"{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b": delete_fake_remove_container,
# TODO: the following is a duplicate of the import endpoint further above!
f"{prefix}/{CURRENT_VERSION}/images/create": post_fake_image_create,
f"{prefix}/{CURRENT_VERSION}/images/create": post_fake_image_create, # noqa: F601
f"{prefix}/{CURRENT_VERSION}/images/e9aa60c60128": delete_fake_remove_image,
f"{prefix}/{CURRENT_VERSION}/images/e9aa60c60128/get": get_fake_get_image,
f"{prefix}/{CURRENT_VERSION}/images/load": post_fake_load_image,
@@ -256,7 +256,7 @@ class ResolveAuthTest(unittest.TestCase):
m.return_value = None
ac = auth.resolve_authconfig(auth_config, None)
assert ac is not None
assert "indexuser" == ac["username"]
assert ac["username"] == "indexuser"
class LoadConfigTest(unittest.TestCase):
@@ -421,18 +421,18 @@ class TarTest(unittest.TestCase):
base = make_tree(dirs, files)
self.addCleanup(shutil.rmtree, base)
with tar(base, exclude=exclude) as archive:
with tarfile.open(fileobj=archive) as tar_data:
assert sorted(tar_data.getnames()) == sorted(expected_names)
with tar(base, exclude=exclude) as archive, tarfile.open(
fileobj=archive
) as tar_data:
assert sorted(tar_data.getnames()) == sorted(expected_names)
def test_tar_with_empty_directory(self) -> None:
base = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, base)
for d in ["foo", "bar"]:
os.makedirs(os.path.join(base, d))
with tar(base) as archive:
with tarfile.open(fileobj=archive) as tar_data:
assert sorted(tar_data.getnames()) == ["bar", "foo"]
with tar(base) as archive, tarfile.open(fileobj=archive) as tar_data:
assert sorted(tar_data.getnames()) == ["bar", "foo"]
@pytest.mark.skipif(
IS_WINDOWS_PLATFORM or os.geteuid() == 0,
@@ -458,9 +458,8 @@ class TarTest(unittest.TestCase):
f.write("content")
os.makedirs(os.path.join(base, "bar"))
os.symlink("../foo", os.path.join(base, "bar/foo"))
with tar(base) as archive:
with tarfile.open(fileobj=archive) as tar_data:
assert sorted(tar_data.getnames()) == ["bar", "bar/foo", "foo"]
with tar(base) as archive, tarfile.open(fileobj=archive) as tar_data:
assert sorted(tar_data.getnames()) == ["bar", "bar/foo", "foo"]
@pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason="No symlinks on Windows")
def test_tar_with_directory_symlinks(self) -> None:
@@ -469,9 +468,8 @@ class TarTest(unittest.TestCase):
for d in ["foo", "bar"]:
os.makedirs(os.path.join(base, d))
os.symlink("../foo", os.path.join(base, "bar/foo"))
with tar(base) as archive:
with tarfile.open(fileobj=archive) as tar_data:
assert sorted(tar_data.getnames()) == ["bar", "bar/foo", "foo"]
with tar(base) as archive, tarfile.open(fileobj=archive) as tar_data:
assert sorted(tar_data.getnames()) == ["bar", "bar/foo", "foo"]
@pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason="No symlinks on Windows")
def test_tar_with_broken_symlinks(self) -> None:
@@ -481,9 +479,8 @@ class TarTest(unittest.TestCase):
os.makedirs(os.path.join(base, d))
os.symlink("../baz", os.path.join(base, "bar/foo"))
with tar(base) as archive:
with tarfile.open(fileobj=archive) as tar_data:
assert sorted(tar_data.getnames()) == ["bar", "bar/foo", "foo"]
with tar(base) as archive, tarfile.open(fileobj=archive) as tar_data:
assert sorted(tar_data.getnames()) == ["bar", "bar/foo", "foo"]
@pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason="No UNIX sockets on Win32")
def test_tar_socket_file(self) -> None:
@@ -494,9 +491,8 @@ class TarTest(unittest.TestCase):
sock = socket.socket(socket.AF_UNIX)
self.addCleanup(sock.close)
sock.bind(os.path.join(base, "test.sock"))
with tar(base) as archive:
with tarfile.open(fileobj=archive) as tar_data:
assert sorted(tar_data.getnames()) == ["bar", "foo"]
with tar(base) as archive, tarfile.open(fileobj=archive) as tar_data:
assert sorted(tar_data.getnames()) == ["bar", "foo"]
def tar_test_negative_mtime_bug(self) -> None:
base = tempfile.mkdtemp()
@@ -505,10 +501,9 @@ class TarTest(unittest.TestCase):
with open(filename, "wt", encoding="utf-8") as f:
f.write("Invisible Full Moon")
os.utime(filename, (12345, -3600.0))
with tar(base) as archive:
with tarfile.open(fileobj=archive) as tar_data:
assert tar_data.getnames() == ["th.txt"]
assert tar_data.getmember("th.txt").mtime == -3600
with tar(base) as archive, tarfile.open(fileobj=archive) as tar_data:
assert tar_data.getnames() == ["th.txt"]
assert tar_data.getmember("th.txt").mtime == -3600
@pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason="No symlinks on Windows")
def test_tar_directory_link(self) -> None:
@@ -58,7 +58,12 @@ class KwargsFromEnvTest(unittest.TestCase):
self.os_environ = os.environ.copy()
def tearDown(self) -> None:
os.environ = self.os_environ # type: ignore
for k, v in self.os_environ.items():
if os.environ.get(k) != v:
os.environ[k] = v
for k in os.environ:
if k not in self.os_environ:
os.environ.pop(k)
def test_kwargs_from_env_empty(self) -> None:
os.environ.update(DOCKER_HOST="", DOCKER_CERT_PATH="")
@@ -75,7 +80,7 @@ class KwargsFromEnvTest(unittest.TestCase):
DOCKER_TLS_VERIFY="1",
)
kwargs = kwargs_from_env(assert_hostname=False)
assert "tcp://192.168.59.103:2376" == kwargs["base_url"]
assert kwargs["base_url"] == "tcp://192.168.59.103:2376"
assert "ca.pem" in kwargs["tls"].ca_cert
assert "cert.pem" in kwargs["tls"].cert[0]
assert "key.pem" in kwargs["tls"].cert[1]
@@ -99,7 +104,7 @@ class KwargsFromEnvTest(unittest.TestCase):
DOCKER_TLS_VERIFY="",
)
kwargs = kwargs_from_env(assert_hostname=True)
assert "tcp://192.168.59.103:2376" == kwargs["base_url"]
assert kwargs["base_url"] == "tcp://192.168.59.103:2376"
assert "ca.pem" in kwargs["tls"].ca_cert
assert "cert.pem" in kwargs["tls"].cert[0]
assert "key.pem" in kwargs["tls"].cert[1]
@@ -125,7 +130,7 @@ class KwargsFromEnvTest(unittest.TestCase):
)
os.environ.pop("DOCKER_CERT_PATH", None)
kwargs = kwargs_from_env(assert_hostname=True)
assert "tcp://192.168.59.103:2376" == kwargs["base_url"]
assert kwargs["base_url"] == "tcp://192.168.59.103:2376"
def test_kwargs_from_env_no_cert_path(self) -> None:
try:
@@ -157,7 +162,7 @@ class KwargsFromEnvTest(unittest.TestCase):
"DOCKER_HOST": "http://docker.gensokyo.jp:2581",
}
)
assert "http://docker.gensokyo.jp:2581" == kwargs["base_url"]
assert kwargs["base_url"] == "http://docker.gensokyo.jp:2581"
assert "tls" not in kwargs
@@ -23,7 +23,6 @@ from ..test_support.docker_image_archive_stubbing import (
if t.TYPE_CHECKING:
from collections.abc import Callable
from pathlib import Path
def assert_no_logging(msg: str) -> t.NoReturn:
@@ -156,7 +156,7 @@ def test_has_list_changed() -> None:
[{"a": 1}, {"a": 2}], [{"a": 1}, {"a": 2}], sort_key="a"
)
with pytest.raises(Exception):
with pytest.raises(ValueError):
docker_swarm_service.has_list_changed(
[{"a": 1}, {"a": 2}], [{"a": 1}, {"a": 2}]
)
@@ -36,15 +36,14 @@ def write_imitation_archive(
def write_imitation_archive_with_manifest(
file_name: str, manifest: list[dict[str, t.Any]]
) -> None:
with tarfile.open(file_name, "w") as tf:
with TemporaryFile() as f:
f.write(json.dumps(manifest).encode("utf-8"))
with tarfile.open(file_name, "w") as tf, TemporaryFile() as f:
f.write(json.dumps(manifest).encode("utf-8"))
ti = tarfile.TarInfo("manifest.json")
ti.size = f.tell()
ti = tarfile.TarInfo("manifest.json")
ti.size = f.tell()
f.seek(0)
tf.addfile(ti, f)
f.seek(0)
tf.addfile(ti, f)
def write_irrelevant_tar(file_name: str) -> None:
@@ -55,12 +54,11 @@ def write_irrelevant_tar(file_name: str) -> None:
:type file_name: str
"""
with tarfile.open(file_name, "w") as tf:
with TemporaryFile() as f:
f.write("Hello, world.".encode("utf-8"))
with tarfile.open(file_name, "w") as tf, TemporaryFile() as f:
f.write("Hello, world.".encode("utf-8"))
ti = tarfile.TarInfo("hi.txt")
ti.size = f.tell()
ti = tarfile.TarInfo("hi.txt")
ti.size = f.tell()
f.seek(0)
tf.addfile(ti, f)
f.seek(0)
tf.addfile(ti, f)