1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-02-04 07:51:50 +00:00
community.general/tests/unit/plugins/modules/hpe_test_utils.py
patchback[bot] 16f1d07509
[PR #11043/3478863e backport][stable-12] Address issues reported by ruff check (#11047)
Address issues reported by ruff check (#11043)

* Resolve E713 and E714 (not in/is tests).

* Address UP018 (unnecessary str call).

* UP045 requires Python 3.10+.

* Address UP007 (X | Y for type annotations).

* Address UP035 (import Callable from collections.abc).

* Address UP006 (t.Dict -> dict).

* Address UP009 (UTF-8 encoding comment).

* Address UP034 (extraneous parantheses).

* Address SIM910 (dict.get() with None default).

* Address F401 (unused import).

* Address UP020 (use builtin open).

* Address B009 and B010 (getattr/setattr with constant name).

* Address SIM300 (Yoda conditions).

* UP029 isn't in use anyway.

* Address FLY002 (static join).

* Address B034 (re.sub positional args).

* Address B020 (loop variable overrides input).

* Address B017 (assert raise Exception).

* Address SIM211 (if expression with false/true).

* Address SIM113 (enumerate for loop).

* Address UP036 (sys.version_info checks).

* Remove unnecessary UP039.

* Address SIM201 (not ==).

* Address SIM212 (if expr with twisted arms).

* Add changelog fragment.

* Reformat.

(cherry picked from commit 3478863ef0)

Co-authored-by: Felix Fontein <felix@fontein.de>
2025-11-08 09:49:52 +01:00

203 lines
7.5 KiB
Python

#
# Copyright (2016-2017) Hewlett Packard Enterprise Development LP
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
import pytest
import re
import yaml
from unittest.mock import Mock, patch
from .oneview_module_loader import ONEVIEW_MODULE_UTILS_PATH
from hpOneView.oneview_client import OneViewClient
class OneViewBaseTest:
@pytest.fixture(autouse=True)
def setUp(self, mock_ansible_module, mock_ov_client, request):
marker = request.node.get_marker("resource")
self.resource = getattr(mock_ov_client, f"{marker.args}")
self.mock_ov_client = mock_ov_client
self.mock_ansible_module = mock_ansible_module
@pytest.fixture
def testing_module(self):
resource_name = type(self).__name__.replace("Test", "")
resource_module_path_name = resource_name.replace("Module", "")
resource_module_path_name = re.findall("[A-Z][^A-Z]*", resource_module_path_name)
resource_module_path_name = f"oneview_{str.join('_', resource_module_path_name).lower()}"
ansible_collections = __import__("ansible_collections")
oneview_module = ansible_collections.community.general.plugins.modules
resource_module = getattr(oneview_module, resource_module_path_name)
self.testing_class = getattr(resource_module, resource_name)
testing_module = self.testing_class.__module__.split(".")[-1]
testing_module = getattr(oneview_module, testing_module)
try:
# Load scenarios from module examples (Also checks if it is a valid yaml)
EXAMPLES = yaml.safe_load(testing_module.EXAMPLES)
except yaml.scanner.ScannerError:
message = f"Something went wrong while parsing yaml from {self.testing_class.__module__}.EXAMPLES"
raise Exception(message)
return testing_module
def test_main_function_should_call_run_method(self, testing_module, mock_ansible_module):
mock_ansible_module.params = {"config": "config.json"}
main_func = testing_module.main
with patch.object(self.testing_class, "run") as mock_run:
main_func()
mock_run.assert_called_once()
class FactsParamsTest(OneViewBaseTest):
def test_should_get_all_using_filters(self, testing_module):
self.resource.get_all.return_value = []
params_get_all_with_filters = dict(
config="config.json",
name=None,
params={
"start": 1,
"count": 3,
"sort": "name:descending",
"filter": "purpose=General",
"query": "imported eq true",
},
)
self.mock_ansible_module.params = params_get_all_with_filters
self.testing_class().run()
self.resource.get_all.assert_called_once_with(
start=1, count=3, sort="name:descending", filter="purpose=General", query="imported eq true"
)
def test_should_get_all_without_params(self, testing_module):
self.resource.get_all.return_value = []
params_get_all_with_filters = dict(config="config.json", name=None)
self.mock_ansible_module.params = params_get_all_with_filters
self.testing_class().run()
self.resource.get_all.assert_called_once_with()
class OneViewBaseTestCase:
mock_ov_client_from_json_file = None
testing_class = None
mock_ansible_module = None
mock_ov_client = None
testing_module = None
EXAMPLES = None
def configure_mocks(self, test_case, testing_class):
"""
Preload mocked OneViewClient instance and AnsibleModule
Args:
test_case (object): class instance (self) that are inheriting from OneViewBaseTestCase
testing_class (object): class being tested
"""
self.testing_class = testing_class
# Define OneView Client Mock (FILE)
patcher_json_file = patch.object(OneViewClient, "from_json_file")
test_case.addCleanup(patcher_json_file.stop)
self.mock_ov_client_from_json_file = patcher_json_file.start()
# Define OneView Client Mock
self.mock_ov_client = self.mock_ov_client_from_json_file.return_value
# Define Ansible Module Mock
patcher_ansible = patch(f"{ONEVIEW_MODULE_UTILS_PATH}.AnsibleModule")
test_case.addCleanup(patcher_ansible.stop)
mock_ansible_module = patcher_ansible.start()
self.mock_ansible_module = Mock()
mock_ansible_module.return_value = self.mock_ansible_module
self.__set_module_examples()
def test_main_function_should_call_run_method(self):
self.mock_ansible_module.params = {"config": "config.json"}
main_func = self.testing_module.main
with patch.object(self.testing_class, "run") as mock_run:
main_func()
mock_run.assert_called_once()
def __set_module_examples(self):
# Load scenarios from module examples (Also checks if it is a valid yaml)
ansible_collections = __import__("ansible_collections")
testing_module = self.testing_class.__module__.split(".")[-1]
self.testing_module = getattr(ansible_collections.community.general.plugins.modules, testing_module)
try:
# Load scenarios from module examples (Also checks if it is a valid yaml)
self.EXAMPLES = yaml.safe_load(self.testing_module.EXAMPLES)
except yaml.scanner.ScannerError:
message = f"Something went wrong while parsing yaml from {self.testing_class.__module__}.EXAMPLES"
raise Exception(message)
class FactsParamsTestCase(OneViewBaseTestCase):
"""
FactsParamsTestCase has common test for classes that support pass additional
parameters when retrieving all resources.
"""
def configure_client_mock(self, resorce_client):
"""
Args:
resorce_client: Resource client that is being called
"""
self.resource_client = resorce_client
def __validations(self):
if not self.testing_class:
raise Exception("Mocks are not configured, you must call 'configure_mocks' before running this test.")
if not self.resource_client:
raise Exception(
"Mock for the client not configured, you must call 'configure_client_mock' before running this test."
)
def test_should_get_all_using_filters(self):
self.__validations()
self.resource_client.get_all.return_value = []
params_get_all_with_filters = dict(
config="config.json",
name=None,
params={
"start": 1,
"count": 3,
"sort": "name:descending",
"filter": "purpose=General",
"query": "imported eq true",
},
)
self.mock_ansible_module.params = params_get_all_with_filters
self.testing_class().run()
self.resource_client.get_all.assert_called_once_with(
start=1, count=3, sort="name:descending", filter="purpose=General", query="imported eq true"
)
def test_should_get_all_without_params(self):
self.__validations()
self.resource_client.get_all.return_value = []
params_get_all_with_filters = dict(config="config.json", name=None)
self.mock_ansible_module.params = params_get_all_with_filters
self.testing_class().run()
self.resource_client.get_all.assert_called_once_with()