diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 492e22215e..16aaf809d0 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,7 +3,7 @@ default_language_version: repos: - repo: https://github.com/PyCQA/autoflake - rev: "v2.3.1" + rev: "v2.3.3" hooks: - id: autoflake args: @@ -13,7 +13,7 @@ repos: stages: [pre-commit] - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.15.1 + rev: v0.15.4 hooks: - id: ruff stages: [pre-commit] diff --git a/conftest.py b/conftest.py index ffe4d0ac45..c2dc9dfd3a 100644 --- a/conftest.py +++ b/conftest.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Pytest conftest file for CNV tests """ @@ -684,10 +683,9 @@ def pytest_runtest_makereport(item, call): elif report.failed: if reprcrash := getattr(report.longrepr, "reprcrash", None): - if message := getattr(report.longrepr, "message", None): - setattr(report, SETUP_ERROR, message) - - elif message := getattr(reprcrash, "message", None): + if (message := getattr(report.longrepr, "message", None)) or ( + message := getattr(reprcrash, "message", None) + ): setattr(report, SETUP_ERROR, message) @@ -880,7 +878,7 @@ def is_skip_must_gather(node: Node) -> bool: def get_inspect_command_namespace_string(node: Node, test_name: str) -> str: namespace_str = "" - components = [key for key in NAMESPACE_COLLECTION.keys() if f"tests/{key}/" in test_name] + components = [key for key in NAMESPACE_COLLECTION if f"tests/{key}/" in test_name] if not components: LOGGER.warning(f"{test_name} does not require special data collection on failure") else: diff --git a/libs/net/netattachdef.py b/libs/net/netattachdef.py index 0ab140d1ab..9c0d3e9a9a 100644 --- a/libs/net/netattachdef.py +++ b/libs/net/netattachdef.py @@ -35,7 +35,7 @@ class IpamStatic(Ipam): """ type: str = field(default="static", init=False) - addresses: list["IpamStatic.Address"] + addresses: list[IpamStatic.Address] routes: list[IpamRoute] | None = None @dataclass @@ -61,7 +61,7 @@ class CNIPluginBridgeConfig(CNIPluginConfig): mtu: int | None = None vlan: int | None = None macspoofchk: bool | None = None - disableContainerInterface: bool | None = None # noqa: N815 + disableContainerInterface: bool | None = None @dataclass @@ -76,8 +76,8 @@ class CNIPluginOvnK8sConfig(CNIPluginConfig): type: str = field(default="ovn-k8s-cni-overlay", init=False) topology: str - netAttachDefName: str # noqa: N815 - vlanID: int | None = None # noqa: N815 + netAttachDefName: str + vlanID: int | None = None class Topology(Enum): LOCALNET = "localnet" @@ -105,7 +105,7 @@ class NetConfig: name: str plugins: list[CNIPluginConfig] - cniVersion: str = _DEFAULT_CNI_VERSION # noqa: N815 + cniVersion: str = _DEFAULT_CNI_VERSION class NetworkAttachmentDefinition(NamespacedResource): diff --git a/libs/net/traffic_generator.py b/libs/net/traffic_generator.py index 475fe9023d..78934bcfa2 100644 --- a/libs/net/traffic_generator.py +++ b/libs/net/traffic_generator.py @@ -1,7 +1,8 @@ import contextlib import logging from abc import ABC, abstractmethod -from typing import Final, Generator +from collections.abc import Generator +from typing import Final from ocp_resources.pod import Pod from ocp_utilities.exceptions import CommandExecFailed @@ -27,7 +28,7 @@ def __init__(self, server_ip: str, server_port: int): self._cmd = f"{_IPERF_BIN} --client {self._server_ip} --time 0 --port {self.server_port} --connect-timeout 300" @abstractmethod - def __enter__(self) -> "BaseTcpClient": + def __enter__(self) -> BaseTcpClient: pass @abstractmethod @@ -58,7 +59,7 @@ def __init__( self._port = port self._cmd = f"{_IPERF_BIN} --server --port {self._port} --one-off" - def __enter__(self) -> "TcpServer": + def __enter__(self) -> TcpServer: self._vm.console( commands=[f"{self._cmd} &"], timeout=_DEFAULT_CMD_TIMEOUT_SEC, @@ -105,7 +106,7 @@ def __init__( self._vm = vm self._cmd += f" --set-mss {maximum_segment_size}" if maximum_segment_size else "" - def __enter__(self) -> "VMTcpClient": + def __enter__(self) -> VMTcpClient: self._vm.console( commands=[f"{self._cmd} &"], timeout=_DEFAULT_CMD_TIMEOUT_SEC, @@ -166,7 +167,7 @@ def __init__(self, pod: Pod, server_ip: str, server_port: int, bind_interface: s self._container = _IPERF_BIN self._cmd += f" --bind {bind_interface}" if bind_interface else "" - def __enter__(self) -> "PodTcpClient": + def __enter__(self) -> PodTcpClient: # run the command in the background using nohup to ensure it keeps running after the exec session ends self._pod.execute( command=["sh", "-c", f"nohup {self._cmd} >/tmp/{_IPERF_BIN}.log 2>&1 &"], container=self._container @@ -199,7 +200,7 @@ def client_server_active_connection( port: int = IPERF_SERVER_PORT, maximum_segment_size: int = 0, ip_family: int = 4, -) -> Generator[tuple[VMTcpClient, TcpServer], None, None]: +) -> Generator[tuple[VMTcpClient, TcpServer]]: """Start iperf3 client-server connection with continuous TCP traffic flow. Automatically starts an iperf3 server and client, with traffic flowing continuously @@ -221,11 +222,13 @@ def client_server_active_connection( Note: Traffic runs with infinite duration until context exits. """ - with TcpServer(vm=server_vm, port=port) as server: - with VMTcpClient( + with ( + TcpServer(vm=server_vm, port=port) as server, + VMTcpClient( vm=client_vm, server_ip=str(lookup_iface_status_ip(vm=server_vm, iface_name=spec_logical_network, ip_family=ip_family)), server_port=port, maximum_segment_size=maximum_segment_size, - ) as client: - yield client, server + ) as client, + ): + yield client, server diff --git a/libs/storage/config.py b/libs/storage/config.py index 8224229180..48dbdbd461 100644 --- a/libs/storage/config.py +++ b/libs/storage/config.py @@ -26,7 +26,7 @@ def __init__(self, name: str): self.name = name self.storage_config = self.get_storage_config() - def supported_storage_classes(self) -> list["StorageClass"]: + def supported_storage_classes(self) -> list[StorageClass]: return [ StorageClass( name=StorageClassNames.CEPH_RBD_VIRTUALIZATION, diff --git a/libs/vm/spec.py b/libs/vm/spec.py index 2377dcbcf6..2d27558e0d 100644 --- a/libs/vm/spec.py +++ b/libs/vm/spec.py @@ -9,7 +9,7 @@ @dataclass class VMSpec: template: Template - runStrategy: str = VirtualMachine.RunStrategy.HALTED # noqa: N815 + runStrategy: str = VirtualMachine.RunStrategy.HALTED @dataclass @@ -29,7 +29,7 @@ class VMISpec: domain: Domain networks: list[Network] | None = None volumes: list[Volume] | None = None - terminationGracePeriodSeconds: int | None = None # noqa: N815 + terminationGracePeriodSeconds: int | None = None affinity: Affinity | None = None @@ -92,30 +92,30 @@ class Network: @dataclass class Multus: - networkName: str # noqa: N815 + networkName: str @dataclass class Affinity: - podAntiAffinity: PodAntiAffinity # noqa: N815 + podAntiAffinity: PodAntiAffinity @dataclass class PodAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: list[PodAffinityTerm] # noqa: N815 + requiredDuringSchedulingIgnoredDuringExecution: list[PodAffinityTerm] @dataclass class PodAffinityTerm: - labelSelector: LabelSelector # noqa: N815 - topologyKey: str # noqa: N815 - namespaceSelector: dict[str, Any] | None = None # noqa: N815 + labelSelector: LabelSelector + topologyKey: str + namespaceSelector: dict[str, Any] | None = None namespaces: list[str] | None = None @dataclass class LabelSelector: - matchExpressions: list[LabelSelectorRequirement] # noqa: N815 + matchExpressions: list[LabelSelectorRequirement] @dataclass @@ -128,8 +128,8 @@ class LabelSelectorRequirement: @dataclass class Volume: name: str - containerDisk: ContainerDisk | None = None # noqa: N815 - cloudInitNoCloud: CloudInitNoCloud | None = None # noqa: N815 + containerDisk: ContainerDisk | None = None + cloudInitNoCloud: CloudInitNoCloud | None = None @dataclass @@ -139,5 +139,5 @@ class ContainerDisk: @dataclass class CloudInitNoCloud: - networkData: str # noqa: N815 - userData: str | None = None # noqa: N815 + networkData: str + userData: str | None = None diff --git a/scripts/tests_analyzer/pytest_marker_analyzer.py b/scripts/tests_analyzer/pytest_marker_analyzer.py index 6624696c47..c15465fd9f 100644 --- a/scripts/tests_analyzer/pytest_marker_analyzer.py +++ b/scripts/tests_analyzer/pytest_marker_analyzer.py @@ -2,7 +2,6 @@ # Generated using Claude cli -# flake8: noqa: N802 """ Pytest Marker Analyzer @@ -772,10 +771,9 @@ def _process_test_file_for_markers( if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): if node.name.startswith("test_"): for decorator in node.decorator_list: - if is_marker(decorator=decorator, marker_names=marker_names): - tests.append(node.name) - break - elif check_parametrize_marks(decorator=decorator, marker_names=marker_names): + if is_marker(decorator=decorator, marker_names=marker_names) or check_parametrize_marks( + decorator=decorator, marker_names=marker_names + ): tests.append(node.name) break elif isinstance(node, ast.ClassDef): @@ -794,10 +792,9 @@ def _process_test_file_for_markers( if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)): if item.name.startswith("test_"): for decorator in item.decorator_list: - if is_marker(decorator=decorator, marker_names=marker_names): - tests.append(f"{node.name}::{item.name}") - break - elif check_parametrize_marks(decorator=decorator, marker_names=marker_names): + if is_marker( + decorator=decorator, marker_names=marker_names + ) or check_parametrize_marks(decorator=decorator, marker_names=marker_names): tests.append(f"{node.name}::{item.name}") break @@ -1568,11 +1565,9 @@ def _extract_marked_tests_from_file(self, file_path: Path) -> list[str]: # Module-level function with marker if node.name.startswith("test_"): for decorator in node.decorator_list: - if is_marker(decorator=decorator, marker_names=self.marker_names): - tests.append(node.name) - break - # Also check for markers in parametrize pytest.param(..., marks=...) - elif check_parametrize_marks(decorator=decorator, marker_names=self.marker_names): + if is_marker( + decorator=decorator, marker_names=self.marker_names + ) or check_parametrize_marks(decorator=decorator, marker_names=self.marker_names): tests.append(node.name) break @@ -1597,11 +1592,9 @@ def _extract_marked_tests_from_file(self, file_path: Path) -> list[str]: if item.name.startswith("test_"): # Check method-level markers for decorator in item.decorator_list: - if is_marker(decorator=decorator, marker_names=self.marker_names): - tests.append(f"{node.name}::{item.name}") - break - # Also check parametrize marks - elif check_parametrize_marks( + if is_marker( + decorator=decorator, marker_names=self.marker_names + ) or check_parametrize_marks( decorator=decorator, marker_names=self.marker_names ): tests.append(f"{node.name}::{item.name}") diff --git a/tests/chaos/oadp/conftest.py b/tests/chaos/oadp/conftest.py index 8f5520560a..33f1a4bb61 100644 --- a/tests/chaos/oadp/conftest.py +++ b/tests/chaos/oadp/conftest.py @@ -76,7 +76,6 @@ def rebooted_vm_source_node(rhel_vm_with_dv_running, oadp_backup_in_progress, wo LOGGER.info(f"Waiting for node {vm_node.name} to come back online") wait_for_node_status(node=vm_node, status=True, wait_timeout=TIMEOUT_10MIN) - return @pytest.fixture() diff --git a/tests/conftest.py b/tests/conftest.py index 0c3b1e23fc..a81bbd1c7c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -14,7 +14,7 @@ import tempfile from bisect import bisect_left from collections import defaultdict -from datetime import datetime, timezone +from datetime import UTC, datetime from signal import SIGINT, SIGTERM, getsignal, signal from subprocess import check_output @@ -265,7 +265,7 @@ def session_start_time() -> datetime: Returns: datetime: UTC timestamp when test session began (timezone-naive) """ - return datetime.now(timezone.utc).replace(tzinfo=None) + return datetime.now(UTC).replace(tzinfo=None) @pytest.fixture(scope="session") @@ -2258,16 +2258,16 @@ def rhel_vm_with_instance_type_and_preference( with ( instance_type_for_test_scope_class as vm_instance_type, vm_preference_for_test as vm_preference, - ): - with VirtualMachineForTests( + VirtualMachineForTests( client=unprivileged_client, name="rhel-vm-with-instance-type", namespace=namespace.name, image=Images.Rhel.RHEL9_REGISTRY_GUEST_IMG, vm_instance_type=vm_instance_type, vm_preference=vm_preference, - ) as vm: - yield vm + ) as vm, + ): + yield vm @pytest.fixture(scope="session") diff --git a/tests/global_config_amd64.py b/tests/global_config_amd64.py index 544240304b..ebf4a7b3e4 100644 --- a/tests/global_config_amd64.py +++ b/tests/global_config_amd64.py @@ -31,4 +31,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/global_config_arm64.py b/tests/global_config_arm64.py index f77fde2ea3..f7d12ca9a2 100644 --- a/tests/global_config_arm64.py +++ b/tests/global_config_arm64.py @@ -63,4 +63,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/global_config_aro.py b/tests/global_config_aro.py index ec65dd4b67..ec2c87535c 100644 --- a/tests/global_config_aro.py +++ b/tests/global_config_aro.py @@ -34,4 +34,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/global_config_aws.py b/tests/global_config_aws.py index 687338cbc3..f3f309e5c7 100644 --- a/tests/global_config_aws.py +++ b/tests/global_config_aws.py @@ -63,4 +63,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/global_config_ibm_spectrum_sc.py b/tests/global_config_ibm_spectrum_sc.py index ef64d15aca..fa594c6308 100644 --- a/tests/global_config_ibm_spectrum_sc.py +++ b/tests/global_config_ibm_spectrum_sc.py @@ -33,4 +33,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/global_config_interop.py b/tests/global_config_interop.py index d90584e776..e11202d747 100644 --- a/tests/global_config_interop.py +++ b/tests/global_config_interop.py @@ -16,4 +16,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/global_config_interop_sno.py b/tests/global_config_interop_sno.py index fdc7883358..50334941b3 100644 --- a/tests/global_config_interop_sno.py +++ b/tests/global_config_interop_sno.py @@ -28,4 +28,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/global_config_lvms.py b/tests/global_config_lvms.py index 876bfe1fc3..78393ea31c 100644 --- a/tests/global_config_lvms.py +++ b/tests/global_config_lvms.py @@ -38,4 +38,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/global_config_nfs.py b/tests/global_config_nfs.py index 84374c0106..84bf5ee671 100644 --- a/tests/global_config_nfs.py +++ b/tests/global_config_nfs.py @@ -34,4 +34,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/global_config_oci.py b/tests/global_config_oci.py index 8964e02ccd..30b2486141 100644 --- a/tests/global_config_oci.py +++ b/tests/global_config_oci.py @@ -44,4 +44,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/global_config_rh_it.py b/tests/global_config_rh_it.py index 7cdaeab0b9..987341c69e 100644 --- a/tests/global_config_rh_it.py +++ b/tests/global_config_rh_it.py @@ -36,4 +36,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/global_config_s390x.py b/tests/global_config_s390x.py index 883d27f9da..6322b59b3c 100644 --- a/tests/global_config_s390x.py +++ b/tests/global_config_s390x.py @@ -34,4 +34,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/global_config_sno.py b/tests/global_config_sno.py index 3549ba01b8..d0c9677efd 100644 --- a/tests/global_config_sno.py +++ b/tests/global_config_sno.py @@ -36,4 +36,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/global_config_sno_hpp.py b/tests/global_config_sno_hpp.py index bee6a1fb08..27c136f274 100644 --- a/tests/global_config_sno_hpp.py +++ b/tests/global_config_sno_hpp.py @@ -30,4 +30,4 @@ if _dir in ["encoding", "py_file"]: continue - config[_dir] = locals()[_dir] # noqa: F821 + config[_dir] = locals()[_dir] diff --git a/tests/infrastructure/golden_images/test_golden_image_restricted_ns.py b/tests/infrastructure/golden_images/test_golden_image_restricted_ns.py index da87c74525..12043ee45a 100644 --- a/tests/infrastructure/golden_images/test_golden_image_restricted_ns.py +++ b/tests/infrastructure/golden_images/test_golden_image_restricted_ns.py @@ -8,17 +8,19 @@ def check_pod_creation_failed(pod_name, client, namespace): - with pytest.raises( - ApiException, - match=ErrorMsg.CANNOT_CREATE_RESOURCE, - ): - with Pod( + with ( + pytest.raises( + ApiException, + match=ErrorMsg.CANNOT_CREATE_RESOURCE, + ), + Pod( name=pod_name, namespace=namespace.name, client=client, containers=[{"name": "dummy", "image": "kubevirt/cdi-importer:latest"}], - ): - return + ), + ): + return @pytest.mark.polarion("CNV-4900") diff --git a/tests/infrastructure/golden_images/update_boot_source/utils.py b/tests/infrastructure/golden_images/update_boot_source/utils.py index 2bbb4320ee..fd0660cc7f 100644 --- a/tests/infrastructure/golden_images/update_boot_source/utils.py +++ b/tests/infrastructure/golden_images/update_boot_source/utils.py @@ -87,7 +87,7 @@ def get_all_dic_volume_names(client: DynamicClient, namespace: str) -> list[str] list[str]: Combined list of PVC and VolumeSnapshot names managed by DataImportCron. """ - def _fetch_volume_names(resource_cls: type[PersistentVolumeClaim] | type[VolumeSnapshot]) -> list[str]: + def _fetch_volume_names(resource_cls: type[PersistentVolumeClaim | VolumeSnapshot]) -> list[str]: return [ volume.name for volume in resource_cls.get( diff --git a/tests/infrastructure/instance_types/test_vm_with_instance_and_pref.py b/tests/infrastructure/instance_types/test_vm_with_instance_and_pref.py index 0ee408e690..98a3426502 100644 --- a/tests/infrastructure/instance_types/test_vm_with_instance_and_pref.py +++ b/tests/infrastructure/instance_types/test_vm_with_instance_and_pref.py @@ -93,21 +93,24 @@ class TestNegativeVmWithInstanceTypeAndPref: def test_vm_start_fails_with_insufficient_cpu_for_spread_option( self, unprivileged_client, namespace, instance_type_for_test_scope_class, vm_preference_for_test ): - with pytest.raises( - UnprocessibleEntityError, - match=r".*vCPUs provided by the instance type are not divisible by the " - r"Spec.PreferSpreadSocketToCoreRatio or Spec.CPU.PreferSpreadOptions.Ratio*", + with ( + pytest.raises( + UnprocessibleEntityError, + match=r".*vCPUs provided by the instance type are not divisible by the " + r"Spec.PreferSpreadSocketToCoreRatio or Spec.CPU.PreferSpreadOptions.Ratio*", + ), + instance_type_for_test_scope_class as vm_instance_type, + vm_preference_for_test as vm_preference, ): - with instance_type_for_test_scope_class as vm_instance_type, vm_preference_for_test as vm_preference: - with VirtualMachineForTests( - client=unprivileged_client, - name="rhel-vm-with-instance-type", - namespace=namespace.name, - image=Images.Rhel.RHEL9_REGISTRY_GUEST_IMG, - vm_instance_type=vm_instance_type, - vm_preference=vm_preference, - ): - pytest.fail("Expected Failure due to UnprocessibleEntityError") + with VirtualMachineForTests( + client=unprivileged_client, + name="rhel-vm-with-instance-type", + namespace=namespace.name, + image=Images.Rhel.RHEL9_REGISTRY_GUEST_IMG, + vm_instance_type=vm_instance_type, + vm_preference=vm_preference, + ): + pytest.fail("Expected Failure due to UnprocessibleEntityError") @pytest.mark.parametrize( diff --git a/tests/infrastructure/vhostmd/test_downwardmetrics_virtio.py b/tests/infrastructure/vhostmd/test_downwardmetrics_virtio.py index 2a76f587a8..d106299ef8 100644 --- a/tests/infrastructure/vhostmd/test_downwardmetrics_virtio.py +++ b/tests/infrastructure/vhostmd/test_downwardmetrics_virtio.py @@ -167,12 +167,14 @@ def vm_ready_for_tests(vm_parameters_for_virtio_downward_metrics): def test_downward_metrics_virtio_serial_port_default( vm_parameters_for_virtio_downward_metrics, ): - with pytest.raises( - UnprocessibleEntityError, - match=r".*DownwardMetrics feature gate is not enabled*", + with ( + pytest.raises( + UnprocessibleEntityError, + match=r".*DownwardMetrics feature gate is not enabled*", + ), + VirtualMachineWithDownwardMetrics(**vm_parameters_for_virtio_downward_metrics), ): - with VirtualMachineWithDownwardMetrics(**vm_parameters_for_virtio_downward_metrics): - pytest.fail("Expected Failure due to UnprocessibleEntityError") + pytest.fail("Expected Failure due to UnprocessibleEntityError") @pytest.mark.polarion("CNV-10808") diff --git a/tests/infrastructure/vm_console_proxy/utils.py b/tests/infrastructure/vm_console_proxy/utils.py index 2313edb417..f323540742 100644 --- a/tests/infrastructure/vm_console_proxy/utils.py +++ b/tests/infrastructure/vm_console_proxy/utils.py @@ -1,7 +1,7 @@ from __future__ import annotations import logging -from typing import Any, Type +from typing import Any import requests from kubernetes.dynamic import DynamicClient @@ -60,7 +60,7 @@ def create_vnc_console_token( raise -def get_vm_console_proxy_resource(resource_kind: Type, client: DynamicClient, namespace: str | None = None) -> Type: +def get_vm_console_proxy_resource(resource_kind: type, client: DynamicClient, namespace: str | None = None) -> type: if namespace: vm_console_proxy_resource_object = resource_kind( name=VM_CONSOLE_PROXY, diff --git a/tests/infrastructure/workload_availability/remediation_fencing_mhc/test_ha_vm.py b/tests/infrastructure/workload_availability/remediation_fencing_mhc/test_ha_vm.py index 75d56d8dbc..7e1b62825c 100644 --- a/tests/infrastructure/workload_availability/remediation_fencing_mhc/test_ha_vm.py +++ b/tests/infrastructure/workload_availability/remediation_fencing_mhc/test_ha_vm.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ HA VM reboot and provisioning scenario tests. """ diff --git a/tests/install_upgrade_operators/crypto_policy/test_hco_custom_profile_negative.py b/tests/install_upgrade_operators/crypto_policy/test_hco_custom_profile_negative.py index f6f3925a6f..a20055f2a9 100644 --- a/tests/install_upgrade_operators/crypto_policy/test_hco_custom_profile_negative.py +++ b/tests/install_upgrade_operators/crypto_policy/test_hco_custom_profile_negative.py @@ -30,15 +30,17 @@ def test_set_hco_crypto_failed_without_required_cipher( "ECDHE-RSA-AES256-GCM-SHA384", ] tls_spec = {"spec": {TLS_SECURITY_PROFILE: tls_custom_profile}} - with pytest.raises(ForbiddenError, match=r"missing an HTTP/2-required"): - with ResourceEditorValidateHCOReconcile( + with ( + pytest.raises(ForbiddenError, match=r"missing an HTTP/2-required"), + ResourceEditorValidateHCOReconcile( patches={hyperconverged_resource_scope_function: tls_spec}, list_resource_reconcile=MANAGED_CRS_LIST, wait_for_reconcile_post_update=True, - ): - LOGGER.error( - f"Setting HCO TLS profile without required http/2 ciphers using the spec - {tls_spec} was successful" - ) + ), + ): + LOGGER.error( + f"Setting HCO TLS profile without required http/2 ciphers using the spec - {tls_spec} was successful" + ) @pytest.mark.polarion("CNV-10551") @@ -46,11 +48,13 @@ def test_set_ciphers_for_tlsv13(hyperconverged_resource_scope_function): error_string = r"custom ciphers cannot be selected when minTLSVersion is VersionTLS13" tls_custom_profile = copy.deepcopy(TLS_CUSTOM_PROFILE) tls_custom_profile[TLS_CUSTOM_POLICY]["minTLSVersion"] = "VersionTLS13" - with pytest.raises(ForbiddenError, match=error_string): - with ResourceEditorValidateHCOReconcile( + with ( + pytest.raises(ForbiddenError, match=error_string), + ResourceEditorValidateHCOReconcile( patches={hyperconverged_resource_scope_function: {"spec": {TLS_SECURITY_PROFILE: tls_custom_profile}}} - ): - LOGGER.error( - "Setting HCO with custom tlsSecurityProfile with TLS Version 1.3 " - "and custom ciphers was successful against expected failure" - ) + ), + ): + LOGGER.error( + "Setting HCO with custom tlsSecurityProfile with TLS Version 1.3 " + "and custom ciphers was successful against expected failure" + ) diff --git a/tests/install_upgrade_operators/crypto_policy/test_hco_override_api_server_crypto_policy.py b/tests/install_upgrade_operators/crypto_policy/test_hco_override_api_server_crypto_policy.py index 0dd6aa90d0..01eb225513 100644 --- a/tests/install_upgrade_operators/crypto_policy/test_hco_override_api_server_crypto_policy.py +++ b/tests/install_upgrade_operators/crypto_policy/test_hco_override_api_server_crypto_policy.py @@ -72,7 +72,7 @@ def test_hco_overriding_apiserver_crypto_policy( conflicting_resources = { resource.kind: crypto_policy for resource, crypto_policy in sample.items() - if expected_all_managed_crs_crypto_policies[resource] != sample[resource] + if expected_all_managed_crs_crypto_policies[resource] != crypto_policy } assert not conflicting_resources, ( "API server crypto policy overrides HCO crypto policy\n" diff --git a/tests/install_upgrade_operators/crypto_policy/test_hco_without_required_cipher.py b/tests/install_upgrade_operators/crypto_policy/test_hco_without_required_cipher.py index b5fc6fbab5..d9fdb7fbe7 100644 --- a/tests/install_upgrade_operators/crypto_policy/test_hco_without_required_cipher.py +++ b/tests/install_upgrade_operators/crypto_policy/test_hco_without_required_cipher.py @@ -30,12 +30,14 @@ def test_set_hco_crypto_failed_without_required_cipher( "ECDHE-RSA-AES256-GCM-SHA384", ] tls_spec = {"spec": {TLS_SECURITY_PROFILE: tls_custom_profile}} - with pytest.raises(ForbiddenError, match=r"missing an HTTP/2-required"): - with ResourceEditorValidateHCOReconcile( + with ( + pytest.raises(ForbiddenError, match=r"missing an HTTP/2-required"), + ResourceEditorValidateHCOReconcile( patches={hyperconverged_resource_scope_function: tls_spec}, list_resource_reconcile=MANAGED_CRS_LIST, wait_for_reconcile_post_update=True, - ): - LOGGER.error( - f"Setting HCO TLS profile without required http/2 ciphers using the spec - {tls_spec} was successful" - ) + ), + ): + LOGGER.error( + f"Setting HCO TLS profile without required http/2 ciphers using the spec - {tls_spec} was successful" + ) diff --git a/tests/install_upgrade_operators/crypto_policy/test_update_specific_component_crypto_policy.py b/tests/install_upgrade_operators/crypto_policy/test_update_specific_component_crypto_policy.py index e62ef9bb56..51d2dd7628 100644 --- a/tests/install_upgrade_operators/crypto_policy/test_update_specific_component_crypto_policy.py +++ b/tests/install_upgrade_operators/crypto_policy/test_update_specific_component_crypto_policy.py @@ -91,7 +91,7 @@ def updated_cr_with_custom_crypto_policy( hco_namespace=hco_namespace, expected_conditions={ **DEFAULT_HCO_CONDITIONS, - **{"TaintedConfiguration": Resource.Condition.Status.TRUE}, + "TaintedConfiguration": Resource.Condition.Status.TRUE, }, ) yield {"resource": resource, "tls_policy": value} diff --git a/tests/install_upgrade_operators/csv/csv_permissions_audit/test_csv_permissions_audit.py b/tests/install_upgrade_operators/csv/csv_permissions_audit/test_csv_permissions_audit.py index 0804d1ba74..10ef6f7013 100644 --- a/tests/install_upgrade_operators/csv/csv_permissions_audit/test_csv_permissions_audit.py +++ b/tests/install_upgrade_operators/csv/csv_permissions_audit/test_csv_permissions_audit.py @@ -129,7 +129,7 @@ def test_global_csv_permissions(cnv_operators_matrix__function__, global_permiss errors[key] = error_list if errors: LOGGER.error(yaml.dump(errors)) - if cnv_operators_matrix__function__ in JIRA_LINKS.keys() and is_jira_open( + if cnv_operators_matrix__function__ in JIRA_LINKS and is_jira_open( jira_id=JIRA_LINKS[cnv_operators_matrix__function__] ): pytest.xfail(error_message) diff --git a/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_cdi.py b/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_cdi.py index 1b6cd64882..9155dc5165 100644 --- a/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_cdi.py +++ b/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_cdi.py @@ -57,7 +57,7 @@ def test_cdi_json_patch( admin_client=admin_client, hco_namespace=hco_namespace, expected_conditions={ - **{"TaintedConfiguration": Resource.Condition.Status.TRUE}, + "TaintedConfiguration": Resource.Condition.Status.TRUE, }, ) validate_cdi_json_patch( diff --git a/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_cnao.py b/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_cnao.py index acc9c444f3..a0e7937d66 100644 --- a/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_cnao.py +++ b/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_cnao.py @@ -61,7 +61,7 @@ def test_cnao_json_patch( admin_client=admin_client, hco_namespace=hco_namespace, expected_conditions={ - **{"TaintedConfiguration": Resource.Condition.Status.TRUE}, + "TaintedConfiguration": Resource.Condition.Status.TRUE, }, ) cnao_spec = cnao_resource.instance.spec diff --git a/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_kubevirt.py b/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_kubevirt.py index 1d7c550d42..be0c7b441c 100644 --- a/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_kubevirt.py +++ b/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_kubevirt.py @@ -54,7 +54,7 @@ def test_kubevirt_json_patch( admin_client=admin_client, hco_namespace=hco_namespace, expected_conditions={ - **{"TaintedConfiguration": Resource.Condition.Status.TRUE}, + "TaintedConfiguration": Resource.Condition.Status.TRUE, }, ) validate_kubevirt_json_patch(kubevirt_resource=kubevirt_resource) diff --git a/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_multiple_updates.py b/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_multiple_updates.py index 240c4bc1e7..f043763525 100644 --- a/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_multiple_updates.py +++ b/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_multiple_updates.py @@ -91,7 +91,7 @@ def test_multiple_json_patch( admin_client=admin_client, hco_namespace=hco_namespace, expected_conditions={ - **{"TaintedConfiguration": Resource.Condition.Status.TRUE}, + "TaintedConfiguration": Resource.Condition.Status.TRUE, }, ) validate_cdi_json_patch( @@ -121,6 +121,6 @@ def test_multiple_json_patch_metrics(self, prometheus, kubevirt_all_unsafe_modif @pytest.mark.polarion("CNV-8813") def test_multiple_json_patch_alert(self, prometheus): - for component in COMPONENT_DICT.keys(): + for component in COMPONENT_DICT: LOGGER.info(f"Waiting for alert: {ALERT_NAME} for component: {component}") wait_for_alert(prometheus=prometheus, alert_name=ALERT_NAME, component_name=component) diff --git a/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_ssp.py b/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_ssp.py index b8f58b395e..6464261837 100644 --- a/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_ssp.py +++ b/tests/install_upgrade_operators/json_patch/test_json_patch_annotation_ssp.py @@ -57,7 +57,7 @@ def test_ssp_json_patch( admin_client=admin_client, hco_namespace=hco_namespace, expected_conditions={ - **{"TaintedConfiguration": Resource.Condition.Status.TRUE}, + "TaintedConfiguration": Resource.Condition.Status.TRUE, }, ) ssp_replicas_current_value = ssp_resource_scope_function.instance.spec.templateValidator.replicas diff --git a/tests/install_upgrade_operators/must_gather/test_must_gather.py b/tests/install_upgrade_operators/must_gather/test_must_gather.py index 031e158617..bfab98504e 100644 --- a/tests/install_upgrade_operators/must_gather/test_must_gather.py +++ b/tests/install_upgrade_operators/must_gather/test_must_gather.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import logging import os import re diff --git a/tests/install_upgrade_operators/must_gather/utils.py b/tests/install_upgrade_operators/must_gather/utils.py index 76d47ca202..d4c7f5471a 100644 --- a/tests/install_upgrade_operators/must_gather/utils.py +++ b/tests/install_upgrade_operators/must_gather/utils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import difflib import glob import logging @@ -54,7 +53,7 @@ # To be removed after the issue is fixed in openshift -class ResourceFieldEqBugWorkaround(object): +class ResourceFieldEqBugWorkaround: def __enter__(self): self.prev_eq_func = ResourceField.__eq__ @@ -384,7 +383,7 @@ def validate_must_gather_vm_file_collection( nftables_ruleset_from_utility_pods=nftables_ruleset_from_utility_pods, ) assert all(entry in str(exeption_found.value) for entry in not_collected_vm_names + ["path_not_found"]), ( - f"Failed to find {not_collected_vm_names} in exception message: {str(exeption_found.value)}" + f"Failed to find {not_collected_vm_names} in exception message: {exeption_found.value!s}" ) diff --git a/tests/install_upgrade_operators/security/scc/test_cnv_deployment_required_scc.py b/tests/install_upgrade_operators/security/scc/test_cnv_deployment_required_scc.py index 1bac08a1df..4c5304bc90 100644 --- a/tests/install_upgrade_operators/security/scc/test_cnv_deployment_required_scc.py +++ b/tests/install_upgrade_operators/security/scc/test_cnv_deployment_required_scc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Test to verify all HCO deployments have 'openshift.io/required-scc' annotation. """ diff --git a/tests/install_upgrade_operators/security/scc/test_cnv_pods_scc.py b/tests/install_upgrade_operators/security/scc/test_cnv_pods_scc.py index 995e833a2c..1091cec66e 100644 --- a/tests/install_upgrade_operators/security/scc/test_cnv_pods_scc.py +++ b/tests/install_upgrade_operators/security/scc/test_cnv_pods_scc.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Tests to check, HCO Namespace Pod's, Security Context Constraint """ diff --git a/tests/install_upgrade_operators/security/scc/test_default_scc.py b/tests/install_upgrade_operators/security/scc/test_default_scc.py index 17d5919f9a..b652ab33a5 100644 --- a/tests/install_upgrade_operators/security/scc/test_default_scc.py +++ b/tests/install_upgrade_operators/security/scc/test_default_scc.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Tests to check, the default Security Context Constraint """ diff --git a/tests/install_upgrade_operators/security/selinux/test_selinux_launcher_type.py b/tests/install_upgrade_operators/security/selinux/test_selinux_launcher_type.py index 6b7cf121d1..376bccc466 100644 --- a/tests/install_upgrade_operators/security/selinux/test_selinux_launcher_type.py +++ b/tests/install_upgrade_operators/security/selinux/test_selinux_launcher_type.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Test to check, SELinuxLauncher Type in kubevirt config map """ diff --git a/tests/network/conftest.py b/tests/network/conftest.py index 90cc85cb50..4353d1ab38 100644 --- a/tests/network/conftest.py +++ b/tests/network/conftest.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Pytest conftest file for CNV network tests """ diff --git a/tests/network/general/test_bridge_marker.py b/tests/network/general/test_bridge_marker.py index f4003de73b..54f0062657 100644 --- a/tests/network/general/test_bridge_marker.py +++ b/tests/network/general/test_bridge_marker.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - from contextlib import contextmanager import pytest @@ -51,21 +49,23 @@ def bridge_marker_bridge_network(admin_client, namespace): @pytest.fixture() def bridge_networks(admin_client, namespace): - with network_nad( - nad_type=LINUX_BRIDGE, - nad_name=BRIDGEMARKER2, - interface_name=BRIDGEMARKER2, - namespace=namespace, - client=admin_client, - ) as bridgemarker2_nad: - with network_nad( + with ( + network_nad( + nad_type=LINUX_BRIDGE, + nad_name=BRIDGEMARKER2, + interface_name=BRIDGEMARKER2, + namespace=namespace, + client=admin_client, + ) as bridgemarker2_nad, + network_nad( nad_type=LINUX_BRIDGE, nad_name=BRIDGEMARKER3, interface_name=BRIDGEMARKER3, namespace=namespace, client=admin_client, - ) as bridgemarker3_nad: - yield bridgemarker2_nad, bridgemarker3_nad + ) as bridgemarker3_nad, + ): + yield bridgemarker2_nad, bridgemarker3_nad @pytest.fixture() @@ -116,21 +116,23 @@ def bridge_device_on_all_nodes(nmstate_dependent_placeholder, admin_client): @pytest.fixture() def non_homogenous_bridges(nmstate_dependent_placeholder, admin_client, worker_node1, worker_node2): - with network_device( - interface_type=LINUX_BRIDGE, - nncp_name="bridge-marker2", - interface_name=BRIDGEMARKER2, - node_selector=get_node_selector_dict(node_selector=worker_node1.hostname), - client=admin_client, - ) as bridgemarker2_ncp: - with network_device( + with ( + network_device( + interface_type=LINUX_BRIDGE, + nncp_name="bridge-marker2", + interface_name=BRIDGEMARKER2, + node_selector=get_node_selector_dict(node_selector=worker_node1.hostname), + client=admin_client, + ) as bridgemarker2_ncp, + network_device( interface_type=LINUX_BRIDGE, nncp_name="bridge-marker3", interface_name=BRIDGEMARKER3, node_selector=get_node_selector_dict(node_selector=worker_node2.hostname), client=admin_client, - ) as bridgemarker3_ncp: - yield bridgemarker2_ncp, bridgemarker3_ncp + ) as bridgemarker3_ncp, + ): + yield bridgemarker2_ncp, bridgemarker3_ncp @pytest.mark.sno diff --git a/tests/network/general/test_network_naming.py b/tests/network/general/test_network_naming.py index 973aae29b4..90a57c5094 100644 --- a/tests/network/general/test_network_naming.py +++ b/tests/network/general/test_network_naming.py @@ -17,15 +17,17 @@ def invalid_network_names(): def test_vm_with_illegal_network_name(namespace, unprivileged_client, invalid_network_names): vm_name = "unsupported-network-name-vm" - with pytest.raises( - UnprocessibleEntityError, - match="r.*Network interface name can only contain alphabetical characters*", - ): - with VirtualMachineForTests( + with ( + pytest.raises( + UnprocessibleEntityError, + match="r.*Network interface name can only contain alphabetical characters*", + ), + VirtualMachineForTests( namespace=namespace.name, name=vm_name, body=fedora_vm_body(name=vm_name), client=unprivileged_client, **invalid_network_names, - ): - return + ), + ): + return diff --git a/tests/network/kubemacpool/explicit_range/conftest.py b/tests/network/kubemacpool/explicit_range/conftest.py index d9c1212fc1..c15bad6f34 100644 --- a/tests/network/kubemacpool/explicit_range/conftest.py +++ b/tests/network/kubemacpool/explicit_range/conftest.py @@ -1,4 +1,4 @@ -from typing import Generator +from collections.abc import Generator import pytest from kubernetes.dynamic import DynamicClient diff --git a/tests/network/libs/cluster_user_defined_network.py b/tests/network/libs/cluster_user_defined_network.py index 2f2f0d1186..e16de1e119 100644 --- a/tests/network/libs/cluster_user_defined_network.py +++ b/tests/network/libs/cluster_user_defined_network.py @@ -49,7 +49,7 @@ class Role(Enum): SECONDARY = "Secondary" role: str - physicalNetworkName: str # noqa: N815 + physicalNetworkName: str ipam: Ipam vlan: Vlan | None = None mtu: int | None = None diff --git a/tests/network/libs/label_selector.py b/tests/network/libs/label_selector.py index 4d07565813..16ab3c7349 100644 --- a/tests/network/libs/label_selector.py +++ b/tests/network/libs/label_selector.py @@ -3,4 +3,4 @@ @dataclass class LabelSelector: - matchLabels: dict[str, str] | None = None # noqa: N815 + matchLabels: dict[str, str] | None = None diff --git a/tests/network/localnet/conftest.py b/tests/network/localnet/conftest.py index bb47eee707..6a4bec7e54 100644 --- a/tests/network/localnet/conftest.py +++ b/tests/network/localnet/conftest.py @@ -466,7 +466,7 @@ def ovs_bridge_localnet_running_jumbo_frame_vms( def localnet_ovs_bridge_jumbo_frame_client_and_server_vms( ovs_bridge_localnet_running_jumbo_frame_vms: tuple[BaseVirtualMachine, BaseVirtualMachine], cluster_hardware_mtu: int, -) -> Generator[tuple[TcpClient, TcpServer], None, None]: +) -> Generator[tuple[TcpClient, TcpServer]]: with client_server_active_connection( client_vm=ovs_bridge_localnet_running_jumbo_frame_vms[1], server_vm=ovs_bridge_localnet_running_jumbo_frame_vms[0], diff --git a/tests/network/localnet/liblocalnet.py b/tests/network/localnet/liblocalnet.py index 2f9ec4f0cc..7c697f11d8 100644 --- a/tests/network/localnet/liblocalnet.py +++ b/tests/network/localnet/liblocalnet.py @@ -1,7 +1,7 @@ import contextlib import logging import uuid -from typing import Generator +from collections.abc import Generator from kubernetes.client import ApiException from kubernetes.dynamic import DynamicClient @@ -187,7 +187,7 @@ def create_nncp_localnet_on_secondary_node_nic( node_nic_name: str, client: DynamicClient, mtu: int | None = None, -) -> Generator[libnncp.NodeNetworkConfigurationPolicy, None, None]: +) -> Generator[libnncp.NodeNetworkConfigurationPolicy]: """Create NNCP to configure an OVS bridge on a secondary NIC across all worker nodes. Note: diff --git a/tests/network/migration/test_migration.py b/tests/network/migration/test_migration.py index 990f886820..f5eb3f3c41 100644 --- a/tests/network/migration/test_migration.py +++ b/tests/network/migration/test_migration.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Network Migration test """ diff --git a/tests/network/nmstate/conftest.py b/tests/network/nmstate/conftest.py index 7095674019..be492d8022 100644 --- a/tests/network/nmstate/conftest.py +++ b/tests/network/nmstate/conftest.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import logging import pytest diff --git a/tests/network/nmstate/test_connectivity_after_nmstate_changes.py b/tests/network/nmstate/test_connectivity_after_nmstate_changes.py index e1840a327d..31f59459c8 100644 --- a/tests/network/nmstate/test_connectivity_after_nmstate_changes.py +++ b/tests/network/nmstate/test_connectivity_after_nmstate_changes.py @@ -282,11 +282,9 @@ def test_nmstate_restart_and_check_connectivity( nmstate_ds=nmstate_ds, ) LOGGER.info( - ( - f"Check connectivity from {nmstate_linux_bridge_attached_running_vma.name} " - f"to {nmstate_linux_bridge_attached_running_vmb.name} " - f"IP {vmb_dst_ip}. NMstate restart number: {idx + 1}" - ) + f"Check connectivity from {nmstate_linux_bridge_attached_running_vma.name} " + f"to {nmstate_linux_bridge_attached_running_vmb.name} " + f"IP {vmb_dst_ip}. NMstate restart number: {idx + 1}" ) assert_ping_successful( diff --git a/tests/network/provider_migration/libprovider.py b/tests/network/provider_migration/libprovider.py index d8ed26d28e..b9dce4c562 100644 --- a/tests/network/provider_migration/libprovider.py +++ b/tests/network/provider_migration/libprovider.py @@ -89,5 +89,4 @@ def extract_vm_primary_network_data(vm: vim.VirtualMachine) -> tuple[str, str]: for net in getattr(vm.guest, "net", []): if net.macAddress == device.macAddress and net.ipAddress: return net.macAddress, net.ipAddress[0] - else: - raise IfaceNotFoundError("No network interface found in the VM or no IP address assigned.") + raise IfaceNotFoundError("No network interface found in the VM or no IP address assigned.") diff --git a/tests/network/user_defined_network/ip_specification/conftest.py b/tests/network/user_defined_network/ip_specification/conftest.py index 2da0b71442..e6f8dd1067 100644 --- a/tests/network/user_defined_network/ip_specification/conftest.py +++ b/tests/network/user_defined_network/ip_specification/conftest.py @@ -20,7 +20,7 @@ def vm_under_test( namespaced_layer2_user_defined_network: Layer2UserDefinedNetwork, udn_affinity_label: tuple[str, str], admin_client: DynamicClient, -) -> Generator[BaseVirtualMachine, None, None]: +) -> Generator[BaseVirtualMachine]: with udn_vm( namespace_name=udn_namespace.name, name="ip-spec-vm-under-test", @@ -37,7 +37,7 @@ def vm_for_connectivity_ref( namespaced_layer2_user_defined_network: Layer2UserDefinedNetwork, udn_affinity_label: tuple[str, str], admin_client: DynamicClient, -) -> Generator[BaseVirtualMachine, None, None]: +) -> Generator[BaseVirtualMachine]: with udn_vm( namespace_name=udn_namespace.name, name="vm-for-connectivity-ref", @@ -77,7 +77,7 @@ def ip_to_request( @pytest.fixture(scope="module") def client_server_tcp_connectivity_between_vms( vm_for_connectivity_ref: BaseVirtualMachine, vm_under_test: BaseVirtualMachine -) -> Generator[tuple[TcpClient, TcpServer], None, None]: +) -> Generator[tuple[TcpClient, TcpServer]]: with client_server_active_connection( client_vm=vm_for_connectivity_ref, server_vm=vm_under_test, diff --git a/tests/network/user_defined_network/test_user_defined_network_passt.py b/tests/network/user_defined_network/test_user_defined_network_passt.py index ee84de8518..78cbcf08d5 100644 --- a/tests/network/user_defined_network/test_user_defined_network_passt.py +++ b/tests/network/user_defined_network/test_user_defined_network_passt.py @@ -1,4 +1,4 @@ -from typing import Generator +from collections.abc import Generator import pytest from kubernetes.dynamic import DynamicClient @@ -31,7 +31,7 @@ def wait_for_ready_vm_with_restart(vm: BaseVirtualMachine) -> bool: @pytest.fixture(scope="module") def passt_enabled_in_hco( hyperconverged_resource_scope_module: HyperConverged, -) -> Generator[None, None, None]: +) -> Generator[None]: with ResourceEditorValidateHCOReconcile( patches={ hyperconverged_resource_scope_module: { @@ -51,7 +51,7 @@ def passt_running_vm_pair( udn_affinity_label: tuple[str, str], admin_client: DynamicClient, passt_enabled_in_hco, -) -> Generator[tuple[BaseVirtualMachine, BaseVirtualMachine], None, None]: +) -> Generator[tuple[BaseVirtualMachine, BaseVirtualMachine]]: with ( udn_vm( namespace_name=udn_namespace.name, diff --git a/tests/observability/metrics/test_migration_metrics.py b/tests/observability/metrics/test_migration_metrics.py index 50a460da4c..63ea7fb1d3 100644 --- a/tests/observability/metrics/test_migration_metrics.py +++ b/tests/observability/metrics/test_migration_metrics.py @@ -1,5 +1,5 @@ import logging -from datetime import datetime, timezone +from datetime import UTC, datetime import pytest @@ -55,7 +55,7 @@ def test_kubevirt_vmi_migration_metrics( query, ): minutes_passed_since_migration_start = ( - int(datetime.now(timezone.utc).timestamp()) + int(datetime.now(UTC).timestamp()) - timestamp_to_seconds( timestamp=vm_for_migration_metrics_test.vmi.instance.status.migrationState.startTimestamp ) @@ -63,7 +63,7 @@ def test_kubevirt_vmi_migration_metrics( wait_for_non_empty_metrics_value( prometheus=prometheus, metric_name=f"last_over_time({query.format(vm_name=vm_for_migration_metrics_test.name)}" - f"[{minutes_passed_since_migration_start if minutes_passed_since_migration_start > 10 else 10}m])", + f"[{max(10, minutes_passed_since_migration_start)}m])", ) diff --git a/tests/observability/metrics/test_ssp_metrics.py b/tests/observability/metrics/test_ssp_metrics.py index b770a83206..763e6aaac9 100644 --- a/tests/observability/metrics/test_ssp_metrics.py +++ b/tests/observability/metrics/test_ssp_metrics.py @@ -41,8 +41,9 @@ def created_multiple_failed_vms( """ with instance_type_for_test_scope_class as vm_instance_type: for _ in range(request.param["vm_count"]): - with pytest.raises(UnprocessibleEntityError): - with VirtualMachineForTests( + with ( + pytest.raises(UnprocessibleEntityError), + VirtualMachineForTests( name="non-creatable-vm", namespace=namespace.name, client=unprivileged_client, @@ -55,8 +56,9 @@ def created_multiple_failed_vms( "message": "This VM requires more memory.", "min": 1073741824, }, - ) as vm: - return vm + ) as vm, + ): + return vm class TestSSPTemplate: diff --git a/tests/observability/metrics/test_vms_metrics.py b/tests/observability/metrics/test_vms_metrics.py index 06ea7a0b4a..7f70eb4611 100644 --- a/tests/observability/metrics/test_vms_metrics.py +++ b/tests/observability/metrics/test_vms_metrics.py @@ -1,5 +1,5 @@ import logging -from datetime import datetime, timezone +from datetime import UTC, datetime import bitmath import pytest @@ -47,9 +47,7 @@ def get_last_transition_time(vm): for condition in vm.instance.get("status", {}).get("conditions"): if condition.get("type") == vm.Condition.READY: last_transition_time = condition.get("lastTransitionTime") - return int( - (datetime.strptime(last_transition_time, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)).timestamp() - ) + return int((datetime.strptime(last_transition_time, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)).timestamp()) def check_vm_last_transition_metric_value(prometheus, metric, vm): diff --git a/tests/observability/metrics/utils.py b/tests/observability/metrics/utils.py index bc337e2b7a..b35b3caab0 100644 --- a/tests/observability/metrics/utils.py +++ b/tests/observability/metrics/utils.py @@ -3,9 +3,10 @@ import re import shlex import urllib +from collections.abc import Generator from contextlib import contextmanager -from datetime import datetime, timezone -from typing import Any, Generator, Optional +from datetime import UTC, datetime +from typing import Any import bitmath from kubernetes.dynamic import DynamicClient @@ -222,7 +223,7 @@ def enable_swap_fedora_vm(vm: VirtualMachineForTests) -> None: vm.ssh_exec.executor(sudo=True).run_cmd(cmd=shlex.split("sysctl vm.swappiness=100")) -def get_vm_cpu_info_from_prometheus(prometheus: Prometheus, vm_name: str) -> Optional[int]: +def get_vm_cpu_info_from_prometheus(prometheus: Prometheus, vm_name: str) -> int | None: query = urllib.parse.quote_plus( f'kubevirt_vmi_node_cpu_affinity{{kubernetes_vmi_label_kubevirt_io_domain="{vm_name}"}}' ) @@ -453,7 +454,7 @@ def compare_kubevirt_vmi_info_metric_with_vm_info( def timestamp_to_seconds(timestamp: str) -> int: # Parse the timestamp with UTC timezone and convert to seconds dt = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ") - dt = dt.replace(tzinfo=timezone.utc) # Ensure it is treated as UTC + dt = dt.replace(tzinfo=UTC) # Ensure it is treated as UTC return int(dt.timestamp()) diff --git a/tests/storage/cdi_import/test_import_http.py b/tests/storage/cdi_import/test_import_http.py index 3858ab13ce..aef2beea80 100644 --- a/tests/storage/cdi_import/test_import_http.py +++ b/tests/storage/cdi_import/test_import_http.py @@ -161,16 +161,18 @@ def test_invalid_url(dv_non_exist_url): @pytest.mark.polarion("CNV-674") @pytest.mark.s390x def test_empty_url(namespace, storage_class_name_scope_module, unprivileged_client): - with pytest.raises(UnprocessibleEntityError): - with create_dv( + with ( + pytest.raises(UnprocessibleEntityError), + create_dv( client=unprivileged_client, dv_name=f"cnv-674-{storage_class_name_scope_module}", namespace=namespace.name, url="", size=DEFAULT_DV_SIZE, storage_class=storage_class_name_scope_module, - ): - pass + ), + ): + pass @pytest.mark.sno @@ -477,16 +479,18 @@ def test_blank_disk_import_validate_status(data_volume_multi_storage_scope_funct @pytest.mark.sno def test_disk_falloc(data_volume_multi_storage_scope_function, unprivileged_client): data_volume_multi_storage_scope_function.wait_for_dv_success() - with create_vm_from_dv( - client=unprivileged_client, - dv=data_volume_multi_storage_scope_function, - os_flavor=OS_FLAVOR_ALPINE, - memory_guest=Images.Alpine.DEFAULT_MEMORY_SIZE, - ) as vm_dv: - with console.Console(vm=vm_dv) as vm_console: - LOGGER.info("Fill disk space.") - vm_console.sendline("dd if=/dev/urandom of=file bs=1M") - vm_console.expect("No space left on device", timeout=TIMEOUT_1MIN) + with ( + create_vm_from_dv( + client=unprivileged_client, + dv=data_volume_multi_storage_scope_function, + os_flavor=OS_FLAVOR_ALPINE, + memory_guest=Images.Alpine.DEFAULT_MEMORY_SIZE, + ) as vm_dv, + console.Console(vm=vm_dv) as vm_console, + ): + LOGGER.info("Fill disk space.") + vm_console.sendline("dd if=/dev/urandom of=file bs=1M") + vm_console.expect("No space left on device", timeout=TIMEOUT_1MIN) @pytest.mark.destructive diff --git a/tests/storage/cdi_import/test_import_registry.py b/tests/storage/cdi_import/test_import_registry.py index bab5d040a8..89a252fd71 100644 --- a/tests/storage/cdi_import/test_import_registry.py +++ b/tests/storage/cdi_import/test_import_registry.py @@ -171,8 +171,9 @@ def test_public_registry_data_volume_low_capacity(unprivileged_client, namespace @pytest.mark.polarion("CNV-2150") @pytest.mark.s390x def test_public_registry_data_volume_archive(unprivileged_client, namespace, storage_class_name_scope_function): - with pytest.raises(ApiException, match=r".*ContentType must be kubevirt when Source is Registry.*"): - with create_dv( + with ( + pytest.raises(ApiException, match=r".*ContentType must be kubevirt when Source is Registry.*"), + create_dv( client=unprivileged_client, source=REGISTRY_STR, dv_name="import-public-registry-archive", @@ -180,5 +181,6 @@ def test_public_registry_data_volume_archive(unprivileged_client, namespace, sto url=QUAY_FEDORA_CONTAINER_IMAGE, content_type=DataVolume.ContentType.ARCHIVE, storage_class=[*storage_class_name_scope_function][0], - ): - return + ), + ): + return diff --git a/tests/storage/cdi_upload/test_upload.py b/tests/storage/cdi_upload/test_upload.py index 6f22b5f1b9..f1a1e5f8b4 100644 --- a/tests/storage/cdi_upload/test_upload.py +++ b/tests/storage/cdi_upload/test_upload.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Upload tests """ diff --git a/tests/storage/cdi_upload/test_upload_virtctl.py b/tests/storage/cdi_upload/test_upload_virtctl.py index d56900133c..b3214cadc5 100644 --- a/tests/storage/cdi_upload/test_upload_virtctl.py +++ b/tests/storage/cdi_upload/test_upload_virtctl.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Upload using virtctl """ diff --git a/tests/storage/cdi_upload/utils.py b/tests/storage/cdi_upload/utils.py index f4c63dd0d6..d0bdb30591 100644 --- a/tests/storage/cdi_upload/utils.py +++ b/tests/storage/cdi_upload/utils.py @@ -1,5 +1,4 @@ import logging -from typing import Optional from kubernetes.dynamic import DynamicClient from ocp_resources.resource import Resource @@ -8,7 +7,7 @@ LOGGER = logging.getLogger(__name__) -def get_storage_profile_minimum_supported_pvc_size(storage_class_name: str, client: DynamicClient) -> Optional[str]: +def get_storage_profile_minimum_supported_pvc_size(storage_class_name: str, client: DynamicClient) -> str | None: """ Get the minimum supported PVC size from the storage profile annotations. diff --git a/tests/storage/checkups/conftest.py b/tests/storage/checkups/conftest.py index b17d7b9ee2..d1b8f97998 100644 --- a/tests/storage/checkups/conftest.py +++ b/tests/storage/checkups/conftest.py @@ -176,12 +176,14 @@ def checkup_job( @pytest.fixture() def updated_two_default_storage_classes(removed_default_storage_classes, cluster_storage_classes): first_sc, second_sc = cluster_storage_classes[:2] - with update_default_sc(default=True, storage_class=first_sc): - with update_default_sc( + with ( + update_default_sc(default=True, storage_class=first_sc), + update_default_sc( default=True, storage_class=second_sc, - ): - yield + ), + ): + yield @pytest.fixture() diff --git a/tests/storage/conftest.py b/tests/storage/conftest.py index 1df0865b7f..b1b1976480 100644 --- a/tests/storage/conftest.py +++ b/tests/storage/conftest.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Pytest conftest file for CNV CDI tests """ diff --git a/tests/storage/cross_cluster_live_migration/utils.py b/tests/storage/cross_cluster_live_migration/utils.py index be4227f744..7fea17ff0c 100644 --- a/tests/storage/cross_cluster_live_migration/utils.py +++ b/tests/storage/cross_cluster_live_migration/utils.py @@ -1,4 +1,4 @@ -from typing import Generator +from collections.abc import Generator from kubernetes.dynamic import DynamicClient from ocp_resources.hyperconverged import HyperConverged @@ -17,7 +17,7 @@ def enable_feature_gate_and_configure_hco_live_migration_network( client: DynamicClient, network_for_live_migration: NetworkAttachmentDefinition, hco_namespace: Namespace, -) -> Generator[None, None, None]: +) -> Generator[None]: """ Enable decentralized live migration feature gate and configure HCO live migration network. diff --git a/tests/storage/data_import_cron/conftest.py b/tests/storage/data_import_cron/conftest.py index 70a04590ce..151c876b30 100644 --- a/tests/storage/data_import_cron/conftest.py +++ b/tests/storage/data_import_cron/conftest.py @@ -114,18 +114,19 @@ def cdi_cloner_rbac(dv_source_for_data_import_cron, data_import_cron_pvc_target_ resources. """ - with ClusterRole( - name="datavolume-cloner", - client=admin_client, - rules=[ - { - "apiGroups": [Resource.ApiGroup.CDI_KUBEVIRT_IO], - "resources": ["datavolumes", "datavolumes/source"], - "verbs": ["*"], - } - ], - ) as cluster_role: - with create_role_binding( + with ( + ClusterRole( + name="datavolume-cloner", + client=admin_client, + rules=[ + { + "apiGroups": [Resource.ApiGroup.CDI_KUBEVIRT_IO], + "resources": ["datavolumes", "datavolumes/source"], + "verbs": ["*"], + } + ], + ) as cluster_role, + create_role_binding( client=admin_client, name=f"allow-clone-to-{data_import_cron_pvc_target_namespace.name}", namespace=dv_source_for_data_import_cron.namespace, @@ -134,5 +135,6 @@ def cdi_cloner_rbac(dv_source_for_data_import_cron, data_import_cron_pvc_target_ subjects_namespace=data_import_cron_pvc_target_namespace.name, role_ref_kind=cluster_role.kind, role_ref_name=cluster_role.name, - ): - yield + ), + ): + yield diff --git a/tests/storage/golden_image/test_golden_image.py b/tests/storage/golden_image/test_golden_image.py index 6e792b203a..9d6faaeec1 100644 --- a/tests/storage/golden_image/test_golden_image.py +++ b/tests/storage/golden_image/test_golden_image.py @@ -54,19 +54,21 @@ def test_regular_user_cant_create_dv_in_ns( unprivileged_client, ): LOGGER.info("Try as a regular user, to create a DV in golden image NS and receive the proper error") - with pytest.raises( - ApiException, - match=ErrorMsg.CANNOT_CREATE_RESOURCE, - ): - with create_dv( + with ( + pytest.raises( + ApiException, + match=ErrorMsg.CANNOT_CREATE_RESOURCE, + ), + create_dv( dv_name="cnv-4755", namespace=golden_images_namespace.name, url=f"{get_test_artifact_server_url()}{LATEST_RHEL_IMAGE}", size=RHEL_IMAGE_SIZE, storage_class=py_config["default_storage_class"], client=unprivileged_client, - ): - return + ), + ): + return @pytest.mark.sno @@ -137,11 +139,12 @@ def test_regular_user_cant_clone_dv_in_ns( storage_class = golden_image_data_volume_scope_module.storage_class golden_images_namespace = golden_image_data_volume_scope_module.namespace - with pytest.raises( - ApiException, - match=ErrorMsg.CANNOT_CREATE_RESOURCE, - ): - with create_dv( + with ( + pytest.raises( + ApiException, + match=ErrorMsg.CANNOT_CREATE_RESOURCE, + ), + create_dv( dv_name=f"cnv-4760-{storage_class}", namespace=golden_images_namespace, source=PVC, @@ -150,8 +153,9 @@ def test_regular_user_cant_clone_dv_in_ns( source_namespace=golden_images_namespace, client=unprivileged_client, storage_class=storage_class, - ): - return + ), + ): + return @pytest.mark.sno diff --git a/tests/storage/hpp/test_hostpath.py b/tests/storage/hpp/test_hostpath.py index dd125daca4..71d6b06c69 100644 --- a/tests/storage/hpp/test_hostpath.py +++ b/tests/storage/hpp/test_hostpath.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Hostpath Provisioner test suite """ diff --git a/tests/storage/hpp/test_hpp_node_placement.py b/tests/storage/hpp/test_hpp_node_placement.py index 5dbee33816..4160bb9545 100644 --- a/tests/storage/hpp/test_hpp_node_placement.py +++ b/tests/storage/hpp/test_hpp_node_placement.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ HPP Node Placement test suite """ diff --git a/tests/storage/online_resize/conftest.py b/tests/storage/online_resize/conftest.py index 8343fc5ceb..d726e1e83b 100644 --- a/tests/storage/online_resize/conftest.py +++ b/tests/storage/online_resize/conftest.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Fixtures for online resize tests """ diff --git a/tests/storage/online_resize/test_online_resize.py b/tests/storage/online_resize/test_online_resize.py index c9a611fa46..e792dea4e7 100644 --- a/tests/storage/online_resize/test_online_resize.py +++ b/tests/storage/online_resize/test_online_resize.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Online resize (PVC expanded while VM running) """ diff --git a/tests/storage/online_resize/utils.py b/tests/storage/online_resize/utils.py index b2962a8aba..fefd328715 100644 --- a/tests/storage/online_resize/utils.py +++ b/tests/storage/online_resize/utils.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Utility functions and context managers for online resize tests """ diff --git a/tests/storage/restricted_namespace_cloning/test_restricted_namespace_cloning_vms.py b/tests/storage/restricted_namespace_cloning/test_restricted_namespace_cloning_vms.py index 421cce8179..5cc3d0e427 100644 --- a/tests/storage/restricted_namespace_cloning/test_restricted_namespace_cloning_vms.py +++ b/tests/storage/restricted_namespace_cloning/test_restricted_namespace_cloning_vms.py @@ -54,11 +54,12 @@ def create_vm_negative( unprivileged_client, data_volume_clone_settings, ): - with pytest.raises( - ApiException, - match=ErrorMsg.CANNOT_CREATE_RESOURCE, - ): - with VirtualMachineForTests( + with ( + pytest.raises( + ApiException, + match=ErrorMsg.CANNOT_CREATE_RESOURCE, + ), + VirtualMachineForTests( name=VM_FOR_TEST, namespace=namespace, os_flavor=Images.Cirros.OS_FLAVOR, @@ -66,8 +67,9 @@ def create_vm_negative( client=unprivileged_client, memory_guest=Images.Cirros.DEFAULT_MEMORY_SIZE, data_volume_template=get_dv_template(data_volume_clone_settings=data_volume_clone_settings), - ): - return + ), + ): + return @pytest.mark.sno diff --git a/tests/storage/restricted_namespace_cloning/utils.py b/tests/storage/restricted_namespace_cloning/utils.py index aca9da6a6a..078b9972cf 100644 --- a/tests/storage/restricted_namespace_cloning/utils.py +++ b/tests/storage/restricted_namespace_cloning/utils.py @@ -35,11 +35,12 @@ def create_dv_negative( source_namespace: str, unprivileged_client: DynamicClient, ) -> None: - with pytest.raises( - ApiException, - match=ErrorMsg.CANNOT_CREATE_RESOURCE, - ): - with create_dv( + with ( + pytest.raises( + ApiException, + match=ErrorMsg.CANNOT_CREATE_RESOURCE, + ), + create_dv( dv_name=TARGET_DV, namespace=namespace, source=PVC, @@ -48,5 +49,6 @@ def create_dv_negative( source_namespace=source_namespace, client=unprivileged_client, storage_class=storage_class, - ): - LOGGER.error("Target dv was created, but shouldn't have been") + ), + ): + LOGGER.error("Target dv was created, but shouldn't have been") diff --git a/tests/storage/snapshots/conftest.py b/tests/storage/snapshots/conftest.py index 4db9193480..8e59c17c3a 100644 --- a/tests/storage/snapshots/conftest.py +++ b/tests/storage/snapshots/conftest.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Pytest conftest file for CNV Storage snapshots tests """ diff --git a/tests/storage/snapshots/test_snapshots.py b/tests/storage/snapshots/test_snapshots.py index 9f936cbf6f..3fea06cfb2 100644 --- a/tests/storage/snapshots/test_snapshots.py +++ b/tests/storage/snapshots/test_snapshots.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Snapshots tests """ @@ -209,18 +207,20 @@ def test_fail_restore_vm_with_unprivileged_client( ): if rhel_vm_for_snapshot.ready: rhel_vm_for_snapshot.stop(wait=True) - with pytest.raises( - ApiException, - match=ERROR_MSG_USER_CANNOT_CREATE_VM_RESTORE, - ): - with VirtualMachineRestore( + with ( + pytest.raises( + ApiException, + match=ERROR_MSG_USER_CANNOT_CREATE_VM_RESTORE, + ), + VirtualMachineRestore( client=unprivileged_client, name="restore-snapshot-cnv-5049-unprivileged", namespace=rhel_vm_for_snapshot.namespace, vm_name=rhel_vm_for_snapshot.name, snapshot_name=snapshot_with_content[0].name, - ): - return + ), + ): + return @pytest.mark.sno @pytest.mark.parametrize( diff --git a/tests/storage/snapshots/utils.py b/tests/storage/snapshots/utils.py index 7b85eb72de..ce862c469d 100644 --- a/tests/storage/snapshots/utils.py +++ b/tests/storage/snapshots/utils.py @@ -31,17 +31,19 @@ def expected_output_after_restore(snapshot_number): def fail_to_create_snapshot_no_permissions(snapshot_name, namespace, vm_name, client): - with pytest.raises( - ApiException, - match=ERROR_MSG_USER_CANNOT_CREATE_VM_SNAPSHOTS, - ): - with VirtualMachineSnapshot( + with ( + pytest.raises( + ApiException, + match=ERROR_MSG_USER_CANNOT_CREATE_VM_SNAPSHOTS, + ), + VirtualMachineSnapshot( name=snapshot_name, namespace=namespace, vm_name=vm_name, client=client, - ): - return + ), + ): + return def start_windows_vm_after_restore(vm_restore, windows_vm): diff --git a/tests/storage/test_cdi_certificate.py b/tests/storage/test_cdi_certificate.py index 17cfec7058..098e16528f 100644 --- a/tests/storage/test_cdi_certificate.py +++ b/tests/storage/test_cdi_certificate.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Automatic refresh of CDI certificates test suite """ @@ -83,9 +81,9 @@ def valid_cdi_certificates(secrets): start = secret.certificate_not_before end = secret.certificate_not_after - start_dt = datetime.datetime.strptime(start, RFC3339_FORMAT).replace(tzinfo=datetime.timezone.utc) - end_dt = datetime.datetime.strptime(end, RFC3339_FORMAT).replace(tzinfo=datetime.timezone.utc) - now_dt = datetime.datetime.now(datetime.timezone.utc) + start_dt = datetime.datetime.strptime(start, RFC3339_FORMAT).replace(tzinfo=datetime.UTC) + end_dt = datetime.datetime.strptime(end, RFC3339_FORMAT).replace(tzinfo=datetime.UTC) + now_dt = datetime.datetime.now(datetime.UTC) assert start_dt <= now_dt <= end_dt, f"Certificate of {cdi_secret} not valid at current time" diff --git a/tests/storage/test_cdi_config.py b/tests/storage/test_cdi_config.py index f4d267027f..fc43af4f25 100644 --- a/tests/storage/test_cdi_config.py +++ b/tests/storage/test_cdi_config.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """CDIConfig tests""" import logging @@ -279,13 +277,14 @@ def test_cdiconfig_changing_storage_class_default( images_https_server=get_test_artifact_server_url(schema="https"), file_name=Images.Cirros.QCOW2_IMG, ) - with ConfigMap( - client=unprivileged_client, - name="https-cert-configmap", - namespace=namespace.name, - data={"tlsregistry.crt": https_server_certificate}, - ) as configmap: - with create_dv( + with ( + ConfigMap( + client=unprivileged_client, + name="https-cert-configmap", + namespace=namespace.name, + data={"tlsregistry.crt": https_server_certificate}, + ) as configmap, + create_dv( client=unprivileged_client, source="http", dv_name="import-cdiconfig-scratch-space-not-default", @@ -293,9 +292,10 @@ def test_cdiconfig_changing_storage_class_default( url=url, storage_class=StorageClassNames.CEPH_RBD_VIRTUALIZATION, cert_configmap=configmap.name, - ) as dv: - dv.wait_for_dv_success() - create_vm_from_dv(client=unprivileged_client, dv=dv) + ) as dv, + ): + dv.wait_for_dv_success() + create_vm_from_dv(client=unprivileged_client, dv=dv) @pytest.mark.sno diff --git a/tests/storage/test_cdi_resources.py b/tests/storage/test_cdi_resources.py index df7a165719..dfcc001fc1 100644 --- a/tests/storage/test_cdi_resources.py +++ b/tests/storage/test_cdi_resources.py @@ -53,11 +53,14 @@ def verify_label(cdi_resources): def verify_cdi_app_label(cdi_resources, cnv_version): for resource in cdi_resources: - if resource.kind == "Secret" and resource.name not in CDI_SECRETS: - continue - elif resource.kind == "ServiceAccount" and resource.name == CDI_OPERATOR: - continue - elif resource.kind == "ConfigMap" and resource.name not in CDI_CONFIGMAPS: + if ( + resource.kind == "Secret" + and resource.name not in CDI_SECRETS + or resource.kind == "ServiceAccount" + and resource.name == CDI_OPERATOR + or resource.kind == "ConfigMap" + and resource.name not in CDI_CONFIGMAPS + ): continue else: assert resource.labels[f"{Resource.ApiGroup.APP_KUBERNETES_IO}/component"] == "storage", ( diff --git a/tests/storage/test_data_protection.py b/tests/storage/test_data_protection.py index aff1314cb7..a9521ccb68 100644 --- a/tests/storage/test_data_protection.py +++ b/tests/storage/test_data_protection.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ CDI data protection test suite """ diff --git a/tests/storage/test_disk_preallocation.py b/tests/storage/test_disk_preallocation.py index 513b78e94a..40a95cd2ab 100644 --- a/tests/storage/test_disk_preallocation.py +++ b/tests/storage/test_disk_preallocation.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ CDI disk preallocation test suite """ diff --git a/tests/storage/test_local_storage.py b/tests/storage/test_local_storage.py index c8897318d3..5a55eb384d 100644 --- a/tests/storage/test_local_storage.py +++ b/tests/storage/test_local_storage.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Test local storage """ diff --git a/tests/storage/test_wffc.py b/tests/storage/test_wffc.py index 564f78c183..826250b1cf 100644 --- a/tests/storage/test_wffc.py +++ b/tests/storage/test_wffc.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ HonorWaitForFirstConsumer test suite """ @@ -230,7 +228,7 @@ def test_wffc_import_registry_dv( "data_volume_multi_wffc_storage_scope_module", [ pytest.param( - {**DV_PARAMS, **{"consume_wffc": True}}, + {**DV_PARAMS, "consume_wffc": True}, marks=pytest.mark.polarion("CNV-4379"), ), ], diff --git a/tests/storage/utils.py b/tests/storage/utils.py index 7b2340e8ec..985296561c 100644 --- a/tests/storage/utils.py +++ b/tests/storage/utils.py @@ -1,8 +1,8 @@ import ast import logging import shlex +from collections.abc import Generator from contextlib import contextmanager -from typing import Generator import requests from kubernetes.dynamic import DynamicClient @@ -67,13 +67,14 @@ def import_image_to_dv( client, ): url = get_file_url_https_server(images_https_server=images_https_server_name, file_name=Images.Cirros.QCOW2_IMG) - with ConfigMap( - name="https-cert-configmap", - namespace=storage_ns_name, - data={"tlsregistry.crt": https_server_certificate}, - client=client, - ) as configmap: - with create_dv( + with ( + ConfigMap( + name="https-cert-configmap", + namespace=storage_ns_name, + data={"tlsregistry.crt": https_server_certificate}, + client=client, + ) as configmap, + create_dv( source="http", dv_name=dv_name, namespace=configmap.namespace, @@ -81,8 +82,9 @@ def import_image_to_dv( cert_configmap=configmap.name, storage_class=py_config["default_storage_class"], client=client, - ) as dv: - yield dv + ) as dv, + ): + yield dv @contextmanager @@ -236,14 +238,15 @@ def set_permissions( subjects_api_group: str | None = None, subjects_namespace: str | None = None, ) -> Generator: - with create_cluster_role( - client=client, - name=role_name, - api_groups=role_api_groups, - permissions_to_resources=permissions_to_resources, - verbs=verbs, - ) as cluster_role: - with create_role_binding( + with ( + create_cluster_role( + client=client, + name=role_name, + api_groups=role_api_groups, + permissions_to_resources=permissions_to_resources, + verbs=verbs, + ) as cluster_role, + create_role_binding( client=client, name=binding_name, namespace=namespace, @@ -253,8 +256,9 @@ def set_permissions( subjects_namespace=subjects_namespace, role_ref_kind=cluster_role.kind, role_ref_name=cluster_role.name, - ): - yield + ), + ): + yield def get_importer_pod( diff --git a/tests/storage/vm_export/test_vm_export.py b/tests/storage/vm_export/test_vm_export.py index c7e48a00fe..6e4833fd16 100644 --- a/tests/storage/vm_export/test_vm_export.py +++ b/tests/storage/vm_export/test_vm_export.py @@ -38,11 +38,12 @@ def test_fail_to_vmexport_with_unprivileged_client_no_permissions( blank_dv_created_by_admin_user, unprivileged_client, ): - with pytest.raises( - ApiException, - match=ERROR_MSG_USER_CANNOT_CREATE_VM_EXPORT, - ): - with VirtualMachineExport( + with ( + pytest.raises( + ApiException, + match=ERROR_MSG_USER_CANNOT_CREATE_VM_EXPORT, + ), + VirtualMachineExport( name="vmexport-unprivileged", namespace=blank_dv_created_by_admin_user.namespace, client=unprivileged_client, @@ -51,8 +52,9 @@ def test_fail_to_vmexport_with_unprivileged_client_no_permissions( "kind": PersistentVolumeClaim.kind, "name": blank_dv_created_by_admin_user.name, }, - ) as vmexport: - assert not vmexport, "VMExport created by unprivileged client" + ) as vmexport, + ): + assert not vmexport, "VMExport created by unprivileged client" @pytest.mark.polarion("CNV-9903") diff --git a/tests/storage/vm_export/utils.py b/tests/storage/vm_export/utils.py index 100c1af67f..cceae57ed7 100644 --- a/tests/storage/vm_export/utils.py +++ b/tests/storage/vm_export/utils.py @@ -5,8 +5,8 @@ import io import logging import shlex +from collections.abc import Generator from contextlib import contextmanager -from typing import Generator import yaml from kubernetes.dynamic import DynamicClient diff --git a/tests/utils.py b/tests/utils.py index 48b0a22474..e63ea2d112 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -4,9 +4,9 @@ import re import shlex import tarfile +from collections.abc import Generator from contextlib import contextmanager from io import BytesIO -from typing import Generator, Optional import bitmath import requests @@ -534,12 +534,12 @@ def create_cirros_vm( client: DynamicClient, dv_name: str, vm_name: str, - node: Optional[str] = None, - wait_running: Optional[bool] = True, - volume_mode: Optional[str] = None, - cpu_model: Optional[str] = None, - annotations: Optional[str] = None, -) -> Generator[VirtualMachineForTests, None, None]: + node: str | None = None, + wait_running: bool | None = True, + volume_mode: str | None = None, + cpu_model: str | None = None, + annotations: str | None = None, +) -> Generator[VirtualMachineForTests]: artifactory_secret = get_artifactory_secret(namespace=namespace) artifactory_config_map = get_artifactory_config_map(namespace=namespace) diff --git a/tests/virt/cluster/common_templates/centos/test_centos_os_support.py b/tests/virt/cluster/common_templates/centos/test_centos_os_support.py index 30c3ea095e..0bdb3f51b8 100644 --- a/tests/virt/cluster/common_templates/centos/test_centos_os_support.py +++ b/tests/virt/cluster/common_templates/centos/test_centos_os_support.py @@ -76,9 +76,9 @@ def test_domain_label(self, matrix_centos_os_vm_from_template): def test_expose_ssh(self, matrix_centos_os_vm_from_template): """CNV common templates access VM via SSH""" - assert matrix_centos_os_vm_from_template.ssh_exec.executor().is_connective( # noqa: E501 - tcp_timeout=120 - ), "Failed to login via SSH" + assert matrix_centos_os_vm_from_template.ssh_exec.executor().is_connective(tcp_timeout=120), ( + "Failed to login via SSH" + ) @pytest.mark.dependency( name=f"{TESTS_CLASS_NAME}::vmi_guest_agent_info", depends=[f"{TESTS_CLASS_NAME}::vm_expose_ssh"] diff --git a/tests/virt/cluster/common_templates/fedora/test_fedora_os_support.py b/tests/virt/cluster/common_templates/fedora/test_fedora_os_support.py index 8cec0871fb..40b765cf6a 100644 --- a/tests/virt/cluster/common_templates/fedora/test_fedora_os_support.py +++ b/tests/virt/cluster/common_templates/fedora/test_fedora_os_support.py @@ -151,9 +151,9 @@ def test_domain_label(self, matrix_fedora_os_vm_from_template): def test_expose_ssh(self, matrix_fedora_os_vm_from_template): """CNV common templates access VM via SSH""" - assert matrix_fedora_os_vm_from_template.ssh_exec.executor().is_connective( # noqa: E501 - tcp_timeout=120 - ), "Failed to login via SSH" + assert matrix_fedora_os_vm_from_template.ssh_exec.executor().is_connective(tcp_timeout=120), ( + "Failed to login via SSH" + ) @pytest.mark.sno @pytest.mark.dependency( diff --git a/tests/virt/cluster/common_templates/general/test_template_validator.py b/tests/virt/cluster/common_templates/general/test_template_validator.py index 1a737b94e3..3106efa1fe 100644 --- a/tests/virt/cluster/common_templates/general/test_template_validator.py +++ b/tests/virt/cluster/common_templates/general/test_template_validator.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - """ Base templates test """ diff --git a/tests/virt/cluster/common_templates/rhel/test_rhel_os_support.py b/tests/virt/cluster/common_templates/rhel/test_rhel_os_support.py index 373cd2c79a..45ccd8e871 100644 --- a/tests/virt/cluster/common_templates/rhel/test_rhel_os_support.py +++ b/tests/virt/cluster/common_templates/rhel/test_rhel_os_support.py @@ -109,9 +109,9 @@ def test_domain_label(self, matrix_rhel_os_vm_from_template): @pytest.mark.polarion("CNV-3320") def test_expose_ssh(self, matrix_rhel_os_vm_from_template): """CNV common templates access VM via SSH""" - assert matrix_rhel_os_vm_from_template.ssh_exec.executor().is_connective( # noqa: E501 - tcp_timeout=120 - ), "Failed to login via SSH" + assert matrix_rhel_os_vm_from_template.ssh_exec.executor().is_connective(tcp_timeout=120), ( + "Failed to login via SSH" + ) @pytest.mark.arm64 @pytest.mark.sno diff --git a/tests/virt/cluster/common_templates/utils.py b/tests/virt/cluster/common_templates/utils.py index c3c32b3b36..1c8e14baef 100644 --- a/tests/virt/cluster/common_templates/utils.py +++ b/tests/virt/cluster/common_templates/utils.py @@ -2,9 +2,9 @@ import logging import re import shlex -from datetime import datetime, timedelta, timezone +from collections.abc import Generator +from datetime import UTC, datetime, timedelta, timezone from functools import cache -from typing import Generator, Optional import bitmath import pytest @@ -178,7 +178,7 @@ def _get_vm_timezone_diff(): if virtctl_info["userName"].lower() not in windows_info: data_mismatch.append("user name mismatch") # Windows date format - 11/4/2020 (-m/-d/Y) - if datetime.fromtimestamp(timestamp=virtctl_time, tz=timezone.utc).strftime("%-m/%-d/%Y") not in windows_info: + if datetime.fromtimestamp(timestamp=virtctl_time, tz=UTC).strftime("%-m/%-d/%Y") not in windows_info: data_mismatch.append("login time mismatch") assert not data_mismatch, ( @@ -478,7 +478,7 @@ def check_vm_xml_tablet_device(vm): def get_matrix_os_golden_image_data_source( admin_client: DynamicClient, golden_images_namespace: Namespace, os_matrix: dict[str, dict] -) -> Generator[DataSource, None, None]: +) -> Generator[DataSource]: """Retrieves or creates a DataSource object in golden image namespace specified in the OS matrix. Args: @@ -501,8 +501,8 @@ def matrix_os_vm_from_template( data_source_object: DataSource, os_matrix: dict[str, dict], cpu_model: str | None = None, - request: Optional[FixtureRequest] = None, - data_volume_template: Optional[dict[str, dict]] = None, + request: FixtureRequest | None = None, + data_volume_template: dict[str, dict] | None = None, ) -> VirtualMachineForTestsFromTemplate: param_dict = request.param if request else {} os_matrix_key = [*os_matrix][0] diff --git a/tests/virt/cluster/longevity_tests/utils.py b/tests/virt/cluster/longevity_tests/utils.py index e94e3bf281..e668808648 100644 --- a/tests/virt/cluster/longevity_tests/utils.py +++ b/tests/virt/cluster/longevity_tests/utils.py @@ -1,7 +1,6 @@ import logging import shlex import shutil -import socket from threading import Thread from ocp_resources import pod @@ -138,7 +137,7 @@ def _start_win_upgrade(vm): timeout=TIMEOUT_40MIN, ) LOGGER.info(f"VM {vm.name}: Finished upgrades download/install stage") - except socket.timeout: + except TimeoutError: LOGGER.warning(f"VM {vm.name}: Finished upgrades download/install stage but the script was stuck") upgrade_threads_list = [] diff --git a/tests/virt/cluster/sysprep/test_sysprep.py b/tests/virt/cluster/sysprep/test_sysprep.py index 6d9a363d99..b36b09b844 100644 --- a/tests/virt/cluster/sysprep/test_sysprep.py +++ b/tests/virt/cluster/sysprep/test_sysprep.py @@ -127,8 +127,9 @@ def sysprep_vm( namespace, instance_type_for_test_scope_class, ): - with instance_type_for_test_scope_class as vm_instance_type: - with VirtualMachineForTests( + with ( + instance_type_for_test_scope_class as vm_instance_type, + VirtualMachineForTests( name=f"sysprep-{sysprep_source_matrix__class__.lower()}-vm", namespace=namespace.name, client=unprivileged_client, @@ -138,9 +139,10 @@ def sysprep_vm( os_flavor=OS_FLAVOR_WINDOWS, disk_type=None, cpu_model=modern_cpu_for_migration, - ) as vm: - running_vm(vm=vm) - yield vm + ) as vm, + ): + running_vm(vm=vm) + yield vm @pytest.fixture(scope="class") diff --git a/tests/virt/node/cpu_sockets_threads/test_cpu_support_sockets_threads.py b/tests/virt/node/cpu_sockets_threads/test_cpu_support_sockets_threads.py index 29a6516531..69430caacb 100644 --- a/tests/virt/node/cpu_sockets_threads/test_cpu_support_sockets_threads.py +++ b/tests/virt/node/cpu_sockets_threads/test_cpu_support_sockets_threads.py @@ -140,13 +140,15 @@ def test_vm_with_cpu_limitation_negative(namespace, unprivileged_client): negative case: CPU requests is larger then limits """ name = "vm-cpu-limitation-negative" - with pytest.raises(UnprocessibleEntityError): - with VirtualMachineForTests( + with ( + pytest.raises(UnprocessibleEntityError), + VirtualMachineForTests( name=name, namespace=namespace.name, cpu_limits=2, cpu_requests=4, body=fedora_vm_body(name=name), client=unprivileged_client, - ): - return + ), + ): + return diff --git a/tests/virt/node/descheduler/conftest.py b/tests/virt/node/descheduler/conftest.py index c78c2ab4aa..2de96408ba 100644 --- a/tests/virt/node/descheduler/conftest.py +++ b/tests/virt/node/descheduler/conftest.py @@ -272,13 +272,14 @@ def utilization_imbalance( evict_protected_pod_selector = {"matchLabels": evict_protected_pod_label_dict} utilization_imbalance_deployment_name = "utilization-imbalance-deployment" - with PodDisruptionBudget( - name=utilization_imbalance_deployment_name, - namespace=namespace.name, - min_available=unallocated_pod_count, - selector=evict_protected_pod_selector, - ): - with Deployment( + with ( + PodDisruptionBudget( + name=utilization_imbalance_deployment_name, + namespace=namespace.name, + min_available=unallocated_pod_count, + selector=evict_protected_pod_selector, + ), + Deployment( name=utilization_imbalance_deployment_name, namespace=namespace.name, client=admin_client, @@ -303,9 +304,10 @@ def utilization_imbalance( ], }, }, - ) as deployment: - deployment.wait_for_replicas(timeout=unallocated_pod_count * TIMEOUT_5SEC) - yield + ) as deployment, + ): + deployment.wait_for_replicas(timeout=unallocated_pod_count * TIMEOUT_5SEC) + yield LOGGER.info(f"Wait while all {utilization_imbalance_deployment_name} pods removed") wait_for_pods_deletion( diff --git a/tests/virt/node/efi_secureboot/test_vm_with_efi_secureboot.py b/tests/virt/node/efi_secureboot/test_vm_with_efi_secureboot.py index d31e65796f..f21c61e1bf 100644 --- a/tests/virt/node/efi_secureboot/test_vm_with_efi_secureboot.py +++ b/tests/virt/node/efi_secureboot/test_vm_with_efi_secureboot.py @@ -16,13 +16,15 @@ @pytest.mark.polarion("CNV-4465") def test_efi_secureboot_with_smm_disabled(namespace, unprivileged_client): """Test that EFI secureBoot VM with SMM disabled, does not get created""" - with pytest.raises(UnprocessibleEntityError): - with VirtualMachineForTests( + with ( + pytest.raises(UnprocessibleEntityError), + VirtualMachineForTests( name="efi-secureboot-smm-disabled-vm", namespace=namespace.name, image="kubevirt/microlivecd-container-disk-demo", client=unprivileged_client, smm_enabled=False, efi_params={"secureBoot": True}, - ): - pytest.fail("VM created with EFI SecureBoot enabled. SecureBoot requires SMM, which is currently disabled") + ), + ): + pytest.fail("VM created with EFI SecureBoot enabled. SecureBoot requires SMM, which is currently disabled") diff --git a/tests/virt/node/general/test_machinetype.py b/tests/virt/node/general/test_machinetype.py index 86222bb5a7..39714b266b 100644 --- a/tests/virt/node/general/test_machinetype.py +++ b/tests/virt/node/general/test_machinetype.py @@ -212,15 +212,17 @@ def test_machine_type_kubevirt_config_update(updated_kubevirt_config_machine_typ def test_unsupported_machine_type(namespace, unprivileged_client): vm_name = "vm-invalid-machine-type" - with pytest.raises(UnprocessibleEntityError): - with VirtualMachineForTests( + with ( + pytest.raises(UnprocessibleEntityError), + VirtualMachineForTests( name=vm_name, namespace=namespace.name, body=fedora_vm_body(name=vm_name), client=unprivileged_client, machine_type=MachineTypesNames.pc_i440fx_rhel7_6, - ): - pytest.fail("VM created with invalid machine type.") + ), + ): + pytest.fail("VM created with invalid machine type.") @pytest.mark.arm64 diff --git a/tests/virt/node/migration_and_maintenance/test_node_maintenance.py b/tests/virt/node/migration_and_maintenance/test_node_maintenance.py index d6b637fdf1..db18572e99 100644 --- a/tests/virt/node/migration_and_maintenance/test_node_maintenance.py +++ b/tests/virt/node/migration_and_maintenance/test_node_maintenance.py @@ -211,14 +211,16 @@ def test_node_cordon_template_windows( vm_for_test_from_template_scope_class, ): vm = vm_for_test_from_template_scope_class - with node_mgmt_console( - admin_client=admin_client, - node=vm.privileged_vmi.virt_launcher_pod.node, - node_mgmt="cordon", + with ( + node_mgmt_console( + admin_client=admin_client, + node=vm.privileged_vmi.virt_launcher_pod.node, + node_mgmt="cordon", + ), + pytest.raises(TimeoutExpiredError), ): - with pytest.raises(TimeoutExpiredError): - migration_job_sampler( - client=admin_client, - namespace=vm.namespace, - ) - pytest.fail("Cordon of a Node should not trigger VMI migration.") + migration_job_sampler( + client=admin_client, + namespace=vm.namespace, + ) + pytest.fail("Cordon of a Node should not trigger VMI migration.") diff --git a/tests/virt/node/node_labeller/cpu_features/test_vm_with_cpu_features.py b/tests/virt/node/node_labeller/cpu_features/test_vm_with_cpu_features.py index 2a249eee6e..c3e910aea6 100644 --- a/tests/virt/node/node_labeller/cpu_features/test_vm_with_cpu_features.py +++ b/tests/virt/node/node_labeller/cpu_features/test_vm_with_cpu_features.py @@ -76,12 +76,14 @@ def test_vm_with_cpu_feature_positive(cpu_features_vm_positive): def test_invalid_cpu_feature_policy_negative(unprivileged_client, namespace, features): """VM should not be created successfully""" vm_name = "invalid-cpu-feature-policy-vm" - with pytest.raises(UnprocessibleEntityError): - with VirtualMachineForTests( + with ( + pytest.raises(UnprocessibleEntityError), + VirtualMachineForTests( name=vm_name, namespace=namespace.name, cpu_flags={"features": features}, body=fedora_vm_body(name=vm_name), client=unprivileged_client, - ): - pytest.fail("VM was created with an invalid cpu feature policy.") + ), + ): + pytest.fail("VM was created with an invalid cpu feature policy.") diff --git a/tests/virt/upgrade/conftest.py b/tests/virt/upgrade/conftest.py index 069ec92f18..1b59eb9d2e 100644 --- a/tests/virt/upgrade/conftest.py +++ b/tests/virt/upgrade/conftest.py @@ -256,22 +256,24 @@ def windows_vm( size=latest_windows_dict["dv_size"], ) as dv: dv.wait_for_dv_success(timeout=TIMEOUT_30MIN) - with DataSource( - name=dv.name, - namespace=dv.namespace, - client=admin_client, - source=generate_data_source_dict(dv=dv), - ) as ds: - with vm_from_template( + with ( + DataSource( + name=dv.name, + namespace=dv.namespace, + client=admin_client, + source=generate_data_source_dict(dv=dv), + ) as ds, + vm_from_template( vm_name="windows-vm", namespace=virt_upgrade_namespace.name, client=unprivileged_client, template_labels=latest_windows_dict["template_labels"], data_source=ds, cpu_model=modern_cpu_for_migration, - ) as vm: - running_vm(vm=vm) - yield vm + ) as vm, + ): + running_vm(vm=vm) + yield vm @pytest.fixture() diff --git a/tests/virt/upgrade/utils.py b/tests/virt/upgrade/utils.py index 64e5bc4894..92347dc260 100644 --- a/tests/virt/upgrade/utils.py +++ b/tests/virt/upgrade/utils.py @@ -81,7 +81,7 @@ def get_workload_update_migrations_list( if migration_job.name.startswith("kubevirt-workload-update"): job_instance = migration_job.instance vmi_name = job_instance.spec.vmiName - if vmi_name not in workload_migrations.keys() or datetime.strptime( + if vmi_name not in workload_migrations or datetime.strptime( job_instance.metadata.creationTimestamp, TIMESTAMP_FORMAT ) > datetime.strptime( workload_migrations[vmi_name].metadata.creationTimestamp, diff --git a/tests/virt/utils.py b/tests/virt/utils.py index 221ed0a722..dd07d0e8d2 100644 --- a/tests/virt/utils.py +++ b/tests/virt/utils.py @@ -2,8 +2,9 @@ import logging import shlex +from collections.abc import Generator from contextlib import contextmanager -from typing import Any, Generator +from typing import Any import bitmath from kubernetes.dynamic import DynamicClient @@ -87,7 +88,7 @@ def append_feature_gate_to_hco(feature_gate, resource, client, namespace): hco_namespace=namespace, expected_conditions={ **DEFAULT_HCO_CONDITIONS, - **{"TaintedConfiguration": Resource.Condition.Status.TRUE}, + "TaintedConfiguration": Resource.Condition.Status.TRUE, }, ) yield @@ -429,7 +430,7 @@ def verify_guest_boot_time(vm_list, initial_boot_time): def get_or_create_golden_image_data_source( admin_client: DynamicClient, golden_images_namespace: Namespace, os_dict: dict[str, Any] -) -> Generator[DataSource, None, None]: +) -> Generator[DataSource]: """Retrieves or creates a DataSource object in golden image namespace specified in the OS matrix. Args: diff --git a/utilities/console.py b/utilities/console.py index cd1ec6f8f4..2921caa5f4 100644 --- a/utilities/console.py +++ b/utilities/console.py @@ -16,7 +16,7 @@ LOGGER = logging.getLogger(__name__) -class Console(object): +class Console: def __init__( self, vm: VirtualMachine, @@ -44,10 +44,10 @@ def __init__( self.vm = vm # TODO: `BaseVirtualMachine` does not set cloud-init so the VM is using predefined credentials self.username = ( - username or getattr(self.vm, "login_params", {}).get("username") or self.vm.username # type: ignore[attr-defined] # noqa: E501 + username or getattr(self.vm, "login_params", {}).get("username") or self.vm.username # type: ignore[attr-defined] ) self.password = ( - password or getattr(self.vm, "login_params", {}).get("password") or self.vm.password # type: ignore[attr-defined] # noqa: E501 + password or getattr(self.vm, "login_params", {}).get("password") or self.vm.password # type: ignore[attr-defined] ) self.timeout = timeout self.child = None diff --git a/utilities/constants.py b/utilities/constants.py index 1e38eff4f1..fa12cc505d 100644 --- a/utilities/constants.py +++ b/utilities/constants.py @@ -853,7 +853,7 @@ class NamespacesNames: EXCLUDED_CPU_MODELS_S390X = [ # Below are deprecated & usable models, but violate RHEL 9 ALS (min z14) causing guest to crash (disable-wait) - # Ref: https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/9/html/automatically_installing_rhel/preparing-a-rhel-installation-on-64-bit-ibm-z_rhel-installer#planning-for-installation-on-ibm-z_preparing-a-rhel-installation-on-64-bit-ibm-z # noqa: E501 + # Ref: https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/9/html/automatically_installing_rhel/preparing-a-rhel-installation-on-64-bit-ibm-z_rhel-installer#planning-for-installation-on-ibm-z_preparing-a-rhel-installation-on-64-bit-ibm-z "z114", "z114-base", "z13", diff --git a/utilities/cpu.py b/utilities/cpu.py index c9e70c3cb4..003c7e9728 100644 --- a/utilities/cpu.py +++ b/utilities/cpu.py @@ -1,6 +1,5 @@ import logging import re -from typing import Set from ocp_resources.node import Node from ocp_resources.resource import Resource @@ -16,7 +15,7 @@ HOST_MODEL_CPU_LABEL = f"host-model-cpu.node.{Resource.ApiGroup.KUBEVIRT_IO}" -def get_nodes_cpu_model(nodes: list[Node]) -> dict[str, dict[str, Set[str]]]: +def get_nodes_cpu_model(nodes: list[Node]) -> dict[str, dict[str, set[str]]]: """Checks the CPU model labels on each node and returns a dictionary of nodes and supported CPU models. Args: @@ -28,7 +27,7 @@ def get_nodes_cpu_model(nodes: list[Node]) -> dict[str, dict[str, Set[str]]]: excludes old CPU models. """ - nodes_cpu_model: dict[str, dict[str, Set[str]]] = {"common": {}, "modern": {}} + nodes_cpu_model: dict[str, dict[str, set[str]]] = {"common": {}, "modern": {}} for node in nodes: nodes_cpu_model["common"][node.name] = set() nodes_cpu_model["modern"][node.name] = set() @@ -113,7 +112,7 @@ def find_common_cpu_model_for_live_migration(cluster_cpu: str | None, host_cpu_m return None -def get_common_cpu_from_nodes(cluster_cpus: Set[str]) -> str | None: +def get_common_cpu_from_nodes(cluster_cpus: set[str]) -> str | None: """Receives a set of unique common CPUs between all schedulable nodes and returns one from the set. Args: diff --git a/utilities/guest_support.py b/utilities/guest_support.py index 4c7b7226e2..e42bfc3974 100644 --- a/utilities/guest_support.py +++ b/utilities/guest_support.py @@ -11,7 +11,7 @@ from utilities.virt import VirtualMachineForTests -def assert_windows_efi(vm: "VirtualMachineForTests") -> None: +def assert_windows_efi(vm: VirtualMachineForTests) -> None: """ Verify guest OS is using EFI. @@ -29,7 +29,7 @@ def assert_windows_efi(vm: "VirtualMachineForTests") -> None: assert "\\EFI\\Microsoft\\Boot\\bootmgfw.efi" in out, f"EFI boot not found in path. bcdedit output:\n{out}" -def check_vm_xml_hyperv(vm: "VirtualMachineForTests") -> None: +def check_vm_xml_hyperv(vm: VirtualMachineForTests) -> None: """ Verify HyperV values in VMI XML configuration. @@ -62,7 +62,7 @@ def check_vm_xml_hyperv(vm: "VirtualMachineForTests") -> None: ) -def check_windows_vm_hvinfo(vm: "VirtualMachineForTests") -> None: +def check_windows_vm_hvinfo(vm: VirtualMachineForTests) -> None: """ Verify HyperV values in Windows VM using hvinfo.exe tool. diff --git a/utilities/infra.py b/utilities/infra.py index 3c1bd552bf..20a0c1c174 100644 --- a/utilities/infra.py +++ b/utilities/infra.py @@ -12,10 +12,11 @@ import tempfile import time import zipfile +from collections.abc import Generator from contextlib import contextmanager from functools import cache from subprocess import PIPE, CalledProcessError, Popen -from typing import Any, Generator +from typing import Any import netaddr import requests @@ -692,8 +693,7 @@ def download_and_extract_file_from_cluster(tmpdir, url): with requests.get(url, verify=False, stream=True) as created_request: created_request.raise_for_status() with open(local_file_name, "wb") as file_downloaded: - for chunk in created_request.iter_content(chunk_size=8192): - file_downloaded.write(chunk) + file_downloaded.writelines(created_request.iter_content(chunk_size=8192)) LOGGER.info("Extract the downloaded archive.") if url.endswith(zip_file_extension): archive_file_object = zipfile.ZipFile(file=local_file_name) @@ -849,7 +849,7 @@ def get_node_audit_log_entries(log: str, node: str, log_entry: str) -> tuple[boo return True, lines -def get_node_audit_log_line_dict(logs: list[str], node: str, log_entry: str) -> Generator[dict[str, Any], None, None]: +def get_node_audit_log_line_dict(logs: list[str], node: str, log_entry: str) -> Generator[dict[str, Any]]: """ Parse audit log entries into dictionaries. @@ -1079,8 +1079,7 @@ def get_latest_stable_released_z_stream_info(minor_version: str) -> dict[str, st if build["errata_status"] == "SHIPPED_LIVE" and stable_channel_released_to_prod(channels=build["channels"]): build_version = Version(version=build["csv_version"]) if latest_z_stream: - if build_version > latest_z_stream: - latest_z_stream = build_version + latest_z_stream = max(latest_z_stream, build_version) else: latest_z_stream = build_version return get_build_info_dict(version=str(latest_z_stream)) if latest_z_stream else None diff --git a/utilities/logger.py b/utilities/logger.py index 8e20af730d..f3c591acfe 100644 --- a/utilities/logger.py +++ b/utilities/logger.py @@ -27,7 +27,7 @@ def filter(self, record): class TestLogFormatter(ColoredFormatter): - def formatTime(self, record, datefmt=None): # noqa: N802 + def formatTime(self, record, datefmt=None): return datetime.fromtimestamp(record.created).isoformat() diff --git a/utilities/oadp.py b/utilities/oadp.py index 896f175821..62ff857a1e 100644 --- a/utilities/oadp.py +++ b/utilities/oadp.py @@ -122,7 +122,7 @@ def __init__( self.wait_complete = wait_complete self.timeout = timeout - def __enter__(self) -> "VeleroBackup": + def __enter__(self) -> VeleroBackup: super().__enter__() if self.wait_complete: self.wait_for_status( @@ -148,7 +148,7 @@ def create_rhel_vm( client: DynamicClient, wait_running: bool = True, volume_mode: str | None = None, -) -> Generator["VirtualMachineForTests", None, None]: +) -> Generator[VirtualMachineForTests]: artifactory_secret = None artifactory_config_map = None diff --git a/utilities/operator.py b/utilities/operator.py index 66801b114d..e585b9ffc9 100644 --- a/utilities/operator.py +++ b/utilities/operator.py @@ -293,7 +293,7 @@ def collect_mcp_data_on_update_timeout(machine_config_pools_list, not_matching_m LOGGER.error( f"Out of MCPs {mcps_to_check}, following MCPs {not_matching_mcps} were not at desired " f"condition {condition_type} before timeout.\n" - f"Current MCP status={str({mcp.name: mcp.instance.status.conditions for mcp in machine_config_pools_list})}" + f"Current MCP status={ {mcp.name: mcp.instance.status.conditions for mcp in machine_config_pools_list}!s}" ) collect_ocp_must_gather(since_time=since_time) diff --git a/utilities/sanity.py b/utilities/sanity.py index f8263c3a31..0992ccfd9b 100644 --- a/utilities/sanity.py +++ b/utilities/sanity.py @@ -1,4 +1,4 @@ -from typing import Any, List +from typing import Any from _pytest.fixtures import FixtureRequest from kubernetes.client import ApiException @@ -22,7 +22,7 @@ from utilities.pytest_utils import exit_pytest_execution -def storage_sanity_check(cluster_storage_classes_names: List[str]) -> bool: +def storage_sanity_check(cluster_storage_classes_names: list[str]) -> bool: """ Verify cluster has all expected storage classes from pytest configuration. @@ -204,8 +204,8 @@ def check_vm_creation_capability(admin_client: DynamicClient, namespace: str) -> def cluster_sanity( request: FixtureRequest, admin_client: DynamicClient, - cluster_storage_classes_names: List[str], - nodes: List[Node], + cluster_storage_classes_names: list[str], + nodes: list[Node], hco_namespace: Namespace, junitxml_property: Any | None = None, ) -> None: diff --git a/utilities/storage.py b/utilities/storage.py index be0ae8e9f7..20526eafea 100644 --- a/utilities/storage.py +++ b/utilities/storage.py @@ -2,8 +2,9 @@ import math import os import shlex +from collections.abc import Generator from contextlib import contextmanager -from typing import Any, Dict, Generator +from typing import Any import cachetools.func import kubernetes @@ -180,13 +181,13 @@ def create_dv( def data_volume( namespace: Namespace, client: DynamicClient, - storage_class_matrix: Dict[str, Dict[str, Any]] | None = None, + storage_class_matrix: dict[str, dict[str, Any]] | None = None, storage_class: str | None = None, request: FixtureRequest | None = None, - os_matrix: Dict[str, Dict[str, Any]] | None = None, + os_matrix: dict[str, dict[str, Any]] | None = None, check_dv_exists: bool = False, bind_immediate: bool | None = None, -) -> Generator[DataVolume, None, None]: +) -> Generator[DataVolume]: """ DV creation using create_dv. @@ -304,8 +305,7 @@ def get_downloaded_artifact(remote_name, local_name): with requests.get(url, headers=artifactory_header, verify=False, stream=True) as created_request: created_request.raise_for_status() with open(local_name, "wb") as file_downloaded: - for chunk in created_request.iter_content(chunk_size=8192): - file_downloaded.write(chunk) + file_downloaded.writelines(created_request.iter_content(chunk_size=8192)) try: assert os.path.isfile(local_name) return True diff --git a/utilities/unittests/test_artifactory.py b/utilities/unittests/test_artifactory.py index 58319d8d31..160560ad9d 100644 --- a/utilities/unittests/test_artifactory.py +++ b/utilities/unittests/test_artifactory.py @@ -255,9 +255,8 @@ def test_get_artifactory_header_uses_environment_variable(self): def test_get_artifactory_header_raises_key_error_if_not_set(self): """Test raises KeyError if ARTIFACTORY_TOKEN not set""" - with patch.dict(os.environ, {}, clear=True): - with pytest.raises(KeyError): - get_artifactory_header() + with patch.dict(os.environ, {}, clear=True), pytest.raises(KeyError): + get_artifactory_header() def test_get_artifactory_header_with_special_characters(self): """Test handles tokens with special characters""" @@ -340,16 +339,14 @@ def test_get_artifactory_secret_returns_existing_if_exists(self, mock_base64_enc @patch("utilities.artifactory.Secret") def test_get_artifactory_secret_raises_key_error_if_user_not_set(self, mock_secret_class): """Test raises KeyError if ARTIFACTORY_USER not set""" - with patch.dict(os.environ, {"ARTIFACTORY_TOKEN": "test-token"}, clear=True): - with pytest.raises(KeyError): - get_artifactory_secret(namespace="test-namespace") + with patch.dict(os.environ, {"ARTIFACTORY_TOKEN": "test-token"}, clear=True), pytest.raises(KeyError): + get_artifactory_secret(namespace="test-namespace") @patch("utilities.artifactory.Secret") def test_get_artifactory_secret_raises_key_error_if_token_not_set(self, mock_secret_class): """Test raises KeyError if ARTIFACTORY_TOKEN not set""" - with patch.dict(os.environ, {"ARTIFACTORY_USER": "test-user"}, clear=True): - with pytest.raises(KeyError): - get_artifactory_secret(namespace="test-namespace") + with patch.dict(os.environ, {"ARTIFACTORY_USER": "test-user"}, clear=True), pytest.raises(KeyError): + get_artifactory_secret(namespace="test-namespace") @patch("utilities.artifactory.Secret") @patch("utilities.artifactory.base64_encode_str") diff --git a/utilities/unittests/test_data_collector.py b/utilities/unittests/test_data_collector.py index ea0b01f446..43931fff6d 100644 --- a/utilities/unittests/test_data_collector.py +++ b/utilities/unittests/test_data_collector.py @@ -274,7 +274,7 @@ def test_write_to_file_custom_mode(self, mock_file_open, mock_makedirs): mock_file_open.assert_called_once_with("/test/dir/test.txt", "a") @patch("os.makedirs") - @patch("builtins.open", side_effect=IOError("Permission denied")) + @patch("builtins.open", side_effect=OSError("Permission denied")) @patch("utilities.data_collector.LOGGER") def test_write_to_file_exception_handling(self, mock_logger, mock_file_open, mock_makedirs): """Test write_to_file handles exceptions gracefully""" diff --git a/utilities/unittests/test_guest_support.py b/utilities/unittests/test_guest_support.py index fd7f930e94..d16c91a88d 100644 --- a/utilities/unittests/test_guest_support.py +++ b/utilities/unittests/test_guest_support.py @@ -17,7 +17,7 @@ utilities.virt = mock_virt # Import after setting up mocks to avoid circular dependency -from utilities.guest_support import ( # noqa: E402 +from utilities.guest_support import ( assert_windows_efi, check_vm_xml_hyperv, check_windows_vm_hvinfo, diff --git a/utilities/unittests/test_hco.py b/utilities/unittests/test_hco.py index c855661a60..4c362faf22 100644 --- a/utilities/unittests/test_hco.py +++ b/utilities/unittests/test_hco.py @@ -39,7 +39,7 @@ del sys.modules["utilities.hco"] # Import after setting up mocks to avoid circular dependency -from utilities.hco import ( # noqa: E402 +from utilities.hco import ( DEFAULT_HCO_PROGRESSING_CONDITIONS, HCO_JSONPATCH_ANNOTATION_COMPONENT_DICT, ResourceEditorValidateHCOReconcile, @@ -1103,13 +1103,15 @@ def test_enable_aaq_timeout_waiting_for_pods(self, mock_editor_class, mock_get_p mock_sampler_instance.__iter__ = MagicMock(side_effect=TimeoutExpiredError("Timeout", "aaq-pod")) mock_sampler.return_value = mock_sampler_instance - with pytest.raises(TimeoutExpiredError): - with enabled_aaq_in_hco( + with ( + pytest.raises(TimeoutExpiredError), + enabled_aaq_in_hco( client=mock_client, hco_namespace=mock_namespace, hyperconverged_resource=mock_hco, - ): - pass + ), + ): + pass @patch("utilities.hco.LOGGER") @patch("utilities.hco.TimeoutSampler") diff --git a/utilities/unittests/test_oadp.py b/utilities/unittests/test_oadp.py index 48525fba6d..eddcae0e7a 100644 --- a/utilities/unittests/test_oadp.py +++ b/utilities/unittests/test_oadp.py @@ -2,7 +2,6 @@ """Unit tests for oadp module""" -# flake8: noqa: E402 import sys from re import escape from shlex import quote @@ -481,8 +480,9 @@ def test_create_rhel_vm_cleanup_on_exception( # Make VirtualMachineForTests raise exception on enter mock_vm_class.return_value.__enter__.side_effect = Exception("VM creation failed") - with pytest.raises(Exception, match="VM creation failed"): - with create_rhel_vm( + with ( + pytest.raises(Exception, match="VM creation failed"), + create_rhel_vm( storage_class="ocs-storagecluster-ceph-rbd", namespace="test-namespace", dv_name="test-dv", @@ -490,8 +490,9 @@ def test_create_rhel_vm_cleanup_on_exception( rhel_image="rhel-9.6.qcow2", client=mock_client, wait_running=True, - ): - pass + ), + ): + pass # Cleanup should still be called mock_cleanup.assert_called_once_with(artifactory_secret=mock_secret, artifactory_config_map=mock_config_map) @@ -588,8 +589,9 @@ def test_create_rhel_vm_running_vm_exception( mock_running_vm.side_effect = Exception("VM failed to start") - with pytest.raises(Exception, match="VM failed to start"): - with create_rhel_vm( + with ( + pytest.raises(Exception, match="VM failed to start"), + create_rhel_vm( storage_class="ocs-storagecluster-ceph-rbd", namespace="test-namespace", dv_name="test-dv", @@ -597,8 +599,9 @@ def test_create_rhel_vm_running_vm_exception( rhel_image="rhel-9.6.qcow2", client=mock_client, wait_running=True, - ): - pass + ), + ): + pass # Cleanup should still be called mock_cleanup.assert_called_once_with(artifactory_secret=mock_secret, artifactory_config_map=mock_config_map) diff --git a/utilities/unittests/test_operator.py b/utilities/unittests/test_operator.py index fcab9315ee..ebe4971956 100644 --- a/utilities/unittests/test_operator.py +++ b/utilities/unittests/test_operator.py @@ -9,7 +9,7 @@ from timeout_sampler import TimeoutExpiredError # Import after setting up mocks to avoid circular dependency -from utilities.operator import ( # noqa: E402 +from utilities.operator import ( apply_icsp_idms, approve_install_plan, cluster_with_icsp, diff --git a/utilities/unittests/test_pytest_matrix_utils.py b/utilities/unittests/test_pytest_matrix_utils.py index 0bbbe0417e..de6a1b21ed 100644 --- a/utilities/unittests/test_pytest_matrix_utils.py +++ b/utilities/unittests/test_pytest_matrix_utils.py @@ -4,7 +4,7 @@ from unittest.mock import MagicMock, patch -from utilities.pytest_matrix_utils import ( # noqa: E402 +from utilities.pytest_matrix_utils import ( hpp_matrix, immediate_matrix, online_resize_matrix, diff --git a/utilities/unittests/test_pytest_utils.py b/utilities/unittests/test_pytest_utils.py index b2bb0522b2..5a4b139a0d 100644 --- a/utilities/unittests/test_pytest_utils.py +++ b/utilities/unittests/test_pytest_utils.py @@ -791,9 +791,7 @@ def test_get_artifactory_server_url_default_server_empty_dict(self, mock_get_sec mock_session.config.getoption.return_value = False def mock_secret_side_effect(secret_name, session): - if secret_name == "artifactory_servers": - return {} - elif secret_name == "default_artifactory_server": + if secret_name == "artifactory_servers" or secret_name == "default_artifactory_server": return {} mock_get_secret.side_effect = mock_secret_side_effect diff --git a/utilities/unittests/test_ssp.py b/utilities/unittests/test_ssp.py index 296f89d519..08fd5abed4 100644 --- a/utilities/unittests/test_ssp.py +++ b/utilities/unittests/test_ssp.py @@ -28,7 +28,7 @@ del sys.modules["utilities.ssp"] # Import after setting up mocks to avoid circular dependency -from utilities.ssp import ( # noqa: E402 +from utilities.ssp import ( cluster_instance_type_for_hot_plug, create_custom_template_from_url, get_cim_instance_json, diff --git a/utilities/virt.py b/utilities/virt.py index 44bbec8244..4b9002276a 100644 --- a/utilities/virt.py +++ b/utilities/virt.py @@ -13,7 +13,7 @@ from functools import cache from json import JSONDecodeError from subprocess import run -from typing import TYPE_CHECKING, Any, Dict, List, Optional +from typing import TYPE_CHECKING, Any import bitmath import jinja2 @@ -1667,7 +1667,7 @@ def generate_dict_from_yaml_template(stream, **kwargs): # Find all template variables template_vars = [i.split()[1] for i in re.findall(r"{{ .* }}", data)] for var in template_vars: - if var not in kwargs.keys(): + if var not in kwargs: raise MissingTemplateVariables(var=var, template=data) template = jinja2.Template(data) out = template.render(**kwargs) @@ -2587,7 +2587,7 @@ def validate_pause_unpause_linux_vm(vm: VirtualMachineForTests, pre_pause_pid: i ) -def check_vm_xml_smbios(vm: VirtualMachineForTests, cm_values: Dict[str, str]) -> None: +def check_vm_xml_smbios(vm: VirtualMachineForTests, cm_values: dict[str, str]) -> None: """ Verify SMBIOS on VM XML [sysinfo type=smbios][system] match kubevirt-config config map. @@ -2640,7 +2640,7 @@ def update_vm_efi_spec_and_restart( restart_vm_wait_for_running_vm(vm=vm, wait_for_interfaces=wait_for_interfaces) -def delete_guestosinfo_keys(data: Dict[str, Any]) -> Dict[str, Any]: +def delete_guestosinfo_keys(data: dict[str, Any]) -> dict[str, Any]: """ supportedCommands - removed as the data is used for internal guest agent validations fsInfo, userList - checked in validate_fs_info_virtctl_vs_linux_os / validate_user_info_virtctl_vs_linux_os @@ -2761,7 +2761,7 @@ def guest_reboot(vm: VirtualMachineForTests, os_type: str) -> None: run_os_command(vm=vm, command=commands["reboot"][os_type]) -def run_os_command(vm: VirtualMachineForTests, command: str) -> Optional[str]: +def run_os_command(vm: VirtualMachineForTests, command: str) -> str | None: try: return run_ssh_commands( host=vm.ssh_exec, @@ -2790,7 +2790,7 @@ def wait_for_user_agent_down(vm: VirtualMachineForTests, timeout: int) -> None: break -def get_virt_handler_pods(client: DynamicClient, namespace: Namespace) -> List[Pod]: +def get_virt_handler_pods(client: DynamicClient, namespace: Namespace) -> list[Pod]: return utilities.infra.get_pods( client=client, namespace=namespace, @@ -2800,7 +2800,7 @@ def get_virt_handler_pods(client: DynamicClient, namespace: Namespace) -> List[P def check_virt_handler_pods_for_migration_network( client: DynamicClient, namespace: Namespace, network_name: str, migration_network: bool = True -) -> List[Pod]: +) -> list[Pod]: """ Checks whether virt-handler pods have migration network. @@ -2822,9 +2822,7 @@ def check_virt_handler_pods_for_migration_network( f"{Pod.ApiGroup.K8S_V1_CNI_CNCF_IO}/networks", "" ) migration_network_on_pod = pod_network_annotations.split("@")[0] == network_name - if migration_network and migration_network_on_pod: - verified_pods_list.append(pod) - elif not migration_network and not migration_network_on_pod: + if migration_network and migration_network_on_pod or not migration_network and not migration_network_on_pod: verified_pods_list.append(pod) return verified_pods_list