1
0
mirror of https://github.com/ansible-collections/community.general.git synced 2025-07-30 18:43:09 +03:00

Unit tests: make set_module_args() a context manager, and remove copies of it in some tests (#9838)

Make set_module_args() a context manager, and remove copies of set_module_args().

Prepares for Data Tagging.
This commit is contained in:
Felix Fontein
2025-03-07 07:21:03 +01:00
committed by GitHub
parent 402f725424
commit a1781d09dd
84 changed files with 4043 additions and 4302 deletions

View File

@ -5,42 +5,11 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible_collections.community.general.tests.unit.compat import mock
from ansible_collections.community.general.tests.unit.compat import unittest
from ansible.module_utils import basic
from ansible.module_utils.common.text.converters import to_bytes
from ansible_collections.community.general.plugins.modules import usb_facts
def set_module_args(args):
"""prepare arguments so that they will be picked up during module creation"""
args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
basic._ANSIBLE_ARGS = to_bytes(args)
class AnsibleExitJson(Exception):
"""Exception class to be raised by module.exit_json and caught by the test case"""
pass
class AnsibleFailJson(Exception):
"""Exception class to be raised by module.fail_json and caught by the test case"""
pass
def exit_json(*args, **kwargs):
"""function to patch over exit_json; package return data into an exception"""
if 'changed' not in kwargs:
kwargs['changed'] = False
raise AnsibleExitJson(kwargs)
def fail_json(*args, **kwargs):
"""function to patch over fail_json; package return data into an exception"""
kwargs['failed'] = True
raise AnsibleFailJson(kwargs)
from ansible_collections.community.general.tests.unit.plugins.modules.utils import AnsibleExitJson, set_module_args, exit_json, fail_json
def get_bin_path(self, arg, required=False):
@ -85,8 +54,8 @@ class TestUsbFacts(unittest.TestCase):
command_output = data["input"]
mock_run_command.return_value = 0, command_output, None
with self.assertRaises(AnsibleExitJson) as result:
set_module_args({})
usb_facts.main()
with set_module_args({}):
usb_facts.main()
for output_field in self.output_fields:
self.assertEqual(result.exception.args[0]["ansible_facts"]["usb_devices"][0][output_field], data[output_field])
@ -97,8 +66,8 @@ class TestUsbFacts(unittest.TestCase):
with mock.patch.object(basic.AnsibleModule, 'run_command') as mock_run_command:
mock_run_command.return_value = 0, input, None
with self.assertRaises(AnsibleExitJson) as result:
set_module_args({})
usb_facts.main()
with set_module_args({}):
usb_facts.main()
for index in range(0, len(self.testing_data)):
for output_field in self.output_fields:
self.assertEqual(result.exception.args[0]["ansible_facts"]["usb_devices"][index][output_field],