diff --git a/.ansible-lint b/.ansible-lint index 265a1ec1..5d60ca90 100644 --- a/.ansible-lint +++ b/.ansible-lint @@ -9,3 +9,4 @@ exclude_paths: - examples/vm_os_upgrade/main.yml - .github/workflows - changelogs + - .tox diff --git a/.github/workflows/linters.yml b/.github/workflows/linters.yml new file mode 100644 index 00000000..cb9e7bed --- /dev/null +++ b/.github/workflows/linters.yml @@ -0,0 +1,16 @@ +--- +# from https://github.com/ansible-collections/amazon.aws/ +name: changelog and linters + +# on: [workflow_call] # allow this workflow to be called from other workflows +on: + push: + pull_request: + +jobs: + linters: + uses: ansible-network/github_actions/.github/workflows/tox.yml@main + with: + envname: "" + labelname: lint +# 12 diff --git a/.gitignore b/.gitignore index e972f55c..5e2f99e3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ child-pipeline-gitlab-ci.yml # developer instance, including credentials tests/integration/integration_config.yml tests/integration/inventory +collections docs/build docs/source/modules diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 024f261a..271897fb 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -147,6 +147,18 @@ sanity: ## Run sanity tests units: ## Run unit tests ``` +Tox based testing was added as we want to use linters from ansible-network/github_actions. +Sample commands : + +``` +tox list +tox -e ansible-sanity +tox -m lint +tox -e flake8-lint,pylint +tox -e black,flake8 # will reformat code +tox -e ansible2.18-py312-with_constraints +``` + If you want to run tests with a single python version (e.g. not with whole test matrix), use: ``` diff --git a/plugins/doc_fragments/cloud_init.py b/plugins/doc_fragments/cloud_init.py index 23be24aa..bd9c739c 100644 --- a/plugins/doc_fragments/cloud_init.py +++ b/plugins/doc_fragments/cloud_init.py @@ -4,7 +4,9 @@ # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type diff --git a/plugins/doc_fragments/cluster_instance.py b/plugins/doc_fragments/cluster_instance.py index 65e4e7ca..3ac25d33 100644 --- a/plugins/doc_fragments/cluster_instance.py +++ b/plugins/doc_fragments/cluster_instance.py @@ -4,7 +4,9 @@ # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type diff --git a/plugins/doc_fragments/endpoint.py b/plugins/doc_fragments/endpoint.py index f502480f..11bdcc66 100644 --- a/plugins/doc_fragments/endpoint.py +++ b/plugins/doc_fragments/endpoint.py @@ -4,7 +4,9 @@ # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type diff --git a/plugins/doc_fragments/force_reboot.py b/plugins/doc_fragments/force_reboot.py index 03e49bec..0198dc3e 100644 --- a/plugins/doc_fragments/force_reboot.py +++ b/plugins/doc_fragments/force_reboot.py @@ -4,7 +4,9 @@ # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type diff --git a/plugins/doc_fragments/machine_type.py b/plugins/doc_fragments/machine_type.py index cf5ce3d8..188c4030 100644 --- a/plugins/doc_fragments/machine_type.py +++ b/plugins/doc_fragments/machine_type.py @@ -4,7 +4,9 @@ # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type diff --git a/plugins/doc_fragments/vm_name.py b/plugins/doc_fragments/vm_name.py index 866e749d..dd7c9e1f 100644 --- a/plugins/doc_fragments/vm_name.py +++ b/plugins/doc_fragments/vm_name.py @@ -4,7 +4,9 @@ # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type diff --git a/plugins/inventory/hypercore.py b/plugins/inventory/hypercore.py index 35c15f77..62cb4411 100644 --- a/plugins/inventory/hypercore.py +++ b/plugins/inventory/hypercore.py @@ -3,7 +3,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -134,13 +136,18 @@ # } """ -from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable -import yaml import logging +import os + +import yaml + +from ansible.plugins.inventory import BaseInventoryPlugin +from ansible.plugins.inventory import Cacheable +from ansible.plugins.inventory import Constructable + from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient -import os logging.basicConfig(level=logging.ERROR) logger = logging.getLogger(__name__) diff --git a/plugins/module_utils/arguments.py b/plugins/module_utils/arguments.py index 18a9f0d9..7c3eb128 100644 --- a/plugins/module_utils/arguments.py +++ b/plugins/module_utils/arguments.py @@ -3,13 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type -from ansible.module_utils.basic import env_fallback from typing import Any + +from ansible.module_utils.basic import env_fallback + from ..module_utils.client import AuthMethod # TODO - env from /etc/environment is loaded diff --git a/plugins/module_utils/client.py b/plugins/module_utils/client.py index facfe357..c56806eb 100644 --- a/plugins/module_utils/client.py +++ b/plugins/module_utils/client.py @@ -3,30 +3,33 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type +import enum import json import os import ssl -from typing import Any, Optional, Union from io import BufferedReader -import enum - +from typing import Any +from typing import Optional +from typing import Union + +from ansible.module_utils.six.moves.urllib.error import HTTPError +from ansible.module_utils.six.moves.urllib.error import URLError +from ansible.module_utils.six.moves.urllib.parse import quote +from ansible.module_utils.six.moves.urllib.parse import urlencode from ansible.module_utils.urls import Request -from .errors import ( - AuthError, - ScaleComputingError, - UnexpectedAPIResponse, - ApiResponseNotJson, -) from ..module_utils.typed_classes import TypedClusterInstance - -from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError -from ansible.module_utils.six.moves.urllib.parse import urlencode, quote +from .errors import ApiResponseNotJson +from .errors import AuthError +from .errors import ScaleComputingError +from .errors import UnexpectedAPIResponse DEFAULT_HEADERS = dict(Accept="application/json") @@ -56,15 +59,11 @@ class Response: # Response(raw_resp) would be simpler. # How is this used in other projects? Jure? # Maybe we need/want both. - def __init__( - self, status: int, data: Any, headers: Optional[dict[Any, Any]] = None - ): + def __init__(self, status: int, data: Any, headers: Optional[dict[Any, Any]] = None): self.status = status self.data = data # [('h1', 'v1'), ('H2', 'V2')] -> {'h1': 'v1', 'h2': 'V2'} - self.headers = ( - dict((k.lower(), v) for k, v in dict(headers).items()) if headers else {} - ) + self.headers = dict((k.lower(), v) for k, v in dict(headers).items()) if headers else {} self._json = None @@ -89,8 +88,7 @@ def __init__( ): if not (host or "").startswith(("https://", "http://")): raise ScaleComputingError( - "Invalid instance host value: '{0}'. " - "Value must start with 'https://' or 'http://'".format(host) + f"Invalid instance host value: '{host}'. Value must start with 'https://' or 'http://'" ) self.host = host @@ -202,9 +200,7 @@ def _request_no_log( # Wrong username/password, or expired access token if e.code == 401: raise AuthError( - "Failed to authenticate with the instance: {0} {1}".format( - e.code, e.reason - ), + f"Failed to authenticate with the instance: {e.code} {e.reason}", ) # Other HTTP error codes do not necessarily mean errors. # This is for the caller to decide. @@ -212,23 +208,14 @@ def _request_no_log( except URLError as e: # TODO: Add other errors here; we need to handle them in modules. # TimeoutError is handled in the rest_client - if ( - e.args - and isinstance(e.args, tuple) - and isinstance(e.args[0], ConnectionRefusedError) - ): + if e.args and isinstance(e.args, tuple) and isinstance(e.args[0], ConnectionRefusedError): raise ConnectionRefusedError(e.reason) - elif ( - e.args - and isinstance(e.args, tuple) - and isinstance(e.args[0], ConnectionResetError) - ): + elif e.args and isinstance(e.args, tuple) and isinstance(e.args[0], ConnectionResetError): raise ConnectionResetError(e.reason) elif ( e.args and isinstance(e.args, tuple) - and type(e.args[0]) - in [ssl.SSLEOFError, ssl.SSLZeroReturnError, ssl.SSLSyscallError] + and type(e.args[0]) in [ssl.SSLEOFError, ssl.SSLZeroReturnError, ssl.SSLSyscallError] ): raise type(e.args[0])(e) raise ScaleComputingError(e.reason) @@ -246,15 +233,13 @@ def request( ) -> Response: # Make sure we only have one kind of payload if data is not None and binary_data is not None: - raise AssertionError( - "Cannot have JSON and binary payload in a single request." - ) + raise AssertionError("Cannot have JSON and binary payload in a single request.") escaped_path = quote(path.strip("/")) if escaped_path: escaped_path = "/" + escaped_path - url = "{0}{1}".format(self.host, escaped_path) + url = f"{self.host}{escaped_path}" if query: - url = "{0}?{1}".format(url, urlencode(query)) + url = f"{url}?{urlencode(query)}" headers = dict(headers or DEFAULT_HEADERS, **self.auth_header) if data is not None: headers["Content-type"] = "application/json" @@ -267,9 +252,7 @@ def request( ) elif binary_data is not None: headers["Content-type"] = "application/octet-stream" - return self._request( - method, url, data=binary_data, headers=headers, timeout=timeout - ) + return self._request(method, url, data=binary_data, headers=headers, timeout=timeout) return self._request(method, url, data=data, headers=headers, timeout=timeout) def get( diff --git a/plugins/module_utils/cluster.py b/plugins/module_utils/cluster.py index 6bce9289..fcc42ce2 100644 --- a/plugins/module_utils/cluster.py +++ b/plugins/module_utils/cluster.py @@ -3,18 +3,22 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type from time import sleep -from ..module_utils.utils import PayloadMapper -from ..module_utils.rest_client import RestClient -from ..module_utils.errors import ScaleTimeoutError -from ..module_utils.typed_classes import TypedClusterToAnsible, TypedTaskTag from typing import Any +from ..module_utils.errors import ScaleTimeoutError +from ..module_utils.rest_client import RestClient +from ..module_utils.typed_classes import TypedClusterToAnsible +from ..module_utils.typed_classes import TypedTaskTag +from ..module_utils.utils import PayloadMapper + class Cluster(PayloadMapper): def __init__(self, uuid: str, name: str, icos_version: str): @@ -61,23 +65,15 @@ def __eq__(self, other: object) -> bool: @classmethod def get(cls, rest_client: RestClient, must_exist: bool = True) -> Cluster: - hypercore_dict = rest_client.get_record( - "/rest/v1/Cluster", must_exist=must_exist - ) + hypercore_dict = rest_client.get_record("/rest/v1/Cluster", must_exist=must_exist) cluster = cls.from_hypercore(hypercore_dict) # type: ignore # cluster never None return cluster - def update_name( - self, rest_client: RestClient, name_new: str, check_mode: bool = False - ) -> TypedTaskTag: - return rest_client.update_record( - f"/rest/v1/Cluster/{self.uuid}", dict(clusterName=name_new), check_mode - ) + def update_name(self, rest_client: RestClient, name_new: str, check_mode: bool = False) -> TypedTaskTag: + return rest_client.update_record(f"/rest/v1/Cluster/{self.uuid}", dict(clusterName=name_new), check_mode) @staticmethod - def shutdown( - rest_client: RestClient, force_shutdown: bool = False, check_mode: bool = False - ) -> None: + def shutdown(rest_client: RestClient, force_shutdown: bool = False, check_mode: bool = False) -> None: try: rest_client.create_record( "/rest/v1/Cluster/shutdown", diff --git a/plugins/module_utils/disk.py b/plugins/module_utils/disk.py index d6d03bd0..588f4297 100644 --- a/plugins/module_utils/disk.py +++ b/plugins/module_utils/disk.py @@ -4,16 +4,19 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type -from ..module_utils.utils import PayloadMapper +from typing import Any +from typing import Optional + from ..module_utils import errors from ..module_utils.rest_client import RestClient -from typing import Optional, Any - +from ..module_utils.utils import PayloadMapper TIERING_PRIORITY_MAPPING_TO_HYPERCORE = { 0: 0, @@ -50,7 +53,7 @@ class Disk(PayloadMapper): def __init__( self, - type, + disk_type, slot, uuid=None, vm_uuid=None, @@ -64,7 +67,7 @@ def __init__( ): self.uuid = uuid self.vm_uuid = vm_uuid - self.type = type + self.type = disk_type self.cache_mode = cache_mode self.size = size self.slot = slot @@ -115,7 +118,7 @@ def from_hypercore(cls, hypercore_data: dict[Any, Any]) -> Optional[Disk]: return cls( uuid=hypercore_data["uuid"], vm_uuid=hypercore_data["virDomainUUID"], - type=hypercore_data["type"].lower(), + disk_type=hypercore_data["type"].lower(), cache_mode=hypercore_data["cacheMode"].lower(), size=hypercore_data["capacity"], slot=hypercore_data["slot"], @@ -123,11 +126,8 @@ def from_hypercore(cls, hypercore_data: dict[Any, Any]) -> Optional[Disk]: disable_snapshotting=hypercore_data["disableSnapshotting"], # Hypercore sometimes returns values outside the mapping table, so we set it to default. tiering_priority_factor=( - TIERING_PRIORITY_MAPPING_FROM_HYPERCORE[ - hypercore_data["tieringPriorityFactor"] - ] - if hypercore_data["tieringPriorityFactor"] - in TIERING_PRIORITY_MAPPING_FROM_HYPERCORE + TIERING_PRIORITY_MAPPING_FROM_HYPERCORE[hypercore_data["tieringPriorityFactor"]] + if hypercore_data["tieringPriorityFactor"] in TIERING_PRIORITY_MAPPING_FROM_HYPERCORE else TIERING_PRIORITY_DEFAULT ), mount_points=hypercore_data["mountPoints"], @@ -153,7 +153,7 @@ def from_ansible(cls, ansible_data): else: size = None return cls( - type=disk_type, + disk_type=disk_type, slot=ansible_data["disk_slot"], size=size, cache_mode=ansible_data.get("cache_mode", None), @@ -222,10 +222,6 @@ def needs_reboot(self, action: str, desired_disk=None) -> bool: return False @classmethod - def get_by_uuid( - cls, uuid: str, rest_client: RestClient, must_exist: bool - ) -> Optional[Disk]: - hypercore_dict = rest_client.get_record( - f"/rest/v1/VirDomainBlockDevice/{uuid}", must_exist=must_exist - ) + def get_by_uuid(cls, uuid: str, rest_client: RestClient, must_exist: bool) -> Optional[Disk]: + hypercore_dict = rest_client.get_record(f"/rest/v1/VirDomainBlockDevice/{uuid}", must_exist=must_exist) return cls.from_hypercore(hypercore_dict) diff --git a/plugins/module_utils/dns_config.py b/plugins/module_utils/dns_config.py index 7051cb64..e5871c87 100644 --- a/plugins/module_utils/dns_config.py +++ b/plugins/module_utils/dns_config.py @@ -3,12 +3,15 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type -from ..module_utils.utils import PayloadMapper, get_query from ..module_utils import errors +from ..module_utils.utils import PayloadMapper +from ..module_utils.utils import get_query class DNSConfig(PayloadMapper): @@ -73,9 +76,7 @@ def __eq__(self, other): @classmethod def get_by_uuid(cls, ansible_dict, rest_client, must_exist=False): query = get_query(ansible_dict, "uuid", ansible_hypercore_map=dict(uuid="uuid")) - hypercore_dict = rest_client.get_record( - "/rest/v1/DNSConfig", query, must_exist=must_exist - ) + hypercore_dict = rest_client.get_record("/rest/v1/DNSConfig", query, must_exist=must_exist) dns_config_from_hypercore = DNSConfig.from_hypercore(hypercore_dict) return dns_config_from_hypercore diff --git a/plugins/module_utils/email_alert.py b/plugins/module_utils/email_alert.py index 6b3a4e10..36d832d8 100644 --- a/plugins/module_utils/email_alert.py +++ b/plugins/module_utils/email_alert.py @@ -3,22 +3,27 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type -from .rest_client import RestClient +from typing import Any +from typing import Dict +from typing import List +from typing import Optional +from typing import Union -# from .client import Client -from ..module_utils.utils import PayloadMapper, get_query +from ..module_utils.typed_classes import TypedEmailAlertFromAnsible +from ..module_utils.typed_classes import TypedEmailAlertToAnsible +from ..module_utils.typed_classes import TypedTaskTag -from ..module_utils.typed_classes import ( - TypedTaskTag, - TypedEmailAlertToAnsible, - TypedEmailAlertFromAnsible, -) -from typing import Union, Any, Dict, Optional, List +# from .client import Client +from ..module_utils.utils import PayloadMapper +from ..module_utils.utils import get_query +from .rest_client import RestClient class EmailAlert(PayloadMapper): @@ -100,9 +105,7 @@ def get_by_uuid( must_exist: bool = False, ) -> Optional[EmailAlert]: query = get_query(ansible_dict, "uuid", ansible_hypercore_map=dict(uuid="uuid")) - hypercore_dict = rest_client.get_record( - "/rest/v1/AlertEmailTarget", query, must_exist=must_exist - ) + hypercore_dict = rest_client.get_record("/rest/v1/AlertEmailTarget", query, must_exist=must_exist) alert_email_from_hypercore = cls.from_hypercore(hypercore_dict) return alert_email_from_hypercore @@ -118,9 +121,7 @@ def get_by_email( "email", ansible_hypercore_map=dict(email="emailAddress"), ) - hypercore_dict = rest_client.get_record( - "/rest/v1/AlertEmailTarget", query, must_exist=must_exist - ) + hypercore_dict = rest_client.get_record("/rest/v1/AlertEmailTarget", query, must_exist=must_exist) alert_email_from_hypercore = EmailAlert.from_hypercore(hypercore_dict) return alert_email_from_hypercore @@ -136,13 +137,9 @@ def list_by_email( "email", ansible_hypercore_map=dict(email="emailAddress"), ) - hypercore_dict_list = rest_client.list_records( - "/rest/v1/AlertEmailTarget", query - ) + hypercore_dict_list = rest_client.list_records("/rest/v1/AlertEmailTarget", query) - alert_email_from_hypercore_list = [ - EmailAlert.from_hypercore(hc_dict) for hc_dict in hypercore_dict_list - ] + alert_email_from_hypercore_list = [EmailAlert.from_hypercore(hc_dict) for hc_dict in hypercore_dict_list] return alert_email_from_hypercore_list @classmethod @@ -164,9 +161,7 @@ def create( payload: Dict[Any, Any], check_mode: bool = False, ): - task_tag = rest_client.create_record( - "/rest/v1/AlertEmailTarget/", payload, check_mode - ) + task_tag = rest_client.create_record("/rest/v1/AlertEmailTarget/", payload, check_mode) email_alert = cls.get_by_uuid( dict(uuid=task_tag["createdUUID"]), rest_client, @@ -180,9 +175,7 @@ def update( payload: Dict[Any, Any], check_mode: bool = False, ) -> None: - rest_client.update_record( - f"/rest/v1/AlertEmailTarget/{self.uuid}", payload, check_mode - ) + rest_client.update_record(f"/rest/v1/AlertEmailTarget/{self.uuid}", payload, check_mode) def delete( self, @@ -195,7 +188,5 @@ def test( self, rest_client: RestClient, ) -> TypedTaskTag: - response = rest_client.client.post( - f"/rest/v1/AlertEmailTarget/{self.uuid}/test", None - ) + response = rest_client.client.post(f"/rest/v1/AlertEmailTarget/{self.uuid}/test", None) return response diff --git a/plugins/module_utils/errors.py b/plugins/module_utils/errors.py index 9b92c344..4227ac76 100644 --- a/plugins/module_utils/errors.py +++ b/plugins/module_utils/errors.py @@ -3,12 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import json -from typing import Union, Dict, Any +from typing import Any +from typing import Dict +from typing import Union + from ansible.module_utils.urls import Request @@ -28,71 +33,65 @@ def __init__(self, message: str): class UnexpectedAPIResponse(ScaleComputingError): def __init__(self, response: Request): - self.message = "Unexpected response - {0} {1}".format( - response.status, response.data - ) + self.message = f"Unexpected response - {response.status} {response.data}" self.response_status = response.status super(UnexpectedAPIResponse, self).__init__(self.message) class InvalidUuidFormatError(ScaleComputingError): def __init__(self, data: Union[str, Exception]): - self.message = "Invalid UUID - {0}".format(data) + self.message = f"Invalid UUID - {data}" super(InvalidUuidFormatError, self).__init__(self.message) # In-case function parameter is optional but required class MissingFunctionParameter(ScaleComputingError): def __init__(self, data: Union[str, Exception]): - self.message = "Missing parameter - {0}".format(data) + self.message = f"Missing parameter - {data}" super(MissingFunctionParameter, self).__init__(self.message) # In-case argument spec doesn't catch exception class MissingValueAnsible(ScaleComputingError): def __init__(self, data: Union[str, Exception]): - self.message = "Missing value - {0}".format(data) + self.message = f"Missing value - {data}" super(MissingValueAnsible, self).__init__(self.message) # In-case argument spec doesn't catch exception class MissingValueHypercore(ScaleComputingError): def __init__(self, data: Union[str, Exception]): - self.message = "Missing values from hypercore API - {0}".format(data) + self.message = f"Missing values from hypercore API - {data}" super(MissingValueHypercore, self).__init__(self.message) class DeviceNotUnique(ScaleComputingError): def __init__(self, data: Union[str, Exception]): - self.message = "Device is not unique - {0} - already exists".format(data) + self.message = f"Device is not unique - {data} - already exists" super(DeviceNotUnique, self).__init__(self.message) class VMNotFound(ScaleComputingError): def __init__(self, data: Union[str, Exception]): - self.message = "Virtual machine - {0} - not found".format(data) + self.message = f"Virtual machine - {data} - not found" super(VMNotFound, self).__init__(self.message) class ReplicationNotUnique(ScaleComputingError): def __init__(self, data: Union[str, Exception]): - self.message = ( - "There is already a replication on - {0} - virtual machine".format(data) - ) + self.message = f"There is already a replication on - {data} - virtual machine" super(ReplicationNotUnique, self).__init__(self.message) class ClusterConnectionNotFound(ScaleComputingError): def __init__(self, data: Union[str, Exception]): - self.message = "No cluster connection found - {0}".format(data) + self.message = f"No cluster connection found - {data}" super(ClusterConnectionNotFound, self).__init__(self.message) class SMBServerNotFound(ScaleComputingError): def __init__(self, data: Union[str, Exception]): - self.message = "SMB server is either not connected or not in the same network - {0}".format( - data - ) + self.message = f"SMB server is either not connected or not in the same network - {data}" super(SMBServerNotFound, self).__init__(self.message) @@ -104,7 +103,7 @@ def __init__(self) -> None: class SupportTunnelError(ScaleComputingError): def __init__(self, data: Union[str, Exception]): - self.message = "{0}".format(data) + self.message = f"{data}" super(SupportTunnelError, self).__init__(self.message) diff --git a/plugins/module_utils/hypercore_version.py b/plugins/module_utils/hypercore_version.py index cd46fd23..91cd14f0 100644 --- a/plugins/module_utils/hypercore_version.py +++ b/plugins/module_utils/hypercore_version.py @@ -3,24 +3,27 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type import operator import re from functools import total_ordering -from ansible.module_utils.basic import AnsibleModule +from typing import Any from typing import List -from ..module_utils.utils import PayloadMapper +from typing import Optional + +from ansible.module_utils.basic import AnsibleModule + from ..module_utils.rest_client import RestClient -from ..module_utils.typed_classes import ( - TypedUpdateToAnsible, - TypedUpdateStatusToAnsible, - TypedTaskTag, -) -from typing import Any, Optional +from ..module_utils.typed_classes import TypedTaskTag +from ..module_utils.typed_classes import TypedUpdateStatusToAnsible +from ..module_utils.typed_classes import TypedUpdateToAnsible +from ..module_utils.utils import PayloadMapper class HyperCoreVersion: @@ -39,14 +42,8 @@ def __init__(self, rest_client: RestClient): def version(self) -> str: if not self._version: record = self._rest_client.get_record("/rest/v1/Cluster") - if ( - record is None - or "icosVersion" not in record - or not isinstance(record["icosVersion"], str) - ): - raise AssertionError( - "HyperCore version not found in REST API response." - ) + if record is None or "icosVersion" not in record or not isinstance(record["icosVersion"], str): + raise AssertionError("HyperCore version not found in REST API response.") self._version = record["icosVersion"] return self._version @@ -179,9 +176,7 @@ def from_ansible(cls, ansible_data: dict[Any, Any]) -> None: pass @classmethod - def from_hypercore( - cls, hypercore_data: Optional[dict[Any, Any]] - ) -> Optional[Update]: + def from_hypercore(cls, hypercore_data: Optional[dict[Any, Any]]) -> Optional[Update]: if not hypercore_data: return None return cls( @@ -240,9 +235,7 @@ def get( ) -> Optional[Update]: # api has a bug - the endpoint "/rest/v1/Update/{uuid}" returns a list of all available updates (and uuid can actually be anything), # that is why query is used - update = rest_client.get_record( - f"/rest/v1/Update/{uuid}", query=dict(uuid=uuid), must_exist=must_exist - ) + update = rest_client.get_record(f"/rest/v1/Update/{uuid}", query=dict(uuid=uuid), must_exist=must_exist) return cls.from_hypercore(update) @classmethod @@ -252,9 +245,7 @@ def apply_update( version: str, check_mode: bool = False, ) -> TypedTaskTag: - return rest_client.create_record( - f"/rest/v1/Update/{version}/apply", payload=None, check_mode=check_mode - ) + return rest_client.create_record(f"/rest/v1/Update/{version}/apply", payload=None, check_mode=check_mode) class UpdateStatus(PayloadMapper): @@ -297,9 +288,7 @@ def from_hypercore(cls, hypercore_data: dict[Any, Any]) -> UpdateStatus: to_build=hypercore_data["updateStatus"].get("toBuild"), to_version=hypercore_data["updateStatus"].get("toVersion"), percent=hypercore_data["updateStatus"].get("percent"), - update_status_details=hypercore_data["updateStatus"]["status"].get( - "statusdetails" - ), + update_status_details=hypercore_data["updateStatus"]["status"].get("statusdetails"), usernotes=hypercore_data["updateStatus"]["status"].get("usernotes"), ) diff --git a/plugins/module_utils/iso.py b/plugins/module_utils/iso.py index e00a58cc..28207dc8 100644 --- a/plugins/module_utils/iso.py +++ b/plugins/module_utils/iso.py @@ -4,7 +4,9 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -14,9 +16,7 @@ class ISO(PayloadMapper): # Variables in ISO are written in ansible-native format - def __init__( - self, name, uuid=None, size=-1, mounts=None, ready_for_insert=False, path=None - ): + def __init__(self, name, uuid=None, size=-1, mounts=None, ready_for_insert=False, path=None): if mounts is None: mounts = [] self.uuid = uuid @@ -45,10 +45,7 @@ def from_hypercore(cls, hypercore_data): uuid=hypercore_data["uuid"], name=hypercore_data["name"], size=hypercore_data["size"], - mounts=[ - dict(vm_uuid=mount["vmUUID"], vm_name=mount["vmName"]) - for mount in hypercore_data["mounts"] - ], + mounts=[dict(vm_uuid=mount["vmUUID"], vm_name=mount["vmName"]) for mount in hypercore_data["mounts"]], ready_for_insert=hypercore_data["readyForInsert"], path=hypercore_data["path"], ) @@ -93,11 +90,7 @@ def __str__(self): return super().__str__() def build_iso_post_paylaod(self): - return { - key: value - for key, value in self.to_hypercore().items() - if key in ("name", "size", "readyForInsert") - } + return {key: value for key, value in self.to_hypercore().items() if key in ("name", "size", "readyForInsert")} @classmethod def get_by_name(cls, ansible_dict, rest_client, must_exist=False): @@ -106,9 +99,7 @@ def get_by_name(cls, ansible_dict, rest_client, must_exist=False): the record exists. If there is no record with such name, None is returned. """ query = get_query(ansible_dict, "name", ansible_hypercore_map=dict(name="name")) - hypercore_dict = rest_client.get_record( - "/rest/v1/ISO", query, must_exist=must_exist - ) + hypercore_dict = rest_client.get_record("/rest/v1/ISO", query, must_exist=must_exist) iso_from_hypercore = ISO.from_hypercore(hypercore_dict) return iso_from_hypercore diff --git a/plugins/module_utils/nic.py b/plugins/module_utils/nic.py index 215522c9..87196154 100644 --- a/plugins/module_utils/nic.py +++ b/plugins/module_utils/nic.py @@ -4,13 +4,16 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type from typing import Optional -from ..module_utils.utils import PayloadMapper + from ..module_utils import errors +from ..module_utils.utils import PayloadMapper FROM_HYPERCORE_TO_ANSIBLE_NIC_TYPE = { None: None, @@ -18,9 +21,7 @@ "VIRTIO": "virtio", "INTEL_E1000": "INTEL_E1000", } -FROM_ANSIBLE_TO_HYPERCORE_NIC_TYPE = { - v: k for k, v in FROM_HYPERCORE_TO_ANSIBLE_NIC_TYPE.items() -} +FROM_ANSIBLE_TO_HYPERCORE_NIC_TYPE = {v: k for k, v in FROM_HYPERCORE_TO_ANSIBLE_NIC_TYPE.items()} # Maybe create enums.py or scale_enums.py and move all enum classes there? @Jure @Justin @@ -53,29 +54,13 @@ def __eq__(self, other): elif other.vlan_new is not None and not other.mac_new: return self.vlan == other.vlan_new and self.type == other.type elif self.mac_new and self.vlan_new is None: - return ( - self.vlan == other.vlan - and self.type == other.type - and self.mac_new == other.mac - ) + return self.vlan == other.vlan and self.type == other.type and self.mac_new == other.mac elif other.mac_new and other.vlan_new is None: - return ( - self.vlan == other.vlan - and self.type == other.type - and self.mac == other.mac_new - ) + return self.vlan == other.vlan and self.type == other.type and self.mac == other.mac_new elif self.vlan_new is not None and self.mac_new: - return ( - self.vlan_new == other.vlan - and self.type == other.type - and self.mac_new == other.mac - ) + return self.vlan_new == other.vlan and self.type == other.type and self.mac_new == other.mac elif other.vlan_new is not None and other.mac_new: - return ( - self.vlan == other.vlan_new - and self.type == other.type - and self.mac == other.mac_new - ) + return self.vlan == other.vlan_new and self.type == other.type and self.mac == other.mac_new return self.vlan == other.vlan and self.type == other.type @classmethod diff --git a/plugins/module_utils/node.py b/plugins/module_utils/node.py index 069906b1..2c64aeb4 100644 --- a/plugins/module_utils/node.py +++ b/plugins/module_utils/node.py @@ -4,7 +4,9 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -61,8 +63,6 @@ def __eq__(self, other): @classmethod def get_node(cls, query, rest_client, must_exist=False): - hypercore_dict = rest_client.get_record( - "/rest/v1/Node", query, must_exist=must_exist - ) + hypercore_dict = rest_client.get_record("/rest/v1/Node", query, must_exist=must_exist) node_from_hypercore = cls.from_hypercore(hypercore_dict) return node_from_hypercore diff --git a/plugins/module_utils/oidc.py b/plugins/module_utils/oidc.py index 4147e5b3..136923f2 100644 --- a/plugins/module_utils/oidc.py +++ b/plugins/module_utils/oidc.py @@ -4,20 +4,22 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type -from ..module_utils.utils import PayloadMapper +from typing import Any +from typing import Optional + from ..module_utils import errors from ..module_utils.rest_client import RestClient -from ..module_utils.typed_classes import ( - TypedTaskTag, - TypedOidcToAnsible, - TypedOidcFromAnsible, -) -from typing import Any, Optional +from ..module_utils.typed_classes import TypedOidcFromAnsible +from ..module_utils.typed_classes import TypedOidcToAnsible +from ..module_utils.typed_classes import TypedTaskTag +from ..module_utils.utils import PayloadMapper class Oidc(PayloadMapper): @@ -95,6 +97,4 @@ def send_create_request(self, rest_client: RestClient) -> TypedTaskTag: def send_update_request(self, rest_client: RestClient) -> TypedTaskTag: payload = self.to_hypercore() - return rest_client.update_record( - "/rest/v1/OIDCConfig/oidcconfig_uuid", payload, False - ) + return rest_client.update_record("/rest/v1/OIDCConfig/oidcconfig_uuid", payload, False) diff --git a/plugins/module_utils/registration.py b/plugins/module_utils/registration.py index 50412940..5a7aa8d6 100644 --- a/plugins/module_utils/registration.py +++ b/plugins/module_utils/registration.py @@ -4,20 +4,22 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type -from ..module_utils.utils import PayloadMapper +from typing import Any +from typing import Optional + from ..module_utils import errors from ..module_utils.rest_client import RestClient -from ..module_utils.typed_classes import ( - TypedTaskTag, - TypedRegistrationFromAnsible, - TypedRegistrationToAnsible, -) -from typing import Any, Optional +from ..module_utils.typed_classes import TypedRegistrationFromAnsible +from ..module_utils.typed_classes import TypedRegistrationToAnsible +from ..module_utils.typed_classes import TypedTaskTag +from ..module_utils.utils import PayloadMapper class Registration(PayloadMapper): @@ -102,12 +104,8 @@ def send_create_request(self, rest_client: RestClient) -> TypedTaskTag: return rest_client.create_record("/rest/v1/Registration", payload, False) def send_delete_request(self, rest_client: RestClient) -> TypedTaskTag: - return rest_client.delete_record( - "/rest/v1/Registration/registration_guid", False - ) + return rest_client.delete_record("/rest/v1/Registration/registration_guid", False) def send_update_request(self, rest_client: RestClient) -> TypedTaskTag: payload = self.to_hypercore() - return rest_client.update_record( - "/rest/v1/Registration/registration_guid", payload, False - ) + return rest_client.update_record("/rest/v1/Registration/registration_guid", payload, False) diff --git a/plugins/module_utils/remote_cluster.py b/plugins/module_utils/remote_cluster.py index 066278af..766ba08e 100644 --- a/plugins/module_utils/remote_cluster.py +++ b/plugins/module_utils/remote_cluster.py @@ -4,7 +4,9 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -70,12 +72,8 @@ def __eq__(self, other): ) @classmethod - def get_cluster_name_from_replication_connection_uuid( - cls, rest_client, connection_uuid - ): - hypercore_dict = rest_client.get_record( - "/rest/v1/RemoteClusterConnection", {"uuid": connection_uuid} - ) + def get_cluster_name_from_replication_connection_uuid(cls, rest_client, connection_uuid): + hypercore_dict = rest_client.get_record("/rest/v1/RemoteClusterConnection", {"uuid": connection_uuid}) if hypercore_dict is None: return None record = cls.from_hypercore(hypercore_data=hypercore_dict).to_ansible() diff --git a/plugins/module_utils/replication.py b/plugins/module_utils/replication.py index f5cf4939..50d92701 100644 --- a/plugins/module_utils/replication.py +++ b/plugins/module_utils/replication.py @@ -4,15 +4,17 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type -from ..module_utils.utils import PayloadMapper -from ..module_utils.state import ReplicationState +from ..module_utils import errors from ..module_utils.remote_cluster import RemoteCluster +from ..module_utils.state import ReplicationState +from ..module_utils.utils import PayloadMapper from ..module_utils.vm import VM -from ..module_utils import errors class Replication(PayloadMapper): @@ -31,10 +33,8 @@ def _replication(cls, rest_client, replication_dict): query={"uuid": replication_dict["sourceDomainUUID"]}, rest_client=rest_client, )[0] - replication_dict["remote_cluster"] = ( - RemoteCluster.get_cluster_name_from_replication_connection_uuid( - rest_client, replication_dict["connectionUUID"] - ) + replication_dict["remote_cluster"] = RemoteCluster.get_cluster_name_from_replication_connection_uuid( + rest_client, replication_dict["connectionUUID"] ) replication_dict["vm_name"] = virtual_machine.name return replication_dict @@ -53,12 +53,7 @@ def get(cls, query, rest_client): ) if not record: return [] - return [ - cls.from_hypercore( - hypercore_data=cls._replication(rest_client, replication) - ) - for replication in record - ] + return [cls.from_hypercore(hypercore_data=cls._replication(rest_client, replication)) for replication in record] @classmethod def from_hypercore(cls, hypercore_data): @@ -92,13 +87,8 @@ def find_available_cluster_connection_or_fail(rest_client, ansible_dict): query=None, ) if not records: - raise errors.ClusterConnectionNotFound( - "replication.py - find_available_cluster_connection_or_fail()" - ) - if ( - "remote_cluster" in ansible_dict - and ansible_dict["remote_cluster"] is not None - ): + raise errors.ClusterConnectionNotFound("replication.py - find_available_cluster_connection_or_fail()") + if "remote_cluster" in ansible_dict and ansible_dict["remote_cluster"] is not None: # Try to find the correct cluster connection for cluster_connection in records: if ( @@ -115,10 +105,7 @@ def to_hypercore(self): "sourceDomainUUID": self.vm_uuid, "connectionUUID": self.connection_uuid, } - if ( - self.state == ReplicationState.enabled - or self.state == ReplicationState.reenabled - ): + if self.state == ReplicationState.enabled or self.state == ReplicationState.reenabled: replication_dict["enable"] = True elif self.state == ReplicationState.disabled: replication_dict["enable"] = False diff --git a/plugins/module_utils/rest_client.py b/plugins/module_utils/rest_client.py index c7a81862..10532ab5 100644 --- a/plugins/module_utils/rest_client.py +++ b/plugins/module_utils/rest_client.py @@ -3,19 +3,23 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function -from . import errors -from . import utils from ..module_utils.client import Client from ..module_utils.typed_classes import TypedTaskTag +from . import errors +from . import utils __metaclass__ = type -from typing import Any, Optional, Union -from io import BufferedReader import json +from io import BufferedReader +from typing import Any +from typing import Optional +from typing import Union def _query(original: Optional[dict[Any, Any]] = None) -> dict[Any, Any]: @@ -67,16 +71,10 @@ def get_record( records = self.list_records(endpoint=endpoint, query=query, timeout=timeout) if len(records) > 1: raise errors.ScaleComputingError( - "{0} records from endpoint {1} match the {2} query.".format( - len(records), endpoint, query - ) + f"{len(records)} records from endpoint {endpoint} match the {query} query." ) if must_exist and not records: - raise errors.ScaleComputingError( - "No records from endpoint {0} match the {1} query.".format( - endpoint, query - ) - ) + raise errors.ScaleComputingError(f"No records from endpoint {endpoint} match the {query} query.") return records[0] if records else None def create_record( @@ -89,9 +87,7 @@ def create_record( if check_mode: return utils.MOCKED_TASK_TAG try: - response: TypedTaskTag = self.client.post( - endpoint, payload, query=_query(), timeout=timeout - ).json + response: TypedTaskTag = self.client.post(endpoint, payload, query=_query(), timeout=timeout).json except TimeoutError as e: raise errors.ScaleTimeoutError(e) return response @@ -107,16 +103,12 @@ def update_record( if check_mode: return utils.MOCKED_TASK_TAG try: - response: TypedTaskTag = self.client.patch( - endpoint, payload, query=_query(), timeout=timeout - ).json + response: TypedTaskTag = self.client.patch(endpoint, payload, query=_query(), timeout=timeout).json except TimeoutError as e: raise errors.ScaleTimeoutError(e) return response - def delete_record( - self, endpoint: str, check_mode: bool, timeout: Optional[float] = None - ) -> TypedTaskTag: + def delete_record(self, endpoint: str, check_mode: bool, timeout: Optional[float] = None) -> TypedTaskTag: # No action is possible when deleting a record if check_mode: return utils.MOCKED_TASK_TAG diff --git a/plugins/module_utils/role.py b/plugins/module_utils/role.py index 1f469daa..3150babc 100644 --- a/plugins/module_utils/role.py +++ b/plugins/module_utils/role.py @@ -4,16 +4,19 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type -from ..module_utils.utils import PayloadMapper +from typing import Any +from typing import Optional + from ..module_utils.rest_client import RestClient from ..module_utils.typed_classes import TypedRoleToAnsible - -from typing import Any, Optional +from ..module_utils.utils import PayloadMapper class Role(PayloadMapper): @@ -59,21 +62,13 @@ def __eq__(self, other: object) -> bool: ) @classmethod - def get_role_from_uuid( - cls, role_uuid: str, rest_client: RestClient, must_exist: bool = False - ) -> Optional[Role]: - hypercore_dict = rest_client.get_record( - "/rest/v1/Role/{0}".format(role_uuid), must_exist=must_exist - ) + def get_role_from_uuid(cls, role_uuid: str, rest_client: RestClient, must_exist: bool = False) -> Optional[Role]: + hypercore_dict = rest_client.get_record(f"/rest/v1/Role/{role_uuid}", must_exist=must_exist) role = cls.from_hypercore(hypercore_dict) return role @classmethod - def get_role_from_name( - cls, role_name: str, rest_client: RestClient, must_exist: bool = False - ) -> Optional[Role]: - hypercore_dict = rest_client.get_record( - "/rest/v1/Role", {"name": role_name}, must_exist=must_exist - ) + def get_role_from_name(cls, role_name: str, rest_client: RestClient, must_exist: bool = False) -> Optional[Role]: + hypercore_dict = rest_client.get_record("/rest/v1/Role", {"name": role_name}, must_exist=must_exist) role = cls.from_hypercore(hypercore_dict) return role diff --git a/plugins/module_utils/smtp.py b/plugins/module_utils/smtp.py index 0a34c521..e20201c9 100644 --- a/plugins/module_utils/smtp.py +++ b/plugins/module_utils/smtp.py @@ -3,20 +3,25 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type -from ..module_utils.utils import PayloadMapper, get_query +from typing import Any +from typing import Dict +from typing import Optional +from typing import Union + from ..module_utils import errors from ..module_utils.rest_client import RestClient -from ..module_utils.typed_classes import ( - TypedTaskTag, - TypedSmtpToAnsible, - TypedSmtpFromAnsible, -) -from typing import Union, Any, Dict, Optional +from ..module_utils.typed_classes import TypedSmtpFromAnsible +from ..module_utils.typed_classes import TypedSmtpToAnsible +from ..module_utils.typed_classes import TypedTaskTag +from ..module_utils.utils import PayloadMapper +from ..module_utils.utils import get_query class SMTP(PayloadMapper): @@ -123,9 +128,7 @@ def get_by_uuid( must_exist: bool = False, ) -> Optional[SMTP]: query = get_query(ansible_dict, "uuid", ansible_hypercore_map=dict(uuid="uuid")) - hypercore_dict = rest_client.get_record( - "/rest/v1/AlertSMTPConfig", query, must_exist=must_exist - ) + hypercore_dict = rest_client.get_record("/rest/v1/AlertSMTPConfig", query, must_exist=must_exist) if hypercore_dict is None: return None smtp_config_from_hypercore = SMTP.from_hypercore(hypercore_dict) @@ -133,9 +136,7 @@ def get_by_uuid( # This method is being tested with integration tests (dns_config_info) @classmethod - def get_state( - cls, rest_client: RestClient - ) -> Union[TypedSmtpToAnsible, dict[Any, Any]]: + def get_state(cls, rest_client: RestClient) -> Union[TypedSmtpToAnsible, dict[Any, Any]]: state = [ SMTP.from_hypercore(hypercore_data=hypercore_dict).to_ansible() for hypercore_dict in rest_client.list_records("/rest/v1/AlertSMTPConfig/") diff --git a/plugins/module_utils/snapshot_schedule.py b/plugins/module_utils/snapshot_schedule.py index 9898edd1..d8d839e0 100644 --- a/plugins/module_utils/snapshot_schedule.py +++ b/plugins/module_utils/snapshot_schedule.py @@ -4,7 +4,9 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -26,8 +28,7 @@ def from_ansible(cls, ansible_data): return SnapshotSchedule( name=vm_dict["name"], recurrences=[ - Recurrence.from_ansible(recurrence_dict) - for recurrence_dict in vm_dict.get("recurrences", []) + Recurrence.from_ansible(recurrence_dict) for recurrence_dict in vm_dict.get("recurrences", []) ], ) @@ -39,10 +40,7 @@ def from_hypercore(cls, hypercore_data): return SnapshotSchedule( name=vm_dict["name"], uuid=vm_dict["uuid"], - recurrences=[ - Recurrence.from_hypercore(recurrence_dict) - for recurrence_dict in vm_dict["rrules"] - ], + recurrences=[Recurrence.from_hypercore(recurrence_dict) for recurrence_dict in vm_dict["rrules"]], ) def to_hypercore(self): @@ -79,19 +77,13 @@ def get_by_name(cls, ansible_dict, rest_client, must_exist=False): object SnapshotSchedule if the record exists. If there is no record with such name, None is returned. """ query = get_query(ansible_dict, "name", ansible_hypercore_map=dict(name="name")) - hypercore_dict = rest_client.get_record( - "/rest/v1/VirDomainSnapshotSchedule", query, must_exist=must_exist - ) - snapshot_schedule_from_hypercore = SnapshotSchedule.from_hypercore( - hypercore_dict - ) + hypercore_dict = rest_client.get_record("/rest/v1/VirDomainSnapshotSchedule", query, must_exist=must_exist) + snapshot_schedule_from_hypercore = SnapshotSchedule.from_hypercore(hypercore_dict) return snapshot_schedule_from_hypercore @classmethod def get_snapshot_schedule(cls, query, rest_client, must_exist=False): - hypercore_dict = rest_client.get_record( - "/rest/v1/VirDomainSnapshotSchedule", query, must_exist=must_exist - ) + hypercore_dict = rest_client.get_record("/rest/v1/VirDomainSnapshotSchedule", query, must_exist=must_exist) return cls.from_hypercore(hypercore_dict) def create_post_payload(self): @@ -100,20 +92,14 @@ def create_post_payload(self): def create_patch_payload(self, new_recurrences_ansible_list): # Override the existing Recurrence objects with the new ones. # Then construct the same payload as in create_post_payload. - self.recurrences = [ - Recurrence.from_ansible(new_recurrence) - for new_recurrence in new_recurrences_ansible_list - ] + self.recurrences = [Recurrence.from_ansible(new_recurrence) for new_recurrence in new_recurrences_ansible_list] return self._post_and_patch_payload() def _post_and_patch_payload(self): """Method shared by create_post_payload and create_patch_payload""" return dict( name=self.name, - rrules=[ - recurrence.create_post_and_patch_payload() - for recurrence in self.recurrences - ], + rrules=[recurrence.create_post_and_patch_payload() for recurrence in self.recurrences], ) diff --git a/plugins/module_utils/state.py b/plugins/module_utils/state.py index ce7eb760..613f8ea7 100644 --- a/plugins/module_utils/state.py +++ b/plugins/module_utils/state.py @@ -4,7 +4,9 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type diff --git a/plugins/module_utils/support_tunnel.py b/plugins/module_utils/support_tunnel.py index 020e7a8a..c472ab1d 100644 --- a/plugins/module_utils/support_tunnel.py +++ b/plugins/module_utils/support_tunnel.py @@ -3,21 +3,27 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type -from ..module_utils.utils import PayloadMapper +from typing import Any +from typing import Optional +from typing import Union + from ansible.module_utils.basic import AnsibleModule + from ..module_utils.client import Client from ..module_utils.typed_classes import TypedSupportTunnelToAnsible -from typing import Any, Union, Optional +from ..module_utils.utils import PayloadMapper class SupportTunnel(PayloadMapper): - def __init__(self, open: bool, code: Optional[int]): - self.open = open + def __init__(self, open_flag: bool, code: Optional[int]): + self.open = open_flag self.code = code @classmethod @@ -25,17 +31,15 @@ def from_ansible(cls, ansible_data: Any) -> Any: pass @classmethod - def from_hypercore( - cls, hypercore_data: dict[str, Union[int, bool, None]] - ) -> SupportTunnel: + def from_hypercore(cls, hypercore_data: dict[str, Union[int, bool, None]]) -> SupportTunnel: # There is no None check since get_record is not used (support_tunnel's api behaves different) if not hypercore_data["tunnelOpen"]: - open = False + open_flag = False code = None else: - open = True + open_flag = True code = hypercore_data["tunnelOpen"] - return cls(open=open, code=code) + return cls(open_flag=open_flag, code=code) def to_hypercore(self) -> Any: pass @@ -46,9 +50,7 @@ def to_ansible(self) -> TypedSupportTunnelToAnsible: code=self.code, ) - def __eq__( - self, other: object - ) -> bool: # object instead of SupportTunnel to make mypy happy + def __eq__(self, other: object) -> bool: # object instead of SupportTunnel to make mypy happy """ One support_tunnel is equal to another if it has all attributes exactly the same. This method is used only in tests. diff --git a/plugins/module_utils/syslog_server.py b/plugins/module_utils/syslog_server.py index 25d03c09..0be8b8f3 100644 --- a/plugins/module_utils/syslog_server.py +++ b/plugins/module_utils/syslog_server.py @@ -3,22 +3,26 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type -from .rest_client import RestClient +from typing import Any +from typing import Dict +from typing import List +from typing import Optional +from typing import Union -from ..module_utils.utils import PayloadMapper, get_query from ..module_utils.task_tag import TaskTag - -from ..module_utils.typed_classes import ( - TypedTaskTag, - TypedSyslogServerToAnsible, - TypedSyslogServerFromAnsible, -) -from typing import List, Union, Any, Dict, Optional +from ..module_utils.typed_classes import TypedSyslogServerFromAnsible +from ..module_utils.typed_classes import TypedSyslogServerToAnsible +from ..module_utils.typed_classes import TypedTaskTag +from ..module_utils.utils import PayloadMapper +from ..module_utils.utils import get_query +from .rest_client import RestClient protocols = {"SYSLOG_PROTOCOL_TCP": "tcp", "SYSLOG_PROTOCOL_UDP": "udp"} @@ -128,9 +132,7 @@ def get_by_uuid( must_exist: bool = False, ) -> Optional[SyslogServer]: query = get_query(ansible_dict, "uuid", ansible_hypercore_map=dict(uuid="uuid")) - hypercore_dict = rest_client.get_record( - "/rest/v1/AlertSyslogTarget", query, must_exist=must_exist - ) + hypercore_dict = rest_client.get_record("/rest/v1/AlertSyslogTarget", query, must_exist=must_exist) if hypercore_dict is None: return None syslog_server_from_hypercore = cls.from_hypercore(hypercore_dict) @@ -143,9 +145,7 @@ def get_by_host( rest_client: RestClient, must_exist: bool = False, ) -> Optional[SyslogServer]: - hypercore_dict = rest_client.get_record( - "/rest/v1/AlertSyslogTarget", {"host": host}, must_exist=must_exist - ) + hypercore_dict = rest_client.get_record("/rest/v1/AlertSyslogTarget", {"host": host}, must_exist=must_exist) if hypercore_dict is None: return None @@ -189,9 +189,7 @@ def get_all( ) -> List[SyslogServer]: syslog_servers = [ cls.from_hypercore(hypercore_data=hypercore_dict) - for hypercore_dict in rest_client.list_records( - "/rest/v1/AlertSyslogTarget/" - ) + for hypercore_dict in rest_client.list_records("/rest/v1/AlertSyslogTarget/") ] syslog_servers.sort() return syslog_servers @@ -212,9 +210,7 @@ def create( payload: Dict[Any, Any], check_mode: bool = False, ) -> SyslogServer: - task_tag = rest_client.create_record( - "/rest/v1/AlertSyslogTarget/", payload, check_mode - ) + task_tag = rest_client.create_record("/rest/v1/AlertSyslogTarget/", payload, check_mode) TaskTag.wait_task(rest_client, task_tag) syslog_server = cls.get_by_uuid( dict(uuid=task_tag["createdUUID"]), @@ -231,9 +227,7 @@ def update( payload: Dict[Any, Any], check_mode: bool = False, ) -> None: - task_tag = rest_client.update_record( - f"/rest/v1/AlertSyslogTarget/{self.uuid}", payload, check_mode - ) + task_tag = rest_client.update_record(f"/rest/v1/AlertSyslogTarget/{self.uuid}", payload, check_mode) TaskTag.wait_task(rest_client, task_tag) def delete( @@ -241,7 +235,5 @@ def delete( rest_client: RestClient, check_mode: bool = False, ) -> None: - task_tag = rest_client.delete_record( - f"/rest/v1/AlertSyslogTarget/{self.uuid}", check_mode - ) + task_tag = rest_client.delete_record(f"/rest/v1/AlertSyslogTarget/{self.uuid}", check_mode) TaskTag.wait_task(rest_client, task_tag) diff --git a/plugins/module_utils/task_tag.py b/plugins/module_utils/task_tag.py index 17cccf37..f3a00e1f 100644 --- a/plugins/module_utils/task_tag.py +++ b/plugins/module_utils/task_tag.py @@ -4,17 +4,21 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type from time import sleep +from typing import Any +from typing import Dict +from typing import Optional from ..module_utils import errors from ..module_utils.rest_client import RestClient from ..module_utils.typed_classes import TypedTaskTag -from typing import Optional, Dict, Any class TaskTag: @@ -37,9 +41,7 @@ def wait_task( return while True: - task_status = rest_client.get_record( - "{0}/{1}".format("/rest/v1/TaskTag", task["taskTag"]), query={} - ) + task_status = rest_client.get_record(f"/rest/v1/TaskTag/{task['taskTag']}", query={}) if task_status is None: # No such task_status is found break if task_status.get("state", "") in ( @@ -55,9 +57,7 @@ def wait_task( sleep(1) @staticmethod - def get_task_status( - rest_client: RestClient, task: Optional[TypedTaskTag] - ) -> Optional[Dict[Any, Any]]: + def get_task_status(rest_client: RestClient, task: Optional[TypedTaskTag]) -> Optional[Dict[Any, Any]]: if not task: return None if not isinstance(task, dict): @@ -66,7 +66,5 @@ def get_task_status( raise errors.ScaleComputingError("taskTag is not in task dictionary.") if not task["taskTag"]: return None - task_status: Optional[Dict[Any, Any]] = rest_client.get_record( - "{0}/{1}".format("/rest/v1/TaskTag", task["taskTag"]), query={} - ) + task_status: Optional[Dict[Any, Any]] = rest_client.get_record(f"/rest/v1/TaskTag/{task['taskTag']}", query={}) return task_status if task_status else None diff --git a/plugins/module_utils/time_server.py b/plugins/module_utils/time_server.py index 69ea141e..b251cdb6 100644 --- a/plugins/module_utils/time_server.py +++ b/plugins/module_utils/time_server.py @@ -3,12 +3,15 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type -from ..module_utils.utils import PayloadMapper, get_query from ..module_utils import errors +from ..module_utils.utils import PayloadMapper +from ..module_utils.utils import get_query # ------------------------------------------ @@ -67,9 +70,7 @@ def __eq__(self, other): @classmethod def get_by_uuid(cls, ansible_dict, rest_client, must_exist=False): query = get_query(ansible_dict, "uuid", ansible_hypercore_map=dict(uuid="uuid")) - hypercore_dict = rest_client.get_record( - "/rest/v1/TimeSource", query, must_exist=must_exist - ) + hypercore_dict = rest_client.get_record("/rest/v1/TimeSource", query, must_exist=must_exist) time_server_from_hypercore = TimeServer.from_hypercore(hypercore_dict) return time_server_from_hypercore diff --git a/plugins/module_utils/time_zone.py b/plugins/module_utils/time_zone.py index 7f5ce138..3a355e7f 100644 --- a/plugins/module_utils/time_zone.py +++ b/plugins/module_utils/time_zone.py @@ -3,12 +3,15 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type -from ..module_utils.utils import PayloadMapper, get_query from ..module_utils import errors +from ..module_utils.utils import PayloadMapper +from ..module_utils.utils import get_query # ------------------------------------------ @@ -75,9 +78,7 @@ def __eq__(self, other): @classmethod def get_by_uuid(cls, ansible_dict, rest_client, must_exist=False): query = get_query(ansible_dict, "uuid", ansible_hypercore_map=dict(uuid="uuid")) - hypercore_dict = rest_client.get_record( - "/rest/v1/TimeZone", query, must_exist=must_exist - ) + hypercore_dict = rest_client.get_record("/rest/v1/TimeZone", query, must_exist=must_exist) time_zone_from_hypercore = TimeZone.from_hypercore(hypercore_dict) return time_zone_from_hypercore diff --git a/plugins/module_utils/typed_classes.py b/plugins/module_utils/typed_classes.py index 096bdd1a..ed57b268 100644 --- a/plugins/module_utils/typed_classes.py +++ b/plugins/module_utils/typed_classes.py @@ -4,14 +4,18 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type -from typing import TypedDict, Union, Any, Optional import datetime - +from typing import Any +from typing import Optional +from typing import TypedDict +from typing import Union # Typed Classes use for Python hints. diff --git a/plugins/module_utils/user.py b/plugins/module_utils/user.py index 64689f13..c1b2b40f 100644 --- a/plugins/module_utils/user.py +++ b/plugins/module_utils/user.py @@ -3,16 +3,19 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type -from ..module_utils.utils import PayloadMapper -from ..module_utils.role import Role +from typing import Optional + from ..module_utils.rest_client import RestClient +from ..module_utils.role import Role from ..module_utils.typed_classes import TypedUserToAnsible -from typing import Optional +from ..module_utils.utils import PayloadMapper class User(PayloadMapper): @@ -56,9 +59,7 @@ def to_ansible(self, rest_client: RestClient) -> TypedUserToAnsible: username=self.username, full_name=self.full_name, roles=[ - Role.get_role_from_uuid( - role_uuid, rest_client, must_exist=False - ).to_ansible() + Role.get_role_from_uuid(role_uuid, rest_client, must_exist=False).to_ansible() for role_uuid in self.role_uuids ], session_limit=self.session_limit, @@ -82,22 +83,14 @@ def __eq__(self, other: object) -> bool: ) @classmethod - def get_user_from_uuid( - cls, user_uuid, rest_client: RestClient, must_exist: bool = False - ) -> Optional[User]: - hypercore_dict = rest_client.get_record( - "/rest/v1/User/{0}".format(user_uuid), must_exist=must_exist - ) + def get_user_from_uuid(cls, user_uuid, rest_client: RestClient, must_exist: bool = False) -> Optional[User]: + hypercore_dict = rest_client.get_record(f"/rest/v1/User/{user_uuid}", must_exist=must_exist) user = cls.from_hypercore(hypercore_dict) return user @classmethod - def get_user_from_username( - cls, username, rest_client: RestClient, must_exist: bool = False - ) -> Optional[User]: - hypercore_dict = rest_client.get_record( - "/rest/v1/User", {"username": username}, must_exist=must_exist - ) + def get_user_from_username(cls, username, rest_client: RestClient, must_exist: bool = False) -> Optional[User]: + hypercore_dict = rest_client.get_record("/rest/v1/User", {"username": username}, must_exist=must_exist) user = cls.from_hypercore(hypercore_dict) return user @@ -109,9 +102,7 @@ def delete(self, rest_client: RestClient, check_mode: bool = False) -> None: # "createdUUID": "" # } - def update( - self, rest_client: RestClient, payload, check_mode: bool = False - ) -> None: + def update(self, rest_client: RestClient, payload, check_mode: bool = False) -> None: rest_client.update_record(f"/rest/v1/User/{self.uuid}", payload, check_mode) # returned: # { @@ -122,9 +113,7 @@ def update( @classmethod def create(cls, rest_client: RestClient, payload, check_mode=False) -> User: task_tag = rest_client.create_record("/rest/v1/User", payload, check_mode) - user = cls.get_user_from_uuid( - task_tag["createdUUID"], rest_client, must_exist=True - ) + user = cls.get_user_from_uuid(task_tag["createdUUID"], rest_client, must_exist=True) return user # type: ignore # user is never None # returned # { diff --git a/plugins/module_utils/utils.py b/plugins/module_utils/utils.py index 57a31010..266aa7b7 100644 --- a/plugins/module_utils/utils.py +++ b/plugins/module_utils/utils.py @@ -3,25 +3,26 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function + from abc import abstractmethod __metaclass__ = type import uuid +from typing import Any +from typing import Union from ..module_utils.errors import InvalidUuidFormatError -from typing import Union, Any -from ..module_utils.typed_classes import ( - TypedTaskTag, - TypedRegistrationToAnsible, - TypedOidcToAnsible, - TypedCertificateToAnsible, - TypedVirtualDiskToAnsible, - TypedVMSnapshotToAnsible, -) - +from ..module_utils.typed_classes import TypedCertificateToAnsible +from ..module_utils.typed_classes import TypedOidcToAnsible +from ..module_utils.typed_classes import TypedRegistrationToAnsible +from ..module_utils.typed_classes import TypedTaskTag +from ..module_utils.typed_classes import TypedVirtualDiskToAnsible +from ..module_utils.typed_classes import TypedVMSnapshotToAnsible MIN_PYTHON_VERSION = (3, 8) @@ -40,24 +41,22 @@ def validate_uuid(value): raise InvalidUuidFormatError(value) -def get_query( - input: dict[Any, Any], *field_names: str, ansible_hypercore_map: dict[Any, Any] -): +def get_query(query_filter: dict[Any, Any], *field_names: str, ansible_hypercore_map: dict[Any, Any]): """ Wrapps filter_dict and transform_ansible_to_hypercore_query. Prefer to use 'get_query' over filter_dict even if there's no mapping between hypercore and ansible columns for the sake of verbosity and consistency """ - ansible_query = filter_dict(input, *field_names) + ansible_query = filter_dict(query_filter, *field_names) hypercore_query = transform_query(ansible_query, ansible_hypercore_map) return hypercore_query -def filter_dict(input, *field_names): +def filter_dict(query_filter, *field_names): output = {} for field_name in field_names: - if field_name not in input: + if field_name not in query_filter: continue - value = input[field_name] + value = query_filter[field_name] if value is not None: output[field_name] = value return output diff --git a/plugins/module_utils/virtual_disk.py b/plugins/module_utils/virtual_disk.py index 8d6807f5..fa673914 100644 --- a/plugins/module_utils/virtual_disk.py +++ b/plugins/module_utils/virtual_disk.py @@ -3,22 +3,26 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type +from typing import Any +from typing import Dict +from typing import List +from typing import Optional + from ansible.module_utils.basic import AnsibleModule -from ..module_utils.typed_classes import ( - TypedVirtualDiskFromAnsible, - TypedVirtualDiskToAnsible, - TypedTaskTag, -) -from typing import Dict, List, Any, Optional -from .rest_client import RestClient -from ..module_utils.utils import PayloadMapper from ..module_utils import errors +from ..module_utils.typed_classes import TypedTaskTag +from ..module_utils.typed_classes import TypedVirtualDiskFromAnsible +from ..module_utils.typed_classes import TypedVirtualDiskToAnsible +from ..module_utils.utils import PayloadMapper +from .rest_client import RestClient REQUEST_TIMEOUT_TIME = 3600 @@ -98,52 +102,32 @@ def __eq__(self, other: object) -> bool: # return virtual_disk @classmethod - def get_by_name( - cls, rest_client: RestClient, name: str, must_exist: bool = False - ) -> Optional[VirtualDisk]: + def get_by_name(cls, rest_client: RestClient, name: str, must_exist: bool = False) -> Optional[VirtualDisk]: result = rest_client.list_records("/rest/v1/VirtualDisk", query=dict(name=name)) if not isinstance(result, list): - raise errors.ScaleComputingError( - "Virtual disk API return value is not a list." - ) + raise errors.ScaleComputingError("Virtual disk API return value is not a list.") elif must_exist and (not result or not result[0]): - raise errors.ScaleComputingError( - f"Virtual disk with name {name} does not exist." - ) + raise errors.ScaleComputingError(f"Virtual disk with name {name} does not exist.") elif not result or not result[0]: return None elif len(result) > 1: - raise errors.ScaleComputingError( - f"Virtual disk {name} has multiple instances and is not unique." - ) + raise errors.ScaleComputingError(f"Virtual disk {name} has multiple instances and is not unique.") return cls.from_hypercore(result[0]) @classmethod - def get_state( - cls, rest_client: RestClient, query: Dict[Any, Any] - ) -> List[TypedVirtualDiskToAnsible]: + def get_state(cls, rest_client: RestClient, query: Dict[Any, Any]) -> List[TypedVirtualDiskToAnsible]: state = [ cls.from_hypercore(hypercore_data=hypercore_dict).to_ansible() - for hypercore_dict in rest_client.list_records( - "/rest/v1/VirtualDisk", query - ) + for hypercore_dict in rest_client.list_records("/rest/v1/VirtualDisk", query) ] return state # Uploads a disk file (qcow2, vmdk, vhd); Hypercore creates virtual disk from uploaded file. # Filename and filesize need to be send as parameters in PUT request. @staticmethod - def send_upload_request( - rest_client: RestClient, file_size: int, module: AnsibleModule - ) -> TypedTaskTag: - if ( - file_size is None - or not module.params["name"] - or not module.params["source"] - ): - raise errors.ScaleComputingError( - "Missing some virtual disk file values inside upload request." - ) + def send_upload_request(rest_client: RestClient, file_size: int, module: AnsibleModule) -> TypedTaskTag: + if file_size is None or not module.params["name"] or not module.params["source"]: + raise errors.ScaleComputingError("Missing some virtual disk file values inside upload request.") try: with open(module.params["source"], "rb") as source_file: task = rest_client.put_record( @@ -160,23 +144,15 @@ def send_upload_request( }, ) except FileNotFoundError: - raise errors.ScaleComputingError( - f"Disk file {module.params['source']} not found." - ) + raise errors.ScaleComputingError(f"Disk file {module.params['source']} not found.") return task def send_delete_request(self, rest_client: RestClient) -> TypedTaskTag: if not self.uuid: - raise errors.ScaleComputingError( - "Missing virtual disk UUID inside delete request." - ) - return rest_client.delete_record( - f"/rest/v1/VirtualDisk/{self.uuid}", check_mode=False - ) + raise errors.ScaleComputingError("Missing virtual disk UUID inside delete request.") + return rest_client.delete_record(f"/rest/v1/VirtualDisk/{self.uuid}", check_mode=False) - def attach_to_vm( - self, rest_client: RestClient, payload: dict[Any, Any] - ) -> TypedTaskTag: + def attach_to_vm(self, rest_client: RestClient, payload: dict[Any, Any]) -> TypedTaskTag: return rest_client.create_record( endpoint=f"/rest/v1/VirtualDisk/{self.uuid}/attach", payload=payload, diff --git a/plugins/module_utils/vm.py b/plugins/module_utils/vm.py index cd65be22..d23a034b 100644 --- a/plugins/module_utils/vm.py +++ b/plugins/module_utils/vm.py @@ -4,36 +4,39 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type import base64 -from time import sleep, time -from typing import Dict, Any, Optional, List +from time import sleep +from time import time +from typing import Any +from typing import Dict +from typing import List +from typing import Optional -from ..module_utils.errors import DeviceNotUnique -from ..module_utils.rest_client import RestClient -from ..module_utils.nic import Nic, NicType +from ..module_utils import errors from ..module_utils.disk import Disk -from ..module_utils.node import Node +from ..module_utils.errors import DeviceNotUnique +from ..module_utils.hypercore_version import HyperCoreVersion from ..module_utils.iso import ISO -from ..module_utils.utils import ( - PayloadMapper, - filter_dict, - transform_query, - is_superset, -) +from ..module_utils.nic import Nic +from ..module_utils.nic import NicType +from ..module_utils.node import Node +from ..module_utils.rest_client import RestClient +from ..module_utils.snapshot_schedule import SnapshotSchedule from ..module_utils.state import NicState -from ..module_utils.utils import ( - get_query, - filter_results, -) from ..module_utils.task_tag import TaskTag -from ..module_utils import errors -from ..module_utils.snapshot_schedule import SnapshotSchedule -from ..module_utils.hypercore_version import HyperCoreVersion +from ..module_utils.utils import PayloadMapper +from ..module_utils.utils import filter_dict +from ..module_utils.utils import filter_results +from ..module_utils.utils import get_query +from ..module_utils.utils import is_superset +from ..module_utils.utils import transform_query # HyperCore state (ansible power_state) are a state machine. # We have states and actions to move between states. @@ -79,9 +82,7 @@ "operatingSystem", ] -VM_DEVICE_QUERY_MAPPING_ANSIBLE = dict( - disk_slot="disk_slot", nic_vlan="vlan", iso_name="iso_name" -) +VM_DEVICE_QUERY_MAPPING_ANSIBLE = dict(disk_slot="disk_slot", nic_vlan="vlan", iso_name="iso_name") DISK_TYPES_HYPERCORE = [ "IDE_DISK", @@ -152,9 +153,7 @@ class VmMachineType: } @classmethod - def from_ansible_to_hypercore( - cls, ansible_machine_type: str, hcversion: HyperCoreVersion - ) -> str: + def from_ansible_to_hypercore(cls, ansible_machine_type: str, hcversion: HyperCoreVersion) -> str: # Empty string is returned if ansible_machine_type cannot bve used with give HyperCore version. if not ansible_machine_type: return "" @@ -173,13 +172,11 @@ def from_hypercore_to_ansible(cls, vm_dict: dict) -> str: # and use machineTypeKeyword if present. if "machineTypeKeyword" in vm_dict: _map_hypercore_machine_type_keyword_to_ansible = { - cls._map_ansible_to_hypercore_machine_type_keyword[k]: k - for k in cls._map_ansible_to_hypercore_machine_type_keyword + hypercore_value: ansible_value + for ansible_value, hypercore_value in cls._map_ansible_to_hypercore_machine_type_keyword.items() } # "machineTypeKeyword" is available in HyperCore 9.3 or later - return _map_hypercore_machine_type_keyword_to_ansible.get( - vm_dict["machineTypeKeyword"], "" - ) + return _map_hypercore_machine_type_keyword_to_ansible.get(vm_dict["machineTypeKeyword"], "") return cls._map_hypercore_to_ansible.get(vm_dict["machineType"], "") @classmethod @@ -251,12 +248,8 @@ def __init__( self.machine_type = machine_type self.replication_source_vm_uuid = replication_source_vm_uuid - power_state_values = list(FROM_HYPERCORE_TO_ANSIBLE_POWER_STATE.values()) + [ - None - ] - power_action_values = list(FROM_ANSIBLE_TO_HYPERCORE_POWER_ACTION.keys()) + [ - None - ] + power_state_values = list(FROM_HYPERCORE_TO_ANSIBLE_POWER_STATE.values()) + [None] + power_action_values = list(FROM_ANSIBLE_TO_HYPERCORE_POWER_ACTION.keys()) + [None] if power_state not in power_state_values: raise AssertionError(f"Unknown VM power_state={power_state}") if power_action not in power_action_values: @@ -265,14 +258,10 @@ def __init__( # VM.from_ansible() will get only power_action if power_state and power_action: # is bug, or is this useful? - raise AssertionError( - f"Both power_state={power_state} and power_action={power_action} are set" - ) + raise AssertionError(f"Both power_state={power_state} and power_action={power_action} are set") if power_state is None and power_action is None: # is bug, or is this useful? - raise AssertionError( - f"Neither power_state={power_state} nor power_action={power_action} is set" - ) + raise AssertionError(f"Neither power_state={power_state} nor power_action={power_action} is set") self._power_state = power_state self._power_action = power_action if power_state and power_action is None: @@ -322,9 +311,7 @@ def from_ansible(cls, ansible_data): memory=vm_dict["memory"], vcpu=vm_dict["vcpu"], nics=[Nic.from_ansible(ansible_data=nic) for nic in vm_dict["nics"] or []], - disks=[ - Disk.from_ansible(disk_dict) for disk_dict in vm_dict["disks"] or [] - ], + disks=[Disk.from_ansible(disk_dict) for disk_dict in vm_dict["disks"] or []], boot_devices=vm_dict.get("boot_devices", []), attach_guest_tools_iso=vm_dict["attach_guest_tools_iso"] or False, operating_system=vm_dict.get("operating_system"), @@ -385,16 +372,12 @@ def from_hypercore(cls, vm_dict, rest_client) -> Optional[VM]: power_state=FROM_HYPERCORE_TO_ANSIBLE_POWER_STATE[vm_dict["state"]], vcpu=vm_dict["numVCPU"], nics=[Nic.from_hypercore(hypercore_data=nic) for nic in vm_dict["netDevs"]], - disks=[ - Disk.from_hypercore(disk_dict) for disk_dict in vm_dict["blockDevs"] - ], + disks=[Disk.from_hypercore(disk_dict) for disk_dict in vm_dict["blockDevs"]], boot_devices=cls.get_vm_device_list(vm_dict), attach_guest_tools_iso=vm_dict.get("attachGuestToolsISO", ""), operating_system=vm_dict["operatingSystem"], node_affinity=node_affinity, - snapshot_schedule=( - snapshot_schedule.name if snapshot_schedule else "" - ), # "" for vm_params diff check + snapshot_schedule=(snapshot_schedule.name if snapshot_schedule else ""), # "" for vm_params diff check snapshot_uuids=vm_dict["snapUUIDs"], machine_type=machine_type, replication_source_vm_uuid=vm_dict["sourceVirDomainUUID"], @@ -403,25 +386,16 @@ def from_hypercore(cls, vm_dict, rest_client) -> Optional[VM]: @classmethod def create_cloud_init_payload(cls, ansible_dict): if "cloud_init" in ansible_dict.keys() and ( - ansible_dict["cloud_init"]["user_data"] - or ansible_dict["cloud_init"]["meta_data"] + ansible_dict["cloud_init"]["user_data"] or ansible_dict["cloud_init"]["meta_data"] ): return dict( userData=( - str( - base64.b64encode( - bytes(str(ansible_dict["cloud_init"]["user_data"]), "utf-8") - ) - )[2:-1] + str(base64.b64encode(bytes(str(ansible_dict["cloud_init"]["user_data"]), "utf-8")))[2:-1] if ansible_dict["cloud_init"]["user_data"] is not None else "" ), metaData=( - str( - base64.b64encode( - bytes(str(ansible_dict["cloud_init"]["meta_data"]), "utf-8") - ) - )[2:-1] + str(base64.b64encode(bytes(str(ansible_dict["cloud_init"]["meta_data"]), "utf-8")))[2:-1] if ansible_dict["cloud_init"]["meta_data"] is not None else "" ), @@ -466,9 +440,7 @@ def create_clone_vm_payload( data["snapUUID"] = source_snapshot_uuid if clone_name: data["template"]["name"] = clone_name - if ( - ansible_tags or hypercore_tags - ): # Cloned VM does not retain tags from the original + if ansible_tags or hypercore_tags: # Cloned VM does not retain tags from the original for tag in ansible_tags or []: if tag not in hypercore_tags: hypercore_tags.append(tag) @@ -494,10 +466,7 @@ def get(cls, query, rest_client): # if query is None, return list of all VMs ) if not record: return [] - return [ - cls.from_hypercore(vm_dict=virtual_machine, rest_client=rest_client) - for virtual_machine in record - ] + return [cls.from_hypercore(vm_dict=virtual_machine, rest_client=rest_client) for virtual_machine in record] @classmethod def get_or_fail(cls, query, rest_client): # if vm is not found, raise exception @@ -507,10 +476,7 @@ def get_or_fail(cls, query, rest_client): # if vm is not found, raise exception ) if not record: raise errors.VMNotFound(query) - return [ - cls.from_hypercore(vm_dict=virtual_machine, rest_client=rest_client) - for virtual_machine in record - ] + return [cls.from_hypercore(vm_dict=virtual_machine, rest_client=rest_client) for virtual_machine in record] @classmethod def get_by_name( @@ -526,12 +492,8 @@ def get_by_name( """ # name_field won't be equal to "vm_name" in case of updating the vm. # In that case, it's going to be equal to vm_name_new. - query = get_query( - ansible_dict, name_field, ansible_hypercore_map={name_field: "name"} - ) - hypercore_dict = rest_client.get_record( - "/rest/v1/VirDomain", query, must_exist=must_exist - ) + query = get_query(ansible_dict, name_field, ansible_hypercore_map={name_field: "name"}) + hypercore_dict = rest_client.get_record("/rest/v1/VirDomain", query, must_exist=must_exist) vm_from_hypercore = cls.from_hypercore(hypercore_dict, rest_client) return vm_from_hypercore @@ -550,9 +512,7 @@ def get_by_old_or_new_name(cls, ansible_dict, rest_client, must_exist=False): ) vm = vm_old_name or vm_new_name if must_exist and vm is None: - raise errors.VMNotFound( - f"vm_name={ansible_dict['vm_name']} or vm_name_new={ansible_dict['vm_name_new']}" - ) + raise errors.VMNotFound(f"vm_name={ansible_dict['vm_name']} or vm_name_new={ansible_dict['vm_name_new']}") return vm @classmethod @@ -592,9 +552,7 @@ def to_hypercore(self, hcversion: HyperCoreVersion): ) if self.machine_type and hcversion.verify("<9.3.0"): - vm_dict["machineType"] = VmMachineType.from_ansible_to_hypercore( - self.machine_type, hcversion - ) + vm_dict["machineType"] = VmMachineType.from_ansible_to_hypercore(self.machine_type, hcversion) return vm_dict @@ -611,9 +569,7 @@ def to_ansible(self): nics=[nic.to_ansible() for nic in self.nic_list], tags=self.tags, uuid=self.uuid, - boot_devices=[ - boot_device.to_ansible() for boot_device in self.boot_devices - ], + boot_devices=[boot_device.to_ansible() for boot_device in self.boot_devices], attach_guest_tools_iso=self.attach_guest_tools_iso, node_affinity=self.node_affinity, snapshot_schedule=self.snapshot_schedule, @@ -661,9 +617,7 @@ def post_vm_payload(self, rest_client, ansible_dict): hcversion = HyperCoreVersion(rest_client) payload = self.to_hypercore(hcversion) VM._post_vm_payload_set_disks(payload, rest_client) - payload["netDevs"] = [ - filter_dict(nic, *nic.keys()) for nic in payload["netDevs"] - ] + payload["netDevs"] = [filter_dict(nic, *nic.keys()) for nic in payload["netDevs"]] payload["bootDevices"] = [] dom = filter_dict(payload, *VM_PAYLOAD_KEYS) cloud_init_payload = VM.create_cloud_init_payload(ansible_dict) @@ -672,11 +626,7 @@ def post_vm_payload(self, rest_client, ansible_dict): options = dict(attachGuestToolsISO=payload["attachGuestToolsISO"]) if hcversion.verify(">=9.3.0"): if self.machine_type: - machine_type_keyword = ( - VmMachineType.from_ansible_to_hypercore_machine_type_keyword( - self.machine_type - ) - ) + machine_type_keyword = VmMachineType.from_ansible_to_hypercore_machine_type_keyword(self.machine_type) options.update(dict(machineTypeKeyword=machine_type_keyword)) return dict(dom=dom, options=options) @@ -705,11 +655,7 @@ def _post_vm_payload_set_disks(vm_hypercore_dict, rest_client): def delete_unused_nics_to_hypercore_vm(self, module, rest_client, nic_key): changed = False ansible_nic_uuid_list = [ - ( - nic["vlan_new"] - if ("vlan_new" in nic.keys() and nic["vlan_new"]) - else nic["vlan"] - ) + (nic["vlan_new"] if ("vlan_new" in nic.keys() and nic["vlan_new"]) else nic["vlan"]) for nic in module.params[nic_key] or [] ] for nic in self.nic_list: @@ -805,18 +751,12 @@ def filter_specific_objects(results, query, object_type): # Type is type of the device, for example disk or nic filtered_results = filter_results(results, query) if len(filtered_results) > 1: - raise errors.ScaleComputingError( - "{0} isn't uniquely identifyed by {1} in the VM.".format( - object_type, query - ) - ) + raise errors.ScaleComputingError(f"{object_type} isn't uniquely identifyed by {query} in the VM.") return filtered_results[0] if filtered_results else None @staticmethod def get_vm_device_ansible_query(desired_vm_device_ansible): - vm_device_raw_query = filter_dict( - desired_vm_device_ansible, "disk_slot", "nic_vlan", "iso_name" - ) + vm_device_raw_query = filter_dict(desired_vm_device_ansible, "disk_slot", "nic_vlan", "iso_name") return transform_query(vm_device_raw_query, VM_DEVICE_QUERY_MAPPING_ANSIBLE) def get_vm_device(self, desired_vm_object): @@ -840,15 +780,13 @@ def update_boot_device_order(module, rest_client, vm, boot_order): # uuid is vm's uuid. boot_order is the desired order we want to set to boot devices vm.do_shutdown_steps(module, rest_client) task_tag = rest_client.update_record( - "{0}/{1}".format("/rest/v1/VirDomain", vm.uuid), + f"/rest/v1/VirDomain/{vm.uuid}", dict(bootDevices=boot_order), module.check_mode, ) TaskTag.wait_task(rest_client, task_tag) - def set_boot_devices( - self, boot_items, module, rest_client, previous_boot_order, changed=False - ): + def set_boot_devices(self, boot_items, module, rest_client, previous_boot_order, changed=False): desired_boot_order = self.set_boot_devices_order(boot_items) if desired_boot_order != previous_boot_order: VM.update_boot_device_order(module, rest_client, self, desired_boot_order) @@ -860,14 +798,10 @@ def get_vm_and_boot_devices(cls, ansible_dict, rest_client): """Helper to modules vm_boot_devices and vm.""" vm = cls.get_by_name(ansible_dict, rest_client, must_exist=True) boot_devices_uuid = vm.get_boot_device_order() - boot_devices_ansible = [ - boot_device.to_ansible() for boot_device in vm.boot_devices - ] + boot_devices_ansible = [boot_device.to_ansible() for boot_device in vm.boot_devices] return vm, boot_devices_uuid, boot_devices_ansible - def update_vm_power_state( - self, module, rest_client, desired_power_action, ignore_repeated_request: bool - ): + def update_vm_power_state(self, module, rest_client, desired_power_action, ignore_repeated_request: bool): """Sets the power state to what is stored in self.power_state""" # desired_power_action must be present in FROM_ANSIBLE_TO_HYPERCORE_POWER_ACTION's keys @@ -889,33 +823,23 @@ def assert_or_ignore_repeated_request(msg): # keep a record what was done if desired_power_action == "start": if self._was_start_tried: - return assert_or_ignore_repeated_request( - "VM _was_start_tried already set" - ) + return assert_or_ignore_repeated_request("VM _was_start_tried already set") self._was_start_tried = True if desired_power_action == "shutdown": if self._was_nice_shutdown_tried: - return assert_or_ignore_repeated_request( - "VM _was_nice_shutdown_tried already set" - ) + return assert_or_ignore_repeated_request("VM _was_nice_shutdown_tried already set") self._was_nice_shutdown_tried = True if desired_power_action == "stop": if self._was_force_shutdown_tried: - return assert_or_ignore_repeated_request( - "VM _was_force_shutdown_tried already set" - ) + return assert_or_ignore_repeated_request("VM _was_force_shutdown_tried already set") self._was_force_shutdown_tried = True if desired_power_action == "reboot": if self._was_reboot_tried: - return assert_or_ignore_repeated_request( - "VM _was_reboot_tried already set" - ) + return assert_or_ignore_repeated_request("VM _was_reboot_tried already set") self._was_reboot_tried = True if desired_power_action == "reset": if self._was_reset_tried: - return assert_or_ignore_repeated_request( - "VM _was_reset_tried already set" - ) + return assert_or_ignore_repeated_request("VM _was_reset_tried already set") self._was_reset_tried = True try: @@ -924,9 +848,7 @@ def assert_or_ignore_repeated_request(msg): [ dict( virDomainUUID=self.uuid, - actionType=FROM_ANSIBLE_TO_HYPERCORE_POWER_ACTION[ - desired_power_action - ], + actionType=FROM_ANSIBLE_TO_HYPERCORE_POWER_ACTION[desired_power_action], cause="INTERNAL", ) ], @@ -953,9 +875,7 @@ def get_vm_device_list(cls, vm_hypercore_dict): all_vm_devices = vm_hypercore_dict["netDevs"] + vm_hypercore_dict["blockDevs"] vm_device_list = [] for vm_device_uuid in vm_hypercore_dict["bootDevices"]: - vm_device_hypercore = cls.filter_specific_objects( - all_vm_devices, {"uuid": vm_device_uuid}, "Disk or nic" - ) + vm_device_hypercore = cls.filter_specific_objects(all_vm_devices, {"uuid": vm_device_uuid}, "Disk or nic") if vm_device_hypercore["type"] in DISK_TYPES_HYPERCORE: vm_device_list.append(Disk.from_hypercore(vm_device_hypercore)) else: # The device is Nic @@ -985,13 +905,9 @@ def vm_shutdown_forced(self, module, rest_client, reboot=False): # forces a VM power off, only if force_shutdown is true from ansbile. # Returns True if successful, False if unsuccessful if "force_reboot" not in module.params: - raise errors.ScaleComputingError( - "Force shutdown is not supported by this module." - ) + raise errors.ScaleComputingError("Force shutdown is not supported by this module.") # Get fresh VM data, in case vm_params changed power state. - vm_fresh_data = rest_client.get_record( - f"/rest/v1/VirDomain/{self.uuid}", must_exist=True - ) + vm_fresh_data = rest_client.get_record(f"/rest/v1/VirDomain/{self.uuid}", must_exist=True) if vm_fresh_data["state"] in ["SHUTOFF", "SHUTDOWN"]: return True if module.params["force_reboot"] and self._was_nice_shutdown_tried: @@ -1008,9 +924,7 @@ def wait_shutdown(self, module, rest_client): # Send GET request every 10 seconds. # Returns True if successful, False if unsuccessful # Get fresh VM data, there is an error if VM is not running and shutdown request is sent. - vm_fresh_data = rest_client.get_record( - f"/rest/v1/VirDomain/{self.uuid}", must_exist=True - ) + vm_fresh_data = rest_client.get_record(f"/rest/v1/VirDomain/{self.uuid}", must_exist=True) if vm_fresh_data["state"] in ["SHUTOFF", "SHUTDOWN"]: return True if ( @@ -1022,9 +936,7 @@ def wait_shutdown(self, module, rest_client): shutdown_timeout = module.params["shutdown_timeout"] start = time() while 1: - vm = rest_client.get_record( - f"/rest/v1/VirDomain/{self.uuid}", must_exist=True - ) + vm = rest_client.get_record(f"/rest/v1/VirDomain/{self.uuid}", must_exist=True) current_time = time() - start if vm["state"] in ["SHUTDOWN", "SHUTOFF"]: self._did_nice_shutdown_work = True @@ -1076,9 +988,7 @@ def check_vm_before_create(self): # UEFI machine type must have NVRAM disk. disk_type_list = [disk.type for disk in self.disks] if self.machine_type == "UEFI" and "nvram" not in disk_type_list: - raise errors.ScaleComputingError( - "Machine of type UEFI requires NVRAM disk." - ) + raise errors.ScaleComputingError("Machine of type UEFI requires NVRAM disk.") # vTPM+UEFI machine type must have NVRAM and VTPM disks. # This in not implemented yet, since this version of API does not support VTPM. if ( @@ -1087,9 +997,7 @@ def check_vm_before_create(self): and "nvram" not in disk_type_list and "vtpm" not in disk_type_list ): - raise errors.ScaleComputingError( - "Machine of type vTPM+UEFI requires NVRAM disk and VTPM disk." - ) + raise errors.ScaleComputingError("Machine of type vTPM+UEFI requires NVRAM disk and VTPM disk.") class ManageVMParams(VM): @@ -1103,9 +1011,7 @@ def _build_payload(module, rest_client): if module.params["description"] is not None: # we want to be able to write "" payload["description"] = module.params["description"] if module.params["tags"] is not None: # we want to be able to write "" - payload["tags"] = ",".join( - module.params["tags"] - ) # tags is a list of strings + payload["tags"] = ",".join(module.params["tags"]) # tags is a list of strings if module.params["memory"] is not None: payload["mem"] = module.params["memory"] if module.params["vcpu"] is not None: @@ -1114,20 +1020,14 @@ def _build_payload(module, rest_client): # On create/POST, machineTypeKeyword can be used (if HC3>=9.3.0). # On update/PATCH, machineTypeKeyword cannot be used (tested with HC3 9.3.5). hcversion = HyperCoreVersion(rest_client) - hc3_machine_type = VmMachineType.from_ansible_to_hypercore( - module.params["machine_type"], hcversion - ) + hc3_machine_type = VmMachineType.from_ansible_to_hypercore(module.params["machine_type"], hcversion) payload["machineType"] = hc3_machine_type - if ( - module.params["snapshot_schedule"] is not None - ): # we want to be able to write "" + if module.params["snapshot_schedule"] is not None: # we want to be able to write "" if module.params["snapshot_schedule"] == "": payload["snapshotScheduleUUID"] = "" else: query = {"name": module.params["snapshot_schedule"]} - snapshot_schedule = SnapshotSchedule.get_snapshot_schedule( - query, rest_client, must_exist=True - ) + snapshot_schedule = SnapshotSchedule.get_snapshot_schedule(query, rest_client, must_exist=True) payload["snapshotScheduleUUID"] = snapshot_schedule.uuid return payload @@ -1156,13 +1056,9 @@ def _to_be_changed(vm, module, param_subset: List[str]): if module.params["vm_name_new"]: changed_params["vm_name"] = vm.name != module.params["vm_name_new"] if module.params["operating_system"]: - changed_params["operating_system"] = ( - vm.operating_system != module.params["operating_system"] - ) + changed_params["operating_system"] = vm.operating_system != module.params["operating_system"] if module.params["description"] is not None: # we want to be able to write "" - changed_params["description"] = ( - vm.description != module.params["description"] - ) + changed_params["description"] = vm.description != module.params["description"] if module.params["tags"] is not None: # we want to be able to write "" changed_params["tags"] = vm.tags != module.params["tags"] if module.params["memory"]: @@ -1187,29 +1083,19 @@ def _to_be_changed(vm, module, param_subset: List[str]): # "reset" and "reboot" needs to be applied always. changed_params["power_state"] = True else: - desired_power_state = FROM_ANSIBLE_POWER_ACTION_TO_ANSIBLE_POWER_STATE[ - requested_power_action - ] + desired_power_state = FROM_ANSIBLE_POWER_ACTION_TO_ANSIBLE_POWER_STATE[requested_power_action] changed_params["power_state"] = desired_power_state != vm._power_state if module.params.get("machine_type") is not None: - changed_params["machine_type"] = ( - vm.machine_type != module.params["machine_type"] - ) - if ( - module.params["snapshot_schedule"] is not None - ): # we want to be able to write "" - changed_params["snapshot_schedule"] = ( - vm.snapshot_schedule != module.params["snapshot_schedule"] - ) + changed_params["machine_type"] = vm.machine_type != module.params["machine_type"] + if module.params["snapshot_schedule"] is not None: # we want to be able to write "" + changed_params["snapshot_schedule"] = vm.snapshot_schedule != module.params["snapshot_schedule"] if param_subset: # Caller can decide to change only subset of all needed changes. # This allows applying a change in two steps. changed_params_filtered = { - param_name: changed_params[param_name] - for param_name in param_subset - if param_name in changed_params + param_name: changed_params[param_name] for param_name in param_subset if param_name in changed_params } else: changed_params_filtered = changed_params @@ -1238,13 +1124,7 @@ def _build_after_diff(module, rest_client): after["snapshot_schedule"] = module.params["snapshot_schedule"] return after - query = { - "name": ( - module.params["vm_name_new"] - if module.params["vm_name_new"] - else module.params["vm_name"] - ) - } + query = {"name": (module.params["vm_name_new"] if module.params["vm_name_new"] else module.params["vm_name"])} vm = VM.get_or_fail(query, rest_client)[0] if module.params["operating_system"]: after["operating_system"] = vm.operating_system @@ -1287,21 +1167,21 @@ def _build_before_diff(vm, module): @classmethod def set_vm_params(cls, module, rest_client, vm, param_subset: List[str]): - changed, changed_parameters = ManageVMParams._to_be_changed( - vm, module, param_subset - ) + changed, changed_parameters = ManageVMParams._to_be_changed(vm, module, param_subset) cls._check_if_required_disks_are_present(module, vm, changed_parameters) if changed: payload = ManageVMParams._build_payload(module, rest_client) - endpoint = "{0}/{1}".format("/rest/v1/VirDomain", vm.uuid) + endpoint = f"/rest/v1/VirDomain/{vm.uuid}" task_tag = rest_client.update_record(endpoint, payload, module.check_mode) TaskTag.wait_task(rest_client, task_tag) # shutdown VM if it needs to be rebooted to apply NIC/disk changes - if ManageVMParams._needs_reboot( - module, changed_parameters - ) and vm._power_action not in ["stop", "stopped", "shutdown"]: + if ManageVMParams._needs_reboot(module, changed_parameters) and vm._power_action not in [ + "stop", + "stopped", + "shutdown", + ]: vm.do_shutdown_steps(module, rest_client) return ( @@ -1320,9 +1200,7 @@ def set_vm_params(cls, module, rest_client, vm, param_subset: List[str]): ) @classmethod - def _check_if_required_disks_are_present( - cls, module, vm, changed_parameters: dict[str, bool] - ): + def _check_if_required_disks_are_present(cls, module, vm, changed_parameters: dict[str, bool]): if "machine_type" in changed_parameters: # Changing machineType can make VM unbootable (from BIOS to UEFI, without NVRAM disk). # After boot is tried, VM does not boot, type cannot be changed back, and support is needed. @@ -1337,15 +1215,11 @@ def _check_if_required_disks_are_present( nvram_needed = True vtpm_needed = True else: - raise AssertionError( - f"machine_type={module.params['machine_type']} not included in set_vm_params." - ) + raise AssertionError(f"machine_type={module.params['machine_type']} not included in set_vm_params.") # At end of module execution we will have VM with final_disks. if "disks" in module.params: # vm module, "disks" param was passed - final_disks = [ - Disk.from_ansible(disk) for disk in module.params["disks"] - ] + final_disks = [Disk.from_ansible(disk) for disk in module.params["disks"]] else: # vm_params has no disks, we need to check the actual VM disks final_disks = vm.disks @@ -1358,9 +1232,7 @@ def _check_if_required_disks_are_present( fail_message_requirements.append("vtpm disk") if fail_message_requirements: fail_details = ", ".join(fail_message_requirements) - module.fail_json( - f"Changing machineType to {module.params['machine_type']} requires {fail_details}." - ) + module.fail_json(f"Changing machineType to {module.params['machine_type']} requires {fail_details}.") class ManageVMDisks: @@ -1393,7 +1265,7 @@ def iso_image_management(module, rest_client, iso, uuid, attach): # If false, it means you're detaching an image. payload = iso.attach_iso_payload() if attach else iso.detach_iso_payload() task_tag = rest_client.update_record( - "{0}/{1}".format("/rest/v1/VirDomainBlockDevice", uuid), + f"/rest/v1/VirDomainBlockDevice/{uuid}", payload, module.check_mode, ) @@ -1402,14 +1274,12 @@ def iso_image_management(module, rest_client, iso, uuid, attach): TaskTag.wait_task(rest_client, task_tag, module.check_mode) @staticmethod - def _update_block_device( - module, rest_client, desired_disk, existing_disk: Disk, vm - ): + def _update_block_device(module, rest_client, desired_disk, existing_disk: Disk, vm): payload = desired_disk.post_and_patch_payload(vm, existing_disk) if existing_disk.needs_reboot("update", desired_disk): vm.do_shutdown_steps(module, rest_client) task_tag = rest_client.update_record( - "{0}/{1}".format("/rest/v1/VirDomainBlockDevice", existing_disk.uuid), + f"/rest/v1/VirDomainBlockDevice/{existing_disk.uuid}", payload, module.check_mode, ) @@ -1423,17 +1293,11 @@ def _delete_not_used_disks(cls, module, rest_client, vm, changed, disk_key): existing_disk = Disk.from_ansible(updated_ansible_disk) to_delete = True # Ensure idempotence with cloud-init and guest-tools IDE_DISKs - if existing_disk.name and ( - "cloud-init" in existing_disk.name - or "guest-tools" in existing_disk.name - ): + if existing_disk.name and ("cloud-init" in existing_disk.name or "guest-tools" in existing_disk.name): continue for ansible_desired_disk in module.params[disk_key]: desired_disk = Disk.from_ansible(ansible_desired_disk) - if ( - desired_disk.slot == existing_disk.slot - and desired_disk.type == existing_disk.type - ): + if desired_disk.slot == existing_disk.slot and desired_disk.type == existing_disk.type: to_delete = False if to_delete: # HyperCore is sometimes able to delete disk on running VM, @@ -1443,9 +1307,7 @@ def _delete_not_used_disks(cls, module, rest_client, vm, changed, disk_key): if existing_disk.needs_reboot("delete"): vm.do_shutdown_steps(module, rest_client) task_tag = rest_client.delete_record( - "{0}/{1}".format( - "/rest/v1/VirDomainBlockDevice", existing_disk.uuid - ), + f"/rest/v1/VirDomainBlockDevice/{existing_disk.uuid}", module.check_mode, ) try: @@ -1457,17 +1319,13 @@ def _delete_not_used_disks(cls, module, rest_client, vm, changed, disk_key): raise if not cls._disk_remove_failed_because_vm_running(ex.task_status): raise - vm_fresh_data = rest_client.get_record( - f"/rest/v1/VirDomain/{vm.uuid}", must_exist=True - ) + vm_fresh_data = rest_client.get_record(f"/rest/v1/VirDomain/{vm.uuid}", must_exist=True) if vm_fresh_data["state"] != "RUNNING": raise # shutdown and retry remove vm.do_shutdown_steps(module, rest_client) task_tag = rest_client.delete_record( - "{0}/{1}".format( - "/rest/v1/VirDomainBlockDevice", existing_disk.uuid - ), + f"/rest/v1/VirDomainBlockDevice/{existing_disk.uuid}", module.check_mode, ) TaskTag.wait_task(rest_client, task_tag, module.check_mode) @@ -1482,10 +1340,7 @@ def _disk_remove_failed_because_vm_running(task_status: Dict): # 9.2.17 - "Unable to delete block device from VM '%@': Still in use" # 9.1.14 - "Virt Exception, code: 84, domain 10: Operation not supported: This type of disk cannot be hot unplugged" - if ( - task_status["formattedMessage"] - == "Unable to delete block device from VM '%@': Still in use" - ): + if task_status["formattedMessage"] == "Unable to delete block device from VM '%@': Still in use": return True if task_status["formattedMessage"].endswith( "Operation not supported: This type of disk cannot be hot unplugged" @@ -1498,13 +1353,11 @@ def _force_remove_all_disks(module, rest_client, vm, disks_before): # It's important to check if items is equal to empty list and empty list only (no None-s) # This method is going to be called in vm_disk class only. if module.params["items"] != []: - raise errors.ScaleComputingError( - "If force set to true, items should be set to empty list" - ) + raise errors.ScaleComputingError("If force set to true, items should be set to empty list") # Delete all disks for existing_disk in vm.disks: task_tag = rest_client.delete_record( - "{0}/{1}".format("/rest/v1/VirDomainBlockDevice", existing_disk.uuid), + f"/rest/v1/VirDomainBlockDevice/{existing_disk.uuid}", module.check_mode, ) TaskTag.wait_task(rest_client, task_tag, module.check_mode) @@ -1519,14 +1372,8 @@ def ensure_present_or_set(cls, module, rest_client, module_path, vm_before: VM): disk_key = "items" if called_from_vm_disk else "disks" # vm_before, disks_before = cls.get_vm_by_name(module, rest_client) disks_before = [disk.to_ansible() for disk in vm_before.disks] - if ( - called_from_vm_disk - and module.params["state"] == "set" - and module.params["force"] - ): - return cls._force_remove_all_disks( - module, rest_client, vm_before, disks_before - ) + if called_from_vm_disk and module.params["state"] == "set" and module.params["force"]: + return cls._force_remove_all_disks(module, rest_client, vm_before, disks_before) for ansible_desired_disk in module.params[disk_key]: # For the given VM, disk can be uniquely identified with disk_slot and type or # just name, if not empty string @@ -1539,15 +1386,10 @@ def ensure_present_or_set(cls, module, rest_client, module_path, vm_before: VM): and ansible_desired_disk["size"] is not None and ansible_existing_disk["size"] > ansible_desired_disk["size"] ): - raise errors.ScaleComputingError( - "Disk size can only be enlarged, never downsized." - ) + raise errors.ScaleComputingError("Disk size can only be enlarged, never downsized.") if ansible_desired_disk["type"] == "ide_cdrom": if ansible_existing_disk: - if ( - ansible_existing_disk["iso_name"] - == ansible_desired_disk["iso_name"] - ): + if ansible_existing_disk["iso_name"] == ansible_desired_disk["iso_name"]: continue # CD-ROM with such iso_name already exists existing_disk = Disk.from_ansible(ansible_existing_disk) uuid = existing_disk.uuid @@ -1556,66 +1398,46 @@ def ensure_present_or_set(cls, module, rest_client, module_path, vm_before: VM): # size is not relevant when creating CD-ROM --> # https://github.com/ScaleComputing/HyperCoreAnsibleCollection/issues/11 desired_disk.size = 0 - uuid = cls._create_block_device( - module, rest_client, vm_before, desired_disk - ) + uuid = cls._create_block_device(module, rest_client, vm_before, desired_disk) changed = True # Attach ISO image # If ISO image's name is specified, it's assumed you want to attach ISO image name = ansible_desired_disk["iso_name"] if name: # Not creating empty CD-ROM without attaching anything iso = ISO.get_by_name(dict(name=name), rest_client, must_exist=True) - cls.iso_image_management( - module, rest_client, iso, uuid, attach=True - ) + cls.iso_image_management(module, rest_client, iso, uuid, attach=True) changed = True else: # Empty CD-ROM is requested. Detach ISO if needed. if ansible_existing_disk: name = ansible_existing_disk["iso_name"] # - existing_iso = ISO.get_by_name( - dict(name=name), rest_client, must_exist=False - ) + existing_iso = ISO.get_by_name(dict(name=name), rest_client, must_exist=False) if existing_iso: - cls.iso_image_management( - module, rest_client, existing_iso, uuid, attach=False - ) + cls.iso_image_management(module, rest_client, existing_iso, uuid, attach=False) changed = True else: if ansible_existing_disk: existing_disk = Disk.from_ansible(ansible_existing_disk) # Check superset for idempotency ansible_desired_disk_filtered = { - k: v - for k, v in desired_disk.to_ansible().items() - if v is not None + k: v for k, v in desired_disk.to_ansible().items() if v is not None } if existing_disk.type == "nvram": # Special case: nvram disk, PATCH cannot change the size/capacity # See also Disk.post_and_patch_payload - ansible_desired_disk_filtered["size"] = ansible_existing_disk[ - "size" - ] + ansible_desired_disk_filtered["size"] = ansible_existing_disk["size"] - if is_superset( - ansible_existing_disk, ansible_desired_disk_filtered - ): + if is_superset(ansible_existing_disk, ansible_desired_disk_filtered): # There's nothing to do - all properties are already set the way we want them to be continue - cls._update_block_device( - module, rest_client, desired_disk, existing_disk, vm_before - ) + cls._update_block_device(module, rest_client, desired_disk, existing_disk, vm_before) else: - cls._create_block_device( - module, rest_client, vm_before, desired_disk - ) + cls._create_block_device(module, rest_client, vm_before, desired_disk) changed = True if module.params["state"] == "set" or not called_from_vm_disk: - changed = cls._delete_not_used_disks( - module, rest_client, vm_before, changed, disk_key - ) + changed = cls._delete_not_used_disks(module, rest_client, vm_before, changed, disk_key) if called_from_vm_disk: vm_before.vm_power_up(module, rest_client) vm_after, disks_after = cls.get_vm_by_name(module, rest_client) @@ -1632,9 +1454,7 @@ class ManageVMNics(Nic): @classmethod def get_by_uuid(cls, rest_client, nic_uuid): return Nic.from_hypercore( - rest_client.get_record( - "/rest/v1/VirDomainNetDevice", query={"uuid": nic_uuid}, must_exist=True - ) + rest_client.get_record("/rest/v1/VirDomainNetDevice", query={"uuid": nic_uuid}, must_exist=True) ) @classmethod @@ -1649,9 +1469,7 @@ def send_update_nic_request_to_hypercore( after, ): if new_nic is None or existing_nic is None: - raise errors.MissingFunctionParameter( - "new_nic or existing_nic - nic.py - update_nic_to_hypercore()" - ) + raise errors.MissingFunctionParameter("new_nic or existing_nic - nic.py - update_nic_to_hypercore()") before.append(existing_nic.to_ansible()) data = new_nic.to_hypercore() virtual_machine_obj.do_shutdown_steps(module, rest_client) @@ -1661,30 +1479,20 @@ def send_update_nic_request_to_hypercore( check_mode=False, ) TaskTag.wait_task(rest_client=rest_client, task=response) - new_nic_obj = ManageVMNics.get_by_uuid( - rest_client=rest_client, nic_uuid=existing_nic.uuid - ) + new_nic_obj = ManageVMNics.get_by_uuid(rest_client=rest_client, nic_uuid=existing_nic.uuid) after.append(new_nic_obj.to_ansible()) return True, before, after @classmethod - def send_create_nic_request_to_hypercore( - cls, module, virtual_machine_obj, rest_client, new_nic, before, after - ): + def send_create_nic_request_to_hypercore(cls, module, virtual_machine_obj, rest_client, new_nic, before, after): if new_nic is None: - raise errors.MissingFunctionParameter( - "new_nic - nic.py - create_nic_to_hypercore()" - ) + raise errors.MissingFunctionParameter("new_nic - nic.py - create_nic_to_hypercore()") before.append(None) data = new_nic.to_hypercore() virtual_machine_obj.do_shutdown_steps(module, rest_client) - response = rest_client.create_record( - endpoint="/rest/v1/VirDomainNetDevice", payload=data, check_mode=False - ) + response = rest_client.create_record(endpoint="/rest/v1/VirDomainNetDevice", payload=data, check_mode=False) TaskTag.wait_task(rest_client=rest_client, task=response) - new_nic_obj = ManageVMNics.get_by_uuid( - rest_client=rest_client, nic_uuid=response["createdUUID"] - ) + new_nic_obj = ManageVMNics.get_by_uuid(rest_client=rest_client, nic_uuid=response["createdUUID"]) after.append(new_nic_obj.to_ansible()) return True, before, after @@ -1693,9 +1501,7 @@ def send_delete_nic_request_to_hypercore( cls, virtual_machine_obj, module, rest_client, nic_to_delete, before, after ): if nic_to_delete is None: - raise errors.MissingFunctionParameter( - "nic_to_delete - nic.py - delete_nic_to_hypercore()" - ) + raise errors.MissingFunctionParameter("nic_to_delete - nic.py - delete_nic_to_hypercore()") before.append(nic_to_delete.to_ansible()) virtual_machine_obj.do_shutdown_steps(module, rest_client) response = rest_client.delete_record( @@ -1792,16 +1598,12 @@ def ensure_present_or_set(cls, module, rest_client, module_path, vm_before: VM): for nic in vm_before.nic_list: before.append(nic.to_ansible()) else: - raise errors.MissingValueAnsible( - "items, cannot be null, empty must be set to []" - ) + raise errors.MissingValueAnsible("items, cannot be null, empty must be set to []") # If the only change is to delete a NIC, then # the vm_before would not know VM was shutdown and reboot is needed. # The delete_unused_nics_to_hypercore_vm() must get updated VLANs. - updated_virtual_machine_TEMP = VM.get_by_old_or_new_name( - module.params, rest_client=rest_client - ) + updated_virtual_machine_TEMP = VM.get_by_old_or_new_name(module.params, rest_client=rest_client) updated_virtual_machine = vm_before updated_virtual_machine.nics = updated_virtual_machine_TEMP.nics del updated_virtual_machine_TEMP @@ -1809,9 +1611,7 @@ def ensure_present_or_set(cls, module, rest_client, module_path, vm_before: VM): if module.params["state"] == NicState.set or not called_from_vm_nic: # Check if any nics need to be deleted from the vm - changed_tmp = updated_virtual_machine.delete_unused_nics_to_hypercore_vm( - module, rest_client, nic_key - ) + changed_tmp = updated_virtual_machine.delete_unused_nics_to_hypercore_vm(module, rest_client, nic_key) changed = changed or changed_tmp if called_from_vm_nic: return ( diff --git a/plugins/module_utils/vm_snapshot.py b/plugins/module_utils/vm_snapshot.py index d17f58de..863e416c 100644 --- a/plugins/module_utils/vm_snapshot.py +++ b/plugins/module_utils/vm_snapshot.py @@ -3,28 +3,29 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import from __future__ import annotations +from __future__ import division +from __future__ import print_function __metaclass__ = type +import datetime +import time from copy import copy +from typing import Any +from typing import Dict +from typing import List +from typing import Optional -from .rest_client import RestClient - -from ..module_utils.utils import PayloadMapper +from ..module_utils import errors from ..module_utils.errors import ScaleComputingError +from ..module_utils.typed_classes import TypedTaskTag +from ..module_utils.typed_classes import TypedVMSnapshotFromAnsible +from ..module_utils.typed_classes import TypedVMSnapshotToAnsible +from ..module_utils.utils import PayloadMapper from ..module_utils.vm import VM -from ..module_utils import errors - -from ..module_utils.typed_classes import ( - TypedVMSnapshotToAnsible, - TypedVMSnapshotFromAnsible, - TypedTaskTag, -) -from typing import List, Any, Dict, Optional -import time -import datetime +from .rest_client import RestClient class VMSnapshot(PayloadMapper): @@ -37,7 +38,7 @@ def __init__( device_snapshots: Optional[List[Dict[Any, Any]]] = None, timestamp: Optional[int] = None, label: Optional[str] = None, - type: Optional[str] = None, + snapshot_type: Optional[str] = None, automated_trigger_timestamp: Optional[int] = None, local_retain_until_timestamp: Optional[float] = None, remote_retain_until_timestamp: Optional[float] = None, @@ -52,7 +53,7 @@ def __init__( self.device_snapshots = device_snapshots if device_snapshots is not None else [] self.timestamp = timestamp self.label = label - self.type = type + self.type = snapshot_type self.automated_trigger_timestamp = automated_trigger_timestamp self.local_retain_until_timestamp = local_retain_until_timestamp self.remote_retain_until_timestamp = remote_retain_until_timestamp @@ -81,9 +82,7 @@ def convert_from_unix_timestamp( def calculate_date(days: Optional[int]) -> Optional[float]: if days is None or days == 0: return None - return VMSnapshot.convert_to_unix_timestamp( - datetime.datetime.today() + datetime.timedelta(days=days) - ) + return VMSnapshot.convert_to_unix_timestamp(datetime.datetime.today() + datetime.timedelta(days=days)) @classmethod def from_ansible(cls, ansible_data: TypedVMSnapshotFromAnsible) -> VMSnapshot: @@ -98,9 +97,7 @@ def from_ansible(cls, ansible_data: TypedVMSnapshotFromAnsible) -> VMSnapshot: ) @classmethod - def from_hypercore( - cls, hypercore_data: Optional[Dict[Any, Any]] - ) -> Optional[VMSnapshot]: + def from_hypercore(cls, hypercore_data: Optional[Dict[Any, Any]]) -> Optional[VMSnapshot]: if not hypercore_data: return None return cls( @@ -109,9 +106,7 @@ def from_hypercore( vm={ "name": hypercore_data["domain"]["name"], "uuid": hypercore_data["domainUUID"], - "snapshot_serial_number": hypercore_data["domain"][ - "snapshotSerialNumber" - ], + "snapshot_serial_number": hypercore_data["domain"]["snapshotSerialNumber"], "disks": [ { "uuid": disk["uuid"], @@ -128,18 +123,15 @@ def from_hypercore( ], }, device_snapshots=[ - {"uuid": device_snapshot["uuid"]} - for device_snapshot in hypercore_data["deviceSnapshots"] + {"uuid": device_snapshot["uuid"]} for device_snapshot in hypercore_data["deviceSnapshots"] ], timestamp=hypercore_data["timestamp"], label=hypercore_data["label"], - type=hypercore_data["type"], + snapshot_type=hypercore_data["type"], automated_trigger_timestamp=hypercore_data["automatedTriggerTimestamp"], local_retain_until_timestamp=hypercore_data["localRetainUntilTimestamp"], remote_retain_until_timestamp=hypercore_data["remoteRetainUntilTimestamp"], - block_count_diff_from_serial_number=hypercore_data[ - "blockCountDiffFromSerialNumber" - ], + block_count_diff_from_serial_number=hypercore_data["blockCountDiffFromSerialNumber"], replication=hypercore_data["replication"], ) @@ -148,19 +140,14 @@ def to_hypercore(self) -> Dict[Any, Any]: uuid=self.snapshot_uuid, domainUUID=self.domain.uuid if self.domain else None, label=self.label, - type=self.type - or "USER", # Currently we don't expose type; USER is default. + type=self.type or "USER", # Currently we don't expose type; USER is default. replication=self.replication, ) # Timestamps can't be set to None in the body. if self.local_retain_until_timestamp: - hypercore_dict["localRetainUntilTimestamp"] = ( - self.local_retain_until_timestamp - ) + hypercore_dict["localRetainUntilTimestamp"] = self.local_retain_until_timestamp if self.remote_retain_until_timestamp: - hypercore_dict["remoteRetainUntilTimestamp"] = ( - self.remote_retain_until_timestamp - ) + hypercore_dict["remoteRetainUntilTimestamp"] = self.remote_retain_until_timestamp return hypercore_dict def to_ansible(self) -> TypedVMSnapshotToAnsible: @@ -173,12 +160,8 @@ def to_ansible(self) -> TypedVMSnapshotToAnsible: label=self.label, type=self.type, automated_trigger_timestamp=self.automated_trigger_timestamp, - local_retain_until_timestamp=self.convert_from_unix_timestamp( - self.local_retain_until_timestamp - ), - remote_retain_until_timestamp=self.convert_from_unix_timestamp( - self.remote_retain_until_timestamp - ), + local_retain_until_timestamp=self.convert_from_unix_timestamp(self.local_retain_until_timestamp), + remote_retain_until_timestamp=self.convert_from_unix_timestamp(self.remote_retain_until_timestamp), block_count_diff_from_serial_number=self.block_count_diff_from_serial_number, replication=self.replication, ) @@ -190,19 +173,14 @@ def __eq__(self, other: object) -> bool: check_vm = True # it will stay True if self.vm == {} if self.vm != {}: - vm_sorted_disks = sorted( - self.vm["disks"], key=lambda disk: disk["iso_name"] - ) - other_sorted_disks = sorted( - other.vm["disks"], key=lambda disk: disk["iso_name"] - ) + vm_sorted_disks = sorted(self.vm["disks"], key=lambda disk: disk["iso_name"]) + other_sorted_disks = sorted(other.vm["disks"], key=lambda disk: disk["iso_name"]) check_vm = all( ( self.vm["name"] == other.vm["name"], self.vm["uuid"] == other.vm["uuid"], - self.vm["snapshot_serial_number"] - == other.vm["snapshot_serial_number"], + self.vm["snapshot_serial_number"] == other.vm["snapshot_serial_number"], vm_sorted_disks == other_sorted_disks, ) ) @@ -217,10 +195,8 @@ def __eq__(self, other: object) -> bool: self.type == other.type, self.automated_trigger_timestamp == other.automated_trigger_timestamp, self.local_retain_until_timestamp == other.local_retain_until_timestamp, - self.remote_retain_until_timestamp - == other.remote_retain_until_timestamp, - self.block_count_diff_from_serial_number - == other.block_count_diff_from_serial_number, + self.remote_retain_until_timestamp == other.remote_retain_until_timestamp, + self.block_count_diff_from_serial_number == other.block_count_diff_from_serial_number, self.replication == other.replication, ) ) @@ -244,9 +220,7 @@ def get_snapshots_by_query( ) -> List[TypedVMSnapshotToAnsible]: snapshots = [ cls.from_hypercore(hypercore_data=hypercore_dict).to_ansible() # type: ignore - for hypercore_dict in rest_client.list_records( - "/rest/v1/VirDomainSnapshot", query - ) + for hypercore_dict in rest_client.list_records("/rest/v1/VirDomainSnapshot", query) ] return snapshots @@ -254,27 +228,17 @@ def get_snapshots_by_query( @classmethod def filter_snapshots_by_params( cls, - params: dict[ - Any, Any - ], # params must be a dict with keys: "vm_name", "serial", "label" + params: dict[Any, Any], # params must be a dict with keys: "vm_name", "serial", "label" rest_client: RestClient, ) -> List[TypedVMSnapshotToAnsible]: vm_snapshots = cls.get_snapshots_by_query({}, rest_client) if not params["vm_name"] and not params["serial"] and not params["label"]: - return ( - vm_snapshots # return all snapshots if none of the params are present - ) + return vm_snapshots # return all snapshots if none of the params are present # else filter results by label, vm.name, vm.snapshotSerialNumber - new_snaps = vm_snapshots[ - : - ] # for some unknown reason, using just "vm_snapshots" returns empty list: [] + new_snaps = vm_snapshots[:] # for some unknown reason, using just "vm_snapshots" returns empty list: [] if params["vm_name"]: - new_snaps = [ - vm_snap - for vm_snap in new_snaps - if vm_snap["vm"]["name"] == params["vm_name"] # type: ignore - ] + new_snaps = [vm_snap for vm_snap in new_snaps if vm_snap["vm"]["name"] == params["vm_name"]] # type: ignore if params["serial"]: new_snaps = [ vm_snap @@ -282,9 +246,7 @@ def filter_snapshots_by_params( if vm_snap["vm"]["snapshot_serial_number"] == params["serial"] # type: ignore ] if params["label"]: - new_snaps = [ - vm_snap for vm_snap in new_snaps if vm_snap["label"] == params["label"] - ] + new_snaps = [vm_snap for vm_snap in new_snaps if vm_snap["label"] == params["label"]] return new_snaps @@ -294,20 +256,14 @@ def send_create_request(self, rest_client: RestClient) -> TypedTaskTag: return rest_client.create_record("/rest/v1/VirDomainSnapshot", payload, False) @staticmethod - def send_delete_request( - rest_client: RestClient, snapshot_uuid: Optional[str] - ) -> TypedTaskTag: + def send_delete_request(rest_client: RestClient, snapshot_uuid: Optional[str]) -> TypedTaskTag: if not snapshot_uuid: raise ScaleComputingError("Missing Snapshot UUID inside delete request.") - return rest_client.delete_record( - f"/rest/v1/VirDomainSnapshot/{snapshot_uuid}", False - ) + return rest_client.delete_record(f"/rest/v1/VirDomainSnapshot/{snapshot_uuid}", False) @classmethod # Used to rename dict keys of a hypercore object that doesn't have an implemented class - def hypercore_disk_to_ansible( - cls, hypercore_dict: Optional[Dict[Any, Any]] - ) -> Optional[Dict[Any, Any]]: + def hypercore_disk_to_ansible(cls, hypercore_dict: Optional[Dict[Any, Any]]) -> Optional[Dict[Any, Any]]: if hypercore_dict is None: return None @@ -320,9 +276,7 @@ def hypercore_disk_to_ansible( ) @classmethod - def get_vm_disk_info_by_uuid( - cls, disk_uuid: str, rest_client: RestClient - ) -> Optional[Dict[Any, Any]]: + def get_vm_disk_info_by_uuid(cls, disk_uuid: str, rest_client: RestClient) -> Optional[Dict[Any, Any]]: record_dict = rest_client.get_record( endpoint="/rest/v1/VirDomainBlockDevice", query={"uuid": disk_uuid}, @@ -330,9 +284,7 @@ def get_vm_disk_info_by_uuid( return cls.hypercore_disk_to_ansible(record_dict) @classmethod - def get_vm_disk_info( - cls, vm_uuid: str, slot: int, _type: str, rest_client: RestClient - ) -> Optional[Dict[Any, Any]]: + def get_vm_disk_info(cls, vm_uuid: str, slot: int, _type: str, rest_client: RestClient) -> Optional[Dict[Any, Any]]: record_dict = rest_client.get_record( endpoint="/rest/v1/VirDomainBlockDevice", query={ @@ -367,9 +319,7 @@ def get_snapshot_disk( @classmethod # Get VM UUID of a VM which does not have this snapshot def get_external_vm_uuid(cls, vm_name: str, rest_client: RestClient) -> Any: - vm_hypercore_dict = rest_client.get_record( - endpoint="/rest/v1/VirDomain", query={"name": vm_name} - ) + vm_hypercore_dict = rest_client.get_record(endpoint="/rest/v1/VirDomain", query={"name": vm_name}) if vm_hypercore_dict is None: return None diff --git a/plugins/modules/api.py b/plugins/modules/api.py index 3ca79cd1..358745ec 100644 --- a/plugins/modules/api.py +++ b/plugins/modules/api.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -179,10 +181,12 @@ """ -from ansible.module_utils.basic import AnsibleModule import os -from ..module_utils import errors, arguments +from ansible.module_utils.basic import AnsibleModule + +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient from ..module_utils.task_tag import TaskTag @@ -247,7 +251,7 @@ def delete_record(module, rest_client): return False, dict() -""" +__COMMENT = """ PUT_TIMEOUT_TIME was copied from the iso module for ISO data upload. Currently, assume we have 4.7 GB ISO and speed 1 MB/s -> 4700 seconds. Rounded to 3600. diff --git a/plugins/modules/certificate.py b/plugins/modules/certificate.py index 29647d7b..3b9b9afe 100644 --- a/plugins/modules/certificate.py +++ b/plugins/modules/certificate.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -62,29 +64,25 @@ -----END CERTIFICATE----- """ +import ssl +from time import sleep +from typing import Optional +from typing import Tuple + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient -from ..module_utils.typed_classes import ( - TypedDiff, - TypedTaskTag, - TypedCertificateToAnsible, -) from ..module_utils.task_tag import TaskTag - -from typing import Tuple, Optional -import ssl -from time import sleep +from ..module_utils.typed_classes import TypedCertificateToAnsible +from ..module_utils.typed_classes import TypedDiff +from ..module_utils.typed_classes import TypedTaskTag def get_certificate(module: AnsibleModule) -> str: - host = ( - module.params["cluster_instance"]["host"] - .replace("https://", "") - .replace("http://", "") - ) + host = module.params["cluster_instance"]["host"].replace("https://", "").replace("http://", "") cert = ssl.get_server_certificate((host, 443)) return cert @@ -111,32 +109,24 @@ def ensure_present( TaskTag.wait_task(rest_client, task) break except ConnectionRefusedError: - module.warn( - f"retry {ii}/{max_retries}, ConnectionRefusedError - ignore and continue" - ) + module.warn(f"retry {ii}/{max_retries}, ConnectionRefusedError - ignore and continue") sleep(2) continue except ConnectionResetError: - module.warn( - f"retry {ii}/{max_retries}, ConnectionResetError - ignore and continue" - ) + module.warn(f"retry {ii}/{max_retries}, ConnectionResetError - ignore and continue") sleep(2) continue except (ssl.SSLEOFError, ssl.SSLZeroReturnError, ssl.SSLSyscallError) as ex: # Ignore "EOF occurred in violation of protocol (_ssl.c:997)" # Alternative message "TLS/SSL connection has been closed (EOF) (_ssl.c:1129)". - module.warn( - f"retry {ii}/{max_retries}, SSL error {ex.__class__.__name__} - ignore and continue" - ) + module.warn(f"retry {ii}/{max_retries}, SSL error {ex.__class__.__name__} - ignore and continue") sleep(2) continue after: TypedCertificateToAnsible = dict(certificate=get_certificate(module)) return True, after, dict(before=before, after=after) -def run( - module: AnsibleModule, rest_client: RestClient -) -> Tuple[bool, Optional[TypedCertificateToAnsible], TypedDiff]: +def run(module: AnsibleModule, rest_client: RestClient) -> Tuple[bool, Optional[TypedCertificateToAnsible], TypedDiff]: return ensure_present(module, rest_client) diff --git a/plugins/modules/cluster_info.py b/plugins/modules/cluster_info.py index ad6656c5..ed8d8bf6 100644 --- a/plugins/modules/cluster_info.py +++ b/plugins/modules/cluster_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -55,10 +57,11 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors -from ..module_utils.rest_client import RestClient +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.cluster import Cluster +from ..module_utils.rest_client import RestClient from ..module_utils.typed_classes import TypedClusterToAnsible diff --git a/plugins/modules/cluster_name.py b/plugins/modules/cluster_name.py index 945f1f16..1103b50e 100644 --- a/plugins/modules/cluster_name.py +++ b/plugins/modules/cluster_name.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -63,25 +65,24 @@ sample: a5d9148c-37f7-4b43-843c-196751d3c050 """ +from typing import Tuple + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient from ..module_utils.cluster import Cluster +from ..module_utils.hypercore_version import HyperCoreVersion +from ..module_utils.rest_client import RestClient from ..module_utils.task_tag import TaskTag -from ..module_utils.typed_classes import TypedClusterToAnsible, TypedDiff -from typing import Tuple -from ..module_utils.hypercore_version import ( - HyperCoreVersion, -) +from ..module_utils.typed_classes import TypedClusterToAnsible +from ..module_utils.typed_classes import TypedDiff HYPERCORE_VERSION_REQUIREMENTS = ">=9.1.21 <9.2.0 || >=9.2.11" -def run( - module: AnsibleModule, rest_client: RestClient -) -> Tuple[bool, TypedClusterToAnsible, TypedDiff]: +def run(module: AnsibleModule, rest_client: RestClient) -> Tuple[bool, TypedClusterToAnsible, TypedDiff]: cluster = Cluster.get(rest_client) if cluster.name == module.params["name_new"]: return ( diff --git a/plugins/modules/cluster_shutdown.py b/plugins/modules/cluster_shutdown.py index d873dd27..e40905b9 100644 --- a/plugins/modules/cluster_shutdown.py +++ b/plugins/modules/cluster_shutdown.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -51,10 +53,11 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient from ..module_utils.cluster import Cluster +from ..module_utils.rest_client import RestClient def run(module: AnsibleModule, rest_client: RestClient) -> bool: diff --git a/plugins/modules/dns_config.py b/plugins/modules/dns_config.py index 1ea28e3e..c82bd372 100644 --- a/plugins/modules/dns_config.py +++ b/plugins/modules/dns_config.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -116,14 +118,16 @@ """ -from ansible.module_utils.basic import AnsibleModule from typing import Tuple -from ..module_utils.task_tag import TaskTag -from ..module_utils import arguments, errors +from ansible.module_utils.basic import AnsibleModule + +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient from ..module_utils.dns_config import DNSConfig +from ..module_utils.rest_client import RestClient +from ..module_utils.task_tag import TaskTag def build_entry_list( @@ -165,9 +169,7 @@ def build_entry_list( ) -def modify_dns_config( - module: AnsibleModule, rest_client: RestClient -) -> Tuple[bool, dict, dict]: +def modify_dns_config(module: AnsibleModule, rest_client: RestClient) -> Tuple[bool, dict, dict]: # GET method to get the DNS Config by UUID dns_config = DNSConfig.get_by_uuid(module.params, rest_client) @@ -190,9 +192,7 @@ def modify_dns_config( # Otherwise, continue with modifying the configuration before = dns_config.to_ansible() - old_state = DNSConfig.get_state( - rest_client - ) # get the state of DNS config before modification + old_state = DNSConfig.get_state(rest_client) # get the state of DNS config before modification # Set action according to specified state param action = "create" @@ -226,8 +226,8 @@ def modify_dns_config( # update_record method uses method PATCH, # create_record method uses method POST. # [ NOTE: PUT method is not allowed on DNS Config ] - task_tag = getattr(rest_client, "{0}_record".format(action))( - endpoint="{0}/{1}".format("/rest/v1/DNSConfig", dns_config.uuid), + task_tag = getattr(rest_client, f"{action}_record")( + endpoint=f"/rest/v1/DNSConfig/{dns_config.uuid}", payload=dict(searchDomains=new_search_domains, serverIPs=new_dns_servers), check_mode=module.check_mode, ) diff --git a/plugins/modules/dns_config_info.py b/plugins/modules/dns_config_info.py index 71c3b6d0..f559d470 100644 --- a/plugins/modules/dns_config_info.py +++ b/plugins/modules/dns_config_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -78,10 +80,11 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient from ..module_utils.dns_config import DNSConfig +from ..module_utils.rest_client import RestClient def run(rest_client: RestClient): diff --git a/plugins/modules/email_alert.py b/plugins/modules/email_alert.py index 551dc75c..1da221ad 100644 --- a/plugins/modules/email_alert.py +++ b/plugins/modules/email_alert.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -127,10 +129,11 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient from ..module_utils.email_alert import EmailAlert +from ..module_utils.rest_client import RestClient # from ..module_utils.typed_classes import TypedEmailAlertToAnsible, TypedDiff @@ -138,9 +141,7 @@ def create_email_alert(module: AnsibleModule, rest_client: RestClient): - email_alert = EmailAlert.get_by_email( - dict(email=module.params["email"]), rest_client - ) + email_alert = EmailAlert.get_by_email(dict(email=module.params["email"]), rest_client) # If that email alert recipient already exists, it will not be created again (no duplicates) if email_alert: @@ -168,13 +169,9 @@ def update_email_alert(module: AnsibleModule, rest_client: RestClient): old_email = EmailAlert.get_by_email(dict(email=module.params["email"]), rest_client) if not old_email: - old_email = EmailAlert.get_by_email( - dict(email=module.params["email_new"]), rest_client - ) + old_email = EmailAlert.get_by_email(dict(email=module.params["email_new"]), rest_client) if not old_email: - raise errors.ScaleComputingError( - "Email Alert: Can't update a nonexistent email." - ) + raise errors.ScaleComputingError("Email Alert: Can't update a nonexistent email.") before = old_email.to_ansible() @@ -191,9 +188,7 @@ def update_email_alert(module: AnsibleModule, rest_client: RestClient): payload=dict(emailAddress=module.params["email_new"]), check_mode=module.check_mode, ) - new_email = EmailAlert.get_by_email( - dict(email=module.params["email_new"]), rest_client - ) + new_email = EmailAlert.get_by_email(dict(email=module.params["email_new"]), rest_client) after = new_email.to_ansible() return ( @@ -204,9 +199,7 @@ def update_email_alert(module: AnsibleModule, rest_client: RestClient): def delete_email_alert(module: AnsibleModule, rest_client: RestClient): - delete_emails = EmailAlert.list_by_email( - dict(email=module.params["email"]), rest_client - ) + delete_emails = EmailAlert.list_by_email(dict(email=module.params["email"]), rest_client) if not delete_emails: return False, {}, dict(before={}, after={}) @@ -227,13 +220,9 @@ def delete_email_alert(module: AnsibleModule, rest_client: RestClient): def send_test(module: AnsibleModule, rest_client: RestClient): - send_email = EmailAlert.get_by_email( - dict(email=module.params["email"]), rest_client - ) + send_email = EmailAlert.get_by_email(dict(email=module.params["email"]), rest_client) - if ( - not send_email - ): # should the module notify user, that the email he's trying to test doesn't exist? + if not send_email: # should the module notify user, that the email he's trying to test doesn't exist? module.warn("Email Alert: can't send a test email to a nonexistent recipient.") return False, {}, dict(before={}, after={}) @@ -242,9 +231,7 @@ def send_test(module: AnsibleModule, rest_client: RestClient): rest_client=rest_client, ) - after_send_email = EmailAlert.get_by_email( - dict(email=module.params["email"]), rest_client - ) + after_send_email = EmailAlert.get_by_email(dict(email=module.params["email"]), rest_client) after = after_send_email.to_ansible() return after != before, after, dict(before=before, after=after) diff --git a/plugins/modules/email_alert_info.py b/plugins/modules/email_alert_info.py index 3c99dbac..13adfc2b 100644 --- a/plugins/modules/email_alert_info.py +++ b/plugins/modules/email_alert_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -81,14 +83,17 @@ """ +from typing import List +from typing import Optional + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient from ..module_utils.email_alert import EmailAlert +from ..module_utils.rest_client import RestClient from ..module_utils.typed_classes import TypedEmailAlertToAnsible -from typing import List, Optional def run(rest_client: RestClient) -> List[Optional[TypedEmailAlertToAnsible]]: diff --git a/plugins/modules/iso.py b/plugins/modules/iso.py index 6bf7ec16..7ce338f9 100644 --- a/plugins/modules/iso.py +++ b/plugins/modules/iso.py @@ -5,7 +5,9 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -150,17 +152,19 @@ """ +import json import os + from ansible.module_utils.basic import AnsibleModule -import json -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client +from ..module_utils.iso import ISO from ..module_utils.rest_client import RestClient from ..module_utils.task_tag import TaskTag -from ..module_utils.iso import ISO -""" +__COMMENT = """ ISO_TIMEOUT_TIME is timeout for ISO data upload. Currently, assume we have 4.7 GB ISO and speed 1 MB/s -> 4700 seconds. Rounded to 3600. @@ -197,7 +201,7 @@ def ensure_present(module, rest_client): file_size = os.stat(module.params["source"]).st_size with open(module.params["source"], "rb") as source_file: rest_client.put_record( - endpoint="/rest/v1/ISO/%s/data" % iso_uuid, + endpoint=f"/rest/v1/ISO/{iso_uuid}/data", payload=None, check_mode=module.check_mode, timeout=ISO_TIMEOUT_TIME, @@ -209,15 +213,13 @@ def ensure_present(module, rest_client): }, ) except FileNotFoundError: - raise errors.ScaleComputingError( - f"ISO file {module.params['source']} not found." - ) + raise errors.ScaleComputingError(f"ISO file {module.params['source']} not found.") except (json.JSONDecodeError, errors.ApiResponseNotJson): pass # ISO API endpoint returns binary content. # Now the ISO image is ready for insertion. Updating readyForInsert to True. task_tag_update = rest_client.update_record( - endpoint="{0}/{1}".format("/rest/v1/ISO", iso_uuid), + endpoint=f"/rest/v1/ISO/{iso_uuid}", payload=dict(readyForInsert=True), check_mode=module.check_mode, ) @@ -230,7 +232,7 @@ def ensure_absent(module, rest_client): iso_image = ISO.get_by_name(module.params, rest_client) if iso_image: task_tag_delete = rest_client.delete_record( - endpoint="{0}/{1}".format("/rest/v1/ISO", iso_image.uuid), + endpoint=f"/rest/v1/ISO/{iso_image.uuid}", check_mode=module.check_mode, ) TaskTag.wait_task(rest_client, task_tag_delete) diff --git a/plugins/modules/iso_info.py b/plugins/modules/iso_info.py index 57b7d02c..68db2dd0 100644 --- a/plugins/modules/iso_info.py +++ b/plugins/modules/iso_info.py @@ -5,7 +5,9 @@ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -92,11 +94,12 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client +from ..module_utils.iso import ISO from ..module_utils.rest_client import RestClient from ..module_utils.utils import get_query -from ..module_utils.iso import ISO def run(module, rest_client): diff --git a/plugins/modules/node_info.py b/plugins/modules/node_info.py index f92fa107..0fa3722e 100644 --- a/plugins/modules/node_info.py +++ b/plugins/modules/node_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -60,10 +62,11 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors -from ..module_utils.rest_client import RestClient +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.node import Node +from ..module_utils.rest_client import RestClient def run(rest_client): diff --git a/plugins/modules/oidc_config.py b/plugins/modules/oidc_config.py index c37c5846..2b9e1857 100644 --- a/plugins/modules/oidc_config.py +++ b/plugins/modules/oidc_config.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -84,17 +86,21 @@ sample: openid+profile """ +from time import sleep +from typing import Optional +from typing import Tuple + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors -from ..module_utils.errors import UnexpectedAPIResponse +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient +from ..module_utils.errors import UnexpectedAPIResponse from ..module_utils.oidc import Oidc -from ..module_utils.typed_classes import TypedOidcToAnsible, TypedDiff +from ..module_utils.rest_client import RestClient from ..module_utils.task_tag import TaskTag -from typing import Tuple, Optional -from time import sleep +from ..module_utils.typed_classes import TypedDiff +from ..module_utils.typed_classes import TypedOidcToAnsible def ensure_present( @@ -117,13 +123,10 @@ def ensure_present( break except UnexpectedAPIResponse as ex: if ex.response_status in [500, 502]: - module.warn( - f"API misbehaving during reconfiguration, retry {ii + 1}/{max_retries}" - ) + module.warn(f"API misbehaving during reconfiguration, retry {ii + 1}/{max_retries}") sleep(1) continue - else: - raise + raise # module.warn(f"API during reconfiguration ii={ii}") for ii in range(max_retries): @@ -132,13 +135,10 @@ def ensure_present( break except UnexpectedAPIResponse as ex: if ex.response_status in [500, 502]: - module.warn( - f"API misbehaving after reconfiguration, retry {ii + 1}/{max_retries}" - ) + module.warn(f"API misbehaving after reconfiguration, retry {ii + 1}/{max_retries}") sleep(1) continue - else: - raise + raise # module.warn(f"API after reconfiguration ii={ii}") after = updated_oidc.to_ansible() if updated_oidc else None @@ -146,9 +146,7 @@ def ensure_present( return True, after, dict(before=before, after=after) -def run( - module: AnsibleModule, rest_client: RestClient -) -> Tuple[bool, Optional[TypedOidcToAnsible], TypedDiff]: +def run(module: AnsibleModule, rest_client: RestClient) -> Tuple[bool, Optional[TypedOidcToAnsible], TypedDiff]: return ensure_present(module, rest_client) diff --git a/plugins/modules/oidc_config_info.py b/plugins/modules/oidc_config_info.py index 73b0ae3a..69f43d51 100644 --- a/plugins/modules/oidc_config_info.py +++ b/plugins/modules/oidc_config_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -52,19 +54,20 @@ sample: openid+profile """ +from typing import Optional +from typing import Tuple + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.oidc import Oidc from ..module_utils.rest_client import CachedRestClient from ..module_utils.typed_classes import TypedOidcToAnsible -from typing import Tuple, Optional -def run( - module: AnsibleModule, rest_client: CachedRestClient -) -> Tuple[bool, Optional[TypedOidcToAnsible]]: +def run(module: AnsibleModule, rest_client: CachedRestClient) -> Tuple[bool, Optional[TypedOidcToAnsible]]: oidc_list = rest_client.list_records("/rest/v1/OIDCConfig") if oidc_list: return False, Oidc.from_hypercore(oidc_list[0]).to_ansible() diff --git a/plugins/modules/registration.py b/plugins/modules/registration.py index bda25df6..d369b4cd 100644 --- a/plugins/modules/registration.py +++ b/plugins/modules/registration.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -95,17 +97,21 @@ sample: 056789987 """ +from typing import Optional +from typing import Tuple + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors -from ..module_utils.utils import is_changed +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client +from ..module_utils.registration import Registration from ..module_utils.rest_client import RestClient from ..module_utils.state import State -from ..module_utils.registration import Registration -from ..module_utils.typed_classes import TypedRegistrationToAnsible, TypedDiff from ..module_utils.task_tag import TaskTag -from typing import Tuple, Optional +from ..module_utils.typed_classes import TypedDiff +from ..module_utils.typed_classes import TypedRegistrationToAnsible +from ..module_utils.utils import is_changed def ensure_present( @@ -142,9 +148,7 @@ def ensure_absent( return is_changed(before, after), after, dict(before=before, after=after) -def run( - module: AnsibleModule, rest_client: RestClient -) -> Tuple[bool, Optional[TypedRegistrationToAnsible], TypedDiff]: +def run(module: AnsibleModule, rest_client: RestClient) -> Tuple[bool, Optional[TypedRegistrationToAnsible], TypedDiff]: registration_obj = Registration.get(rest_client) if module.params["state"] == State.present: return ensure_present(module, rest_client, registration_obj) diff --git a/plugins/modules/registration_info.py b/plugins/modules/registration_info.py index d275300c..806ada7d 100644 --- a/plugins/modules/registration_info.py +++ b/plugins/modules/registration_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -60,20 +62,19 @@ sample: 056789987 """ +from typing import Optional + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.registration import Registration -from ..module_utils.typed_classes import TypedRegistrationToAnsible from ..module_utils.rest_client import CachedRestClient - -from typing import Optional +from ..module_utils.typed_classes import TypedRegistrationToAnsible -def run( - module: AnsibleModule, rest_client: CachedRestClient -) -> Optional[TypedRegistrationToAnsible]: +def run(module: AnsibleModule, rest_client: CachedRestClient) -> Optional[TypedRegistrationToAnsible]: registration_list = rest_client.list_records("/rest/v1/Registration") if registration_list: return Registration.from_hypercore(registration_list[0]).to_ansible() diff --git a/plugins/modules/remote_cluster_info.py b/plugins/modules/remote_cluster_info.py index d4bfae19..c5d6ee01 100644 --- a/plugins/modules/remote_cluster_info.py +++ b/plugins/modules/remote_cluster_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -79,19 +81,18 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors -from ..module_utils.rest_client import RestClient -from ..module_utils.utils import filter_results +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.remote_cluster import RemoteCluster +from ..module_utils.rest_client import RestClient +from ..module_utils.utils import filter_results def run(module, rest_client): records = [ RemoteCluster.from_hypercore(hypercore_data=hypercore_dict).to_ansible() - for hypercore_dict in rest_client.list_records( - "/rest/v1/RemoteClusterConnection" - ) + for hypercore_dict in rest_client.list_records("/rest/v1/RemoteClusterConnection") ] # Since get_query doesn't work for nested parameters (name -> remoteClusterInfo.clusterName) we have this workaround # In case of additional modules needing this functionality, get_query (and is_superset()) will have to be updated diff --git a/plugins/modules/smtp.py b/plugins/modules/smtp.py index e3c50ddb..572847d5 100644 --- a/plugins/modules/smtp.py +++ b/plugins/modules/smtp.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -151,15 +153,20 @@ """ +from typing import Any +from typing import Dict +from typing import Tuple +from typing import Union + from ansible.module_utils.basic import AnsibleModule -from typing import Tuple, Union, Any, Dict -from ..module_utils.typed_classes import TypedSmtpToAnsible -from ..module_utils.task_tag import TaskTag -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient from ..module_utils.smtp import SMTP +from ..module_utils.task_tag import TaskTag +from ..module_utils.typed_classes import TypedSmtpToAnsible def build_entry( @@ -217,22 +224,12 @@ def modify_smtp_config(module: AnsibleModule, rest_client: RestClient) -> Tuple[ # Otherwise, continue with modifying the configuration before = smtp.to_ansible() - old_state = smtp.get_state( - rest_client - ) # get the state of SMTP config before modification + old_state = smtp.get_state(rest_client) # get the state of SMTP config before modification - new_smtp_server, new_smtp_server_change_needed = build_entry( - before.get("server"), module.params["server"] - ) - new_port, new_port_change_needed = build_entry( - before.get("port"), module.params["port"] - ) - new_use_ssl, new_use_ssl_change_needed = build_entry( - before.get("use_ssl"), module.params["use_ssl"] - ) - new_auth_user, new_auth_user_change_needed = build_entry( - before.get("auth_user"), module.params["auth_user"] - ) + new_smtp_server, new_smtp_server_change_needed = build_entry(before.get("server"), module.params["server"]) + new_port, new_port_change_needed = build_entry(before.get("port"), module.params["port"]) + new_use_ssl, new_use_ssl_change_needed = build_entry(before.get("use_ssl"), module.params["use_ssl"]) + new_auth_user, new_auth_user_change_needed = build_entry(before.get("auth_user"), module.params["auth_user"]) new_auth_password, new_auth_password_change_needed = build_entry( before.get("auth_password"), module.params["auth_password"] ) @@ -270,7 +267,7 @@ def modify_smtp_config(module: AnsibleModule, rest_client: RestClient) -> Tuple[ # Set the task tag # update_record -> PATCH update_task_tag = rest_client.update_record( - endpoint="{0}/{1}".format("/rest/v1/AlertSMTPConfig", smtp.uuid), + endpoint=f"/rest/v1/AlertSMTPConfig/{smtp.uuid}", payload=payload, check_mode=module.check_mode, ) diff --git a/plugins/modules/smtp_info.py b/plugins/modules/smtp_info.py index 739308d9..c1fcbdca 100644 --- a/plugins/modules/smtp_info.py +++ b/plugins/modules/smtp_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -100,14 +102,18 @@ """ +from typing import Any +from typing import Dict +from typing import Union + from ansible.module_utils.basic import AnsibleModule -from typing import Union, Dict, Any -from ..module_utils.typed_classes import TypedSmtpToAnsible -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient from ..module_utils.smtp import SMTP +from ..module_utils.typed_classes import TypedSmtpToAnsible def run(rest_client: RestClient) -> Union[TypedSmtpToAnsible, Dict[Any, Any]]: diff --git a/plugins/modules/snapshot_schedule.py b/plugins/modules/snapshot_schedule.py index 514d6266..46d55dac 100644 --- a/plugins/modules/snapshot_schedule.py +++ b/plugins/modules/snapshot_schedule.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -130,10 +132,12 @@ replication: true """ -from ansible.module_utils.basic import AnsibleModule import time -from ..module_utils import arguments, errors +from ansible.module_utils.basic import AnsibleModule + +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient from ..module_utils.snapshot_schedule import SnapshotSchedule @@ -147,18 +151,11 @@ def ensure_present(module, rest_client): if snapshot_schedule_before: before = snapshot_schedule_before.to_ansible() snapshot_schedule_desired = SnapshotSchedule.from_ansible(module.params) - if ( - snapshot_schedule_desired.recurrences - != snapshot_schedule_before.recurrences - ): + if snapshot_schedule_desired.recurrences != snapshot_schedule_before.recurrences: # If desired and recurrence rules before differ, snapshot schedule has to be updated rest_client.update_record( - "{0}/{1}".format( - "/rest/v1/VirDomainSnapshotSchedule", snapshot_schedule_before.uuid - ), - snapshot_schedule_before.create_patch_payload( - module.params["recurrences"] - ), + f"/rest/v1/VirDomainSnapshotSchedule/{snapshot_schedule_before.uuid}", + snapshot_schedule_before.create_patch_payload(module.params["recurrences"]), module.check_mode, ) changed = True @@ -181,9 +178,7 @@ def ensure_absent(module, rest_client): if snapshot_schedule: # No task tag is returned with DELETE on "/rest/v1/VirDomainSnapshotSchedule/{uuid}" task = rest_client.delete_record( - "{0}/{1}".format( - "/rest/v1/VirDomainSnapshotSchedule", snapshot_schedule.uuid - ), + f"/rest/v1/VirDomainSnapshotSchedule/{snapshot_schedule.uuid}", module.check_mode, ) if task["taskTag"] == "": diff --git a/plugins/modules/snapshot_schedule_info.py b/plugins/modules/snapshot_schedule_info.py index 7114bb09..06830e55 100644 --- a/plugins/modules/snapshot_schedule_info.py +++ b/plugins/modules/snapshot_schedule_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -78,20 +80,19 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient -from ..module_utils.utils import get_query from ..module_utils.snapshot_schedule import SnapshotSchedule +from ..module_utils.utils import get_query def run(module, rest_client): query = get_query(module.params, "name", ansible_hypercore_map=dict(name="name")) return [ SnapshotSchedule.from_hypercore(hypercore_dict).to_ansible() - for hypercore_dict in rest_client.list_records( - "/rest/v1/VirDomainSnapshotSchedule", query - ) + for hypercore_dict in rest_client.list_records("/rest/v1/VirDomainSnapshotSchedule", query) ] diff --git a/plugins/modules/support_tunnel.py b/plugins/modules/support_tunnel.py index 0f9c6075..76bf4ca5 100644 --- a/plugins/modules/support_tunnel.py +++ b/plugins/modules/support_tunnel.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -64,37 +66,34 @@ code: 4422 """ +# validate-modules does not agree with "from __future__ import annotations" +from typing import Tuple + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors + +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.typed_classes import TypedSupportTunnelToAnsible, TypedDiff from ..module_utils.support_tunnel import SupportTunnel - -# validate-modules does not agree with "from __future__ import annotations" -from typing import Tuple +from ..module_utils.typed_classes import TypedDiff +from ..module_utils.typed_classes import TypedSupportTunnelToAnsible -def open_tunnel( - module: AnsibleModule, client: Client -) -> Tuple[bool, TypedSupportTunnelToAnsible, TypedDiff]: +def open_tunnel(module: AnsibleModule, client: Client) -> Tuple[bool, TypedSupportTunnelToAnsible, TypedDiff]: tunnel_status = SupportTunnel.check_tunnel_status(client) if tunnel_status.open: # if tunnel already opened if tunnel_status.code == module.params["code"]: return ( False, tunnel_status.to_ansible(), - dict( - before=tunnel_status.to_ansible(), after=tunnel_status.to_ansible() - ), + dict(before=tunnel_status.to_ansible(), after=tunnel_status.to_ansible()), ) else: SupportTunnel.close_tunnel(client) SupportTunnel.open_tunnel(module, client) new_tunnel_status = SupportTunnel.check_tunnel_status(client) if new_tunnel_status.open is False: - raise errors.SupportTunnelError( - "Support tunnel can't be opened, probably the code is already in use." - ) + raise errors.SupportTunnelError("Support tunnel can't be opened, probably the code is already in use.") return ( True, new_tunnel_status.to_ansible(), @@ -121,9 +120,7 @@ def close_tunnel( ) -def run( - module: AnsibleModule, client: Client -) -> Tuple[bool, TypedSupportTunnelToAnsible, TypedDiff]: +def run(module: AnsibleModule, client: Client) -> Tuple[bool, TypedSupportTunnelToAnsible, TypedDiff]: if module.params["state"] == "present": return open_tunnel(module, client) else: diff --git a/plugins/modules/support_tunnel_info.py b/plugins/modules/support_tunnel_info.py index 7180a246..99f4b586 100644 --- a/plugins/modules/support_tunnel_info.py +++ b/plugins/modules/support_tunnel_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -43,10 +45,12 @@ """ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors + +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.typed_classes import TypedSupportTunnelToAnsible from ..module_utils.support_tunnel import SupportTunnel +from ..module_utils.typed_classes import TypedSupportTunnelToAnsible def run(client: Client) -> TypedSupportTunnelToAnsible: diff --git a/plugins/modules/syslog_server.py b/plugins/modules/syslog_server.py index 4022c10c..cd02d60d 100644 --- a/plugins/modules/syslog_server.py +++ b/plugins/modules/syslog_server.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -178,15 +180,22 @@ """ +from typing import Any +from typing import Dict +from typing import List +from typing import Optional +from typing import Tuple +from typing import Union + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient from ..module_utils.syslog_server import SyslogServer -from ..module_utils.typed_classes import TypedSyslogServerToAnsible, TypedDiff -from typing import Tuple, Union, Dict, Any, List, Optional - +from ..module_utils.typed_classes import TypedDiff +from ..module_utils.typed_classes import TypedSyslogServerToAnsible UDP = "SYSLOG_PROTOCOL_UDP" # default TCP = "SYSLOG_PROTOCOL_TCP" @@ -199,9 +208,7 @@ def get_protocol(protocol: str) -> str: def create_syslog_server( module: AnsibleModule, rest_client: RestClient -) -> Tuple[ - bool, TypedSyslogServerToAnsible, List[TypedSyslogServerToAnsible], TypedDiff -]: +) -> Tuple[bool, TypedSyslogServerToAnsible, List[TypedSyslogServerToAnsible], TypedDiff]: protocol = get_protocol(module.params["protocol"]) # If that syslog server already exists, it will not be created again (no duplicates) @@ -225,9 +232,7 @@ def create_syslog_server( ) # changed, records, diff -def build_update_payload( - module: AnsibleModule, syslog_server: SyslogServer -) -> Dict[Any, Any]: +def build_update_payload(module: AnsibleModule, syslog_server: SyslogServer) -> Dict[Any, Any]: payload = dict( host=syslog_server.host, port=syslog_server.port, @@ -235,10 +240,7 @@ def build_update_payload( ) if module.params["host_new"] and syslog_server.host != module.params["host_new"]: payload["host"] = module.params["host_new"] - if ( - module.params["port"] != DEFAULT_PORT - and module.params["port"] != syslog_server.port - ): + if module.params["port"] != DEFAULT_PORT and module.params["port"] != syslog_server.port: payload["port"] = module.params["port"] if module.params["protocol"]: protocol = get_protocol(module.params["protocol"]) @@ -247,9 +249,7 @@ def build_update_payload( return payload -def update_syslog_server( - old_syserver: SyslogServer, module: AnsibleModule, rest_client: RestClient -) -> Tuple[ +def update_syslog_server(old_syserver: SyslogServer, module: AnsibleModule, rest_client: RestClient) -> Tuple[ bool, Union[TypedSyslogServerToAnsible, Dict[None, None]], List[TypedSyslogServerToAnsible], @@ -258,9 +258,7 @@ def update_syslog_server( old_syserver_tmp = old_syserver if not old_syserver: if module.params["host_new"]: - old_syserver_tmp = SyslogServer.get_by_host( - module.params["host_new"], rest_client - ) # type: ignore + old_syserver_tmp = SyslogServer.get_by_host(module.params["host_new"], rest_client) # type: ignore if not old_syserver_tmp: # Syslog server not found by old or by new host, do nothing. # Maybe module should fail with error instead. @@ -285,9 +283,7 @@ def update_syslog_server( check_mode=module.check_mode, ) - new_syserver = SyslogServer.get_by_host( - host=payload["host"], rest_client=rest_client - ) + new_syserver = SyslogServer.get_by_host(host=payload["host"], rest_client=rest_client) after = new_syserver.to_ansible() # type: ignore records_after = SyslogServer.get_state(rest_client) @@ -335,9 +331,7 @@ def set_syslog_servers(module: AnsibleModule, rest_client: RestClient) -> Tuple[ Just ensure first N servers match what is requested by syslog_servers module param. """ old_hc3_syslog_servers = SyslogServer.get_all(rest_client) - ansible_syslog_servers = [ - SyslogServer.from_ansible(ss) for ss in module.params["syslog_servers"] - ] + ansible_syslog_servers = [SyslogServer.from_ansible(ss) for ss in module.params["syslog_servers"]] ansible_syslog_servers.sort() changed = False for ii, ansible_syslog_server in enumerate(ansible_syslog_servers): @@ -388,9 +382,7 @@ def run(module: AnsibleModule, rest_client: RestClient) -> Tuple[ if state == "set": return set_syslog_servers(module, rest_client) - syslog_server = SyslogServer.get_by_host( - host=module.params["host"], rest_client=rest_client - ) + syslog_server = SyslogServer.get_by_host(host=module.params["host"], rest_client=rest_client) if state == "present": if syslog_server or module.params["host_new"] is not None: return update_syslog_server(syslog_server, module, rest_client) # type: ignore diff --git a/plugins/modules/syslog_server_info.py b/plugins/modules/syslog_server_info.py index 268a1401..d57b6ff1 100644 --- a/plugins/modules/syslog_server_info.py +++ b/plugins/modules/syslog_server_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -92,14 +94,16 @@ """ +from typing import List + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient from ..module_utils.syslog_server import SyslogServer from ..module_utils.typed_classes import TypedSyslogServerToAnsible -from typing import List def run(rest_client: RestClient) -> List[TypedSyslogServerToAnsible]: diff --git a/plugins/modules/task_wait.py b/plugins/modules/task_wait.py index 5745f5a5..9fa2d579 100644 --- a/plugins/modules/task_wait.py +++ b/plugins/modules/task_wait.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -51,10 +53,11 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils.task_tag import TaskTag -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient +from ..module_utils.task_tag import TaskTag def run(module, rest_client): diff --git a/plugins/modules/time_server.py b/plugins/modules/time_server.py index ee7243fc..4c1a6e1f 100644 --- a/plugins/modules/time_server.py +++ b/plugins/modules/time_server.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -80,19 +82,19 @@ """ from typing import Tuple + from ansible.module_utils.basic import AnsibleModule -from ..module_utils.task_tag import TaskTag -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient +from ..module_utils.task_tag import TaskTag from ..module_utils.time_server import TimeServer # Remove not needed -def modify_time_server( - module: AnsibleModule, rest_client: RestClient -) -> Tuple[bool, dict, dict]: +def modify_time_server(module: AnsibleModule, rest_client: RestClient) -> Tuple[bool, dict, dict]: # GET method to get the Time Server by UUID time_server = TimeServer.get_by_uuid(module.params, rest_client) @@ -112,9 +114,7 @@ def modify_time_server( # Otherwise, continue with modifying the configuration before = time_server.to_ansible() - old_state = TimeServer.get_state( - rest_client=rest_client - ) # get the state of Time Server before modification + old_state = TimeServer.get_state(rest_client=rest_client) # get the state of Time Server before modification # Init return values and return if no changes were made change, record, diff = ( @@ -128,7 +128,7 @@ def modify_time_server( # Set the task tag: # update_record -> PATCH update_task_tag = rest_client.update_record( - endpoint="{0}/{1}".format("/rest/v1/TimeSource", time_server.uuid), + endpoint=f"/rest/v1/TimeSource/{time_server.uuid}", payload=dict(host=new_time_server_source), check_mode=module.check_mode, ) diff --git a/plugins/modules/time_server_info.py b/plugins/modules/time_server_info.py index 38c29816..c7ffe685 100644 --- a/plugins/modules/time_server_info.py +++ b/plugins/modules/time_server_info.py @@ -3,7 +3,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -71,7 +73,8 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient from ..module_utils.time_server import TimeServer diff --git a/plugins/modules/time_zone.py b/plugins/modules/time_zone.py index 4e5f212d..4d064f07 100644 --- a/plugins/modules/time_zone.py +++ b/plugins/modules/time_zone.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -478,12 +480,14 @@ """ from typing import Tuple + from ansible.module_utils.basic import AnsibleModule -from ..module_utils.task_tag import TaskTag -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient +from ..module_utils.task_tag import TaskTag from ..module_utils.time_zone import TimeZone # List is based on date_time_zonespec.csv. @@ -887,9 +891,7 @@ # Remove implementation not needed -def modify_time_zone( - module: AnsibleModule, rest_client: RestClient -) -> Tuple[bool, dict, dict]: +def modify_time_zone(module: AnsibleModule, rest_client: RestClient) -> Tuple[bool, dict, dict]: # GET method to get the Time Server by UUID time_zone = TimeZone.get_by_uuid(module.params, rest_client) @@ -909,9 +911,7 @@ def modify_time_zone( # Otherwise, continue with modifying the configuration before = time_zone.to_ansible() - old_state = TimeZone.get_state( - rest_client=rest_client - ) # get the state of Time Server before modification + old_state = TimeZone.get_state(rest_client=rest_client) # get the state of Time Server before modification # Init return values and return if no changes were made change, record, diff = ( @@ -928,7 +928,7 @@ def modify_time_zone( # Set the task tag: # update_record -> PATCH update_task_tag = rest_client.update_record( - endpoint="{0}/{1}".format("/rest/v1/TimeZone", time_zone.uuid), + endpoint=f"/rest/v1/TimeZone/{time_zone.uuid}", payload=dict(timeZone=new_time_zone_entry), check_mode=module.check_mode, ) diff --git a/plugins/modules/time_zone_info.py b/plugins/modules/time_zone_info.py index 23bee5a1..071098e3 100644 --- a/plugins/modules/time_zone_info.py +++ b/plugins/modules/time_zone_info.py @@ -3,7 +3,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -72,7 +74,8 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient from ..module_utils.time_zone import TimeZone diff --git a/plugins/modules/user.py b/plugins/modules/user.py index 818f9b43..74b2a8bd 100644 --- a/plugins/modules/user.py +++ b/plugins/modules/user.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -129,16 +131,24 @@ sample: 51e6d073-7566-4273-9196-58720117bd7f """ +from typing import Any +from typing import Dict +from typing import List +from typing import Optional +from typing import Tuple +from typing import Union + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient from ..module_utils.rest_client import CachedRestClient -from ..module_utils.user import User +from ..module_utils.rest_client import RestClient from ..module_utils.role import Role -from ..module_utils.typed_classes import TypedUserToAnsible, TypedDiff -from typing import List, Tuple, Union, Dict, Any, Optional +from ..module_utils.typed_classes import TypedDiff +from ..module_utils.typed_classes import TypedUserToAnsible +from ..module_utils.user import User def get_role_uuids(module: AnsibleModule, rest_client: RestClient) -> List[str]: @@ -150,9 +160,7 @@ def get_role_uuids(module: AnsibleModule, rest_client: RestClient) -> List[str]: return role_uuids -def data_for_create_user( - module: AnsibleModule, rest_client: RestClient -) -> Dict[Any, Any]: +def data_for_create_user(module: AnsibleModule, rest_client: RestClient) -> Dict[Any, Any]: data = {} data["username"] = module.params[ "username" @@ -168,9 +176,7 @@ def data_for_create_user( return data -def create_user( - module: AnsibleModule, rest_client: RestClient -) -> Tuple[bool, TypedUserToAnsible, TypedDiff]: +def create_user(module: AnsibleModule, rest_client: RestClient) -> Tuple[bool, TypedUserToAnsible, TypedDiff]: data = data_for_create_user(module, rest_client) user = User.create(rest_client, data).to_ansible(rest_client) return ( @@ -180,9 +186,7 @@ def create_user( ) -def data_for_update_user( - module: AnsibleModule, rest_client: RestClient, user: User -) -> Dict[Any, Any]: +def data_for_update_user(module: AnsibleModule, rest_client: RestClient, user: User) -> Dict[Any, Any]: data = {} if module.params["username_new"]: if user.username != module.params["username_new"]: @@ -196,9 +200,7 @@ def data_for_update_user( role_uuids = get_role_uuids(module, rest_client) if user.role_uuids != role_uuids: data["roleUUIDs"] = role_uuids - if ( - module.params["session_limit"] is not None - ): # "is not None" needed to be able to write zero + if module.params["session_limit"] is not None: # "is not None" needed to be able to write zero if user.session_limit != module.params["session_limit"]: data["sessionLimit"] = module.params["session_limit"] return data @@ -238,9 +240,7 @@ def delete_user( def run( module: AnsibleModule, rest_client: RestClient ) -> Tuple[bool, Union[TypedUserToAnsible, Dict[None, None]], TypedDiff]: - user = User.get_user_from_username( - module.params["username"], rest_client, must_exist=False - ) + user = User.get_user_from_username(module.params["username"], rest_client, must_exist=False) if module.params["state"] == "present": if user: return update_user(module, rest_client, user) diff --git a/plugins/modules/user_info.py b/plugins/modules/user_info.py index ca310240..d99e37d5 100644 --- a/plugins/modules/user_info.py +++ b/plugins/modules/user_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -77,27 +79,24 @@ """ +from typing import List +from typing import Optional + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors -from ..module_utils.rest_client import RestClient +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client +from ..module_utils.rest_client import RestClient +from ..module_utils.typed_classes import TypedUserToAnsible from ..module_utils.user import User from ..module_utils.utils import get_query -from ..module_utils.typed_classes import TypedUserToAnsible -from typing import List, Optional -def run( - module: AnsibleModule, rest_client: RestClient -) -> List[Optional[TypedUserToAnsible]]: - query = get_query( - module.params, "username", ansible_hypercore_map=dict(username="username") - ) +def run(module: AnsibleModule, rest_client: RestClient) -> List[Optional[TypedUserToAnsible]]: + query = get_query(module.params, "username", ansible_hypercore_map=dict(username="username")) return [ - User.from_hypercore(hypercore_data=hypercore_dict).to_ansible( # type: ignore - rest_client - ) + User.from_hypercore(hypercore_data=hypercore_dict).to_ansible(rest_client) # type: ignore for hypercore_dict in rest_client.list_records("/rest/v1/User", query) ] @@ -105,9 +104,7 @@ def run( def main() -> None: module = AnsibleModule( supports_check_mode=True, - argument_spec=dict( - arguments.get_spec("cluster_instance"), username=dict(type="str") - ), + argument_spec=dict(arguments.get_spec("cluster_instance"), username=dict(type="str")), ) try: diff --git a/plugins/modules/version_update.py b/plugins/modules/version_update.py index c76bf81b..138e9f85 100644 --- a/plugins/modules/version_update.py +++ b/plugins/modules/version_update.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -96,20 +98,23 @@ sample: 0 """ +from typing import Any +from typing import Dict +from typing import Optional +from typing import Tuple + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient from ..module_utils.cluster import Cluster from ..module_utils.hypercore_version import Update +from ..module_utils.rest_client import RestClient from ..module_utils.typed_classes import TypedUpdateToAnsible -from typing import Tuple, Dict, Any, Optional -def run( - module: AnsibleModule, rest_client: RestClient -) -> Tuple[bool, Optional[TypedUpdateToAnsible], Dict[Any, Any]]: +def run(module: AnsibleModule, rest_client: RestClient) -> Tuple[bool, Optional[TypedUpdateToAnsible], Dict[Any, Any]]: cluster = Cluster.get(rest_client) new_icos_version = module.params["icos_version"] if cluster.icos_version == new_icos_version: diff --git a/plugins/modules/version_update_info.py b/plugins/modules/version_update_info.py index 85794a09..bc00b973 100644 --- a/plugins/modules/version_update_info.py +++ b/plugins/modules/version_update_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -150,15 +152,19 @@ sample: 0 """ +import operator +from typing import List +from typing import Optional +from typing import Tuple + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors -from ..module_utils.rest_client import RestClient +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.hypercore_version import Update +from ..module_utils.rest_client import RestClient from ..module_utils.typed_classes import TypedUpdateToAnsible -from typing import List, Optional, Tuple -import operator def run( @@ -173,11 +179,7 @@ def run( for hypercore_dict in rest_client.list_records("/rest/v1/Update") ] if records: - records.sort( - key=operator.itemgetter( - "major_version", "minor_version", "revision", "build_id" - ) - ) + records.sort(key=operator.itemgetter("major_version", "minor_version", "revision", "build_id")) return records, records[0], records[-1] return records, None, None @@ -193,8 +195,8 @@ def main() -> None: try: client = Client.get_client(module.params["cluster_instance"]) rest_client = RestClient(client) - records, next, latest = run(rest_client) - module.exit_json(changed=False, records=records, next=next, latest=latest) + records, next_version, latest_version = run(rest_client) + module.exit_json(changed=False, records=records, next=next_version, latest=latest_version) except errors.ScaleComputingError as e: module.fail_json(msg=str(e)) diff --git a/plugins/modules/version_update_status_info.py b/plugins/modules/version_update_status_info.py index cd4ad10e..7c2b0745 100644 --- a/plugins/modules/version_update_status_info.py +++ b/plugins/modules/version_update_status_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -76,12 +78,14 @@ """ from typing import Optional + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors -from ..module_utils.rest_client import RestClient +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.hypercore_version import UpdateStatus +from ..module_utils.rest_client import RestClient from ..module_utils.typed_classes import TypedUpdateStatusToAnsible diff --git a/plugins/modules/virtual_disk.py b/plugins/modules/virtual_disk.py index f18e3724..c637856e 100644 --- a/plugins/modules/virtual_disk.py +++ b/plugins/modules/virtual_disk.py @@ -3,7 +3,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -89,27 +91,25 @@ sample: 7983b298-c37a-4c99-8dfe-b2952e81b092 """ -from ansible.module_utils.basic import AnsibleModule -from typing import Tuple, Optional import os import time +from typing import Optional +from typing import Tuple + +from ansible.module_utils.basic import AnsibleModule -from ..module_utils.typed_classes import ( - TypedVirtualDiskToAnsible, - TypedDiff, - TypedTaskTag, -) -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client +from ..module_utils.hypercore_version import HyperCoreVersion from ..module_utils.rest_client import RestClient -from ..module_utils.utils import is_changed -from ..module_utils.virtual_disk import VirtualDisk from ..module_utils.state import State from ..module_utils.task_tag import TaskTag - -from ..module_utils.hypercore_version import ( - HyperCoreVersion, -) +from ..module_utils.typed_classes import TypedDiff +from ..module_utils.typed_classes import TypedTaskTag +from ..module_utils.typed_classes import TypedVirtualDiskToAnsible +from ..module_utils.utils import is_changed +from ..module_utils.virtual_disk import VirtualDisk HYPERCORE_VERSION_REQUIREMENTS = ">=9.2.10" @@ -118,9 +118,7 @@ def read_disk_file(module: AnsibleModule) -> int: try: file_size = os.path.getsize(module.params["source"]) except FileNotFoundError: - raise errors.ScaleComputingError( - f"Disk file {module.params['source']} not found." - ) + raise errors.ScaleComputingError(f"Disk file {module.params['source']} not found.") return file_size @@ -131,9 +129,7 @@ def wait_task_and_get_updated( must_exist: bool = False, ) -> Optional[TypedVirtualDiskToAnsible]: TaskTag.wait_task(rest_client, task) - updated_disk = VirtualDisk.get_by_name( - rest_client, name=module.params["name"], must_exist=must_exist - ) + updated_disk = VirtualDisk.get_by_name(rest_client, name=module.params["name"], must_exist=must_exist) return updated_disk.to_ansible() if updated_disk else None @@ -150,9 +146,7 @@ def ensure_present( else: file_size = read_disk_file(module) if not file_size: - raise errors.ScaleComputingError( - f"Invalid size for file: {module.params['source']}" - ) + raise errors.ScaleComputingError(f"Invalid size for file: {module.params['source']}") task = VirtualDisk.send_upload_request(rest_client, file_size, module) after = wait_task_and_get_updated(rest_client, module, task, must_exist=False) return is_changed(before, after), after, dict(before=before, after=after) @@ -183,9 +177,7 @@ def ensure_absent( # Virtual disk can only be created or deleted; No update actions available. -def run( - module: AnsibleModule, rest_client: RestClient -) -> Tuple[bool, Optional[TypedVirtualDiskToAnsible], TypedDiff]: +def run(module: AnsibleModule, rest_client: RestClient) -> Tuple[bool, Optional[TypedVirtualDiskToAnsible], TypedDiff]: virtual_disk_obj = VirtualDisk.get_by_name(rest_client, name=module.params["name"]) if module.params["state"] == State.present: return ensure_present(module, rest_client, virtual_disk_obj) diff --git a/plugins/modules/virtual_disk_attach.py b/plugins/modules/virtual_disk_attach.py index 2ac1cc08..247f6922 100644 --- a/plugins/modules/virtual_disk_attach.py +++ b/plugins/modules/virtual_disk_attach.py @@ -3,7 +3,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -161,19 +163,24 @@ """ +from typing import Any +from typing import Dict +from typing import Optional +from typing import Tuple + from ansible.module_utils.basic import AnsibleModule -from typing import Tuple, Optional, Any, Dict -from ..module_utils.typed_classes import TypedDiff, TypedDiskToAnsible -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient -from ..module_utils.virtual_disk import VirtualDisk from ..module_utils.disk import Disk +from ..module_utils.hypercore_version import HyperCoreVersion +from ..module_utils.rest_client import RestClient from ..module_utils.task_tag import TaskTag +from ..module_utils.typed_classes import TypedDiff +from ..module_utils.typed_classes import TypedDiskToAnsible +from ..module_utils.virtual_disk import VirtualDisk from ..module_utils.vm import VM -from ..module_utils.hypercore_version import HyperCoreVersion - HYPERCORE_VERSION_REQUIREMENTS = ">=9.2.10" @@ -185,17 +192,15 @@ def is_slot_available(module: AnsibleModule, vm: VM) -> Tuple[bool, Optional[Dis return True, None -def create_payload( - module: AnsibleModule, vm: VM, virtual_disk: VirtualDisk -) -> Dict[Any, Any]: +def create_payload(module: AnsibleModule, vm: VM, virtual_disk: VirtualDisk) -> Dict[Any, Any]: payload = {} payload["options"] = dict( regenerateDiskID=module.params["disk"]["regenerate_disk_id"], readOnly=module.params["disk"]["read_only"], ) - payload["template"] = Disk.from_ansible( # type: ignore - module.params["disk"] - ).post_and_patch_payload(vm, existing_disk=None) + payload["template"] = Disk.from_ansible(module.params["disk"]).post_and_patch_payload( # type: ignore + vm, existing_disk=None + ) payload["template"].pop("readOnly") # get() does not work, since key is always present if module.params["disk"]["size"]: @@ -207,9 +212,7 @@ def create_payload( return payload -def run( - module: AnsibleModule, rest_client: RestClient -) -> Tuple[bool, Optional[TypedDiskToAnsible], TypedDiff]: +def run(module: AnsibleModule, rest_client: RestClient) -> Tuple[bool, Optional[TypedDiskToAnsible], TypedDiff]: vm = VM.get_by_name(module.params, rest_client) slot_available, disk = is_slot_available(module, vm) # type: ignore if not slot_available: @@ -218,9 +221,7 @@ def run( disk.to_ansible(), # type: ignore dict(before=disk.to_ansible(), after=disk.to_ansible()), # type: ignore ) - virtual_disk = VirtualDisk.get_by_name( - rest_client, name=module.params["name"], must_exist=True - ) + virtual_disk = VirtualDisk.get_by_name(rest_client, name=module.params["name"], must_exist=True) payload = create_payload(module, vm, virtual_disk) # type: ignore task_tag = virtual_disk.attach_to_vm(rest_client, payload) # type: ignore TaskTag.wait_task(rest_client, task_tag) @@ -253,9 +254,7 @@ def main() -> None: ), disk_slot=dict(type="int", required=True), size=dict(type="int"), - cache_mode=dict( - type="str", choices=["none", "writeback", "writethrough"] - ), + cache_mode=dict(type="str", choices=["none", "writeback", "writethrough"]), disable_snapshotting=dict(type="bool"), tiering_priority_factor=dict( type="int", diff --git a/plugins/modules/virtual_disk_info.py b/plugins/modules/virtual_disk_info.py index 499db67b..6a8e5689 100644 --- a/plugins/modules/virtual_disk_info.py +++ b/plugins/modules/virtual_disk_info.py @@ -3,7 +3,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -74,28 +76,24 @@ """ -from ansible.module_utils.basic import AnsibleModule from typing import List -from ..module_utils.typed_classes import ( - TypedVirtualDiskToAnsible, -) -from ..module_utils import errors, arguments +from ansible.module_utils.basic import AnsibleModule + +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient, CachedRestClient +from ..module_utils.hypercore_version import HyperCoreVersion +from ..module_utils.rest_client import CachedRestClient +from ..module_utils.rest_client import RestClient +from ..module_utils.typed_classes import TypedVirtualDiskToAnsible from ..module_utils.utils import get_query from ..module_utils.virtual_disk import VirtualDisk -from ..module_utils.hypercore_version import ( - HyperCoreVersion, -) - HYPERCORE_VERSION_REQUIREMENTS = ">=9.2.10" -def run( - module: AnsibleModule, rest_client: RestClient -) -> List[TypedVirtualDiskToAnsible]: +def run(module: AnsibleModule, rest_client: RestClient) -> List[TypedVirtualDiskToAnsible]: query = get_query(module.params, "name", ansible_hypercore_map=dict(name="name")) return VirtualDisk.get_state(rest_client, query) diff --git a/plugins/modules/vm.py b/plugins/modules/vm.py index 12949c6f..00b4924b 100644 --- a/plugins/modules/vm.py +++ b/plugins/modules/vm.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -397,23 +399,22 @@ sample: true """ -from ansible.module_utils.basic import AnsibleModule - from typing import List -from ..module_utils import arguments, errors +from ansible.module_utils.basic import AnsibleModule + +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client +from ..module_utils.hypercore_version import HyperCoreVersion from ..module_utils.rest_client import RestClient -from ..module_utils.vm import ( - VM, - ManageVMParams, - ManageVMDisks, - ManageVMNics, - VmMachineType, - compute_params_disk_slot, -) from ..module_utils.task_tag import TaskTag -from ..module_utils.hypercore_version import HyperCoreVersion +from ..module_utils.vm import VM +from ..module_utils.vm import ManageVMDisks +from ..module_utils.vm import ManageVMNics +from ..module_utils.vm import ManageVMParams +from ..module_utils.vm import VmMachineType +from ..module_utils.vm import compute_params_disk_slot MODULE_PATH = "scale_computing.hypercore.vm" @@ -432,21 +433,15 @@ def _set_boot_order(module, rest_client, vm, existing_boot_order): def _set_disks(module, rest_client, vm_before: VM): - return ManageVMDisks.ensure_present_or_set( - module, rest_client, MODULE_PATH, vm_before - ) + return ManageVMDisks.ensure_present_or_set(module, rest_client, MODULE_PATH, vm_before) def _set_nics(module, rest_client, vm_before: VM): - return ManageVMNics.ensure_present_or_set( - module, rest_client, MODULE_PATH, vm_before - ) + return ManageVMNics.ensure_present_or_set(module, rest_client, MODULE_PATH, vm_before) def _set_vm_params(module, rest_client, vm, param_subset: List[str]): - changed_params, diff, changed_parameters = ManageVMParams.set_vm_params( - module, rest_client, vm, param_subset - ) + changed_params, diff, changed_parameters = ManageVMParams.set_vm_params(module, rest_client, vm, param_subset) return changed_params, changed_parameters @@ -462,17 +457,13 @@ def ensure_present(module, rest_client): ) changed_disks = _set_disks(module, rest_client, vm_before) changed_nics = _set_nics(module, rest_client, vm_before) - changed_order = _set_boot_order( - module, rest_client, vm_before, existing_boot_order - ) + changed_order = _set_boot_order(module, rest_client, vm_before, existing_boot_order) # Set vm params # ManageVMParams.set_vm_params has to be executed only after setting the boot order, # since boot order cannot be set when the vm is running. # set_vm_params updates VM's name, description, tags, memory, number of CPU, # changed the power state and/or assigns the snapshot schedule to the VM - changed_params_2, changed_parameters_2 = _set_vm_params( - module, rest_client, vm_before, param_subset=[] - ) + changed_params_2, changed_parameters_2 = _set_vm_params(module, rest_client, vm_before, param_subset=[]) changed = any( ( changed_order, @@ -504,9 +495,7 @@ def ensure_present(module, rest_client): _set_boot_order(module, rest_client, vm_created, existing_boot_order) # Set power state if module.params["power_state"] != "shutdown": - vm_created.update_vm_power_state( - module, rest_client, module.params["power_state"], False - ) + vm_created.update_vm_power_state(module, rest_client, module.params["power_state"], False) changed = True name_field = "vm_name" was_vm_rebooted = False @@ -528,9 +517,7 @@ def ensure_absent(module, rest_client): if vm._power_state != "shutdown": # First, shut it off and then delete # TODO ==shutdown or ==stopped ?? vm.update_vm_power_state(module, rest_client, "stop", False) - task_tag = rest_client.delete_record( - "{0}/{1}".format("/rest/v1/VirDomain", vm.uuid), module.check_mode - ) + task_tag = rest_client.delete_record(f"/rest/v1/VirDomain/{vm.uuid}", module.check_mode) TaskTag.wait_task(rest_client, task_tag) output = vm.to_ansible() return True, [output], dict(before=output, after=None), reboot @@ -542,9 +529,7 @@ def check_params(module, rest_client): ansible_machine_type = module.params.get("machine_type") if ansible_machine_type: hcversion = HyperCoreVersion(rest_client) - hypercore_machine_type = VmMachineType.from_ansible_to_hypercore( - ansible_machine_type, hcversion - ) + hypercore_machine_type = VmMachineType.from_ansible_to_hypercore(ansible_machine_type, hcversion) if not hypercore_machine_type: msg = f"machine_type={ansible_machine_type} is not supported on HyperCore version {hcversion.version}." module.fail_json(msg=msg) diff --git a/plugins/modules/vm_boot_devices.py b/plugins/modules/vm_boot_devices.py index 4e7d05c3..7ae8a6e5 100644 --- a/plugins/modules/vm_boot_devices.py +++ b/plugins/modules/vm_boot_devices.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -215,20 +217,19 @@ sample: true """ -from ansible.module_utils.basic import AnsibleModule from copy import deepcopy +from ansible.module_utils.basic import AnsibleModule + from ..module_utils import arguments -from ..module_utils.errors import ScaleComputingError from ..module_utils.client import Client +from ..module_utils.errors import ScaleComputingError from ..module_utils.rest_client import RestClient from ..module_utils.vm import VM def ensure_absent(module, rest_client): - vm_before, boot_devices_before, before = VM.get_vm_and_boot_devices( - module.params, rest_client - ) + vm_before, boot_devices_before, before = VM.get_vm_and_boot_devices(module.params, rest_client) changed = False for desired_boot_device in module.params["items"]: vm_device = vm_before.get_vm_device(desired_boot_device) @@ -239,16 +240,12 @@ def ensure_absent(module, rest_client): boot_order.remove(uuid) VM.update_boot_device_order(module, rest_client, vm_before, boot_order) changed = True - vm_after, boot_devices_after, after = VM.get_vm_and_boot_devices( - module.params, rest_client - ) + vm_after, boot_devices_after, after = VM.get_vm_and_boot_devices(module.params, rest_client) return changed, after, dict(before=before, after=after), vm_before.was_vm_rebooted() def ensure_present(module, rest_client): - vm_before, boot_devices_before, before = VM.get_vm_and_boot_devices( - module.params, rest_client - ) + vm_before, boot_devices_before, before = VM.get_vm_and_boot_devices(module.params, rest_client) changed = False for desired_boot_device in module.params["items"]: vm_device = vm_before.get_vm_device(desired_boot_device) @@ -268,29 +265,19 @@ def ensure_present(module, rest_client): continue VM.update_boot_device_order(module, rest_client, vm_before, desired_boot_order) changed = True - vm_after, boot_devices_after, after = VM.get_vm_and_boot_devices( - module.params, rest_client - ) + vm_after, boot_devices_after, after = VM.get_vm_and_boot_devices(module.params, rest_client) return changed, after, dict(before=before, after=after), vm_before.was_vm_rebooted() def ensure_set(module, rest_client): - vm_before, boot_devices_before, before = VM.get_vm_and_boot_devices( - module.params, rest_client - ) - changed = vm_before.set_boot_devices( - module.params["items"], module, rest_client, boot_devices_before - ) - vm_after, boot_devices_after, after = VM.get_vm_and_boot_devices( - module.params, rest_client - ) + vm_before, boot_devices_before, before = VM.get_vm_and_boot_devices(module.params, rest_client) + changed = vm_before.set_boot_devices(module.params["items"], module, rest_client, boot_devices_before) + vm_after, boot_devices_after, after = VM.get_vm_and_boot_devices(module.params, rest_client) return changed, after, dict(before=before, after=after), vm_before.was_vm_rebooted() def run(module, rest_client): - vm, boot_devices_before, before = VM.get_vm_and_boot_devices( - module.params, rest_client - ) + vm, boot_devices_before, before = VM.get_vm_and_boot_devices(module.params, rest_client) if module.params["state"] == "absent": changed, after, diff, reboot = ensure_absent(module, rest_client) elif module.params["state"] == "set": diff --git a/plugins/modules/vm_clone.py b/plugins/modules/vm_clone.py index f2f187cb..8d518a9e 100644 --- a/plugins/modules/vm_clone.py +++ b/plugins/modules/vm_clone.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -86,12 +88,14 @@ """ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors + +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient +from ..module_utils.task_tag import TaskTag from ..module_utils.vm import VM from ..module_utils.vm_snapshot import VMSnapshot as Snapshot -from ..module_utils.task_tag import TaskTag # Check snapshot list, raise error if necessary. @@ -114,9 +118,7 @@ def check_snapshot_list(module: AnsibleModule, snapshot_list: list) -> None: ) -def get_snapshot( - module: AnsibleModule, rest_client: RestClient, virtual_machine_obj: VM -) -> AnsibleModule: +def get_snapshot(module: AnsibleModule, rest_client: RestClient, virtual_machine_obj: VM) -> AnsibleModule: snapshot_list = [] # Get snapshot from uuid. if module.params["source_snapshot_uuid"]: @@ -154,9 +156,7 @@ def run(module, rest_client): ) # Get Source VM, fail if not found. - virtual_machine_obj = VM.get_or_fail( - query={"name": module.params["source_vm_name"]}, rest_client=rest_client - )[0] + virtual_machine_obj = VM.get_or_fail(query={"name": module.params["source_vm_name"]}, rest_client=rest_client)[0] if module.params["source_snapshot_label"] or module.params["source_snapshot_uuid"]: module = get_snapshot(module, rest_client, virtual_machine_obj) @@ -188,9 +188,7 @@ def main(): type="str", required=True, ), - tags=dict( # We give user a chance to add aditional tags here. - type="list", elements="str" - ), + tags=dict(type="list", elements="str"), # We give user a chance to add aditional tags here. cloud_init=dict( type="dict", default={}, diff --git a/plugins/modules/vm_disk.py b/plugins/modules/vm_disk.py index da4d764c..b8882c97 100644 --- a/plugins/modules/vm_disk.py +++ b/plugins/modules/vm_disk.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -289,15 +291,15 @@ from ansible.module_utils.basic import AnsibleModule from ..module_utils import arguments -from ..module_utils.errors import ScaleComputingError from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient -from ..module_utils.vm import ManageVMDisks, compute_params_disk_slot -from ..module_utils.task_tag import TaskTag from ..module_utils.disk import Disk +from ..module_utils.errors import ScaleComputingError from ..module_utils.iso import ISO +from ..module_utils.rest_client import RestClient +from ..module_utils.task_tag import TaskTag from ..module_utils.utils import filter_dict - +from ..module_utils.vm import ManageVMDisks +from ..module_utils.vm import compute_params_disk_slot MODULE_PATH = "scale_computing.hypercore.vm_disk" @@ -323,14 +325,12 @@ def ensure_absent(module, rest_client): if name: # Detach the ISO image iso = ISO.get_by_name(dict(name=name), rest_client, must_exist=True) - ManageVMDisks.iso_image_management( - module, rest_client, iso, uuid, attach=False - ) + ManageVMDisks.iso_image_management(module, rest_client, iso, uuid, attach=False) # Remove the disk if existing_disk.needs_reboot("delete"): vm_before.do_shutdown_steps(module, rest_client) task_tag = rest_client.delete_record( - "{0}/{1}".format("/rest/v1/VirDomainBlockDevice", uuid), + f"/rest/v1/VirDomainBlockDevice/{uuid}", module.check_mode, ) TaskTag.wait_task(rest_client, task_tag, module.check_mode) diff --git a/plugins/modules/vm_export.py b/plugins/modules/vm_export.py index 34d2f37e..62134809 100644 --- a/plugins/modules/vm_export.py +++ b/plugins/modules/vm_export.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -85,17 +87,17 @@ """ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors + +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient -from ..module_utils.vm import VM from ..module_utils.task_tag import TaskTag +from ..module_utils.vm import VM def run(module, rest_client): - virtual_machine_obj = VM.get_or_fail( - query={"name": module.params["vm_name"]}, rest_client=rest_client - )[0] + virtual_machine_obj = VM.get_or_fail(query={"name": module.params["vm_name"]}, rest_client=rest_client)[0] try: task = virtual_machine_obj.export_vm(rest_client, module.params) TaskTag.wait_task(rest_client, task) diff --git a/plugins/modules/vm_import.py b/plugins/modules/vm_import.py index 410aac14..18575e0b 100644 --- a/plugins/modules/vm_import.py +++ b/plugins/modules/vm_import.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -138,17 +140,17 @@ """ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors + +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient -from ..module_utils.vm import VM from ..module_utils.task_tag import TaskTag +from ..module_utils.vm import VM def run(module, rest_client): - virtual_machine_obj_list = VM.get( - query={"name": module.params["vm_name"]}, rest_client=rest_client - ) + virtual_machine_obj_list = VM.get(query={"name": module.params["vm_name"]}, rest_client=rest_client) if len(virtual_machine_obj_list) > 0: return False, f"Virtual machine - {module.params['vm_name']} - already exists." task = VM.import_vm(rest_client, module.params) @@ -156,9 +158,7 @@ def run(module, rest_client): task_status = TaskTag.get_task_status(rest_client, task) if task_status and task_status.get("state", "") == "COMPLETE": return True, f"Virtual machine - {module.params['vm_name']} - import complete." - raise errors.ScaleComputingError( - f"There was a problem during import of {module.params['vm_name']}, import failed." - ) + raise errors.ScaleComputingError(f"There was a problem during import of {module.params['vm_name']}, import failed.") def main(): diff --git a/plugins/modules/vm_info.py b/plugins/modules/vm_info.py index 31759370..886fe2fa 100644 --- a/plugins/modules/vm_info.py +++ b/plugins/modules/vm_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -147,11 +149,12 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.vm import VM -from ..module_utils.utils import get_query from ..module_utils.rest_client import CachedRestClient +from ..module_utils.utils import get_query +from ..module_utils.vm import VM def run(module, rest_client): diff --git a/plugins/modules/vm_nic.py b/plugins/modules/vm_nic.py index e77c6def..cea730de 100644 --- a/plugins/modules/vm_nic.py +++ b/plugins/modules/vm_nic.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -182,13 +184,14 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient -from ..module_utils.vm import VM, ManageVMNics from ..module_utils.nic import Nic +from ..module_utils.rest_client import RestClient from ..module_utils.state import NicState - +from ..module_utils.vm import VM +from ..module_utils.vm import ManageVMNics MODULE_PATH = "scale_computing.hypercore.vm_nic" @@ -226,17 +229,13 @@ def ensure_absent(module, rest_client, vm_before: VM): def run(module, rest_client): - virtual_machine_obj_list = VM.get( - query={"name": module.params["vm_name"]}, rest_client=rest_client - ) + virtual_machine_obj_list = VM.get(query={"name": module.params["vm_name"]}, rest_client=rest_client) if len(virtual_machine_obj_list) == 0: # VM absent, might be typo in vm_name module.fail_json(f"VM with name={module.params['vm_name']} not found.") vm_before = virtual_machine_obj_list[0] if module.params["state"] in [NicState.present, NicState.set]: - changed, records, diff = ManageVMNics.ensure_present_or_set( - module, rest_client, MODULE_PATH, vm_before - ) + changed, records, diff = ManageVMNics.ensure_present_or_set(module, rest_client, MODULE_PATH, vm_before) else: changed, records, diff = ensure_absent(module, rest_client, vm_before) vm_before.vm_power_up(module, rest_client) diff --git a/plugins/modules/vm_nic_info.py b/plugins/modules/vm_nic_info.py index cf1e1753..b610469f 100644 --- a/plugins/modules/vm_nic_info.py +++ b/plugins/modules/vm_nic_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -83,16 +85,15 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.vm import VM from ..module_utils.rest_client import RestClient +from ..module_utils.vm import VM def run(module, rest_client): - virtual_machine = VM.get_or_fail( - query={"name": module.params["vm_name"]}, rest_client=rest_client - )[0] + virtual_machine = VM.get_or_fail(query={"name": module.params["vm_name"]}, rest_client=rest_client)[0] if not module.params["vlan"]: return False, [nic.to_ansible() for nic in virtual_machine.nic_list] return False, [virtual_machine.find_nic(module.params["vlan"])[0].to_ansible()] diff --git a/plugins/modules/vm_node_affinity.py b/plugins/modules/vm_node_affinity.py index 1f299cab..22dec2c7 100644 --- a/plugins/modules/vm_node_affinity.py +++ b/plugins/modules/vm_node_affinity.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -130,19 +132,18 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient -from ..module_utils.vm import VM from ..module_utils.node import Node -from ..module_utils.utils import get_query +from ..module_utils.rest_client import RestClient from ..module_utils.task_tag import TaskTag +from ..module_utils.utils import get_query +from ..module_utils.vm import VM def get_node_uuid(module, node, rest_client): - if module.params[node] and any( - value == "" for value in module.params[node].values() - ): # delete node + if module.params[node] and any(value == "" for value in module.params[node].values()): # delete node node_uuid = "" return node_uuid if module.params[node] and any( @@ -191,13 +192,9 @@ def set_parameters_for_payload(module, vm, rest_client): def run(module, rest_client): - vm = VM.get_by_name( - module.params, rest_client, must_exist=True - ) # get vm from vm_name + vm = VM.get_by_name(module.params, rest_client, must_exist=True) # get vm from vm_name - strict_affinity, preferred_node_uuid, backup_node_uuid = set_parameters_for_payload( - module, vm, rest_client - ) + strict_affinity, preferred_node_uuid, backup_node_uuid = set_parameters_for_payload(module, vm, rest_client) if strict_affinity is True and preferred_node_uuid == "" and backup_node_uuid == "": raise errors.VMInvalidParams @@ -221,7 +218,7 @@ def run(module, rest_client): "backupNodeUUID": backup_node_uuid, } } - endpoint = "{0}/{1}".format("/rest/v1/VirDomain", vm.uuid) + endpoint = f"/rest/v1/VirDomain/{vm.uuid}" task_tag = rest_client.update_record(endpoint, payload, module.check_mode) TaskTag.wait_task(rest_client, task_tag) vm_after = VM.get_by_name(module.params, rest_client, must_exist=True) @@ -234,9 +231,7 @@ def run(module, rest_client): else None ), backup_node=( - Node.get_node({"uuid": backup_node_uuid}, rest_client).to_ansible() - if backup_node_uuid != "" - else None + Node.get_node({"uuid": backup_node_uuid}, rest_client).to_ansible() if backup_node_uuid != "" else None ), ) msg = "Node affinity successfully updated." diff --git a/plugins/modules/vm_params.py b/plugins/modules/vm_params.py index f942d496..407eddfb 100644 --- a/plugins/modules/vm_params.py +++ b/plugins/modules/vm_params.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -126,10 +128,11 @@ from ansible.module_utils.basic import AnsibleModule from ..module_utils import arguments -from ..module_utils.errors import ScaleComputingError from ..module_utils.client import Client +from ..module_utils.errors import ScaleComputingError from ..module_utils.rest_client import RestClient -from ..module_utils.vm import VM, ManageVMParams +from ..module_utils.vm import VM +from ..module_utils.vm import ManageVMParams def run(module, rest_client): @@ -137,9 +140,7 @@ def run(module, rest_client): # Update VM's name, description, tags, memory, number of CPUs, power_state and/or assign snapshot schedule. # In case if reboot is needed, set_vm_params will shutdown the vm # In case if reboot is not needed, set_vm_params will set power_state as specified in the module.params["power_state"] - changed, diff, changed_parameters = ManageVMParams.set_vm_params( - module, rest_client, vm, param_subset=[] - ) + changed, diff, changed_parameters = ManageVMParams.set_vm_params(module, rest_client, vm, param_subset=[]) if module.params["power_state"] not in ["shutdown", "stop"]: # VM will be powered on in case if reboot is needed and module.params["power_state"] in ["start", "reboot", "reset"] # if reboot is not needed, vm_power_up doesn't do anything @@ -151,9 +152,7 @@ def run(module, rest_client): # vm.vm_power_up can already start VM, and a second start here would assert. # ManageVMParams.set_vm_params can already shutdown/stop VM. ignore_repeated_request = True - vm.update_vm_power_state( - module, rest_client, requested_power_action, ignore_repeated_request - ) + vm.update_vm_power_state(module, rest_client, requested_power_action, ignore_repeated_request) return changed, vm.was_vm_rebooted(), diff diff --git a/plugins/modules/vm_replication.py b/plugins/modules/vm_replication.py index 468952a9..2580adc3 100644 --- a/plugins/modules/vm_replication.py +++ b/plugins/modules/vm_replication.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -84,10 +86,11 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client -from ..module_utils.rest_client import RestClient from ..module_utils.replication import Replication +from ..module_utils.rest_client import RestClient from ..module_utils.state import ReplicationState from ..module_utils.task_tag import TaskTag from ..module_utils.vm import VM @@ -97,9 +100,7 @@ def ensure_enabled_or_reenabled(module, rest_client): changed = False before = None after = None - virtual_machine_obj_list = VM.get_or_fail( - query={"name": module.params["vm_name"]}, rest_client=rest_client - ) + virtual_machine_obj_list = VM.get_or_fail(query={"name": module.params["vm_name"]}, rest_client=rest_client) existing_replication_obj_list = Replication.get( rest_client=rest_client, query={"sourceDomainUUID": virtual_machine_obj_list[0].uuid}, @@ -107,15 +108,13 @@ def ensure_enabled_or_reenabled(module, rest_client): if existing_replication_obj_list: # Update existing if ( module.params["remote_cluster"] is None - or existing_replication_obj_list[0].remote_cluster - == module.params["remote_cluster"] + or existing_replication_obj_list[0].remote_cluster == module.params["remote_cluster"] ) and existing_replication_obj_list[0].state != ReplicationState.enabled: before = existing_replication_obj_list[0].to_ansible() existing_replication_obj_list[0].state = ReplicationState.enabled data = existing_replication_obj_list[0].to_hypercore() rest_client.update_record( - endpoint="/rest/v1/VirDomainReplication/" - + existing_replication_obj_list[0].replication_uuid, + endpoint="/rest/v1/VirDomainReplication/" + existing_replication_obj_list[0].replication_uuid, payload=data, check_mode=False, ) @@ -126,23 +125,18 @@ def ensure_enabled_or_reenabled(module, rest_client): changed = True elif ( module.params["remote_cluster"] is not None - and existing_replication_obj_list[0].remote_cluster - != module.params["remote_cluster"] + and existing_replication_obj_list[0].remote_cluster != module.params["remote_cluster"] ): raise errors.ReplicationNotUnique(virtual_machine_obj_list[0].name) else: # Create replication - cluster_connection = Replication.find_available_cluster_connection_or_fail( - rest_client, module.params - ) + cluster_connection = Replication.find_available_cluster_connection_or_fail(rest_client, module.params) new_replication_obj = Replication.from_ansible( ansible_data=module.params, virtual_machine_obj=virtual_machine_obj_list[0], cluster_connection=cluster_connection, ) data = new_replication_obj.to_hypercore() - response = rest_client.create_record( - endpoint="/rest/v1/VirDomainReplication", payload=data, check_mode=False - ) + response = rest_client.create_record(endpoint="/rest/v1/VirDomainReplication", payload=data, check_mode=False) TaskTag.wait_task(rest_client=rest_client, task=response) after = Replication.get( rest_client=rest_client, @@ -160,23 +154,17 @@ def ensure_disabled(module, rest_client): changed = False after = None before = None - virtual_machine_obj_list = VM.get_or_fail( - query={"name": module.params["vm_name"]}, rest_client=rest_client - ) + virtual_machine_obj_list = VM.get_or_fail(query={"name": module.params["vm_name"]}, rest_client=rest_client) existing_replication_obj_list = Replication.get( rest_client=rest_client, query={"sourceDomainUUID": virtual_machine_obj_list[0].uuid}, ) - if ( - existing_replication_obj_list - and existing_replication_obj_list[0].state != ReplicationState.disabled - ): + if existing_replication_obj_list and existing_replication_obj_list[0].state != ReplicationState.disabled: before = existing_replication_obj_list[0].to_ansible() existing_replication_obj_list[0].state = ReplicationState.disabled data = existing_replication_obj_list[0].to_hypercore() rest_client.update_record( - endpoint="/rest/v1/VirDomainReplication/" - + existing_replication_obj_list[0].replication_uuid, + endpoint="/rest/v1/VirDomainReplication/" + existing_replication_obj_list[0].replication_uuid, payload=data, check_mode=False, ) diff --git a/plugins/modules/vm_replication_info.py b/plugins/modules/vm_replication_info.py index 0d6bb275..b7ee6555 100644 --- a/plugins/modules/vm_replication_info.py +++ b/plugins/modules/vm_replication_info.py @@ -4,8 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function - +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -69,23 +70,21 @@ from ansible.module_utils.basic import AnsibleModule -from ..module_utils import arguments, errors +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client +from ..module_utils.replication import Replication from ..module_utils.rest_client import RestClient from ..module_utils.vm import VM -from ..module_utils.replication import Replication def run(module, rest_client): if not module.params["vm_name"]: records = [ - replication_obj.to_ansible() - for replication_obj in Replication.get(rest_client=rest_client, query=None) + replication_obj.to_ansible() for replication_obj in Replication.get(rest_client=rest_client, query=None) ] else: - virtual_machine_obj_list = VM.get_or_fail( - query={"name": module.params["vm_name"]}, rest_client=rest_client - ) + virtual_machine_obj_list = VM.get_or_fail(query={"name": module.params["vm_name"]}, rest_client=rest_client) replication_list = Replication.get( query={"sourceDomainUUID": virtual_machine_obj_list[0].uuid}, rest_client=rest_client, diff --git a/plugins/modules/vm_snapshot.py b/plugins/modules/vm_snapshot.py index 67eae219..9b39cd62 100644 --- a/plugins/modules/vm_snapshot.py +++ b/plugins/modules/vm_snapshot.py @@ -3,7 +3,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -142,26 +144,26 @@ uuid: 7c4f0fa5-868c-4d06-89d7-c5db7d142030 """ +from typing import List +from typing import Optional +from typing import Tuple + from ansible.module_utils.basic import AnsibleModule -from typing import Tuple, Optional, List -from ..module_utils.typed_classes import ( - TypedVMSnapshotToAnsible, - TypedDiff, -) -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient -from ..module_utils.utils import is_changed from ..module_utils.state import State from ..module_utils.task_tag import TaskTag -from ..module_utils.vm_snapshot import VMSnapshot +from ..module_utils.typed_classes import TypedDiff +from ..module_utils.typed_classes import TypedVMSnapshotToAnsible +from ..module_utils.utils import is_changed from ..module_utils.vm import VM +from ..module_utils.vm_snapshot import VMSnapshot -def get_snapshot( - module: AnsibleModule, rest_client: RestClient, vm_object: VM -) -> List[TypedVMSnapshotToAnsible]: +def get_snapshot(module: AnsibleModule, rest_client: RestClient, vm_object: VM) -> List[TypedVMSnapshotToAnsible]: # Get snapshot by uuid first if parameter exists. if module.params["uuid"]: snapshot_list = VMSnapshot.get_snapshots_by_query( @@ -223,9 +225,7 @@ def ensure_absent( return False, before, dict(before=before, after=before) # Send delete request. - task = VMSnapshot.send_delete_request( - rest_client, snapshot_list[0]["snapshot_uuid"] - ) + task = VMSnapshot.send_delete_request(rest_client, snapshot_list[0]["snapshot_uuid"]) TaskTag.wait_task(rest_client, task) # Get after from API, check snapshot was deleted. @@ -236,9 +236,7 @@ def ensure_absent( return is_changed(before, after), after, dict(before=before, after=after) -def run( - module: AnsibleModule, rest_client: RestClient -) -> Tuple[bool, Optional[TypedVMSnapshotToAnsible], TypedDiff]: +def run(module: AnsibleModule, rest_client: RestClient) -> Tuple[bool, Optional[TypedVMSnapshotToAnsible], TypedDiff]: vm_object: VM = VM.get_by_name(module.params, rest_client, must_exist=True) # type: ignore snapshot_list = get_snapshot(module, rest_client, vm_object) diff --git a/plugins/modules/vm_snapshot_attach_disk.py b/plugins/modules/vm_snapshot_attach_disk.py index 33d17399..56917737 100644 --- a/plugins/modules/vm_snapshot_attach_disk.py +++ b/plugins/modules/vm_snapshot_attach_disk.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -113,16 +115,21 @@ """ +from typing import Any +from typing import Dict +from typing import Optional +from typing import Tuple + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient -from ..module_utils.vm_snapshot import VMSnapshot -from ..module_utils.vm import VM from ..module_utils.task_tag import TaskTag from ..module_utils.typed_classes import TypedDiff -from typing import Tuple, Dict, Any, Optional +from ..module_utils.vm import VM +from ..module_utils.vm_snapshot import VMSnapshot def attach_disk( @@ -137,9 +144,7 @@ def attach_disk( # source source_snapshot_uuid = module.params["source_snapshot_uuid"] source_disk_type = module.params["source_disk_type"] - source_disk_slot = int( - module.params["source_disk_slot"] - ) # the higher the index, the newer the disk + source_disk_slot = int(module.params["source_disk_slot"]) # the higher the index, the newer the disk # Get destination VM object vm_object = VM.get_by_name(module.params, rest_client, must_exist=True) @@ -147,15 +152,11 @@ def attach_disk( raise errors.ScaleComputingError("VM named '" + vm_name + "' doesn't exist.") # =============== IMPLEMENTATION =================== - vm_snapshot_hypercore = VMSnapshot.get_snapshot_by_uuid( - source_snapshot_uuid, rest_client - ) + vm_snapshot_hypercore = VMSnapshot.get_snapshot_by_uuid(source_snapshot_uuid, rest_client) # if the desired snapshot (with source_snapshot_uuid) doesn't exist, raise an error. if vm_snapshot_hypercore is None: - raise errors.ScaleComputingError( - "Snapshot with uuid='" + source_snapshot_uuid + "' doesn't exist." - ) + raise errors.ScaleComputingError("Snapshot with uuid='" + source_snapshot_uuid + "' doesn't exist.") vm_snapshot = vm_snapshot_hypercore.to_ansible() @@ -182,9 +183,7 @@ def attach_disk( # First power off the destination VM vm_object.do_shutdown_steps(module, rest_client) # type: ignore - source_disk_info = VMSnapshot.get_snapshot_disk( - vm_snapshot, slot=source_disk_slot, _type=source_disk_type - ) + source_disk_info = VMSnapshot.get_snapshot_disk(vm_snapshot, slot=source_disk_slot, _type=source_disk_type) # build a payload according to /rest/v1/VirDomainBlockDevice/{uuid}/clone documentation payload = dict( @@ -205,17 +204,13 @@ def attach_disk( ) create_task_tag = rest_client.create_record( - endpoint="/rest/v1/VirDomainBlockDevice/{0}/clone".format( - source_disk_info["uuid"] - ), + endpoint=f"/rest/v1/VirDomainBlockDevice/{source_disk_info['uuid']}/clone", payload=payload, check_mode=module.check_mode, ) TaskTag.wait_task(rest_client, create_task_tag) - created_disk = VMSnapshot.get_vm_disk_info_by_uuid( - create_task_tag["createdUUID"], rest_client - ) + created_disk = VMSnapshot.get_vm_disk_info_by_uuid(create_task_tag["createdUUID"], rest_client) # Restart the previously running VM (destination) vm_object.vm_power_up(module, rest_client) # type: ignore @@ -232,9 +227,7 @@ def attach_disk( ) -def run( - module: AnsibleModule, rest_client: RestClient -) -> Tuple[bool, Optional[Dict[Any, Any]], TypedDiff, bool]: +def run(module: AnsibleModule, rest_client: RestClient) -> Tuple[bool, Optional[Dict[Any, Any]], TypedDiff, bool]: return attach_disk(module, rest_client) diff --git a/plugins/modules/vm_snapshot_info.py b/plugins/modules/vm_snapshot_info.py index 1b6fc31b..5095ce21 100644 --- a/plugins/modules/vm_snapshot_info.py +++ b/plugins/modules/vm_snapshot_info.py @@ -4,7 +4,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -147,19 +149,19 @@ """ +from typing import List + from ansible.module_utils.basic import AnsibleModule -from ..module_utils import errors, arguments +from ..module_utils import arguments +from ..module_utils import errors from ..module_utils.client import Client from ..module_utils.rest_client import RestClient -from ..module_utils.vm_snapshot import VMSnapshot from ..module_utils.typed_classes import TypedVMSnapshotToAnsible -from typing import List +from ..module_utils.vm_snapshot import VMSnapshot -def run( - module: AnsibleModule, rest_client: RestClient -) -> List[TypedVMSnapshotToAnsible]: +def run(module: AnsibleModule, rest_client: RestClient) -> List[TypedVMSnapshotToAnsible]: filtered = VMSnapshot.filter_snapshots_by_params(module.params, rest_client) return filtered diff --git a/pyproject.toml b/pyproject.toml index c4cfe06c..676965d8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -80,3 +80,35 @@ disable_error_code = ["no-untyped-def", "no-untyped-call", "assignment", "type-a target-version = ["py38"] # exclude - a regex like 'plugins/inventory/hypercore.py|second.py' exclude = 'plugins/inventory/hypercore.py' +line_length = 120 + +[tool.isort] +profile = "black" +force_single_line = true +line_length = 120 + +src_paths = [ + "plugins", + "tests/unit", + "tests/integration", +] + +#sections = ["FUTURE", "STDLIB", "THIRDPARTY", "FIRSTPARTY", "ANSIBLE_CORE", "ANSIBLE_AMAZON_AWS", "ANSIBLE_COMMUNITY_AWS", "LOCALFOLDER"] +sections = ["FUTURE", "STDLIB", "THIRDPARTY", "FIRSTPARTY", "ANSIBLE_CORE", "LOCALFOLDER"] +#known_third_party = ["botocore", "boto3"] +known_ansible_core = ["ansible"] +#known_ansible_amazon_aws = ["ansible_collections.amazon.aws"] +#known_ansible_community_aws = ["ansible_collections.community.aws"] + +[tool.flynt] +transform-joins = true +#exclude = [ +# "ec2_metadata_facts", +#] + +[tool.flake8] +# E123, E125 skipped as they are invalid PEP-8. +show-source = true +ignore = ["E123", "E125", "E203", "E402", "E501", "E741", "F401", "F811", "F841", "W503"] +max-line-length = 160 +builtins = "_" diff --git a/test-requirements.txt b/test-requirements.txt new file mode 100644 index 00000000..0b7947ee --- /dev/null +++ b/test-requirements.txt @@ -0,0 +1,17 @@ +#botocore +#boto3 + +#placebo +#mock +pytest +pytest-forked +pytest-mock +pytest-xdist +pytest-ansible + +# Needed for ansible.utils.ipaddr in tests +#netaddr +# Sometimes needed where we don't have features we need in modules +#awscli +# Used for comparing SSH Public keys to the Amazon fingerprints +cryptography diff --git a/test.requirements b/test.requirements index 7f51089a..aa1e7739 100644 --- a/test.requirements +++ b/test.requirements @@ -3,4 +3,6 @@ pytest==8.2.2 pytest-xdist==3.6.1 pytest-mock==3.14.0 pytest-forked==1.6.0 -ansible-lint==24.7.0 +ansible-lint==25.1.2 +isort +pylint diff --git a/tests/integration/targets/certificate/files/pyproxy.py b/tests/integration/targets/certificate/files/pyproxy.py index 7fa72794..9d008d02 100644 --- a/tests/integration/targets/certificate/files/pyproxy.py +++ b/tests/integration/targets/certificate/files/pyproxy.py @@ -20,7 +20,6 @@ import socket import time - FORMAT = "%(asctime)-15s %(levelname)-10s %(message)s" logging.basicConfig(format=FORMAT) LOGGER = logging.getLogger() @@ -153,9 +152,7 @@ def tcp_proxy_one_conn(s, dst, connection_count): restart = True break if inject_ssl_eof_error(connection_count): - LOGGER.info( - "Injecting SSL EOF to connection %s", s_src.getpeername() - ) + LOGGER.info("Injecting SSL EOF to connection %s", s_src.getpeername()) restart = True break s_src.sendall(d) @@ -205,9 +202,7 @@ def main(): proto_group.add_argument("--tcp", action="store_true", help="TCP proxy") proto_group.add_argument("--udp", action="store_true", help="UDP proxy") - parser.add_argument( - "-s", "--src", required=True, help="Source IP and port, i.e.: 127.0.0.1:8000" - ) + parser.add_argument("-s", "--src", required=True, help="Source IP and port, i.e.: 127.0.0.1:8000") parser.add_argument( "-d", "--dst", diff --git a/tests/unit/plugins/conftest.py b/tests/unit/plugins/conftest.py index dbddb05c..d1958a01 100644 --- a/tests/unit/plugins/conftest.py +++ b/tests/unit/plugins/conftest.py @@ -3,37 +3,25 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import json +import os +from unittest.mock import MagicMock import pytest +from ansible_collections.scale_computing.hypercore.plugins.module_utils.client import Client +from ansible_collections.scale_computing.hypercore.plugins.module_utils.hypercore_version import HyperCoreVersion +from ansible_collections.scale_computing.hypercore.plugins.module_utils.rest_client import RestClient +from ansible_collections.scale_computing.hypercore.plugins.module_utils.task_tag import TaskTag +from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import VM from ansible.module_utils import basic from ansible.module_utils._text import to_bytes -from unittest.mock import MagicMock -import os - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.client import ( - Client, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.rest_client import ( - RestClient, -) - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import ( - VM, -) - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.task_tag import ( - TaskTag, -) - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.hypercore_version import ( - HyperCoreVersion, -) @pytest.fixture @@ -103,20 +91,20 @@ def fail_json_mock(self, **result): raise AnsibleRunEnd(False, result) -def run_mock(module, client, another_client=None): +def run_mock(module, _client, _another_client=None): return False, {}, dict(before={}, after={}) -def run_mock_with_reboot(module, client, another_client=None): +def run_mock_with_reboot(module, _client, _another_client=None): return False, {}, dict(before={}, after={}), False # for syslog_server module -def run_mock_with_record_and_records(module, client, another_client=None): +def run_mock_with_record_and_records(module, _client, _another_client=None): return False, {}, [], dict(before={}, after={}) -def run_mock_info(module, client, another_client=None): +def run_mock_info(module, _client, _another_client=None): return False, [] @@ -142,9 +130,7 @@ def runner(module, params=None): return e.success, e.result assert False, "Module is not calling exit_json or fail_json." - mocker.patch.multiple( - basic.AnsibleModule, exit_json=exit_json_mock, fail_json=fail_json_mock - ) + mocker.patch.multiple(basic.AnsibleModule, exit_json=exit_json_mock, fail_json=fail_json_mock) return runner @@ -170,9 +156,7 @@ def runner(module, params=None): return e.success, e.result assert False, "Module is not calling exit_json or fail_json." - mocker.patch.multiple( - basic.AnsibleModule, exit_json=exit_json_mock, fail_json=fail_json_mock - ) + mocker.patch.multiple(basic.AnsibleModule, exit_json=exit_json_mock, fail_json=fail_json_mock) return runner @@ -198,9 +182,7 @@ def runner(module, params=None): return e.success, e.result assert False, "Module is not calling exit_json or fail_json." - mocker.patch.multiple( - basic.AnsibleModule, exit_json=exit_json_mock, fail_json=fail_json_mock - ) + mocker.patch.multiple(basic.AnsibleModule, exit_json=exit_json_mock, fail_json=fail_json_mock) return runner @@ -226,9 +208,7 @@ def runner(module, params=None): return e.success, e.result assert False, "Module is not calling exit_json or fail_json." - mocker.patch.multiple( - basic.AnsibleModule, exit_json=exit_json_mock, fail_json=fail_json_mock - ) + mocker.patch.multiple(basic.AnsibleModule, exit_json=exit_json_mock, fail_json=fail_json_mock) return runner diff --git a/tests/unit/plugins/module_utils/__init__.py b/tests/unit/plugins/module_utils/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/unit/plugins/module_utils/test_check_local_time.py b/tests/unit/plugins/module_utils/test_check_local_time.py index 9f0ff62e..37f53b1a 100644 --- a/tests/unit/plugins/module_utils/test_check_local_time.py +++ b/tests/unit/plugins/module_utils/test_check_local_time.py @@ -3,25 +3,23 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type -import sys -import pytest import datetime +import sys -from ansible_collections.scale_computing.hypercore.roles.check_local_time.files import ( - check_local_time, -) +import pytest +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.roles.check_local_time.files import check_local_time # from ansible_collections.scale_computing.hypercore.plugins.module_utils import ( # check_local_time, # ) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -54,16 +52,12 @@ def test_get_time_interval(self): ("22:00-12:31", "True"), ], ) - def test_is_local_time_in_time_interval( - self, time_interval, expected_result, capfd - ): + def test_is_local_time_in_time_interval(self, time_interval, expected_result, capfd): local_time = datetime.datetime.now() local_time_constant = local_time.replace(hour=12, minute=30) start_time, end_time = check_local_time.get_time_interval(time_interval) - check_local_time.is_local_time_in_time_interval( - local_time_constant, start_time, end_time - ) + check_local_time.is_local_time_in_time_interval(local_time_constant, start_time, end_time) result, err = capfd.readouterr() assert result.strip() == expected_result # strip removes "\n" diff --git a/tests/unit/plugins/module_utils/test_client.py b/tests/unit/plugins/module_utils/test_client.py index e87c63c9..4b311594 100644 --- a/tests/unit/plugins/module_utils/test_client.py +++ b/tests/unit/plugins/module_utils/test_client.py @@ -3,7 +3,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -11,18 +13,15 @@ import sys import pytest +from ansible_collections.scale_computing.hypercore.plugins.module_utils import client +from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible.module_utils.common.text.converters import to_text -from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError -from ansible.module_utils.six.moves.urllib.parse import urlparse, parse_qs - -from ansible_collections.scale_computing.hypercore.plugins.module_utils import ( - client, - errors, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible.module_utils.six.moves.urllib.error import HTTPError +from ansible.module_utils.six.moves.urllib.error import URLError +from ansible.module_utils.six.moves.urllib.parse import parse_qs +from ansible.module_utils.six.moves.urllib.parse import urlparse pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -47,11 +46,11 @@ def test_valid_json(self): resp = client.Response( 200, '{"a": ["b", "c"], "d": 1}', - headers=[("Content-type", "applcation/json")], + headers=[("Content-type", "application/json")], ) assert resp.status == 200 - assert resp.headers == {"content-type": "applcation/json"} + assert resp.headers == {"content-type": "application/json"} assert resp.data == '{"a": ["b", "c"], "d": 1}' assert resp.json == {"a": ["b", "c"], "d": 1} @@ -62,17 +61,17 @@ def test_invalid_json(self): assert resp.headers == {} assert resp.data == "Not Found" with pytest.raises(errors.ApiResponseNotJson): - resp.json + resp.json # pylint: disable=pointless-statement def test_json_is_cached(self, mocker): json_mock = mocker.patch.object(client, "json") resp = client.Response( 200, '{"a": ["b", "c"], "d": 1}', - headers=[("Content-type", "applcation/json")], + headers=[("Content-type", "application/json")], ) - resp.json - resp.json + resp.json # pylint: disable=pointless-statement + resp.json # pylint: disable=pointless-statement assert json_mock.loads.call_count == 1 @@ -80,9 +79,7 @@ def test_json_is_cached(self, mocker): class TestClientInit: @pytest.mark.parametrize("host", [None, "", "invalid", "missing.schema"]) def test_invalid_host(self, host): - with pytest.raises( - errors.ScaleComputingError, match="Invalid instance host value" - ): + with pytest.raises(errors.ScaleComputingError, match="Invalid instance host value"): client.Client(host, "user", "pass", None, "local") @pytest.mark.parametrize("host", ["http://insecure.host", "https://secure.host"]) @@ -94,26 +91,20 @@ class TestClientAuthHeader: def test_basic_auth(self, mocker): resp_mock = mocker.MagicMock() resp_mock.status = 200 # Used when testing on Python 3 - resp_mock.read.return_value = ( - '{"sessionID":"7e3a2a70-7130-41c4-9402-fc0953cc1d7b"}'.encode("utf-8") - ) + resp_mock.read.return_value = '{"sessionID":"7e3a2a70-7130-41c4-9402-fc0953cc1d7b"}'.encode("utf-8") request_mock = mocker.patch.object(client, "Request").return_value request_mock.open.return_value = resp_mock c = client.Client("https://instance.com", "user", "pass", None, "local") - assert c.auth_header == { - "Cookie": "sessionID=7e3a2a70-7130-41c4-9402-fc0953cc1d7b" - } + assert c.auth_header == {"Cookie": "sessionID=7e3a2a70-7130-41c4-9402-fc0953cc1d7b"} class TestClientRequest: def test_request_without_data_success(self, mocker): c = client.Client("https://instance.com", "user", "pass", None, "local") c._auth_header = {"Cookie": "sessionID=7e3a2a70-7130-41c4-9402-fc0953cc1d7b"} - mock_response = client.Response( - 200, '{"returned": "data"}', headers=[("Content-type", "application/json")] - ) + mock_response = client.Response(200, '{"returned": "data"}', headers=[("Content-type", "application/json")]) request_mock = mocker.patch.object(c, "_request") request_mock.return_value = mock_response @@ -131,9 +122,7 @@ def test_request_without_data_success(self, mocker): def test_request_with_data_success(self, mocker): c = client.Client("https://instance.com", "user", "pass", None, "local") c._auth_header = {"Cookie": "sessionID=7e3a2a70-7130-41c4-9402-fc0953cc1d7b"} - mock_response = client.Response( - 200, '{"returned": "data"}', headers=[("Content-type", "application/json")] - ) + mock_response = client.Response(200, '{"returned": "data"}', headers=[("Content-type", "application/json")]) request_mock = mocker.patch.object(c, "_request") request_mock.return_value = mock_response @@ -163,9 +152,7 @@ def test_auth_error(self, mocker): def test_http_error(self, mocker): request_mock = mocker.patch.object(client, "Request").return_value - request_mock.open.side_effect = HTTPError( - "", 404, "Not Found", {}, io.StringIO(to_text("My Error")) - ) + request_mock.open.side_effect = HTTPError("", 404, "Not Found", {}, io.StringIO(to_text("My Error"))) c = client.Client("https://instance.com", "user", "pass", None, "local") c._auth_header = {"Cookie": "sessionID=7e3a2a70-7130-41c4-9402-fc0953cc1d7b"} @@ -237,9 +224,7 @@ def test_path_with_query(self, mocker, query): def test_request_without_data_binary_success(self, mocker): c = client.Client("https://instance.com", "user", "pass", None, "local") c._auth_header = {"Cookie": "sessionID=7e3a2a70-7130-41c4-9402-fc0953cc1d7b"} - mock_response = client.Response( - 200, "data", headers=[("Content-type", "image/apng")] - ) + mock_response = client.Response(200, "data", headers=[("Content-type", "image/apng")]) request_mock = mocker.patch.object(c, "_request") request_mock.return_value = mock_response @@ -253,9 +238,7 @@ def test_request_without_data_binary_success(self, mocker): "GET", "https://instance.com/api/rest/v1/some/path", data=None, - headers=dict( - {"Accept": "image/apng", "Content-type": "text/plain"}, **c.auth_header - ), + headers=dict({"Accept": "image/apng", "Content-type": "text/plain"}, **c.auth_header), timeout=None, ) assert resp == mock_response @@ -298,9 +281,7 @@ def test_query(self, mocker): c.get("api/rest/v1/table/incident/1", query=dict(a="1")) - request_mock.assert_called_with( - "GET", "api/rest/v1/table/incident/1", query=dict(a="1"), timeout=None - ) + request_mock.assert_called_with("GET", "api/rest/v1/table/incident/1", query=dict(a="1"), timeout=None) class TestClientPost: @@ -436,6 +417,4 @@ def test_query(self, mocker): c.delete("api/rest/v1/table/resource/1", query=dict(x="y")) - request_mock.assert_called_with( - "DELETE", "api/rest/v1/table/resource/1", query=dict(x="y"), timeout=None - ) + request_mock.assert_called_with("DELETE", "api/rest/v1/table/resource/1", query=dict(x="y"), timeout=None) diff --git a/tests/unit/plugins/module_utils/test_cluster.py b/tests/unit/plugins/module_utils/test_cluster.py index b46818ca..5dff0174 100644 --- a/tests/unit/plugins/module_utils/test_cluster.py +++ b/tests/unit/plugins/module_utils/test_cluster.py @@ -1,20 +1,15 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.cluster import ( - Cluster, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.errors import ( - ScaleTimeoutError, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.cluster import Cluster +from ansible_collections.scale_computing.hypercore.plugins.module_utils.errors import ScaleTimeoutError +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_disk.py b/tests/unit/plugins/module_utils/test_disk.py index bbb4c959..cd7ff94b 100644 --- a/tests/unit/plugins/module_utils/test_disk.py +++ b/tests/unit/plugins/module_utils/test_disk.py @@ -1,19 +1,16 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils.disk import Disk +from ansible_collections.scale_computing.hypercore.plugins.module_utils.errors import ScaleComputingError +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import VM -from ansible_collections.scale_computing.hypercore.plugins.module_utils.errors import ( - ScaleComputingError, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -38,7 +35,7 @@ def test_disk_from_ansible_no_type_new(self): ) disk = Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, cache_mode="none", size=4200, @@ -70,7 +67,7 @@ def test_disk_from_ansible_type_new(self): ) disk = Disk( - type="virtio-disk", + disk_type="virtio-disk", slot=0, cache_mode="none", size=4200, @@ -87,7 +84,7 @@ def test_disk_from_ansible_type_new(self): def test_disk_from_hypercore_dict_not_empty_success(self): disk = Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, uuid="id", vm_uuid="vm-id", @@ -140,7 +137,7 @@ def test_disk_from_hypercore_dict_empty(self): def test_disk_to_hypercore(self): disk = Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, uuid="id", vm_uuid="vm-id", @@ -184,7 +181,7 @@ def test_disk_to_ansible(self): ) disk = Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, uuid="id", vm_uuid="vm-id", @@ -202,7 +199,7 @@ def test_disk_to_ansible(self): def test_equal(self): disk1 = Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, uuid="id", vm_uuid="vm-id", @@ -216,7 +213,7 @@ def test_equal(self): ) disk2 = Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, uuid="id", vm_uuid="vm-id", @@ -241,7 +238,7 @@ def test_post_and_patch_payload__virtio(self): ) disk = Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, cache_mode="none", size=4200, @@ -274,7 +271,7 @@ def test_post_and_patch_payload__nvram_post(self): ) disk = Disk( - type="nvram", + disk_type="nvram", slot=-1, cache_mode="none", size=4200, @@ -307,7 +304,7 @@ def test_post_and_patch_payload__nvram_patch(self): ) disk = Disk( - type="nvram", + disk_type="nvram", slot=-1, cache_mode="none", size=4200, @@ -316,7 +313,7 @@ def test_post_and_patch_payload__nvram_patch(self): read_only=False, ) existing_disk = Disk( - type="nvram", + disk_type="nvram", slot=-1, cache_mode="none", size=540672, @@ -348,7 +345,7 @@ def test_post_and_patch_payload__vtpm_post(self): ) disk = Disk( - type="vtpm", + disk_type="vtpm", slot=-1, cache_mode="none", size=4200, @@ -381,7 +378,7 @@ def test_post_and_patch_payload__vtpm_patch(self): ) disk = Disk( - type="vtpm", + disk_type="vtpm", slot=-1, cache_mode="none", size=4200, @@ -390,7 +387,7 @@ def test_post_and_patch_payload__vtpm_patch(self): read_only=False, ) existing_disk = Disk( - type="vtpm", + disk_type="vtpm", slot=-1, cache_mode="none", size=4100, @@ -436,7 +433,7 @@ def test_get_by_uuid(self, rest_client, mocker): ) assert disk == Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, uuid="disk_uuid", vm_uuid="vm-id", diff --git a/tests/unit/plugins/module_utils/test_dns_config.py b/tests/unit/plugins/module_utils/test_dns_config.py index b647cc56..695b10e1 100644 --- a/tests/unit/plugins/module_utils/test_dns_config.py +++ b/tests/unit/plugins/module_utils/test_dns_config.py @@ -3,21 +3,18 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.dns_config import ( - DNSConfig, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.dns_config import DNSConfig +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_email_alert.py b/tests/unit/plugins/module_utils/test_email_alert.py index 4b8c63cf..a3daf936 100644 --- a/tests/unit/plugins/module_utils/test_email_alert.py +++ b/tests/unit/plugins/module_utils/test_email_alert.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.email_alert import ( - EmailAlert, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.email_alert import EmailAlert +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_hypercore_version.py b/tests/unit/plugins/module_utils/test_hypercore_version.py index 4a77b93a..4f3cbc76 100644 --- a/tests/unit/plugins/module_utils/test_hypercore_version.py +++ b/tests/unit/plugins/module_utils/test_hypercore_version.py @@ -3,28 +3,24 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type -import sys -import pytest import json +import sys -from ansible_collections.scale_computing.hypercore.plugins.module_utils.hypercore_version import ( - HyperCoreVersion, - Version, - VersionSpecSimple, - VersionSpec, - Update, - UpdateStatus, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.client import ( - Response, -) +import pytest +from ansible_collections.scale_computing.hypercore.plugins.module_utils.client import Response +from ansible_collections.scale_computing.hypercore.plugins.module_utils.hypercore_version import HyperCoreVersion +from ansible_collections.scale_computing.hypercore.plugins.module_utils.hypercore_version import Update +from ansible_collections.scale_computing.hypercore.plugins.module_utils.hypercore_version import UpdateStatus +from ansible_collections.scale_computing.hypercore.plugins.module_utils.hypercore_version import Version +from ansible_collections.scale_computing.hypercore.plugins.module_utils.hypercore_version import VersionSpec +from ansible_collections.scale_computing.hypercore.plugins.module_utils.hypercore_version import VersionSpecSimple +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_iso.py b/tests/unit/plugins/module_utils/test_iso.py index 46fd19fd..650fda55 100644 --- a/tests/unit/plugins/module_utils/test_iso.py +++ b/tests/unit/plugins/module_utils/test_iso.py @@ -1,15 +1,14 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils.iso import ISO -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -145,9 +144,7 @@ def test_build_iso_post_paylaod(self): ready_for_insert=False, ) - assert iso.build_iso_post_paylaod() == dict( - name="ISO-test-name", size=8000, readyForInsert=False - ) + assert iso.build_iso_post_paylaod() == dict(name="ISO-test-name", size=8000, readyForInsert=False) def test_get_by_name(self, rest_client): ansible_dict = dict( diff --git a/tests/unit/plugins/module_utils/test_minimal_util.py b/tests/unit/plugins/module_utils/test_minimal_util.py index a65b261e..000d8114 100644 --- a/tests/unit/plugins/module_utils/test_minimal_util.py +++ b/tests/unit/plugins/module_utils/test_minimal_util.py @@ -1,13 +1,13 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_nic.py b/tests/unit/plugins/module_utils/test_nic.py index 38f25bc0..2aec0f20 100644 --- a/tests/unit/plugins/module_utils/test_nic.py +++ b/tests/unit/plugins/module_utils/test_nic.py @@ -3,21 +3,18 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils.nic import Nic -from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import ( - ManageVMNics, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import ManageVMNics pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -107,9 +104,9 @@ def test_to_ansible(self): ipv4_addresses=["10.0.0.10", "10.0.1.10"], ) - for kk in expected_data.keys(): + for kk, vv in expected_data.items(): assert kk in ansible_data.keys() - assert expected_data[kk] == ansible_data[kk] + assert vv == ansible_data[kk] assert expected_data.keys() == ansible_data.keys() # assert below detects a difference, but does not tell back which key/value is problem. assert expected_data == ansible_data diff --git a/tests/unit/plugins/module_utils/test_node.py b/tests/unit/plugins/module_utils/test_node.py index 9165af36..b5a79bf7 100644 --- a/tests/unit/plugins/module_utils/test_node.py +++ b/tests/unit/plugins/module_utils/test_node.py @@ -1,15 +1,14 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils.node import Node -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_oidc.py b/tests/unit/plugins/module_utils/test_oidc.py index 07cf3b53..76d2d2fa 100644 --- a/tests/unit/plugins/module_utils/test_oidc.py +++ b/tests/unit/plugins/module_utils/test_oidc.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.oidc import ( - Oidc, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.oidc import Oidc +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_registration.py b/tests/unit/plugins/module_utils/test_registration.py index 0f5d1f11..b9744926 100644 --- a/tests/unit/plugins/module_utils/test_registration.py +++ b/tests/unit/plugins/module_utils/test_registration.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.registration import ( - Registration, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.registration import Registration +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_remote_cluster.py b/tests/unit/plugins/module_utils/test_remote_cluster.py index 061a8534..a4c98150 100644 --- a/tests/unit/plugins/module_utils/test_remote_cluster.py +++ b/tests/unit/plugins/module_utils/test_remote_cluster.py @@ -1,17 +1,14 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.remote_cluster import ( - RemoteCluster, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.remote_cluster import RemoteCluster +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -107,22 +104,16 @@ def test_get_cluster_name_from_replication_connection_uuid(self, rest_client): remoteNodeUUIDs=["895033ed-b863-4a42-8215-477a1a4ef812"], ) - remote_cluster_name = ( - RemoteCluster.get_cluster_name_from_replication_connection_uuid( - rest_client, "891f482a-8f5f-4755-bea4-bbcc338f566f" - ) + remote_cluster_name = RemoteCluster.get_cluster_name_from_replication_connection_uuid( + rest_client, "891f482a-8f5f-4755-bea4-bbcc338f566f" ) assert remote_cluster_name == "PUB4" - def test_get_cluster_name_from_replication_connection_uuid_record_missing( - self, rest_client - ): + def test_get_cluster_name_from_replication_connection_uuid_record_missing(self, rest_client): rest_client.get_record.return_value = None - remote_cluster_name = ( - RemoteCluster.get_cluster_name_from_replication_connection_uuid( - rest_client, "891f482a-8f5f-4755-bea4-bbcc338f566f" - ) + remote_cluster_name = RemoteCluster.get_cluster_name_from_replication_connection_uuid( + rest_client, "891f482a-8f5f-4755-bea4-bbcc338f566f" ) assert remote_cluster_name is None diff --git a/tests/unit/plugins/module_utils/test_replication.py b/tests/unit/plugins/module_utils/test_replication.py index 9c80c3c3..a0c05812 100644 --- a/tests/unit/plugins/module_utils/test_replication.py +++ b/tests/unit/plugins/module_utils/test_replication.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.replication import ( - Replication, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.replication import Replication +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -124,9 +121,7 @@ def test_create_from_hypercore(self): replication_obj = Replication.from_hypercore(hypercore_data) assert replication_obj.vm_uuid == hypercore_data["sourceDomainUUID"] assert replication_obj.replication_uuid == hypercore_data["uuid"] - assert replication_obj.state == Replication.handle_state( - hypercore_data["enable"] - ) + assert replication_obj.state == Replication.handle_state(hypercore_data["enable"]) assert replication_obj.connection_uuid == hypercore_data["connectionUUID"] assert replication_obj.vm_name == "test-vm" assert replication_obj.remote_cluster == "remote-cluster-name" diff --git a/tests/unit/plugins/module_utils/test_rest_client.py b/tests/unit/plugins/module_utils/test_rest_client.py index f0cdebd6..2bc7ce39 100644 --- a/tests/unit/plugins/module_utils/test_rest_client.py +++ b/tests/unit/plugins/module_utils/test_rest_client.py @@ -3,24 +3,19 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils import ( - rest_client, - errors, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.client import ( - Response, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors +from ansible_collections.scale_computing.hypercore.plugins.module_utils import rest_client +from ansible_collections.scale_computing.hypercore.plugins.module_utils.client import Response +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -30,9 +25,7 @@ class TestTableListRecords: def test_empty_response(self, client): - client.get.return_value = Response( - 200, '{"result": []}', {"X-Total-Count": "0"} - ) + client.get.return_value = Response(200, '{"result": []}', {"X-Total-Count": "0"}) t = rest_client.RestClient(client) records = t.list_records("my_table") @@ -41,9 +34,7 @@ def test_empty_response(self, client): client.get.assert_called_once_with(path="my_table", timeout=None) def test_non_empty_response(self, client): - client.get.return_value = Response( - 200, '{"result": [{"a": 3, "b": "sys_id"}]}', {"X-Total-Count": "1"} - ) + client.get.return_value = Response(200, '{"result": [{"a": 3, "b": "sys_id"}]}', {"X-Total-Count": "1"}) t = rest_client.RestClient(client) records = t.list_records("my_table") @@ -51,9 +42,7 @@ def test_non_empty_response(self, client): assert records == ["result"] def test_query_passing(self, client): - client.get.return_value = Response( - 200, '{"result": []}', {"X-Total-Count": "0"} - ) + client.get.return_value = Response(200, '{"result": []}', {"X-Total-Count": "0"}) t = rest_client.RestClient(client) t.list_records("my_table", dict(a="b")) @@ -66,9 +55,7 @@ def test_query_passing(self, client): class TestTableListRecordsRaw: def test_empty_response(self, client): - client.get.return_value = Response( - 200, '{"result": []}', {"X-Total-Count": "0"} - ) + client.get.return_value = Response(200, '{"result": []}', {"X-Total-Count": "0"}) t = rest_client.RestClient(client) records = t.list_records_raw("my_table") @@ -77,9 +64,7 @@ def test_empty_response(self, client): client.get.assert_called_once_with(path="my_table", timeout=None) def test_non_empty_response(self, client): - client.get.return_value = Response( - 200, '{"result": [{"a": 3, "b": "sys_id"}]}', {"X-Total-Count": "1"} - ) + client.get.return_value = Response(200, '{"result": [{"a": 3, "b": "sys_id"}]}', {"X-Total-Count": "1"}) t = rest_client.RestClient(client) records = t.list_records_raw("my_table") @@ -89,17 +74,13 @@ def test_non_empty_response(self, client): class TestTableGetRecord: def test_zero_matches(self, client): - client.get.return_value = Response( - 200, '{"result": []}', {"X-Total-Count": "0"} - ) + client.get.return_value = Response(200, '{"result": []}', {"X-Total-Count": "0"}) t = rest_client.RestClient(client) assert t.get_record("my_table", dict(our="query")) is None def test_zero_matches_fail(self, client): - client.get.return_value = Response( - 200, '{"result": []}', {"X-Total-Count": "0"} - ) + client.get.return_value = Response(200, '{"result": []}', {"X-Total-Count": "0"}) t = rest_client.RestClient(client) with pytest.raises(errors.ScaleComputingError, match="No"): @@ -161,9 +142,7 @@ def test_check_mode(self, client): class TestTableDeleteRecord: def test_normal_mode(self, client): - client.delete.return_value = Response( - 204, '{"result": {"a": 3, "b": "sys_id"}}' - ) + client.delete.return_value = Response(204, '{"result": {"a": 3, "b": "sys_id"}}') t = rest_client.RestClient(client) t.delete_record("my_table/id", check_mode=False) diff --git a/tests/unit/plugins/module_utils/test_rest_client_CachedRestClient.py b/tests/unit/plugins/module_utils/test_rest_client_CachedRestClient.py index 0458e62c..f9fcb207 100644 --- a/tests/unit/plugins/module_utils/test_rest_client_CachedRestClient.py +++ b/tests/unit/plugins/module_utils/test_rest_client_CachedRestClient.py @@ -3,7 +3,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -11,14 +13,9 @@ import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils import ( - client, - rest_client, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils import client +from ansible_collections.scale_computing.hypercore.plugins.module_utils import rest_client +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_role.py b/tests/unit/plugins/module_utils/test_role.py index 943b8b07..40f5ab74 100644 --- a/tests/unit/plugins/module_utils/test_role.py +++ b/tests/unit/plugins/module_utils/test_role.py @@ -1,15 +1,14 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils.role import Role -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_smtp.py b/tests/unit/plugins/module_utils/test_smtp.py index 101d6752..09a23fc5 100644 --- a/tests/unit/plugins/module_utils/test_smtp.py +++ b/tests/unit/plugins/module_utils/test_smtp.py @@ -3,7 +3,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -11,14 +13,9 @@ from copy import deepcopy import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.smtp import ( - SMTP, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.smtp import SMTP +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_snapshot_schedule.py b/tests/unit/plugins/module_utils/test_snapshot_schedule.py index 3fb8cb2a..a8637284 100644 --- a/tests/unit/plugins/module_utils/test_snapshot_schedule.py +++ b/tests/unit/plugins/module_utils/test_snapshot_schedule.py @@ -1,18 +1,15 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.snapshot_schedule import ( - SnapshotSchedule, - Recurrence, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.snapshot_schedule import Recurrence +from ansible_collections.scale_computing.hypercore.plugins.module_utils.snapshot_schedule import SnapshotSchedule +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -87,9 +84,7 @@ def test_snapshot_schedule_from_hypercore_dict_not_empty(self): ], ) - snapshot_schedule_from_hypercore = SnapshotSchedule.from_hypercore( - hypercore_dict - ) + snapshot_schedule_from_hypercore = SnapshotSchedule.from_hypercore(hypercore_dict) assert snapshot_schedule == snapshot_schedule_from_hypercore def test_snapshot_schedule_from_hypercore_dict_empty(self): @@ -213,10 +208,7 @@ def test_get_by_name(self, rest_client): recurrences=[], ) - assert ( - SnapshotSchedule.get_by_name(ansible_dict, rest_client) - == snapshot_schedule_image - ) + assert SnapshotSchedule.get_by_name(ansible_dict, rest_client) == snapshot_schedule_image class TestRecurrence: diff --git a/tests/unit/plugins/module_utils/test_support_tunnel.py b/tests/unit/plugins/module_utils/test_support_tunnel.py index 1c3eac33..7e154472 100644 --- a/tests/unit/plugins/module_utils/test_support_tunnel.py +++ b/tests/unit/plugins/module_utils/test_support_tunnel.py @@ -3,23 +3,18 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.support_tunnel import ( - SupportTunnel, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.client import ( - Response, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.client import Response +from ansible_collections.scale_computing.hypercore.plugins.module_utils.support_tunnel import SupportTunnel +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -30,7 +25,7 @@ class TestSupportTunnel: def test_support_tunnel_from_hypercore(self): support_tunnel = SupportTunnel( - open=True, + open_flag=True, code=4422, ) @@ -43,7 +38,7 @@ def test_support_tunnel_from_hypercore(self): def test_support_tunnel_from_hypercore_false(self): support_tunnel = SupportTunnel( - open=False, + open_flag=False, code=None, ) @@ -55,21 +50,21 @@ def test_support_tunnel_from_hypercore_false(self): assert support_tunnel == support_tunnel_from_hypercore def test_support_tunnel_to_ansible(self): - support_tunnel = SupportTunnel(open=True, code=4422) + support_tunnel = SupportTunnel(open_flag=True, code=4422) ansible_dict = dict(open=True, code=4422) assert support_tunnel.to_ansible() == ansible_dict def test_support_tunnel_equal_true(self): - support_tunnel1 = SupportTunnel(open=True, code=4422) - support_tunnel2 = SupportTunnel(open=True, code=4422) + support_tunnel1 = SupportTunnel(open_flag=True, code=4422) + support_tunnel2 = SupportTunnel(open_flag=True, code=4422) assert support_tunnel1 == support_tunnel2 def test_support_tunnel_equal_false(self): - support_tunnel1 = SupportTunnel(open=True, code=4422) - support_tunnel2 = SupportTunnel(open=False, code=None) + support_tunnel1 = SupportTunnel(open_flag=True, code=4422) + support_tunnel2 = SupportTunnel(open_flag=False, code=None) assert support_tunnel1 != support_tunnel2 @@ -107,14 +102,10 @@ def test_open_tunnel(self, create_module, client): SupportTunnel.open_tunnel(module, client) - client.get.assert_called_with( - "/support-api/open", query={"code": 4422, "user": "mock_username"} - ) + client.get.assert_called_with("/support-api/open", query={"code": 4422, "user": "mock_username"}) def test_close_tunnel(self, client): client.get.return_value = Response(status=200, data="") SupportTunnel.close_tunnel(client) - client.get.assert_called_with( - "/support-api/close", query={"user": "mock_username"} - ) + client.get.assert_called_with("/support-api/close", query={"user": "mock_username"}) diff --git a/tests/unit/plugins/module_utils/test_syslog_server.py b/tests/unit/plugins/module_utils/test_syslog_server.py index 2d1ac6dc..07e2929a 100644 --- a/tests/unit/plugins/module_utils/test_syslog_server.py +++ b/tests/unit/plugins/module_utils/test_syslog_server.py @@ -3,23 +3,18 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.syslog_server import ( - SyslogServer, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.task_tag import ( - TaskTag, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.syslog_server import SyslogServer +from ansible_collections.scale_computing.hypercore.plugins.module_utils.task_tag import TaskTag +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -72,9 +67,7 @@ def test_syslog_server_to_hypercore(self): assert self.syslog_server.to_hypercore() == self.to_hypercore_dict def test_syslog_server_from_hypercore_dict_not_empty(self): - syslog_server_from_hypercore = SyslogServer.from_hypercore( - self.from_hypercore_dict - ) + syslog_server_from_hypercore = SyslogServer.from_hypercore(self.from_hypercore_dict) assert self.syslog_server == syslog_server_from_hypercore def test_syslog_server_from_hypercore_dict_empty(self): @@ -99,9 +92,7 @@ def test_get_by_uuid(self, rest_client): ansible_dict = dict( uuid="test", ) - syslog_server_from_hypercore = SyslogServer.get_by_uuid( - ansible_dict, rest_client - ) + syslog_server_from_hypercore = SyslogServer.get_by_uuid(ansible_dict, rest_client) assert syslog_server_from_hypercore == self.syslog_server def test_get_state(self, rest_client): @@ -149,21 +140,11 @@ def test_is_equivalent(self): protocol="udp", alert_tag_uuid="alert_tag_uuid-a2", ) - a3 = SyslogServer( - host="1.0.0.10", port=10514, protocol="udp", resend_delay=12345 - ) - a4 = SyslogServer( - host="1.0.0.10", port=10514, protocol="udp", silent_period=123456 - ) - a5 = SyslogServer( - host="1.0.0.10", port=10514, protocol="udp", latest_task_tag=TaskTag() - ) - task_tag = dict( - createdUUID="latest_task_tag-createdUUID", taskTag="taskTag-112233" - ) - a6 = SyslogServer( - host="1.0.0.10", port=10514, protocol="udp", latest_task_tag=task_tag - ) + a3 = SyslogServer(host="1.0.0.10", port=10514, protocol="udp", resend_delay=12345) + a4 = SyslogServer(host="1.0.0.10", port=10514, protocol="udp", silent_period=123456) + a5 = SyslogServer(host="1.0.0.10", port=10514, protocol="udp", latest_task_tag=TaskTag()) + task_tag = dict(createdUUID="latest_task_tag-createdUUID", taskTag="taskTag-112233") + a6 = SyslogServer(host="1.0.0.10", port=10514, protocol="udp", latest_task_tag=task_tag) assert ss.is_equivalent(a0) assert ss.is_equivalent(a1) diff --git a/tests/unit/plugins/module_utils/test_task_tag.py b/tests/unit/plugins/module_utils/test_task_tag.py index 4c3b8863..d243ec0c 100644 --- a/tests/unit/plugins/module_utils/test_task_tag.py +++ b/tests/unit/plugins/module_utils/test_task_tag.py @@ -3,21 +3,18 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.task_tag import ( - TaskTag, -) from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.task_tag import TaskTag +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_time_server.py b/tests/unit/plugins/module_utils/test_time_server.py index bdf6f3e4..275f02ce 100644 --- a/tests/unit/plugins/module_utils/test_time_server.py +++ b/tests/unit/plugins/module_utils/test_time_server.py @@ -3,21 +3,18 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.time_server import ( - TimeServer, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.time_server import TimeServer +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_time_zone.py b/tests/unit/plugins/module_utils/test_time_zone.py index d4884fad..29f9c53b 100644 --- a/tests/unit/plugins/module_utils/test_time_zone.py +++ b/tests/unit/plugins/module_utils/test_time_zone.py @@ -3,21 +3,18 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.time_zone import ( - TimeZone, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.time_zone import TimeZone +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/module_utils/test_user.py b/tests/unit/plugins/module_utils/test_user.py index 7c34b7dd..2c4b3151 100644 --- a/tests/unit/plugins/module_utils/test_user.py +++ b/tests/unit/plugins/module_utils/test_user.py @@ -3,19 +3,18 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.user import User from ansible_collections.scale_computing.hypercore.plugins.module_utils.role import Role -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.user import User +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -76,12 +75,8 @@ def test_user_to_ansible(self, mocker, rest_client): ansible_dict = dict( full_name="fullname", roles=[ - dict( - name="Cluster Settings", uuid="38b346c6-a626-444b-b6ab-92ecd671afc0" - ), - dict( - name="Cluster Shutdown", uuid="7224a2bd-5a08-4b99-a0de-9977089c66a4" - ), + dict(name="Cluster Settings", uuid="38b346c6-a626-444b-b6ab-92ecd671afc0"), + dict(name="Cluster Shutdown", uuid="7224a2bd-5a08-4b99-a0de-9977089c66a4"), ], session_limit=0, username="username", diff --git a/tests/unit/plugins/module_utils/test_utils.py b/tests/unit/plugins/module_utils/test_utils.py index f2c8da5c..79b77a1a 100644 --- a/tests/unit/plugins/module_utils/test_utils.py +++ b/tests/unit/plugins/module_utils/test_utils.py @@ -3,18 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils import utils -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -30,9 +29,7 @@ def test_ignoring_none_values(self): assert {} == utils.filter_dict(dict(a=None), "a") def test_selecting_a_subset_skip_none_values(self): - assert dict(a=1, c="str") == utils.filter_dict( - dict(a=1, b=2, c="str", d=None), "a", "c", "d" - ) + assert dict(a=1, c="str") == utils.filter_dict(dict(a=1, b=2, c="str", d=None), "a", "c", "d") class TestTransformQuery: @@ -91,6 +88,4 @@ def test_not_a_superset(self, superset, candidate): class TestFilterResults: def test_filter_results(self): - assert utils.filter_results( - [dict(a=1), dict(b=1), dict(a=1, b=2)], dict(a=1) - ) == [dict(a=1), dict(a=1, b=2)] + assert utils.filter_results([dict(a=1), dict(b=1), dict(a=1, b=2)], dict(a=1)) == [dict(a=1), dict(a=1, b=2)] diff --git a/tests/unit/plugins/module_utils/test_virtual_disk.py b/tests/unit/plugins/module_utils/test_virtual_disk.py index f5c1ba22..45652bac 100644 --- a/tests/unit/plugins/module_utils/test_virtual_disk.py +++ b/tests/unit/plugins/module_utils/test_virtual_disk.py @@ -3,7 +3,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -11,16 +13,9 @@ from copy import deepcopy import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.virtual_disk import ( - VirtualDisk, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.errors import ( - ScaleComputingError, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.errors import ScaleComputingError +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.module_utils.virtual_disk import VirtualDisk pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -65,9 +60,7 @@ def test_virtual_disk_to_hypercore(self): self.virtual_disk.to_hypercore() def test_virtual_disk_from_hypercore_dict_not_empty(self): - virtual_disk_from_hypercore = VirtualDisk.from_hypercore( - self.from_hypercore_dict - ) + virtual_disk_from_hypercore = VirtualDisk.from_hypercore(self.from_hypercore_dict) assert self.virtual_disk == virtual_disk_from_hypercore # def test_virtual_disk_from_hypercore_dict_empty(self): @@ -576,9 +569,7 @@ def test_get_by_name_virtual_disk( ScaleComputingError, match=f"Virtual disk {virtual_disk_dict_from_api['name']} has multiple instances and is not unique.", ): - VirtualDisk.get_by_name( - rest_client, virtual_disk_dict_from_api["name"], must_exist - ) + VirtualDisk.get_by_name(rest_client, virtual_disk_dict_from_api["name"], must_exist) else: # Mock rest_client rest_client.list_records.return_value = [virtual_disk_dict_from_api] @@ -668,9 +659,7 @@ def test_send_upload_request_virtual_disk( ): module = create_module( params=dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), name=file_name, source=file_source, state="present", @@ -759,24 +748,18 @@ class TestSendDeleteRequest: ), # Missing UUID exception ( - VirtualDisk( - uuid="", name="", block_size="", size="", replication_factor="" - ), + VirtualDisk(uuid="", name="", block_size="", size="", replication_factor=""), True, None, ), ( - VirtualDisk( - uuid=None, name="", block_size="", size="", replication_factor="" - ), + VirtualDisk(uuid=None, name="", block_size="", size="", replication_factor=""), True, None, ), ], ) - def test_send_delete_request_virtual_disk( - self, rest_client, virtual_disk, expected_exception, expected_result - ): + def test_send_delete_request_virtual_disk(self, rest_client, virtual_disk, expected_exception, expected_result): if expected_exception: with pytest.raises( ScaleComputingError, diff --git a/tests/unit/plugins/module_utils/test_vm.py b/tests/unit/plugins/module_utils/test_vm.py index 1c66ffe4..7b303371 100644 --- a/tests/unit/plugins/module_utils/test_vm.py +++ b/tests/unit/plugins/module_utils/test_vm.py @@ -1,30 +1,23 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import ( - VM, - ManageVMParams, - ManageVMDisks, - ManageVMNics, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.errors import ( - ScaleComputingError, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors from ansible_collections.scale_computing.hypercore.plugins.module_utils.disk import Disk -from ansible_collections.scale_computing.hypercore.plugins.module_utils.nic import Nic +from ansible_collections.scale_computing.hypercore.plugins.module_utils.errors import ScaleComputingError from ansible_collections.scale_computing.hypercore.plugins.module_utils.iso import ISO -from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.snapshot_schedule import ( - SnapshotSchedule, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.nic import Nic +from ansible_collections.scale_computing.hypercore.plugins.module_utils.snapshot_schedule import SnapshotSchedule +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import VM +from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import ManageVMDisks +from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import ManageVMNics +from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import ManageVMParams pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -423,7 +416,7 @@ def test_get_specific_disk_result_not_empty(self): description="desc", disks=[ Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, cache_mode="none", size=4200, @@ -435,7 +428,7 @@ def test_get_specific_disk_result_not_empty(self): read_only=False, ), Disk( - type="ide_cdrom", + disk_type="ide_cdrom", slot=1, cache_mode="none", size=4200, @@ -480,7 +473,7 @@ def test_get_specific_disk_result_empty(self): description="desc", disks=[ Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=1, cache_mode="none", size=4200, @@ -492,7 +485,7 @@ def test_get_specific_disk_result_empty(self): read_only=False, ), Disk( - type="ide_cdrom", + disk_type="ide_cdrom", slot=1, cache_mode="none", size=4200, @@ -524,7 +517,7 @@ def test_get_specific_disk_multiple_results(self): description="desc", disks=[ Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, cache_mode="none", size=4200, @@ -536,7 +529,7 @@ def test_get_specific_disk_multiple_results(self): read_only=False, ), Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, cache_mode="none", size=4200, @@ -596,12 +589,8 @@ def test_get_or_fail_when_get(self, rest_client, hcversion, mocker): "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.SnapshotSchedule.get_snapshot_schedule" ).return_value = None hypercore_dict = rest_client.list_records.return_value[0] - actual = VM.from_hypercore( - vm_dict=hypercore_dict, rest_client=rest_client - ).to_hypercore(hcversion) - results = VM.get_or_fail( - query={"name": "XLAB_test_vm"}, rest_client=rest_client - )[0].to_hypercore(hcversion) + actual = VM.from_hypercore(vm_dict=hypercore_dict, rest_client=rest_client).to_hypercore(hcversion) + results = VM.get_or_fail(query={"name": "XLAB_test_vm"}, rest_client=rest_client)[0].to_hypercore(hcversion) assert results == actual def test_get_or_fail_when_fail(self, rest_client): @@ -937,9 +926,7 @@ def _get_test_vm(cls, rest_client, mocker): rest_client, ) - def test_delete_unused_nics_to_hypercore_vm_when_no_delete( - self, create_module, rest_client, mocker - ): + def test_delete_unused_nics_to_hypercore_vm_when_no_delete(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -982,18 +969,12 @@ def test_delete_unused_nics_to_hypercore_vm_when_no_delete( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.SnapshotSchedule.get_snapshot_schedule" ).return_value = None rest_client.list_records.return_value = [vm_dict] - virtual_machine = VM.get( - query={"name": module.params["vm_name"]}, rest_client=rest_client - )[0] + virtual_machine = VM.get(query={"name": module.params["vm_name"]}, rest_client=rest_client)[0] nic_key = "items" - results = virtual_machine.delete_unused_nics_to_hypercore_vm( - module, rest_client, nic_key - ) + results = virtual_machine.delete_unused_nics_to_hypercore_vm(module, rest_client, nic_key) assert results is False - def test_delete_unused_nics_to_hypercore_vm_when_one_nic_deleted( - self, create_module, rest_client, mocker - ): + def test_delete_unused_nics_to_hypercore_vm_when_one_nic_deleted(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -1053,18 +1034,12 @@ def test_delete_unused_nics_to_hypercore_vm_when_one_nic_deleted( "taskTag": "1234", "state": "COMPLETED", } - virtual_machine = VM.get( - query={"name": module.params["vm_name"]}, rest_client=rest_client - )[0] + virtual_machine = VM.get(query={"name": module.params["vm_name"]}, rest_client=rest_client)[0] nic_key = "items" - results = virtual_machine.delete_unused_nics_to_hypercore_vm( - module, rest_client, nic_key - ) + results = virtual_machine.delete_unused_nics_to_hypercore_vm(module, rest_client, nic_key) assert results is True - def test_delete_unused_nics_to_hypercore_vm_when_multiple_nic_deleted( - self, create_module, rest_client, mocker - ): + def test_delete_unused_nics_to_hypercore_vm_when_multiple_nic_deleted(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -1136,13 +1111,9 @@ def test_delete_unused_nics_to_hypercore_vm_when_multiple_nic_deleted( {"taskTag": "1234"}, {"taskTag": "5678"}, ] - virtual_machine = VM.get( - query={"name": module.params["vm_name"]}, rest_client=rest_client - )[0] + virtual_machine = VM.get(query={"name": module.params["vm_name"]}, rest_client=rest_client)[0] nic_key = "items" - results = virtual_machine.delete_unused_nics_to_hypercore_vm( - module, rest_client, nic_key - ) + results = virtual_machine.delete_unused_nics_to_hypercore_vm(module, rest_client, nic_key) assert results is True def test_find_nic_vlan(self, rest_client, mocker): @@ -1192,9 +1163,7 @@ def test_find_nic_mac_and_mac_new(self, rest_client, mocker): "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.SnapshotSchedule.get_snapshot_schedule" ).return_value = None virtual_machine = self._get_test_vm(rest_client, mocker) - results = virtual_machine.find_nic( - mac="12-34-56-78-CD", mac_new="12-34-56-78-AB" - ) + results = virtual_machine.find_nic(mac="12-34-56-78-CD", mac_new="12-34-56-78-AB") assert results[0].vlan == 2 assert results[0].mac == "12-34-56-78-CD" assert results[0].uuid == "6456f2hj-6u9a-90ff-6g91-7jeahgf47aab" @@ -1222,13 +1191,7 @@ def test_create_export_or_import_vm_payload_when_export(self): results = VM.create_export_or_import_vm_payload(ansible_dict, None, True) assert results == dict( target=dict( - pathURI="smb://" - + "username" - + ":" - + "password" - + "@" - + "10.5.11.170" - + "/user", + pathURI="smb://" + "username" + ":" + "password" + "@" + "10.5.11.170" + "/user", definitionFileName="my_file.xml", ), template=dict(), @@ -1307,13 +1270,7 @@ def test_create_export_or_import_vm_payload_when_import(self): results = VM.create_export_or_import_vm_payload(ansible_dict, None, False) assert results == dict( source=dict( - pathURI="smb://" - + "username" - + ":" - + "password" - + "@" - + "10.5.11.170" - + "/user", + pathURI="smb://" + "username" + ":" + "password" + "@" + "10.5.11.170" + "/user", definitionFileName="my_file.xml", ), template=dict(name="this-vm-name"), @@ -1383,7 +1340,7 @@ def test_get_vm_device_type_not_nic(self, create_module, rest_client): description="desc", disks=[ Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, uuid="id", vm_uuid="vm-id", @@ -1492,9 +1449,7 @@ def test_create_clone_vm_payload_with__preserve_mac_address__1_nics(self): ["original_tag", "original_tag2"], {"userData": "something", "metaData": "else"}, preserve_mac_address=True, - source_nics=[ - Nic.from_ansible(dict(type="virtio", mac="11:00:00:00:00:10", vlan=10)) - ], + source_nics=[Nic.from_ansible(dict(type="virtio", mac="11:00:00:00:00:10", vlan=10))], source_snapshot_uuid="", ) assert results == { @@ -1569,9 +1524,7 @@ def test_clone_vm(self, rest_client, mocker): mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.SnapshotSchedule.get_snapshot_schedule" ).return_value = None - virtual_machine = VM.get_or_fail( - query={"name": "XLAB-test-vm-clone"}, rest_client=rest_client - )[0] + virtual_machine = VM.get_or_fail(query={"name": "XLAB-test-vm-clone"}, rest_client=rest_client)[0] results = virtual_machine.clone_vm(rest_client, ansible_dict) assert results == {"taskTag": "1234"} @@ -1617,9 +1570,7 @@ def test_clone_vm_replicated_vm(self, rest_client, mocker): mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.SnapshotSchedule.get_snapshot_schedule" ).return_value = None - virtual_machine = VM.get_or_fail( - query={"name": "XLAB-test-vm-clone"}, rest_client=rest_client - )[0] + virtual_machine = VM.get_or_fail(query={"name": "XLAB-test-vm-clone"}, rest_client=rest_client)[0] results = virtual_machine.clone_vm(rest_client, ansible_dict) assert results == {"taskTag": "1234"} @@ -2039,9 +1990,7 @@ def test_set_vm_params(self, create_module, rest_client, mocker): vcpu=2, snapshot_schedule="", ) - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.TaskTag.wait_task" - ) + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.TaskTag.wait_task") mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.get_or_fail" ).return_value = [ @@ -2060,9 +2009,7 @@ def test_set_vm_params(self, create_module, rest_client, mocker): mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.wait_shutdown" ).return_value = True - changed, diff, changed_parameters = ManageVMParams.set_vm_params( - module, rest_client, vm_before, [] - ) + changed, diff, changed_parameters = ManageVMParams.set_vm_params(module, rest_client, vm_before, []) assert changed is True assert diff == { @@ -2129,9 +2076,7 @@ def test_run_no_change(self, create_module, rest_client, mocker): snapshot_schedule="", ) - changed, diff, changed_parameters = ManageVMParams.set_vm_params( - module, rest_client, vm_before, [] - ) + changed, diff, changed_parameters = ManageVMParams.set_vm_params(module, rest_client, vm_before, []) assert changed is False assert diff == { @@ -2299,7 +2244,7 @@ def test_get_vm_by_name_disks_present(self, create_module, rest_client, mocker): description="desc", disks=[ Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, uuid="id", vm_uuid="vm-id", @@ -2379,7 +2324,7 @@ def test_create_block_device(self, create_module, rest_client, vm, mocker): ) vm = VM(name="vm-name", memory=42, vcpu=2, uuid="id", power_state="shutdown") desired_disk = Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, uuid="id", vm_uuid="vm-id", @@ -2399,9 +2344,7 @@ def test_create_block_device(self, create_module, rest_client, vm, mocker): mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.wait_shutdown" ).return_value = True - result = ManageVMDisks._create_block_device( - module, rest_client, vm, desired_disk - ) + result = ManageVMDisks._create_block_device(module, rest_client, vm, desired_disk) rest_client.create_record.assert_called_with( "/rest/v1/VirDomainBlockDevice", { @@ -2441,9 +2384,7 @@ def test_iso_image_management_attach(self, create_module, rest_client, task_wait ) uuid = "disk_id" attach = True - result = ManageVMDisks.iso_image_management( - module, rest_client, iso, uuid, attach - ) + result = ManageVMDisks.iso_image_management(module, rest_client, iso, uuid, attach) rest_client.update_record.assert_called_with( "/rest/v1/VirDomainBlockDevice/disk_id", dict( @@ -2475,9 +2416,7 @@ def test_iso_image_management_detach(self, create_module, rest_client, task_wait ) uuid = "disk_id" attach = False - result = ManageVMDisks.iso_image_management( - module, rest_client, iso, uuid, attach - ) + result = ManageVMDisks.iso_image_management(module, rest_client, iso, uuid, attach) rest_client.update_record.assert_called_with( "/rest/v1/VirDomainBlockDevice/disk_id", dict( @@ -2501,7 +2440,7 @@ def test_update_block_device(self, create_module, rest_client, mocker): ) existing_disk = Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, uuid="id", vm_uuid="vm-id", @@ -2515,7 +2454,7 @@ def test_update_block_device(self, create_module, rest_client, mocker): ) desired_disk = Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, uuid="id", vm_uuid="vm-id", @@ -2535,9 +2474,7 @@ def test_update_block_device(self, create_module, rest_client, mocker): "state": "COMPLETED", } vm = VM(name="vm-name", memory=42, vcpu=2, uuid="id", power_state="shutdown") - ManageVMDisks._update_block_device( - module, rest_client, desired_disk, existing_disk, vm - ) + ManageVMDisks._update_block_device(module, rest_client, desired_disk, existing_disk, vm) rest_client.update_record.assert_called_with( "/rest/v1/VirDomainBlockDevice/id", { @@ -2556,9 +2493,7 @@ def test_update_block_device(self, create_module, rest_client, mocker): False, ) - def test_delete_not_used_disks_no_deletion( - self, create_module, rest_client, mocker - ): + def test_delete_not_used_disks_no_deletion(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -2629,9 +2564,7 @@ def test_delete_not_used_disks_no_deletion( rest_client.delete_record.assert_not_called() assert not changed - def test_delete_not_used_disks_deletion( - self, create_module, rest_client, task_wait, mocker - ): + def test_delete_not_used_disks_deletion(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -2709,9 +2642,7 @@ def test_delete_not_used_disks_deletion( ) assert changed - def test_force_remove_all_disks_disks_present( - self, create_module, rest_client, mocker - ): + def test_force_remove_all_disks_disks_present(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -2730,7 +2661,7 @@ def test_force_remove_all_disks_disks_present( description="desc", disks=[ Disk( - type="virtio_disk", + disk_type="virtio_disk", slot=0, uuid="id", vm_uuid="vm-id", @@ -2782,9 +2713,7 @@ def test_force_remove_all_disks_disks_present( mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.wait_shutdown" ).return_value = True - result = ManageVMDisks._force_remove_all_disks( - module, rest_client, vm, disks_before - ) + result = ManageVMDisks._force_remove_all_disks(module, rest_client, vm, disks_before) assert result == ( True, [], @@ -2809,9 +2738,7 @@ def test_force_remove_all_disks_disks_present( False, ) - def test_force_remove_all_disks_items_not_empty_list( - self, create_module, rest_client - ): + def test_force_remove_all_disks_items_not_empty_list(self, create_module, rest_client): module = create_module( params=dict( cluster_instance=dict( @@ -2828,9 +2755,7 @@ def test_force_remove_all_disks_items_not_empty_list( with pytest.raises(ScaleComputingError, match="force"): ManageVMDisks._force_remove_all_disks(module, rest_client, vm, disks_before) - def test_ensure_present_create_new_disk( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_present_create_new_disk(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -2923,9 +2848,7 @@ def test_ensure_present_create_new_disk( ).return_value = True module_path = "scale_computing.hypercore.vm_disk" vm_before, disks_before = ManageVMDisks.get_vm_by_name(module, rest_client) - results = ManageVMDisks.ensure_present_or_set( - module, rest_client, module_path, vm_before - ) + results = ManageVMDisks.ensure_present_or_set(module, rest_client, module_path, vm_before) assert results == ( True, [ @@ -2964,9 +2887,7 @@ def test_ensure_present_create_new_disk( False, ) - def test_ensure_present_update_test_idempotency( - self, create_module, rest_client, mocker - ): + def test_ensure_present_update_test_idempotency(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -3066,9 +2987,7 @@ def test_ensure_present_update_test_idempotency( ).return_value = None module_path = "scale_computing.hypercore.vm_disk" vm_before, disks_before = ManageVMDisks.get_vm_by_name(module, rest_client) - results = ManageVMDisks.ensure_present_or_set( - module, rest_client, module_path, vm_before - ) + results = ManageVMDisks.ensure_present_or_set(module, rest_client, module_path, vm_before) assert results == ( False, [ @@ -3121,9 +3040,7 @@ def test_ensure_present_update_test_idempotency( False, ) - def test_ensure_present_update_record( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_present_update_record(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -3230,9 +3147,7 @@ def test_ensure_present_update_record( ).return_value = True module_path = "scale_computing.hypercore.vm_disk" vm_before, disks_before = ManageVMDisks.get_vm_by_name(module, rest_client) - results = ManageVMDisks.ensure_present_or_set( - module, rest_client, module_path, vm_before - ) + results = ManageVMDisks.ensure_present_or_set(module, rest_client, module_path, vm_before) assert results == ( True, [ @@ -3285,9 +3200,7 @@ def test_ensure_present_update_record( False, ) - def test_ensure_present_attach_iso_cdrom_existing( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_present_attach_iso_cdrom_existing(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -3401,9 +3314,7 @@ def test_ensure_present_attach_iso_cdrom_existing( ).return_value = None module_path = "scale_computing.hypercore.vm_disk" vm_before, disks_before = ManageVMDisks.get_vm_by_name(module, rest_client) - results = ManageVMDisks.ensure_present_or_set( - module, rest_client, module_path, vm_before - ) + results = ManageVMDisks.ensure_present_or_set(module, rest_client, module_path, vm_before) assert results == ( True, [ @@ -3456,9 +3367,7 @@ def test_ensure_present_attach_iso_cdrom_existing( False, ) - def test_ensure_present_attach_iso_cdrom_absent( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_present_attach_iso_cdrom_absent(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -3564,9 +3473,7 @@ def test_ensure_present_attach_iso_cdrom_absent( ).return_value = None module_path = "scale_computing.hypercore.vm_disk" vm_before, disks_before = ManageVMDisks.get_vm_by_name(module, rest_client) - results = ManageVMDisks.ensure_present_or_set( - module, rest_client, module_path, vm_before - ) + results = ManageVMDisks.ensure_present_or_set(module, rest_client, module_path, vm_before) assert results == ( True, [ @@ -3607,9 +3514,7 @@ def test_ensure_present_attach_iso_cdrom_absent( # ensure_present uses only a subset of code of ensure_set. So not testing ensure set again, setting the created # disks to empty list as this is tested in this class in methods above already - def test_ensure_set_force_remove_disks( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_set_force_remove_disks(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -3674,9 +3579,7 @@ def test_ensure_set_force_remove_disks( ).return_value = None module_path = "scale_computing.hypercore.vm_disk" vm_before, disks_before = ManageVMDisks.get_vm_by_name(module, rest_client) - result = ManageVMDisks.ensure_present_or_set( - module, rest_client, module_path, vm_before - ) + result = ManageVMDisks.ensure_present_or_set(module, rest_client, module_path, vm_before) assert result == ( True, [], @@ -3701,9 +3604,7 @@ def test_ensure_set_force_remove_disks( False, ) - def test_ensure_set_remove_unused_disk( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_set_remove_unused_disk(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -3835,9 +3736,7 @@ def test_ensure_set_remove_unused_disk( ).return_value = None module_path = "scale_computing.hypercore.vm_disk" vm_before, disks_before = ManageVMDisks.get_vm_by_name(module, rest_client) - result = ManageVMDisks.ensure_present_or_set( - module, rest_client, module_path, vm_before - ) + result = ManageVMDisks.ensure_present_or_set(module, rest_client, module_path, vm_before) assert result == ( True, @@ -3962,9 +3861,7 @@ def test_get_by_uuid(self, rest_client): ) nic_dict = nic rest_client.get_record.return_value = nic_dict - results = ManageVMNics.get_by_uuid( - rest_client=rest_client, nic_uuid="my-nic-uuid" - ) + results = ManageVMNics.get_by_uuid(rest_client=rest_client, nic_uuid="my-nic-uuid") nic_dict = Nic.from_hypercore(nic_dict).to_hypercore() assert results.to_hypercore() == nic_dict @@ -4164,9 +4061,7 @@ def test_send_create_nic_to_hypercore(self, rest_client, create_module, mocker): [Nic.from_hypercore(new_nic).to_ansible()], ) - def test_send_delete_nic_request_to_hypercore( - self, rest_client, create_module, mocker - ): + def test_send_delete_nic_request_to_hypercore(self, rest_client, create_module, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -4391,9 +4286,7 @@ def _get_nic_2_updated_mac(cls): "ipv4Addresses": ["10.0.0.1", "10.0.0.2"], } - def test_ensure_present_or_set_when_no_change_and_state_set( - self, rest_client, create_module, mocker - ): + def test_ensure_present_or_set_when_no_change_and_state_set(self, rest_client, create_module, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -4425,9 +4318,7 @@ def test_ensure_present_or_set_when_no_change_and_state_set( ) assert results == (False, [], {"before": [], "after": []}) - def test_ensure_present_or_set_when_no_change_and_state_present( - self, rest_client, create_module, mocker - ): + def test_ensure_present_or_set_when_no_change_and_state_present(self, rest_client, create_module, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -4460,9 +4351,7 @@ def test_ensure_present_or_set_when_no_change_and_state_present( assert results == (False, [], {"before": [], "after": []}) @pytest.mark.skip("todo") - def test_ensure_present_or_set_when_changed_create_nics_and_state_set( - self, rest_client, create_module, mocker - ): + def test_ensure_present_or_set_when_changed_create_nics_and_state_set(self, rest_client, create_module, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -4497,9 +4386,7 @@ def test_ensure_present_or_set_when_changed_create_nics_and_state_set( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.do_shutdown_steps" ).return_value = None module_path = "scale_computing.hypercore.vm_nic" - results = ManageVMNics.ensure_present_or_set( - module=module, rest_client=rest_client, module_path=module_path - ) + results = ManageVMNics.ensure_present_or_set(module=module, rest_client=rest_client, module_path=module_path) assert results == ( True, @@ -4546,9 +4433,7 @@ def test_ensure_present_or_set_when_changed_create_nics_and_state_set( ) @pytest.mark.skip("todo") - def test_ensure_present_or_set_when_changed_create_nics_and_state_present( - self, rest_client, create_module, mocker - ): + def test_ensure_present_or_set_when_changed_create_nics_and_state_present(self, rest_client, create_module, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -4583,9 +4468,7 @@ def test_ensure_present_or_set_when_changed_create_nics_and_state_present( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.do_shutdown_steps" ).return_value = None module_path = "scale_computing.hypercore.vm_nic" - results = ManageVMNics.ensure_present_or_set( - module=module, rest_client=rest_client, module_path=module_path - ) + results = ManageVMNics.ensure_present_or_set(module=module, rest_client=rest_client, module_path=module_path) assert results == ( True, @@ -4632,9 +4515,7 @@ def test_ensure_present_or_set_when_changed_create_nics_and_state_present( ) @pytest.mark.skip("how to mockup Node.get_node?") - def test_ensure_present_or_set_when_changed_delete_all_and_state_set( - self, rest_client, create_module, mocker - ): + def test_ensure_present_or_set_when_changed_delete_all_and_state_set(self, rest_client, create_module, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -4670,9 +4551,7 @@ def test_ensure_present_or_set_when_changed_delete_all_and_state_set( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.do_shutdown_steps" ).return_value = None module_path = "scale_computing.hypercore.vm_nic" - results = ManageVMNics.ensure_present_or_set( - module=module, rest_client=rest_client, module_path=module_path - ) + results = ManageVMNics.ensure_present_or_set(module=module, rest_client=rest_client, module_path=module_path) assert results == ( True, @@ -4702,9 +4581,7 @@ def test_ensure_present_or_set_when_changed_delete_all_and_state_set( ) @pytest.mark.skip("todo") - def test_ensure_present_or_set_when_changed_nic_type_and_state_present( - self, rest_client, create_module, mocker - ): + def test_ensure_present_or_set_when_changed_nic_type_and_state_present(self, rest_client, create_module, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -4745,9 +4622,7 @@ def test_ensure_present_or_set_when_changed_nic_type_and_state_present( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.do_shutdown_steps" ).return_value = None module_path = "scale_computing.hypercore.vm_nic" - results = ManageVMNics.ensure_present_or_set( - module=module, rest_client=rest_client, module_path=module_path - ) + results = ManageVMNics.ensure_present_or_set(module=module, rest_client=rest_client, module_path=module_path) assert results == ( True, @@ -4811,9 +4686,7 @@ def test_ensure_present_or_set_when_changed_nic_type_and_state_present( ) @pytest.mark.skip("todo") - def test_ensure_present_or_set_when_changed_nic_type_and_state_set( - self, rest_client, create_module, mocker - ): + def test_ensure_present_or_set_when_changed_nic_type_and_state_set(self, rest_client, create_module, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -4854,9 +4727,7 @@ def test_ensure_present_or_set_when_changed_nic_type_and_state_set( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.do_shutdown_steps" ).return_value = None module_path = "scale_computing.hypercore.vm_nic" - results = ManageVMNics.ensure_present_or_set( - module=module, rest_client=rest_client, module_path=module_path - ) + results = ManageVMNics.ensure_present_or_set(module=module, rest_client=rest_client, module_path=module_path) assert results == ( True, @@ -4920,9 +4791,7 @@ def test_ensure_present_or_set_when_changed_nic_type_and_state_set( ) @pytest.mark.skip("todo") - def test_ensure_present_or_set_when_changed_nic_vlan_and_state_present( - self, rest_client, create_module, mocker - ): + def test_ensure_present_or_set_when_changed_nic_vlan_and_state_present(self, rest_client, create_module, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -4963,9 +4832,7 @@ def test_ensure_present_or_set_when_changed_nic_vlan_and_state_present( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.do_shutdown_steps" ).return_value = None module_path = "scale_computing.hypercore.vm_nic" - results = ManageVMNics.ensure_present_or_set( - module=module, rest_client=rest_client, module_path=module_path - ) + results = ManageVMNics.ensure_present_or_set(module=module, rest_client=rest_client, module_path=module_path) assert results == ( True, @@ -5029,9 +4896,7 @@ def test_ensure_present_or_set_when_changed_nic_vlan_and_state_present( ) @pytest.mark.skip("todo") - def test_ensure_present_or_set_when_changed_nic_vlan_and_state_set( - self, rest_client, create_module, mocker - ): + def test_ensure_present_or_set_when_changed_nic_vlan_and_state_set(self, rest_client, create_module, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -5075,9 +4940,7 @@ def test_ensure_present_or_set_when_changed_nic_vlan_and_state_set( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.do_shutdown_steps" ).return_value = None module_path = "scale_computing.hypercore.vm_nic" - results = ManageVMNics.ensure_present_or_set( - module=module, rest_client=rest_client, module_path=module_path - ) + results = ManageVMNics.ensure_present_or_set(module=module, rest_client=rest_client, module_path=module_path) assert results == ( True, @@ -5141,9 +5004,7 @@ def test_ensure_present_or_set_when_changed_nic_vlan_and_state_set( ) @pytest.mark.skip("todo") - def test_ensure_present_or_set_when_changed_nic_mac_and_state_present( - self, rest_client, create_module, mocker - ): + def test_ensure_present_or_set_when_changed_nic_mac_and_state_present(self, rest_client, create_module, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -5184,9 +5045,7 @@ def test_ensure_present_or_set_when_changed_nic_mac_and_state_present( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.do_shutdown_steps" ).return_value = None module_path = "scale_computing.hypercore.vm_nic" - results = ManageVMNics.ensure_present_or_set( - module=module, rest_client=rest_client, module_path=module_path - ) + results = ManageVMNics.ensure_present_or_set(module=module, rest_client=rest_client, module_path=module_path) assert results == ( True, @@ -5250,9 +5109,7 @@ def test_ensure_present_or_set_when_changed_nic_mac_and_state_present( ) @pytest.mark.skip("todo") - def test_ensure_present_or_set_when_changed_nic_mac_and_state_set( - self, rest_client, create_module, mocker - ): + def test_ensure_present_or_set_when_changed_nic_mac_and_state_set(self, rest_client, create_module, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -5293,9 +5150,7 @@ def test_ensure_present_or_set_when_changed_nic_mac_and_state_set( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.do_shutdown_steps" ).return_value = None module_path = "scale_computing.hypercore.vm_nic" - results = ManageVMNics.ensure_present_or_set( - module=module, rest_client=rest_client, module_path=module_path - ) + results = ManageVMNics.ensure_present_or_set(module=module, rest_client=rest_client, module_path=module_path) assert results == ( True, diff --git a/tests/unit/plugins/module_utils/test_vm_snapshot.py b/tests/unit/plugins/module_utils/test_vm_snapshot.py index c91238b0..c368608e 100644 --- a/tests/unit/plugins/module_utils/test_vm_snapshot.py +++ b/tests/unit/plugins/module_utils/test_vm_snapshot.py @@ -3,22 +3,19 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type -import sys - -import pytest import datetime +import sys from datetime import date -from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm_snapshot import ( - VMSnapshot, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +import pytest +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm_snapshot import VMSnapshot pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -77,7 +74,7 @@ def setup_method(self): device_snapshots=self.device_snapshots, timestamp=123, label="snapshot", - type="USER", + snapshot_type="USER", automated_trigger_timestamp=111, local_retain_until_timestamp=222, remote_retain_until_timestamp=333, @@ -196,7 +193,7 @@ def test_vm_snapshot_from_ansible(self): vm=vm_snapshot_from_ansible.vm, device_snapshots=vm_snapshot_from_ansible.device_snapshots, label=vm_snapshot_from_ansible.label, - type=vm_snapshot_from_ansible.type, + snapshot_type=vm_snapshot_from_ansible.type, ) def test_get_snapshot_by_uuid(self, rest_client): @@ -248,9 +245,7 @@ def test_get_snapshots_by_query(self, rest_client, query): # ============================= def test_hypercore_disk_to_ansible(self): - hypercore_disk_to_ansible = VMSnapshot.hypercore_disk_to_ansible( - self.disk_hypercore - ) + hypercore_disk_to_ansible = VMSnapshot.hypercore_disk_to_ansible(self.disk_hypercore) assert hypercore_disk_to_ansible == self.disk_ansible def test_get_vm_disk_info_by_uuid(self, rest_client): diff --git a/tests/unit/plugins/modules/__init__.py b/tests/unit/plugins/modules/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/unit/plugins/modules/test_api.py b/tests/unit/plugins/modules/test_api.py index 79ac6893..f3301005 100644 --- a/tests/unit/plugins/modules/test_api.py +++ b/tests/unit/plugins/modules/test_api.py @@ -3,18 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import api -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -27,9 +26,7 @@ class TestGetMethod: ("list_records_raw_return"), [([dict(name="record1"), dict(name="record2")]), (dict(name="record1"))], ) - def test_get_method_record_present( - self, create_module, rest_client, list_records_raw_return - ): + def test_get_method_record_present(self, create_module, rest_client, list_records_raw_return): module = create_module( params=dict( cluster_instance=dict( diff --git a/tests/unit/plugins/modules/test_certificate.py b/tests/unit/plugins/modules/test_certificate.py index f8b408e6..86ed2aef 100644 --- a/tests/unit/plugins/modules/test_certificate.py +++ b/tests/unit/plugins/modules/test_certificate.py @@ -3,18 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import certificate -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -25,9 +24,7 @@ class TestMain: def test_params_certificate(self, run_main) -> None: params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), private_key="this_key", certificate="this_certificate", ) @@ -43,9 +40,7 @@ def test_params_certificate(self, run_main) -> None: class TestRun: - def test_run_with_present_certificate( - self, create_module, rest_client, mocker - ) -> None: + def test_run_with_present_certificate(self, create_module, rest_client, mocker) -> None: module = create_module( params=dict( cluster_instance=dict( diff --git a/tests/unit/plugins/modules/test_cluster_info.py b/tests/unit/plugins/modules/test_cluster_info.py index d1788440..fe260f52 100644 --- a/tests/unit/plugins/modules/test_cluster_info.py +++ b/tests/unit/plugins/modules/test_cluster_info.py @@ -3,18 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import cluster_info -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_cluster_name.py b/tests/unit/plugins/modules/test_cluster_name.py index 57ccd833..c4a3c435 100644 --- a/tests/unit/plugins/modules/test_cluster_name.py +++ b/tests/unit/plugins/modules/test_cluster_name.py @@ -1,15 +1,14 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import cluster_name -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -27,9 +26,7 @@ def test_all_params(self, run_main, mocker): ), name_new="updated_name", ) - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.modules.cluster_name.HyperCoreVersion" - ) + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.modules.cluster_name.HyperCoreVersion") mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.modules.cluster_name.HyperCoreVersion.verify" ) diff --git a/tests/unit/plugins/modules/test_dns_config.py b/tests/unit/plugins/modules/test_dns_config.py index fbf2accf..29241374 100644 --- a/tests/unit/plugins/modules/test_dns_config.py +++ b/tests/unit/plugins/modules/test_dns_config.py @@ -3,22 +3,19 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.dns_config import ( - DNSConfig, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.dns_config import DNSConfig +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import dns_config -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -147,9 +144,7 @@ def test_modify_dns_config( ): module = create_module( params=dict( - cluster_instance=dict( - host="https://0.0.0.0", username="admin", password="admin" - ), + cluster_instance=dict(host="https://0.0.0.0", username="admin", password="admin"), search_domains=search_domains, dns_servers=dns_servers, state=state, @@ -172,9 +167,7 @@ def test_modify_dns_config( called_with_dict = dict( endpoint="/rest/v1/DNSConfig/test", - payload=dict( - searchDomains=expected_search_domains, serverIPs=expected_server_ips - ), + payload=dict(searchDomains=expected_search_domains, serverIPs=expected_server_ips), check_mode=False, ) dns_config.modify_dns_config(module, rest_client) @@ -192,9 +185,7 @@ def test_modify_dns_config_missing_config(self, create_module, rest_client, mock with pytest.raises(errors.ScaleComputingError): module = create_module( params=dict( - cluster_instance=dict( - host="https://0.0.0.0", username="admin", password="admin" - ), + cluster_instance=dict(host="https://0.0.0.0", username="admin", password="admin"), search_domains=[], dns_servers=[], state="set", diff --git a/tests/unit/plugins/modules/test_dns_config_info.py b/tests/unit/plugins/modules/test_dns_config_info.py index 16fdd6ab..2be0b877 100644 --- a/tests/unit/plugins/modules/test_dns_config_info.py +++ b/tests/unit/plugins/modules/test_dns_config_info.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - dns_config_info, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import dns_config_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_email_alert.py b/tests/unit/plugins/modules/test_email_alert.py index 5f416701..8c9ca85d 100644 --- a/tests/unit/plugins/modules/test_email_alert.py +++ b/tests/unit/plugins/modules/test_email_alert.py @@ -3,27 +3,22 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys - from unittest import mock from unittest.mock import call import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.email_alert import ( - EmailAlert, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.email_alert import EmailAlert +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import email_alert -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) - pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, reason=f"requires python{MIN_PYTHON_VERSION[0]}.{MIN_PYTHON_VERSION[1]} or higher", @@ -235,9 +230,7 @@ def test_update_email_alert( if update_email == email_on_client or email == email_new: EmailAlert.update.assert_not_called() else: - EmailAlert.update.assert_called_once_with( - rc_email_alert, **called_with_dict - ) + EmailAlert.update.assert_called_once_with(rc_email_alert, **called_with_dict) assert changed == expected_return[0] assert record == expected_return[1] @@ -327,10 +320,7 @@ def test_delete_email_alert( email_alert.delete_email_alert(module, rest_client) assert EmailAlert.delete.call_count == len(rc_email_alerts) EmailAlert.delete.assert_has_calls( - [ - call(rc_email_alert, **called_with_dict) - for rc_email_alert in rc_email_alerts - ] + [call(rc_email_alert, **called_with_dict) for rc_email_alert in rc_email_alerts] ) assert changed == expected_return[0] assert record == expected_return[1] @@ -352,9 +342,7 @@ def test_delete_email_alert( ), ], ) - def test_send_test( - self, create_module, rest_client, task_wait, mocker, rc_email_alert, email - ): + def test_send_test(self, create_module, rest_client, task_wait, mocker, rc_email_alert, email): module = create_module( params=dict( cluster_instance=self.cluster_instance, diff --git a/tests/unit/plugins/modules/test_email_alert_info.py b/tests/unit/plugins/modules/test_email_alert_info.py index 7e422c83..afc07adc 100644 --- a/tests/unit/plugins/modules/test_email_alert_info.py +++ b/tests/unit/plugins/modules/test_email_alert_info.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - email_alert_info, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import email_alert_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_iso.py b/tests/unit/plugins/modules/test_iso.py index f091e37b..b0cd1540 100644 --- a/tests/unit/plugins/modules/test_iso.py +++ b/tests/unit/plugins/modules/test_iso.py @@ -3,19 +3,19 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys +from unittest.mock import mock_open +from unittest.mock import patch import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import iso -from unittest.mock import patch, mock_open -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -85,9 +85,7 @@ def test_ensure_absent(self, create_module, rest_client, task_wait): class TestEnsurePresent: - def test_ensure_present_iso_image_present( - self, create_module, rest_client, os_stat, task_wait - ): + def test_ensure_present_iso_image_present(self, create_module, rest_client, os_stat, task_wait): module = create_module( params=dict( cluster_instance=dict( @@ -155,9 +153,7 @@ def test_ensure_present_iso_image_present( }, ) - def test_ensure_present_iso_image_present_ready_for_insert_true( - self, create_module, rest_client - ): + def test_ensure_present_iso_image_present_ready_for_insert_true(self, create_module, rest_client): module = create_module( params=dict( cluster_instance=dict( diff --git a/tests/unit/plugins/modules/test_iso_info.py b/tests/unit/plugins/modules/test_iso_info.py index b9efb09c..871a18bd 100644 --- a/tests/unit/plugins/modules/test_iso_info.py +++ b/tests/unit/plugins/modules/test_iso_info.py @@ -3,18 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import iso_info -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_minimal.py b/tests/unit/plugins/modules/test_minimal.py index a65b261e..000d8114 100644 --- a/tests/unit/plugins/modules/test_minimal.py +++ b/tests/unit/plugins/modules/test_minimal.py @@ -1,13 +1,13 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_node_info.py b/tests/unit/plugins/modules/test_node_info.py index 5d34dae9..7e4b5545 100644 --- a/tests/unit/plugins/modules/test_node_info.py +++ b/tests/unit/plugins/modules/test_node_info.py @@ -3,18 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import node_info -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_oidc_config.py b/tests/unit/plugins/modules/test_oidc_config.py index 6bd69890..76bf09bc 100644 --- a/tests/unit/plugins/modules/test_oidc_config.py +++ b/tests/unit/plugins/modules/test_oidc_config.py @@ -1,18 +1,15 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.oidc import Oidc +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import oidc_config -from ansible_collections.scale_computing.hypercore.plugins.module_utils.oidc import ( - Oidc, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -23,9 +20,7 @@ class TestMain: def test_minimal_set_of_params(self, run_main) -> None: params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), client_id="this_client", scopes="this_scopes", shared_secret="this_shared_secret", @@ -43,9 +38,7 @@ def test_minimal_set_of_params(self, run_main) -> None: def test_maximum_set_of_params(self, run_main) -> None: params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), client_id="this_client", scopes="this_scopes", shared_secret="this_shared_secret", @@ -109,9 +102,7 @@ def test_ensure_present_when_create_oidc(self, create_module, rest_client, mocke mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.module_utils.task_tag.TaskTag.wait_task" ).return_value = {} - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.module_utils.oidc.Oidc.get" - ).side_effect = [ + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.module_utils.oidc.Oidc.get").side_effect = [ None, Oidc( client_id="this_client", @@ -163,9 +154,7 @@ def test_ensure_present_when_update_oidc(self, create_module, rest_client, mocke # mocker.patch( # "ansible_collections.scale_computing.hypercore.plugins.module_utils.oidc.Oidc.get" # ).return_value = {} - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.module_utils.oidc.Oidc.get" - ).side_effect = [ + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.module_utils.oidc.Oidc.get").side_effect = [ Oidc( client_id="cid", certificate="", diff --git a/tests/unit/plugins/modules/test_oidc_config_info.py b/tests/unit/plugins/modules/test_oidc_config_info.py index 3c1382a5..cdb9f233 100644 --- a/tests/unit/plugins/modules/test_oidc_config_info.py +++ b/tests/unit/plugins/modules/test_oidc_config_info.py @@ -1,20 +1,15 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - oidc_config_info, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.oidc import ( - Oidc, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.oidc import Oidc +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import oidc_config_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -25,9 +20,7 @@ class TestMain: def test_minimal_set_of_params(self, run_main_info) -> None: params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), ) success, results = run_main_info(oidc_config_info, params) @@ -36,9 +29,7 @@ def test_minimal_set_of_params(self, run_main_info) -> None: def test_maximum_set_of_params(self, run_main_info) -> None: params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), ) success, results = run_main_info(oidc_config_info, params) @@ -47,9 +38,7 @@ def test_maximum_set_of_params(self, run_main_info) -> None: class TestRun: - def test_run_oidc_info_without_record( - self, create_module, rest_client, mocker - ) -> None: + def test_run_oidc_info_without_record(self, create_module, rest_client, mocker) -> None: module = create_module( params=dict( cluster_instance=dict( @@ -64,9 +53,7 @@ def test_run_oidc_info_without_record( assert isinstance(results, tuple) assert results == (False, None) - def test_run_oidc_info_with_record( - self, create_module, rest_client, mocker - ) -> None: + def test_run_oidc_info_with_record(self, create_module, rest_client, mocker) -> None: module = create_module( params=dict( cluster_instance=dict( diff --git a/tests/unit/plugins/modules/test_registration.py b/tests/unit/plugins/modules/test_registration.py index 93e8963c..61ce56fa 100644 --- a/tests/unit/plugins/modules/test_registration.py +++ b/tests/unit/plugins/modules/test_registration.py @@ -1,18 +1,15 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.registration import Registration +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import registration -from ansible_collections.scale_computing.hypercore.plugins.module_utils.registration import ( - Registration, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -23,9 +20,7 @@ class TestMain: def test_minimal_set_of_params(self, run_main) -> None: params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), state="present", ) @@ -40,9 +35,7 @@ def test_minimal_set_of_params(self, run_main) -> None: def test_maximum_set_of_params(self, run_main) -> None: params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), state="present", company_name="this_company", contact="this_contact", @@ -60,9 +53,7 @@ def test_maximum_set_of_params(self, run_main) -> None: class TestRun: - def test_run_with_present_registration( - self, create_module, rest_client, mocker - ) -> None: + def test_run_with_present_registration(self, create_module, rest_client, mocker) -> None: module = create_module( params=dict( cluster_instance=dict( @@ -83,9 +74,7 @@ def test_run_with_present_registration( assert isinstance(results, tuple) assert results == (True, {}, {}) - def test_run_with_absent_registration( - self, create_module, rest_client, mocker - ) -> None: + def test_run_with_absent_registration(self, create_module, rest_client, mocker) -> None: module = create_module( params=dict( cluster_instance=dict( @@ -108,9 +97,7 @@ def test_run_with_absent_registration( class TestEnsurePresent: - def test_ensure_present_when_create_registration( - self, create_module, rest_client, mocker - ): + def test_ensure_present_when_create_registration(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -135,9 +122,7 @@ def test_ensure_present_when_create_registration( assert isinstance(result, tuple) assert result == (False, None, {"before": None, "after": None}) - def test_ensure_present_when_update_registration( - self, create_module, rest_client, mocker - ): + def test_ensure_present_when_update_registration(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -177,9 +162,7 @@ def test_ensure_present_when_update_registration( class TestEnsureAbsent: - def test_ensure_absent_when_exist_registration( - self, create_module, rest_client, mocker - ): + def test_ensure_absent_when_exist_registration(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -216,9 +199,7 @@ def test_ensure_absent_when_exist_registration( }, ) - def test_ensure_absent_when_not_exist_registration( - self, create_module, rest_client, mocker - ): + def test_ensure_absent_when_not_exist_registration(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( diff --git a/tests/unit/plugins/modules/test_remote_cluster_info.py b/tests/unit/plugins/modules/test_remote_cluster_info.py index c3262bec..5994ff47 100644 --- a/tests/unit/plugins/modules/test_remote_cluster_info.py +++ b/tests/unit/plugins/modules/test_remote_cluster_info.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - remote_cluster_info, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import remote_cluster_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -58,9 +55,7 @@ def test_run_records_present(self, create_module, rest_client): } ] - def test_run_records_present_without_selected_cluster( - self, create_module, rest_client - ): + def test_run_records_present_without_selected_cluster(self, create_module, rest_client): module = create_module( params=dict( cluster_instance=dict( diff --git a/tests/unit/plugins/modules/test_smtp.py b/tests/unit/plugins/modules/test_smtp.py index 136fdd35..58ea2ccd 100644 --- a/tests/unit/plugins/modules/test_smtp.py +++ b/tests/unit/plugins/modules/test_smtp.py @@ -3,22 +3,19 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.smtp import ( - SMTP, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.smtp import SMTP +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import smtp -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -181,9 +178,7 @@ def test_modify_smtp_config( ): module = create_module( params=dict( - cluster_instance=dict( - host="https://0.0.0.0", username="admin", password="admin" - ), + cluster_instance=dict(host="https://0.0.0.0", username="admin", password="admin"), server=server_param, port=port_param, use_ssl=use_ssl_param, @@ -205,9 +200,7 @@ def test_modify_smtp_config( from_address=rc_from_address, latest_task_tag={}, ) - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.module_utils.smtp.SMTP.get_state" - ) + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.module_utils.smtp.SMTP.get_state") rest_client.create_record.return_value = { "taskTag": 123, } @@ -230,15 +223,11 @@ def test_modify_smtp_config( else: rest_client.update_record.assert_not_called() - def test_modify_smtp_config_missing_config( - self, create_module, rest_client, mocker - ): + def test_modify_smtp_config_missing_config(self, create_module, rest_client, mocker): with pytest.raises(errors.ScaleComputingError): module = create_module( params=dict( - cluster_instance=dict( - host="https://0.0.0.0", username="admin", password="admin" - ), + cluster_instance=dict(host="https://0.0.0.0", username="admin", password="admin"), server="test.com", port=25, use_ssl=True, diff --git a/tests/unit/plugins/modules/test_smtp_info.py b/tests/unit/plugins/modules/test_smtp_info.py index e0cea541..3ce860a2 100644 --- a/tests/unit/plugins/modules/test_smtp_info.py +++ b/tests/unit/plugins/modules/test_smtp_info.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - smtp_info, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import smtp_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_snapshot_schedule.py b/tests/unit/plugins/modules/test_snapshot_schedule.py index 002d6702..f6546909 100644 --- a/tests/unit/plugins/modules/test_snapshot_schedule.py +++ b/tests/unit/plugins/modules/test_snapshot_schedule.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - snapshot_schedule, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import snapshot_schedule pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -60,9 +57,7 @@ def test_ensure_absent(self, create_module, rest_client): class TestEnsurePresent: - def test_ensure_present_snapshot_schedule_record_present_no_update( - self, create_module, rest_client - ): + def test_ensure_present_snapshot_schedule_record_present_no_update(self, create_module, rest_client): module = create_module( params=dict( cluster_instance=dict( @@ -106,9 +101,7 @@ def test_ensure_present_snapshot_schedule_record_present_no_update( }, ) - def test_ensure_present_snapshot_schedule_record_updated( - self, create_module, rest_client - ): + def test_ensure_present_snapshot_schedule_record_updated(self, create_module, rest_client): module = create_module( params=dict( cluster_instance=dict( @@ -160,9 +153,7 @@ def test_ensure_present_snapshot_schedule_record_updated( }, ) - def test_ensure_present_snapshot_schedule_image_absent( - self, create_module, rest_client - ): + def test_ensure_present_snapshot_schedule_image_absent(self, create_module, rest_client): module = create_module( params=dict( cluster_instance=dict( diff --git a/tests/unit/plugins/modules/test_snapshot_schedule_info.py b/tests/unit/plugins/modules/test_snapshot_schedule_info.py index f1a1398a..9fa22ef8 100644 --- a/tests/unit/plugins/modules/test_snapshot_schedule_info.py +++ b/tests/unit/plugins/modules/test_snapshot_schedule_info.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - snapshot_schedule_info, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import snapshot_schedule_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_support_tunnel.py b/tests/unit/plugins/modules/test_support_tunnel.py index 2e33e32c..a4d1b7f2 100644 --- a/tests/unit/plugins/modules/test_support_tunnel.py +++ b/tests/unit/plugins/modules/test_support_tunnel.py @@ -1,15 +1,14 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import support_tunnel -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -57,10 +56,7 @@ def test_required_if(self, run_main): success, result = run_main(support_tunnel, params) assert success is False - assert ( - "state is present but all of the following are missing: code" - in result["msg"] - ) + assert "state is present but all of the following are missing: code" in result["msg"] def test_fail(self, run_main): success, result = run_main(support_tunnel) diff --git a/tests/unit/plugins/modules/test_syslog_server.py b/tests/unit/plugins/modules/test_syslog_server.py index b94b363d..ef5af614 100644 --- a/tests/unit/plugins/modules/test_syslog_server.py +++ b/tests/unit/plugins/modules/test_syslog_server.py @@ -3,24 +3,20 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys - from unittest import mock -import pytest -from ansible_collections.scale_computing.hypercore.plugins.module_utils.syslog_server import ( - SyslogServer, -) +import pytest +from ansible_collections.scale_computing.hypercore.plugins.module_utils.syslog_server import SyslogServer +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import syslog_server -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) - pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, reason=f"requires python{MIN_PYTHON_VERSION[0]}.{MIN_PYTHON_VERSION[1]} or higher", @@ -103,9 +99,7 @@ def test_create_syslog_server( check_mode=False, ) - changed, record, records, diff = syslog_server.create_syslog_server( - module, rest_client - ) + changed, record, records, diff = syslog_server.create_syslog_server(module, rest_client) SyslogServer.create = mock.create_autospec(SyslogServer.create) syslog_server.create_syslog_server(module, rest_client) @@ -125,9 +119,7 @@ def test_create_syslog_server( ("0.0.0.0", "0.0.0.0", 42, "tcp", ("0.0.0.0", 42, "tcp")), ], ) - def test_build_update_payload( - self, create_module, host, host_new, port, protocol, expected - ): + def test_build_update_payload(self, create_module, host, host_new, port, protocol, expected): module = create_module( params=dict( cluster_instance=self.cluster_instance, @@ -344,16 +336,12 @@ def test_update_syslog_server( called_with_dict = dict( rest_client=rest_client, - payload=dict( - host=expected_host, port=expected_port, protocol=expected_protocol - ), + payload=dict(host=expected_host, port=expected_port, protocol=expected_protocol), check_mode=False, ) SyslogServer.update = mock.create_autospec(SyslogServer.update) - changed, record, records, diff = syslog_server.update_syslog_server( - rc_syslog_server, module, rest_client - ) + changed, record, records, diff = syslog_server.update_syslog_server(rc_syslog_server, module, rest_client) if not rc_syslog_server: old_payload = None else: @@ -366,9 +354,7 @@ def test_update_syslog_server( if (not old_payload) or called_with_dict.get("payload") == old_payload: SyslogServer.update.assert_not_called() else: - SyslogServer.update.assert_called_once_with( - rc_syslog_server, **called_with_dict - ) + SyslogServer.update.assert_called_once_with(rc_syslog_server, **called_with_dict) print("record:", record) print("records:", records) @@ -432,16 +418,12 @@ def test_delete_syslog_server( check_mode=False, ) - changed, record, records, diff = syslog_server.delete_syslog_server( - rc_syslog_server, module, rest_client - ) + changed, record, records, diff = syslog_server.delete_syslog_server(rc_syslog_server, module, rest_client) SyslogServer.delete = mock.create_autospec(SyslogServer.delete) syslog_server.delete_syslog_server(rc_syslog_server, module, rest_client) if rc_syslog_server: - SyslogServer.delete.assert_called_once_with( - rc_syslog_server, **called_with_dict - ) + SyslogServer.delete.assert_called_once_with(rc_syslog_server, **called_with_dict) else: SyslogServer.delete.assert_not_called() diff --git a/tests/unit/plugins/modules/test_syslog_server_info.py b/tests/unit/plugins/modules/test_syslog_server_info.py index 823bc3e3..41db9863 100644 --- a/tests/unit/plugins/modules/test_syslog_server_info.py +++ b/tests/unit/plugins/modules/test_syslog_server_info.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - syslog_server_info, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import syslog_server_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_time_server.py b/tests/unit/plugins/modules/test_time_server.py index 19db8343..21ad8a15 100644 --- a/tests/unit/plugins/modules/test_time_server.py +++ b/tests/unit/plugins/modules/test_time_server.py @@ -3,22 +3,19 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.time_server import ( - TimeServer, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.time_server import TimeServer +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import time_server -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -42,9 +39,7 @@ def test_modify_time_server( ): module = create_module( params=dict( - cluster_instance=dict( - host="https://0.0.0.0", username="admin", password="admin" - ), + cluster_instance=dict(host="https://0.0.0.0", username="admin", password="admin"), source=param_source, ) ) @@ -76,9 +71,7 @@ def test_modify_time_server( else: rest_client.update_record.assert_not_called() - def test_modify_time_server_missing_config( - self, create_module, rest_client, mocker - ): + def test_modify_time_server_missing_config(self, create_module, rest_client, mocker): with pytest.raises(errors.ScaleComputingError): module = create_module( params=dict( diff --git a/tests/unit/plugins/modules/test_time_server_info.py b/tests/unit/plugins/modules/test_time_server_info.py index 6698768a..c0906646 100644 --- a/tests/unit/plugins/modules/test_time_server_info.py +++ b/tests/unit/plugins/modules/test_time_server_info.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - time_server_info, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import time_server_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_time_zone.py b/tests/unit/plugins/modules/test_time_zone.py index 5ec1d1ae..a4613108 100644 --- a/tests/unit/plugins/modules/test_time_zone.py +++ b/tests/unit/plugins/modules/test_time_zone.py @@ -3,22 +3,19 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.time_zone import ( - TimeZone, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.time_zone import TimeZone +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import time_zone -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -42,9 +39,7 @@ def test_modify_time_zone( ): module = create_module( params=dict( - cluster_instance=dict( - host="https://0.0.0.0", username="admin", password="admin" - ), + cluster_instance=dict(host="https://0.0.0.0", username="admin", password="admin"), zone=param_zone, ) ) @@ -55,9 +50,7 @@ def test_modify_time_zone( zone=rc_time_zone, latest_task_tag={}, ) - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.module_utils.time_zone.TimeZone.get_state" - ) + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.module_utils.time_zone.TimeZone.get_state") rest_client.create_record.return_value = { "taskTag": 123, } @@ -89,9 +82,7 @@ def test_modify_time_zone_missing_config(self, create_module, rest_client, mocke time_zone.modify_time_zone(module, rest_client) - def test_modify_time_zone_unsupported_zone( - self, create_module, rest_client, mocker - ): + def test_modify_time_zone_unsupported_zone(self, create_module, rest_client, mocker): with pytest.raises(errors.ScaleComputingError): module = create_module( params=dict( diff --git a/tests/unit/plugins/modules/test_time_zone_info.py b/tests/unit/plugins/modules/test_time_zone_info.py index 94158ae5..5797af12 100644 --- a/tests/unit/plugins/modules/test_time_zone_info.py +++ b/tests/unit/plugins/modules/test_time_zone_info.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - time_zone_info, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import time_zone_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_user.py b/tests/unit/plugins/modules/test_user.py index 67730d81..d8799083 100644 --- a/tests/unit/plugins/modules/test_user.py +++ b/tests/unit/plugins/modules/test_user.py @@ -1,17 +1,16 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.role import Role from ansible_collections.scale_computing.hypercore.plugins.module_utils.user import User +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import user -from ansible_collections.scale_computing.hypercore.plugins.module_utils.role import Role -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_user_info.py b/tests/unit/plugins/modules/test_user_info.py index 7d16a547..3ac5370f 100644 --- a/tests/unit/plugins/modules/test_user_info.py +++ b/tests/unit/plugins/modules/test_user_info.py @@ -3,18 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import user_info -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -154,9 +153,7 @@ def test_run_selected_user(self, create_module, rest_client, mocker): result = user_info.run(module, rest_client) - rest_client.list_records.assert_called_with( - "/rest/v1/User", {"username": "admin"} - ) + rest_client.list_records.assert_called_with("/rest/v1/User", {"username": "admin"}) assert result == [ { "fullname": "admin", diff --git a/tests/unit/plugins/modules/test_version_update.py b/tests/unit/plugins/modules/test_version_update.py index c9aa5df1..5fe39c5b 100644 --- a/tests/unit/plugins/modules/test_version_update.py +++ b/tests/unit/plugins/modules/test_version_update.py @@ -1,15 +1,14 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import version_update -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_version_update_info.py b/tests/unit/plugins/modules/test_version_update_info.py index 597739bf..3cebfc4c 100644 --- a/tests/unit/plugins/modules/test_version_update_info.py +++ b/tests/unit/plugins/modules/test_version_update_info.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - version_update_info, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import version_update_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -79,7 +76,7 @@ def test_run(self, rest_client): }, ] - records, next, latest = version_update_info.run(rest_client) + records, next_version, latest_version = version_update_info.run(rest_client) assert records == [ { @@ -133,7 +130,7 @@ def test_run(self, rest_client): "timestamp": 1676920067, }, ] - assert next == { + assert next_version == { "uuid": "9.2.11.210763", "description": "description", "change_log": "change log", @@ -143,7 +140,7 @@ def test_run(self, rest_client): "revision": 11, "timestamp": 1676920067, } - assert latest == { + assert latest_version == { "uuid": "10.2.11.210763", "description": "description", "change_log": "change log", @@ -157,8 +154,8 @@ def test_run(self, rest_client): def test_run_no_records(self, rest_client): rest_client.list_records.return_value = [] - records, next, latest = version_update_info.run(rest_client) + records, next_version, latest_version = version_update_info.run(rest_client) assert records == [] - assert next is None - assert latest is None + assert next_version is None + assert latest_version is None diff --git a/tests/unit/plugins/modules/test_version_update_status_info.py b/tests/unit/plugins/modules/test_version_update_status_info.py index 1e2c1e6f..2a85bf4a 100644 --- a/tests/unit/plugins/modules/test_version_update_status_info.py +++ b/tests/unit/plugins/modules/test_version_update_status_info.py @@ -3,23 +3,18 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - version_update_status_info, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.hypercore_version import ( - UpdateStatus, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.hypercore_version import UpdateStatus +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import version_update_status_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_virtual_disk.py b/tests/unit/plugins/modules/test_virtual_disk.py index 1a1dd8e0..a5901c43 100644 --- a/tests/unit/plugins/modules/test_virtual_disk.py +++ b/tests/unit/plugins/modules/test_virtual_disk.py @@ -1,21 +1,16 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.errors import ScaleComputingError +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.module_utils.virtual_disk import VirtualDisk from ansible_collections.scale_computing.hypercore.plugins.modules import virtual_disk -from ansible_collections.scale_computing.hypercore.plugins.module_utils.virtual_disk import ( - VirtualDisk, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.errors import ( - ScaleComputingError, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -39,9 +34,7 @@ class TestMain: "presen", ( False, - { - "msg": "value of state must be one of: present, absent, got: presen" - }, + {"msg": "value of state must be one of: present, absent, got: presen"}, ), ), ( @@ -207,9 +200,7 @@ class TestMain: "absen", ( False, - { - "msg": "value of state must be one of: present, absent, got: absen" - }, + {"msg": "value of state must be one of: present, absent, got: absen"}, ), ), ( @@ -380,9 +371,7 @@ def test_parameters_virtual_disk( expected_result, ) -> None: params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), name=file_name_test, source=file_location_test, state=state_test, @@ -483,9 +472,7 @@ def test_run_virtual_disk( ) -> None: module = create_module( params=dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), name="foobar.qcow2", source="c:/somewhere/foobar.qcow2", state=state_test, @@ -1160,9 +1147,7 @@ def test_ensure_present_virtual_disk( ): module = create_module( params=dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), name="foobar.qcow2", source="c:/somewhere/foobar.qcow2", state="present", @@ -1171,9 +1156,7 @@ def test_ensure_present_virtual_disk( # Does virtual_disk exist on cluster or not. cluster_before_virtual_disk_obj = None if cluster_before_virtual_disk_dict: - cluster_before_virtual_disk_obj = VirtualDisk.from_hypercore( - cluster_before_virtual_disk_dict - ) + cluster_before_virtual_disk_obj = VirtualDisk.from_hypercore(cluster_before_virtual_disk_dict) else: # Mock read_disk_file(); returns a tuple() with file content and file size. mocker.patch( @@ -1188,9 +1171,7 @@ def test_ensure_present_virtual_disk( # Mock wait_task_and_get_updated(); Performs wait_task and returns updated virtual disk. cluster_after_virtual_disk = None if cluster_after_virtual_disk_dict: - cluster_after_virtual_disk = VirtualDisk.from_hypercore( - cluster_after_virtual_disk_dict - ).to_ansible() + cluster_after_virtual_disk = VirtualDisk.from_hypercore(cluster_after_virtual_disk_dict).to_ansible() mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.modules.virtual_disk.wait_task_and_get_updated" ).return_value = cluster_after_virtual_disk @@ -1200,13 +1181,9 @@ def test_ensure_present_virtual_disk( ScaleComputingError, match=f"Invalid size for file: {module.params['source']}", ): - virtual_disk.ensure_present( - module, rest_client, cluster_before_virtual_disk_obj - ) + virtual_disk.ensure_present(module, rest_client, cluster_before_virtual_disk_obj) else: - result = virtual_disk.ensure_present( - module, rest_client, cluster_before_virtual_disk_obj - ) + result = virtual_disk.ensure_present(module, rest_client, cluster_before_virtual_disk_obj) assert isinstance(result, tuple) assert result == expected_result @@ -1359,9 +1336,7 @@ def test_ensure_absent_virtual_disk( ): module = create_module( params=dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), name="foobar.qcow2", source="c:/somewhere/foobar.qcow2", state="absent", @@ -1370,9 +1345,7 @@ def test_ensure_absent_virtual_disk( # Does virtual_disk exist on cluster or not. cluster_before_virtual_disk_obj = None if cluster_before_virtual_disk_dict: - cluster_before_virtual_disk_obj = VirtualDisk.from_hypercore( - cluster_before_virtual_disk_dict - ) + cluster_before_virtual_disk_obj = VirtualDisk.from_hypercore(cluster_before_virtual_disk_dict) # Mock send_delete_request(); returns empty task tag. mocker.patch( @@ -1382,16 +1355,12 @@ def test_ensure_absent_virtual_disk( # Mock wait_task_and_get_updated(); Performs wait_task and returns updated virtual disk. cluster_after_virtual_disk = None if cluster_after_virtual_disk_dict: - cluster_after_virtual_disk = VirtualDisk.from_hypercore( - cluster_after_virtual_disk_dict - ).to_ansible() + cluster_after_virtual_disk = VirtualDisk.from_hypercore(cluster_after_virtual_disk_dict).to_ansible() mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.modules.virtual_disk.wait_task_and_get_updated" ).return_value = cluster_after_virtual_disk - result = virtual_disk.ensure_absent( - module, rest_client, cluster_before_virtual_disk_obj - ) + result = virtual_disk.ensure_absent(module, rest_client, cluster_before_virtual_disk_obj) assert isinstance(result, tuple) assert result == expected_result @@ -1591,9 +1560,7 @@ def test_wait_task_and_get_updated_virtual_disk( ): module = create_module( params=dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), name="foobar.qcow2", source="c:/somewhere/foobar.qcow2", state="present", @@ -1614,9 +1581,7 @@ def test_wait_task_and_get_updated_virtual_disk( "ansible_collections.scale_computing.hypercore.plugins.module_utils.virtual_disk.VirtualDisk.get_by_name" ).return_value = updated_virtual_disk_obj - result = virtual_disk.wait_task_and_get_updated( - rest_client, module, task, must_exist - ) + result = virtual_disk.wait_task_and_get_updated(rest_client, module, task, must_exist) assert result == expected_result @@ -1670,9 +1635,7 @@ def test_read_disk_file_virtual_disk( ): module = create_module( params=dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), name="foobar.qcow2", source=file_location, state="present", diff --git a/tests/unit/plugins/modules/test_virtual_disk_attach.py b/tests/unit/plugins/modules/test_virtual_disk_attach.py index e16056f2..58be8979 100644 --- a/tests/unit/plugins/modules/test_virtual_disk_attach.py +++ b/tests/unit/plugins/modules/test_virtual_disk_attach.py @@ -3,25 +3,20 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - virtual_disk_attach, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import VM from ansible_collections.scale_computing.hypercore.plugins.module_utils.disk import Disk -from ansible_collections.scale_computing.hypercore.plugins.module_utils.virtual_disk import ( - VirtualDisk, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.module_utils.virtual_disk import VirtualDisk +from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import VM +from ansible_collections.scale_computing.hypercore.plugins.modules import virtual_disk_attach pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -29,6 +24,7 @@ ) +# pylint: disable=redefined-outer-name @pytest.fixture def virtual_machine(): return VM( @@ -36,11 +32,12 @@ def virtual_machine(): name="vm_name", memory=1024, vcpu=4, - disks=[Disk(type="virtio_disk", slot=0), Disk(type="virtio_disk", slot=1)], + disks=[Disk(disk_type="virtio_disk", slot=0), Disk(disk_type="virtio_disk", slot=1)], power_state="stopped", ) +# pylint: disable=redefined-outer-name @pytest.fixture def virtual_disk(): return VirtualDisk( @@ -56,13 +53,11 @@ class TestIsSlotAvailable: @pytest.mark.parametrize( "disk_slot, expected_result", [ - (1, (False, Disk(type="virtio_disk", slot=1))), + (1, (False, Disk(disk_type="virtio_disk", slot=1))), (5, (True, None)), ], ) - def test_is_slot_available( - self, create_module, disk_slot, expected_result, virtual_machine - ): + def test_is_slot_available(self, create_module, disk_slot, expected_result, virtual_machine): module = create_module( params=dict( cluster_instance=dict( @@ -76,9 +71,7 @@ def test_is_slot_available( ) ) - assert expected_result == virtual_disk_attach.is_slot_available( - module, virtual_machine - ) + assert expected_result == virtual_disk_attach.is_slot_available(module, virtual_machine) class TestCreatePayload: @@ -105,9 +98,7 @@ def test_create_payload(self, create_module, virtual_machine, virtual_disk): ) ) - payload = virtual_disk_attach.create_payload( - module, virtual_machine, virtual_disk - ) + payload = virtual_disk_attach.create_payload(module, virtual_machine, virtual_disk) assert payload == dict( options={"regenerateDiskID": False, "readOnly": True}, @@ -122,9 +113,7 @@ def test_create_payload(self, create_module, virtual_machine, virtual_disk): }, ) - def test_create_payload_min_params( - self, create_module, virtual_machine, virtual_disk - ): + def test_create_payload_min_params(self, create_module, virtual_machine, virtual_disk): module = create_module( params=dict( cluster_instance=dict( @@ -147,9 +136,7 @@ def test_create_payload_min_params( ) ) - payload = virtual_disk_attach.create_payload( - module, virtual_machine, virtual_disk - ) + payload = virtual_disk_attach.create_payload(module, virtual_machine, virtual_disk) assert payload == dict( options={ diff --git a/tests/unit/plugins/modules/test_virtual_disk_info.py b/tests/unit/plugins/modules/test_virtual_disk_info.py index b17716ff..5546bfe3 100644 --- a/tests/unit/plugins/modules/test_virtual_disk_info.py +++ b/tests/unit/plugins/modules/test_virtual_disk_info.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - virtual_disk_info, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import virtual_disk_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_vm.py b/tests/unit/plugins/modules/test_vm.py index 635070ad..328c2673 100644 --- a/tests/unit/plugins/modules/test_vm.py +++ b/tests/unit/plugins/modules/test_vm.py @@ -1,15 +1,14 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import vm -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -18,9 +17,7 @@ class TestEnsureAbsent: - def test_ensure_absent_record_present_power_state_shutdown( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_absent_record_present_power_state_shutdown(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -156,9 +153,7 @@ def test_ensure_absent_record_present_power_state_shutdown( False, ) - def test_ensure_absent_record_present_power_state_not_shutdown( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_absent_record_present_power_state_not_shutdown(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -332,9 +327,7 @@ def test_ensure_absent_record_absent(self, create_module, rest_client): class TestEnsurePresent: - def test_ensure_present_create_record( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_present_create_record(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -505,9 +498,7 @@ def test_ensure_present_create_record( False, ) - def test_ensure_present_update_record_manage_vm_params( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_present_update_record_manage_vm_params(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -609,18 +600,18 @@ def test_ensure_present_update_record_manage_vm_params( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.VM.get_by_name" ).side_effect = [vm_b] - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_vm_params" - ).side_effect = [ + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_vm_params").side_effect = [ (False, False), # first machine_type - no change (True, True), # second memory changes ] - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_disks" - ).return_value = (True, True) - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_nics" - ).return_value = (True, True) + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_disks").return_value = ( + True, + True, + ) + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_nics").return_value = ( + True, + True, + ) mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_boot_order" ).return_value = (False, False) @@ -734,9 +725,7 @@ def test_ensure_present_update_record_manage_vm_params( ) assert expected_result == result - def test_ensure_present_update_record_no_changes( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_present_update_record_no_changes(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -810,26 +799,21 @@ def test_ensure_present_update_record_no_changes( mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.SnapshotSchedule.get_snapshot_schedule" ).return_value = None - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_vm_params" - ).return_value = (False, {}) - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_disks" - ).return_value = False + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_vm_params").return_value = ( + False, + {}, + ) + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_disks").return_value = False mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_boot_order" ).return_value = False - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_nics" - ).return_value = False + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_nics").return_value = False result = vm.ensure_present(module, rest_client) changed = result[0] assert not changed - def test_ensure_present_updated_boot_order( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_present_updated_boot_order(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -955,18 +939,21 @@ def test_ensure_present_updated_boot_order( mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm.SnapshotSchedule.get_snapshot_schedule" ).return_value = None - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_vm_params" - ).return_value = (False, False) - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_disks" - ).return_value = (True, True) + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_vm_params").return_value = ( + False, + False, + ) + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_disks").return_value = ( + True, + True, + ) mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_boot_order" ).return_value = (True, True) - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_nics" - ).return_value = (False, False) + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.modules.vm._set_nics").return_value = ( + False, + False, + ) result = vm.ensure_present(module, rest_client) assert result == ( diff --git a/tests/unit/plugins/modules/test_vm_boot_devices.py b/tests/unit/plugins/modules/test_vm_boot_devices.py index 2a3f48a2..5ccb7f33 100644 --- a/tests/unit/plugins/modules/test_vm_boot_devices.py +++ b/tests/unit/plugins/modules/test_vm_boot_devices.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - vm_boot_devices, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import vm_boot_devices pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -25,9 +22,7 @@ class TestEnsureAbsent: - def test_ensure_absent_no_source_object_present( - self, create_module, rest_client, mocker - ): + def test_ensure_absent_no_source_object_present(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -185,9 +180,7 @@ def test_ensure_absent_no_source_object_present( False, ) - def test_ensure_absent_uuid_not_in_boot_devices( - self, create_module, rest_client, mocker - ): + def test_ensure_absent_uuid_not_in_boot_devices(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -295,9 +288,7 @@ def test_ensure_absent_uuid_not_in_boot_devices( rest_client.update_record.assert_not_called() assert result == (False, [], {"after": [], "before": []}, False) - def test_ensure_absent_update_successful( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_absent_update_successful(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -438,9 +429,7 @@ def test_ensure_absent_update_successful( class TestEnsurePresent: - def test_ensure_present_no_source_object_present( - self, create_module, rest_client, mocker - ): + def test_ensure_present_no_source_object_present(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -548,9 +537,7 @@ def test_ensure_present_no_source_object_present( rest_client.update_record.assert_not_called() assert result == (False, [], {"after": [], "before": []}, False) - def test_ensure_present_item_first( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_present_item_first(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -870,9 +857,7 @@ def test_ensure_present_item_not_first_boot_order_already_present( False, ) - def test_ensure_present_item_not_first_boot_order_updated( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_present_item_not_first_boot_order_updated(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -1028,9 +1013,7 @@ def test_ensure_present_item_not_first_boot_order_updated( class TestEnsureSet: - def test_ensure_set_no_source_object_present( - self, create_module, rest_client, mocker - ): + def test_ensure_set_no_source_object_present(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -1138,9 +1121,7 @@ def test_ensure_set_no_source_object_present( rest_client.update_record.assert_not_called() assert result == (False, [], {"after": [], "before": []}, False) - def test_ensure_set_source_object_present( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_set_source_object_present(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( diff --git a/tests/unit/plugins/modules/test_vm_clone.py b/tests/unit/plugins/modules/test_vm_clone.py index c5bfebb0..a5619460 100644 --- a/tests/unit/plugins/modules/test_vm_clone.py +++ b/tests/unit/plugins/modules/test_vm_clone.py @@ -1,17 +1,16 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import vm_clone from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import VM -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.modules import vm_clone pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -22,9 +21,7 @@ class TestMain: def test_minimal_set_of_params(self, run_main_info): params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), vm_name=dict( type="str", required=True, @@ -167,9 +164,7 @@ def test_run_when_VM_cloned(self, rest_client, create_module, mocker): "Virtual machine - XLAB-test-vm - cloning complete to - XLAB-test-vm-clone.", ) - def test_run_when_VM_cloned_with_tag_and_cloud_init( - self, rest_client, create_module, mocker - ): + def test_run_when_VM_cloned_with_tag_and_cloud_init(self, rest_client, create_module, mocker): module = create_module( params=dict( cluster_instance=dict( diff --git a/tests/unit/plugins/modules/test_vm_disk.py b/tests/unit/plugins/modules/test_vm_disk.py index c68b6ae4..ce5c7be1 100644 --- a/tests/unit/plugins/modules/test_vm_disk.py +++ b/tests/unit/plugins/modules/test_vm_disk.py @@ -3,18 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import vm_disk -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -103,9 +102,7 @@ def test_ensure_absent_no_disk_present(self, create_module, rest_client, mocker) False, ) - def test_ensure_absent_delete_record( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_absent_delete_record(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -218,9 +215,7 @@ def test_ensure_absent_delete_record( False, ) - def test_ensure_absent_cdrom_name_in_desired_disk_and_query( - self, create_module, rest_client, task_wait, mocker - ): + def test_ensure_absent_cdrom_name_in_desired_disk_and_query(self, create_module, rest_client, task_wait, mocker): module = create_module( params=dict( cluster_instance=dict( diff --git a/tests/unit/plugins/modules/test_vm_export.py b/tests/unit/plugins/modules/test_vm_export.py index dbeaf8d0..03a293d3 100644 --- a/tests/unit/plugins/modules/test_vm_export.py +++ b/tests/unit/plugins/modules/test_vm_export.py @@ -1,16 +1,15 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import vm_export from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import vm_export pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -21,9 +20,7 @@ class TestMain: def test_minimal_set_of_params(self, run_main_info): params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), vm_name=dict( type="str", required=True, diff --git a/tests/unit/plugins/modules/test_vm_import.py b/tests/unit/plugins/modules/test_vm_import.py index 2431bdaf..3751bb8c 100644 --- a/tests/unit/plugins/modules/test_vm_import.py +++ b/tests/unit/plugins/modules/test_vm_import.py @@ -1,16 +1,15 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import vm_import from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import vm_import pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -21,9 +20,7 @@ class TestMain: def test_minimal_set_of_params(self, run_main_info): params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), vm_name=dict( type="str", required=True, @@ -145,9 +142,7 @@ def test_run_when_imported_VM_not_exists(self, create_module, rest_client): "Virtual machine - XLAB-test-vm - import complete.", ) - def test_run_when_imported_VM_already_exists( - self, create_module, rest_client, mocker - ): + def test_run_when_imported_VM_already_exists(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -203,9 +198,7 @@ def test_run_when_imported_VM_already_exists( f"Virtual machine - {module.params['vm_name']} - already exists.", ) - def test_run_when_imported_VM_not_exists_but_import_failed( - self, create_module, rest_client - ): + def test_run_when_imported_VM_not_exists_but_import_failed(self, create_module, rest_client): module = create_module( params=dict( cluster_instance=dict( diff --git a/tests/unit/plugins/modules/test_vm_info.py b/tests/unit/plugins/modules/test_vm_info.py index 91662a62..6ffb7158 100644 --- a/tests/unit/plugins/modules/test_vm_info.py +++ b/tests/unit/plugins/modules/test_vm_info.py @@ -1,15 +1,14 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import vm_info -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_vm_nic.py b/tests/unit/plugins/modules/test_vm_nic.py index 5d41786d..ba9f48b7 100644 --- a/tests/unit/plugins/modules/test_vm_nic.py +++ b/tests/unit/plugins/modules/test_vm_nic.py @@ -3,20 +3,18 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import vm_nic -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import VM +from ansible_collections.scale_computing.hypercore.plugins.modules import vm_nic pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -120,9 +118,7 @@ def test_ensure_absent_when_no_change(self, create_module, rest_client, mocker): # rest_client.list_records.return_value = [self._get_empty_test_vm()] vm_before = VM.from_hypercore(self._get_empty_test_vm(), rest_client) # rest_client.create_record.return_value = {"taskTag": "1234"} - results = vm_nic.ensure_absent( - module=module, rest_client=rest_client, vm_before=vm_before - ) + results = vm_nic.ensure_absent(module=module, rest_client=rest_client, vm_before=vm_before) assert results == (False, [], {"before": [], "after": []}) def test_ensure_absent_when_change(self, create_module, rest_client, mocker): @@ -157,9 +153,7 @@ def test_ensure_absent_when_change(self, create_module, rest_client, mocker): vm_before = VM.from_hypercore(self._get_test_vm(), rest_client) rest_client.get_record.return_value = {"state": "COMPLETED"} # rest_client.create_record.return_value = {"taskTag": "1234"} - results = vm_nic.ensure_absent( - module=module, rest_client=rest_client, vm_before=vm_before - ) + results = vm_nic.ensure_absent(module=module, rest_client=rest_client, vm_before=vm_before) assert results == ( True, [None, None], @@ -190,9 +184,7 @@ def test_ensure_absent_when_change(self, create_module, rest_client, mocker): class TestMain: def test_minimal_set_of_params(self, run_main_with_reboot, mocker): params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), state="present", vm_name=dict( type="str", diff --git a/tests/unit/plugins/modules/test_vm_node_affinity.py b/tests/unit/plugins/modules/test_vm_node_affinity.py index 85d6a2cb..92829c74 100644 --- a/tests/unit/plugins/modules/test_vm_node_affinity.py +++ b/tests/unit/plugins/modules/test_vm_node_affinity.py @@ -1,20 +1,17 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - vm_node_affinity, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import VM -from ansible_collections.scale_computing.hypercore.plugins.module_utils.node import Node from ansible_collections.scale_computing.hypercore.plugins.module_utils import errors -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.node import Node +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import VM +from ansible_collections.scale_computing.hypercore.plugins.modules import vm_node_affinity pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -65,9 +62,7 @@ def test_get_node_uuid(self, create_module, rest_client, mocker): ), ] - preferred_node_uuid = vm_node_affinity.get_node_uuid( - module, "preferred_node", rest_client - ) + preferred_node_uuid = vm_node_affinity.get_node_uuid(module, "preferred_node", rest_client) assert preferred_node_uuid == "preferred_node_uuid" @@ -96,9 +91,7 @@ def test_get_node_uuid_empty_string(self, create_module, rest_client, mocker): ), ) - preferred_node_uuid = vm_node_affinity.get_node_uuid( - module, "preferred_node", rest_client - ) + preferred_node_uuid = vm_node_affinity.get_node_uuid(module, "preferred_node", rest_client) assert preferred_node_uuid == "" @@ -122,12 +115,8 @@ def test_get_node_uuid_none(self, create_module, rest_client, mocker): ), ) - preferred_node_uuid = vm_node_affinity.get_node_uuid( - module, "preferred_node", rest_client - ) - backup_node_uuid = vm_node_affinity.get_node_uuid( - module, "backup_node", rest_client - ) + preferred_node_uuid = vm_node_affinity.get_node_uuid(module, "preferred_node", rest_client) + backup_node_uuid = vm_node_affinity.get_node_uuid(module, "backup_node", rest_client) assert preferred_node_uuid is None assert backup_node_uuid is None @@ -202,9 +191,7 @@ def test_set_parameters_for_payload(self, create_module, rest_client, mocker): assert preferred_node_uuid == "preferred_node_uuid" assert backup_node_uuid == "backup_node_uuid" - def test_set_parameters_for_payload_nodes_not_provided( - self, create_module, rest_client, mocker - ): + def test_set_parameters_for_payload_nodes_not_provided(self, create_module, rest_client, mocker): module = create_module( params=dict( cluster_instance=dict( @@ -257,9 +244,7 @@ def test_set_parameters_for_payload_nodes_not_provided( mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.modules.vm_node_affinity.get_node_uuid" ).side_effect = [None, None] - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.modules.vm_node_affinity.Node.get_node" - ) + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.modules.vm_node_affinity.Node.get_node") ( strict_affinity, @@ -300,9 +285,7 @@ def test_run(self, create_module, rest_client, mocker): mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.modules.vm_node_affinity.set_parameters_for_payload" ).return_value = (True, "preferred_node_uuid", "backup_node_uuid") - mocker.patch( - "ansible_collections.scale_computing.hypercore.plugins.modules.vm_node_affinity.TaskTag.wait_task" - ) + mocker.patch("ansible_collections.scale_computing.hypercore.plugins.modules.vm_node_affinity.TaskTag.wait_task") mocker.patch( "ansible_collections.scale_computing.hypercore.plugins.modules.vm_node_affinity.VM.get_by_name" ).return_value = VM( @@ -405,10 +388,7 @@ def test_run_invalid_parameters(self, create_module, rest_client, mocker): with pytest.raises(errors.VMInvalidParams) as exc: vm_node_affinity.run(module, rest_client) - assert ( - "Invalid set of parameters - strict affinity set to true and nodes not provided." - in str(exc.value) - ) + assert "Invalid set of parameters - strict affinity set to true and nodes not provided." in str(exc.value) def test_run_no_change(self, create_module, rest_client, mocker): module = create_module( diff --git a/tests/unit/plugins/modules/test_vm_params.py b/tests/unit/plugins/modules/test_vm_params.py index f1606df6..9fff8945 100644 --- a/tests/unit/plugins/modules/test_vm_params.py +++ b/tests/unit/plugins/modules/test_vm_params.py @@ -1,15 +1,14 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.modules import vm_params -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, diff --git a/tests/unit/plugins/modules/test_vm_replication.py b/tests/unit/plugins/modules/test_vm_replication.py index 458fe377..677c5163 100644 --- a/tests/unit/plugins/modules/test_vm_replication.py +++ b/tests/unit/plugins/modules/test_vm_replication.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - vm_replication, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import vm_replication pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -25,9 +22,7 @@ class TestEnabledOrReenabled: - def test_ensure_enabled_or_reenabled_when_replication_not_exist( - self, rest_client, create_module, mocker - ): + def test_ensure_enabled_or_reenabled_when_replication_not_exist(self, rest_client, create_module, mocker): vm_dict = { "uuid": "7542f2gg-5f9a-51ff-8a91-8ceahgf47ghg", "nodeUUID": "", @@ -105,9 +100,7 @@ def test_ensure_enabled_or_reenabled_when_replication_not_exist( results = vm_replication.ensure_enabled_or_reenabled(module, rest_client) assert results == (True, after, {"before": None, "after": after}) - def test_ensure_enabled_or_reenabled_when_replication_exists_change_state( - self, rest_client, create_module, mocker - ): + def test_ensure_enabled_or_reenabled_when_replication_exists_change_state(self, rest_client, create_module, mocker): vm_dict = { "uuid": "7542f2gg-5f9a-51ff-8a91-8ceahgf47ghg", "nodeUUID": "", @@ -191,9 +184,7 @@ def test_ensure_enabled_or_reenabled_when_replication_exists_change_state( results = vm_replication.ensure_enabled_or_reenabled(module, rest_client) assert results == (True, after, {"before": before, "after": after}) - def test_ensure_enabled_or_reenabled_when_replication_exists_no_changes( - self, rest_client, create_module, mocker - ): + def test_ensure_enabled_or_reenabled_when_replication_exists_no_changes(self, rest_client, create_module, mocker): vm_dict = { "uuid": "7542f2gg-5f9a-51ff-8a91-8ceahgf47ghg", "nodeUUID": "", @@ -261,9 +252,7 @@ def test_ensure_enabled_or_reenabled_when_replication_exists_no_changes( class TestDisabled: - def test_ensure_disabled_replication_not_exists( - self, rest_client, create_module, mocker - ): + def test_ensure_disabled_replication_not_exists(self, rest_client, create_module, mocker): vm_dict = { "uuid": "7542f2gg-5f9a-51ff-8a91-8ceahgf47ghg", "nodeUUID": "", @@ -310,9 +299,7 @@ def test_ensure_disabled_replication_not_exists( results = vm_replication.ensure_disabled(module, rest_client) assert results == (False, None, {"before": None, "after": None}) - def test_ensure_disabled_replication_exists_state_not_changed( - self, rest_client, create_module, mocker - ): + def test_ensure_disabled_replication_exists_state_not_changed(self, rest_client, create_module, mocker): vm_dict = { "uuid": "7542f2gg-5f9a-51ff-8a91-8ceahgf47ghg", "nodeUUID": "", @@ -359,9 +346,7 @@ def test_ensure_disabled_replication_exists_state_not_changed( results = vm_replication.ensure_disabled(module, rest_client) assert results == (False, None, {"before": None, "after": None}) - def test_ensure_disabled_replication_exists_state_changed( - self, rest_client, create_module, mocker - ): + def test_ensure_disabled_replication_exists_state_changed(self, rest_client, create_module, mocker): vm_dict = { "uuid": "7542f2gg-5f9a-51ff-8a91-8ceahgf47ghg", "nodeUUID": "", @@ -449,9 +434,7 @@ def test_ensure_disabled_replication_exists_state_changed( class TestMain: def test_minimal_set_of_params(self, run_main): params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), state="enabled", vm_name=dict( type="str", diff --git a/tests/unit/plugins/modules/test_vm_replication_info.py b/tests/unit/plugins/modules/test_vm_replication_info.py index 998546fe..3473e21e 100644 --- a/tests/unit/plugins/modules/test_vm_replication_info.py +++ b/tests/unit/plugins/modules/test_vm_replication_info.py @@ -3,20 +3,17 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - vm_replication_info, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.modules import vm_replication_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -195,9 +192,7 @@ def test_run_without_vm_name(self, create_module, rest_client, mocker): class TestMain: def test_minimal_set_of_params(self, run_main_info): params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), vm_name=dict( type="str", required=False, diff --git a/tests/unit/plugins/modules/test_vm_snapshot.py b/tests/unit/plugins/modules/test_vm_snapshot.py index 92146e13..04a6a534 100644 --- a/tests/unit/plugins/modules/test_vm_snapshot.py +++ b/tests/unit/plugins/modules/test_vm_snapshot.py @@ -1,22 +1,17 @@ -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import vm_snapshot -from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm_snapshot import ( - VMSnapshot, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.errors import ScaleComputingError +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm import VM -from ansible_collections.scale_computing.hypercore.plugins.module_utils.errors import ( - ScaleComputingError, -) -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm_snapshot import VMSnapshot +from ansible_collections.scale_computing.hypercore.plugins.modules import vm_snapshot pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -110,9 +105,7 @@ def test_parameters_snapshot( expected_result, ) -> None: params = dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), vm_name=vm_name, label=label, retain_for=retain_for, @@ -168,9 +161,7 @@ def test_run_vm_snapshot( ) -> None: module = create_module( params=dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), vm_name="this-VM", label="this-label", retain_for=30, @@ -263,9 +254,7 @@ def test_ensure_present_vm_snapshot( # Mock module module = create_module( params=dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), vm_name="this-VM", label=label, retain_for=None, @@ -291,9 +280,7 @@ def test_ensure_present_vm_snapshot( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm_snapshot.VMSnapshot.get_snapshots_by_query" ).return_value = after - result = vm_snapshot.ensure_present( - module, rest_client, vm_object, snapshot_list - ) + result = vm_snapshot.ensure_present(module, rest_client, vm_object, snapshot_list) print(result) print("\n") @@ -323,9 +310,7 @@ class TestEnsureAbsent: True, None, dict( - before=dict( - vm_name="this-vm", label="this-label", snapshot_uuid="123" - ), + before=dict(vm_name="this-vm", label="this-label", snapshot_uuid="123"), after=None, ), ), @@ -345,9 +330,7 @@ def test_ensure_absent_vm_snapshot( # Mock module module = create_module( params=dict( - cluster_instance=dict( - host="https://my.host.name", username="user", password="pass" - ), + cluster_instance=dict(host="https://my.host.name", username="user", password="pass"), vm_name="this-VM", label=label, retain_for=None, @@ -373,9 +356,7 @@ def test_ensure_absent_vm_snapshot( "ansible_collections.scale_computing.hypercore.plugins.module_utils.vm_snapshot.VMSnapshot.get_snapshots_by_query" ).return_value = after - result = vm_snapshot.ensure_absent( - module, rest_client, vm_object, snapshot_list - ) + result = vm_snapshot.ensure_absent(module, rest_client, vm_object, snapshot_list) print(result, expected_result) assert isinstance(result, tuple) assert result == expected_result diff --git a/tests/unit/plugins/modules/test_vm_snapshot_attach_disk.py b/tests/unit/plugins/modules/test_vm_snapshot_attach_disk.py index fb779c94..ba406ed4 100644 --- a/tests/unit/plugins/modules/test_vm_snapshot_attach_disk.py +++ b/tests/unit/plugins/modules/test_vm_snapshot_attach_disk.py @@ -3,7 +3,9 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type @@ -11,19 +13,10 @@ from unittest import mock import pytest - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm_snapshot import ( - VM, - VMSnapshot, -) - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - vm_snapshot_attach_disk, -) - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm_snapshot import VM +from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm_snapshot import VMSnapshot +from ansible_collections.scale_computing.hypercore.plugins.modules import vm_snapshot_attach_disk pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -84,7 +77,7 @@ def setup_method(self): ], timestamp=123, label="snapshot", - type="USER", + snapshot_type="USER", automated_trigger_timestamp=111, local_retain_until_timestamp=222, remote_retain_until_timestamp=333, @@ -223,17 +216,12 @@ def test_attach_disk_is_change( check_mode=False, ) - changed, record, diff, vm_rebooted = vm_snapshot_attach_disk.attach_disk( - module, rest_client - ) + changed, record, diff, vm_rebooted = vm_snapshot_attach_disk.attach_disk(module, rest_client) if destination_vm_disk_info is None: rest_client.create_record.assert_any_call(**called_with_dict) else: - assert ( - mock.call(**called_with_dict) - not in rest_client.create_record.mock_calls - ) + assert mock.call(**called_with_dict) not in rest_client.create_record.mock_calls assert changed == expected_return[0] assert record == expected_return[1] diff --git a/tests/unit/plugins/modules/test_vm_snapshot_info.py b/tests/unit/plugins/modules/test_vm_snapshot_info.py index b70fe909..670c4bd2 100644 --- a/tests/unit/plugins/modules/test_vm_snapshot_info.py +++ b/tests/unit/plugins/modules/test_vm_snapshot_info.py @@ -3,25 +3,18 @@ # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -from __future__ import absolute_import, division, print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function __metaclass__ = type import sys import pytest - -from ansible_collections.scale_computing.hypercore.plugins.modules import ( - vm_snapshot_info, -) - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm_snapshot import ( - VMSnapshot, -) - -from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import ( - MIN_PYTHON_VERSION, -) +from ansible_collections.scale_computing.hypercore.plugins.module_utils.utils import MIN_PYTHON_VERSION +from ansible_collections.scale_computing.hypercore.plugins.module_utils.vm_snapshot import VMSnapshot +from ansible_collections.scale_computing.hypercore.plugins.modules import vm_snapshot_info pytestmark = pytest.mark.skipif( sys.version_info < MIN_PYTHON_VERSION, @@ -32,9 +25,7 @@ class TestRun: def setup_method(self): self.params = dict( - cluster_instance=dict( - host="https://0.0.0.0", username="admin", password="admin" - ), + cluster_instance=dict(host="https://0.0.0.0", username="admin", password="admin"), vm_name=None, serial=None, label=None, @@ -117,47 +108,28 @@ def test_run_present(self, create_module, rest_client): replication=True, ) - result = vm_snapshot_info.run(module, rest_client)[ - 0 - ] # this is safe, since these tests only have one snapshot + result = vm_snapshot_info.run(module, rest_client)[0] # this is safe, since these tests only have one snapshot result_sorted_block_devices = [ - dict(sorted(bd.items(), key=lambda item: item[0])) - for bd in result["vm"]["disks"] + dict(sorted(bd.items(), key=lambda item: item[0])) for bd in result["vm"]["disks"] ] expected_sorted_block_devices = [ - dict(sorted(bd.items(), key=lambda item: item[0])) - for bd in expected["vm"]["disks"] + dict(sorted(bd.items(), key=lambda item: item[0])) for bd in expected["vm"]["disks"] ] assert result["snapshot_uuid"] == expected["snapshot_uuid"] assert result["vm"]["name"] == expected["vm"]["name"] assert result["vm"]["uuid"] == expected["vm"]["uuid"] - assert ( - result["vm"]["snapshot_serial_number"] - == expected["vm"]["snapshot_serial_number"] - ) + assert result["vm"]["snapshot_serial_number"] == expected["vm"]["snapshot_serial_number"] assert result_sorted_block_devices == expected_sorted_block_devices assert result["device_snapshots"] == expected["device_snapshots"] assert result["timestamp"] == expected["timestamp"] assert result["label"] == expected["label"] assert result["type"] == expected["type"] - assert ( - result["automated_trigger_timestamp"] - == expected["automated_trigger_timestamp"] - ) - assert ( - result["local_retain_until_timestamp"] - == expected["local_retain_until_timestamp"] - ) - assert ( - result["remote_retain_until_timestamp"] - == expected["remote_retain_until_timestamp"] - ) - assert ( - result["block_count_diff_from_serial_number"] - == expected["block_count_diff_from_serial_number"] - ) + assert result["automated_trigger_timestamp"] == expected["automated_trigger_timestamp"] + assert result["local_retain_until_timestamp"] == expected["local_retain_until_timestamp"] + assert result["remote_retain_until_timestamp"] == expected["remote_retain_until_timestamp"] + assert result["block_count_diff_from_serial_number"] == expected["block_count_diff_from_serial_number"] assert result["replication"] == expected["replication"] def test_run_record_absent(self, create_module, rest_client): diff --git a/tox.ini b/tox.ini new file mode 100644 index 00000000..b373db82 --- /dev/null +++ b/tox.ini @@ -0,0 +1,279 @@ +# It would be nice to merge this into pyproject.toml, unfortunately as of 4.23.2 they don't support generative environments when using TOML + +[tox] +skipsdist = True +skip_missing_interpreters = True +envlist = + ansible{2.15}-py{39,310,311}-{with_constraints,without_constraints} + ansible{2.16,2.17}-py{310,311,312}-{with_constraints,without_constraints} + ansible{2.18}-py{311,312,313}-{with_constraints,without_constraints} + +[common] +collection_name = scale_computing.hypercore +collection_path = scale_computing/hypercore + +format_dirs = {toxinidir}/plugins {toxinidir}/tests +lint_dirs = {toxinidir}/plugins {toxinidir}/tests + +ansible_desc = + ansible2.15: Ansible-core 2.15 + ansible2.16: Ansible-core 2.16 + ansible2.17: Ansible-core 2.17 + ansible2.18: Ansible-core 2.18 +const_desc = + with_constraints: (With boto3/botocore constraints) + +ansible_home = {envtmpdir}/ansible_home +ansible_collections_path = {[common]ansible_home}/collections +full_collection_path = {[common]ansible_home}/collections/ansible_collections/{[common]collection_path} + +[testenv] +description = Run the unit tests {[common]ansible_desc}/{base_python} {[common]const_desc} +set_env = + ANSIBLE_HOME={[common]ansible_home} + ANSIBLE_COLLECTIONS_PATH={[common]ansible_collections_path} +# ansible_pytest_collections is more aggressive than pytest_ansible when injecting collections into the import path +# not needed if unit tests are under tests/unit/plugins rather than directly under tests/unit +# ANSIBLE_CONTROLLER_MIN_PYTHON_VERSION=3.11 +# PYTEST_PLUGINS=ansible_test._util.target.pytest.plugins.ansible_pytest_collections +labels = unit +deps = + pytest + mock + pytest-mock + pytest-cov + pytest-ansible + pytest-xdist + -rtest-requirements.txt + -rtests/unit/requirements.txt + ansible2.15: ansible-core>2.15,<2.16 + ansible2.16: ansible-core>2.16,<2.17 + ansible2.17: ansible-core>2.17,<2.18 + ansible2.18: ansible-core>2.18,<2.19 + with_constraints: -rtests/unit/constraints.txt +allowlist_externals = rsync +change_dir = {[common]full_collection_path} +commands_pre = + rsync --delete --exclude=.tox -qraugpo {toxinidir}/ {[common]full_collection_path}/ + # ansible-galaxy collection install git+https://github.com/ScaleComputing/HyperCoreAnsibleCollection.git +commands = + pytest \ + --cov-report html \ + ; --cov plugins/callback \ + --cov plugins/inventory \ + ; --cov plugins/lookup \ + --cov plugins/module_utils \ + --cov plugins/modules \ + ; --cov plugins/plugin_utils \ + --cov plugins \ + --ansible-host-pattern localhost \ + {posargs:tests/unit/} + +[testenv:clean] +description = Remove test results and caches +allowlist_externals = rm +deps = coverage +skip_install = true +change_dir = {toxinidir} +commands_pre = +commands = + coverage erase + rm -rf tests/output/ htmlcov/ .mypy_cache/ complexity/ .ruff_cache/ + +[testenv:complexity-report] +labels = future-lint +description = Generate a HTML complexity report in the complexity directory +deps = + flake8-pyproject + flake8-html +change_dir = {toxinidir} +commands_pre = +commands = + -flake8 \ + --select C90 \ + --max-complexity 10 \ + --format=html \ + --htmldir={posargs:complexity} \ + {posargs:{[common]lint_dirs}} + +[testenv:ansible-lint] +labels = lint +description = Run ansible-lint +deps = + ansible-lint >= 25.1.2 + jmespath +change_dir = {toxinidir} +commands_pre = +commands = + ansible-lint \ + --skip-list=name[missing],yaml[line-length],args[module],run-once[task],ignore-errors,sanity[cannot-ignore],run-once[play] \ + {posargs:{[common]lint_dirs}} + +[testenv:black] +labels = format +description = Apply "black" formatting +depends = + flynt, isort +deps = + black >=25.1.0, <26.0 +change_dir = {toxinidir} +commands_pre = +commands = + black {posargs:{[common]format_dirs}} + +[testenv:black-lint] +labels = lint +description = Lint against "black" formatting standards +deps = + {[testenv:black]deps} +change_dir = {toxinidir} +commands_pre = +commands = + black --check --diff {posargs:{[common]format_dirs}} + +[testenv:isort] +labels = format +description = Sort imports +deps = + isort +change_dir = {toxinidir} +commands_pre = +commands = + isort {posargs:{[common]format_dirs}} + +[testenv:isort-lint] +labels = lint +description = Lint for import sorting +deps = + {[testenv:isort]deps} +change_dir = {toxinidir} +commands_pre = +commands = + isort --check-only --diff {posargs:{[common]format_dirs}} + +[testenv:flynt] +labels = format +description = Apply flint (f-string) formatting +deps = + flynt +change_dir = {toxinidir} +commands_pre = +commands = + flynt {posargs:{[common]format_dirs}} + +[testenv:flynt-lint] +labels = lint +description = Run flint (f-string) linting +deps = + flynt +change_dir = {toxinidir} +commands_pre = +commands = + flynt --dry-run --fail-on-change {posargs:{[common]format_dirs}} + +[testenv:flake8-lint] +labels = lint +description = Run FLAKE8 linting +deps = + flake8 + flake8-pyproject +change_dir = {toxinidir} +commands_pre = +commands = + flake8 {posargs:{[common]format_dirs}} + +[testenv:pylint-lint] +labels = lint +description = Run pylint tests that are disabled by the default Ansible sanity tests +deps = + pylint +change_dir = {toxinidir} +commands_pre = +commands = + pylint \ + --disable R,C,W,E \ + --enable pointless-statement \ + --enable consider-using-dict-items \ + --enable assignment-from-no-return \ + --enable no-else-continue \ + --enable no-else-break \ + --enable simplifiable-if-statement \ + --enable pointless-string-statement \ + --enable redefined-outer-name \ + --enable redefined-builtin \ + --enable unused-import \ + {posargs:{[common]lint_dirs}} + +[testenv:ruff] +description = lint source code +labels = format-future +deps = + ruff +change_dir = {toxinidir} +commands_pre = +commands = + ruff check --fix {posargs:{[common]lint_dirs}} + ruff format {posargs:{[common]lint_dirs}} + +[testenv:ruff-lint] +description = lint source code +labels = lint-future +deps = + ruff +change_dir = {toxinidir} +commands_pre = +commands = + ruff check --diff --unsafe-fixes {posargs:{[common]lint_dirs}} + ruff check {posargs:{[common]lint_dirs}} + +[testenv:ansible-lint-future] +labels = future-lint +description = Run ansible-lint +deps = + ansible-lint + jmespath + git+https://github.com/ansible/ansible.git@devel + shellcheck-py +commands = + ansible-lint \ + {posargs:{[common]lint_dirs}} + +[testenv:ansible-sanity] +labels = future-lint +description = Run latest (devel) Ansible sanity tests +deps = + git+https://github.com/ansible/ansible.git@devel + shellcheck-py +commands = + ansible-test sanity + +[testenv:mypy-lint] +allowlist_externals = rsync,ln +labels = future-lint +description = Run mypi type tests +set_env = + ANSIBLE_HOME={[common]ansible_home} + ANSIBLE_COLLECTIONS_PATH={[common]ansible_collections_path} + MYPYPATH={[common]ansible_home} +deps = + mypy + # ansible-core + git+https://github.com/ansible/ansible.git@devel + botocore + boto3 + placebo + typing_extensions +commands_pre = + rsync --delete --exclude=.tox -qraugpo {toxinidir}/ {[common]full_collection_path}/ +; ansible-galaxy collection install git+https://github.com/ansible-collections/community.aws.git + ln -s {env_site_packages_dir}/ansible {[common]ansible_collections_path}/ansible + ln -s {[common]ansible_home}/collections/ansible_collections {[common]ansible_home}/ansible_collections +commands = + # TODO: passing directories doesn't work well, it's better to pass the package + # we might want to consider manipulating posargs/directories into the package names + mypy \ + --check-untyped-defs \ + --namespace-packages --explicit-package-bases \ + --follow-imports silent \ + -p ansible_collections.scale_computing.hypercore.plugins.module_utils + ; -p ansible_collections.scale_computing.hypercore.plugins.plugin_utils \