id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
13,800
__init__.py
ansible_ansible/test/units/utils/collection_loader/fixtures/collections_masked/ansible_collections/testns/__init__.py
from __future__ import annotations # pragma: nocover raise Exception('this code should never execute') # pragma: nocover
125
Python
.py
2
60.5
68
0.768595
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,801
__init__.py
ansible_ansible/test/units/utils/collection_loader/fixtures/collections_masked/ansible_collections/testns/testcoll/__init__.py
from __future__ import annotations # pragma: nocover raise Exception('this code should never execute') # pragma: nocover
125
Python
.py
2
60.5
68
0.768595
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,802
test_broken_cowsay.py
ansible_ansible/test/units/utils/display/test_broken_cowsay.py
# -*- coding: utf-8 -*- # Copyright (c) 2021 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from ansible.utils.display import Display from unittest.mock import MagicMock def test_display_with_fake_cowsay_binary(capsys, mocker, display_resource): mocker.patch("ansible.constants.ANSIBLE_COW_PATH", "./cowsay.sh") mock_popen = MagicMock() mock_popen.return_value.returncode = 1 mocker.patch("subprocess.Popen", mock_popen) display = Display() assert not hasattr(display, "cows_available") assert display.b_cowsay is None
651
Python
.py
14
43
92
0.746032
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,803
test_warning.py
ansible_ansible/test/units/utils/display/test_warning.py
# -*- coding: utf-8 -*- # Copyright (c) 2020 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.utils.display import Display @pytest.fixture def warning_message(): warning_message = 'bad things will happen' expected_warning_message = '[WARNING]: {0}\n'.format(warning_message) return warning_message, expected_warning_message def test_warning(capsys, mocker, warning_message): warning_message, expected_warning_message = warning_message mocker.patch('ansible.utils.color.ANSIBLE_COLOR', True) mocker.patch('ansible.utils.color.parsecolor', return_value=u'1;35') # value for 'bright purple' d = Display() d.warning(warning_message) out, err = capsys.readouterr() assert d._warns == {expected_warning_message: 1} assert err == '\x1b[1;35m{0}\x1b[0m\n'.format(expected_warning_message.rstrip('\n')) def test_warning_no_color(capsys, mocker, warning_message): warning_message, expected_warning_message = warning_message mocker.patch('ansible.utils.color.ANSIBLE_COLOR', False) d = Display() d.warning(warning_message) out, err = capsys.readouterr() assert d._warns == {expected_warning_message: 1} assert err == expected_warning_message
1,339
Python
.py
28
43.785714
101
0.731125
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,804
test_logger.py
ansible_ansible/test/units/utils/display/test_logger.py
# -*- coding: utf-8 -*- # Copyright (c) 2020 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import logging import sys def test_logger(): """ Avoid CVE-2019-14846 as 3rd party libs will disclose secrets when logging is set to DEBUG """ # clear loaded modules to have unadultered test. for loaded in list(sys.modules.keys()): if 'ansible' in loaded: del sys.modules[loaded] # force logger to exist via config from ansible import constants as C C.DEFAULT_LOG_PATH = '/dev/null' # initialize logger from ansible.utils.display import logger assert logger.root.level != logging.DEBUG def test_empty_logger(): # clear loaded modules to have unadultered test. for loaded in list(sys.modules.keys()): if 'ansible' in loaded: del sys.modules[loaded] # force logger to exist via config from ansible import constants as C C.DEFAULT_LOG_PATH = '' # initialize logger from ansible.utils.display import logger assert logger is None
1,148
Python
.py
32
30.6875
92
0.697822
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,805
test_curses.py
ansible_ansible/test/units/utils/display/test_curses.py
# -*- coding: utf-8 -*- # Copyright (c) 2021 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import curses import importlib import io import pytest import sys import ansible.utils.display # make available for monkeypatch assert ansible.utils.display # avoid reporting as unused builtin_import = 'builtins.__import__' def test_pause_curses_tigetstr_none(mocker, monkeypatch): monkeypatch.delitem(sys.modules, 'ansible.utils.display') dunder_import = __import__ def _import(*args, **kwargs): if args[0] == 'curses': mock_curses = mocker.Mock() mock_curses.setupterm = mocker.Mock(return_value=True) mock_curses.tigetstr = mocker.Mock(return_value=None) return mock_curses else: return dunder_import(*args, **kwargs) mocker.patch(builtin_import, _import) mod = importlib.import_module('ansible.utils.display') assert mod.HAS_CURSES is True mod.setupterm() assert mod.HAS_CURSES is True assert mod.MOVE_TO_BOL == b'\r' assert mod.CLEAR_TO_EOL == b'\x1b[K' def test_pause_missing_curses(mocker, monkeypatch): monkeypatch.delitem(sys.modules, 'ansible.utils.display') dunder_import = __import__ def _import(*args, **kwargs): if args[0] == 'curses': raise ImportError else: return dunder_import(*args, **kwargs) mocker.patch(builtin_import, _import) mod = importlib.import_module('ansible.utils.display') assert mod.HAS_CURSES is False with pytest.raises(AttributeError, match=r"^module 'ansible\.utils\.display' has no attribute"): mod.curses # pylint: disable=pointless-statement assert mod.HAS_CURSES is False assert mod.MOVE_TO_BOL == b'\r' assert mod.CLEAR_TO_EOL == b'\x1b[K' @pytest.mark.parametrize('exc', (curses.error, TypeError, io.UnsupportedOperation)) def test_pause_curses_setupterm_error(mocker, monkeypatch, exc): monkeypatch.delitem(sys.modules, 'ansible.utils.display') dunder_import = __import__ def _import(*args, **kwargs): if args[0] == 'curses': mock_curses = mocker.Mock() mock_curses.setupterm = mocker.Mock(side_effect=exc) mock_curses.error = curses.error return mock_curses else: return dunder_import(*args, **kwargs) mocker.patch(builtin_import, _import) mod = importlib.import_module('ansible.utils.display') assert mod.HAS_CURSES is True mod.setupterm() assert mod.HAS_CURSES is False assert mod.MOVE_TO_BOL == b'\r' assert mod.CLEAR_TO_EOL == b'\x1b[K'
2,729
Python
.py
65
35.584615
100
0.679453
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,806
test_display.py
ansible_ansible/test/units/utils/display/test_display.py
# -*- coding: utf-8 -*- # Copyright (c) 2020 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from ansible.utils.display import Display def test_display_basic_message(capsys, mocker, display_resource): # Disable logging mocker.patch('ansible.utils.display.logger', return_value=None) d = Display() d.display(u'Some displayed message') out, err = capsys.readouterr() assert out == 'Some displayed message\n' assert err == ''
553
Python
.py
13
38.923077
92
0.720974
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,807
conftest.py
ansible_ansible/test/units/modules/conftest.py
# Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import json import pytest from ansible.module_utils.common.text.converters import to_bytes @pytest.fixture def patch_ansible_module(request, mocker): request.param = {'ANSIBLE_MODULE_ARGS': request.param} request.param['ANSIBLE_MODULE_ARGS']['_ansible_remote_tmp'] = '/tmp' request.param['ANSIBLE_MODULE_ARGS']['_ansible_keep_remote_files'] = False args = json.dumps(request.param) mocker.patch('ansible.module_utils.basic._ANSIBLE_ARGS', to_bytes(args))
648
Python
.py
13
46.692308
92
0.754386
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,808
test_iptables.py
ansible_ansible/test/units/modules/test_iptables.py
# Copyright: Contributors to the Ansible project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from units.modules.utils import AnsibleExitJson, AnsibleFailJson, set_module_args, fail_json, exit_json import pytest from ansible.modules import iptables IPTABLES_CMD = "/sbin/iptables" IPTABLES_VERSION = "1.8.2" CONST_INPUT_FILTER = [IPTABLES_CMD, "-t", "filter", "-L", "INPUT",] @pytest.fixture def _mock_basic_commands(mocker): """Mock basic commands like get_bin_path and get_iptables_version.""" mocker.patch( "ansible.module_utils.basic.AnsibleModule.get_bin_path", return_value=IPTABLES_CMD, ) mocker.patch("ansible.modules.iptables.get_iptables_version", return_value=IPTABLES_VERSION) @pytest.mark.usefixtures('_mock_basic_commands') def test_flush_table_without_chain(mocker): """Test flush without chain, flush the table.""" set_module_args( { "flush": True, } ) run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", return_value=(0, "", "") ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args[0][0] assert first_cmd_args_list[0], IPTABLES_CMD assert first_cmd_args_list[1], "-t" assert first_cmd_args_list[2], "filter" assert first_cmd_args_list[3], "-F" @pytest.mark.usefixtures('_mock_basic_commands') def test_flush_table_check_true(mocker): """Test flush without parameters and check == true.""" set_module_args( { "flush": True, "_ansible_check_mode": True, } ) run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", return_value=(0, "", "") ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 0 @pytest.mark.usefixtures('_mock_basic_commands') def test_policy_table(mocker): """Test change policy of a chain.""" set_module_args( { "policy": "ACCEPT", "chain": "INPUT", } ) commands_results = [(0, "Chain INPUT (policy DROP)\n", ""), (0, "", "")] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 2 first_cmd_args_list = run_command.call_args_list[0] second_cmd_args_list = run_command.call_args_list[1] assert first_cmd_args_list[0][0] == CONST_INPUT_FILTER assert second_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-P", "INPUT", "ACCEPT", ] @pytest.mark.usefixtures('_mock_basic_commands') @pytest.mark.parametrize( ("test_input", "commands_results"), [ pytest.param( { "policy": "ACCEPT", "chain": "INPUT", "_ansible_check_mode": True, }, [ (0, "Chain INPUT (policy DROP)\n", ""), ], id="policy-table-no-change", ), pytest.param( { "policy": "ACCEPT", "chain": "INPUT", }, [ (0, "Chain INPUT (policy ACCEPT)\n", ""), (0, "", ""), ], id="policy-table-change-false", ) ] ) def test_policy_table_flush(mocker, test_input, commands_results): """Test flush without parameters and change == false.""" set_module_args(test_input) run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == CONST_INPUT_FILTER # TODO ADD test policy without chain fail # TODO ADD test policy with chain don't exists # TODO ADD test policy with wrong choice fail @pytest.mark.usefixtures('_mock_basic_commands') def test_insert_rule_change_false(mocker): """Test flush without parameters.""" set_module_args( { "chain": "OUTPUT", "source": "1.2.3.4/32", "destination": "7.8.9.10/42", "jump": "ACCEPT", "action": "insert", "_ansible_check_mode": True, } ) commands_results = [ (1, "", ""), # check_rule_present (0, "", ""), # check_chain_present ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-C", "OUTPUT", "-s", "1.2.3.4/32", "-d", "7.8.9.10/42", "-j", "ACCEPT", ] @pytest.mark.usefixtures('_mock_basic_commands') def test_insert_rule(mocker): """Test flush without parameters.""" set_module_args( { "chain": "OUTPUT", "source": "1.2.3.4/32", "destination": "7.8.9.10/42", "jump": "ACCEPT", "action": "insert", } ) commands_results = [ (1, "", ""), # check_rule_present (0, "", ""), ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 2 first_cmd_args_list = run_command.call_args_list[0] second_cmd_args_list = run_command.call_args_list[1] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-C", "OUTPUT", "-s", "1.2.3.4/32", "-d", "7.8.9.10/42", "-j", "ACCEPT", ] assert second_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-I", "OUTPUT", "-s", "1.2.3.4/32", "-d", "7.8.9.10/42", "-j", "ACCEPT", ] @pytest.mark.usefixtures('_mock_basic_commands') def test_append_rule_check_mode(mocker): """Test append a redirection rule in check mode.""" set_module_args( { "chain": "PREROUTING", "source": "1.2.3.4/32", "destination": "7.8.9.10/42", "jump": "REDIRECT", "table": "nat", "to_destination": "5.5.5.5/32", "protocol": "udp", "destination_port": "22", "to_ports": "8600", "_ansible_check_mode": True, } ) commands_results = [ (1, "", ""), # check_rule_present (0, "", ""), # check_chain_present ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "nat", "-C", "PREROUTING", "-p", "udp", "-s", "1.2.3.4/32", "-d", "7.8.9.10/42", "-j", "REDIRECT", "--to-destination", "5.5.5.5/32", "--destination-port", "22", "--to-ports", "8600", ] @pytest.mark.usefixtures('_mock_basic_commands') def test_append_rule(mocker): """Test append a redirection rule.""" set_module_args( { "chain": "PREROUTING", "source": "1.2.3.4/32", "destination": "7.8.9.10/42", "jump": "REDIRECT", "table": "nat", "to_destination": "5.5.5.5/32", "protocol": "udp", "destination_port": "22", "to_ports": "8600", } ) commands_results = [ (1, "", ""), # check_rule_present (0, "", ""), # check_chain_present (0, "", ""), ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 2 first_cmd_args_list = run_command.call_args_list[0] second_cmd_args_list = run_command.call_args_list[1] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "nat", "-C", "PREROUTING", "-p", "udp", "-s", "1.2.3.4/32", "-d", "7.8.9.10/42", "-j", "REDIRECT", "--to-destination", "5.5.5.5/32", "--destination-port", "22", "--to-ports", "8600", ] assert second_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "nat", "-A", "PREROUTING", "-p", "udp", "-s", "1.2.3.4/32", "-d", "7.8.9.10/42", "-j", "REDIRECT", "--to-destination", "5.5.5.5/32", "--destination-port", "22", "--to-ports", "8600", ] @pytest.mark.usefixtures('_mock_basic_commands') def test_remove_rule(mocker): """Test flush without parameters.""" set_module_args( { "chain": "PREROUTING", "source": "1.2.3.4/32", "destination": "7.8.9.10/42", "jump": "SNAT", "table": "nat", "to_source": "5.5.5.5/32", "protocol": "udp", "source_port": "22", "to_ports": "8600", "state": "absent", "in_interface": "eth0", "out_interface": "eth1", "comment": "this is a comment", } ) commands_results = [ (0, "", ""), (0, "", ""), ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 2 first_cmd_args_list = run_command.call_args_list[0] second_cmd_args_list = run_command.call_args_list[1] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "nat", "-C", "PREROUTING", "-p", "udp", "-s", "1.2.3.4/32", "-d", "7.8.9.10/42", "-j", "SNAT", "--to-source", "5.5.5.5/32", "-i", "eth0", "-o", "eth1", "--source-port", "22", "--to-ports", "8600", "-m", "comment", "--comment", "this is a comment", ] assert second_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "nat", "-D", "PREROUTING", "-p", "udp", "-s", "1.2.3.4/32", "-d", "7.8.9.10/42", "-j", "SNAT", "--to-source", "5.5.5.5/32", "-i", "eth0", "-o", "eth1", "--source-port", "22", "--to-ports", "8600", "-m", "comment", "--comment", "this is a comment", ] @pytest.mark.usefixtures('_mock_basic_commands') def test_remove_rule_check_mode(mocker): """Test flush without parameters check mode.""" set_module_args( { "chain": "PREROUTING", "source": "1.2.3.4/32", "destination": "7.8.9.10/42", "jump": "SNAT", "table": "nat", "to_source": "5.5.5.5/32", "protocol": "udp", "source_port": "22", "to_ports": "8600", "state": "absent", "in_interface": "eth0", "out_interface": "eth1", "comment": "this is a comment", "_ansible_check_mode": True, } ) commands_results = [ (0, "", ""), ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "nat", "-C", "PREROUTING", "-p", "udp", "-s", "1.2.3.4/32", "-d", "7.8.9.10/42", "-j", "SNAT", "--to-source", "5.5.5.5/32", "-i", "eth0", "-o", "eth1", "--source-port", "22", "--to-ports", "8600", "-m", "comment", "--comment", "this is a comment", ] @pytest.mark.usefixtures('_mock_basic_commands') @pytest.mark.parametrize( ("test_input", "expected"), [ pytest.param( { "chain": "INPUT", "protocol": "tcp", "reject_with": "tcp-reset", "ip_version": "ipv4", }, [ IPTABLES_CMD, "-t", "filter", "-C", "INPUT", "-p", "tcp", "-j", "REJECT", "--reject-with", "tcp-reset", ], id="insert-reject-with", ), pytest.param( { "chain": "INPUT", "protocol": "tcp", "jump": "REJECT", "reject_with": "tcp-reset", "ip_version": "ipv4", }, [ IPTABLES_CMD, "-t", "filter", "-C", "INPUT", "-p", "tcp", "-j", "REJECT", "--reject-with", "tcp-reset", ], id="update-reject-with", ), ] ) def test_insert_with_reject(mocker, test_input, expected): """Using reject_with with a previously defined jump: REJECT results in two Jump statements #18988.""" set_module_args(test_input) commands_results = [ (0, "", ""), ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == expected @pytest.mark.usefixtures('_mock_basic_commands') def test_jump_tee_gateway_negative(mocker): """Missing gateway when JUMP is set to TEE.""" set_module_args( { "table": "mangle", "chain": "PREROUTING", "in_interface": "eth0", "protocol": "udp", "match": "state", "jump": "TEE", "ctstate": ["NEW"], "destination_port": "9521", "destination": "127.0.0.1", } ) mocker.patch( "ansible.module_utils.basic.AnsibleModule.fail_json", side_effect=fail_json, ) jump_err_msg = "jump is TEE but all of the following are missing: gateway" with pytest.raises(AnsibleFailJson, match=jump_err_msg) as exc: iptables.main() assert exc.value.args[0]["failed"] @pytest.mark.usefixtures('_mock_basic_commands') def test_jump_tee_gateway(mocker): """Using gateway when JUMP is set to TEE.""" set_module_args( { "table": "mangle", "chain": "PREROUTING", "in_interface": "eth0", "protocol": "udp", "match": "state", "jump": "TEE", "ctstate": ["NEW"], "destination_port": "9521", "gateway": "192.168.10.1", "destination": "127.0.0.1", } ) commands_results = [ (0, "", ""), ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "mangle", "-C", "PREROUTING", "-p", "udp", "-d", "127.0.0.1", "-m", "state", "-j", "TEE", "--gateway", "192.168.10.1", "-i", "eth0", "--destination-port", "9521", "--state", "NEW", ] @pytest.mark.usefixtures('_mock_basic_commands') @pytest.mark.parametrize( ("test_input"), [ pytest.param( 'flags=ALL flags_set="ACK,RST,SYN,FIN"', id="tcp-flags-str" ), pytest.param( { "flags": "ALL", "flags_set": "ACK,RST,SYN,FIN" }, id="tcp-flags-dict" ), pytest.param( { "flags": ["ALL"], "flags_set": ["ACK", "RST", "SYN", "FIN"] }, id="tcp-flags-list" ), ], ) def test_tcp_flags(mocker, test_input): """Test various ways of inputting tcp_flags.""" rule_data = { "chain": "OUTPUT", "protocol": "tcp", "jump": "DROP", "tcp_flags": test_input, } set_module_args(rule_data) commands_results = [ (0, "", ""), ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-C", "OUTPUT", "-p", "tcp", "--tcp-flags", "ALL", "ACK,RST,SYN,FIN", "-j", "DROP", ] @pytest.mark.usefixtures('_mock_basic_commands') @pytest.mark.parametrize( "log_level", [ "0", "1", "2", "3", "4", "5", "6", "7", "emerg", "alert", "crit", "error", "warning", "notice", "info", "debug", ], ) def test_log_level(mocker, log_level): """Test various ways of log level flag.""" set_module_args( { "chain": "INPUT", "jump": "LOG", "log_level": log_level, "source": "1.2.3.4/32", "log_prefix": "** DROP-this_ip **", } ) commands_results = [ (0, "", ""), ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-C", "INPUT", "-s", "1.2.3.4/32", "-j", "LOG", "--log-prefix", "** DROP-this_ip **", "--log-level", log_level, ] @pytest.mark.usefixtures('_mock_basic_commands') @pytest.mark.parametrize( ("test_input", "expected"), [ pytest.param( { "chain": "INPUT", "match": ["iprange"], "src_range": "192.168.1.100-192.168.1.199", "jump": "ACCEPT", }, [ IPTABLES_CMD, "-t", "filter", "-C", "INPUT", "-m", "iprange", "-j", "ACCEPT", "--src-range", "192.168.1.100-192.168.1.199", ], id="src-range", ), pytest.param( { "chain": "INPUT", "src_range": "192.168.1.100-192.168.1.199", "dst_range": "10.0.0.50-10.0.0.100", "jump": "ACCEPT", }, [ IPTABLES_CMD, "-t", "filter", "-C", "INPUT", "-j", "ACCEPT", "-m", "iprange", "--src-range", "192.168.1.100-192.168.1.199", "--dst-range", "10.0.0.50-10.0.0.100", ], id="src-range-dst-range", ), pytest.param( { "chain": "INPUT", "dst_range": "10.0.0.50-10.0.0.100", "jump": "ACCEPT" }, [ IPTABLES_CMD, "-t", "filter", "-C", "INPUT", "-j", "ACCEPT", "-m", "iprange", "--dst-range", "10.0.0.50-10.0.0.100", ], id="dst-range" ), ], ) def test_iprange(mocker, test_input, expected): """Test iprange module with its flags src_range and dst_range.""" set_module_args(test_input) commands_results = [ (0, "", ""), ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == expected @pytest.mark.usefixtures('_mock_basic_commands') def test_insert_rule_with_wait(mocker): """Test flush without parameters.""" set_module_args( { "chain": "OUTPUT", "source": "1.2.3.4/32", "destination": "7.8.9.10/42", "jump": "ACCEPT", "action": "insert", "wait": "10", } ) commands_results = [ (0, "", ""), ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-C", "OUTPUT", "-w", "10", "-s", "1.2.3.4/32", "-d", "7.8.9.10/42", "-j", "ACCEPT", ] @pytest.mark.usefixtures('_mock_basic_commands') def test_comment_position_at_end(mocker): """Test comment position to make sure it is at the end of command.""" set_module_args( { "chain": "INPUT", "jump": "ACCEPT", "action": "insert", "ctstate": ["NEW"], "comment": "this is a comment", "_ansible_check_mode": True, } ) commands_results = [ (0, "", ""), ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-C", "INPUT", "-j", "ACCEPT", "-m", "conntrack", "--ctstate", "NEW", "-m", "comment", "--comment", "this is a comment", ] assert run_command.call_args[0][0][14] == "this is a comment" @pytest.mark.usefixtures('_mock_basic_commands') def test_destination_ports(mocker): """Test multiport module usage with multiple ports.""" set_module_args( { "chain": "INPUT", "protocol": "tcp", "in_interface": "eth0", "source": "192.168.0.1/32", "destination_ports": ["80", "443", "8081:8085"], "jump": "ACCEPT", "comment": "this is a comment", } ) commands_results = [ (0, "", ""), ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-C", "INPUT", "-p", "tcp", "-s", "192.168.0.1/32", "-j", "ACCEPT", "-m", "multiport", "--dports", "80,443,8081:8085", "-i", "eth0", "-m", "comment", "--comment", "this is a comment", ] @pytest.mark.usefixtures('_mock_basic_commands') @pytest.mark.parametrize( ("test_input", "expected"), [ pytest.param( { "chain": "INPUT", "protocol": "tcp", "match_set": "admin_hosts", "match_set_flags": "src", "destination_port": "22", "jump": "ACCEPT", "comment": "this is a comment", }, [ IPTABLES_CMD, "-t", "filter", "-C", "INPUT", "-p", "tcp", "-j", "ACCEPT", "--destination-port", "22", "-m", "set", "--match-set", "admin_hosts", "src", "-m", "comment", "--comment", "this is a comment", ], id="match-set-src", ), pytest.param( { "chain": "INPUT", "protocol": "udp", "match_set": "banned_hosts", "match_set_flags": "src,dst", "jump": "REJECT", }, [ IPTABLES_CMD, "-t", "filter", "-C", "INPUT", "-p", "udp", "-j", "REJECT", "-m", "set", "--match-set", "banned_hosts", "src,dst", ], id="match-set-src-dst", ), pytest.param( { "chain": "INPUT", "protocol": "udp", "match_set": "banned_hosts_dst", "match_set_flags": "dst,dst", "jump": "REJECT", }, [ IPTABLES_CMD, "-t", "filter", "-C", "INPUT", "-p", "udp", "-j", "REJECT", "-m", "set", "--match-set", "banned_hosts_dst", "dst,dst", ], id="match-set-dst-dst", ), pytest.param( { "chain": "INPUT", "protocol": "udp", "match_set": "banned_hosts", "match_set_flags": "src,src", "jump": "REJECT", }, [ IPTABLES_CMD, "-t", "filter", "-C", "INPUT", "-p", "udp", "-j", "REJECT", "-m", "set", "--match-set", "banned_hosts", "src,src", ], id="match-set-src-src", ), ], ) def test_match_set(mocker, test_input, expected): """Test match_set together with match_set_flags.""" set_module_args(test_input) commands_results = [ (0, "", ""), ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(SystemExit): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == expected @pytest.mark.usefixtures('_mock_basic_commands') def test_chain_creation(mocker): """Test chain creation when absent.""" set_module_args( { "chain": "FOOBAR", "state": "present", "chain_management": True, } ) commands_results = [ (1, "", ""), # check_chain_present (0, "", ""), # create_chain ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) mocker.patch( "ansible.module_utils.basic.AnsibleModule.exit_json", side_effect=exit_json, ) with pytest.raises(AnsibleExitJson): iptables.main() assert run_command.call_count == 2 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-L", "FOOBAR", ] second_cmd_args_list = run_command.call_args_list[1] assert second_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-N", "FOOBAR", ] commands_results = [ (0, "", ""), # check_rule_present ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(AnsibleExitJson) as exc: iptables.main() assert not exc.value.args[0]["changed"] @pytest.mark.usefixtures('_mock_basic_commands') def test_chain_creation_check_mode(mocker): """Test chain creation when absent in check mode.""" set_module_args( { "chain": "FOOBAR", "state": "present", "chain_management": True, "_ansible_check_mode": True, } ) commands_results = [ (1, "", ""), # check_rule_present ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) mocker.patch( "ansible.module_utils.basic.AnsibleModule.exit_json", side_effect=exit_json, ) with pytest.raises(AnsibleExitJson): iptables.main() assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-L", "FOOBAR", ] commands_results = [ (0, "", ""), # check_rule_present ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(AnsibleExitJson) as exc: iptables.main() assert not exc.value.args[0]["changed"] @pytest.mark.usefixtures('_mock_basic_commands') def test_chain_deletion(mocker): """Test chain deletion when present.""" set_module_args( { "chain": "FOOBAR", "state": "absent", "chain_management": True, } ) commands_results = [ (0, "", ""), # check_chain_present (0, "", ""), # delete_chain ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) mocker.patch( "ansible.module_utils.basic.AnsibleModule.exit_json", side_effect=exit_json, ) with pytest.raises(AnsibleExitJson) as exc: iptables.main() assert exc.value.args[0]["changed"] assert run_command.call_count == 2 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-L", "FOOBAR", ] second_cmd_args_list = run_command.call_args_list[1] assert second_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-X", "FOOBAR", ] commands_results = [ (1, "", ""), # check_rule_present ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(AnsibleExitJson) as exc: iptables.main() assert not exc.value.args[0]["changed"] @pytest.mark.usefixtures('_mock_basic_commands') def test_chain_deletion_check_mode(mocker): """Test chain deletion when present in check mode.""" set_module_args( { "chain": "FOOBAR", "state": "absent", "chain_management": True, "_ansible_check_mode": True, } ) commands_results = [ (0, "", ""), # check_chain_present ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) mocker.patch( "ansible.module_utils.basic.AnsibleModule.exit_json", side_effect=exit_json, ) with pytest.raises(AnsibleExitJson) as exc: iptables.main() assert exc.value.args[0]["changed"] assert run_command.call_count == 1 first_cmd_args_list = run_command.call_args_list[0] assert first_cmd_args_list[0][0] == [ IPTABLES_CMD, "-t", "filter", "-L", "FOOBAR", ] commands_results = [ (1, "", ""), # check_rule_present ] run_command = mocker.patch( "ansible.module_utils.basic.AnsibleModule.run_command", side_effect=commands_results, ) with pytest.raises(AnsibleExitJson) as exc: iptables.main() assert not exc.value.args[0]["changed"]
35,216
Python
.py
1,281
18.282592
105
0.480621
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,809
test_systemd.py
ansible_ansible/test/units/modules/test_systemd.py
from __future__ import annotations import unittest from ansible.modules.systemd import parse_systemctl_show class ParseSystemctlShowTestCase(unittest.TestCase): def test_simple(self): lines = [ 'Type=simple', 'Restart=no', 'Requires=system.slice sysinit.target', 'Description=Blah blah blah', ] parsed = parse_systemctl_show(lines) self.assertEqual(parsed, { 'Type': 'simple', 'Restart': 'no', 'Requires': 'system.slice sysinit.target', 'Description': 'Blah blah blah', }) def test_multiline_exec(self): # This was taken from a real service that specified "ExecStart=/bin/echo foo\nbar" lines = [ 'Type=simple', 'ExecStart={ path=/bin/echo ; argv[]=/bin/echo foo', 'bar ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }', 'Description=blah', ] parsed = parse_systemctl_show(lines) self.assertEqual(parsed, { 'Type': 'simple', 'ExecStart': '{ path=/bin/echo ; argv[]=/bin/echo foo\n' 'bar ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }', 'Description': 'blah', }) def test_single_line_with_brace(self): lines = [ 'Type=simple', 'Description={ this is confusing', 'Restart=no', ] parsed = parse_systemctl_show(lines) self.assertEqual(parsed, { 'Type': 'simple', 'Description': '{ this is confusing', 'Restart': 'no', })
1,730
Python
.py
45
28.044444
124
0.541989
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,810
test_hostname.py
ansible_ansible/test/units/modules/test_hostname.py
from __future__ import annotations import os import shutil import tempfile from unittest.mock import patch, MagicMock, mock_open from ansible.module_utils.common._utils import get_all_subclasses from ansible.modules import hostname from units.modules.utils import ModuleTestCase, set_module_args class TestHostname(ModuleTestCase): @patch('os.path.isfile') def test_stategy_get_never_writes_in_check_mode(self, isfile): isfile.return_value = True set_module_args({'name': 'fooname', '_ansible_check_mode': True}) subclasses = get_all_subclasses(hostname.BaseStrategy) module = MagicMock() for cls in subclasses: instance = cls(module) instance.module.run_command = MagicMock() instance.module.run_command.return_value = (0, '', '') m = mock_open() builtins = 'builtins' with patch('%s.open' % builtins, m): instance.get_permanent_hostname() instance.get_current_hostname() self.assertFalse( m.return_value.write.called, msg='%s called write, should not have' % str(cls)) def test_all_named_strategies_exist(self): """Loop through the STRATS and see if anything is missing.""" for _name, prefix in hostname.STRATS.items(): classname = "%sStrategy" % prefix cls = getattr(hostname, classname, None) assert cls is not None self.assertTrue(issubclass(cls, hostname.BaseStrategy)) class TestRedhatStrategy(ModuleTestCase): def setUp(self): super(TestRedhatStrategy, self).setUp() self.testdir = tempfile.mkdtemp(prefix='ansible-test-hostname-') self.network_file = os.path.join(self.testdir, "network") def tearDown(self): super(TestRedhatStrategy, self).tearDown() shutil.rmtree(self.testdir, ignore_errors=True) @property def instance(self): self.module = MagicMock() instance = hostname.RedHatStrategy(self.module) instance.NETWORK_FILE = self.network_file return instance def test_get_permanent_hostname_missing(self): self.assertIsNone(self.instance.get_permanent_hostname()) self.assertTrue(self.module.fail_json.called) self.module.fail_json.assert_called_with( "Unable to locate HOSTNAME entry in %s" % self.network_file ) def test_get_permanent_hostname_line_missing(self): with open(self.network_file, "w") as f: f.write("# some other content\n") self.assertIsNone(self.instance.get_permanent_hostname()) self.module.fail_json.assert_called_with( "Unable to locate HOSTNAME entry in %s" % self.network_file ) def test_get_permanent_hostname_existing(self): with open(self.network_file, "w") as f: f.write( "some other content\n" "HOSTNAME=foobar\n" "more content\n" ) self.assertEqual(self.instance.get_permanent_hostname(), "foobar") def test_get_permanent_hostname_existing_whitespace(self): with open(self.network_file, "w") as f: f.write( "some other content\n" " HOSTNAME=foobar \n" "more content\n" ) self.assertEqual(self.instance.get_permanent_hostname(), "foobar") def test_set_permanent_hostname_missing(self): self.instance.set_permanent_hostname("foobar") with open(self.network_file) as f: self.assertEqual(f.read(), "HOSTNAME=foobar\n") def test_set_permanent_hostname_line_missing(self): with open(self.network_file, "w") as f: f.write("# some other content\n") self.instance.set_permanent_hostname("foobar") with open(self.network_file) as f: self.assertEqual(f.read(), "# some other content\nHOSTNAME=foobar\n") def test_set_permanent_hostname_existing(self): with open(self.network_file, "w") as f: f.write( "some other content\n" "HOSTNAME=spam\n" "more content\n" ) self.instance.set_permanent_hostname("foobar") with open(self.network_file) as f: self.assertEqual( f.read(), "some other content\n" "HOSTNAME=foobar\n" "more content\n" ) def test_set_permanent_hostname_existing_whitespace(self): with open(self.network_file, "w") as f: f.write( "some other content\n" " HOSTNAME=spam \n" "more content\n" ) self.instance.set_permanent_hostname("foobar") with open(self.network_file) as f: self.assertEqual( f.read(), "some other content\n" "HOSTNAME=foobar\n" "more content\n" )
5,055
Python
.py
117
32.478632
81
0.606794
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,811
test_mount_facts.py
ansible_ansible/test/units/modules/test_mount_facts.py
# Copyright: Contributors to the Ansible project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from ansible.module_utils.basic import AnsibleModule from ansible.modules import mount_facts from units.modules.utils import ( AnsibleExitJson, AnsibleFailJson, exit_json, fail_json, set_module_args, ) from units.modules.mount_facts_data import aix7_2, freebsd14_1, openbsd6_4, rhel9_4, solaris11_2 from dataclasses import astuple from unittest.mock import MagicMock import pytest import time def get_mock_module(invocation): set_module_args(invocation) module = AnsibleModule( argument_spec=mount_facts.get_argument_spec(), supports_check_mode=True, ) return module def mock_callable(return_value=None): def func(*args, **kwargs): return return_value return func @pytest.fixture def set_file_content(monkeypatch): def _set_file_content(data): def mock_get_file_content(filename, default=None): if filename in data: return data[filename] return default monkeypatch.setattr(mount_facts, "get_file_content", mock_get_file_content) return _set_file_content def test_invocation(monkeypatch, set_file_content): set_file_content({}) set_module_args({}) monkeypatch.setattr(mount_facts, "run_mount_bin", mock_callable(return_value="")) monkeypatch.setattr(AnsibleModule, "exit_json", exit_json) with pytest.raises(AnsibleExitJson, match="{'ansible_facts': {'mount_points': {}, 'aggregate_mounts': \\[\\]}}"): mount_facts.main() def test_invalid_timeout(monkeypatch): set_module_args({"timeout": 0}) monkeypatch.setattr(AnsibleModule, "fail_json", fail_json) with pytest.raises(AnsibleFailJson, match="argument 'timeout' must be a positive number or null"): mount_facts.main() @pytest.mark.parametrize("invalid_binary, error", [ ("ansible_test_missing_binary", 'Failed to find required executable "ansible_test_missing_binary" in paths: .*'), ("false", "Failed to execute .*false: Command '[^']*false' returned non-zero exit status 1"), (["one", "two"], "argument 'mount_binary' must be a string or null, not \\['one', 'two'\\]"), ]) def test_invalid_mount_binary(monkeypatch, set_file_content, invalid_binary, error): set_file_content({}) set_module_args({"mount_binary": invalid_binary}) monkeypatch.setattr(AnsibleModule, "fail_json", fail_json) with pytest.raises(AnsibleFailJson, match=error): mount_facts.main() def test_invalid_source(monkeypatch): set_module_args({"sources": [""]}) monkeypatch.setattr(AnsibleModule, "fail_json", fail_json) with pytest.raises(AnsibleFailJson, match="sources contains an empty string"): mount_facts.main() def test_duplicate_source(monkeypatch, set_file_content): set_file_content({"/etc/fstab": rhel9_4.fstab}) mock_warn = MagicMock() monkeypatch.setattr(AnsibleModule, "warn", mock_warn) user_sources = ["static", "/etc/fstab"] resolved_sources = ["/etc/fstab", "/etc/vfstab", "/etc/filesystems", "/etc/fstab"] expected_warning = "mount_facts option 'sources' contains duplicate entries, repeat sources will be ignored:" module = get_mock_module({"sources": user_sources}) list(mount_facts.gen_mounts_by_source(module)) assert mock_warn.called assert len(mock_warn.call_args_list) == 1 assert mock_warn.call_args_list[0].args == (f"{expected_warning} {resolved_sources}",) @pytest.mark.parametrize("function, data, expected_result_data", [ ("gen_fstab_entries", rhel9_4.fstab, rhel9_4.fstab_parsed), ("gen_fstab_entries", rhel9_4.mtab, rhel9_4.mtab_parsed), ("gen_fstab_entries", freebsd14_1.fstab, freebsd14_1.fstab_parsed), ("gen_vfstab_entries", solaris11_2.vfstab, solaris11_2.vfstab_parsed), ("gen_mnttab_entries", solaris11_2.mnttab, solaris11_2.mnttab_parsed), ("gen_aix_filesystems_entries", aix7_2.filesystems, aix7_2.filesystems_parsed), ]) def test_list_mounts(function, data, expected_result_data): function = getattr(mount_facts, function) result = [astuple(mount_info) for mount_info in function(data.splitlines())] assert result == [(_mnt, _line, _info) for _src, _mnt, _line, _info in expected_result_data] def test_etc_filesystems_linux(set_file_content): not_aix_data = ( "ext4\next3\next2\nnodev proc\nnodev devpts\niso9770\nvfat\nhfs\nhfsplus\n*" ) set_file_content({"/etc/filesystems": not_aix_data}) module = get_mock_module({"sources": ["/etc/filesystems"]}) assert list(mount_facts.gen_mounts_by_source(module)) == [] @pytest.mark.parametrize("mount_stdout, expected_result_data", [ (rhel9_4.mount, rhel9_4.mount_parsed), (freebsd14_1.mount, freebsd14_1.mount_parsed), (openbsd6_4.mount, openbsd6_4.mount_parsed), (aix7_2.mount, aix7_2.mount_parsed), ]) def test_parse_mount_bin_stdout(mount_stdout, expected_result_data): expected_result = [(_mnt, _line, _info) for _src, _mnt, _line, _info in expected_result_data] result = [astuple(mount_info) for mount_info in mount_facts.gen_mounts_from_stdout(mount_stdout)] assert result == expected_result def test_parse_mount_bin_stdout_unknown(monkeypatch, set_file_content): set_file_content({}) set_module_args({}) monkeypatch.setattr(mount_facts, "run_mount_bin", mock_callable(return_value="nonsense")) monkeypatch.setattr(AnsibleModule, "exit_json", exit_json) with pytest.raises(AnsibleExitJson, match="{'ansible_facts': {'mount_points': {}, 'aggregate_mounts': \\[\\]}}"): mount_facts.main() rhel_mock_fs = {"/etc/fstab": rhel9_4.fstab, "/etc/mtab": rhel9_4.mtab} freebsd_mock_fs = {"/etc/fstab": freebsd14_1.fstab} aix_mock_fs = {"/etc/filesystems": aix7_2.filesystems} openbsd_mock_fs = {"/etc/fstab": openbsd6_4.fstab} solaris_mock_fs = {"/etc/mnttab": solaris11_2.mnttab, "/etc/vfstab": solaris11_2.vfstab} @pytest.mark.parametrize("sources, file_data, mount_data, results", [ (["static"], rhel_mock_fs, rhel9_4.mount, rhel9_4.fstab_parsed), (["/etc/fstab"], rhel_mock_fs, rhel9_4.mount, rhel9_4.fstab_parsed), (["dynamic"], rhel_mock_fs, rhel9_4.mount, rhel9_4.mtab_parsed), (["/etc/mtab"], rhel_mock_fs, rhel9_4.mount, rhel9_4.mtab_parsed), (["all"], rhel_mock_fs, rhel9_4.mount, rhel9_4.mtab_parsed + rhel9_4.fstab_parsed), (["mount"], rhel_mock_fs, rhel9_4.mount, rhel9_4.mount_parsed), (["all"], freebsd_mock_fs, freebsd14_1.mount, freebsd14_1.fstab_parsed + freebsd14_1.mount_parsed), (["static"], freebsd_mock_fs, freebsd14_1.mount, freebsd14_1.fstab_parsed), (["dynamic"], freebsd_mock_fs, freebsd14_1.mount, freebsd14_1.mount_parsed), (["mount"], freebsd_mock_fs, freebsd14_1.mount, freebsd14_1.mount_parsed), (["all"], aix_mock_fs, aix7_2.mount, aix7_2.filesystems_parsed + aix7_2.mount_parsed), (["all"], openbsd_mock_fs, openbsd6_4.mount, openbsd6_4.fstab_parsed + openbsd6_4.mount_parsed), (["all"], solaris_mock_fs, "", solaris11_2.mnttab_parsed + solaris11_2.vfstab_parsed), ]) def test_gen_mounts_by_sources(monkeypatch, set_file_content, sources, file_data, mount_data, results): set_file_content(file_data) mock_run_mount = mock_callable(return_value=mount_data) monkeypatch.setattr(mount_facts, "run_mount_bin", mock_run_mount) module = get_mock_module({"sources": sources}) actual_results = list(mount_facts.gen_mounts_by_source(module)) assert actual_results == results @pytest.mark.parametrize("on_timeout, should_warn, should_raise", [ (None, False, True), ("warn", True, False), ("ignore", False, False), ]) def test_gen_mounts_by_source_timeout(monkeypatch, set_file_content, on_timeout, should_warn, should_raise): set_file_content({}) monkeypatch.setattr(AnsibleModule, "fail_json", fail_json) mock_warn = MagicMock() monkeypatch.setattr(AnsibleModule, "warn", mock_warn) # hack to simulate a hang (module entrypoint requires >= 1 or None) params = {"timeout": 0} if on_timeout: params["on_timeout"] = on_timeout module = get_mock_module(params) if should_raise: with pytest.raises(AnsibleFailJson, match="Command '[^']*mount' timed out after 0.0 seconds"): list(mount_facts.gen_mounts_by_source(module)) else: assert list(mount_facts.gen_mounts_by_source(module)) == [] assert mock_warn.called == should_warn def test_get_mount_facts(monkeypatch, set_file_content): set_file_content({"/etc/mtab": rhel9_4.mtab, "/etc/fstab": rhel9_4.fstab}) monkeypatch.setattr(mount_facts, "get_mount_size", mock_callable(return_value=None)) monkeypatch.setattr(mount_facts, "get_partition_uuid", mock_callable(return_value=None)) module = get_mock_module({}) assert len(rhel9_4.fstab_parsed) == 3 assert len(rhel9_4.mtab_parsed) == 4 assert len(mount_facts.get_mount_facts(module)) == 7 @pytest.mark.parametrize("filter_name, filter_value, source, mount_info", [ ("devices", "proc", rhel9_4.mtab_parsed[0][2], rhel9_4.mtab_parsed[0][-1]), ("fstypes", "proc", rhel9_4.mtab_parsed[0][2], rhel9_4.mtab_parsed[0][-1]), ]) def test_get_mounts_facts_filtering(monkeypatch, set_file_content, filter_name, filter_value, source, mount_info): set_file_content({"/etc/mtab": rhel9_4.mtab}) monkeypatch.setattr(mount_facts, "get_mount_size", mock_callable(return_value=None)) monkeypatch.setattr(mount_facts, "get_partition_uuid", mock_callable(return_value=None)) module = get_mock_module({filter_name: [filter_value]}) results = mount_facts.get_mount_facts(module) expected_context = {"source": "/etc/mtab", "source_data": source} assert len(results) == 1 assert results[0]["ansible_context"] == expected_context assert results[0] == dict(ansible_context=expected_context, uuid=None, **mount_info) def test_get_mounts_size(monkeypatch, set_file_content): def mock_get_mount_size(*args, **kwargs): return { "block_available": 3242510, "block_size": 4096, "block_total": 3789825, "block_used": 547315, "inode_available": 1875503, "inode_total": 1966080, "size_available": 13281320960, "size_total": 15523123200, } set_file_content({"/etc/mtab": rhel9_4.mtab}) monkeypatch.setattr(mount_facts, "get_mount_size", mock_get_mount_size) monkeypatch.setattr(mount_facts, "get_partition_uuid", mock_callable(return_value=None)) module = get_mock_module({}) result = mount_facts.get_mount_facts(module) assert len(result) == len(rhel9_4.mtab_parsed) expected_results = setup_parsed_sources_with_context(rhel9_4.mtab_parsed) assert result == [dict(**result, **mock_get_mount_size()) for result in expected_results] @pytest.mark.parametrize("on_timeout, should_warn, should_raise", [ (None, False, True), ("error", False, True), ("warn", True, False), ("ignore", False, False), ]) def test_get_mount_size_timeout(monkeypatch, set_file_content, on_timeout, should_warn, should_raise): set_file_content({"/etc/mtab": rhel9_4.mtab}) monkeypatch.setattr(AnsibleModule, "fail_json", fail_json) mock_warn = MagicMock() monkeypatch.setattr(AnsibleModule, "warn", mock_warn) monkeypatch.setattr(mount_facts, "get_partition_uuid", mock_callable(return_value=None)) params = {"timeout": 0.1, "sources": ["dynamic"], "mount_binary": "mount"} if on_timeout: params["on_timeout"] = on_timeout module = get_mock_module(params) def mock_slow_function(*args, **kwargs): time.sleep(0.15) raise Exception("Timeout failed") monkeypatch.setattr(mount_facts, "get_mount_size", mock_slow_function) match = r"Timed out getting mount size for mount /proc \(type proc\) after 0.1 seconds" if should_raise: with pytest.raises(AnsibleFailJson, match=match): mount_facts.get_mount_facts(module) else: results = mount_facts.get_mount_facts(module) assert len(results) == len(rhel9_4.mtab_parsed) assert results == setup_parsed_sources_with_context(rhel9_4.mtab_parsed) assert mock_warn.called == should_warn def setup_missing_uuid(monkeypatch, module): monkeypatch.setattr(module, "get_bin_path", mock_callable(return_value="fake_bin")) monkeypatch.setattr(mount_facts.subprocess, "check_output", mock_callable(return_value="")) monkeypatch.setattr(mount_facts.os, "listdir", MagicMock(side_effect=FileNotFoundError)) def setup_udevadm_fallback(monkeypatch): mock_udevadm_snippet = ( "DEVPATH=/devices/virtual/block/dm-0\n" "DEVNAME=/dev/dm-0\n" "DEVTYPE=disk\n" "ID_FS_UUID=d37b5483-304d-471d-913e-4bb77856d90f\n" ) monkeypatch.setattr(mount_facts.subprocess, "check_output", mock_callable(return_value=mock_udevadm_snippet)) def setup_run_lsblk_fallback(monkeypatch): mount_facts.run_lsblk.cache_clear() mock_lsblk_snippet = ( "/dev/zram0\n" "/dev/mapper/luks-2f2610e3-56b3-4131-ae3e-caf9aa535b73 d37b5483-304d-471d-913e-4bb77856d90f\n" "/dev/nvme0n1\n" "/dev/nvme0n1p1 B521-06FD\n" ) monkeypatch.setattr(mount_facts.subprocess, "check_output", mock_callable(return_value=mock_lsblk_snippet)) def setup_list_uuids_linux_preferred(monkeypatch): mount_facts.list_uuids_linux.cache_clear() def mock_realpath(path): if path.endswith("d37b5483-304d-471d-913e-4bb77856d90f"): return "/dev/mapper/luks-2f2610e3-56b3-4131-ae3e-caf9aa535b73" return 'miss' monkeypatch.setattr(mount_facts.os.path, "realpath", mock_realpath) monkeypatch.setattr(mount_facts.os, "listdir", mock_callable(return_value=["B521-06FD", "d37b5483-304d-471d-913e-4bb77856d90f"])) def test_get_partition_uuid(monkeypatch): module = get_mock_module({}) # Test missing UUID setup_missing_uuid(monkeypatch, module) assert mount_facts.get_partition_uuid(module, "ansible-test-fake-dev") is None # Test udevadm (legacy fallback) setup_udevadm_fallback(monkeypatch) assert mount_facts.get_partition_uuid(module, "ansible-test-udevadm") == "d37b5483-304d-471d-913e-4bb77856d90f" # Test run_lsblk fallback setup_run_lsblk_fallback(monkeypatch) assert mount_facts.get_partition_uuid(module, "/dev/nvme0n1p1") == "B521-06FD" # Test list_uuids_linux (preferred) setup_list_uuids_linux_preferred(monkeypatch) assert mount_facts.get_partition_uuid(module, "/dev/mapper/luks-2f2610e3-56b3-4131-ae3e-caf9aa535b73") == "d37b5483-304d-471d-913e-4bb77856d90f" def setup_parsed_sources_with_context(parsed_sources): mounts = [] for source, mount, line, info in parsed_sources: mount_point_result = dict(ansible_context={"source": source, "source_data": line}, uuid=None, **info) mounts.append(mount_point_result) return mounts def test_handle_deduplication(monkeypatch): unformatted_mounts = [ {"mount": "/mnt/mount1", "device": "foo", "ansible_context": {"source": "/proc/mounts"}}, {"mount": "/mnt/mount2", "ansible_context": {"source": "/proc/mounts"}}, {"mount": "/mnt/mount1", "device": "qux", "ansible_context": {"source": "/etc/fstab"}}, ] mock_warn = MagicMock() monkeypatch.setattr(AnsibleModule, "warn", mock_warn) module = get_mock_module({}) mount_points, aggregate_mounts = mount_facts.handle_deduplication(module, unformatted_mounts) assert len(mount_points.keys()) == 2 assert mount_points["/mnt/mount1"]["device"] == "foo" assert aggregate_mounts == [] assert not mock_warn.called @pytest.mark.parametrize("include_aggregate_mounts, warn_expected", [ (None, True), (False, False), (True, False), ]) def test_handle_deduplication_warning(monkeypatch, include_aggregate_mounts, warn_expected): unformatted_mounts = [ {"mount": "/mnt/mount1", "device": "foo", "ansible_context": {"source": "/proc/mounts"}}, {"mount": "/mnt/mount1", "device": "bar", "ansible_context": {"source": "/proc/mounts"}}, {"mount": "/mnt/mount2", "ansible_context": {"source": "/proc/mounts"}}, {"mount": "/mnt/mount1", "device": "qux", "ansible_context": {"source": "/etc/fstab"}}, ] mock_warn = MagicMock() monkeypatch.setattr(AnsibleModule, "warn", mock_warn) module = get_mock_module({"include_aggregate_mounts": include_aggregate_mounts}) mount_points, aggregate_mounts = mount_facts.handle_deduplication(module, unformatted_mounts) assert aggregate_mounts == [] if not include_aggregate_mounts else unformatted_mounts assert mock_warn.called == warn_expected
16,869
Python
.py
313
48.501597
148
0.695636
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,812
test_apt_key.py
ansible_ansible/test/units/modules/test_apt_key.py
from __future__ import annotations import os from unittest.mock import patch, Mock import unittest from ansible.modules import apt_key def returnc(x): return 'C' class AptKeyTestCase(unittest.TestCase): @patch.object(apt_key, 'apt_key_bin', '/usr/bin/apt-key') @patch.object(apt_key, 'lang_env', returnc) @patch.dict(os.environ, {'HTTP_PROXY': 'proxy.example.com'}) def test_import_key_with_http_proxy(self): m_mock = Mock() m_mock.run_command.return_value = (0, '', '') apt_key.import_key( m_mock, keyring=None, keyserver='keyserver.example.com', key_id='0xDEADBEEF') self.assertEqual( m_mock.run_command.call_args_list[0][0][0], '/usr/bin/apt-key adv --no-tty --keyserver keyserver.example.com' ' --keyserver-options http-proxy=proxy.example.com' ' --recv 0xDEADBEEF' )
912
Python
.py
23
32.565217
77
0.640182
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,813
test_copy.py
ansible_ansible/test/units/modules/test_copy.py
# -*- coding: utf-8 -*- # Copyright: # (c) 2018 Ansible Project # License: GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.modules.copy import AnsibleModuleError, split_pre_existing_dir from ansible.module_utils.basic import AnsibleModule THREE_DIRS_DATA: tuple[tuple[str, tuple[str, list[str]] | None, tuple[str, list[str]], tuple[str, list[str]], tuple[str, list[str]]], ...] = ( ('/dir1/dir2', # 0 existing dirs: error (because / should always exist) None, # 1 existing dir: ('/', ['dir1', 'dir2']), # 2 existing dirs: ('/dir1', ['dir2']), # 3 existing dirs: ('/dir1/dir2', []) ), ('/dir1/dir2/', # 0 existing dirs: error (because / should always exist) None, # 1 existing dir: ('/', ['dir1', 'dir2']), # 2 existing dirs: ('/dir1', ['dir2']), # 3 existing dirs: ('/dir1/dir2', []) ), ) TWO_DIRS_DATA: tuple[tuple[str, tuple[str, list[str]] | None, tuple[str, list[str]], tuple[str, list[str]]], ...] = ( ('dir1/dir2', # 0 existing dirs: ('.', ['dir1', 'dir2']), # 1 existing dir: ('dir1', ['dir2']), # 2 existing dirs: ('dir1/dir2', []), # 3 existing dirs: Same as 2 because we never get to the third ), ('dir1/dir2/', # 0 existing dirs: ('.', ['dir1', 'dir2']), # 1 existing dir: ('dir1', ['dir2']), # 2 existing dirs: ('dir1/dir2', []), # 3 existing dirs: Same as 2 because we never get to the third ), ('/dir1', # 0 existing dirs: error (because / should always exist) None, # 1 existing dir: ('/', ['dir1']), # 2 existing dirs: ('/dir1', []), # 3 existing dirs: Same as 2 because we never get to the third ), ('/dir1/', # 0 existing dirs: error (because / should always exist) None, # 1 existing dir: ('/', ['dir1']), # 2 existing dirs: ('/dir1', []), # 3 existing dirs: Same as 2 because we never get to the third ), ) TWO_DIRS_DATA += tuple(item[:4] for item in THREE_DIRS_DATA) ONE_DIR_DATA: tuple[tuple[str, tuple[str, list[str]] | None, tuple[str, list[str]]], ...] = ( ('dir1', # 0 existing dirs: ('.', ['dir1']), # 1 existing dir: ('dir1', []), # 2 existing dirs: Same as 1 because we never get to the third ), ('dir1/', # 0 existing dirs: ('.', ['dir1']), # 1 existing dir: ('dir1', []), # 2 existing dirs: Same as 1 because we never get to the third ), ) ONE_DIR_DATA += tuple(item[:3] for item in TWO_DIRS_DATA) @pytest.mark.parametrize('directory, expected', ((d[0], d[4]) for d in THREE_DIRS_DATA)) @pytest.mark.xfail(reason='broken test and/or code, original test missing assert', strict=False) def test_split_pre_existing_dir_three_levels_exist(directory, expected, mocker): mocker.patch('os.path.exists', side_effect=[True, True, True]) assert split_pre_existing_dir(directory) == expected @pytest.mark.parametrize('directory, expected', ((d[0], d[3]) for d in TWO_DIRS_DATA)) @pytest.mark.xfail(reason='broken test and/or code, original test missing assert', strict=False) def test_split_pre_existing_dir_two_levels_exist(directory, expected, mocker): mocker.patch('os.path.exists', side_effect=[True, True, False]) assert split_pre_existing_dir(directory) == expected @pytest.mark.parametrize('directory, expected', ((d[0], d[2]) for d in ONE_DIR_DATA)) @pytest.mark.xfail(reason='broken test and/or code, original test missing assert', strict=False) def test_split_pre_existing_dir_one_level_exists(directory, expected, mocker): mocker.patch('os.path.exists', side_effect=[True, False, False]) assert split_pre_existing_dir(directory) == expected @pytest.mark.parametrize('directory', (d[0] for d in ONE_DIR_DATA if d[1] is None)) def test_split_pre_existing_dir_root_does_not_exist(directory, mocker): mocker.patch('os.path.exists', return_value=False) with pytest.raises(AnsibleModuleError) as excinfo: split_pre_existing_dir(directory) assert excinfo.value.results['msg'].startswith("The '/' directory doesn't exist on this machine.") @pytest.mark.parametrize('directory, expected', ((d[0], d[1]) for d in ONE_DIR_DATA if not d[0].startswith('/'))) @pytest.mark.xfail(reason='broken test and/or code, original test missing assert', strict=False) def test_split_pre_existing_dir_working_dir_exists(directory, expected, mocker): mocker.patch('os.path.exists', return_value=False) assert split_pre_existing_dir(directory) == expected # # Info helpful for making new test cases: # # base_mode = { # 'dir no perms': 0o040000, # 'file no perms': 0o100000, # 'dir all perms': 0o040000 | 0o777, # 'file all perms': 0o100000 | 0o777} # # perm_bits = { # 'x': 0b001, # 'w': 0b010, # 'r': 0b100} # # role_shift = { # 'u': 6, # 'g': 3, # 'o': 0} DATA = ( # Going from no permissions to setting all for user, group, and/or other (0o040000, u'a+rwx', 0o0777), (0o040000, u'u+rwx,g+rwx,o+rwx', 0o0777), (0o040000, u'o+rwx', 0o0007), (0o040000, u'g+rwx', 0o0070), (0o040000, u'u+rwx', 0o0700), # Going from all permissions to none for user, group, and/or other (0o040777, u'a-rwx', 0o0000), (0o040777, u'u-rwx,g-rwx,o-rwx', 0o0000), (0o040777, u'o-rwx', 0o0770), (0o040777, u'g-rwx', 0o0707), (0o040777, u'u-rwx', 0o0077), # now using absolute assignment from None to a set of perms (0o040000, u'a=rwx', 0o0777), (0o040000, u'u=rwx,g=rwx,o=rwx', 0o0777), (0o040000, u'o=rwx', 0o0007), (0o040000, u'g=rwx', 0o0070), (0o040000, u'u=rwx', 0o0700), # X effect on files and dirs (0o040000, u'a+X', 0o0111), (0o100000, u'a+X', 0), (0o040000, u'a=X', 0o0111), (0o100000, u'a=X', 0), (0o040777, u'a-X', 0o0666), # Same as chmod but is it a bug? # chmod a-X statfile <== removes execute from statfile (0o100777, u'a-X', 0o0666), # Verify X uses computed not original mode (0o100777, u'a=,u=rX', 0o0400), (0o040777, u'a=,u=rX', 0o0500), # Multiple permissions (0o040000, u'u=rw-x+X,g=r-x+X,o=r-x+X', 0o0755), (0o100000, u'u=rw-x+X,g=r-x+X,o=r-x+X', 0o0644), ) UMASK_DATA = ( (0o100000, '+rwx', 0o770), (0o100777, '-rwx', 0o007), ) INVALID_DATA = ( (0o040000, u'a=foo', "bad symbolic permission for mode: a=foo"), (0o040000, u'f=rwx', "bad symbolic permission for mode: f=rwx"), (0o100777, u'of=r', "bad symbolic permission for mode: of=r"), (0o100777, u'ao=r', "bad symbolic permission for mode: ao=r"), (0o100777, u'oa=r', "bad symbolic permission for mode: oa=r"), ) @pytest.mark.parametrize('stat_info, mode_string, expected', DATA) def test_good_symbolic_modes(mocker, stat_info, mode_string, expected): mock_stat = mocker.MagicMock() mock_stat.st_mode = stat_info assert AnsibleModule._symbolic_mode_to_octal(mock_stat, mode_string) == expected @pytest.mark.parametrize('stat_info, mode_string, expected', UMASK_DATA) def test_umask_with_symbolic_modes(mocker, stat_info, mode_string, expected): mock_umask = mocker.patch('os.umask') mock_umask.return_value = 0o7 mock_stat = mocker.MagicMock() mock_stat.st_mode = stat_info assert AnsibleModule._symbolic_mode_to_octal(mock_stat, mode_string) == expected @pytest.mark.parametrize('stat_info, mode_string, expected', INVALID_DATA) def test_invalid_symbolic_modes(mocker, stat_info, mode_string, expected): mock_stat = mocker.MagicMock() mock_stat.st_mode = stat_info with pytest.raises(ValueError) as exc: assert AnsibleModule._symbolic_mode_to_octal(mock_stat, mode_string) == 'blah' assert exc.match(expected)
7,825
Python
.py
194
36.015464
142
0.646912
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,814
test_uri.py
ansible_ansible/test/units/modules/test_uri.py
# -*- coding: utf-8 -*- # Copyright: # (c) 2023 Ansible Project # License: GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from unittest.mock import MagicMock, patch from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase, set_module_args from ansible.modules import uri class TestUri(ModuleTestCase): def test_main_no_args(self): """Module must fail if called with no args.""" with self.assertRaises(AnsibleFailJson): set_module_args({}) uri.main() def test_main_no_force(self): """The "force" parameter to fetch_url() must be absent or false when the module is called without "force".""" set_module_args({"url": "http://example.com/"}) resp = MagicMock() resp.headers.get_content_type.return_value = "text/html" info = {"url": "http://example.com/", "status": 200} with patch.object(uri, "fetch_url", return_value=(resp, info)) as fetch_url: with self.assertRaises(AnsibleExitJson): uri.main() fetch_url.assert_called_once() assert not fetch_url.call_args[1].get("force") def test_main_force(self): """The "force" parameter to fetch_url() must be true when the module is called with "force".""" set_module_args({"url": "http://example.com/", "force": True}) resp = MagicMock() resp.headers.get_content_type.return_value = "text/html" info = {"url": "http://example.com/", "status": 200} with patch.object(uri, "fetch_url", return_value=(resp, info)) as fetch_url: with self.assertRaises(AnsibleExitJson): uri.main() fetch_url.assert_called_once() assert fetch_url.call_args[1].get("force")
1,856
Python
.py
36
43.361111
117
0.639272
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,815
utils.py
ansible_ansible/test/units/modules/utils.py
from __future__ import annotations import json import unittest from unittest.mock import patch from ansible.module_utils import basic from ansible.module_utils.common.text.converters import to_bytes def set_module_args(args): args['_ansible_remote_tmp'] = '/tmp' args['_ansible_keep_remote_files'] = False args = json.dumps({'ANSIBLE_MODULE_ARGS': args}) basic._ANSIBLE_ARGS = to_bytes(args) class AnsibleExitJson(Exception): pass class AnsibleFailJson(Exception): pass def exit_json(*args, **kwargs): raise AnsibleExitJson(kwargs) def fail_json(*args, **kwargs): kwargs['failed'] = True raise AnsibleFailJson(kwargs) class ModuleTestCase(unittest.TestCase): def setUp(self): self.mock_module = patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json) self.mock_module.start() self.mock_sleep = patch('time.sleep') self.mock_sleep.start() set_module_args({}) self.addCleanup(self.mock_module.stop) self.addCleanup(self.mock_sleep.stop)
1,069
Python
.py
29
32
104
0.723633
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,816
test_service_facts.py
ansible_ansible/test/units/modules/test_service_facts.py
# -*- coding: utf-8 -*- # Copyright (c) 2020 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import unittest from unittest.mock import patch from ansible.module_utils import basic from ansible.modules.service_facts import AIXScanService # AIX # lssrc -a LSSRC_OUTPUT = """ Subsystem Group PID Status sendmail mail 5243302 active syslogd ras 5636528 active portmap portmap 5177768 active snmpd tcpip 5308844 active hostmibd tcpip 5374380 active snmpmibd tcpip 5439918 active aixmibd tcpip 5505456 active nimsh nimclient 5571004 active aso 6029758 active biod nfs 6357464 active nfsd nfs 5701906 active rpc.mountd nfs 6488534 active rpc.statd nfs 7209216 active rpc.lockd nfs 7274988 active qdaemon spooler 6816222 active writesrv spooler 6685150 active clcomd caa 7471600 active sshd ssh 7602674 active pfcdaemon 7012860 active ctrmc rsct 6947312 active IBM.HostRM rsct_rm 14418376 active IBM.ConfigRM rsct_rm 6160674 active IBM.DRM rsct_rm 14680550 active IBM.MgmtDomainRM rsct_rm 14090676 active IBM.ServiceRM rsct_rm 13828542 active cthats cthats 13959668 active cthags cthags 14025054 active IBM.StorageRM rsct_rm 12255706 active inetd tcpip 12517828 active lpd spooler inoperative keyserv keyserv inoperative ypbind yp inoperative gsclvmd inoperative cdromd inoperative ndpd-host tcpip inoperative ndpd-router tcpip inoperative netcd netcd inoperative tftpd tcpip inoperative routed tcpip inoperative mrouted tcpip inoperative rsvpd qos inoperative policyd qos inoperative timed tcpip inoperative iptrace tcpip inoperative dpid2 tcpip inoperative rwhod tcpip inoperative pxed tcpip inoperative binld tcpip inoperative xntpd tcpip inoperative gated tcpip inoperative dhcpcd tcpip inoperative dhcpcd6 tcpip inoperative dhcpsd tcpip inoperative dhcpsdv6 tcpip inoperative dhcprd tcpip inoperative dfpd tcpip inoperative named tcpip inoperative automountd autofs inoperative nfsrgyd nfs inoperative gssd nfs inoperative cpsd ike inoperative tmd ike inoperative isakmpd inoperative ikev2d inoperative iked ike inoperative clconfd caa inoperative ksys_vmmon inoperative nimhttp inoperative IBM.SRVPROXY ibmsrv inoperative ctcas rsct inoperative IBM.ERRM rsct_rm inoperative IBM.AuditRM rsct_rm inoperative isnstgtd isnstgtd inoperative IBM.LPRM rsct_rm inoperative cthagsglsm cthags inoperative """ class TestAIXScanService(unittest.TestCase): def setUp(self): self.mock1 = patch.object(basic.AnsibleModule, 'get_bin_path', return_value='/usr/sbin/lssrc') self.mock1.start() self.addCleanup(self.mock1.stop) self.mock2 = patch.object(basic.AnsibleModule, 'run_command', return_value=(0, LSSRC_OUTPUT, '')) self.mock2.start() self.addCleanup(self.mock2.stop) self.mock3 = patch('platform.system', return_value='AIX') self.mock3.start() self.addCleanup(self.mock3.stop) def test_gather_services(self): svcmod = AIXScanService(basic.AnsibleModule) result = svcmod.gather_services() self.assertIsInstance(result, dict) self.assertIn('IBM.HostRM', result) self.assertEqual(result['IBM.HostRM'], { 'name': 'IBM.HostRM', 'source': 'src', 'state': 'running', }) self.assertIn('IBM.AuditRM', result) self.assertEqual(result['IBM.AuditRM'], { 'name': 'IBM.AuditRM', 'source': 'src', 'state': 'stopped', })
5,915
Python
.py
114
48.166667
105
0.463558
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,817
test_async_wrapper.py
ansible_ansible/test/units/modules/test_async_wrapper.py
# Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import os import json import shutil import sys import tempfile from ansible.modules import async_wrapper class TestAsyncWrapper: def test_run_module(self, monkeypatch): def mock_get_interpreter(module_path): return [sys.executable] module_result = {'rc': 0} module_lines = [ 'import sys', 'sys.stderr.write("stderr stuff")', "print('%s')" % json.dumps(module_result) ] module_data = '\n'.join(module_lines) + '\n' module_data = module_data.encode('utf-8') workdir = tempfile.mkdtemp() fh, fn = tempfile.mkstemp(dir=workdir) with open(fn, 'wb') as f: f.write(module_data) command = fn jobid = 0 job_path = os.path.join(os.path.dirname(command), 'job') monkeypatch.setattr(async_wrapper, '_get_interpreter', mock_get_interpreter) monkeypatch.setattr(async_wrapper, 'job_path', job_path) res = async_wrapper._run_module(command, jobid) with open(os.path.join(workdir, 'job'), 'r') as f: jres = json.loads(f.read()) shutil.rmtree(workdir) assert jres.get('rc') == 0 assert jres.get('stderr') == 'stderr stuff'
1,415
Python
.py
36
31.527778
92
0.625092
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,818
mount_facts_data.py
ansible_ansible/test/units/modules/mount_facts_data.py
# Copyright: Contributors to the Ansible project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from dataclasses import dataclass @dataclass class LinuxData: fstab: str fstab_parsed: list[dict[str, str]] mtab: str mtab_parsed: list[dict[str, str]] mount: str mount_parsed: list[dict[str, str]] @dataclass class SolarisData: vfstab: str vfstab_parsed: list[dict[str, str]] mnttab: str mnttab_parsed: list[dict[str, str]] @dataclass class AIXData: filesystems: str filesystems_parsed: list[dict[str, str | dict[str, str]]] mount: str mount_parsed: list[dict[str, str]] freebsd_fstab = """# Custom /etc/fstab for FreeBSD VM images /dev/gpt/rootfs / ufs rw,acls 1 1 /dev/gpt/efiesp /boot/efi msdosfs rw 2 2""" freebsd_fstab_parsed = [ ( "/etc/fstab", "/", "/dev/gpt/rootfs / ufs rw,acls 1 1", { "device": "/dev/gpt/rootfs", "fstype": "ufs", "mount": "/", "options": "rw,acls", "dump": 1, "passno": 1, }, ), ( "/etc/fstab", "/boot/efi", "/dev/gpt/efiesp /boot/efi msdosfs rw 2 2", { "device": "/dev/gpt/efiesp", "fstype": "msdosfs", "mount": "/boot/efi", "options": "rw", "dump": 2, "passno": 2, }, ), ] freebsd_mount = """/dev/gpt/rootfs on / (ufs, local, soft-updates, acls) devfs on /dev (devfs) /dev/gpt/efiesp on /boot/efi (msdosfs, local)""" freebsd_mount_parsed = [ ( "mount", "/", "/dev/gpt/rootfs on / (ufs, local, soft-updates, acls)", { "device": "/dev/gpt/rootfs", "mount": "/", "fstype": "ufs", "options": "local, soft-updates, acls", }, ), ( "mount", "/dev", "devfs on /dev (devfs)", { "device": "devfs", "mount": "/dev", "fstype": "devfs", }, ), ( "mount", "/boot/efi", "/dev/gpt/efiesp on /boot/efi (msdosfs, local)", { "device": "/dev/gpt/efiesp", "mount": "/boot/efi", "fstype": "msdosfs", "options": "local", }, ), ] freebsd14_1 = LinuxData(freebsd_fstab, freebsd_fstab_parsed, "", [], freebsd_mount, freebsd_mount_parsed) rhel_fstab = """ UUID=6b8b920d-f334-426e-a440-1207d0d8725b / xfs defaults 0 0 UUID=3ecd4b07-f49a-410c-b7fc-6d1e7bb98ab9 /boot xfs defaults 0 0 UUID=7B77-95E7 /boot/efi vfat defaults,uid=0,gid=0,umask=077,shortname=winnt 0 2 """ rhel_fstab_parsed = [ ( "/etc/fstab", "/", "UUID=6b8b920d-f334-426e-a440-1207d0d8725b / xfs defaults 0 0", { "device": "UUID=6b8b920d-f334-426e-a440-1207d0d8725b", "mount": "/", "fstype": "xfs", "options": "defaults", "dump": 0, "passno": 0, }, ), ( "/etc/fstab", "/boot", "UUID=3ecd4b07-f49a-410c-b7fc-6d1e7bb98ab9 /boot xfs defaults 0 0", { "device": "UUID=3ecd4b07-f49a-410c-b7fc-6d1e7bb98ab9", "mount": "/boot", "fstype": "xfs", "options": "defaults", "dump": 0, "passno": 0, }, ), ( "/etc/fstab", "/boot/efi", "UUID=7B77-95E7 /boot/efi vfat defaults,uid=0,gid=0,umask=077,shortname=winnt 0 2", { "device": "UUID=7B77-95E7", "mount": "/boot/efi", "fstype": "vfat", "options": "defaults,uid=0,gid=0,umask=077,shortname=winnt", "dump": 0, "passno": 2, }, ), ] rhel_mtab = """proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0 /dev/nvme0n1p2 /boot ext4 rw,seclabel,relatime 0 0 systemd-1 /proc/sys/fs/binfmt_misc autofs rw,relatime,fd=33,pgrp=1,timeout=0,minproto=5,maxproto=5,direct,pipe_ino=33850 0 0 binfmt_misc /proc/sys/fs/binfmt_misc binfmt_misc rw,nosuid,nodev,noexec,relatime 0 0""" rhel_mtab_parsed = [ ( "/etc/mtab", "/proc", "proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0", { "device": "proc", "mount": "/proc", "fstype": "proc", "options": "rw,nosuid,nodev,noexec,relatime", "dump": 0, "passno": 0, }, ), ( "/etc/mtab", "/boot", "/dev/nvme0n1p2 /boot ext4 rw,seclabel,relatime 0 0", { "device": "/dev/nvme0n1p2", "mount": "/boot", "fstype": "ext4", "options": "rw,seclabel,relatime", "dump": 0, "passno": 0, }, ), ( "/etc/mtab", "/proc/sys/fs/binfmt_misc", "systemd-1 /proc/sys/fs/binfmt_misc autofs rw,relatime,fd=33,pgrp=1,timeout=0,minproto=5,maxproto=5,direct,pipe_ino=33850 0 0", { "device": "systemd-1", "mount": "/proc/sys/fs/binfmt_misc", "fstype": "autofs", "options": "rw,relatime,fd=33,pgrp=1,timeout=0,minproto=5,maxproto=5,direct,pipe_ino=33850", "dump": 0, "passno": 0, }, ), ( "/etc/mtab", "/proc/sys/fs/binfmt_misc", "binfmt_misc /proc/sys/fs/binfmt_misc binfmt_misc rw,nosuid,nodev,noexec,relatime 0 0", { "device": "binfmt_misc", "mount": "/proc/sys/fs/binfmt_misc", "fstype": "binfmt_misc", "options": "rw,nosuid,nodev,noexec,relatime", "dump": 0, "passno": 0, }, ), ] rhel_mount = """proc on /proc type proc (rw,nosuid,nodev,noexec,relatime) sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime,seclabel) devtmpfs on /dev type devtmpfs (rw,nosuid,seclabel,size=4096k,nr_inodes=445689,mode=755,inode64)""" rhel_mount_parsed = [ ( "mount", "/proc", "proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)", { "device": "proc", "mount": "/proc", "fstype": "proc", "options": "rw,nosuid,nodev,noexec,relatime", }, ), ( "mount", "/sys", "sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime,seclabel)", { "device": "sysfs", "mount": "/sys", "fstype": "sysfs", "options": "rw,nosuid,nodev,noexec,relatime,seclabel", }, ), ( "mount", "/dev", "devtmpfs on /dev type devtmpfs (rw,nosuid,seclabel,size=4096k,nr_inodes=445689,mode=755,inode64)", { "device": "devtmpfs", "mount": "/dev", "fstype": "devtmpfs", "options": "rw,nosuid,seclabel,size=4096k,nr_inodes=445689,mode=755,inode64", }, ), ] rhel9_4 = LinuxData(rhel_fstab, rhel_fstab_parsed, rhel_mtab, rhel_mtab_parsed, rhel_mount, rhel_mount_parsed) # https://www.ibm.com/docs/en/aix/7.3?topic=files-filesystems-file aix_filesystems = """* * File system information * default: vol = "OS" mount = false check = false /: dev = /dev/hd4 vol = "root" mount = automatic check = true log = /dev/hd8 /home: dev = /dev/hd1 vol = "u" mount = true check = true log = /dev/hd8 /home/joe/1: dev = /home/joe/1 nodename = vance vfs = nfs """ aix_filesystems_parsed = [ ( "/etc/filesystems", "default", 'default:\n vol = "OS"\n mount = false\n check = false', { "fstype": "unknown", "device": "unknown", "mount": "default", "attributes": { "mount": "false", "vol": '"OS"', "check": "false", }, }, ), ( "/etc/filesystems", "/", ( '/:' '\n dev = /dev/hd4' '\n vol = "root"' '\n mount = automatic' '\n check = true' '\n log = /dev/hd8' ), { "fstype": "unknown", "device": "/dev/hd4", "mount": "/", "attributes": { "mount": "automatic", "dev": "/dev/hd4", "vol": '"root"', "check": "true", "log": "/dev/hd8", }, }, ), ( "/etc/filesystems", "/home", ( '/home:' '\n dev = /dev/hd1' '\n vol = "u"' '\n mount = true' '\n check = true' '\n log = /dev/hd8' ), { "fstype": "unknown", "device": "/dev/hd1", "mount": "/home", "attributes": { "dev": "/dev/hd1", "vol": '"u"', "mount": "true", "check": "true", "log": "/dev/hd8", }, }, ), ( "/etc/filesystems", "/home/joe/1", '/home/joe/1:\n dev = /home/joe/1\n nodename = vance\n vfs = nfs', { "fstype": "nfs", "device": "vance:/home/joe/1", "mount": "/home/joe/1", "attributes": { "dev": "/home/joe/1", "nodename": "vance", "vfs": "nfs", }, }, ), ] # https://www.ibm.com/docs/en/aix/7.2?topic=m-mount-command aix_mount = """node mounted mounted over vfs date options\t ---- ------- ------------ --- ------------ ------------------- /dev/hd0 / jfs Dec 17 08:04 rw, log =/dev/hd8 /dev/hd2 /usr jfs Dec 17 08:06 rw, log =/dev/hd8 sue /home/local/src /usr/code nfs Dec 17 08:06 ro, log =/dev/hd8""" aix_mount_parsed = [ ( "mount", "/", " /dev/hd0 / jfs Dec 17 08:04 rw, log =/dev/hd8", { "mount": "/", "device": "/dev/hd0", "fstype": "jfs", "time": "Dec 17 08:04", "options": "rw, log =/dev/hd8", }, ), ( "mount", "/usr", " /dev/hd2 /usr jfs Dec 17 08:06 rw, log =/dev/hd8", { "mount": "/usr", "device": "/dev/hd2", "fstype": "jfs", "time": "Dec 17 08:06", "options": "rw, log =/dev/hd8", }, ), ( "mount", "/usr/code", "sue /home/local/src /usr/code nfs Dec 17 08:06 ro, log =/dev/hd8", { "mount": "/usr/code", "device": "sue:/home/local/src", "fstype": "nfs", "time": "Dec 17 08:06", "options": "ro, log =/dev/hd8", }, ), ] aix7_2 = AIXData(aix_filesystems, aix_filesystems_parsed, aix_mount, aix_mount_parsed) openbsd_fstab = """726d525601651a64.b none swap sw 726d525601651a64.a / ffs rw 1 1 726d525601651a64.k /home ffs rw,nodev,nosuid 1 2""" openbsd_fstab_parsed = [ ( "/etc/fstab", "none", "726d525601651a64.b none swap sw", { "device": "726d525601651a64.b", "fstype": "swap", "mount": "none", "options": "sw", }, ), ( "/etc/fstab", "/", "726d525601651a64.a / ffs rw 1 1", { "device": "726d525601651a64.a", "dump": 1, "fstype": "ffs", "mount": "/", "options": "rw", "passno": 1, }, ), ( "/etc/fstab", "/home", "726d525601651a64.k /home ffs rw,nodev,nosuid 1 2", { "device": "726d525601651a64.k", "dump": 1, "fstype": "ffs", "mount": "/home", "options": "rw,nodev,nosuid", "passno": 2, }, ), ] # Note: matches Linux mount format, like NetBSD openbsd_mount = """/dev/sd0a on / type ffs (local) /dev/sd0k on /home type ffs (local, nodev, nosuid) /dev/sd0e on /tmp type ffs (local, nodev, nosuid)""" openbsd_mount_parsed = [ ( "mount", "/", "/dev/sd0a on / type ffs (local)", { "device": "/dev/sd0a", "mount": "/", "fstype": "ffs", "options": "local" }, ), ( "mount", "/home", "/dev/sd0k on /home type ffs (local, nodev, nosuid)", { "device": "/dev/sd0k", "mount": "/home", "fstype": "ffs", "options": "local, nodev, nosuid", }, ), ( "mount", "/tmp", "/dev/sd0e on /tmp type ffs (local, nodev, nosuid)", { "device": "/dev/sd0e", "mount": "/tmp", "fstype": "ffs", "options": "local, nodev, nosuid", }, ), ] openbsd6_4 = LinuxData(openbsd_fstab, openbsd_fstab_parsed, "", [], openbsd_mount, openbsd_mount_parsed) solaris_vfstab = """#device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /dev/dsk/c2t10d0s0 /dev/rdsk/c2t10d0s0 /export/local ufs 3 yes logging example1:/usr/local - /usr/local nfs - yes ro mailsvr:/var/mail - /var/mail nfs - yes intr,bg""" solaris_vfstab_parsed = [ ( "/etc/vfstab", "/export/local", "/dev/dsk/c2t10d0s0 /dev/rdsk/c2t10d0s0 /export/local ufs 3 yes logging", { "device": "/dev/dsk/c2t10d0s0", "device_to_fsck": "/dev/rdsk/c2t10d0s0", "mount": "/export/local", "fstype": "ufs", "passno": 3, "mount_at_boot": "yes", "options": "logging", }, ), ( "/etc/vfstab", "/usr/local", "example1:/usr/local - /usr/local nfs - yes ro", { "device": "example1:/usr/local", "device_to_fsck": "-", "mount": "/usr/local", "fstype": "nfs", "passno": "-", "mount_at_boot": "yes", "options": "ro", }, ), ( "/etc/vfstab", "/var/mail", "mailsvr:/var/mail - /var/mail nfs - yes intr,bg", { "device": "mailsvr:/var/mail", "device_to_fsck": "-", "mount": "/var/mail", "fstype": "nfs", "passno": "-", "mount_at_boot": "yes", "options": "intr,bg", }, ), ] solaris_mnttab = """rpool/ROOT/solaris / zfs dev=4490002 0 -hosts /net autofs ignore,indirect,nosuid,soft,nobrowse,dev=4000002 1724055352 example.ansible.com:/export/nfs /mnt/nfs nfs xattr,dev=8e40010 1724055352""" solaris_mnttab_parsed = [ ( "/etc/mnttab", "/", "rpool/ROOT/solaris / zfs dev=4490002 0", { "device": "rpool/ROOT/solaris", "mount": "/", "fstype": "zfs", "options": "dev=4490002", "time": 0, }, ), ( "/etc/mnttab", "/net", "-hosts /net autofs ignore,indirect,nosuid,soft,nobrowse,dev=4000002 1724055352", { "device": "-hosts", "mount": "/net", "fstype": "autofs", "options": "ignore,indirect,nosuid,soft,nobrowse,dev=4000002", "time": 1724055352, }, ), ( "/etc/mnttab", "/mnt/nfs", "example.ansible.com:/export/nfs /mnt/nfs nfs xattr,dev=8e40010 1724055352", { "device": "example.ansible.com:/export/nfs", "mount": "/mnt/nfs", "fstype": "nfs", "options": "xattr,dev=8e40010", "time": 1724055352, }, ), ] solaris11_2 = SolarisData(solaris_vfstab, solaris_vfstab_parsed, solaris_mnttab, solaris_mnttab_parsed)
16,675
Python
.py
560
20.894643
135
0.456921
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,819
test_pip.py
ansible_ansible/test/units/modules/test_pip.py
# Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import json import pytest from ansible.modules import pip pytestmark = pytest.mark.usefixtures('patch_ansible_module') @pytest.mark.parametrize('patch_ansible_module', [{'name': 'six'}], indirect=['patch_ansible_module']) def test_failure_when_pip_absent(mocker, capfd): mocker.patch('ansible.modules.pip._have_pip_module').return_value = False get_bin_path = mocker.patch('ansible.module_utils.basic.AnsibleModule.get_bin_path') get_bin_path.return_value = None with pytest.raises(SystemExit): pip.main() out, err = capfd.readouterr() results = json.loads(out) assert results['failed'] assert 'pip needs to be installed' in results['msg'] @pytest.mark.parametrize('patch_ansible_module, test_input, expected', [ [None, ['django>1.11.1', '<1.11.2', 'ipaddress', 'simpleproject<2.0.0', '>1.1.0'], ['django>1.11.1,<1.11.2', 'ipaddress', 'simpleproject<2.0.0,>1.1.0']], [None, ['django>1.11.1,<1.11.2,ipaddress', 'simpleproject<2.0.0,>1.1.0'], ['django>1.11.1,<1.11.2', 'ipaddress', 'simpleproject<2.0.0,>1.1.0']], [None, ['django>1.11.1', '<1.11.2', 'ipaddress,simpleproject<2.0.0,>1.1.0'], ['django>1.11.1,<1.11.2', 'ipaddress', 'simpleproject<2.0.0,>1.1.0']]]) def test_recover_package_name(test_input, expected): assert pip._recover_package_name(test_input) == expected
1,528
Python
.py
27
52.185185
102
0.683009
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,820
test_known_hosts.py
ansible_ansible/test/units/modules/test_known_hosts.py
from __future__ import annotations import os import tempfile from ansible.module_utils import basic import unittest from ansible.module_utils.common.text.converters import to_bytes from ansible.module_utils.basic import AnsibleModule from ansible.modules.known_hosts import compute_diff, sanity_check class KnownHostsDiffTestCase(unittest.TestCase): def _create_file(self, content): tmp_file = tempfile.NamedTemporaryFile(prefix='ansible-test-', suffix='-known_hosts', delete=False) tmp_file.write(to_bytes(content)) tmp_file.close() self.addCleanup(os.unlink, tmp_file.name) return tmp_file.name def test_no_existing_file(self): path = "/tmp/this_file_does_not_exists_known_hosts" key = 'example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=None, replace_or_add=False, state='present', key=key) self.assertEqual(diff, { 'before_header': '/dev/null', 'after_header': path, 'before': '', 'after': 'example.com ssh-rsa AAAAetc\n', }) def test_key_addition(self): path = self._create_file( 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=None, replace_or_add=False, state='present', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'two.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\none.example.com ssh-rsa AAAAetc\n', }) def test_no_change(self): path = self._create_file( 'one.example.com ssh-rsa AAAAetc\n' 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=1, replace_or_add=False, state='present', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'one.example.com ssh-rsa AAAAetc\ntwo.example.com ssh-rsa BBBBetc\n', 'after': 'one.example.com ssh-rsa AAAAetc\ntwo.example.com ssh-rsa BBBBetc\n', }) def test_key_change(self): path = self._create_file( 'one.example.com ssh-rsa AAAaetc\n' 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=1, replace_or_add=True, state='present', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'one.example.com ssh-rsa AAAaetc\ntwo.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\none.example.com ssh-rsa AAAAetc\n', }) def test_key_removal(self): path = self._create_file( 'one.example.com ssh-rsa AAAAetc\n' 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=1, replace_or_add=False, state='absent', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'one.example.com ssh-rsa AAAAetc\ntwo.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\n', }) def test_key_removal_no_change(self): path = self._create_file( 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=None, replace_or_add=False, state='absent', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'two.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\n', }) def test_sanity_check(self): basic._load_params = lambda: {} # Module used internally to execute ssh-keygen system executable module = AnsibleModule(argument_spec={}) host = '10.0.0.1' key = '%s ssh-rsa ASDF foo@bar' % (host,) keygen = module.get_bin_path('ssh-keygen') sanity_check(module, host, key, keygen)
4,319
Python
.py
96
35.604167
107
0.612589
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,821
test_apt.py
ansible_ansible/test/units/modules/test_apt.py
# Copyright: Contributors to the Ansible project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import collections from ansible.modules.apt import expand_pkgspec_from_fnmatches import pytest FakePackage = collections.namedtuple("Package", ("name",)) fake_cache = [ FakePackage("apt"), FakePackage("apt-utils"), FakePackage("not-selected"), ] @pytest.mark.parametrize( ("test_input", "expected"), [ pytest.param( ["apt"], ["apt"], id="trivial", ), pytest.param( ["apt=1.0*"], ["apt=1.0*"], id="version-wildcard", ), pytest.param( ["apt*=1.0*"], ["apt", "apt-utils"], id="pkgname-wildcard-version", ), pytest.param( ["apt*"], ["apt", "apt-utils"], id="pkgname-expands", ), ], ) def test_expand_pkgspec_from_fnmatches(test_input, expected): """Test positive cases of ``expand_pkgspec_from_fnmatches``.""" assert expand_pkgspec_from_fnmatches(None, test_input, fake_cache) == expected
1,207
Python
.py
40
23.05
92
0.580895
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,822
test_unarchive.py
ansible_ansible/test/units/modules/test_unarchive.py
# Copyright: Contributors to the Ansible project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import time import pytest from ansible.modules.unarchive import ZipArchive, TgzArchive @pytest.fixture def fake_ansible_module(): return FakeAnsibleModule() class FakeAnsibleModule: def __init__(self): self.params = {} self.tmpdir = None class TestCaseZipArchive: @pytest.mark.parametrize( 'side_effect, expected_reason', ( ([ValueError, '/bin/zipinfo'], "Unable to find required 'unzip'"), (ValueError, "Unable to find required 'unzip' or 'zipinfo'"), ) ) def test_no_zip_zipinfo_binary(self, mocker, fake_ansible_module, side_effect, expected_reason): mocker.patch("ansible.modules.unarchive.get_bin_path", side_effect=side_effect) fake_ansible_module.params = { "extra_opts": "", "exclude": "", "include": "", "io_buffer_size": 65536, } z = ZipArchive( src="", b_dest="", file_args="", module=fake_ansible_module, ) can_handle, reason = z.can_handle_archive() assert can_handle is False assert expected_reason in reason assert z.cmd_path is None @pytest.mark.parametrize( ("test_input", "expected"), [ pytest.param( "19800000.000000", time.mktime(time.struct_time((1980, 0, 0, 0, 0, 0, 0, 0, 0))), id="invalid-month-1980", ), pytest.param( "19791231.000000", time.mktime(time.struct_time((1980, 1, 1, 0, 0, 0, 0, 0, 0))), id="invalid-year-1979", ), pytest.param( "19810101.000000", time.mktime(time.struct_time((1981, 1, 1, 0, 0, 0, 0, 0, 0))), id="valid-datetime", ), pytest.param( "21081231.000000", time.mktime(time.struct_time((2107, 12, 31, 23, 59, 59, 0, 0, 0))), id="invalid-year-2108", ), pytest.param( "INVALID_TIME_DATE", time.mktime(time.struct_time((1980, 1, 1, 0, 0, 0, 0, 0, 0))), id="invalid-datetime", ), ], ) def test_valid_time_stamp(self, mocker, fake_ansible_module, test_input, expected): mocker.patch( "ansible.modules.unarchive.get_bin_path", side_effect=["/bin/unzip", "/bin/zipinfo"], ) fake_ansible_module.params = { "extra_opts": "", "exclude": "", "include": "", "io_buffer_size": 65536, } z = ZipArchive( src="", b_dest="", file_args="", module=fake_ansible_module, ) assert z._valid_time_stamp(test_input) == expected class TestCaseTgzArchive: def test_no_tar_binary(self, mocker, fake_ansible_module): mocker.patch("ansible.modules.unarchive.get_bin_path", side_effect=ValueError) fake_ansible_module.params = { "extra_opts": "", "exclude": "", "include": "", "io_buffer_size": 65536, } fake_ansible_module.check_mode = False t = TgzArchive( src="", b_dest="", file_args="", module=fake_ansible_module, ) can_handle, reason = t.can_handle_archive() assert can_handle is False assert 'Unable to find required' in reason assert t.cmd_path is None assert t.tar_type is None
3,803
Python
.py
107
25
100
0.532753
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,823
test_debconf.py
ansible_ansible/test/units/modules/test_debconf.py
# Copyright: Contributors to the Ansible project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.modules.debconf import get_password_value password_testdata = [ pytest.param( ( "ddclient2 ddclient/password1 password Sample", "ddclient2", "ddclient/password1", "password", ), "Sample", id="valid_password", ), pytest.param( ( "ddclient2 ddclient/password1 password", "ddclient2", "ddclient/password1", "password", ), '', id="invalid_password", ), pytest.param( ( "ddclient2 ddclient/password password", "ddclient2", "ddclient/password1", "password", ), '', id="invalid_password_none", ), pytest.param( ( "ddclient2 ddclient/password", "ddclient2", "ddclient/password", "password", ), '', id="invalid_line", ), ] @pytest.mark.parametrize("test_input,expected", password_testdata) def test_get_password_value(mocker, test_input, expected): module = mocker.MagicMock() mocker.patch.object( module, "get_bin_path", return_value="/usr/bin/debconf-get-selections" ) mocker.patch.object(module, "run_command", return_value=(0, test_input[0], "")) res = get_password_value(module, *test_input[1:]) assert res == expected
1,610
Python
.py
56
20.767857
92
0.575953
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,824
test_service.py
ansible_ansible/test/units/modules/test_service.py
# Copyright: (c) 2021, Ansible Project # Copyright: (c) 2021, Abhijeet Kasurde <akasurde@redhat.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import json import platform import pytest from ansible.modules import service from ansible.module_utils.basic import AnsibleModule from units.modules.utils import set_module_args def mocker_sunos_service(mocker): """ Configure common mocker object for SunOSService """ platform_system = mocker.patch.object(platform, "system") platform_system.return_value = "SunOS" get_bin_path = mocker.patch.object(AnsibleModule, "get_bin_path") get_bin_path.return_value = "/usr/bin/svcs" # Read a mocked /etc/release file mocked_etc_release_data = mocker.mock_open( read_data=" Oracle Solaris 12.0") builtin_open = "builtins.open" mocker.patch(builtin_open, mocked_etc_release_data) service_status = mocker.patch.object( service.Service, "modify_service_state") service_status.return_value = (0, "", "") get_sunos_svcs_status = mocker.patch.object( service.SunOSService, "get_sunos_svcs_status") get_sunos_svcs_status.return_value = "offline" get_service_status = mocker.patch.object( service.Service, "get_service_status") get_service_status.return_value = "" mocker.patch('ansible.module_utils.common.sys_info.distro.id', return_value='') @pytest.fixture def mocked_sunos_service(mocker): mocker_sunos_service(mocker) def test_sunos_service_start(mocked_sunos_service, capfd): """ test SunOS Service Start """ set_module_args( { "name": "environment", "state": "started", } ) with pytest.raises(SystemExit): service.main() out, dummy = capfd.readouterr() results = json.loads(out) assert not results.get("failed") assert results["changed"]
1,971
Python
.py
52
32.826923
92
0.702575
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,825
conftest.py
ansible_ansible/test/units/module_utils/conftest.py
# Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import json import sys from io import BytesIO import pytest import ansible.module_utils.basic from ansible.module_utils.common.text.converters import to_bytes from collections.abc import MutableMapping @pytest.fixture def stdin(mocker, request): old_args = ansible.module_utils.basic._ANSIBLE_ARGS ansible.module_utils.basic._ANSIBLE_ARGS = None old_argv = sys.argv sys.argv = ['ansible_unittest'] if isinstance(request.param, str): args = request.param elif isinstance(request.param, MutableMapping): if 'ANSIBLE_MODULE_ARGS' not in request.param: request.param = {'ANSIBLE_MODULE_ARGS': request.param} if '_ansible_remote_tmp' not in request.param['ANSIBLE_MODULE_ARGS']: request.param['ANSIBLE_MODULE_ARGS']['_ansible_remote_tmp'] = '/tmp' if '_ansible_keep_remote_files' not in request.param['ANSIBLE_MODULE_ARGS']: request.param['ANSIBLE_MODULE_ARGS']['_ansible_keep_remote_files'] = False args = json.dumps(request.param) else: raise Exception('Malformed data to the stdin pytest fixture') fake_stdin = BytesIO(to_bytes(args, errors='surrogate_or_strict')) mocker.patch('ansible.module_utils.basic.sys.stdin', mocker.MagicMock()) mocker.patch('ansible.module_utils.basic.sys.stdin.buffer', fake_stdin) yield fake_stdin ansible.module_utils.basic._ANSIBLE_ARGS = old_args sys.argv = old_argv @pytest.fixture def am(stdin, request): old_args = ansible.module_utils.basic._ANSIBLE_ARGS ansible.module_utils.basic._ANSIBLE_ARGS = None old_argv = sys.argv sys.argv = ['ansible_unittest'] argspec = {} if hasattr(request, 'param'): if isinstance(request.param, dict): argspec = request.param am = ansible.module_utils.basic.AnsibleModule( argument_spec=argspec, ) am._name = 'ansible_unittest' yield am ansible.module_utils.basic._ANSIBLE_ARGS = old_args sys.argv = old_argv
2,169
Python
.py
51
37.039216
92
0.709186
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,826
test_distro.py
ansible_ansible/test/units/module_utils/test_distro.py
# (c) 2018 Adrian Likins <alikins@redhat.com> # Copyright (c) 2018 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # or # Apache License v2.0 (see http://www.apache.org/licenses/LICENSE-2.0) # # Dual licensed so any test cases could potentially be included by the upstream project # that module_utils/distro.py is from (https://github.com/nir0s/distro) # Note that nir0s/distro has many more tests in it's test suite. The tests here are # primarily for testing the vendoring. from __future__ import annotations from ansible.module_utils import distro # Generic test case with minimal assertions about specific returned values. class TestDistro(): # should run on any platform without errors, even if non-linux without any # useful info to return def test_info(self): info = distro.info() assert isinstance(info, dict), \ 'distro.info() returned %s (%s) which is not a dist' % (info, type(info)) def test_id(self): id = distro.id() assert isinstance(id, str), 'distro.id() returned %s (%s) which is not a string' % (id, type(id))
1,159
Python
.py
23
46.434783
105
0.715426
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,827
test_api.py
ansible_ansible/test/units/module_utils/test_api.py
# -*- coding: utf-8 -*- # Copyright: (c) 2020, Abhijeet Kasurde <akasurde@redhat.com> # Copyright: (c) 2020, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from ansible.module_utils.api import rate_limit, retry, retry_with_delays_and_condition import pytest class CustomException(Exception): pass class CustomBaseException(BaseException): pass class TestRateLimit: def test_ratelimit(self): @rate_limit(rate=1, rate_limit=1) def login_database(): return "success" r = login_database() assert r == 'success' class TestRetry: def test_no_retry_required(self): @retry(retries=4, retry_pause=2) def login_database(): login_database.counter += 1 return 'success' login_database.counter = 0 r = login_database() assert r == 'success' assert login_database.counter == 1 def test_catch_exception(self): @retry(retries=1) def login_database(): return 'success' with pytest.raises(Exception, match="Retry"): login_database() def test_no_retries(self): @retry() def login_database(): assert False, "Should not execute" login_database() class TestRetryWithDelaysAndCondition: def test_empty_retry_iterator(self): @retry_with_delays_and_condition(backoff_iterator=[]) def login_database(): login_database.counter += 1 login_database.counter = 0 r = login_database() assert login_database.counter == 1 def test_no_retry_exception(self): @retry_with_delays_and_condition( backoff_iterator=[1], should_retry_error=lambda x: False, ) def login_database(): login_database.counter += 1 if login_database.counter == 1: raise CustomException("Error") login_database.counter = 0 with pytest.raises(CustomException, match="Error"): login_database() assert login_database.counter == 1 def test_no_retry_baseexception(self): @retry_with_delays_and_condition( backoff_iterator=[1], should_retry_error=lambda x: True, # Retry all exceptions inheriting from Exception ) def login_database(): login_database.counter += 1 if login_database.counter == 1: # Raise an exception inheriting from BaseException raise CustomBaseException("Error") login_database.counter = 0 with pytest.raises(CustomBaseException, match="Error"): login_database() assert login_database.counter == 1 def test_retry_exception(self): @retry_with_delays_and_condition( backoff_iterator=[1], should_retry_error=lambda x: isinstance(x, CustomException), ) def login_database(): login_database.counter += 1 if login_database.counter == 1: raise CustomException("Retry") return 'success' login_database.counter = 0 assert login_database() == 'success' assert login_database.counter == 2
3,336
Python
.py
87
29.149425
96
0.622512
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,828
test_text.py
ansible_ansible/test/units/module_utils/test_text.py
from __future__ import annotations import codecs from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text def test_exports(): """Ensure legacy attributes are exported.""" from ansible.module_utils import _text assert _text.codecs == codecs assert _text.PY3 is True assert _text.text_type is str assert _text.binary_type is bytes assert _text.to_bytes == to_bytes assert _text.to_native == to_native assert _text.to_text == to_text
501
Python
.py
13
34.307692
84
0.726141
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,829
test_connection.py
ansible_ansible/test/units/module_utils/test_connection.py
# -*- coding: utf-8 -*- # Copyright: (c) 2021, Matt Martz <matt@sivel.net> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from ansible.module_utils import connection import pytest def test_set_options_credential_exposure(): def send(data): return '{' c = connection.Connection(connection.__file__) c.send = send with pytest.raises(connection.ConnectionError) as excinfo: c._exec_jsonrpc('set_options', become_pass='password') assert 'password' not in str(excinfo.value)
594
Python
.py
14
38.357143
92
0.715532
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,830
test_convert_bool.py
ansible_ansible/test/units/module_utils/parsing/test_convert_bool.py
# -*- coding: utf-8 -*- # Copyright: (c) 2017 Ansible Project # License: GNU General Public License v3 or later (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt ) from __future__ import annotations import pytest from ansible.module_utils.parsing.convert_bool import boolean junk_values = ("flibbity", 42, 42.0, object(), None, 2, -1, 0.1) @pytest.mark.parametrize(("value", "expected"), [ (True, True), (False, False), (1, True), (0, False), (0.0, False), ("true", True), ("TRUE", True), ("t", True), ("yes", True), ("y", True), ("on", True), ]) def test_boolean(value: object, expected: bool) -> None: assert boolean(value) is expected @pytest.mark.parametrize("value", junk_values) def test_junk_values_non_strict(value: object) -> None: assert boolean(value, strict=False) is False @pytest.mark.parametrize("value", junk_values) def test_junk_values_strict(value: object) -> None: with pytest.raises(TypeError, match=f"^The value '{value}' is not"): boolean(value, strict=True)
1,064
Python
.py
29
33.103448
108
0.667969
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,831
test_network.py
ansible_ansible/test/units/module_utils/common/test_network.py
# -*- coding: utf-8 -*- # (c) 2017 Red Hat, Inc. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.network import ( to_bits, to_masklen, to_netmask, to_subnet, to_ipv6_network, is_masklen, is_netmask ) def test_to_masklen(): assert 24 == to_masklen('255.255.255.0') def test_to_masklen_invalid(): with pytest.raises(ValueError): to_masklen('255') def test_to_netmask(): assert '255.0.0.0' == to_netmask(8) assert '255.0.0.0' == to_netmask('8') def test_to_netmask_invalid(): with pytest.raises(ValueError): to_netmask(128) def test_to_subnet(): result = to_subnet('192.168.1.1', 24) assert '192.168.1.0/24' == result result = to_subnet('192.168.1.1', 24, dotted_notation=True) assert '192.168.1.0 255.255.255.0' == result def test_to_subnet_invalid(): with pytest.raises(ValueError): to_subnet('foo', 'bar') def test_is_masklen(): assert is_masklen(32) assert not is_masklen(33) assert not is_masklen('foo') def test_is_netmask(): assert is_netmask('255.255.255.255') assert not is_netmask(24) assert not is_netmask('foo') def test_to_ipv6_network(): assert '2001:db8::' == to_ipv6_network('2001:db8::') assert '2001:0db8:85a3::' == to_ipv6_network('2001:0db8:85a3:0000:0000:8a2e:0370:7334') assert '2001:0db8:85a3::' == to_ipv6_network('2001:0db8:85a3:0:0:8a2e:0370:7334') def test_to_bits(): assert to_bits('0') == '00000000' assert to_bits('1') == '00000001' assert to_bits('2') == '00000010' assert to_bits('1337') == '10100111001' assert to_bits('127.0.0.1') == '01111111000000000000000000000001' assert to_bits('255.255.255.255') == '11111111111111111111111111111111' assert to_bits('255.255.255.0') == '11111111111111111111111100000000'
1,949
Python
.py
53
32.377358
92
0.667201
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,832
test_utils.py
ansible_ansible/test/units/module_utils/common/test_utils.py
# -*- coding: utf-8 -*- # (c) 2018 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from ansible.module_utils.common.sys_info import get_all_subclasses # # Tests for get_all_subclasses # class TestGetAllSubclasses: class Base: pass class BranchI(Base): pass class BranchII(Base): pass class BranchIA(BranchI): pass class BranchIB(BranchI): pass class BranchIIA(BranchII): pass class BranchIIB(BranchII): pass def test_bottom_level(self): assert get_all_subclasses(self.BranchIIB) == set() def test_one_inheritance(self): assert set(get_all_subclasses(self.BranchII)) == set([self.BranchIIA, self.BranchIIB]) def test_toplevel(self): assert set(get_all_subclasses(self.Base)) == set([self.BranchI, self.BranchII, self.BranchIA, self.BranchIB, self.BranchIIA, self.BranchIIB])
1,120
Python
.py
31
27.064516
94
0.616744
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,833
test_dict_transformations.py
ansible_ansible/test/units/module_utils/common/test_dict_transformations.py
# -*- coding: utf-8 -*- # Copyright: (c) 2017, Will Thames <will.thames@xvt.com.au> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.dict_transformations import ( _camel_to_snake, _snake_to_camel, camel_dict_to_snake_dict, dict_merge, recursive_diff, ) EXPECTED_SNAKIFICATION = { 'alllower': 'alllower', 'TwoWords': 'two_words', 'AllUpperAtEND': 'all_upper_at_end', 'AllUpperButPLURALs': 'all_upper_but_plurals', 'TargetGroupARNs': 'target_group_arns', 'HTTPEndpoints': 'http_endpoints', 'PLURALs': 'plurals' } EXPECTED_REVERSIBLE = { 'TwoWords': 'two_words', 'AllUpperAtEND': 'all_upper_at_e_n_d', 'AllUpperButPLURALs': 'all_upper_but_p_l_u_r_a_ls', 'TargetGroupARNs': 'target_group_a_r_ns', 'HTTPEndpoints': 'h_t_t_p_endpoints', 'PLURALs': 'p_l_u_r_a_ls' } class TestCaseCamelToSnake: def test_camel_to_snake(self): for (k, v) in EXPECTED_SNAKIFICATION.items(): assert _camel_to_snake(k) == v def test_reversible_camel_to_snake(self): for (k, v) in EXPECTED_REVERSIBLE.items(): assert _camel_to_snake(k, reversible=True) == v class TestCaseSnakeToCamel: def test_snake_to_camel_reversed(self): for (k, v) in EXPECTED_REVERSIBLE.items(): assert _snake_to_camel(v, capitalize_first=True) == k class TestCaseCamelToSnakeAndBack: def test_camel_to_snake_and_back(self): for (k, v) in EXPECTED_REVERSIBLE.items(): assert _snake_to_camel(_camel_to_snake(k, reversible=True), capitalize_first=True) == k class TestCaseCamelDictToSnakeDict: def test_ignore_list(self): camel_dict = dict(Hello=dict(One='one', Two='two'), World=dict(Three='three', Four='four')) snake_dict = camel_dict_to_snake_dict(camel_dict, ignore_list='World') assert snake_dict['hello'] == dict(one='one', two='two') assert snake_dict['world'] == dict(Three='three', Four='four') class TestCaseDictMerge: def test_dict_merge(self): base = dict(obj2=dict(), b1=True, b2=False, b3=False, one=1, two=2, three=3, obj1=dict(key1=1, key2=2), l1=[1, 3], l2=[1, 2, 3], l4=[4], nested=dict(n1=dict(n2=2))) other = dict(b1=True, b2=False, b3=True, b4=True, one=1, three=4, four=4, obj1=dict(key1=2), l1=[2, 1], l2=[3, 2, 1], l3=[1], nested=dict(n1=dict(n2=2, n3=3))) result = dict_merge(base, other) # string assertions assert 'one' in result assert 'two' in result assert result['three'] == 4 assert result['four'] == 4 # dict assertions assert 'obj1' in result assert 'key1' in result['obj1'] assert 'key2' in result['obj1'] # list assertions # this line differs from the network_utils/common test of the function of the # same name as this method does not merge lists assert result['l1'], [2, 1] assert 'l2' in result assert result['l3'], [1] assert 'l4' in result # nested assertions assert 'obj1' in result assert result['obj1']['key1'], 2 assert 'key2' in result['obj1'] # bool assertions assert 'b1' in result assert 'b2' in result assert result['b3'] assert result['b4'] class TestCaseAzureIncidental: def test_dict_merge_invalid_dict(self): """ if b is not a dict, return b """ res = dict_merge({}, None) assert res is None def test_merge_sub_dicts(self): """merge sub dicts """ a = {'a': {'a1': 1}} b = {'a': {'b1': 2}} c = {'a': {'a1': 1, 'b1': 2}} res = dict_merge(a, b) assert res == c class TestCaseRecursiveDiff: def test_recursive_diff(self): a = {'foo': {'bar': [{'baz': {'qux': 'ham_sandwich'}}]}} c = {'foo': {'bar': [{'baz': {'qux': 'ham_sandwich'}}]}} b = {'foo': {'bar': [{'baz': {'qux': 'turkey_sandwich'}}]}} assert recursive_diff(a, b) is not None assert len(recursive_diff(a, b)) == 2 assert recursive_diff(a, c) is None @pytest.mark.parametrize( 'p1, p2', ( ([1, 2], [2, 3]), ({1: 2}, [2, 3]), ([1, 2], {2: 3}), ({2: 3}, 'notadict'), ('notadict', {2: 3}), ) ) def test_recursive_diff_negative(self, p1, p2): with pytest.raises(TypeError, match="Unable to diff"): recursive_diff(p1, p2)
4,724
Python
.py
118
32.008475
99
0.580052
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,834
test_collections.py
ansible_ansible/test/units/module_utils/common/test_collections.py
# -*- coding: utf-8 -*- # Copyright (c) 2018–2019, Sviatoslav Sydorenko <webknjaz@redhat.com> # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) """Test low-level utility functions from ``module_utils.common.collections``.""" from __future__ import annotations import pytest from collections.abc import Sequence from ansible.module_utils.common.collections import ImmutableDict, is_iterable, is_sequence class SeqStub: """Stub emulating a sequence type. >>> from collections.abc import Sequence >>> assert issubclass(SeqStub, Sequence) >>> assert isinstance(SeqStub(), Sequence) """ Sequence.register(SeqStub) class FakeAnsibleVaultEncryptedUnicode(Sequence): __ENCRYPTED__ = True def __init__(self, data): self.data = data def __getitem__(self, index): raise NotImplementedError() # pragma: nocover def __len__(self): raise NotImplementedError() # pragma: nocover TEST_STRINGS = u'he', u'Україна', u'Česká republika' TEST_STRINGS = TEST_STRINGS + tuple(s.encode('utf-8') for s in TEST_STRINGS) + (FakeAnsibleVaultEncryptedUnicode(u'foo'),) TEST_ITEMS_NON_SEQUENCES: tuple = ( {}, object(), frozenset(), 4, 0., ) + TEST_STRINGS TEST_ITEMS_SEQUENCES: tuple = ( [], (), SeqStub(), # Iterable effectively containing nested random data: TEST_ITEMS_NON_SEQUENCES, ) @pytest.mark.parametrize('sequence_input', TEST_ITEMS_SEQUENCES) def test_sequence_positive(sequence_input): """Test that non-string item sequences are identified correctly.""" assert is_sequence(sequence_input) assert is_sequence(sequence_input, include_strings=False) @pytest.mark.parametrize('non_sequence_input', TEST_ITEMS_NON_SEQUENCES) def test_sequence_negative(non_sequence_input): """Test that non-sequences are identified correctly.""" assert not is_sequence(non_sequence_input) @pytest.mark.parametrize('string_input', TEST_STRINGS) def test_sequence_string_types_with_strings(string_input): """Test that ``is_sequence`` can separate string and non-string.""" assert is_sequence(string_input, include_strings=True) @pytest.mark.parametrize('string_input', TEST_STRINGS) def test_sequence_string_types_without_strings(string_input): """Test that ``is_sequence`` can separate string and non-string.""" assert not is_sequence(string_input, include_strings=False) @pytest.mark.parametrize( 'seq', ([], (), {}, set(), frozenset()), ) def test_iterable_positive(seq): assert is_iterable(seq) @pytest.mark.parametrize( 'seq', (object(), 5, 9.) ) def test_iterable_negative(seq): assert not is_iterable(seq) @pytest.mark.parametrize('string_input', TEST_STRINGS) def test_iterable_including_strings(string_input): assert is_iterable(string_input, include_strings=True) @pytest.mark.parametrize('string_input', TEST_STRINGS) def test_iterable_excluding_strings(string_input): assert not is_iterable(string_input, include_strings=False) class TestImmutableDict: def test_scalar(self): imdict = ImmutableDict({1: 2}) assert imdict[1] == 2 def test_string(self): imdict = ImmutableDict({u'café': u'くらとみ'}) assert imdict[u'café'] == u'くらとみ' def test_container(self): imdict = ImmutableDict({(1, 2): ['1', '2']}) assert imdict[(1, 2)] == ['1', '2'] def test_from_tuples(self): imdict = ImmutableDict((('a', 1), ('b', 2))) assert frozenset(imdict.items()) == frozenset((('a', 1), ('b', 2))) def test_from_kwargs(self): imdict = ImmutableDict(a=1, b=2) assert frozenset(imdict.items()) == frozenset((('a', 1), ('b', 2))) def test_immutable(self): imdict = ImmutableDict({1: 2}) expected_reason = r"^'ImmutableDict' object does not support item assignment$" with pytest.raises(TypeError, match=expected_reason): imdict[1] = 3 with pytest.raises(TypeError, match=expected_reason): imdict[5] = 3 def test_hashable(self): # ImmutableDict is hashable when all of its values are hashable imdict = ImmutableDict({u'café': u'くらとみ'}) assert hash(imdict) def test_nonhashable(self): # ImmutableDict is unhashable when one of its values is unhashable imdict = ImmutableDict({u'café': u'くらとみ', 1: [1, 2]}) expected_reason = r"^unhashable type: 'list'$" with pytest.raises(TypeError, match=expected_reason): hash(imdict) def test_len(self): imdict = ImmutableDict({1: 2, 'a': 'b'}) assert len(imdict) == 2 def test_repr(self): initial_data = {1: 2, 'a': 'b'} initial_data_repr = repr(initial_data) imdict = ImmutableDict(initial_data) actual_repr = repr(imdict) expected_repr = "ImmutableDict({0})".format(initial_data_repr) assert actual_repr == expected_repr
5,015
Python
.py
112
38.848214
122
0.684835
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,835
test_sys_info.py
ansible_ansible/test/units/module_utils/common/test_sys_info.py
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016 Toshio Kuratomi <tkuratomi@ansible.com> # (c) 2017-2018 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from unittest.mock import patch import builtins # Functions being tested from ansible.module_utils.common.sys_info import get_distribution from ansible.module_utils.common.sys_info import get_distribution_version from ansible.module_utils.common.sys_info import get_platform_subclass realimport = builtins.__import__ @pytest.fixture def platform_linux(mocker): mocker.patch('platform.system', return_value='Linux') # # get_distribution tests # @pytest.mark.parametrize( ('system', 'dist'), ( ('Darwin', 'Darwin'), ('SunOS', 'Solaris'), ('FreeBSD', 'Freebsd'), ), ) def test_get_distribution_not_linux(system, dist, mocker): """For platforms other than Linux, return the distribution""" mocker.patch('platform.system', return_value=system) mocker.patch('ansible.module_utils.common.sys_info.distro.id', return_value=dist) assert get_distribution() == dist @pytest.mark.usefixtures("platform_linux") class TestGetDistribution: """Tests for get_distribution that have to find something""" def test_distro_known(self): with patch('ansible.module_utils.distro.id', return_value="alpine"): assert get_distribution() == "Alpine" with patch('ansible.module_utils.distro.id', return_value="arch"): assert get_distribution() == "Arch" with patch('ansible.module_utils.distro.id', return_value="centos"): assert get_distribution() == "Centos" with patch('ansible.module_utils.distro.id', return_value="clear-linux-os"): assert get_distribution() == "Clear-linux-os" with patch('ansible.module_utils.distro.id', return_value="coreos"): assert get_distribution() == "Coreos" with patch('ansible.module_utils.distro.id', return_value="debian"): assert get_distribution() == "Debian" with patch('ansible.module_utils.distro.id', return_value="flatcar"): assert get_distribution() == "Flatcar" with patch('ansible.module_utils.distro.id', return_value="linuxmint"): assert get_distribution() == "Linuxmint" with patch('ansible.module_utils.distro.id', return_value="opensuse"): assert get_distribution() == "Opensuse" with patch('ansible.module_utils.distro.id', return_value="oracle"): assert get_distribution() == "Oracle" with patch('ansible.module_utils.distro.id', return_value="raspian"): assert get_distribution() == "Raspian" with patch('ansible.module_utils.distro.id', return_value="rhel"): assert get_distribution() == "Redhat" with patch('ansible.module_utils.distro.id', return_value="ubuntu"): assert get_distribution() == "Ubuntu" with patch('ansible.module_utils.distro.id', return_value="virtuozzo"): assert get_distribution() == "Virtuozzo" with patch('ansible.module_utils.distro.id', return_value="foo"): assert get_distribution() == "Foo" def test_distro_unknown(self): with patch('ansible.module_utils.distro.id', return_value=""): assert get_distribution() == "OtherLinux" def test_distro_amazon_linux_short(self): with patch('ansible.module_utils.distro.id', return_value="amzn"): assert get_distribution() == "Amazon" def test_distro_amazon_linux_long(self): with patch('ansible.module_utils.distro.id', return_value="amazon"): assert get_distribution() == "Amazon" # # get_distribution_version tests # @pytest.mark.parametrize( ('system', 'version'), ( ('Darwin', '19.6.0'), ('SunOS', '11.4'), ('FreeBSD', '12.1'), ), ) def test_get_distribution_version_not_linux(mocker, system, version): """If it's not Linux, then it has no distribution""" mocker.patch('platform.system', return_value=system) mocker.patch('ansible.module_utils.common.sys_info.distro.version', return_value=version) assert get_distribution_version() == version @pytest.mark.usefixtures("platform_linux") def test_distro_found(): with patch('ansible.module_utils.distro.version', return_value="1"): assert get_distribution_version() == "1" # # Tests for get_platform_subclass # class TestGetPlatformSubclass: class LinuxTest: pass class Foo(LinuxTest): platform = "Linux" distribution = None class Bar(LinuxTest): platform = "Linux" distribution = "Bar" def test_not_linux(self): # if neither match, the fallback should be the top-level class with patch('platform.system', return_value="Foo"): with patch('ansible.module_utils.common.sys_info.get_distribution', return_value=None): assert get_platform_subclass(self.LinuxTest) is self.LinuxTest @pytest.mark.usefixtures("platform_linux") def test_get_distribution_none(self): # match just the platform class, not a specific distribution with patch('ansible.module_utils.common.sys_info.get_distribution', return_value=None): assert get_platform_subclass(self.LinuxTest) is self.Foo @pytest.mark.usefixtures("platform_linux") def test_get_distribution_found(self): # match both the distribution and platform class with patch('ansible.module_utils.common.sys_info.get_distribution', return_value="Bar"): assert get_platform_subclass(self.LinuxTest) is self.Bar
5,812
Python
.py
123
40.430894
99
0.679362
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,836
test_locale.py
ansible_ansible/test/units/module_utils/common/test_locale.py
# -*- coding: utf-8 -*- # (c) Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from unittest.mock import MagicMock from ansible.module_utils.common.locale import get_best_parsable_locale class TestLocale: """Tests for get_best_parsable_locale""" mock_module = MagicMock() mock_module.get_bin_path = MagicMock(return_value='/usr/bin/locale') def test_finding_best(self): self.mock_module.run_command = MagicMock(return_value=(0, "C.utf8\nen_US.utf8\nC\nPOSIX\n", '')) locale = get_best_parsable_locale(self.mock_module) assert locale == 'C.utf8' def test_finding_last(self): self.mock_module.run_command = MagicMock(return_value=(0, "fr_FR.utf8\nen_UK.utf8\nC\nPOSIX\n", '')) locale = get_best_parsable_locale(self.mock_module) assert locale == 'C' def test_finding_middle(self): self.mock_module.run_command = MagicMock(return_value=(0, "fr_FR.utf8\nen_US.utf8\nC\nPOSIX\n", '')) locale = get_best_parsable_locale(self.mock_module) assert locale == 'en_US.utf8' def test_finding_prefered(self): self.mock_module.run_command = MagicMock(return_value=(0, "es_ES.utf8\nMINE\nC\nPOSIX\n", '')) locale = get_best_parsable_locale(self.mock_module, preferences=['MINE', 'C.utf8']) assert locale == 'MINE' def test_finding_C_on_no_match(self): self.mock_module.run_command = MagicMock(return_value=(0, "fr_FR.UTF8\nMINE\n", '')) locale = get_best_parsable_locale(self.mock_module) assert locale == 'C'
1,652
Python
.py
30
48.633333
108
0.675978
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,837
test_warn.py
ansible_ansible/test/units/module_utils/common/warnings/test_warn.py
# -*- coding: utf-8 -*- # (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common import warnings from ansible.module_utils.common.warnings import warn, get_warning_messages @pytest.fixture def warning_messages(): return [ 'First warning', 'Second warning', 'Third warning', ] def test_warn(): warn('Warning message') assert warnings._global_warnings == ['Warning message'] def test_multiple_warnings(warning_messages): for w in warning_messages: warn(w) assert warning_messages == warnings._global_warnings def test_get_warning_messages(warning_messages): for w in warning_messages: warn(w) accessor_warnings = get_warning_messages() assert isinstance(accessor_warnings, tuple) assert len(accessor_warnings) == 3 @pytest.mark.parametrize( 'test_case', ( 1, True, [1], {'k1': 'v1'}, (1, 2), 6.62607004, b'bytestr', None, ) ) def test_warn_failure(test_case): with pytest.raises(TypeError, match='warn requires a string not a %s' % type(test_case)): warn(test_case)
1,293
Python
.py
43
24.790698
93
0.666937
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,838
test_deprecate.py
ansible_ansible/test/units/module_utils/common/warnings/test_deprecate.py
# -*- coding: utf-8 -*- # (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common import warnings from ansible.module_utils.common.warnings import deprecate, get_deprecation_messages @pytest.fixture def deprecation_messages(): return [ {'msg': 'First deprecation', 'version': None, 'collection_name': None}, {'msg': 'Second deprecation', 'version': None, 'collection_name': 'ansible.builtin'}, {'msg': 'Third deprecation', 'version': '2.14', 'collection_name': None}, {'msg': 'Fourth deprecation', 'version': '2.9', 'collection_name': None}, {'msg': 'Fifth deprecation', 'version': '2.9', 'collection_name': 'ansible.builtin'}, {'msg': 'Sixth deprecation', 'date': '2199-12-31', 'collection_name': None}, {'msg': 'Seventh deprecation', 'date': '2199-12-31', 'collection_name': 'ansible.builtin'}, ] @pytest.fixture def reset(monkeypatch): monkeypatch.setattr(warnings, '_global_deprecations', []) def test_deprecate_message_only(reset): deprecate('Deprecation message') # pylint: disable=ansible-deprecated-no-version assert warnings._global_deprecations == [ {'msg': 'Deprecation message', 'version': None, 'collection_name': None}] def test_deprecate_with_collection(reset): deprecate(msg='Deprecation message', collection_name='ansible.builtin') # pylint: disable=ansible-deprecated-no-version assert warnings._global_deprecations == [ {'msg': 'Deprecation message', 'version': None, 'collection_name': 'ansible.builtin'}] def test_deprecate_with_version(reset): deprecate(msg='Deprecation message', version='2.14') # pylint: disable=ansible-deprecated-version assert warnings._global_deprecations == [ {'msg': 'Deprecation message', 'version': '2.14', 'collection_name': None}] def test_deprecate_with_version_and_collection(reset): deprecate(msg='Deprecation message', version='2.14', collection_name='ansible.builtin') # pylint: disable=ansible-deprecated-version assert warnings._global_deprecations == [ {'msg': 'Deprecation message', 'version': '2.14', 'collection_name': 'ansible.builtin'}] def test_deprecate_with_date(reset): deprecate(msg='Deprecation message', date='2199-12-31') assert warnings._global_deprecations == [ {'msg': 'Deprecation message', 'date': '2199-12-31', 'collection_name': None}] def test_deprecate_with_date_and_collection(reset): deprecate(msg='Deprecation message', date='2199-12-31', collection_name='ansible.builtin') assert warnings._global_deprecations == [ {'msg': 'Deprecation message', 'date': '2199-12-31', 'collection_name': 'ansible.builtin'}] def test_multiple_deprecations(deprecation_messages, reset): for d in deprecation_messages: deprecate(**d) assert deprecation_messages == warnings._global_deprecations def test_get_deprecation_messages(deprecation_messages, reset): for d in deprecation_messages: deprecate(**d) accessor_deprecations = get_deprecation_messages() assert isinstance(accessor_deprecations, tuple) assert len(accessor_deprecations) == 7 @pytest.mark.parametrize( 'test_case', ( 1, True, [1], {'k1': 'v1'}, (1, 2), 6.62607004, b'bytestr', None, ) ) def test_deprecate_failure(test_case): with pytest.raises(TypeError, match='deprecate requires a string not a %s' % type(test_case)): deprecate(test_case) # pylint: disable=ansible-deprecated-no-version
3,691
Python
.py
71
46.478873
137
0.692372
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,839
test_check_arguments.py
ansible_ansible/test/units/module_utils/common/parameters/test_check_arguments.py
# -*- coding: utf-8 -*- # Copyright (c) 2020 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.parameters import ( _get_unsupported_parameters, _validate_argument_values, ) from ansible.module_utils.errors import AnsibleValidationErrorMultiple @pytest.fixture def argument_spec(): return { 'state': {'aliases': ['status']}, 'enabled': {}, } @pytest.mark.parametrize( ('module_parameters', 'legal_inputs', 'expected'), ( ({'fish': 'food'}, ['state', 'enabled'], set(['fish'])), ({'state': 'enabled', 'path': '/var/lib/path'}, None, set(['path'])), ({'state': 'enabled', 'path': '/var/lib/path'}, ['state', 'path'], set()), ({'state': 'enabled', 'path': '/var/lib/path'}, ['state'], set(['path'])), ({}, None, set()), ({'state': 'enabled'}, None, set()), ({'status': 'enabled', 'enabled': True, 'path': '/var/lib/path'}, None, set(['path'])), ({'status': 'enabled', 'enabled': True}, None, set()), ) ) def test_check_arguments(argument_spec, module_parameters, legal_inputs, expected, mocker): result = _get_unsupported_parameters(argument_spec, module_parameters, legal_inputs) assert result == expected def test_validate_argument_values(mocker): argument_spec = { "foo": {"type": "list", "elements": "int", "choices": [1]}, } module_parameters = {"foo": [2]} errors = AnsibleValidationErrorMultiple() result = _validate_argument_values(argument_spec, module_parameters, errors=errors) assert "value of foo must be one" in errors[0].msg
1,736
Python
.py
40
38.425
95
0.629674
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,840
test_handle_aliases.py
ansible_ansible/test/units/module_utils/common/parameters/test_handle_aliases.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.parameters import _handle_aliases def test_handle_aliases_no_aliases(): argument_spec = { 'name': {'type': 'str'}, } params = { 'name': 'foo', 'path': 'bar' } assert _handle_aliases(argument_spec, params) == {} def test_handle_aliases_basic(): argument_spec = { 'name': {'type': 'str', 'aliases': ['surname', 'nick']}, } params = { 'name': 'foo', 'path': 'bar', 'surname': 'foo', 'nick': 'foo', } expected = {'surname': 'name', 'nick': 'name'} result = _handle_aliases(argument_spec, params) assert expected == result def test_handle_aliases_value_error(): argument_spec = { 'name': {'type': 'str', 'aliases': ['surname', 'nick'], 'default': 'bob', 'required': True}, } params = { 'name': 'foo', } with pytest.raises(ValueError, match='internal error: required and default are mutually exclusive'): _handle_aliases(argument_spec, params) def test_handle_aliases_type_error(): argument_spec = { 'name': {'type': 'str', 'aliases': 'surname'}, } params = { 'name': 'foo', } with pytest.raises(TypeError, match='internal error: aliases must be a list or tuple'): _handle_aliases(argument_spec, params)
1,555
Python
.py
46
28
104
0.601478
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,841
test_list_deprecations.py
ansible_ansible/test/units/module_utils/common/parameters/test_list_deprecations.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from ansible.module_utils.common.parameters import _list_deprecations def test_list_deprecations(): argument_spec = { 'old': {'type': 'str', 'removed_in_version': '2.5'}, 'foo': {'type': 'dict', 'options': {'old': {'type': 'str', 'removed_in_version': 1.0}}}, 'bar': {'type': 'list', 'elements': 'dict', 'options': {'old': {'type': 'str', 'removed_in_version': '2.10'}}}, } params = { 'name': 'rod', 'old': 'option', 'foo': {'old': 'value'}, 'bar': [{'old': 'value'}, {}], } result = _list_deprecations(argument_spec, params) assert len(result) == 3 result.sort(key=lambda entry: entry['msg']) assert result[0]['msg'] == """Param 'bar["old"]' is deprecated. See the module docs for more information""" assert result[0]['version'] == '2.10' assert result[1]['msg'] == """Param 'foo["old"]' is deprecated. See the module docs for more information""" assert result[1]['version'] == 1.0 assert result[2]['msg'] == "Param 'old' is deprecated. See the module docs for more information" assert result[2]['version'] == '2.5'
1,320
Python
.py
26
45.384615
119
0.602484
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,842
test_list_no_log_values.py
ansible_ansible/test/units/module_utils/common/parameters/test_list_no_log_values.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.parameters import _list_no_log_values @pytest.fixture def argument_spec(): # Allow extra specs to be passed to the fixture, which will be added to the output def _argument_spec(extra_opts=None): spec = { 'secret': {'type': 'str', 'no_log': True}, 'other_secret': {'type': 'str', 'no_log': True}, 'state': {'type': 'str'}, 'value': {'type': 'int'}, } if extra_opts: spec.update(extra_opts) return spec return _argument_spec @pytest.fixture def module_parameters(): # Allow extra parameters to be passed to the fixture, which will be added to the output def _module_parameters(extra_params=None): params = { 'secret': 'under', 'other_secret': 'makeshift', 'state': 'present', 'value': 5, } if extra_params: params.update(extra_params) return params return _module_parameters def test_list_no_log_values_no_secrets(module_parameters): argument_spec = { 'other_secret': {'type': 'str', 'no_log': False}, 'state': {'type': 'str'}, 'value': {'type': 'int'}, } expected = set() assert expected == _list_no_log_values(argument_spec, module_parameters) def test_list_no_log_values(argument_spec, module_parameters): expected = set(('under', 'makeshift')) assert expected == _list_no_log_values(argument_spec(), module_parameters()) @pytest.mark.parametrize('extra_params', [ {'subopt1': 1}, {'subopt1': 3.14159}, {'subopt1': ['one', 'two']}, {'subopt1': ('one', 'two')}, ]) def test_list_no_log_values_invalid_suboptions(argument_spec, module_parameters, extra_params): extra_opts = { 'subopt1': { 'type': 'dict', 'options': { 'sub_1_1': {}, } } } with pytest.raises(TypeError, match=r"(Value '.*?' in the sub parameter field '.*?' must be a dict, not '.*?')" r"|(dictionary requested, could not parse JSON or key=value)"): _list_no_log_values(argument_spec(extra_opts), module_parameters(extra_params)) def test_list_no_log_values_suboptions(argument_spec, module_parameters): extra_opts = { 'subopt1': { 'type': 'dict', 'options': { 'sub_1_1': {'no_log': True}, 'sub_1_2': {'type': 'list'}, } } } extra_params = { 'subopt1': { 'sub_1_1': 'bagel', 'sub_1_2': ['pebble'], } } expected = set(('under', 'makeshift', 'bagel')) assert expected == _list_no_log_values(argument_spec(extra_opts), module_parameters(extra_params)) def test_list_no_log_values_sub_suboptions(argument_spec, module_parameters): extra_opts = { 'sub_level_1': { 'type': 'dict', 'options': { 'l1_1': {'no_log': True}, 'l1_2': {}, 'l1_3': { 'type': 'dict', 'options': { 'l2_1': {'no_log': True}, 'l2_2': {}, } } } } } extra_params = { 'sub_level_1': { 'l1_1': 'saucy', 'l1_2': 'napped', 'l1_3': { 'l2_1': 'corporate', 'l2_2': 'tinsmith', } } } expected = set(('under', 'makeshift', 'saucy', 'corporate')) assert expected == _list_no_log_values(argument_spec(extra_opts), module_parameters(extra_params)) def test_list_no_log_values_suboptions_list(argument_spec, module_parameters): extra_opts = { 'subopt1': { 'type': 'list', 'elements': 'dict', 'options': { 'sub_1_1': {'no_log': True}, 'sub_1_2': {}, } } } extra_params = { 'subopt1': [ { 'sub_1_1': ['playroom', 'luxury'], 'sub_1_2': 'deuce', }, { 'sub_1_2': ['squishier', 'finished'], } ] } expected = set(('under', 'makeshift', 'playroom', 'luxury')) assert expected == _list_no_log_values(argument_spec(extra_opts), module_parameters(extra_params)) def test_list_no_log_values_sub_suboptions_list(argument_spec, module_parameters): extra_opts = { 'subopt1': { 'type': 'list', 'elements': 'dict', 'options': { 'sub_1_1': {'no_log': True}, 'sub_1_2': {}, 'subopt2': { 'type': 'list', 'elements': 'dict', 'options': { 'sub_2_1': {'no_log': True, 'type': 'list'}, 'sub_2_2': {}, } } } } } extra_params = { 'subopt1': { 'sub_1_1': ['playroom', 'luxury'], 'sub_1_2': 'deuce', 'subopt2': [ { 'sub_2_1': ['basis', 'gave'], 'sub_2_2': 'liquid', }, { 'sub_2_1': ['composure', 'thumping'] }, ] } } expected = set(('under', 'makeshift', 'playroom', 'luxury', 'basis', 'gave', 'composure', 'thumping')) assert expected == _list_no_log_values(argument_spec(extra_opts), module_parameters(extra_params)) @pytest.mark.parametrize('extra_params, expected', ( ({'subopt_dict': 'dict_subopt1=rekindle-scandal,dict_subopt2=subgroupavenge'}, ('rekindle-scandal',)), ({'subopt_dict': 'dict_subopt1=aversion-mutable dict_subopt2=subgroupavenge'}, ('aversion-mutable',)), ({'subopt_dict': ['dict_subopt1=blip-marine,dict_subopt2=subgroupavenge', 'dict_subopt1=tipping,dict_subopt2=hardening']}, ('blip-marine', 'tipping')), )) def test_string_suboptions_as_string(argument_spec, module_parameters, extra_params, expected): extra_opts = { 'subopt_dict': { 'type': 'dict', 'options': { 'dict_subopt1': {'no_log': True}, 'dict_subopt2': {}, }, }, } result = set(('under', 'makeshift')) result.update(expected) assert result == _list_no_log_values(argument_spec(extra_opts), module_parameters(extra_params))
6,780
Python
.py
188
25.771277
155
0.503586
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,843
test_get_bin_path.py
ansible_ansible/test/units/module_utils/common/process/test_get_bin_path.py
# -*- coding: utf-8 -*- # Copyright (c) 2020 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.process import get_bin_path def test_get_bin_path(mocker): path = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' mocker.patch.dict('os.environ', {'PATH': path}) mocker.patch('os.pathsep', ':') mocker.patch('os.path.isdir', return_value=False) mocker.patch('ansible.module_utils.common.process.is_executable', return_value=True) # pytest-mock 2.0.0 will throw when os.path.exists is messed with # and then another method is patched afterwards. Likely # something in the pytest-mock chain uses os.path.exists internally, and # since pytest-mock prohibits context-specific patching, there's not a # good solution. For now, just patch os.path.exists last. mocker.patch('os.path.exists', side_effect=[False, True]) assert '/usr/local/bin/notacommand' == get_bin_path('notacommand') def test_get_path_path_raise_valueerror(mocker): mocker.patch.dict('os.environ', {'PATH': ''}) mocker.patch('os.path.exists', return_value=False) mocker.patch('os.path.isdir', return_value=False) mocker.patch('ansible.module_utils.common.process.is_executable', return_value=True) with pytest.raises(ValueError, match='Failed to find required executable "notacommand"'): get_bin_path('notacommand')
1,516
Python
.py
26
53.923077
93
0.727334
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,844
test_check_type_str.py
ansible_ansible/test/units/module_utils/common/validation/test_check_type_str.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_type_str TEST_CASES = ( ('string', 'string'), (100, '100'), (1.5, '1.5'), ({'k1': 'v1'}, "{'k1': 'v1'}"), ([1, 2, 'three'], "[1, 2, 'three']"), ((1, 2,), '(1, 2)'), ) @pytest.mark.parametrize('value, expected', TEST_CASES) def test_check_type_str(value, expected): assert expected == check_type_str(value) @pytest.mark.parametrize('value, expected', TEST_CASES[1:]) def test_check_type_str_no_conversion(value, expected): with pytest.raises(TypeError) as e: check_type_str(value, allow_conversion=False) assert 'is not a string and conversion is not allowed' in to_native(e.value)
960
Python
.py
23
38.434783
92
0.681034
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,845
test_count_terms.py
ansible_ansible/test/units/module_utils/common/validation/test_count_terms.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.validation import count_terms @pytest.fixture def params(): return { 'name': 'bob', 'dest': '/etc/hosts', 'state': 'present', 'value': 5, } def test_count_terms(params): check = set(('name', 'dest')) assert count_terms(check, params) == 2 def test_count_terms_str_input(params): check = 'name' assert count_terms(check, params) == 1 def test_count_terms_tuple_input(params): check = ('name', 'dest') assert count_terms(check, params) == 2 def test_count_terms_list_input(params): check = ['name', 'dest'] assert count_terms(check, params) == 2
865
Python
.py
26
29
92
0.661017
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,846
test_check_missing_parameters.py
ansible_ansible/test/units/module_utils/common/validation/test_check_missing_parameters.py
# -*- coding: utf-8 -*- # Copyright: (c) 2021, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_missing_parameters def test_check_missing_parameters(): assert check_missing_parameters([], {}) == [] def test_check_missing_parameters_list(): expected = "missing required arguments: path" with pytest.raises(TypeError) as e: check_missing_parameters({}, ["path"]) assert to_native(e.value) == expected def test_check_missing_parameters_positive(): assert check_missing_parameters({"path": "/foo"}, ["path"]) == []
783
Python
.py
16
45.4375
92
0.729801
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,847
test_check_mutually_exclusive.py
ansible_ansible/test/units/module_utils/common/validation/test_check_mutually_exclusive.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_mutually_exclusive @pytest.fixture def mutually_exclusive_terms(): return [ ('string1', 'string2',), ('box', 'fox', 'socks'), ] def test_check_mutually_exclusive(mutually_exclusive_terms): params = { 'string1': 'cat', 'fox': 'hat', } assert check_mutually_exclusive(mutually_exclusive_terms, params) == [] def test_check_mutually_exclusive_found(mutually_exclusive_terms): params = { 'string1': 'cat', 'string2': 'hat', 'fox': 'red', 'socks': 'blue', } expected = "parameters are mutually exclusive: string1|string2, box|fox|socks" with pytest.raises(TypeError) as e: check_mutually_exclusive(mutually_exclusive_terms, params) assert to_native(e.value) == expected def test_check_mutually_exclusive_none(): terms = None params = { 'string1': 'cat', 'fox': 'hat', } assert check_mutually_exclusive(terms, params) == [] def test_check_mutually_exclusive_no_params(mutually_exclusive_terms): with pytest.raises(TypeError) as te: check_mutually_exclusive(mutually_exclusive_terms, None) assert "'NoneType' object is not iterable" in to_native(te.value)
1,550
Python
.py
41
32.536585
92
0.682731
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,848
test_check_type_list.py
ansible_ansible/test/units/module_utils/common/validation/test_check_type_list.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.validation import check_type_list def test_check_type_list(): test_cases = ( ([1, 2], [1, 2]), (1, ['1']), (['a', 'b'], ['a', 'b']), ('a', ['a']), (3.14159, ['3.14159']), ('a,b,1,2', ['a', 'b', '1', '2']) ) for case in test_cases: assert case[1] == check_type_list(case[0]) def test_check_type_list_failure(): test_cases = ( {'k1': 'v1'}, ) for case in test_cases: with pytest.raises(TypeError): check_type_list(case)
769
Python
.py
24
26.25
92
0.555556
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,849
test_check_type_path.py
ansible_ansible/test/units/module_utils/common/validation/test_check_type_path.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import re import os from ansible.module_utils.common.validation import check_type_path def mock_expand(value): return re.sub(r'~|\$HOME', '/home/testuser', value) def test_check_type_path(monkeypatch): monkeypatch.setattr(os.path, 'expandvars', mock_expand) monkeypatch.setattr(os.path, 'expanduser', mock_expand) test_cases = ( ('~/foo', '/home/testuser/foo'), ('$HOME/foo', '/home/testuser/foo'), ('/home/jane', '/home/jane'), (u'/home/jané', u'/home/jané'), ) for case in test_cases: assert case[1] == check_type_path(case[0])
792
Python
.py
20
34.95
92
0.663172
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,850
test_check_required_arguments.py
ansible_ansible/test/units/module_utils/common/validation/test_check_required_arguments.py
# -*- coding: utf-8 -*- # Copyright (c) 2020 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_required_arguments @pytest.fixture def arguments_terms(): return { 'foo': { 'required': True, }, 'bar': { 'required': False, }, 'tomato': { 'irrelevant': 72, }, } @pytest.fixture def arguments_terms_multiple(): return { 'foo': { 'required': True, }, 'bar': { 'required': True, }, 'tomato': { 'irrelevant': 72, }, } def test_check_required_arguments(arguments_terms): params = { 'foo': 'hello', 'bar': 'haha', } assert check_required_arguments(arguments_terms, params) == [] def test_check_required_arguments_missing(arguments_terms): params = { 'apples': 'woohoo', } expected = "missing required arguments: foo" with pytest.raises(TypeError) as e: check_required_arguments(arguments_terms, params) assert to_native(e.value) == expected def test_check_required_arguments_missing_multiple(arguments_terms_multiple): params = { 'apples': 'woohoo', } expected = "missing required arguments: bar, foo" with pytest.raises(TypeError) as e: check_required_arguments(arguments_terms_multiple, params) assert to_native(e.value) == expected def test_check_required_arguments_missing_none(): terms = None params = { 'foo': 'bar', 'baz': 'buzz', } assert check_required_arguments(terms, params) == [] def test_check_required_arguments_no_params(arguments_terms): with pytest.raises(TypeError) as te: check_required_arguments(arguments_terms, None) assert "'NoneType' is not iterable" in to_native(te.value)
2,073
Python
.py
66
25.060606
92
0.632427
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,851
test_check_required_one_of.py
ansible_ansible/test/units/module_utils/common/validation/test_check_required_one_of.py
# -*- coding: utf-8 -*- # Copyright: (c) 2021, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_required_one_of @pytest.fixture def arguments_terms(): return [["path", "owner"]] def test_check_required_one_of(): assert check_required_one_of([], {}) == [] def test_check_required_one_of_missing(arguments_terms): params = {"state": "present"} expected = "one of the following is required: path, owner" with pytest.raises(TypeError) as e: check_required_one_of(arguments_terms, params) assert to_native(e.value) == expected def test_check_required_one_of_provided(arguments_terms): params = {"state": "present", "path": "/foo"} assert check_required_one_of(arguments_terms, params) == [] def test_check_required_one_of_context(arguments_terms): params = {"state": "present"} expected = "one of the following is required: path, owner found in foo_context" option_context = ["foo_context"] with pytest.raises(TypeError) as e: check_required_one_of(arguments_terms, params, option_context) assert to_native(e.value) == expected
1,341
Python
.py
28
43.821429
92
0.718147
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,852
test_check_type_jsonarg.py
ansible_ansible/test/units/module_utils/common/validation/test_check_type_jsonarg.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_type_jsonarg def test_check_type_jsonarg(): test_cases = ( ('a', 'a'), ('a ', 'a'), (b'99', b'99'), (b'99 ', b'99'), ({'k1': 'v1'}, '{"k1": "v1"}'), ([1, 'a'], '[1, "a"]'), ((1, 2, 'three'), '[1, 2, "three"]'), ) for case in test_cases: assert case[1] == check_type_jsonarg(case[0]) def test_check_type_jsonarg_fail(): test_cases = ( 1.5, 910313498012384012341982374109384098, ) for case in test_cases: with pytest.raises(TypeError) as e: check_type_jsonarg(case) assert 'cannot be converted to a json string' in to_native(e.value)
999
Python
.py
28
29.714286
92
0.598548
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,853
test_check_type_float.py
ansible_ansible/test/units/module_utils/common/validation/test_check_type_float.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_type_float def test_check_type_float(): test_cases = ( ('1.5', 1.5), ("""1.5""", 1.5), (u'1.5', 1.5), (1002, 1002.0), (1.0, 1.0), (3.141592653589793, 3.141592653589793), ('3.141592653589793', 3.141592653589793), (b'3.141592653589793', 3.141592653589793), ) for case in test_cases: assert case[1] == check_type_float(case[0]) def test_check_type_float_fail(): test_cases = ( {'k1': 'v1'}, ['a', 'b'], 'b', ) for case in test_cases: with pytest.raises(TypeError) as e: check_type_float(case) assert 'cannot be converted to a float' in to_native(e.value)
1,033
Python
.py
30
28.266667
92
0.614458
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,854
test_check_type_int.py
ansible_ansible/test/units/module_utils/common/validation/test_check_type_int.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_type_int def test_check_type_int(): test_cases = ( ('1', 1), (u'1', 1), (1002, 1002), ) for case in test_cases: assert case[1] == check_type_int(case[0]) def test_check_type_int_fail(): test_cases = ( {'k1': 'v1'}, (b'1', 1), (3.14159, 3), 'b', ) for case in test_cases: with pytest.raises(TypeError) as e: check_type_int(case) assert 'cannot be converted to an int' in to_native(e.value)
838
Python
.py
26
26.5
92
0.619876
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,855
test_check_required_together.py
ansible_ansible/test/units/module_utils/common/validation/test_check_required_together.py
# -*- coding: utf-8 -*- # Copyright (c) 2020 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_required_together @pytest.fixture def together_terms(): return [ ['bananas', 'potatoes'], ['cats', 'wolves'] ] def test_check_required_together(together_terms): params = { 'bananas': 'hello', 'potatoes': 'this is here too', 'dogs': 'haha', } assert check_required_together(together_terms, params) == [] def test_check_required_together_missing(together_terms): params = { 'bananas': 'woohoo', 'wolves': 'uh oh', } expected = "parameters are required together: bananas, potatoes" with pytest.raises(TypeError) as e: check_required_together(together_terms, params) assert to_native(e.value) == expected def test_check_required_together_missing_none(): terms = None params = { 'foo': 'bar', 'baz': 'buzz', } assert check_required_together(terms, params) == [] def test_check_required_together_no_params(together_terms): with pytest.raises(TypeError) as te: check_required_together(together_terms, None) assert "'NoneType' object is not iterable" in to_native(te.value)
1,460
Python
.py
40
31.3
92
0.680912
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,856
test_check_type_bool.py
ansible_ansible/test/units/module_utils/common/validation/test_check_type_bool.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_type_bool def test_check_type_bool(): test_cases = ( (True, True), (False, False), ('1', True), ('on', True), (1, True), ('0', False), (0, False), ('n', False), ('f', False), ('false', False), ('true', True), ('y', True), ('t', True), ('yes', True), ('no', False), ('off', False), ) for case in test_cases: assert case[1] == check_type_bool(case[0]) def test_check_type_bool_fail(): default_test_msg = 'cannot be converted to a bool' test_cases = ( ({'k1': 'v1'}, 'is not a valid bool'), (3.14159, default_test_msg), (-1, default_test_msg), (-90810398401982340981023948192349081, default_test_msg), (90810398401982340981023948192349081, default_test_msg), ) for case in test_cases: with pytest.raises(TypeError) as e: check_type_bool(case) assert 'cannot be converted to a bool' in to_native(e.value)
1,366
Python
.py
41
26.487805
92
0.587253
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,857
test_check_type_raw.py
ansible_ansible/test/units/module_utils/common/validation/test_check_type_raw.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from ansible.module_utils.common.validation import check_type_raw def test_check_type_raw(): test_cases = ( (1, 1), ('1', '1'), ('a', 'a'), ({'k1': 'v1'}, {'k1': 'v1'}), ([1, 2], [1, 2]), (b'42', b'42'), (u'42', u'42'), ) for case in test_cases: assert case[1] == check_type_raw(case[0])
558
Python
.py
17
27.058824
92
0.546642
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,858
test_check_required_by.py
ansible_ansible/test/units/module_utils/common/validation/test_check_required_by.py
# -*- coding: utf-8 -*- # Copyright: (c) 2021, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_required_by @pytest.fixture def path_arguments_terms(): return { "path": ["mode", "owner"], } def test_check_required_by(): arguments_terms = {} params = {} assert check_required_by(arguments_terms, params) == {} def test_check_required_by_missing(): arguments_terms = { "force": "force_reason", } params = {"force": True} expected = "missing parameter(s) required by 'force': force_reason" with pytest.raises(TypeError) as e: check_required_by(arguments_terms, params) assert to_native(e.value) == expected def test_check_required_by_multiple(path_arguments_terms): params = { "path": "/foo/bar", } expected = "missing parameter(s) required by 'path': mode, owner" with pytest.raises(TypeError) as e: check_required_by(path_arguments_terms, params) assert to_native(e.value) == expected def test_check_required_by_single(path_arguments_terms): params = {"path": "/foo/bar", "mode": "0700"} expected = "missing parameter(s) required by 'path': owner" with pytest.raises(TypeError) as e: check_required_by(path_arguments_terms, params) assert to_native(e.value) == expected def test_check_required_by_missing_none(path_arguments_terms): params = { "path": "/foo/bar", "mode": "0700", "owner": "root", } assert check_required_by(path_arguments_terms, params) def test_check_required_by_options_context(path_arguments_terms): params = {"path": "/foo/bar", "mode": "0700"} options_context = ["foo_context"] expected = "missing parameter(s) required by 'path': owner found in foo_context" with pytest.raises(TypeError) as e: check_required_by(path_arguments_terms, params, options_context) assert to_native(e.value) == expected def test_check_required_by_missing_multiple_options_context(path_arguments_terms): params = { "path": "/foo/bar", } options_context = ["foo_context"] expected = ( "missing parameter(s) required by 'path': mode, owner found in foo_context" ) with pytest.raises(TypeError) as e: check_required_by(path_arguments_terms, params, options_context) assert to_native(e.value) == expected
2,608
Python
.py
64
35.421875
92
0.6818
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,859
test_check_type_bits.py
ansible_ansible/test/units/module_utils/common/validation/test_check_type_bits.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_type_bits def test_check_type_bits(): test_cases = ( ('1', 1), (99, 99), (1.5, 2), ('1.5', 2), ('2b', 2), ('2k', 2048), ('2K', 2048), ('1m', 1048576), ('1M', 1048576), ('1g', 1073741824), ('1G', 1073741824), (1073741824, 1073741824), ) for case in test_cases: assert case[1] == check_type_bits(case[0]) def test_check_type_bits_fail(): test_cases = ( 'foo', '2KB', '1MB', '1GB', ) for case in test_cases: with pytest.raises(TypeError) as e: check_type_bits(case) assert 'cannot be converted to a Bit value' in to_native(e.value)
1,050
Python
.py
35
23.428571
92
0.576389
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,860
test_check_required_if.py
ansible_ansible/test/units/module_utils/common/validation/test_check_required_if.py
# -*- coding: utf-8 -*- # Copyright: (c) 2021, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_required_if def test_check_required_if(): arguments_terms = {} params = {} assert check_required_if(arguments_terms, params) == [] def test_check_required_if_missing(): arguments_terms = [["state", "present", ("path",)]] params = {"state": "present"} expected = "state is present but all of the following are missing: path" with pytest.raises(TypeError) as e: check_required_if(arguments_terms, params) assert to_native(e.value) == expected def test_check_required_if_missing_required(): arguments_terms = [["state", "present", ("path", "owner"), True]] params = {"state": "present"} expected = "state is present but any of the following are missing: path, owner" with pytest.raises(TypeError) as e: check_required_if(arguments_terms, params) assert to_native(e.value) == expected def test_check_required_if_missing_multiple(): arguments_terms = [["state", "present", ("path", "owner")]] params = { "state": "present", } expected = "state is present but all of the following are missing: path, owner" with pytest.raises(TypeError) as e: check_required_if(arguments_terms, params) assert to_native(e.value) == expected def test_check_required_if_missing_multiple_with_context(): arguments_terms = [["state", "present", ("path", "owner")]] params = { "state": "present", } options_context = ["foo_context"] expected = "state is present but all of the following are missing: path, owner found in foo_context" with pytest.raises(TypeError) as e: check_required_if(arguments_terms, params, options_context) assert to_native(e.value) == expected def test_check_required_if_multiple(): arguments_terms = [["state", "present", ("path", "owner")]] params = { "state": "present", "path": "/foo", "owner": "root", } options_context = ["foo_context"] assert check_required_if(arguments_terms, params) == [] assert check_required_if(arguments_terms, params, options_context) == []
2,420
Python
.py
54
39.666667
104
0.675491
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,861
test_check_type_dict.py
ansible_ansible/test/units/module_utils/common/validation/test_check_type_dict.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.validation import check_type_dict def test_check_type_dict(): test_cases = ( ({'k1': 'v1'}, {'k1': 'v1'}), ('k1=v1,k2=v2', {'k1': 'v1', 'k2': 'v2'}), ('k1=v1, k2=v2', {'k1': 'v1', 'k2': 'v2'}), ('k1=v1, k2=v2, k3=v3', {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}), ('{"key": "value", "list": ["one", "two"]}', {'key': 'value', 'list': ['one', 'two']}), ('k1=v1 k2=v2', {'k1': 'v1', 'k2': 'v2'}), ) for case in test_cases: assert case[1] == check_type_dict(case[0]) def test_check_type_dict_fail(): test_cases = ( 1, 3.14159, [1, 2], 'a', '{1}', 'k1=v1 k2' ) for case in test_cases: with pytest.raises(TypeError): check_type_dict(case)
1,023
Python
.py
29
28.931034
95
0.510638
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,862
test_check_type_bytes.py
ansible_ansible/test/units/module_utils/common/validation/test_check_type_bytes.py
# -*- coding: utf-8 -*- # Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.common.validation import check_type_bytes def test_check_type_bytes(): test_cases = ( ('1', 1), (99, 99), (1.5, 2), ('1.5', 2), ('2b', 2), ('2B', 2), ('2k', 2048), ('2K', 2048), ('2KB', 2048), ('1m', 1048576), ('1M', 1048576), ('1MB', 1048576), ('1g', 1073741824), ('1G', 1073741824), ('1GB', 1073741824), (1073741824, 1073741824), ) for case in test_cases: assert case[1] == check_type_bytes(case[0]) def test_check_type_bytes_fail(): test_cases = ( 'foo', '2kb', '2Kb', '1mb', '1Mb', '1gb', '1Gb', ) for case in test_cases: with pytest.raises(TypeError) as e: check_type_bytes(case) assert 'cannot be converted to a Byte value' in to_native(e.value)
1,198
Python
.py
42
21.547619
92
0.547433
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,863
test_sub_spec.py
ansible_ansible/test/units/module_utils/common/arg_spec/test_sub_spec.py
# -*- coding: utf-8 -*- # Copyright (c) 2021 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from ansible.module_utils.common.arg_spec import ArgumentSpecValidator, ValidationResult def test_sub_spec(): arg_spec = { 'state': {}, 'user': { 'type': 'dict', 'options': { 'first': {'no_log': True}, 'last': {}, 'age': {'type': 'int'}, } } } parameters = { 'state': 'present', 'user': { 'first': 'Rey', 'last': 'Skywalker', 'age': '19', } } expected = { 'state': 'present', 'user': { 'first': 'Rey', 'last': 'Skywalker', 'age': 19, } } v = ArgumentSpecValidator(arg_spec) result = v.validate(parameters) assert isinstance(result, ValidationResult) assert result.validated_parameters == expected assert result.error_messages == [] def test_nested_sub_spec(): arg_spec = { 'type': {}, 'car': { 'type': 'dict', 'options': { 'make': {}, 'model': {}, 'customizations': { 'type': 'dict', 'options': { 'engine': {}, 'transmission': {}, 'color': {}, 'max_rpm': {'type': 'int'}, } } } } } parameters = { 'type': 'endurance', 'car': { 'make': 'Ford', 'model': 'GT-40', 'customizations': { 'engine': '7.0 L', 'transmission': '5-speed', 'color': 'Ford blue', 'max_rpm': '6000', } } } expected = { 'type': 'endurance', 'car': { 'make': 'Ford', 'model': 'GT-40', 'customizations': { 'engine': '7.0 L', 'transmission': '5-speed', 'color': 'Ford blue', 'max_rpm': 6000, } } } v = ArgumentSpecValidator(arg_spec) result = v.validate(parameters) assert isinstance(result, ValidationResult) assert result.validated_parameters == expected assert result.error_messages == []
2,529
Python
.py
89
17.483146
92
0.426155
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,864
test_validate_invalid.py
ansible_ansible/test/units/module_utils/common/arg_spec/test_validate_invalid.py
# -*- coding: utf-8 -*- # Copyright (c) 2021 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.arg_spec import ArgumentSpecValidator, ValidationResult from ansible.module_utils.errors import AnsibleValidationErrorMultiple # Each item is id, argument_spec, parameters, expected, unsupported parameters, error test string INVALID_SPECS = [ ( 'invalid-list', {'packages': {'type': 'list'}}, {'packages': {'key': 'value'}}, {'packages': {'key': 'value'}}, set(), "unable to convert to list: <class 'dict'> cannot be converted to a list", ), ( 'invalid-dict', {'users': {'type': 'dict'}}, {'users': ['one', 'two']}, {'users': ['one', 'two']}, set(), "unable to convert to dict: <class 'list'> cannot be converted to a dict", ), ( 'invalid-bool', {'bool': {'type': 'bool'}}, {'bool': {'k': 'v'}}, {'bool': {'k': 'v'}}, set(), "unable to convert to bool: <class 'dict'> cannot be converted to a bool", ), ( 'invalid-float', {'float': {'type': 'float'}}, {'float': 'hello'}, {'float': 'hello'}, set(), "unable to convert to float: <class 'str'> cannot be converted to a float", ), ( 'invalid-bytes', {'bytes': {'type': 'bytes'}}, {'bytes': 'one'}, {'bytes': 'one'}, set(), "unable to convert to bytes: <class 'str'> cannot be converted to a Byte value", ), ( 'invalid-bits', {'bits': {'type': 'bits'}}, {'bits': 'one'}, {'bits': 'one'}, set(), "unable to convert to bits: <class 'str'> cannot be converted to a Bit value", ), ( 'invalid-jsonargs', {'some_json': {'type': 'jsonarg'}}, {'some_json': set()}, {'some_json': set()}, set(), "unable to convert to jsonarg: <class 'set'> cannot be converted to a json string", ), ( 'invalid-parameter', {'name': {}}, { 'badparam': '', 'another': '', }, { 'name': None, 'badparam': '', 'another': '', }, set(('another', 'badparam')), "another, badparam. Supported parameters include: name.", ), ( 'invalid-elements', {'numbers': {'type': 'list', 'elements': 'int'}}, {'numbers': [55, 33, 34, {'key': 'value'}]}, {'numbers': [55, 33, 34]}, set(), "Elements value for option 'numbers' is of type <class 'dict'> and we were unable to convert to int:" ), ( 'required', {'req': {'required': True}}, {}, {'req': None}, set(), "missing required arguments: req" ), ( 'blank_values', {'ch_param': {'elements': 'str', 'type': 'list', 'choices': ['a', 'b']}}, {'ch_param': ['']}, {'ch_param': ['']}, set(), "value of ch_param must be one or more of" ) ] @pytest.mark.parametrize( ('arg_spec', 'parameters', 'expected', 'unsupported', 'error'), (i[1:] for i in INVALID_SPECS), ids=[i[0] for i in INVALID_SPECS] ) def test_invalid_spec(arg_spec, parameters, expected, unsupported, error): v = ArgumentSpecValidator(arg_spec) result = v.validate(parameters) with pytest.raises(AnsibleValidationErrorMultiple) as exc_info: raise result.errors assert isinstance(result, ValidationResult) assert error in exc_info.value.msg assert error in result.error_messages[0] assert result.unsupported_parameters == unsupported assert result.validated_parameters == expected
3,874
Python
.py
120
25.008333
109
0.537784
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,865
test_module_validate.py
ansible_ansible/test/units/module_utils/common/arg_spec/test_module_validate.py
# -*- coding: utf-8 -*- # Copyright (c) 2021 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from ansible.module_utils.common import warnings from ansible.module_utils.common.arg_spec import ModuleArgumentSpecValidator, ValidationResult def test_module_validate(): arg_spec = {'name': {}} parameters = {'name': 'larry'} expected = {'name': 'larry'} v = ModuleArgumentSpecValidator(arg_spec) result = v.validate(parameters) assert isinstance(result, ValidationResult) assert result.error_messages == [] assert result._deprecations == [] assert result._warnings == [] assert result.validated_parameters == expected def test_module_alias_deprecations_warnings(monkeypatch): monkeypatch.setattr(warnings, '_global_deprecations', []) arg_spec = { 'path': { 'aliases': ['source', 'src', 'flamethrower'], 'deprecated_aliases': [{'name': 'flamethrower', 'date': '2020-03-04'}], }, } parameters = {'flamethrower': '/tmp', 'source': '/tmp'} expected = { 'path': '/tmp', 'flamethrower': '/tmp', 'source': '/tmp', } v = ModuleArgumentSpecValidator(arg_spec) result = v.validate(parameters) assert result.validated_parameters == expected assert result._deprecations == [ { 'collection_name': None, 'date': '2020-03-04', 'msg': "Alias 'flamethrower' is deprecated. See the module docs for more information", 'version': None, } ] assert "Alias 'flamethrower' is deprecated" in warnings._global_deprecations[0]['msg'] assert result._warnings == [{'alias': 'flamethrower', 'option': 'path'}] assert "Both option path and its alias flamethrower are set" in warnings._global_warnings[0]
1,900
Python
.py
45
35.977778
98
0.651655
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,866
test_validate_valid.py
ansible_ansible/test/units/module_utils/common/arg_spec/test_validate_valid.py
# -*- coding: utf-8 -*- # Copyright (c) 2021 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.arg_spec import ArgumentSpecValidator, ValidationResult # Each item is id, argument_spec, parameters, expected, valid parameter names VALID_SPECS = [ ( 'str-no-type-specified', {'name': {}}, {'name': 'rey'}, {'name': 'rey'}, set(('name',)), ), ( 'str', {'name': {'type': 'str'}}, {'name': 'rey'}, {'name': 'rey'}, set(('name',)), ), ( 'str-convert', {'name': {'type': 'str'}}, {'name': 5}, {'name': '5'}, set(('name',)), ), ( 'list', {'packages': {'type': 'list'}}, {'packages': ['vim', 'python']}, {'packages': ['vim', 'python']}, set(('packages',)), ), ( 'list-comma-string', {'packages': {'type': 'list'}}, {'packages': 'vim,python'}, {'packages': ['vim', 'python']}, set(('packages',)), ), ( 'list-comma-string-space', {'packages': {'type': 'list'}}, {'packages': 'vim, python'}, {'packages': ['vim', ' python']}, set(('packages',)), ), ( 'dict', {'user': {'type': 'dict'}}, { 'user': { 'first': 'rey', 'last': 'skywalker', } }, { 'user': { 'first': 'rey', 'last': 'skywalker', } }, set(('user',)), ), ( 'dict-k=v', {'user': {'type': 'dict'}}, {'user': 'first=rey,last=skywalker'}, { 'user': { 'first': 'rey', 'last': 'skywalker', } }, set(('user',)), ), ( 'dict-k=v-spaces', {'user': {'type': 'dict'}}, {'user': 'first=rey, last=skywalker'}, { 'user': { 'first': 'rey', 'last': 'skywalker', } }, set(('user',)), ), ( 'bool', { 'enabled': {'type': 'bool'}, 'disabled': {'type': 'bool'}, }, { 'enabled': True, 'disabled': False, }, { 'enabled': True, 'disabled': False, }, set(('enabled', 'disabled')), ), ( 'bool-ints', { 'enabled': {'type': 'bool'}, 'disabled': {'type': 'bool'}, }, { 'enabled': 1, 'disabled': 0, }, { 'enabled': True, 'disabled': False, }, set(('enabled', 'disabled')), ), ( 'bool-true-false', { 'enabled': {'type': 'bool'}, 'disabled': {'type': 'bool'}, }, { 'enabled': 'true', 'disabled': 'false', }, { 'enabled': True, 'disabled': False, }, set(('enabled', 'disabled')), ), ( 'bool-yes-no', { 'enabled': {'type': 'bool'}, 'disabled': {'type': 'bool'}, }, { 'enabled': 'yes', 'disabled': 'no', }, { 'enabled': True, 'disabled': False, }, set(('enabled', 'disabled')), ), ( 'bool-y-n', { 'enabled': {'type': 'bool'}, 'disabled': {'type': 'bool'}, }, { 'enabled': 'y', 'disabled': 'n', }, { 'enabled': True, 'disabled': False, }, set(('enabled', 'disabled')), ), ( 'bool-on-off', { 'enabled': {'type': 'bool'}, 'disabled': {'type': 'bool'}, }, { 'enabled': 'on', 'disabled': 'off', }, { 'enabled': True, 'disabled': False, }, set(('enabled', 'disabled')), ), ( 'bool-1-0', { 'enabled': {'type': 'bool'}, 'disabled': {'type': 'bool'}, }, { 'enabled': '1', 'disabled': '0', }, { 'enabled': True, 'disabled': False, }, set(('enabled', 'disabled')), ), ( 'bool-float', { 'enabled': {'type': 'bool'}, 'disabled': {'type': 'bool'}, }, { 'enabled': 1.0, 'disabled': 0.0, }, { 'enabled': True, 'disabled': False, }, set(('enabled', 'disabled')), ), ( 'float', {'digit': {'type': 'float'}}, {'digit': 3.14159}, {'digit': 3.14159}, set(('digit',)), ), ( 'float-str', {'digit': {'type': 'float'}}, {'digit': '3.14159'}, {'digit': 3.14159}, set(('digit',)), ), ( 'path', {'path': {'type': 'path'}}, {'path': '~/bin'}, {'path': '/home/ansible/bin'}, set(('path',)), ), ( 'raw', {'raw': {'type': 'raw'}}, {'raw': 0x644}, {'raw': 0x644}, set(('raw',)), ), ( 'bytes', {'bytes': {'type': 'bytes'}}, {'bytes': '2K'}, {'bytes': 2048}, set(('bytes',)), ), ( 'bits', {'bits': {'type': 'bits'}}, {'bits': '1Mb'}, {'bits': 1048576}, set(('bits',)), ), ( 'jsonarg', {'some_json': {'type': 'jsonarg'}}, {'some_json': '{"users": {"bob": {"role": "accountant"}}}'}, {'some_json': '{"users": {"bob": {"role": "accountant"}}}'}, set(('some_json',)), ), ( 'jsonarg-list', {'some_json': {'type': 'jsonarg'}}, {'some_json': ['one', 'two']}, {'some_json': '["one", "two"]'}, set(('some_json',)), ), ( 'jsonarg-dict', {'some_json': {'type': 'jsonarg'}}, {'some_json': {"users": {"bob": {"role": "accountant"}}}}, {'some_json': '{"users": {"bob": {"role": "accountant"}}}'}, set(('some_json',)), ), ( 'defaults', {'param': {'default': 'DEFAULT'}}, {}, {'param': 'DEFAULT'}, set(('param',)), ), ( 'elements', {'numbers': {'type': 'list', 'elements': 'int'}}, {'numbers': [55, 33, 34, '22']}, {'numbers': [55, 33, 34, 22]}, set(('numbers',)), ), ( 'aliases', {'src': {'aliases': ['path', 'source']}}, {'src': '/tmp'}, {'src': '/tmp'}, set(('src (path, source)',)), ) ] @pytest.mark.parametrize( ('arg_spec', 'parameters', 'expected', 'valid_params'), (i[1:] for i in VALID_SPECS), ids=[i[0] for i in VALID_SPECS] ) def test_valid_spec(arg_spec, parameters, expected, valid_params, mocker): mocker.patch('ansible.module_utils.common.validation.os.path.expanduser', return_value='/home/ansible/bin') mocker.patch('ansible.module_utils.common.validation.os.path.expandvars', return_value='/home/ansible/bin') v = ArgumentSpecValidator(arg_spec) result = v.validate(parameters) assert isinstance(result, ValidationResult) assert result.validated_parameters == expected assert result.unsupported_parameters == set() assert result.error_messages == [] assert v._valid_parameter_names == valid_params # Again to check caching assert v._valid_parameter_names == valid_params
7,920
Python
.py
325
15.587692
111
0.394015
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,867
test_aliases.py
ansible_ansible/test/units/module_utils/common/arg_spec/test_aliases.py
# -*- coding: utf-8 -*- # Copyright (c) 2021 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.errors import AnsibleValidationError, AnsibleValidationErrorMultiple from ansible.module_utils.common.arg_spec import ArgumentSpecValidator, ValidationResult # id, argument spec, parameters, expected parameters, deprecation, warning ALIAS_TEST_CASES = [ ( "alias", {'path': {'aliases': ['dir', 'directory']}}, {'dir': '/tmp'}, { 'dir': '/tmp', 'path': '/tmp', }, "", "", ), ( "alias-duplicate-warning", {'path': {'aliases': ['dir', 'directory']}}, { 'dir': '/tmp', 'directory': '/tmp', }, { 'dir': '/tmp', 'directory': '/tmp', 'path': '/tmp', }, "", {'alias': 'directory', 'option': 'path'}, ), ( "deprecated-alias", { 'path': { 'aliases': ['not_yo_path'], 'deprecated_aliases': [ { 'name': 'not_yo_path', 'version': '1.7', } ] } }, {'not_yo_path': '/tmp'}, { 'path': '/tmp', 'not_yo_path': '/tmp', }, { 'version': '1.7', 'date': None, 'collection_name': None, 'msg': "Alias 'not_yo_path' is deprecated. See the module docs for more information", }, "", ) ] # id, argument spec, parameters, expected parameters, error ALIAS_TEST_CASES_INVALID: list[tuple[str, dict, dict, dict, str]] = [ ( "alias-invalid", {'path': {'aliases': 'bad'}}, {}, {'path': None}, "internal error: aliases must be a list or tuple", ), ( # This isn't related to aliases, but it exists in the alias handling code "default-and-required", {'name': {'default': 'ray', 'required': True}}, {}, {'name': 'ray'}, "internal error: required and default are mutually exclusive for name", ), ] @pytest.mark.parametrize( ('arg_spec', 'parameters', 'expected', 'deprecation', 'warning'), ((i[1:]) for i in ALIAS_TEST_CASES), ids=[i[0] for i in ALIAS_TEST_CASES] ) def test_aliases(arg_spec, parameters, expected, deprecation, warning): v = ArgumentSpecValidator(arg_spec) result = v.validate(parameters) assert isinstance(result, ValidationResult) assert result.validated_parameters == expected assert result.error_messages == [] assert result._aliases == { alias: param for param, value in arg_spec.items() for alias in value.get("aliases", []) } if deprecation: assert deprecation == result._deprecations[0] else: assert result._deprecations == [] if warning: assert warning == result._warnings[0] else: assert result._warnings == [] @pytest.mark.parametrize( ('arg_spec', 'parameters', 'expected', 'error'), ((i[1:]) for i in ALIAS_TEST_CASES_INVALID), ids=[i[0] for i in ALIAS_TEST_CASES_INVALID] ) def test_aliases_invalid(arg_spec, parameters, expected, error): v = ArgumentSpecValidator(arg_spec) result = v.validate(parameters) assert isinstance(result, ValidationResult) assert error in result.error_messages assert isinstance(result.errors.errors[0], AnsibleValidationError) assert isinstance(result.errors, AnsibleValidationErrorMultiple)
3,738
Python
.py
116
24.344828
97
0.560421
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,868
test_lenient_lowercase.py
ansible_ansible/test/units/module_utils/common/text/formatters/test_lenient_lowercase.py
# -*- coding: utf-8 -*- # Copyright 2019, Andrew Klychkov @Andersson007 <aaklychkov@mail.ru> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from datetime import datetime import pytest from ansible.module_utils.common.text.formatters import lenient_lowercase INPUT_LIST = [ u'HELLO', u'Ёлка', u'cafÉ', u'くらとみ', b'HELLO', 1, {1: 'Dict'}, True, [1], 3.14159, ] EXPECTED_LIST = [ u'hello', u'ёлка', u'café', u'くらとみ', b'hello', 1, {1: 'Dict'}, True, [1], 3.14159, ] result_list = lenient_lowercase(INPUT_LIST) @pytest.mark.parametrize( 'input_value,expected_outcome', [ (result_list[0], EXPECTED_LIST[0]), (result_list[1], EXPECTED_LIST[1]), (result_list[2], EXPECTED_LIST[2]), (result_list[3], EXPECTED_LIST[3]), (result_list[4], EXPECTED_LIST[4]), (result_list[5], EXPECTED_LIST[5]), (result_list[6], EXPECTED_LIST[6]), (result_list[7], EXPECTED_LIST[7]), (result_list[8], EXPECTED_LIST[8]), (result_list[9], EXPECTED_LIST[9]), ] ) def test_lenient_lowercase(input_value, expected_outcome): """Test that lenient_lowercase() proper results.""" assert input_value == expected_outcome @pytest.mark.parametrize('input_data', [1, False, 1.001, 1j, datetime.now(), ]) def test_lenient_lowercase_illegal_data_type(input_data): """Test passing objects of illegal types to lenient_lowercase().""" with pytest.raises(TypeError, match='object is not iterable'): lenient_lowercase(input_data)
1,693
Python
.py
55
25.527273
92
0.645
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,869
test_bytes_to_human.py
ansible_ansible/test/units/module_utils/common/text/formatters/test_bytes_to_human.py
# -*- coding: utf-8 -*- # Copyright 2019, Andrew Klychkov @Andersson007 <aaklychkov@mail.ru> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.formatters import bytes_to_human @pytest.mark.parametrize( 'input_data,expected', [ (0, u'0.00 Bytes'), (0.5, u'0.50 Bytes'), (0.54, u'0.54 Bytes'), (1024, u'1.00 KB'), (1025, u'1.00 KB'), (1536, u'1.50 KB'), (1790, u'1.75 KB'), (1048576, u'1.00 MB'), (1073741824, u'1.00 GB'), (1099511627776, u'1.00 TB'), (1125899906842624, u'1.00 PB'), (1152921504606846976, u'1.00 EB'), (1180591620717411303424, u'1.00 ZB'), (1208925819614629174706176, u'1.00 YB'), ] ) def test_bytes_to_human(input_data, expected): """Test of bytes_to_human function, only proper numbers are passed.""" assert bytes_to_human(input_data) == expected @pytest.mark.parametrize( 'input_data,expected', [ (0, u'0.00 bits'), (0.5, u'0.50 bits'), (0.54, u'0.54 bits'), (1024, u'1.00 Kb'), (1025, u'1.00 Kb'), (1536, u'1.50 Kb'), (1790, u'1.75 Kb'), (1048576, u'1.00 Mb'), (1073741824, u'1.00 Gb'), (1099511627776, u'1.00 Tb'), (1125899906842624, u'1.00 Pb'), (1152921504606846976, u'1.00 Eb'), (1180591620717411303424, u'1.00 Zb'), (1208925819614629174706176, u'1.00 Yb'), ] ) def test_bytes_to_human_isbits(input_data, expected): """Test of bytes_to_human function with isbits=True proper results.""" assert bytes_to_human(input_data, isbits=True) == expected @pytest.mark.parametrize( 'input_data,unit,expected', [ (0, u'B', u'0.00 Bytes'), (0.5, u'B', u'0.50 Bytes'), (0.54, u'B', u'0.54 Bytes'), (1024, u'K', u'1.00 KB'), (1536, u'K', u'1.50 KB'), (1790, u'K', u'1.75 KB'), (1048576, u'M', u'1.00 MB'), (1099511627776, u'T', u'1.00 TB'), (1152921504606846976, u'E', u'1.00 EB'), (1180591620717411303424, u'Z', u'1.00 ZB'), (1208925819614629174706176, u'Y', u'1.00 YB'), (1025, u'KB', u'1025.00 Bytes'), (1073741824, u'Gb', u'1073741824.00 Bytes'), (1125899906842624, u'Pb', u'1125899906842624.00 Bytes'), ] ) def test_bytes_to_human_unit(input_data, unit, expected): """Test unit argument of bytes_to_human function proper results.""" assert bytes_to_human(input_data, unit=unit) == expected @pytest.mark.parametrize( 'input_data,unit,expected', [ (0, u'B', u'0.00 bits'), (0.5, u'B', u'0.50 bits'), (0.54, u'B', u'0.54 bits'), (1024, u'K', u'1.00 Kb'), (1536, u'K', u'1.50 Kb'), (1790, u'K', u'1.75 Kb'), (1048576, u'M', u'1.00 Mb'), (1099511627776, u'T', u'1.00 Tb'), (1152921504606846976, u'E', u'1.00 Eb'), (1180591620717411303424, u'Z', u'1.00 Zb'), (1208925819614629174706176, u'Y', u'1.00 Yb'), (1025, u'KB', u'1025.00 bits'), (1073741824, u'Gb', u'1073741824.00 bits'), (1125899906842624, u'Pb', u'1125899906842624.00 bits'), ] ) def test_bytes_to_human_unit_isbits(input_data, unit, expected): """Test unit argument of bytes_to_human function with isbits=True proper results.""" assert bytes_to_human(input_data, isbits=True, unit=unit) == expected @pytest.mark.parametrize('input_data', [0j, u'1B', [1], {1: 1}, None, b'1B']) def test_bytes_to_human_illegal_size(input_data): """Test of bytes_to_human function, illegal objects are passed as a size.""" e_regexp = (r'(no ordering relation is defined for complex numbers)|' r'(unsupported operand type\(s\) for /)|(unorderable types)|' r'(not supported between instances of)') with pytest.raises(TypeError, match=e_regexp): bytes_to_human(input_data)
4,045
Python
.py
102
32.843137
92
0.589822
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,870
test_human_to_bytes.py
ansible_ansible/test/units/module_utils/common/text/formatters/test_human_to_bytes.py
# -*- coding: utf-8 -*- # Copyright 2019, Andrew Klychkov @Andersson007 <aaklychkov@mail.ru> # Copyright 2019, Sviatoslav Sydorenko <webknjaz@redhat.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.common.text.formatters import human_to_bytes NUM_IN_METRIC = { 'K': 2 ** 10, 'M': 2 ** 20, 'G': 2 ** 30, 'T': 2 ** 40, 'P': 2 ** 50, 'E': 2 ** 60, 'Z': 2 ** 70, 'Y': 2 ** 80, } @pytest.mark.parametrize( 'input_data,expected', [ (0, 0), (u'0B', 0), (1024, NUM_IN_METRIC['K']), (u'1024B', NUM_IN_METRIC['K']), (u'1K', NUM_IN_METRIC['K']), (u'1KB', NUM_IN_METRIC['K']), (u'1M', NUM_IN_METRIC['M']), (u'1MB', NUM_IN_METRIC['M']), (u'1G', NUM_IN_METRIC['G']), (u'1GB', NUM_IN_METRIC['G']), (u'1T', NUM_IN_METRIC['T']), (u'1TB', NUM_IN_METRIC['T']), (u'1P', NUM_IN_METRIC['P']), (u'1PB', NUM_IN_METRIC['P']), (u'1E', NUM_IN_METRIC['E']), (u'1EB', NUM_IN_METRIC['E']), (u'1Z', NUM_IN_METRIC['Z']), (u'1ZB', NUM_IN_METRIC['Z']), (u'1Y', NUM_IN_METRIC['Y']), (u'1YB', NUM_IN_METRIC['Y']), ] ) def test_human_to_bytes_number(input_data, expected): """Test of human_to_bytes function, only number arg is passed.""" assert human_to_bytes(input_data) == expected @pytest.mark.parametrize( 'input_data,unit', [ (u'1024', 'B'), (1, u'K'), (1, u'KB'), (u'1', u'M'), (u'1', u'MB'), (1, u'G'), (1, u'GB'), (1, u'T'), (1, u'TB'), (u'1', u'P'), (u'1', u'PB'), (u'1', u'E'), (u'1', u'EB'), (u'1', u'Z'), (u'1', u'ZB'), (u'1', u'Y'), (u'1', u'YB'), ] ) def test_human_to_bytes_number_unit(input_data, unit): """Test of human_to_bytes function, number and default_unit args are passed.""" assert human_to_bytes(input_data, default_unit=unit) == NUM_IN_METRIC.get(unit[0], 1024) @pytest.mark.parametrize('test_input', [u'1024s', u'1024w', ]) def test_human_to_bytes_wrong_unit(test_input): """Test of human_to_bytes function, wrong units.""" with pytest.raises(ValueError, match="The suffix must be one of"): human_to_bytes(test_input) @pytest.mark.parametrize('test_input', [u'b1bbb', u'm2mmm', u'', u' ', -1]) def test_human_to_bytes_wrong_number(test_input): """Test of human_to_bytes function, number param is invalid string / number.""" with pytest.raises(ValueError, match="can't interpret"): human_to_bytes(test_input) @pytest.mark.parametrize( 'input_data,expected', [ (0, 0), (u'0B', 0), (u'1024b', 1024), (u'1024B', 1024), (u'1K', NUM_IN_METRIC['K']), (u'1Kb', NUM_IN_METRIC['K']), (u'1M', NUM_IN_METRIC['M']), (u'1Mb', NUM_IN_METRIC['M']), (u'1G', NUM_IN_METRIC['G']), (u'1Gb', NUM_IN_METRIC['G']), (u'1T', NUM_IN_METRIC['T']), (u'1Tb', NUM_IN_METRIC['T']), (u'1P', NUM_IN_METRIC['P']), (u'1Pb', NUM_IN_METRIC['P']), (u'1E', NUM_IN_METRIC['E']), (u'1Eb', NUM_IN_METRIC['E']), (u'1Z', NUM_IN_METRIC['Z']), (u'1Zb', NUM_IN_METRIC['Z']), (u'1Y', NUM_IN_METRIC['Y']), (u'1Yb', NUM_IN_METRIC['Y']), ] ) def test_human_to_bytes_isbits(input_data, expected): """Test of human_to_bytes function, isbits = True.""" assert human_to_bytes(input_data, isbits=True) == expected @pytest.mark.parametrize( 'input_data,unit', [ (1024, 'b'), (1024, 'B'), (1, u'K'), (1, u'Kb'), (u'1', u'M'), (u'1', u'Mb'), (1, u'G'), (1, u'Gb'), (1, u'T'), (1, u'Tb'), (u'1', u'P'), (u'1', u'Pb'), (u'1', u'E'), (u'1', u'Eb'), (u'1', u'Z'), (u'1', u'Zb'), (u'1', u'Y'), (u'1', u'Yb'), ] ) def test_human_to_bytes_isbits_default_unit(input_data, unit): """Test of human_to_bytes function, isbits = True and default_unit args are passed.""" assert human_to_bytes(input_data, default_unit=unit, isbits=True) == NUM_IN_METRIC.get(unit[0], 1024) @pytest.mark.parametrize( 'test_input,isbits', [ ('1024Kb', False), ('10Mb', False), ('1Gb', False), ('10MB', True), ('2KB', True), ('4GB', True), ] ) def test_human_to_bytes_isbits_wrong_unit(test_input, isbits): """Test of human_to_bytes function, unit identifier is in an invalid format for isbits value.""" with pytest.raises(ValueError, match="Value is not a valid string"): human_to_bytes(test_input, isbits=isbits) @pytest.mark.parametrize( 'test_input,unit,isbits', [ (1024, 'Kb', False), ('10', 'Mb', False), ('10', 'MB', True), (2, 'KB', True), ('4', 'GB', True), ] ) def test_human_to_bytes_isbits_wrong_default_unit(test_input, unit, isbits): """Test of human_to_bytes function, default_unit is in an invalid format for isbits value.""" with pytest.raises(ValueError, match="Value is not a valid string"): human_to_bytes(test_input, default_unit=unit, isbits=isbits) @pytest.mark.parametrize( 'test_input', [ '10 BBQ sticks please', '3000 GB guns of justice', '1 EBOOK please', '3 eBulletins please', '1 bBig family', ] ) def test_human_to_bytes_nonsensical_inputs_first_two_letter_unit(test_input): """Test of human_to_bytes function to ensure it raises ValueError for nonsensical inputs that has the first two letters as a unit.""" expected = "can't interpret following string" with pytest.raises(ValueError, match=expected): human_to_bytes(test_input) @pytest.mark.parametrize( 'test_input', [ '12,000 MB', '12 000 MB', '- |\n 1\n kB', ' 12', ' 12 MB', # OGHAM SPACE MARK '1\u200B000 MB', # U+200B zero-width space after 1 ] ) def test_human_to_bytes_non_number_truncate_result(test_input): """Test of human_to_bytes function to ensure it raises ValueError for handling non-number character and truncating result""" expected = "can't interpret following string" with pytest.raises(ValueError, match=expected): human_to_bytes(test_input) @pytest.mark.parametrize( 'test_input', [ '3 eBulletins', '.1 Geggabytes', '3 prettybytes', '13youcanhaveabyteofmysandwich', '.1 Geggabytes', '10 texasburgerbytes', '12 muppetbytes', ] ) def test_human_to_bytes_nonsensical(test_input): """Test of human_to_bytes function to ensure it raises ValueError for nonsensical input with first letter matches [BEGKMPTYZ] and word contains byte""" expected = "Value is not a valid string" with pytest.raises(ValueError, match=expected): human_to_bytes(test_input) @pytest.mark.parametrize( 'test_input', [ '8𖭙B', '၀k', '1.၀k?', '᭔ MB' ] ) def test_human_to_bytes_non_ascii_number(test_input): """Test of human_to_bytes function,correctly filtering out non ASCII characters""" expected = "can't interpret following string" with pytest.raises(ValueError, match=expected): human_to_bytes(test_input)
7,565
Python
.py
228
26.77193
117
0.565681
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,871
test_container_to_text.py
ansible_ansible/test/units/module_utils/common/text/converters/test_container_to_text.py
# -*- coding: utf-8 -*- # Copyright 2019, Andrew Klychkov @Andersson007 <aaklychkov@mail.ru> # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import container_to_text DEFAULT_ENCODING = 'utf-8' DEFAULT_ERR_HANDLER = 'surrogate_or_strict' @pytest.mark.parametrize( 'test_input,expected', [ ({1: 1}, {1: 1}), ([1, 2], [1, 2]), ((1, 2), (1, 2)), (1, 1), (1.1, 1.1), (b'str', u'str'), (u'str', u'str'), ([b'str'], [u'str']), ((b'str'), (u'str')), ({b'str': b'str'}, {u'str': u'str'}), ] ) @pytest.mark.parametrize('encoding', ['utf-8', 'latin1', 'shift-jis', 'big5', 'koi8_r', ]) @pytest.mark.parametrize('errors', ['strict', 'surrogate_or_strict', 'surrogate_then_replace', ]) def test_container_to_text_different_types(test_input, expected, encoding, errors): """Test for passing objects to container_to_text().""" assert container_to_text(test_input, encoding=encoding, errors=errors) == expected @pytest.mark.parametrize( 'test_input,expected', [ ({1: 1}, {1: 1}), ([1, 2], [1, 2]), ((1, 2), (1, 2)), (1, 1), (1.1, 1.1), (True, True), (None, None), (u'str', u'str'), (u'くらとみ'.encode(DEFAULT_ENCODING), u'くらとみ'), (u'café'.encode(DEFAULT_ENCODING), u'café'), (u'str'.encode(DEFAULT_ENCODING), u'str'), ([u'str'.encode(DEFAULT_ENCODING)], [u'str']), ((u'str'.encode(DEFAULT_ENCODING)), (u'str')), ({b'str': b'str'}, {u'str': u'str'}), ] ) def test_container_to_text_default_encoding_and_err(test_input, expected): """ Test for passing objects to container_to_text(). Default encoding and errors """ assert container_to_text(test_input, encoding=DEFAULT_ENCODING, errors=DEFAULT_ERR_HANDLER) == expected @pytest.mark.parametrize( 'test_input,encoding,expected', [ (u'й'.encode('utf-8'), 'latin1', u'й'), (u'café'.encode('utf-8'), 'shift_jis', u'cafテゥ'), ] ) @pytest.mark.parametrize('errors', ['strict', 'surrogate_or_strict', 'surrogate_then_replace', ]) def test_container_to_text_incomp_encod_chars(test_input, encoding, errors, expected): """ Test for passing incompatible characters and encodings container_to_text(). """ assert container_to_text(test_input, encoding=encoding, errors=errors) == expected
2,613
Python
.py
66
33.287879
106
0.605976
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,872
test_json_encode_fallback.py
ansible_ansible/test/units/module_utils/common/text/converters/test_json_encode_fallback.py
# -*- coding: utf-8 -*- # Copyright 2019, Andrew Klychkov @Andersson007 <aaklychkov@mail.ru> # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) from __future__ import annotations import pytest from datetime import datetime, timedelta, tzinfo from ansible.module_utils.common.text.converters import _json_encode_fallback class timezone(tzinfo): """Simple timezone implementation for use until we drop Python 2.7 support.""" def __init__(self, offset): self._offset = offset def utcoffset(self, dt): return self._offset @pytest.mark.parametrize( 'test_input,expected', [ (set([1]), [1]), (datetime(2019, 5, 14, 13, 39, 38, 569047), '2019-05-14T13:39:38.569047'), (datetime(2019, 5, 14, 13, 47, 16, 923866), '2019-05-14T13:47:16.923866'), (datetime(2019, 6, 15, 14, 45, tzinfo=timezone(timedelta(0))), '2019-06-15T14:45:00+00:00'), (datetime(2019, 6, 15, 14, 45, tzinfo=timezone(timedelta(hours=1, minutes=40))), '2019-06-15T14:45:00+01:40'), ] ) def test_json_encode_fallback(test_input, expected): """ Test for passing expected objects to _json_encode_fallback(). """ assert _json_encode_fallback(test_input) == expected @pytest.mark.parametrize( 'test_input', [ 1, 1.1, u'string', b'string', [1, 2], True, None, {1: 1}, (1, 2), ] ) def test_json_encode_fallback_default_behavior(test_input): """ Test for _json_encode_fallback() default behavior. It must fail with TypeError. """ with pytest.raises(TypeError, match='Cannot json serialize'): _json_encode_fallback(test_input)
1,752
Python
.py
49
30.265306
118
0.650503
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,873
test_container_to_bytes.py
ansible_ansible/test/units/module_utils/common/text/converters/test_container_to_bytes.py
# -*- coding: utf-8 -*- # Copyright 2019, Andrew Klychkov @Andersson007 <aaklychkov@mail.ru> # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import container_to_bytes DEFAULT_ENCODING = 'utf-8' DEFAULT_ERR_HANDLER = 'surrogate_or_strict' @pytest.mark.parametrize( 'test_input,expected', [ ({1: 1}, {1: 1}), ([1, 2], [1, 2]), ((1, 2), (1, 2)), (1, 1), (1.1, 1.1), (b'str', b'str'), (u'str', b'str'), ([u'str'], [b'str']), ((u'str'), (b'str')), ({u'str': u'str'}, {b'str': b'str'}), ] ) @pytest.mark.parametrize('encoding', ['utf-8', 'latin1', 'shift_jis', 'big5', 'koi8_r']) @pytest.mark.parametrize('errors', ['strict', 'surrogate_or_strict', 'surrogate_then_replace']) def test_container_to_bytes(test_input, expected, encoding, errors): """Test for passing objects to container_to_bytes().""" assert container_to_bytes(test_input, encoding=encoding, errors=errors) == expected @pytest.mark.parametrize( 'test_input,expected', [ ({1: 1}, {1: 1}), ([1, 2], [1, 2]), ((1, 2), (1, 2)), (1, 1), (1.1, 1.1), (True, True), (None, None), (u'str', u'str'.encode(DEFAULT_ENCODING)), (u'くらとみ', u'くらとみ'.encode(DEFAULT_ENCODING)), (u'café', u'café'.encode(DEFAULT_ENCODING)), (b'str', u'str'.encode(DEFAULT_ENCODING)), (u'str', u'str'.encode(DEFAULT_ENCODING)), ([u'str'], [u'str'.encode(DEFAULT_ENCODING)]), ((u'str'), (u'str'.encode(DEFAULT_ENCODING))), ({u'str': u'str'}, {u'str'.encode(DEFAULT_ENCODING): u'str'.encode(DEFAULT_ENCODING)}), ] ) def test_container_to_bytes_default_encoding_err(test_input, expected): """ Test for passing objects to container_to_bytes(). Default encoding and errors """ assert container_to_bytes(test_input, encoding=DEFAULT_ENCODING, errors=DEFAULT_ERR_HANDLER) == expected @pytest.mark.parametrize( 'test_input,encoding', [ (u'くらとみ', 'latin1'), (u'café', 'shift_jis'), ] ) @pytest.mark.parametrize('errors', ['surrogate_or_strict', 'strict']) def test_container_to_bytes_incomp_chars_and_encod(test_input, encoding, errors): """ Test for passing incompatible characters and encodings container_to_bytes(). """ with pytest.raises(UnicodeEncodeError, match="codec can't encode"): container_to_bytes(test_input, encoding=encoding, errors=errors) @pytest.mark.parametrize( 'test_input,encoding,expected', [ (u'くらとみ', 'latin1', b'????'), (u'café', 'shift_jis', b'caf?'), ] ) def test_container_to_bytes_surrogate_then_replace(test_input, encoding, expected): """ Test for container_to_bytes() with surrogate_then_replace err handler. """ assert container_to_bytes(test_input, encoding=encoding, errors='surrogate_then_replace') == expected
3,172
Python
.py
81
32.567901
106
0.61407
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,874
test_jsonify.py
ansible_ansible/test/units/module_utils/common/text/converters/test_jsonify.py
# -*- coding: utf-8 -*- # Copyright 2019, Andrew Klychkov @Andersson007 <aaklychkov@mail.ru> # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) from __future__ import annotations import pytest from ansible.module_utils.common.text.converters import jsonify @pytest.mark.parametrize( 'test_input,expected', [ (1, '1'), (u'string', u'"string"'), (u'くらとみ', u'"\\u304f\\u3089\\u3068\\u307f"'), (u'café', u'"caf\\u00e9"'), (b'string', u'"string"'), (False, u'false'), (u'string'.encode('utf-8'), u'"string"'), ] ) def test_jsonify(test_input, expected): """Test for jsonify().""" assert jsonify(test_input) == expected
760
Python
.py
21
30.904762
106
0.637241
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,875
test_to_str.py
ansible_ansible/test/units/module_utils/common/text/converters/test_to_str.py
# -*- coding: utf-8 -*- # (c) 2016 Toshio Kuratomi <tkuratomi@ansible.com> # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import itertools import pytest from ansible.module_utils.common.text.converters import to_text, to_bytes, to_native # Format: byte representation, text representation, encoding of byte representation VALID_STRINGS = ( (b'abcde', u'abcde', 'ascii'), (b'caf\xc3\xa9', u'caf\xe9', 'utf-8'), (b'caf\xe9', u'caf\xe9', 'latin-1'), # u'くらとみ' (b'\xe3\x81\x8f\xe3\x82\x89\xe3\x81\xa8\xe3\x81\xbf', u'\u304f\u3089\u3068\u307f', 'utf-8'), (b'\x82\xad\x82\xe7\x82\xc6\x82\xdd', u'\u304f\u3089\u3068\u307f', 'shift-jis'), ) @pytest.mark.parametrize('in_string, encoding, expected', itertools.chain(((d[0], d[2], d[1]) for d in VALID_STRINGS), ((d[1], d[2], d[1]) for d in VALID_STRINGS))) def test_to_text(in_string, encoding, expected): """test happy path of decoding to text""" assert to_text(in_string, encoding) == expected @pytest.mark.parametrize('in_string, encoding, expected', itertools.chain(((d[0], d[2], d[0]) for d in VALID_STRINGS), ((d[1], d[2], d[0]) for d in VALID_STRINGS))) def test_to_bytes(in_string, encoding, expected): """test happy path of encoding to bytes""" assert to_bytes(in_string, encoding) == expected @pytest.mark.parametrize('in_string, encoding, expected', itertools.chain(((d[0], d[2], d[1]) for d in VALID_STRINGS), ((d[1], d[2], d[1]) for d in VALID_STRINGS))) def test_to_native(in_string, encoding, expected): """test happy path of encoding to native strings""" assert to_native(in_string, encoding) == expected
1,946
Python
.py
35
47
96
0.619249
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,876
test_get_module_path.py
ansible_ansible/test/units/module_utils/basic/test_get_module_path.py
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016 Toshio Kuratomi <tkuratomi@ansible.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from units.mock.procenv import ModuleTestCase from unittest.mock import patch import builtins realimport = builtins.__import__ class TestGetModulePath(ModuleTestCase): def test_module_utils_basic_get_module_path(self): from ansible.module_utils.basic import get_module_path with patch('os.path.realpath', return_value='/path/to/foo/'): self.assertEqual(get_module_path(), '/path/to/foo')
715
Python
.py
15
44.133333
92
0.737752
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,877
test__symbolic_mode_to_octal.py
ansible_ansible/test/units/module_utils/basic/test__symbolic_mode_to_octal.py
# -*- coding: utf-8 -*- # Copyright: # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016-2017 Ansible Project # License: GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from ansible.module_utils.basic import AnsibleModule # # Info helpful for making new test cases: # # base_mode = {'dir no perms': 0o040000, # 'file no perms': 0o100000, # 'dir all perms': 0o400000 | 0o777, # 'file all perms': 0o100000, | 0o777} # # perm_bits = {'x': 0b001, # 'w': 0b010, # 'r': 0b100} # # role_shift = {'u': 6, # 'g': 3, # 'o': 0} DATA = ( # Going from no permissions to setting all for user, group, and/or other (0o040000, u'a+rwx', 0o0777), (0o040000, u'u+rwx,g+rwx,o+rwx', 0o0777), (0o040000, u'o+rwx', 0o0007), (0o040000, u'g+rwx', 0o0070), (0o040000, u'u+rwx', 0o0700), # Going from all permissions to none for user, group, and/or other (0o040777, u'a-rwx', 0o0000), (0o040777, u'u-rwx,g-rwx,o-rwx', 0o0000), (0o040777, u'o-rwx', 0o0770), (0o040777, u'g-rwx', 0o0707), (0o040777, u'u-rwx', 0o0077), # now using absolute assignment from None to a set of perms (0o040000, u'a=rwx', 0o0777), (0o040000, u'u=rwx,g=rwx,o=rwx', 0o0777), (0o040000, u'o=rwx', 0o0007), (0o040000, u'g=rwx', 0o0070), (0o040000, u'u=rwx', 0o0700), # X effect on files and dirs (0o040000, u'a+X', 0o0111), (0o100000, u'a+X', 0), (0o040000, u'a=X', 0o0111), (0o100000, u'a=X', 0), (0o040777, u'a-X', 0o0666), # Same as chmod but is it a bug? # chmod a-X statfile <== removes execute from statfile (0o100777, u'a-X', 0o0666), # Multiple permissions (0o040000, u'u=rw-x+X,g=r-x+X,o=r-x+X', 0o0755), (0o100000, u'u=rw-x+X,g=r-x+X,o=r-x+X', 0o0644), (0o040000, u'ug=rx,o=', 0o0550), (0o100000, u'ug=rx,o=', 0o0550), (0o040000, u'u=rx,g=r', 0o0540), (0o100000, u'u=rx,g=r', 0o0540), (0o040777, u'ug=rx,o=', 0o0550), (0o100777, u'ug=rx,o=', 0o0550), (0o040777, u'u=rx,g=r', 0o0547), (0o100777, u'u=rx,g=r', 0o0547), ) UMASK_DATA = ( (0o100000, '+rwx', 0o770), (0o100777, '-rwx', 0o007), ) INVALID_DATA = ( (0o040000, u'a=foo', "bad symbolic permission for mode: a=foo"), (0o040000, u'f=rwx', "bad symbolic permission for mode: f=rwx"), ) @pytest.mark.parametrize('stat_info, mode_string, expected', DATA) def test_good_symbolic_modes(mocker, stat_info, mode_string, expected): mock_stat = mocker.MagicMock() mock_stat.st_mode = stat_info assert AnsibleModule._symbolic_mode_to_octal(mock_stat, mode_string) == expected @pytest.mark.parametrize('stat_info, mode_string, expected', UMASK_DATA) def test_umask_with_symbolic_modes(mocker, stat_info, mode_string, expected): mock_umask = mocker.patch('os.umask') mock_umask.return_value = 0o7 mock_stat = mocker.MagicMock() mock_stat.st_mode = stat_info assert AnsibleModule._symbolic_mode_to_octal(mock_stat, mode_string) == expected @pytest.mark.parametrize('stat_info, mode_string, expected', INVALID_DATA) def test_invalid_symbolic_modes(mocker, stat_info, mode_string, expected): mock_stat = mocker.MagicMock() mock_stat.st_mode = stat_info with pytest.raises(ValueError) as exc: assert AnsibleModule._symbolic_mode_to_octal(mock_stat, mode_string) == 'blah' assert exc.match(expected)
3,447
Python
.py
89
35.033708
101
0.658778
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,878
test_exit_json.py
ansible_ansible/test/units/module_utils/basic/test_exit_json.py
# -*- coding: utf-8 -*- # Copyright (c) 2015-2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import json import sys import datetime import typing as t import pytest from ansible.module_utils.common import warnings EMPTY_INVOCATION: dict[str, dict[str, t.Any]] = {u'module_args': {}} DATETIME = datetime.datetime.strptime('2020-07-13 12:50:00', '%Y-%m-%d %H:%M:%S') class TestAnsibleModuleExitJson: """ Test that various means of calling exitJson and FailJson return the messages they've been given """ DATA: tuple[tuple[dict[str, t.Any]], ...] = ( ({}, {'invocation': EMPTY_INVOCATION}), ({'msg': 'message'}, {'msg': 'message', 'invocation': EMPTY_INVOCATION}), ({'msg': 'success', 'changed': True}, {'msg': 'success', 'changed': True, 'invocation': EMPTY_INVOCATION}), ({'msg': 'nochange', 'changed': False}, {'msg': 'nochange', 'changed': False, 'invocation': EMPTY_INVOCATION}), ({'msg': 'message', 'date': DATETIME.date()}, {'msg': 'message', 'date': DATETIME.date().isoformat(), 'invocation': EMPTY_INVOCATION}), ({'msg': 'message', 'datetime': DATETIME}, {'msg': 'message', 'datetime': DATETIME.isoformat(), 'invocation': EMPTY_INVOCATION}), ) @pytest.mark.parametrize('args, expected, stdin', ((a, e, {}) for a, e in DATA), indirect=['stdin']) def test_exit_json_exits(self, am, capfd, args, expected, monkeypatch): monkeypatch.setattr(warnings, '_global_deprecations', []) with pytest.raises(SystemExit) as ctx: am.exit_json(**args) assert ctx.value.code == 0 out, err = capfd.readouterr() return_val = json.loads(out) assert return_val == expected @pytest.mark.parametrize('args, expected, stdin', ((a, e, {}) for a, e in DATA if 'msg' in a), indirect=['stdin']) def test_fail_json_exits(self, am, capfd, args, expected, monkeypatch): monkeypatch.setattr(warnings, '_global_deprecations', []) with pytest.raises(SystemExit) as ctx: am.fail_json(**args) assert ctx.value.code == 1 out, err = capfd.readouterr() return_val = json.loads(out) # Fail_json should add failed=True expected['failed'] = True assert return_val == expected @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_fail_json_msg_positional(self, am, capfd, monkeypatch): monkeypatch.setattr(warnings, '_global_deprecations', []) with pytest.raises(SystemExit) as ctx: am.fail_json('This is the msg') assert ctx.value.code == 1 out, err = capfd.readouterr() return_val = json.loads(out) # Fail_json should add failed=True assert return_val == {'msg': 'This is the msg', 'failed': True, 'invocation': EMPTY_INVOCATION} @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_fail_json_msg_as_kwarg_after(self, am, capfd, monkeypatch): """Test that msg as a kwarg after other kwargs works""" monkeypatch.setattr(warnings, '_global_deprecations', []) with pytest.raises(SystemExit) as ctx: am.fail_json(arbitrary=42, msg='This is the msg') assert ctx.value.code == 1 out, err = capfd.readouterr() return_val = json.loads(out) # Fail_json should add failed=True assert return_val == {'msg': 'This is the msg', 'failed': True, 'arbitrary': 42, 'invocation': EMPTY_INVOCATION} @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_fail_json_no_msg(self, am): with pytest.raises(TypeError) as ctx: am.fail_json() if sys.version_info >= (3, 10): error_msg = "AnsibleModule.fail_json() missing 1 required positional argument: 'msg'" else: error_msg = "fail_json() missing 1 required positional argument: 'msg'" assert ctx.value.args[0] == error_msg class TestAnsibleModuleExitValuesRemoved: """ Test that ExitJson and FailJson remove password-like values """ OMIT = 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER' DATA = ( ( dict(username='person', password='$ecret k3y'), dict(one=1, pwd='$ecret k3y', url='https://username:password12345@foo.com/login/', not_secret='following the leader', msg='here'), dict(one=1, pwd=OMIT, url='https://username:password12345@foo.com/login/', not_secret='following the leader', msg='here', invocation=dict(module_args=dict(password=OMIT, token=None, username='person'))), ), ( dict(username='person', password='password12345'), dict(one=1, pwd='$ecret k3y', url='https://username:password12345@foo.com/login/', not_secret='following the leader', msg='here'), dict(one=1, pwd='$ecret k3y', url='https://username:********@foo.com/login/', not_secret='following the leader', msg='here', invocation=dict(module_args=dict(password=OMIT, token=None, username='person'))), ), ( dict(username='person', password='$ecret k3y'), dict(one=1, pwd='$ecret k3y', url='https://username:$ecret k3y@foo.com/login/', not_secret='following the leader', msg='here'), dict(one=1, pwd=OMIT, url='https://username:********@foo.com/login/', not_secret='following the leader', msg='here', invocation=dict(module_args=dict(password=OMIT, token=None, username='person'))), ), ) @pytest.mark.parametrize('am, stdin, return_val, expected', (({'username': {}, 'password': {'no_log': True}, 'token': {'no_log': True}}, s, r, e) for s, r, e in DATA), indirect=['am', 'stdin']) def test_exit_json_removes_values(self, am, capfd, return_val, expected, monkeypatch): monkeypatch.setattr(warnings, '_global_deprecations', []) with pytest.raises(SystemExit): am.exit_json(**return_val) out, err = capfd.readouterr() assert json.loads(out) == expected @pytest.mark.parametrize('am, stdin, return_val, expected', (({'username': {}, 'password': {'no_log': True}, 'token': {'no_log': True}}, s, r, e) for s, r, e in DATA), indirect=['am', 'stdin']) def test_fail_json_removes_values(self, am, capfd, return_val, expected, monkeypatch): monkeypatch.setattr(warnings, '_global_deprecations', []) expected['failed'] = True with pytest.raises(SystemExit): am.fail_json(**return_val) out, err = capfd.readouterr() assert json.loads(out) == expected
7,131
Python
.py
135
42.266667
114
0.588345
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,879
test_atomic_move.py
ansible_ansible/test/units/module_utils/basic/test_atomic_move.py
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016 Toshio Kuratomi <tkuratomi@ansible.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import os import errno import json from itertools import product import pytest from ansible.module_utils import basic from ansible.module_utils.common.file import S_IRWU_RG_RO @pytest.fixture def atomic_am(am, mocker): am.selinux_enabled = mocker.MagicMock() am.selinux_context = mocker.MagicMock() am.selinux_default_context = mocker.MagicMock() am.set_context_if_different = mocker.MagicMock() am._unsafe_writes = mocker.MagicMock() yield am @pytest.fixture def atomic_mocks(mocker, monkeypatch): environ = dict() mocks = { 'copystat': mocker.patch('shutil.copystat'), 'chmod': mocker.patch('os.chmod'), 'chown': mocker.patch('os.chown'), 'close': mocker.patch('os.close'), 'environ': mocker.patch('os.environ', environ), 'getlogin': mocker.patch('os.getlogin'), 'getuid': mocker.patch('os.getuid'), 'path_exists': mocker.patch('os.path.exists'), 'rename': mocker.patch('os.rename'), 'stat': mocker.patch('os.stat'), 'umask': mocker.patch('os.umask'), 'getpwuid': mocker.patch('pwd.getpwuid'), 'copy2': mocker.patch('shutil.copy2'), 'copyfileobj': mocker.patch('shutil.copyfileobj'), 'move': mocker.patch('shutil.move'), 'mkstemp': mocker.patch('tempfile.mkstemp'), 'utime': mocker.patch('os.utime'), } mocks['getlogin'].return_value = 'root' mocks['getuid'].return_value = 0 mocks['getpwuid'].return_value = ('root', '', 0, 0, '', '', '') mocks['umask'].side_effect = [18, 0] mocks['rename'].return_value = None # normalize OS specific features monkeypatch.delattr(os, 'chflags', raising=False) yield mocks @pytest.fixture def fake_stat(mocker): stat1 = mocker.MagicMock() stat1.st_mode = S_IRWU_RG_RO stat1.st_uid = 0 stat1.st_gid = 0 stat1.st_flags = 0 yield stat1 @pytest.mark.parametrize('stdin, selinux', product([{}], (True, False)), indirect=['stdin']) def test_new_file(atomic_am, atomic_mocks, mocker, selinux): # test destination does not exist, login name = 'root', no environment, os.rename() succeeds mock_context = atomic_am.selinux_default_context.return_value atomic_mocks['path_exists'].return_value = False atomic_am.selinux_enabled.return_value = selinux atomic_am.atomic_move('/path/to/src', '/path/to/dest') atomic_mocks['rename'].assert_called_with(b'/path/to/src', b'/path/to/dest') assert atomic_mocks['chmod'].call_args_list == [mocker.call(b'/path/to/dest', basic.DEFAULT_PERM & ~18)] if selinux: assert atomic_am.selinux_default_context.call_args_list == [mocker.call('/path/to/dest')] assert atomic_am.set_context_if_different.call_args_list == [mocker.call('/path/to/dest', mock_context, False)] else: assert not atomic_am.selinux_default_context.called assert not atomic_am.set_context_if_different.called @pytest.mark.parametrize('stdin, selinux', product([{}], (True, False)), indirect=['stdin']) def test_existing_file(atomic_am, atomic_mocks, fake_stat, mocker, selinux): # Test destination already present mock_context = atomic_am.selinux_context.return_value atomic_mocks['stat'].return_value = fake_stat atomic_mocks['path_exists'].return_value = True atomic_am.selinux_enabled.return_value = selinux atomic_am.atomic_move('/path/to/src', '/path/to/dest') atomic_mocks['rename'].assert_called_with(b'/path/to/src', b'/path/to/dest') assert atomic_mocks['copystat'].call_args_list == [mocker.call(b'/path/to/dest', b'/path/to/src')] if selinux: assert atomic_am.set_context_if_different.call_args_list == [mocker.call('/path/to/dest', mock_context, False)] assert atomic_am.selinux_context.call_args_list == [mocker.call('/path/to/dest')] else: assert not atomic_am.selinux_default_context.called assert not atomic_am.set_context_if_different.called @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_no_tty_fallback(atomic_am, atomic_mocks, fake_stat, mocker): """Raise OSError when using getlogin() to simulate no tty cornercase""" mock_context = atomic_am.selinux_context.return_value atomic_mocks['stat'].return_value = fake_stat atomic_mocks['path_exists'].return_value = True atomic_am.selinux_enabled.return_value = True atomic_mocks['getlogin'].side_effect = OSError() atomic_mocks['environ']['LOGNAME'] = 'root' atomic_am.atomic_move('/path/to/src', '/path/to/dest') atomic_mocks['rename'].assert_called_with(b'/path/to/src', b'/path/to/dest') assert atomic_mocks['copystat'].call_args_list == [mocker.call(b'/path/to/dest', b'/path/to/src')] assert atomic_mocks['chmod'].call_args_list == [] assert atomic_am.set_context_if_different.call_args_list == [mocker.call('/path/to/dest', mock_context, False)] assert atomic_am.selinux_context.call_args_list == [mocker.call('/path/to/dest')] @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_existing_file_stat_failure(atomic_am, atomic_mocks, mocker): """Failure to stat an existing file in order to copy permissions propogates the error (unless EPERM)""" atomic_mocks['copystat'].side_effect = FileNotFoundError('testing os copystat with non EPERM error') atomic_mocks['path_exists'].return_value = True with pytest.raises(FileNotFoundError, match='testing os copystat with non EPERM error'): atomic_am.atomic_move('/path/to/src', '/path/to/dest') @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_existing_file_stat_perms_failure(atomic_am, atomic_mocks, mocker): """Failure to stat an existing file to copy the permissions due to permissions passes fine""" # and now have os.copystat return EPERM, which should not fail mock_context = atomic_am.selinux_context.return_value atomic_mocks['copystat'].side_effect = OSError(errno.EPERM, 'testing os copystat with EPERM') atomic_mocks['path_exists'].return_value = True atomic_am.selinux_enabled.return_value = True atomic_am.atomic_move('/path/to/src', '/path/to/dest') atomic_mocks['rename'].assert_called_with(b'/path/to/src', b'/path/to/dest') # FIXME: Should atomic_move() set a default permission value when it cannot retrieve the # existing file's permissions? (Right now it's up to the calling code. assert atomic_mocks['copystat'].call_args_list == [mocker.call(b'/path/to/dest', b'/path/to/src')] assert atomic_am.set_context_if_different.call_args_list == [mocker.call('/path/to/dest', mock_context, False)] assert atomic_am.selinux_context.call_args_list == [mocker.call('/path/to/dest')] @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_rename_failure(atomic_am, atomic_mocks, mocker, capfd): """Test os.rename fails with EIO, causing it to bail out""" atomic_mocks['path_exists'].side_effect = [False, False] atomic_mocks['rename'].side_effect = OSError(errno.EIO, 'failing with EIO') with pytest.raises(SystemExit): atomic_am.atomic_move('/path/to/src', '/path/to/dest') out, err = capfd.readouterr() results = json.loads(out) assert 'Could not replace file' in results['msg'] assert 'failing with EIO' in results['msg'] assert results['failed'] @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_rename_perms_fail_temp_creation_fails(atomic_am, atomic_mocks, mocker, capfd): """Test os.rename fails with EPERM working but failure in mkstemp""" atomic_mocks['path_exists'].return_value = False atomic_mocks['close'].return_value = None atomic_mocks['rename'].side_effect = [OSError(errno.EPERM, 'failing with EPERM'), None] atomic_mocks['mkstemp'].return_value = None atomic_mocks['mkstemp'].side_effect = OSError() atomic_am.selinux_enabled.return_value = False with pytest.raises(SystemExit): atomic_am.atomic_move('/path/to/src', '/path/to/dest') out, err = capfd.readouterr() results = json.loads(out) assert 'is not writable by the current user' in results['msg'] assert results['failed'] @pytest.mark.parametrize('stdin, selinux', product([{}], (True, False)), indirect=['stdin']) def test_rename_perms_fail_temp_succeeds(atomic_am, atomic_mocks, fake_stat, mocker, selinux): """Test os.rename raising an error but fallback to using mkstemp works""" mock_context = atomic_am.selinux_default_context.return_value atomic_mocks['path_exists'].return_value = False atomic_mocks['rename'].side_effect = [OSError(errno.EPERM, 'failing with EPERM'), None] atomic_mocks['mkstemp'].return_value = (None, '/path/to/tempfile') atomic_mocks['mkstemp'].side_effect = None atomic_am.selinux_enabled.return_value = selinux atomic_am.atomic_move('/path/to/src', '/path/to/dest') assert atomic_mocks['rename'].call_args_list == [mocker.call(b'/path/to/src', b'/path/to/dest'), mocker.call(b'/path/to/tempfile', b'/path/to/dest')] assert atomic_mocks['chmod'].call_args_list == [mocker.call(b'/path/to/dest', basic.DEFAULT_PERM & ~18)] if selinux: assert atomic_am.selinux_default_context.call_args_list == [mocker.call('/path/to/dest')] assert atomic_am.set_context_if_different.call_args_list == [mocker.call(b'/path/to/tempfile', mock_context, False), mocker.call('/path/to/dest', mock_context, False)] else: assert not atomic_am.selinux_default_context.called assert not atomic_am.set_context_if_different.called
9,995
Python
.py
174
51.568966
124
0.687749
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,880
test_log.py
ansible_ansible/test/units/module_utils/basic/test_log.py
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import syslog from itertools import product import pytest class TestAnsibleModuleLogSmokeTest: DATA = [u'Text string', u'Toshio くらとみ non-ascii test'] DATA = DATA + [d.encode('utf-8') for d in DATA] DATA += [b'non-utf8 :\xff: test'] @pytest.mark.parametrize('msg, stdin', ((m, {}) for m in DATA), indirect=['stdin']) def test_smoketest_syslog(self, am, mocker, msg): # These talk to the live daemons on the system. Need to do this to # show that what we send doesn't cause an issue once it gets to the # daemon. These are just smoketests to test that we don't fail. mocker.patch('ansible.module_utils.basic.has_journal', False) am.log(u'Text string') am.log(u'Toshio くらとみ non-ascii test') am.log(b'Byte string') am.log(u'Toshio くらとみ non-ascii test'.encode('utf-8')) am.log(b'non-utf8 :\xff: test') class TestAnsibleModuleLogSyslog: """Test the AnsibleModule Log Method""" OUTPUT_DATA = [ (u'Text string', u'Text string'), (u'Toshio くらとみ non-ascii test', u'Toshio くらとみ non-ascii test'), (b'Byte string', u'Byte string'), (u'Toshio くらとみ non-ascii test'.encode('utf-8'), u'Toshio くらとみ non-ascii test'), (b'non-utf8 :\xff: test', b'non-utf8 :\xff: test'.decode('utf-8', 'replace')), ] @pytest.mark.parametrize('no_log, stdin', (product((True, False), [{}])), indirect=['stdin']) def test_no_log(self, am, mocker, no_log): """Test that when no_log is set, logging does not occur""" mock_syslog = mocker.patch('syslog.syslog', autospec=True) mocker.patch('ansible.module_utils.basic.has_journal', False) am.no_log = no_log am.log('unittest no_log') if no_log: assert not mock_syslog.called else: mock_syslog.assert_called_once_with(syslog.LOG_INFO, 'unittest no_log') @pytest.mark.parametrize('msg, param, stdin', ((m, p, {}) for m, p in OUTPUT_DATA), indirect=['stdin']) def test_output_matches(self, am, mocker, msg, param): """Check that log messages are sent correctly""" mocker.patch('ansible.module_utils.basic.has_journal', False) mock_syslog = mocker.patch('syslog.syslog', autospec=True) am.log(msg) mock_syslog.assert_called_once_with(syslog.LOG_INFO, param)
2,711
Python
.py
52
43.288462
97
0.634994
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,881
test_safe_eval.py
ansible_ansible/test/units/module_utils/basic/test_safe_eval.py
# -*- coding: utf-8 -*- # (c) 2015-2017, Toshio Kuratomi <tkuratomi@ansible.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from itertools import chain import typing as t import pytest # Strings that should be converted into a typed value VALID_STRINGS: tuple[tuple[str, t.Any], ...] = ( ("'a'", 'a'), ("'1'", '1'), ("1", 1), ("True", True), ("False", False), ("{}", {}), ) # Passing things that aren't strings should just return the object NONSTRINGS = ( ({'a': 1}, {'a': 1}), ) # These strings are not basic types. For security, these should not be # executed. We return the same string and get an exception for some INVALID_STRINGS = ( ("a=1", "a=1", SyntaxError), ("a.foo()", "a.foo()", None), ("import foo", "import foo", None), ("__import__('foo')", "__import__('foo')", ValueError), ) @pytest.mark.parametrize('code, expected, stdin', ((c, e, {}) for c, e in chain(VALID_STRINGS, NONSTRINGS)), indirect=['stdin']) def test_simple_types(am, code, expected): # test some basic usage for various types assert am.safe_eval(code) == expected @pytest.mark.parametrize('code, expected, stdin', ((c, e, {}) for c, e in chain(VALID_STRINGS, NONSTRINGS)), indirect=['stdin']) def test_simple_types_with_exceptions(am, code, expected): # Test simple types with exceptions requested assert am.safe_eval(code, include_exceptions=True), (expected, None) @pytest.mark.parametrize('code, expected, stdin', ((c, e, {}) for c, e, dummy in INVALID_STRINGS), indirect=['stdin']) def test_invalid_strings(am, code, expected): assert am.safe_eval(code) == expected @pytest.mark.parametrize('code, expected, exception, stdin', ((c, e, ex, {}) for c, e, ex in INVALID_STRINGS), indirect=['stdin']) def test_invalid_strings_with_exceptions(am, code, expected, exception): res = am.safe_eval(code, include_exceptions=True) assert res[0] == expected if exception is None: assert res[1] == exception else: assert isinstance(res[1], exception)
2,321
Python
.py
55
35.527273
92
0.612
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,882
test_filesystem.py
ansible_ansible/test/units/module_utils/basic/test_filesystem.py
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016 Toshio Kuratomi <tkuratomi@ansible.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from units.mock.procenv import ModuleTestCase from unittest.mock import patch, MagicMock import builtins realimport = builtins.__import__ class TestOtherFilesystem(ModuleTestCase): def test_module_utils_basic_ansible_module_user_and_group(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec=dict(), ) mock_stat = MagicMock() mock_stat.st_uid = 0 mock_stat.st_gid = 0 with patch('os.lstat', return_value=mock_stat): self.assertEqual(am.user_and_group('/path/to/file'), (0, 0)) def test_module_utils_basic_ansible_module_find_mount_point(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec=dict(), ) def _mock_ismount(path): if path == b'/': return True return False with patch('os.path.ismount', side_effect=_mock_ismount): self.assertEqual(am.find_mount_point('/root/fs/../mounted/path/to/whatever'), '/') def _mock_ismount(path): if path == b'/subdir/mount': return True return False with patch('os.path.ismount', side_effect=_mock_ismount): self.assertEqual(am.find_mount_point('/subdir/mount/path/to/whatever'), '/subdir/mount') def test_module_utils_basic_ansible_module_set_owner_if_different(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec=dict(), ) assert am.set_owner_if_different('/path/to/file', None, True) assert not am.set_owner_if_different('/path/to/file', None, False) am.user_and_group = MagicMock(return_value=(500, 500)) with patch('os.lchown', return_value=None) as m: assert am.set_owner_if_different('/path/to/file', 0, False) m.assert_called_with(b'/path/to/file', 0, -1) def _mock_getpwnam(*args, **kwargs): mock_pw = MagicMock() mock_pw.pw_uid = 0 return mock_pw m.reset_mock() with patch('pwd.getpwnam', side_effect=_mock_getpwnam): assert am.set_owner_if_different('/path/to/file', 'root', False) m.assert_called_with(b'/path/to/file', 0, -1) with patch('pwd.getpwnam', side_effect=KeyError): self.assertRaises(SystemExit, am.set_owner_if_different, '/path/to/file', 'root', False) m.reset_mock() am.check_mode = True assert am.set_owner_if_different('/path/to/file', 0, False) assert not m.called am.check_mode = False with patch('os.lchown', side_effect=OSError) as m: self.assertRaises(SystemExit, am.set_owner_if_different, '/path/to/file', 'root', False) def test_module_utils_basic_ansible_module_set_group_if_different(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec=dict(), ) assert am.set_group_if_different('/path/to/file', None, True) assert not am.set_group_if_different('/path/to/file', None, False) am.user_and_group = MagicMock(return_value=(500, 500)) with patch('os.lchown', return_value=None) as m: assert am.set_group_if_different('/path/to/file', 0, False) m.assert_called_with(b'/path/to/file', -1, 0) def _mock_getgrnam(*args, **kwargs): mock_gr = MagicMock() mock_gr.gr_gid = 0 return mock_gr m.reset_mock() with patch('grp.getgrnam', side_effect=_mock_getgrnam): assert am.set_group_if_different('/path/to/file', 'root', False) m.assert_called_with(b'/path/to/file', -1, 0) with patch('grp.getgrnam', side_effect=KeyError): self.assertRaises(SystemExit, am.set_group_if_different, '/path/to/file', 'root', False) m.reset_mock() am.check_mode = True assert am.set_group_if_different('/path/to/file', 0, False) assert not m.called am.check_mode = False with patch('os.lchown', side_effect=OSError) as m: self.assertRaises(SystemExit, am.set_group_if_different, '/path/to/file', 'root', False) def test_module_utils_basic_ansible_module_set_directory_attributes_if_different(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec=dict(), ) am.selinux_enabled = lambda: False file_args = { 'path': '/path/to/file', 'mode': None, 'owner': None, 'group': None, 'seuser': None, 'serole': None, 'setype': None, 'selevel': None, 'secontext': [None, None, None], 'attributes': None, } assert am.set_directory_attributes_if_different(file_args, True) assert not am.set_directory_attributes_if_different(file_args, False)
5,640
Python
.py
119
36.478992
104
0.597884
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,883
test_command_nonexisting.py
ansible_ansible/test/units/module_utils/basic/test_command_nonexisting.py
from __future__ import annotations import json import sys import pytest import subprocess from ansible.module_utils.common.text.converters import to_bytes from ansible.module_utils import basic def test_run_non_existent_command(monkeypatch): """ Test that `command` returns std{out,err} even if the executable is not found """ def fail_json(msg, **kwargs): assert kwargs["stderr"] == b'' assert kwargs["stdout"] == b'' sys.exit(1) def popen(*args, **kwargs): raise OSError() monkeypatch.setattr(basic, '_ANSIBLE_ARGS', to_bytes(json.dumps({'ANSIBLE_MODULE_ARGS': {}}))) monkeypatch.setattr(subprocess, 'Popen', popen) am = basic.AnsibleModule(argument_spec={}) monkeypatch.setattr(am, 'fail_json', fail_json) with pytest.raises(SystemExit): am.run_command("lecho", "whatever")
855
Python
.py
21
36
98
0.701691
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,884
test_imports.py
ansible_ansible/test/units/module_utils/basic/test_imports.py
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016 Toshio Kuratomi <tkuratomi@ansible.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import sys from units.mock.procenv import ModuleTestCase from unittest.mock import patch import builtins realimport = builtins.__import__ class TestImports(ModuleTestCase): def clear_modules(self, mods): for mod in mods: if mod in sys.modules: del sys.modules[mod] @patch.object(builtins, '__import__') def test_module_utils_basic_import_syslog(self, mock_import): def _mock_import(name, *args, **kwargs): if name == 'syslog': raise ImportError return realimport(name, *args, **kwargs) self.clear_modules(['syslog', 'ansible.module_utils.basic']) mod = builtins.__import__('ansible.module_utils.basic') self.assertTrue(mod.module_utils.basic.HAS_SYSLOG) self.clear_modules(['syslog', 'ansible.module_utils.basic']) mock_import.side_effect = _mock_import mod = builtins.__import__('ansible.module_utils.basic') self.assertFalse(mod.module_utils.basic.HAS_SYSLOG) @patch.object(builtins, '__import__') def test_module_utils_basic_import_selinux(self, mock_import): def _mock_import(name, globals=None, locals=None, fromlist=tuple(), level=0, **kwargs): if name == 'ansible.module_utils.compat' and fromlist == ('selinux',): raise ImportError return realimport(name, globals=globals, locals=locals, fromlist=fromlist, level=level, **kwargs) try: self.clear_modules(['ansible.module_utils.compat.selinux', 'ansible.module_utils.basic']) mod = builtins.__import__('ansible.module_utils.basic') self.assertTrue(mod.module_utils.basic.HAVE_SELINUX) except ImportError: # no selinux on test system, so skip pass self.clear_modules(['ansible.module_utils.compat.selinux', 'ansible.module_utils.basic']) mock_import.side_effect = _mock_import mod = builtins.__import__('ansible.module_utils.basic') self.assertFalse(mod.module_utils.basic.HAVE_SELINUX) # FIXME: doesn't work yet # @patch.object(builtins, 'bytes') # def test_module_utils_basic_bytes(self, mock_bytes): # mock_bytes.side_effect = NameError() # from ansible.module_utils import basic @patch.object(builtins, '__import__') def test_module_utils_basic_import_systemd_journal(self, mock_import): def _mock_import(name, *args, **kwargs): try: fromlist = kwargs.get('fromlist', args[2]) except IndexError: fromlist = [] if name == 'systemd' and 'journal' in fromlist: raise ImportError return realimport(name, *args, **kwargs) self.clear_modules(['systemd', 'ansible.module_utils.basic']) mod = builtins.__import__('ansible.module_utils.basic') self.assertTrue(mod.module_utils.basic.has_journal) self.clear_modules(['systemd', 'ansible.module_utils.basic']) mock_import.side_effect = _mock_import mod = builtins.__import__('ansible.module_utils.basic') self.assertFalse(mod.module_utils.basic.has_journal)
3,476
Python
.py
68
42.441176
109
0.651622
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,885
test_set_cwd.py
ansible_ansible/test/units/module_utils/basic/test_set_cwd.py
# -*- coding: utf-8 -*- # Copyright (c) 2018 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import json import os import tempfile from unittest.mock import patch from ansible.module_utils.common.text.converters import to_bytes from ansible.module_utils import basic class TestAnsibleModuleSetCwd: def test_set_cwd(self, monkeypatch): """make sure /tmp is used""" def mock_getcwd(): return '/tmp' def mock_access(path, perm): return True def mock_chdir(path): pass monkeypatch.setattr(os, 'getcwd', mock_getcwd) monkeypatch.setattr(os, 'access', mock_access) monkeypatch.setattr(basic, '_ANSIBLE_ARGS', to_bytes(json.dumps({'ANSIBLE_MODULE_ARGS': {}}))) with patch('time.time', return_value=42): am = basic.AnsibleModule(argument_spec={}) result = am._set_cwd() assert result == '/tmp' def test_set_cwd_unreadable_use_self_tmpdir(self, monkeypatch): """pwd is not readable, use instance's tmpdir property""" def mock_getcwd(): return '/tmp' def mock_access(path, perm): if path == '/tmp' and perm == 4: return False return True def mock_expandvars(var): if var == '$HOME': return '/home/foobar' return var def mock_gettempdir(): return '/tmp/testdir' def mock_chdir(path): if path == '/tmp': raise Exception() return monkeypatch.setattr(os, 'getcwd', mock_getcwd) monkeypatch.setattr(os, 'chdir', mock_chdir) monkeypatch.setattr(os, 'access', mock_access) monkeypatch.setattr(os.path, 'expandvars', mock_expandvars) monkeypatch.setattr(basic, '_ANSIBLE_ARGS', to_bytes(json.dumps({'ANSIBLE_MODULE_ARGS': {}}))) with patch('time.time', return_value=42): am = basic.AnsibleModule(argument_spec={}) am._tmpdir = '/tmp2' result = am._set_cwd() assert result == am._tmpdir def test_set_cwd_unreadable_use_home(self, monkeypatch): """cwd and instance tmpdir are unreadable, use home""" def mock_getcwd(): return '/tmp' def mock_access(path, perm): if path in ['/tmp', '/tmp2'] and perm == 4: return False return True def mock_expandvars(var): if var == '$HOME': return '/home/foobar' return var def mock_gettempdir(): return '/tmp/testdir' def mock_chdir(path): if path == '/tmp': raise Exception() return monkeypatch.setattr(os, 'getcwd', mock_getcwd) monkeypatch.setattr(os, 'chdir', mock_chdir) monkeypatch.setattr(os, 'access', mock_access) monkeypatch.setattr(os.path, 'expandvars', mock_expandvars) monkeypatch.setattr(basic, '_ANSIBLE_ARGS', to_bytes(json.dumps({'ANSIBLE_MODULE_ARGS': {}}))) with patch('time.time', return_value=42): am = basic.AnsibleModule(argument_spec={}) am._tmpdir = '/tmp2' result = am._set_cwd() assert result == '/home/foobar' def test_set_cwd_unreadable_use_gettempdir(self, monkeypatch): """fallback to tempfile.gettempdir""" thisdir = None def mock_getcwd(): return '/tmp' def mock_access(path, perm): if path in ['/tmp', '/tmp2', '/home/foobar'] and perm == 4: return False return True def mock_expandvars(var): if var == '$HOME': return '/home/foobar' return var def mock_gettempdir(): return '/tmp3' def mock_chdir(path): if path == '/tmp': raise Exception() thisdir = path monkeypatch.setattr(os, 'getcwd', mock_getcwd) monkeypatch.setattr(os, 'chdir', mock_chdir) monkeypatch.setattr(os, 'access', mock_access) monkeypatch.setattr(os.path, 'expandvars', mock_expandvars) monkeypatch.setattr(basic, '_ANSIBLE_ARGS', to_bytes(json.dumps({'ANSIBLE_MODULE_ARGS': {}}))) with patch('time.time', return_value=42): am = basic.AnsibleModule(argument_spec={}) am._tmpdir = '/tmp2' monkeypatch.setattr(tempfile, 'gettempdir', mock_gettempdir) result = am._set_cwd() assert result == '/tmp3' def test_set_cwd_unreadable_use_None(self, monkeypatch): """all paths are unreable, should return None and not an exception""" def mock_getcwd(): return '/tmp' def mock_access(path, perm): if path in ['/tmp', '/tmp2', '/tmp3', '/home/foobar'] and perm == 4: return False return True def mock_expandvars(var): if var == '$HOME': return '/home/foobar' return var def mock_gettempdir(): return '/tmp3' def mock_chdir(path): if path == '/tmp': raise Exception() monkeypatch.setattr(os, 'getcwd', mock_getcwd) monkeypatch.setattr(os, 'chdir', mock_chdir) monkeypatch.setattr(os, 'access', mock_access) monkeypatch.setattr(os.path, 'expandvars', mock_expandvars) monkeypatch.setattr(basic, '_ANSIBLE_ARGS', to_bytes(json.dumps({'ANSIBLE_MODULE_ARGS': {}}))) with patch('time.time', return_value=42): am = basic.AnsibleModule(argument_spec={}) am._tmpdir = '/tmp2' monkeypatch.setattr(tempfile, 'gettempdir', mock_gettempdir) result = am._set_cwd() assert result is None
5,891
Python
.py
140
31.692857
102
0.581302
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,886
test_get_file_attributes.py
ansible_ansible/test/units/module_utils/basic/test_get_file_attributes.py
# -*- coding: utf-8 -*- # Copyright: # (c) 2017, Pierre-Louis Bonicoli <pierre-louis@libregerbil.fr> # License: GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from itertools import product from ansible.module_utils.basic import AnsibleModule import pytest DATA = ( ( '3353595900 --------------e---- /usr/lib32', {'attr_flags': 'e', 'version': '3353595900', 'attributes': ['extents']} ), # with e2fsprogs < 1.43, output isn't aligned ( '78053594 -----------I--e---- /usr/lib', {'attr_flags': 'Ie', 'version': '78053594', 'attributes': ['indexed', 'extents']} ), ( '15711607 -------A------e---- /tmp/test', {'attr_flags': 'Ae', 'version': '15711607', 'attributes': ['noatime', 'extents']} ), # with e2fsprogs >= 1.43, output is aligned ( '78053594 -----------I--e---- /usr/lib', {'attr_flags': 'Ie', 'version': '78053594', 'attributes': ['indexed', 'extents']} ), ( '15711607 -------A------e---- /tmp/test', {'attr_flags': 'Ae', 'version': '15711607', 'attributes': ['noatime', 'extents']} ), ) NO_VERSION_DATA = ( ( '--------------e---- /usr/lib32', {'attr_flags': 'e', 'attributes': ['extents']} ), ( '-----------I--e---- /usr/lib', {'attr_flags': 'Ie', 'attributes': ['indexed', 'extents']} ), ( '-------A------e---- /tmp/test', {'attr_flags': 'Ae', 'attributes': ['noatime', 'extents']} ), ) @pytest.mark.parametrize('stdin, data', product(({},), DATA), indirect=['stdin']) def test_get_file_attributes(am, stdin, mocker, data): # Test #18731 mocker.patch.object(AnsibleModule, 'get_bin_path', return_value=(0, '/usr/bin/lsattr', '')) mocker.patch.object(AnsibleModule, 'run_command', return_value=(0, data[0], '')) result = am.get_file_attributes('/path/to/file') for key, value in data[1].items(): assert key in result and result[key] == value @pytest.mark.parametrize('stdin, data', product(({},), NO_VERSION_DATA), indirect=['stdin']) def test_get_file_attributes_no_version(am, stdin, mocker, data): # Test #18731 mocker.patch.object(AnsibleModule, 'get_bin_path', return_value=(0, '/usr/bin/lsattr', '')) mocker.patch.object(AnsibleModule, 'run_command', return_value=(0, data[0], '')) result = am.get_file_attributes('/path/to/file', include_version=False) for key, value in data[1].items(): assert key in result and result[key] == value
2,599
Python
.py
62
36.612903
101
0.576801
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,887
test_deprecate_warn.py
ansible_ansible/test/units/module_utils/basic/test_deprecate_warn.py
# -*- coding: utf-8 -*- # # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import json import pytest from ansible.module_utils.common import warnings @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_warn(am, capfd): am.warn('warning1') with pytest.raises(SystemExit): am.exit_json(warnings=['warning2']) out, err = capfd.readouterr() assert json.loads(out)['warnings'] == ['warning1', 'warning2'] @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_deprecate(am, capfd, monkeypatch): monkeypatch.setattr(warnings, '_global_deprecations', []) am.deprecate('deprecation1') # pylint: disable=ansible-deprecated-no-version am.deprecate('deprecation2', '2.3') # pylint: disable=ansible-deprecated-version am.deprecate('deprecation3', version='2.4') # pylint: disable=ansible-deprecated-version am.deprecate('deprecation4', date='2020-03-10') am.deprecate('deprecation5', collection_name='ansible.builtin') # pylint: disable=ansible-deprecated-no-version am.deprecate('deprecation6', '2.3', collection_name='ansible.builtin') # pylint: disable=ansible-deprecated-version am.deprecate('deprecation7', version='2.4', collection_name='ansible.builtin') # pylint: disable=ansible-deprecated-version am.deprecate('deprecation8', date='2020-03-10', collection_name='ansible.builtin') with pytest.raises(SystemExit): am.exit_json(deprecations=['deprecation9', ('deprecation10', '2.4')]) out, err = capfd.readouterr() output = json.loads(out) assert ('warnings' not in output or output['warnings'] == []) assert output['deprecations'] == [ {u'msg': u'deprecation1', u'version': None, u'collection_name': None}, {u'msg': u'deprecation2', u'version': '2.3', u'collection_name': None}, {u'msg': u'deprecation3', u'version': '2.4', u'collection_name': None}, {u'msg': u'deprecation4', u'date': '2020-03-10', u'collection_name': None}, {u'msg': u'deprecation5', u'version': None, u'collection_name': 'ansible.builtin'}, {u'msg': u'deprecation6', u'version': '2.3', u'collection_name': 'ansible.builtin'}, {u'msg': u'deprecation7', u'version': '2.4', u'collection_name': 'ansible.builtin'}, {u'msg': u'deprecation8', u'date': '2020-03-10', u'collection_name': 'ansible.builtin'}, {u'msg': u'deprecation9', u'version': None, u'collection_name': None}, {u'msg': u'deprecation10', u'version': '2.4', u'collection_name': None}, ] @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_deprecate_without_list(am, capfd): with pytest.raises(SystemExit): am.exit_json(deprecations='Simple deprecation warning') out, err = capfd.readouterr() output = json.loads(out) assert ('warnings' not in output or output['warnings'] == []) assert output['deprecations'] == [ {u'msg': u'Simple deprecation warning', u'version': None, u'collection_name': None}, ] @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_deprecate_without_list_version_date_not_set(am, capfd): with pytest.raises(AssertionError) as ctx: am.deprecate('Simple deprecation warning', date='', version='') # pylint: disable=ansible-deprecated-no-version assert ctx.value.args[0] == "implementation error -- version and date must not both be set"
3,515
Python
.py
58
55.362069
128
0.682466
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,888
test_dict_converters.py
ansible_ansible/test/units/module_utils/basic/test_dict_converters.py
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016 Toshio Kuratomi <tkuratomi@ansible.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from units.mock.procenv import ModuleTestCase import builtins realimport = builtins.__import__ class TestTextifyContainers(ModuleTestCase): def test_module_utils_basic_json_dict_converters(self): from ansible.module_utils.basic import json_dict_unicode_to_bytes, json_dict_bytes_to_unicode test_data = dict( item1=u"Fóo", item2=[u"Bár", u"Bam"], item3=dict(sub1=u"Súb"), item4=(u"föo", u"bär", u"©"), item5=42, ) res = json_dict_unicode_to_bytes(test_data) res2 = json_dict_bytes_to_unicode(res) self.assertEqual(test_data, res2)
945
Python
.py
22
36.227273
101
0.666667
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,889
test_argument_spec.py
ansible_ansible/test/units/module_utils/basic/test_argument_spec.py
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016 Toshio Kuratomi <tkuratomi@ansible.com> # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import json import os import typing as t import pytest from unittest.mock import MagicMock from ansible.module_utils import basic from ansible.module_utils.api import basic_auth_argument_spec, rate_limit_argument_spec, retry_argument_spec from ansible.module_utils.common import warnings from ansible.module_utils.common.warnings import get_deprecation_messages, get_warning_messages import builtins MOCK_VALIDATOR_FAIL = MagicMock(side_effect=TypeError("bad conversion")) # Data is argspec, argument, expected VALID_SPECS = ( # Simple type=int ({'arg': {'type': 'int'}}, {'arg': 42}, 42), # Simple type=int with a large value (will be of type long under Python 2) ({'arg': {'type': 'int'}}, {'arg': 18765432109876543210}, 18765432109876543210), # Simple type=list, elements=int ({'arg': {'type': 'list', 'elements': 'int'}}, {'arg': [42, 32]}, [42, 32]), # Type=int with conversion from string ({'arg': {'type': 'int'}}, {'arg': '42'}, 42), # Type=list elements=int with conversion from string ({'arg': {'type': 'list', 'elements': 'int'}}, {'arg': ['42', '32']}, [42, 32]), # Simple type=float ({'arg': {'type': 'float'}}, {'arg': 42.0}, 42.0), # Simple type=list, elements=float ({'arg': {'type': 'list', 'elements': 'float'}}, {'arg': [42.1, 32.2]}, [42.1, 32.2]), # Type=float conversion from int ({'arg': {'type': 'float'}}, {'arg': 42}, 42.0), # type=list, elements=float conversion from int ({'arg': {'type': 'list', 'elements': 'float'}}, {'arg': [42, 32]}, [42.0, 32.0]), # Type=float conversion from string ({'arg': {'type': 'float'}}, {'arg': '42.0'}, 42.0), # type=list, elements=float conversion from string ({'arg': {'type': 'list', 'elements': 'float'}}, {'arg': ['42.1', '32.2']}, [42.1, 32.2]), # Type=float conversion from string without decimal point ({'arg': {'type': 'float'}}, {'arg': '42'}, 42.0), # Type=list elements=float conversion from string without decimal point ({'arg': {'type': 'list', 'elements': 'float'}}, {'arg': ['42', '32.2']}, [42.0, 32.2]), # Simple type=bool ({'arg': {'type': 'bool'}}, {'arg': True}, True), # Simple type=list elements=bool ({'arg': {'type': 'list', 'elements': 'bool'}}, {'arg': [True, 'true', 1, 'yes', False, 'false', 'no', 0]}, [True, True, True, True, False, False, False, False]), # Type=int with conversion from string ({'arg': {'type': 'bool'}}, {'arg': 'yes'}, True), # Type=str converts to string ({'arg': {'type': 'str'}}, {'arg': 42}, '42'), # Type=list elements=str simple converts to string ({'arg': {'type': 'list', 'elements': 'str'}}, {'arg': ['42', '32']}, ['42', '32']), # Type is implicit, converts to string ({'arg': {'type': 'str'}}, {'arg': 42}, '42'), # Type=list elements=str implicit converts to string ({'arg': {'type': 'list', 'elements': 'str'}}, {'arg': [42, 32]}, ['42', '32']), # parameter is required ({'arg': {'required': True}}, {'arg': 42}, '42'), # ignored unknown parameters ({'arg': {'type': 'int'}}, {'arg': 1, 'invalid': True, '_ansible_ignore_unknown_opts': True}, 1), ) INVALID_SPECS: tuple[tuple[dict[str, t.Any], dict[str, t.Any], str], ...] = ( # Type is int; unable to convert this string ({'arg': {'type': 'int'}}, {'arg': "wolf"}, f"is of type {type('wolf')} and we were unable to convert to int:"), # Type is list elements is int; unable to convert this string ({'arg': {'type': 'list', 'elements': 'int'}}, {'arg': [1, "bad"]}, "is of type {0} and we were unable to convert to int:".format(type('int'))), # Type is int; unable to convert float ({'arg': {'type': 'int'}}, {'arg': 42.1}, "'float'> and we were unable to convert to int:"), # Type is list, elements is int; unable to convert float ({'arg': {'type': 'list', 'elements': 'int'}}, {'arg': [42.1, 32, 2]}, "'float'> and we were unable to convert to int:"), # type is a callable that fails to convert ({'arg': {'type': MOCK_VALIDATOR_FAIL}}, {'arg': "bad"}, "bad conversion"), # type is a list, elements is callable that fails to convert ({'arg': {'type': 'list', 'elements': MOCK_VALIDATOR_FAIL}}, {'arg': [1, "bad"]}, "bad conversion"), # unknown parameter ({'arg': {'type': 'int'}}, {'other': 'bad', '_ansible_module_name': 'ansible_unittest'}, 'Unsupported parameters for (ansible_unittest) module: other. Supported parameters include: arg.'), ({'arg': {'type': 'int', 'aliases': ['argument']}}, {'other': 'bad', '_ansible_module_name': 'ansible_unittest'}, 'Unsupported parameters for (ansible_unittest) module: other. Supported parameters include: arg (argument).'), # parameter is required ({'arg': {'required': True}}, {}, 'missing required arguments: arg'), ) BASIC_AUTH_VALID_ARGS = [ {'api_username': 'user1', 'api_password': 'password1', 'api_url': 'http://example.com', 'validate_certs': False}, {'api_username': 'user1', 'api_password': 'password1', 'api_url': 'http://example.com', 'validate_certs': True}, ] RATE_LIMIT_VALID_ARGS = [ {'rate': 1, 'rate_limit': 1}, {'rate': '1', 'rate_limit': 1}, {'rate': 1, 'rate_limit': '1'}, {'rate': '1', 'rate_limit': '1'}, ] RETRY_VALID_ARGS = [ {'retries': 1, 'retry_pause': 1.5}, {'retries': '1', 'retry_pause': '1.5'}, {'retries': 1, 'retry_pause': '1.5'}, {'retries': '1', 'retry_pause': 1.5}, ] @pytest.fixture def complex_argspec(): arg_spec = dict( foo=dict(required=True, aliases=['dup']), bar=dict(), bam=dict(), bing=dict(), bang=dict(), bong=dict(), baz=dict(fallback=(basic.env_fallback, ['BAZ'])), bar1=dict(type='bool'), bar3=dict(type='list', elements='path'), bar_str=dict(type='list', elements=str), zardoz=dict(choices=['one', 'two']), zardoz2=dict(type='list', choices=['one', 'two', 'three']), zardoz3=dict(type='str', aliases=['zodraz'], deprecated_aliases=[dict(name='zodraz', version='9.99')]), ) mut_ex = (('bar', 'bam'), ('bing', 'bang', 'bong')) req_to = (('bam', 'baz'),) kwargs = dict( argument_spec=arg_spec, mutually_exclusive=mut_ex, required_together=req_to, no_log=True, add_file_common_args=True, supports_check_mode=True, ) return kwargs @pytest.fixture def options_argspec_list(): options_spec = dict( foo=dict(required=True, aliases=['dup']), bar=dict(), bar1=dict(type='list', elements='str'), bar2=dict(type='list', elements='int'), bar3=dict(type='list', elements='float'), bar4=dict(type='list', elements='path'), bam=dict(), baz=dict(fallback=(basic.env_fallback, ['BAZ'])), bam1=dict(), bam2=dict(default='test'), bam3=dict(type='bool'), bam4=dict(type='str'), ) arg_spec = dict( foobar=dict( type='list', elements='dict', options=options_spec, mutually_exclusive=[ ['bam', 'bam1'], ], required_if=[ ['foo', 'hello', ['bam']], ['foo', 'bam2', ['bam2']] ], required_one_of=[ ['bar', 'bam'] ], required_together=[ ['bam1', 'baz'] ], required_by={ 'bam4': ('bam1', 'bam3'), }, ) ) kwargs = dict( argument_spec=arg_spec, no_log=True, add_file_common_args=True, supports_check_mode=True ) return kwargs @pytest.fixture def options_argspec_dict(options_argspec_list): # should test ok, for options in dict format. kwargs = options_argspec_list kwargs['argument_spec']['foobar']['type'] = 'dict' kwargs['argument_spec']['foobar']['elements'] = None return kwargs # # Tests for one aspect of arg_spec # @pytest.mark.parametrize('argspec, expected, stdin', [(s[0], s[2], s[1]) for s in VALID_SPECS], indirect=['stdin']) def test_validator_basic_types(argspec, expected, stdin): am = basic.AnsibleModule(argspec) if 'type' in argspec['arg']: if argspec['arg']['type'] == 'int': type_ = int else: type_ = getattr(builtins, argspec['arg']['type']) else: type_ = str assert isinstance(am.params['arg'], type_) assert am.params['arg'] == expected @pytest.mark.parametrize('stdin', [{'arg': 42}, {'arg': 18765432109876543210}], indirect=['stdin']) def test_validator_function(mocker, stdin): # Type is a callable MOCK_VALIDATOR_SUCCESS = mocker.MagicMock(return_value=27) argspec = {'arg': {'type': MOCK_VALIDATOR_SUCCESS}} am = basic.AnsibleModule(argspec) assert isinstance(am.params['arg'], int) assert am.params['arg'] == 27 @pytest.mark.parametrize('stdin', BASIC_AUTH_VALID_ARGS, indirect=['stdin']) def test_validate_basic_auth_arg(mocker, stdin): kwargs = dict( argument_spec=basic_auth_argument_spec() ) am = basic.AnsibleModule(**kwargs) assert isinstance(am.params['api_username'], str) assert isinstance(am.params['api_password'], str) assert isinstance(am.params['api_url'], str) assert isinstance(am.params['validate_certs'], bool) @pytest.mark.parametrize('stdin', RATE_LIMIT_VALID_ARGS, indirect=['stdin']) def test_validate_rate_limit_argument_spec(mocker, stdin): kwargs = dict( argument_spec=rate_limit_argument_spec() ) am = basic.AnsibleModule(**kwargs) assert isinstance(am.params['rate'], int) assert isinstance(am.params['rate_limit'], int) @pytest.mark.parametrize('stdin', RETRY_VALID_ARGS, indirect=['stdin']) def test_validate_retry_argument_spec(mocker, stdin): kwargs = dict( argument_spec=retry_argument_spec() ) am = basic.AnsibleModule(**kwargs) assert isinstance(am.params['retries'], int) assert isinstance(am.params['retry_pause'], float) @pytest.mark.parametrize('stdin', [{'arg': '123'}, {'arg': 123}], indirect=['stdin']) def test_validator_string_type(mocker, stdin): # Custom callable that is 'str' argspec = {'arg': {'type': str}} am = basic.AnsibleModule(argspec) assert isinstance(am.params['arg'], str) assert am.params['arg'] == '123' @pytest.mark.parametrize('argspec, expected, stdin', [(s[0], s[2], s[1]) for s in INVALID_SPECS], indirect=['stdin']) def test_validator_fail(stdin, capfd, argspec, expected): with pytest.raises(SystemExit): basic.AnsibleModule(argument_spec=argspec) out, err = capfd.readouterr() assert not err assert expected in json.loads(out)['msg'] assert json.loads(out)['failed'] class TestComplexArgSpecs: """Test with a more complex arg_spec""" @pytest.mark.parametrize('stdin', [{'foo': 'hello'}, {'dup': 'hello'}], indirect=['stdin']) def test_complex_required(self, stdin, complex_argspec): """Test that the complex argspec works if we give it its required param as either the canonical or aliased name""" am = basic.AnsibleModule(**complex_argspec) assert isinstance(am.params['foo'], str) assert am.params['foo'] == 'hello' @pytest.mark.parametrize('stdin', [{'foo': 'hello1', 'dup': 'hello2'}], indirect=['stdin']) def test_complex_duplicate_warning(self, stdin, complex_argspec): """Test that the complex argspec issues a warning if we specify an option both with its canonical name and its alias""" am = basic.AnsibleModule(**complex_argspec) assert isinstance(am.params['foo'], str) assert 'Both option foo and its alias dup are set.' in get_warning_messages() assert am.params['foo'] == 'hello2' @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'bam': 'test'}], indirect=['stdin']) def test_complex_type_fallback(self, mocker, stdin, complex_argspec): """Test that the complex argspec works if we get a required parameter via fallback""" environ = os.environ.copy() environ['BAZ'] = 'test data' mocker.patch('ansible.module_utils.basic.os.environ', environ) am = basic.AnsibleModule(**complex_argspec) assert isinstance(am.params['baz'], str) assert am.params['baz'] == 'test data' @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'bar': 'bad', 'bam': 'bad2', 'bing': 'a', 'bang': 'b', 'bong': 'c'}], indirect=['stdin']) def test_fail_mutually_exclusive(self, capfd, stdin, complex_argspec): """Fail because of mutually exclusive parameters""" with pytest.raises(SystemExit): am = basic.AnsibleModule(**complex_argspec) out, err = capfd.readouterr() results = json.loads(out) assert results['failed'] assert results['msg'] == "parameters are mutually exclusive: bar|bam, bing|bang|bong" @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'bam': 'bad2'}], indirect=['stdin']) def test_fail_required_together(self, capfd, stdin, complex_argspec): """Fail because only one of a required_together pair of parameters was specified""" with pytest.raises(SystemExit): am = basic.AnsibleModule(**complex_argspec) out, err = capfd.readouterr() results = json.loads(out) assert results['failed'] assert results['msg'] == "parameters are required together: bam, baz" @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'bar': 'hi'}], indirect=['stdin']) def test_fail_required_together_and_default(self, capfd, stdin, complex_argspec): """Fail because one of a required_together pair of parameters has a default and the other was not specified""" complex_argspec['argument_spec']['baz'] = {'default': 42} with pytest.raises(SystemExit): am = basic.AnsibleModule(**complex_argspec) out, err = capfd.readouterr() results = json.loads(out) assert results['failed'] assert results['msg'] == "parameters are required together: bam, baz" @pytest.mark.parametrize('stdin', [{'foo': 'hello'}], indirect=['stdin']) def test_fail_required_together_and_fallback(self, capfd, mocker, stdin, complex_argspec): """Fail because one of a required_together pair of parameters has a fallback and the other was not specified""" environ = os.environ.copy() environ['BAZ'] = 'test data' mocker.patch('ansible.module_utils.basic.os.environ', environ) with pytest.raises(SystemExit): am = basic.AnsibleModule(**complex_argspec) out, err = capfd.readouterr() results = json.loads(out) assert results['failed'] assert results['msg'] == "parameters are required together: bam, baz" @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'zardoz2': ['one', 'four', 'five']}], indirect=['stdin']) def test_fail_list_with_choices(self, capfd, mocker, stdin, complex_argspec): """Fail because one of the items is not in the choice""" with pytest.raises(SystemExit): basic.AnsibleModule(**complex_argspec) out, err = capfd.readouterr() results = json.loads(out) assert results['failed'] assert results['msg'] == "value of zardoz2 must be one or more of: one, two, three. Got no match for: four, five" @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'zardoz2': ['one', 'three']}], indirect=['stdin']) def test_list_with_choices(self, capfd, mocker, stdin, complex_argspec): """Test choices with list""" am = basic.AnsibleModule(**complex_argspec) assert isinstance(am.params['zardoz2'], list) assert am.params['zardoz2'] == ['one', 'three'] @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'bar3': ['~/test', 'test/']}], indirect=['stdin']) def test_list_with_elements_path(self, capfd, mocker, stdin, complex_argspec): """Test choices with list""" am = basic.AnsibleModule(**complex_argspec) assert isinstance(am.params['bar3'], list) assert am.params['bar3'][0].startswith('/') assert am.params['bar3'][1] == 'test/' @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'zodraz': 'one'}], indirect=['stdin']) def test_deprecated_alias(self, capfd, mocker, stdin, complex_argspec, monkeypatch): """Test a deprecated alias""" monkeypatch.setattr(warnings, '_global_deprecations', []) am = basic.AnsibleModule(**complex_argspec) assert "Alias 'zodraz' is deprecated." in get_deprecation_messages()[0]['msg'] assert get_deprecation_messages()[0]['version'] == '9.99' @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'bar_str': [867, '5309']}], indirect=['stdin']) def test_list_with_elements_callable_str(self, capfd, mocker, stdin, complex_argspec): """Test choices with list""" am = basic.AnsibleModule(**complex_argspec) assert isinstance(am.params['bar_str'], list) assert isinstance(am.params['bar_str'][0], str) assert isinstance(am.params['bar_str'][1], str) assert am.params['bar_str'][0] == '867' assert am.params['bar_str'][1] == '5309' class TestComplexOptions: """Test arg spec options""" # (Parameters, expected value of module.params['foobar']) OPTIONS_PARAMS_LIST = ( ({'foobar': [{"foo": "hello", "bam": "good"}, {"foo": "test", "bar": "good"}]}, [{'foo': 'hello', 'bam': 'good', 'bam2': 'test', 'bar': None, 'baz': None, 'bam1': None, 'bam3': None, 'bam4': None, 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}, {'foo': 'test', 'bam': None, 'bam2': 'test', 'bar': 'good', 'baz': None, 'bam1': None, 'bam3': None, 'bam4': None, 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}] ), # Alias for required param ({'foobar': [{"dup": "test", "bar": "good"}]}, [{'foo': 'test', 'dup': 'test', 'bam': None, 'bam2': 'test', 'bar': 'good', 'baz': None, 'bam1': None, 'bam3': None, 'bam4': None, 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}] ), # Required_if utilizing default value of the requirement ({'foobar': [{"foo": "bam2", "bar": "required_one_of"}]}, [{'bam': None, 'bam1': None, 'bam2': 'test', 'bam3': None, 'bam4': None, 'bar': 'required_one_of', 'baz': None, 'foo': 'bam2', 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}] ), # Check that a bool option is converted ({"foobar": [{"foo": "required", "bam": "good", "bam3": "yes"}]}, [{'bam': 'good', 'bam1': None, 'bam2': 'test', 'bam3': True, 'bam4': None, 'bar': None, 'baz': None, 'foo': 'required', 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}] ), # Check required_by options ({"foobar": [{"foo": "required", "bar": "good", "baz": "good", "bam4": "required_by", "bam1": "ok", "bam3": "yes"}]}, [{'bar': 'good', 'baz': 'good', 'bam1': 'ok', 'bam2': 'test', 'bam3': True, 'bam4': 'required_by', 'bam': None, 'foo': 'required', 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}] ), # Check for elements in sub-options ({"foobar": [{"foo": "good", "bam": "required_one_of", "bar1": [1, "good", "yes"], "bar2": ['1', 1], "bar3": ['1.3', 1.3, 1]}]}, [{'foo': 'good', 'bam1': None, 'bam2': 'test', 'bam3': None, 'bam4': None, 'bar': None, 'baz': None, 'bam': 'required_one_of', 'bar1': ["1", "good", "yes"], 'bar2': [1, 1], 'bar3': [1.3, 1.3, 1.0], 'bar4': None}] ), ) # (Parameters, expected value of module.params['foobar']) OPTIONS_PARAMS_DICT = ( ({'foobar': {"foo": "hello", "bam": "good"}}, {'foo': 'hello', 'bam': 'good', 'bam2': 'test', 'bar': None, 'baz': None, 'bam1': None, 'bam3': None, 'bam4': None, 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None} ), # Alias for required param ({'foobar': {"dup": "test", "bar": "good"}}, {'foo': 'test', 'dup': 'test', 'bam': None, 'bam2': 'test', 'bar': 'good', 'baz': None, 'bam1': None, 'bam3': None, 'bam4': None, 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None} ), # Required_if utilizing default value of the requirement ({'foobar': {"foo": "bam2", "bar": "required_one_of"}}, {'bam': None, 'bam1': None, 'bam2': 'test', 'bam3': None, 'bam4': None, 'bar': 'required_one_of', 'baz': None, 'foo': 'bam2', 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None} ), # Check that a bool option is converted ({"foobar": {"foo": "required", "bam": "good", "bam3": "yes"}}, {'bam': 'good', 'bam1': None, 'bam2': 'test', 'bam3': True, 'bam4': None, 'bar': None, 'baz': None, 'foo': 'required', 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None} ), # Check required_by options ({"foobar": {"foo": "required", "bar": "good", "baz": "good", "bam4": "required_by", "bam1": "ok", "bam3": "yes"}}, {'bar': 'good', 'baz': 'good', 'bam1': 'ok', 'bam2': 'test', 'bam3': True, 'bam4': 'required_by', 'bam': None, 'foo': 'required', 'bar1': None, 'bar3': None, 'bar2': None, 'bar4': None} ), # Check for elements in sub-options ({"foobar": {"foo": "good", "bam": "required_one_of", "bar1": [1, "good", "yes"], "bar2": ['1', 1], "bar3": ['1.3', 1.3, 1]}}, {'foo': 'good', 'bam1': None, 'bam2': 'test', 'bam3': None, 'bam4': None, 'bar': None, 'baz': None, 'bam': 'required_one_of', 'bar1': ["1", "good", "yes"], 'bar2': [1, 1], 'bar3': [1.3, 1.3, 1.0], 'bar4': None} ), ) # (Parameters, failure message) FAILING_PARAMS_LIST: tuple[tuple[dict[str, list[dict[str, t.Any]]], str], ...] = ( # Missing required option ({'foobar': [{}]}, 'missing required arguments: foo found in foobar'), # Invalid option ({'foobar': [{"foo": "hello", "bam": "good", "invalid": "bad"}]}, 'module: foobar.invalid. Supported parameters include'), # Mutually exclusive options found ({'foobar': [{"foo": "test", "bam": "bad", "bam1": "bad", "baz": "req_to"}]}, 'parameters are mutually exclusive: bam|bam1 found in foobar'), # required_if fails ({'foobar': [{"foo": "hello", "bar": "bad"}]}, 'foo is hello but all of the following are missing: bam found in foobar'), # Missing required_one_of option ({'foobar': [{"foo": "test"}]}, 'one of the following is required: bar, bam found in foobar'), # Missing required_together option ({'foobar': [{"foo": "test", "bar": "required_one_of", "bam1": "bad"}]}, 'parameters are required together: bam1, baz found in foobar'), # Missing required_by options ({'foobar': [{"foo": "test", "bar": "required_one_of", "bam4": "required_by"}]}, "missing parameter(s) required by 'bam4': bam1, bam3"), ) # (Parameters, failure message) FAILING_PARAMS_DICT: tuple[tuple[dict[str, dict[str, t.Any]], str], ...] = ( # Missing required option ({'foobar': {}}, 'missing required arguments: foo found in foobar'), # Invalid option ({'foobar': {"foo": "hello", "bam": "good", "invalid": "bad"}}, 'module: foobar.invalid. Supported parameters include'), # Mutually exclusive options found ({'foobar': {"foo": "test", "bam": "bad", "bam1": "bad", "baz": "req_to"}}, 'parameters are mutually exclusive: bam|bam1 found in foobar'), # required_if fails ({'foobar': {"foo": "hello", "bar": "bad"}}, 'foo is hello but all of the following are missing: bam found in foobar'), # Missing required_one_of option ({'foobar': {"foo": "test"}}, 'one of the following is required: bar, bam found in foobar'), # Missing required_together option ({'foobar': {"foo": "test", "bar": "required_one_of", "bam1": "bad"}}, 'parameters are required together: bam1, baz found in foobar'), # Missing required_by options ({'foobar': {"foo": "test", "bar": "required_one_of", "bam4": "required_by"}}, "missing parameter(s) required by 'bam4': bam1, bam3"), ) @pytest.mark.parametrize('stdin, expected', OPTIONS_PARAMS_DICT, indirect=['stdin']) def test_options_type_dict(self, stdin, options_argspec_dict, expected): """Test that a basic creation with required and required_if works""" # should test ok, tests basic foo requirement and required_if am = basic.AnsibleModule(**options_argspec_dict) assert isinstance(am.params['foobar'], dict) assert am.params['foobar'] == expected @pytest.mark.parametrize('stdin, expected', OPTIONS_PARAMS_LIST, indirect=['stdin']) def test_options_type_list(self, stdin, options_argspec_list, expected): """Test that a basic creation with required and required_if works""" # should test ok, tests basic foo requirement and required_if am = basic.AnsibleModule(**options_argspec_list) assert isinstance(am.params['foobar'], list) assert am.params['foobar'] == expected @pytest.mark.parametrize('stdin, expected', FAILING_PARAMS_DICT, indirect=['stdin']) def test_fail_validate_options_dict(self, capfd, stdin, options_argspec_dict, expected): """Fail because one of a required_together pair of parameters has a default and the other was not specified""" with pytest.raises(SystemExit): am = basic.AnsibleModule(**options_argspec_dict) out, err = capfd.readouterr() results = json.loads(out) assert results['failed'] assert expected in results['msg'] @pytest.mark.parametrize('stdin, expected', FAILING_PARAMS_LIST, indirect=['stdin']) def test_fail_validate_options_list(self, capfd, stdin, options_argspec_list, expected): """Fail because one of a required_together pair of parameters has a default and the other was not specified""" with pytest.raises(SystemExit): am = basic.AnsibleModule(**options_argspec_list) out, err = capfd.readouterr() results = json.loads(out) assert results['failed'] assert expected in results['msg'] @pytest.mark.parametrize('stdin', [{'foobar': {'foo': 'required', 'bam1': 'test', 'bar': 'case'}}], indirect=['stdin']) def test_fallback_in_option(self, mocker, stdin, options_argspec_dict): """Test that the complex argspec works if we get a required parameter via fallback""" environ = os.environ.copy() environ['BAZ'] = 'test data' mocker.patch('ansible.module_utils.basic.os.environ', environ) am = basic.AnsibleModule(**options_argspec_dict) assert isinstance(am.params['foobar']['baz'], str) assert am.params['foobar']['baz'] == 'test data' @pytest.mark.parametrize('stdin', [{'foobar': {'foo': 'required', 'bam1': 'test', 'baz': 'data', 'bar': 'case', 'bar4': '~/test'}}], indirect=['stdin']) def test_elements_path_in_option(self, mocker, stdin, options_argspec_dict): """Test that the complex argspec works with elements path type""" am = basic.AnsibleModule(**options_argspec_dict) assert isinstance(am.params['foobar']['bar4'][0], str) assert am.params['foobar']['bar4'][0].startswith('/') @pytest.mark.parametrize('stdin,spec,expected', [ ({}, {'one': {'type': 'dict', 'apply_defaults': True, 'options': {'two': {'default': True, 'type': 'bool'}}}}, {'two': True}), ({}, {'one': {'type': 'dict', 'options': {'two': {'default': True, 'type': 'bool'}}}}, None), ], indirect=['stdin']) def test_subspec_not_required_defaults(self, stdin, spec, expected): # Check that top level not required, processed subspec defaults am = basic.AnsibleModule(spec) assert am.params['one'] == expected class TestLoadFileCommonArguments: @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_smoketest_load_file_common_args(self, am): """With no file arguments, an empty dict is returned""" am.selinux_mls_enabled = MagicMock() am.selinux_mls_enabled.return_value = True am.selinux_default_context = MagicMock() am.selinux_default_context.return_value = 'unconfined_u:object_r:default_t:s0'.split(':', 3) assert am.load_file_common_arguments(params={}) == {} @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_load_file_common_args(self, am, mocker): am.selinux_mls_enabled = MagicMock() am.selinux_mls_enabled.return_value = True am.selinux_default_context = MagicMock() am.selinux_default_context.return_value = 'unconfined_u:object_r:default_t:s0'.split(':', 3) base_params = dict( path='/path/to/file', mode=0o600, owner='root', group='root', seuser='_default', serole='_default', setype='_default', selevel='_default', ) extended_params = base_params.copy() extended_params.update(dict( follow=True, foo='bar', )) final_params = base_params.copy() final_params.update(dict( path='/path/to/real_file', secontext=['unconfined_u', 'object_r', 'default_t', 's0'], attributes=None, )) # with the proper params specified, the returned dictionary should represent # only those params which have something to do with the file arguments, excluding # other params and updated as required with proper values which may have been # massaged by the method mocker.patch('os.path.islink', return_value=True) mocker.patch('os.path.realpath', return_value='/path/to/real_file') res = am.load_file_common_arguments(params=extended_params) assert res == final_params @pytest.mark.parametrize("stdin", [{"arg_pass": "testing"}], indirect=["stdin"]) def test_no_log_true(stdin, capfd): """Explicitly mask an argument (no_log=True).""" arg_spec = { "arg_pass": {"no_log": True} } am = basic.AnsibleModule(arg_spec) # no_log=True is picked up by both am._log_invocation and list_no_log_values # (called by am._handle_no_log_values). As a result, we can check for the # value in am.no_log_values. assert "testing" in am.no_log_values @pytest.mark.parametrize("stdin", [{"arg_pass": "testing"}], indirect=["stdin"]) def test_no_log_false(stdin, capfd): """Explicitly log and display an argument (no_log=False).""" arg_spec = { "arg_pass": {"no_log": False} } am = basic.AnsibleModule(arg_spec) assert "testing" not in am.no_log_values and not get_warning_messages() @pytest.mark.parametrize("stdin", [{"arg_pass": "testing"}], indirect=["stdin"]) def test_no_log_none(stdin, capfd): """Allow Ansible to make the decision by matching the argument name against PASSWORD_MATCH.""" arg_spec = { "arg_pass": {} } am = basic.AnsibleModule(arg_spec) # Omitting no_log is only picked up by _log_invocation, so the value never # makes it into am.no_log_values. Instead we can check for the warning # emitted by am._log_invocation. assert len(get_warning_messages()) > 0 @pytest.mark.parametrize("stdin", [{"pass": "testing"}], indirect=["stdin"]) def test_no_log_alias(stdin, capfd): """Given module parameters that use an alias for a parameter that matches PASSWORD_MATCH and has no_log=True set, a warning should not be issued. """ arg_spec = { "other_pass": {"no_log": True, "aliases": ["pass"]}, } am = basic.AnsibleModule(arg_spec) assert len(get_warning_messages()) == 0
32,580
Python
.py
613
45.615008
145
0.599529
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,890
test_tmpdir.py
ansible_ansible/test/units/module_utils/basic/test_tmpdir.py
# -*- coding: utf-8 -*- # Copyright (c) 2018 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import json import os import tempfile import pytest from unittest.mock import patch, MagicMock from ansible.module_utils.common.text.converters import to_bytes from ansible.module_utils import basic class TestAnsibleModuleTmpDir: DATA = ( ( { "_ansible_tmpdir": "/path/to/dir", "_ansible_remote_tmp": "/path/tmpdir", "_ansible_keep_remote_files": False, }, True, "/path/to/dir" ), ( { "_ansible_tmpdir": None, "_ansible_remote_tmp": "/path/tmpdir", "_ansible_keep_remote_files": False }, False, "/path/tmpdir/ansible-moduletmp-42-" ), ( { "_ansible_tmpdir": None, "_ansible_remote_tmp": "/path/tmpdir", "_ansible_keep_remote_files": False }, True, "/path/tmpdir/ansible-moduletmp-42-" ), ( { "_ansible_tmpdir": None, "_ansible_remote_tmp": "$HOME/.test", "_ansible_keep_remote_files": False }, False, os.path.join(os.environ['HOME'], ".test/ansible-moduletmp-42-") ), ) @pytest.mark.parametrize('args, expected, stat_exists', ((s, e, t) for s, t, e in DATA)) def test_tmpdir_property(self, monkeypatch, args, expected, stat_exists): makedirs = {'called': False} def mock_mkdtemp(prefix, dir): return os.path.join(dir, prefix) def mock_makedirs(path, mode): makedirs['called'] = True makedirs['path'] = path makedirs['mode'] = mode return monkeypatch.setattr(tempfile, 'mkdtemp', mock_mkdtemp) monkeypatch.setattr(os.path, 'exists', lambda x: stat_exists) monkeypatch.setattr(os, 'makedirs', mock_makedirs) monkeypatch.setattr(basic, '_ANSIBLE_ARGS', to_bytes(json.dumps({'ANSIBLE_MODULE_ARGS': args}))) with patch('time.time', return_value=42): am = basic.AnsibleModule(argument_spec={}) actual_tmpdir = am.tmpdir assert actual_tmpdir == expected # verify subsequent calls always produces the same tmpdir assert am.tmpdir == actual_tmpdir if not stat_exists: assert makedirs['called'] expected = os.path.expanduser(os.path.expandvars(am._remote_tmp)) assert makedirs['path'] == expected assert makedirs['mode'] == 0o700 @pytest.mark.parametrize('stdin', ({"_ansible_tmpdir": None, "_ansible_remote_tmp": "$HOME/.test", "_ansible_keep_remote_files": True},), indirect=['stdin']) def test_tmpdir_makedirs_failure(self, am, monkeypatch): mock_mkdtemp = MagicMock(return_value="/tmp/path") mock_makedirs = MagicMock(side_effect=OSError("Some OS Error here")) monkeypatch.setattr(tempfile, 'mkdtemp', mock_mkdtemp) monkeypatch.setattr(os.path, 'exists', lambda x: False) monkeypatch.setattr(os, 'makedirs', mock_makedirs) actual = am.tmpdir assert actual == "/tmp/path" assert mock_makedirs.call_args[0] == (os.path.expanduser(os.path.expandvars("$HOME/.test")),) assert mock_makedirs.call_args[1] == {"mode": 0o700} # because makedirs failed the dir should be None so it uses the System tmp assert mock_mkdtemp.call_args[1]['dir'] is None assert mock_mkdtemp.call_args[1]['prefix'].startswith("ansible-moduletmp-")
3,926
Python
.py
92
31.608696
104
0.571991
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,891
test_get_available_hash_algorithms.py
ansible_ansible/test/units/module_utils/basic/test_get_available_hash_algorithms.py
"""Unit tests to provide coverage not easily obtained from integration tests.""" from __future__ import annotations from ansible.module_utils.basic import _get_available_hash_algorithms def test_unavailable_algorithm(mocker): """Simulate an available algorithm that isn't.""" expected_algorithms = {'sha256', 'sha512'} # guaranteed to be available mocker.patch('hashlib.algorithms_available', expected_algorithms | {'not_actually_available'}) available_algorithms = _get_available_hash_algorithms() assert sorted(expected_algorithms) == sorted(available_algorithms) def test_fips_mode(mocker): """Simulate running in FIPS mode on Python 2.7.9 or later.""" expected_algorithms = {'sha256', 'sha512'} # guaranteed to be available mocker.patch('hashlib.algorithms_available', expected_algorithms | {'md5'}) mocker.patch('hashlib.md5').side_effect = ValueError() # using md5 in FIPS mode raises a ValueError available_algorithms = _get_available_hash_algorithms() assert sorted(expected_algorithms) == sorted(available_algorithms)
1,086
Python
.py
16
63.375
104
0.753308
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,892
test_set_mode_if_different.py
ansible_ansible/test/units/module_utils/basic/test_set_mode_if_different.py
# -*- coding: utf-8 -*- # (c) 2016, Toshio Kuratomi <tkuratomi@ansible.com> # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import builtins import errno import os from itertools import product import pytest SYNONYMS_0660 = ( 0o660, '0o660', '660', 'u+rw-x,g+rw-x,o-rwx', 'u=rw,g=rw,o-rwx', ) @pytest.fixture def mock_stats(mocker): mock_stat1 = mocker.MagicMock() mock_stat1.st_mode = 0o444 mock_stat2 = mocker.MagicMock() mock_stat2.st_mode = 0o660 yield {"before": mock_stat1, "after": mock_stat2} @pytest.fixture def am_check_mode(am): am.check_mode = True yield am am.check_mode = False @pytest.fixture def mock_lchmod(mocker): m_lchmod = mocker.patch('ansible.module_utils.basic.os.lchmod', return_value=None, create=True) yield m_lchmod @pytest.mark.parametrize('previous_changes, check_mode, exists, stdin', product((True, False), (True, False), (True, False), ({},)), indirect=['stdin']) def test_no_mode_given_returns_previous_changes(am, mock_stats, mock_lchmod, mocker, previous_changes, check_mode, exists): am.check_mode = check_mode mocker.patch('os.lstat', side_effect=[mock_stats['before']]) m_lchmod = mocker.patch('os.lchmod', return_value=None, create=True) m_path_exists = mocker.patch('os.path.exists', return_value=exists) assert am.set_mode_if_different('/path/to/file', None, previous_changes) == previous_changes assert not m_lchmod.called assert not m_path_exists.called @pytest.mark.parametrize('mode, check_mode, stdin', product(SYNONYMS_0660, (True, False), ({},)), indirect=['stdin']) def test_mode_changed_to_0660(am, mock_stats, mocker, mode, check_mode): # Note: This is for checking that all the different ways of specifying # 0660 mode work. It cannot be used to check that setting a mode that is # not equivalent to 0660 works. am.check_mode = check_mode mocker.patch('os.lstat', side_effect=[mock_stats['before'], mock_stats['after'], mock_stats['after']]) m_lchmod = mocker.patch('os.lchmod', return_value=None, create=True) mocker.patch('os.path.exists', return_value=True) assert am.set_mode_if_different('/path/to/file', mode, False) if check_mode: assert not m_lchmod.called else: m_lchmod.assert_called_with(b'/path/to/file', 0o660) @pytest.mark.parametrize('mode, check_mode, stdin', product(SYNONYMS_0660, (True, False), ({},)), indirect=['stdin']) def test_mode_unchanged_when_already_0660(am, mock_stats, mocker, mode, check_mode): # Note: This is for checking that all the different ways of specifying # 0660 mode work. It cannot be used to check that setting a mode that is # not equivalent to 0660 works. am.check_mode = check_mode mocker.patch('os.lstat', side_effect=[mock_stats['after'], mock_stats['after'], mock_stats['after']]) m_lchmod = mocker.patch('os.lchmod', return_value=None, create=True) mocker.patch('os.path.exists', return_value=True) assert not am.set_mode_if_different('/path/to/file', mode, False) assert not m_lchmod.called @pytest.mark.parametrize('mode, stdin', product(SYNONYMS_0660, ({},)), indirect=['stdin']) def test_mode_changed_to_0660_check_mode_no_file(am, mocker, mode): am.check_mode = True mocker.patch('os.path.exists', return_value=False) assert am.set_mode_if_different('/path/to/file', mode, False) @pytest.mark.parametrize('check_mode, stdin', product((True, False), ({},)), indirect=['stdin']) def test_missing_lchmod_is_not_link(am, mock_stats, mocker, monkeypatch, check_mode): """Some platforms have lchmod (*BSD) others do not (Linux)""" am.check_mode = check_mode original_hasattr = hasattr monkeypatch.delattr(os, 'lchmod', raising=False) mocker.patch('os.lstat', side_effect=[mock_stats['before'], mock_stats['after']]) mocker.patch('os.path.islink', return_value=False) mocker.patch('os.path.exists', return_value=True) m_chmod = mocker.patch('os.chmod', return_value=None) assert am.set_mode_if_different('/path/to/file/no_lchmod', 0o660, False) if check_mode: assert not m_chmod.called else: m_chmod.assert_called_with(b'/path/to/file/no_lchmod', 0o660) @pytest.mark.parametrize('check_mode, stdin', product((True, False), ({},)), indirect=['stdin']) def test_missing_lchmod_is_link(am, mock_stats, mocker, monkeypatch, check_mode): """Some platforms have lchmod (*BSD) others do not (Linux)""" am.check_mode = check_mode original_hasattr = hasattr monkeypatch.delattr(os, 'lchmod', raising=False) mocker.patch('os.lstat', side_effect=[mock_stats['before'], mock_stats['after']]) mocker.patch('os.path.islink', return_value=True) mocker.patch('os.path.exists', return_value=True) m_chmod = mocker.patch('os.chmod', return_value=None) mocker.patch('os.stat', return_value=mock_stats['after']) assert am.set_mode_if_different('/path/to/file/no_lchmod', 0o660, False) if check_mode: assert not m_chmod.called else: m_chmod.assert_called_with(b'/path/to/file/no_lchmod', 0o660) mocker.resetall() mocker.stopall() @pytest.mark.parametrize('stdin,', ({},), indirect=['stdin']) def test_missing_lchmod_is_link_in_sticky_dir(am, mock_stats, mocker): """Some platforms have lchmod (*BSD) others do not (Linux)""" am.check_mode = False original_hasattr = hasattr def _hasattr(obj, name): if obj == os and name == 'lchmod': return False return original_hasattr(obj, name) mock_lstat = mocker.MagicMock() mock_lstat.st_mode = 0o777 mocker.patch('os.lstat', side_effect=[mock_lstat, mock_lstat]) mocker.patch.object(builtins, 'hasattr', side_effect=_hasattr) mocker.patch('os.path.islink', return_value=True) mocker.patch('os.path.exists', return_value=True) m_stat = mocker.patch('os.stat', side_effect=OSError(errno.EACCES, 'Permission denied')) m_chmod = mocker.patch('os.chmod', return_value=None) # not changed: can't set mode on symbolic links assert not am.set_mode_if_different('/path/to/file/no_lchmod', 0o660, False) m_stat.assert_called_with(b'/path/to/file/no_lchmod') m_chmod.assert_not_called() mocker.resetall() mocker.stopall()
6,720
Python
.py
140
41.514286
123
0.666769
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,893
test_platform_distribution.py
ansible_ansible/test/units/module_utils/basic/test_platform_distribution.py
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016 Toshio Kuratomi <tkuratomi@ansible.com> # (c) 2017-2018 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest from unittest.mock import patch import builtins # Functions being tested from ansible.module_utils.basic import get_platform from ansible.module_utils.basic import get_all_subclasses from ansible.module_utils.basic import get_distribution from ansible.module_utils.basic import get_distribution_version from ansible.module_utils.basic import load_platform_subclass realimport = builtins.__import__ @pytest.fixture def platform_linux(mocker): mocker.patch('platform.system', return_value='Linux') # # get_platform tests # def test_get_platform(): with patch('platform.system', return_value='foo'): assert get_platform() == 'foo' # # get_distribution tests # @pytest.mark.usefixtures("platform_linux") class TestGetDistribution: """Tests for get_distribution that have to find something""" def test_distro_known(self): with patch('ansible.module_utils.distro.id', return_value="alpine"): assert get_distribution() == "Alpine" with patch('ansible.module_utils.distro.id', return_value="arch"): assert get_distribution() == "Arch" with patch('ansible.module_utils.distro.id', return_value="centos"): assert get_distribution() == "Centos" with patch('ansible.module_utils.distro.id', return_value="clear-linux-os"): assert get_distribution() == "Clear-linux-os" with patch('ansible.module_utils.distro.id', return_value="coreos"): assert get_distribution() == "Coreos" with patch('ansible.module_utils.distro.id', return_value="debian"): assert get_distribution() == "Debian" with patch('ansible.module_utils.distro.id', return_value="flatcar"): assert get_distribution() == "Flatcar" with patch('ansible.module_utils.distro.id', return_value="linuxmint"): assert get_distribution() == "Linuxmint" with patch('ansible.module_utils.distro.id', return_value="opensuse"): assert get_distribution() == "Opensuse" with patch('ansible.module_utils.distro.id', return_value="oracle"): assert get_distribution() == "Oracle" with patch('ansible.module_utils.distro.id', return_value="raspian"): assert get_distribution() == "Raspian" with patch('ansible.module_utils.distro.id', return_value="rhel"): assert get_distribution() == "Redhat" with patch('ansible.module_utils.distro.id', return_value="ubuntu"): assert get_distribution() == "Ubuntu" with patch('ansible.module_utils.distro.id', return_value="virtuozzo"): assert get_distribution() == "Virtuozzo" with patch('ansible.module_utils.distro.id', return_value="foo"): assert get_distribution() == "Foo" def test_distro_unknown(self): with patch('ansible.module_utils.distro.id', return_value=""): assert get_distribution() == "OtherLinux" def test_distro_amazon_linux_short(self): with patch('ansible.module_utils.distro.id', return_value="amzn"): assert get_distribution() == "Amazon" def test_distro_amazon_linux_long(self): with patch('ansible.module_utils.distro.id', return_value="amazon"): assert get_distribution() == "Amazon" # # get_distribution_version tests # @pytest.mark.usefixtures("platform_linux") def test_distro_found(): with patch('ansible.module_utils.distro.version', return_value="1"): assert get_distribution_version() == "1" # # Tests for LoadPlatformSubclass # class TestLoadPlatformSubclass: class LinuxTest: pass class Foo(LinuxTest): platform = "Linux" distribution = None class Bar(LinuxTest): platform = "Linux" distribution = "Bar" def test_not_linux(self): # if neither match, the fallback should be the top-level class with patch('platform.system', return_value="Foo"): with patch('ansible.module_utils.common.sys_info.get_distribution', return_value=None): assert isinstance(load_platform_subclass(self.LinuxTest), self.LinuxTest) @pytest.mark.usefixtures("platform_linux") def test_get_distribution_none(self): # match just the platform class, not a specific distribution with patch('ansible.module_utils.common.sys_info.get_distribution', return_value=None): assert isinstance(load_platform_subclass(self.LinuxTest), self.Foo) @pytest.mark.usefixtures("platform_linux") def test_get_distribution_found(self): # match both the distribution and platform class with patch('ansible.module_utils.common.sys_info.get_distribution', return_value="Bar"): assert isinstance(load_platform_subclass(self.LinuxTest), self.Bar) # # Tests for get_all_subclasses # class TestGetAllSubclasses: class Base: pass class BranchI(Base): pass class BranchII(Base): pass class BranchIA(BranchI): pass class BranchIB(BranchI): pass class BranchIIA(BranchII): pass class BranchIIB(BranchII): pass def test_bottom_level(self): assert get_all_subclasses(self.BranchIIB) == [] def test_one_inheritance(self): assert set(get_all_subclasses(self.BranchII)) == set([self.BranchIIA, self.BranchIIB]) def test_toplevel(self): assert set(get_all_subclasses(self.Base)) == set([self.BranchI, self.BranchII, self.BranchIA, self.BranchIB, self.BranchIIA, self.BranchIIB])
5,994
Python
.py
131
38.099237
99
0.672636
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,894
test_run_command.py
ansible_ansible/test/units/module_utils/basic/test_run_command.py
# -*- coding: utf-8 -*- # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import selectors from itertools import product from io import BytesIO import pytest from ansible.module_utils.common.text.converters import to_native class OpenBytesIO(BytesIO): """BytesIO with dummy close() method So that you can inspect the content after close() was called. """ def close(self): pass @pytest.fixture def mock_os(mocker): def mock_os_abspath(path): if path.startswith('/'): return path else: return os.getcwd.return_value + '/' + path os = mocker.patch('ansible.module_utils.basic.os') os.path.expandvars.side_effect = lambda x: x os.path.expanduser.side_effect = lambda x: x os.environ = {'PATH': '/bin'} os.getcwd.return_value = '/home/foo' os.path.isdir.return_value = True os.path.abspath.side_effect = mock_os_abspath yield os class SpecialBytesIO(BytesIO): def __init__(self, *args, **kwargs): fh = kwargs.pop('fh', None) super(SpecialBytesIO, self).__init__(*args, **kwargs) self.fh = fh def fileno(self): return self.fh # We need to do this because some of our tests create a new value for stdout and stderr # The new value is able to affect the string that is returned by the subprocess stdout and # stderr but by the time the test gets it, it is too late to change the SpecialBytesIO that # subprocess.Popen returns for stdout and stderr. If we could figure out how to change those as # well, then we wouldn't need this. def __eq__(self, other): if id(self) == id(other) or self.fh == other.fileno(): return True return False class DummyKey: def __init__(self, fileobj): self.fileobj = fileobj @pytest.fixture def mock_subprocess(mocker): class MockSelector(selectors.BaseSelector): def __init__(self): super(MockSelector, self).__init__() self._file_objs = [] def register(self, fileobj, events, data=None): self._file_objs.append(fileobj) def unregister(self, fileobj): self._file_objs.remove(fileobj) def select(self, timeout=None): ready = [] for file_obj in self._file_objs: ready.append((DummyKey(subprocess._output[file_obj.fileno()]), selectors.EVENT_READ)) return ready def get_map(self): return self._file_objs def close(self): super(MockSelector, self).close() self._file_objs = [] selectors.PollSelector = MockSelector subprocess = mocker.patch('ansible.module_utils.basic.subprocess') subprocess._output = {mocker.sentinel.stdout: SpecialBytesIO(b'', fh=mocker.sentinel.stdout), mocker.sentinel.stderr: SpecialBytesIO(b'', fh=mocker.sentinel.stderr)} cmd = mocker.MagicMock() cmd.returncode = 0 cmd.stdin = OpenBytesIO() cmd.stdout = subprocess._output[mocker.sentinel.stdout] cmd.stderr = subprocess._output[mocker.sentinel.stderr] subprocess.Popen.return_value = cmd yield subprocess @pytest.fixture() def rc_am(mocker, am, mock_os, mock_subprocess): am.fail_json = mocker.MagicMock(side_effect=SystemExit) am._os = mock_os am._subprocess = mock_subprocess yield am class TestRunCommandArgs: # Format is command as passed to run_command, command to Popen as list, command to Popen as string ARGS_DATA = ( (['/bin/ls', 'a', 'b', 'c'], [b'/bin/ls', b'a', b'b', b'c'], b'/bin/ls a b c'), ('/bin/ls a " b" "c "', [b'/bin/ls', b'a', b' b', b'c '], b'/bin/ls a " b" "c "'), ) @pytest.mark.parametrize('cmd, expected, shell, stdin', ((arg, cmd_str if sh else cmd_lst, sh, {}) for (arg, cmd_lst, cmd_str), sh in product(ARGS_DATA, (True, False))), indirect=['stdin']) def test_args(self, cmd, expected, shell, rc_am): rc_am.run_command(cmd, use_unsafe_shell=shell) assert rc_am._subprocess.Popen.called args, kwargs = rc_am._subprocess.Popen.call_args assert args == (expected, ) assert kwargs['shell'] == shell @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_tuple_as_args(self, rc_am): with pytest.raises(SystemExit): rc_am.run_command(('ls', '/')) assert rc_am.fail_json.called class TestRunCommandCwd: @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_cwd(self, mocker, rc_am): rc_am.run_command('/bin/ls', cwd='/new') assert rc_am._subprocess.Popen.mock_calls[0][2]['cwd'] == b'/new' @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_cwd_relative_path(self, mocker, rc_am): rc_am.run_command('/bin/ls', cwd='sub-dir') assert rc_am._subprocess.Popen.mock_calls[0][2]['cwd'] == b'/home/foo/sub-dir' @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_cwd_not_a_dir(self, mocker, rc_am): rc_am.run_command('/bin/ls', cwd='/not-a-dir') assert rc_am._subprocess.Popen.mock_calls[0][2]['cwd'] == b'/not-a-dir' @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_cwd_not_a_dir_noignore(self, rc_am): rc_am._os.path.isdir.side_effect = lambda d: d != b'/not-a-dir' with pytest.raises(SystemExit): rc_am.run_command('/bin/ls', cwd='/not-a-dir', ignore_invalid_cwd=False) assert rc_am.fail_json.called class TestRunCommandPrompt: @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_prompt_bad_regex(self, rc_am): with pytest.raises(SystemExit): rc_am.run_command('foo', prompt_regex='[pP)assword:') assert rc_am.fail_json.called @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_prompt_no_match(self, mocker, rc_am): rc_am._os._cmd_out[mocker.sentinel.stdout] = BytesIO(b'hello') (rc, stdout, stderr) = rc_am.run_command('foo', prompt_regex='[pP]assword:') assert rc == 0 @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_prompt_match_wo_data(self, mocker, rc_am): rc_am._subprocess._output = {mocker.sentinel.stdout: SpecialBytesIO(b'Authentication required!\nEnter password: ', fh=mocker.sentinel.stdout), mocker.sentinel.stderr: SpecialBytesIO(b'', fh=mocker.sentinel.stderr)} (rc, stdout, stderr) = rc_am.run_command('foo', prompt_regex=r'[pP]assword:', data=None) assert rc == 257 class TestRunCommandRc: @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_check_rc_false(self, rc_am): rc_am._subprocess.Popen.return_value.returncode = 1 (rc, stdout, stderr) = rc_am.run_command('/bin/false', check_rc=False) assert rc == 1 @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_check_rc_true(self, rc_am): rc_am._subprocess.Popen.return_value.returncode = 1 with pytest.raises(SystemExit): rc_am.run_command('/bin/false', check_rc=True) assert rc_am.fail_json.called args, kwargs = rc_am.fail_json.call_args assert kwargs['rc'] == 1 class TestRunCommandOutput: @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_text_stdin(self, rc_am): (rc, stdout, stderr) = rc_am.run_command('/bin/foo', data='hello world') assert rc_am._subprocess.Popen.return_value.stdin.getvalue() == b'hello world\n' @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_ascii_stdout(self, mocker, rc_am): rc_am._subprocess._output = {mocker.sentinel.stdout: SpecialBytesIO(b'hello', fh=mocker.sentinel.stdout), mocker.sentinel.stderr: SpecialBytesIO(b'', fh=mocker.sentinel.stderr)} (rc, stdout, stderr) = rc_am.run_command('/bin/cat hello.txt') assert rc == 0 # module_utils function. On py3 it returns text and py2 it returns # bytes because it's returning native strings assert stdout == 'hello' @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_utf8_output(self, mocker, rc_am): rc_am._subprocess._output = {mocker.sentinel.stdout: SpecialBytesIO(u'Žarn§'.encode('utf-8'), fh=mocker.sentinel.stdout), mocker.sentinel.stderr: SpecialBytesIO(u'لرئيسية'.encode('utf-8'), fh=mocker.sentinel.stderr)} (rc, stdout, stderr) = rc_am.run_command('/bin/something_ugly') assert rc == 0 # module_utils function. On py3 it returns text and py2 it returns # bytes because it's returning native strings assert stdout == to_native(u'Žarn§') assert stderr == to_native(u'لرئيسية') @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_run_command_fds(mocker, rc_am): subprocess_mock = mocker.patch('ansible.module_utils.basic.subprocess') subprocess_mock.Popen.side_effect = AssertionError try: rc_am.run_command('synchronize', pass_fds=(101, 42)) except SystemExit: pass assert subprocess_mock.Popen.call_args[1]['pass_fds'] == (101, 42) assert subprocess_mock.Popen.call_args[1]['close_fds'] is True
9,984
Python
.py
200
40.19
102
0.610465
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,895
test_no_log.py
ansible_ansible/test/units/module_utils/basic/test_no_log.py
# -*- coding: utf-8 -*- # (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com> # (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import typing as t import unittest from ansible.module_utils.basic import remove_values from ansible.module_utils.common.parameters import _return_datastructure_name class TestReturnValues(unittest.TestCase): dataset: tuple[tuple[t.Any, frozenset[str]], ...] = ( ('string', frozenset(['string'])), ('', frozenset()), (1, frozenset(['1'])), (1.0, frozenset(['1.0'])), (False, frozenset()), (['1', '2', '3'], frozenset(['1', '2', '3'])), (('1', '2', '3'), frozenset(['1', '2', '3'])), ({'one': 1, 'two': 'dos'}, frozenset(['1', 'dos'])), ( { 'one': 1, 'two': 'dos', 'three': [ 'amigos', 'musketeers', None, { 'ping': 'pong', 'base': ( 'balls', 'raquets' ) } ] }, frozenset(['1', 'dos', 'amigos', 'musketeers', 'pong', 'balls', 'raquets']) ), (u'Toshio くらとみ', frozenset(['Toshio くらとみ'])), ('Toshio くらとみ', frozenset(['Toshio くらとみ'])), ) def test_return_datastructure_name(self): for data, expected in self.dataset: self.assertEqual(frozenset(_return_datastructure_name(data)), expected) def test_unknown_type(self): self.assertRaises(TypeError, frozenset, _return_datastructure_name(object())) class TestRemoveValues(unittest.TestCase): OMIT = 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER' dataset_no_remove = ( ('string', frozenset(['nope'])), (1234, frozenset(['4321'])), (False, frozenset(['4321'])), (1.0, frozenset(['4321'])), (['string', 'strang', 'strung'], frozenset(['nope'])), ({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['nope'])), ( { 'one': 1, 'two': 'dos', 'three': [ 'amigos', 'musketeers', None, { 'ping': 'pong', 'base': ['balls', 'raquets'] } ] }, frozenset(['nope']) ), (u'Toshio くら'.encode('utf-8'), frozenset([u'とみ'.encode('utf-8')])), (u'Toshio くら', frozenset([u'とみ'])), ) dataset_remove = ( ('string', frozenset(['string']), OMIT), (1234, frozenset(['1234']), OMIT), (1234, frozenset(['23']), OMIT), (1.0, frozenset(['1.0']), OMIT), (['string', 'strang', 'strung'], frozenset(['strang']), ['string', OMIT, 'strung']), (['string', 'strang', 'strung'], frozenset(['strang', 'string', 'strung']), [OMIT, OMIT, OMIT]), (('string', 'strang', 'strung'), frozenset(['string', 'strung']), [OMIT, 'strang', OMIT]), ((1234567890, 345678, 987654321), frozenset(['1234567890']), [OMIT, 345678, 987654321]), ((1234567890, 345678, 987654321), frozenset(['345678']), [OMIT, OMIT, 987654321]), ({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key']), {'one': 1, 'two': 'dos', 'secret': OMIT}), ({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key', 'dos', '1']), {'one': OMIT, 'two': OMIT, 'secret': OMIT}), ({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key', 'dos', '1']), {'one': OMIT, 'two': OMIT, 'secret': OMIT}), ( { 'one': 1, 'two': 'dos', 'three': [ 'amigos', 'musketeers', None, { 'ping': 'pong', 'base': [ 'balls', 'raquets' ] } ] }, frozenset(['balls', 'base', 'pong', 'amigos']), { 'one': 1, 'two': 'dos', 'three': [ OMIT, 'musketeers', None, { 'ping': OMIT, 'base': [ OMIT, 'raquets' ] } ] } ), ( 'This sentence has an enigma wrapped in a mystery inside of a secret. - mr mystery', frozenset(['enigma', 'mystery', 'secret']), 'This sentence has an ******** wrapped in a ******** inside of a ********. - mr ********' ), (u'Toshio くらとみ'.encode('utf-8'), frozenset([u'くらとみ'.encode('utf-8')]), u'Toshio ********'.encode('utf-8')), (u'Toshio くらとみ', frozenset([u'くらとみ']), u'Toshio ********'), ) def test_no_removal(self): for value, no_log_strings in self.dataset_no_remove: self.assertEqual(remove_values(value, no_log_strings), value) def test_strings_to_remove(self): for value, no_log_strings, expected in self.dataset_remove: self.assertEqual(remove_values(value, no_log_strings), expected) def test_unknown_type(self): self.assertRaises(TypeError, remove_values, object(), frozenset()) def test_hit_recursion_limit(self): """ Check that we do not hit a recursion limit""" data_list = [] inner_list = data_list for i in range(0, 10000): new_list = [] inner_list.append(new_list) inner_list = new_list inner_list.append('secret') # Check that this does not hit a recursion limit actual_data_list = remove_values(data_list, frozenset(('secret',))) levels = 0 inner_list = actual_data_list while True: if isinstance(inner_list, list): self.assertEqual(len(inner_list), 1) else: levels -= 1 break inner_list = inner_list[0] levels += 1 self.assertEqual(inner_list, self.OMIT) self.assertEqual(levels, 10000)
6,233
Python
.py
144
30.784722
128
0.481061
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,896
test_heuristic_log_sanitize.py
ansible_ansible/test/units/module_utils/basic/test_heuristic_log_sanitize.py
# -*- coding: utf-8 -*- # (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from __future__ import annotations import unittest from ansible.module_utils.basic import heuristic_log_sanitize class TestHeuristicLogSanitize(unittest.TestCase): def setUp(self): self.URL_SECRET = 'http://username:pas:word@foo.com/data' self.SSH_SECRET = 'username:pas:word@foo.com/data' self.clean_data = repr(self._gen_data(3, True, True, 'no_secret_here')) self.url_data = repr(self._gen_data(3, True, True, self.URL_SECRET)) self.ssh_data = repr(self._gen_data(3, True, True, self.SSH_SECRET)) def _gen_data(self, records, per_rec, top_level, secret_text): hostvars = {'hostvars': {}} for i in range(1, records, 1): host_facts = { 'host%s' % i: { 'pstack': { 'running': '875.1', 'symlinked': '880.0', 'tars': [], 'versions': ['885.0'] }, } } if per_rec: host_facts['host%s' % i]['secret'] = secret_text hostvars['hostvars'].update(host_facts) if top_level: hostvars['secret'] = secret_text return hostvars def test_did_not_hide_too_much(self): self.assertEqual(heuristic_log_sanitize(self.clean_data), self.clean_data) def test_hides_url_secrets(self): url_output = heuristic_log_sanitize(self.url_data) # Basic functionality: Successfully hid the password self.assertNotIn('pas:word', url_output) # Slightly more advanced, we hid all of the password despite the ":" self.assertNotIn('pas', url_output) # In this implementation we replace the password with 8 "*" which is # also the length of our password. The url fields should be able to # accurately detect where the password ends so the length should be # the same: self.assertEqual(len(url_output), len(self.url_data)) def test_hides_ssh_secrets(self): ssh_output = heuristic_log_sanitize(self.ssh_data) self.assertNotIn('pas:word', ssh_output) # Slightly more advanced, we hid all of the password despite the ":" self.assertNotIn('pas', ssh_output) # ssh checking is harder as the heuristic is overzealous in many # cases. Since the input will have at least one ":" present before # the password we can tell some things about the beginning and end of # the data, though: self.assertTrue(ssh_output.startswith("{'")) self.assertTrue(ssh_output.endswith("}")) self.assertIn(":********@foo.com/data'", ssh_output) def test_hides_parameter_secrets(self): output = heuristic_log_sanitize('token="secret", user="person", token_entry="test=secret"', frozenset(['secret'])) self.assertNotIn('secret', output) def test_no_password(self): self.assertEqual(heuristic_log_sanitize('foo@bar'), 'foo@bar')
3,744
Python
.py
76
40.921053
122
0.641489
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,897
test__log_invocation.py
ansible_ansible/test/units/module_utils/basic/test__log_invocation.py
# -*- coding: utf-8 -*- # (c) 2016, James Cammarata <jimi@sngx.net> # (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import pytest ARGS = dict(foo=False, bar=[1, 2, 3], bam="bam", baz=u'baz') ARGUMENT_SPEC = dict( foo=dict(default=True, type='bool'), bar=dict(default=[], type='list'), bam=dict(default="bam"), baz=dict(default=u"baz"), password=dict(default=True), no_log=dict(default="you shouldn't see me", no_log=True), ) @pytest.mark.parametrize('am, stdin', [(ARGUMENT_SPEC, ARGS)], indirect=['am', 'stdin']) def test_module_utils_basic__log_invocation(am, mocker): am.log = mocker.MagicMock() am._log_invocation() # Message is generated from a dict so it will be in an unknown order. # have to check this manually rather than with assert_called_with() args = am.log.call_args[0] assert len(args) == 1 message = args[0] assert len(message) == \ len('Invoked with bam=bam bar=[1, 2, 3] foo=False baz=baz no_log=NOT_LOGGING_PARAMETER password=NOT_LOGGING_PASSWORD') assert message.startswith('Invoked with ') assert ' bam=bam' in message assert ' bar=[1, 2, 3]' in message assert ' foo=False' in message assert ' baz=baz' in message assert ' no_log=NOT_LOGGING_PARAMETER' in message assert ' password=NOT_LOGGING_PASSWORD' in message kwargs = am.log.call_args[1] assert kwargs == \ dict(log_args={ 'foo': 'False', 'bar': '[1, 2, 3]', 'bam': 'bam', 'baz': 'baz', 'password': 'NOT_LOGGING_PASSWORD', 'no_log': 'NOT_LOGGING_PARAMETER', })
1,746
Python
.py
43
34.976744
126
0.636525
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,898
test_sanitize_keys.py
ansible_ansible/test/units/module_utils/basic/test_sanitize_keys.py
# -*- coding: utf-8 -*- # (c) 2020, Red Hat # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations from ansible.module_utils.basic import sanitize_keys def test_sanitize_keys_non_dict_types(): """ Test that non-dict-like objects return the same data. """ type_exception = 'Unsupported type for key sanitization.' no_log_strings = set() assert 'string value' == sanitize_keys('string value', no_log_strings) assert sanitize_keys(None, no_log_strings) is None assert set(['x', 'y']) == sanitize_keys(set(['x', 'y']), no_log_strings) assert not sanitize_keys(False, no_log_strings) def _run_comparison(obj): no_log_strings = set(['secret', 'password']) ret = sanitize_keys(obj, no_log_strings) expected = [ None, True, 100, "some string", set([1, 2]), [1, 2], {'key1': ['value1a', 'value1b'], 'some-********': 'value-for-some-password', 'key2': {'key3': set(['value3a', 'value3b']), 'i-have-a-********': {'********-********': 'value-for-secret-password', 'key4': 'value4'} } }, {'foo': [{'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER': 1}]} ] assert ret == expected def test_sanitize_keys_dict(): """ Test that sanitize_keys works with a dict. """ d = [ None, True, 100, "some string", set([1, 2]), [1, 2], {'key1': ['value1a', 'value1b'], 'some-password': 'value-for-some-password', 'key2': {'key3': set(['value3a', 'value3b']), 'i-have-a-secret': {'secret-password': 'value-for-secret-password', 'key4': 'value4'} } }, {'foo': [{'secret': 1}]} ] _run_comparison(d) def test_sanitize_keys_with_ignores(): """ Test that we can actually ignore keys. """ no_log_strings = set(['secret', 'rc']) ignore_keys = set(['changed', 'rc', 'status']) value = {'changed': True, 'rc': 0, 'test-rc': 1, 'another-secret': 2, 'status': 'okie dokie'} # We expect to change 'test-rc' but NOT 'rc'. expected = {'changed': True, 'rc': 0, 'test-********': 1, 'another-********': 2, 'status': 'okie dokie'} ret = sanitize_keys(value, no_log_strings, ignore_keys) assert ret == expected
2,518
Python
.py
67
29.208955
107
0.530334
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
13,899
test_selinux.py
ansible_ansible/test/units/module_utils/basic/test_selinux.py
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016 Toshio Kuratomi <tkuratomi@ansible.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import annotations import errno import json import pytest from unittest.mock import mock_open, patch from ansible.module_utils import basic from ansible.module_utils.common.text.converters import to_bytes import builtins @pytest.fixture def no_args_module_exec(): with patch.object(basic, '_ANSIBLE_ARGS', b'{"ANSIBLE_MODULE_ARGS": {}}'): yield # we're patching the global module object, so nothing to yield def no_args_module(selinux_enabled=None, selinux_mls_enabled=None): am = basic.AnsibleModule(argument_spec={}) # just dirty-patch the wrappers on the object instance since it's short-lived if isinstance(selinux_enabled, bool): patch.object(am, 'selinux_enabled', return_value=selinux_enabled).start() if isinstance(selinux_mls_enabled, bool): patch.object(am, 'selinux_mls_enabled', return_value=selinux_mls_enabled).start() return am # test AnsibleModule selinux wrapper methods @pytest.mark.usefixtures('no_args_module_exec') class TestSELinuxMU: def test_selinux_enabled(self): # test selinux unavailable # selinux unavailable, should return false with patch.object(basic, 'HAVE_SELINUX', False): assert no_args_module().selinux_enabled() is False # test selinux present/not-enabled disabled_mod = no_args_module() with patch.object(basic, 'selinux', create=True) as selinux: selinux.is_selinux_enabled.return_value = 0 assert disabled_mod.selinux_enabled() is False # ensure value is cached (same answer after unpatching) assert disabled_mod.selinux_enabled() is False # and present / enabled with patch.object(basic, 'HAVE_SELINUX', True): enabled_mod = no_args_module() with patch.object(basic, 'selinux', create=True) as selinux: selinux.is_selinux_enabled.return_value = 1 assert enabled_mod.selinux_enabled() is True # ensure value is cached (same answer after unpatching) assert enabled_mod.selinux_enabled() is True def test_selinux_mls_enabled(self): # selinux unavailable, should return false with patch.object(basic, 'HAVE_SELINUX', False): assert no_args_module().selinux_mls_enabled() is False # selinux disabled, should return false with patch.object(basic, 'selinux', create=True) as selinux: selinux.is_selinux_mls_enabled.return_value = 0 assert no_args_module(selinux_enabled=False).selinux_mls_enabled() is False with patch.object(basic, 'HAVE_SELINUX', True): # selinux enabled, should pass through the value of is_selinux_mls_enabled with patch.object(basic, 'selinux', create=True) as selinux: selinux.is_selinux_mls_enabled.return_value = 1 assert no_args_module(selinux_enabled=True).selinux_mls_enabled() is True def test_selinux_initial_context(self): # selinux missing/disabled/enabled sans MLS is 3-element None assert no_args_module(selinux_enabled=False, selinux_mls_enabled=False).selinux_initial_context() == [None, None, None] assert no_args_module(selinux_enabled=True, selinux_mls_enabled=False).selinux_initial_context() == [None, None, None] # selinux enabled with MLS is 4-element None assert no_args_module(selinux_enabled=True, selinux_mls_enabled=True).selinux_initial_context() == [None, None, None, None] def test_selinux_default_context(self): # selinux unavailable with patch.object(basic, 'HAVE_SELINUX', False): assert no_args_module().selinux_default_context(path='/foo/bar') == [None, None, None] am = no_args_module(selinux_enabled=True, selinux_mls_enabled=True) with patch.object(basic, 'selinux', create=True) as selinux: # matchpathcon success selinux.matchpathcon.return_value = [0, 'unconfined_u:object_r:default_t:s0'] assert am.selinux_default_context(path='/foo/bar') == ['unconfined_u', 'object_r', 'default_t', 's0'] with patch.object(basic, 'selinux', create=True) as selinux: # matchpathcon fail (return initial context value) selinux.matchpathcon.return_value = [-1, ''] assert am.selinux_default_context(path='/foo/bar') == [None, None, None, None] with patch.object(basic, 'selinux', create=True) as selinux: # matchpathcon OSError selinux.matchpathcon.side_effect = OSError assert am.selinux_default_context(path='/foo/bar') == [None, None, None, None] def test_selinux_context(self): # selinux unavailable with patch.object(basic, 'HAVE_SELINUX', False): assert no_args_module().selinux_context(path='/foo/bar') == [None, None, None] am = no_args_module(selinux_enabled=True, selinux_mls_enabled=True) # lgetfilecon_raw passthru with patch.object(basic, 'selinux', create=True) as selinux: selinux.lgetfilecon_raw.return_value = [0, 'unconfined_u:object_r:default_t:s0'] assert am.selinux_context(path='/foo/bar') == ['unconfined_u', 'object_r', 'default_t', 's0'] # lgetfilecon_raw returned a failure with patch.object(basic, 'selinux', create=True) as selinux: selinux.lgetfilecon_raw.return_value = [-1, ''] assert am.selinux_context(path='/foo/bar') == [None, None, None, None] # lgetfilecon_raw OSError (should bomb the module) with patch.object(basic, 'selinux', create=True) as selinux: selinux.lgetfilecon_raw.side_effect = OSError(errno.ENOENT, 'NotFound') with pytest.raises(SystemExit): am.selinux_context(path='/foo/bar') with patch.object(basic, 'selinux', create=True) as selinux: selinux.lgetfilecon_raw.side_effect = OSError() with pytest.raises(SystemExit): am.selinux_context(path='/foo/bar') def test_is_special_selinux_path(self): args = to_bytes(json.dumps(dict(ANSIBLE_MODULE_ARGS={'_ansible_selinux_special_fs': "nfs,nfsd,foos", '_ansible_remote_tmp': "/tmp", '_ansible_keep_remote_files': False}))) with patch.object(basic, '_ANSIBLE_ARGS', args): am = basic.AnsibleModule( argument_spec=dict(), ) def _mock_find_mount_point(path): if path.startswith('/some/path'): return '/some/path' elif path.startswith('/weird/random/fstype'): return '/weird/random/fstype' return '/' am.find_mount_point = _mock_find_mount_point am.selinux_context = lambda path: ['foo_u', 'foo_r', 'foo_t', 's0'] m = mock_open() m.side_effect = OSError with patch.object(builtins, 'open', m, create=True): assert am.is_special_selinux_path('/some/path/that/should/be/nfs') == (False, None) mount_data = [ '/dev/disk1 / ext4 rw,seclabel,relatime,data=ordered 0 0\n', '10.1.1.1:/path/to/nfs /some/path nfs ro 0 0\n', 'whatever /weird/random/fstype foos rw 0 0\n', ] # mock_open has a broken readlines() implementation apparently... # this should work by default but doesn't, so we fix it m = mock_open(read_data=''.join(mount_data)) m.return_value.readlines.return_value = mount_data with patch.object(builtins, 'open', m, create=True): assert am.is_special_selinux_path('/some/random/path') == (False, None) assert am.is_special_selinux_path('/some/path/that/should/be/nfs') == (True, ['foo_u', 'foo_r', 'foo_t', 's0']) assert am.is_special_selinux_path('/weird/random/fstype/path') == (True, ['foo_u', 'foo_r', 'foo_t', 's0']) def test_set_context_if_different(self): am = no_args_module(selinux_enabled=False) assert am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True) is True assert am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False) is False am = no_args_module(selinux_enabled=True, selinux_mls_enabled=True) am.selinux_context = lambda path: ['bar_u', 'bar_r', None, None] am.is_special_selinux_path = lambda path: (False, None) with patch.object(basic, 'selinux', create=True) as selinux: selinux.lsetfilecon.return_value = 0 assert am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False) is True selinux.lsetfilecon.assert_called_with('/path/to/file', 'foo_u:foo_r:foo_t:s0') selinux.lsetfilecon.reset_mock() am.check_mode = True assert am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False) is True assert not selinux.lsetfilecon.called am.check_mode = False with patch.object(basic, 'selinux', create=True) as selinux: selinux.lsetfilecon.return_value = 1 with pytest.raises(SystemExit): am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True) with patch.object(basic, 'selinux', create=True) as selinux: selinux.lsetfilecon.side_effect = OSError with pytest.raises(SystemExit): am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True) am.is_special_selinux_path = lambda path: (True, ['sp_u', 'sp_r', 'sp_t', 's0']) with patch.object(basic, 'selinux', create=True) as selinux: selinux.lsetfilecon.return_value = 0 assert am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False) is True selinux.lsetfilecon.assert_called_with('/path/to/file', 'sp_u:sp_r:sp_t:s0')
10,477
Python
.py
168
51.035714
131
0.627581
ansible/ansible
62,258
23,791
861
GPL-3.0
9/5/2024, 5:11:58 PM (Europe/Amsterdam)