| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Copyright (c) 2015-2017 Ansible Project |
| 3 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import json |
| 8 |
import sys |
| 9 |
import datetime |
| 10 |
import typing as t |
| 11 |
|
| 12 |
import pytest |
| 13 |
import pytest_mock |
| 14 |
|
| 15 |
EMPTY_INVOCATION: dict[str, dict[str, t.Any]] = {u'module_args': {}} |
| 16 |
DATETIME = datetime.datetime.strptime('2020-07-13 12:50:00', '%Y-%m-%d %H:%M:%S') |
| 17 |
|
| 18 |
pytestmark = pytest.mark.usefixtures("module_env_mocker") |
| 19 |
|
| 20 |
|
| 21 |
class TestAnsibleModuleExitJson: |
| 22 |
""" |
| 23 |
Test that various means of calling exitJson and FailJson return the messages they've been given |
| 24 |
""" |
| 25 |
DATA: tuple[tuple[dict[str, t.Any]], ...] = ( |
| 26 |
({}, {'invocation': EMPTY_INVOCATION}), |
| 27 |
({'msg': 'message'}, {'msg': 'message', 'invocation': EMPTY_INVOCATION}), |
| 28 |
({'msg': 'success', 'changed': True}, |
| 29 |
{'msg': 'success', 'changed': True, 'invocation': EMPTY_INVOCATION}), |
| 30 |
({'msg': 'nochange', 'changed': False}, |
| 31 |
{'msg': 'nochange', 'changed': False, 'invocation': EMPTY_INVOCATION}), |
| 32 |
({'msg': 'message', 'date': DATETIME.date()}, |
| 33 |
{'msg': 'message', 'date': DATETIME.date().isoformat(), 'invocation': EMPTY_INVOCATION}), |
| 34 |
({'msg': 'message', 'datetime': DATETIME}, |
| 35 |
{'msg': 'message', 'datetime': DATETIME.isoformat(), 'invocation': EMPTY_INVOCATION}), |
| 36 |
) |
| 37 |
|
| 38 |
@pytest.mark.parametrize('args, expected, stdin', [(a, e, {}) for a, e in DATA], indirect=['stdin']) |
| 39 |
def test_exit_json_exits(self, am, capfd, args, expected): |
| 40 |
with pytest.raises(SystemExit) as ctx: |
| 41 |
am.exit_json(**args) |
| 42 |
assert ctx.value.code == 0 |
| 43 |
|
| 44 |
out, err = capfd.readouterr() |
| 45 |
return_val = json.loads(out) |
| 46 |
assert return_val == expected |
| 47 |
|
| 48 |
@pytest.mark.parametrize('args, expected, stdin', |
| 49 |
[(a, e, {}) for a, e in DATA if 'msg' in a], |
| 50 |
indirect=['stdin']) |
| 51 |
def test_fail_json_exits(self, am, capfd, args, expected): |
| 52 |
with pytest.raises(SystemExit) as ctx: |
| 53 |
am.fail_json(**args) |
| 54 |
assert ctx.value.code == 1 |
| 55 |
|
| 56 |
out, err = capfd.readouterr() |
| 57 |
return_val = json.loads(out) |
| 58 |
# Fail_json should add failed=True |
| 59 |
expected['failed'] = True |
| 60 |
assert return_val == expected |
| 61 |
|
| 62 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 63 |
def test_fail_json_msg_positional(self, am, capfd): |
| 64 |
with pytest.raises(SystemExit) as ctx: |
| 65 |
am.fail_json('This is the msg') |
| 66 |
assert ctx.value.code == 1 |
| 67 |
|
| 68 |
out, err = capfd.readouterr() |
| 69 |
return_val = json.loads(out) |
| 70 |
# Fail_json should add failed=True |
| 71 |
assert return_val == {'msg': 'This is the msg', 'failed': True, |
| 72 |
'invocation': EMPTY_INVOCATION} |
| 73 |
|
| 74 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 75 |
def test_fail_json_msg_as_kwarg_after(self, am, capfd): |
| 76 |
"""Test that msg as a kwarg after other kwargs works""" |
| 77 |
with pytest.raises(SystemExit) as ctx: |
| 78 |
am.fail_json(arbitrary=42, msg='This is the msg') |
| 79 |
assert ctx.value.code == 1 |
| 80 |
|
| 81 |
out, err = capfd.readouterr() |
| 82 |
return_val = json.loads(out) |
| 83 |
# Fail_json should add failed=True |
| 84 |
assert return_val == {'msg': 'This is the msg', 'failed': True, |
| 85 |
'arbitrary': 42, |
| 86 |
'invocation': EMPTY_INVOCATION} |
| 87 |
|
| 88 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 89 |
def test_fail_json_no_msg(self, am): |
| 90 |
with pytest.raises(TypeError) as ctx: |
| 91 |
am.fail_json() |
| 92 |
|
| 93 |
if sys.version_info >= (3, 10): |
| 94 |
error_msg = "AnsibleModule.fail_json() missing 1 required positional argument: 'msg'" |
| 95 |
else: |
| 96 |
error_msg = "fail_json() missing 1 required positional argument: 'msg'" |
| 97 |
|
| 98 |
assert ctx.value.args[0] == error_msg |
| 99 |
|
| 100 |
|
| 101 |
class TestAnsibleModuleExitNewSecretsProvided: |
| 102 |
""" |
| 103 |
Test that ExitJson and FailJson provide the newly registered secrets |
| 104 |
""" |
| 105 |
|
| 106 |
DATA = ( |
| 107 |
( |
| 108 |
dict(username='person', password='$secret k3y'), |
| 109 |
dict(one=1, pwd='$secret k3y', url='https://username:[email protected]/login/', |
| 110 |
not_secret='following the leader', msg='here'), |
| 111 |
dict(one=1, pwd='$secret k3y', url='https://username:[email protected]/login/', |
| 112 |
not_secret='following the leader', msg='here', |
| 113 |
invocation=dict(module_args=dict(password='$secret k3y', token=None, username='person')), |
| 114 |
_ansible_new_secrets=['$secret k3y']), |
| 115 |
), |
| 116 |
( |
| 117 |
dict(username='person', password='password12345'), |
| 118 |
dict(one=1, pwd='$secret k3y', url='https://username:[email protected]/login/', |
| 119 |
not_secret='following the leader', msg='here'), |
| 120 |
dict(one=1, pwd='$secret k3y', url='https://username:[email protected]/login/', |
| 121 |
not_secret='following the leader', msg='here', |
| 122 |
invocation=dict(module_args=dict(password='password12345', token=None, username='person')), |
| 123 |
_ansible_new_secrets=['password12345']), |
| 124 |
), |
| 125 |
( |
| 126 |
dict(username='person', password='$secret k3y'), |
| 127 |
dict(one=1, pwd='$secret k3y', url='https://username:$secret [email protected]/login/', |
| 128 |
not_secret='following the leader', msg='here'), |
| 129 |
dict(one=1, pwd='$secret k3y', url='https://username:$secret [email protected]/login/', |
| 130 |
not_secret='following the leader', msg='here', |
| 131 |
invocation=dict(module_args=dict(password='$secret k3y', token=None, username='person')), |
| 132 |
_ansible_new_secrets=['$secret k3y']), |
| 133 |
), |
| 134 |
) |
| 135 |
|
| 136 |
@pytest.mark.parametrize('am, stdin, return_val, expected', |
| 137 |
[({'username': {}, 'password': {'no_log': True}, 'token': {'no_log': True}}, s, r, e) |
| 138 |
for s, r, e in DATA], |
| 139 |
indirect=['am', 'stdin']) |
| 140 |
def test_exit_json_removes_values(self, am, capfd, return_val, expected): |
| 141 |
with pytest.raises(SystemExit): |
| 142 |
am.exit_json(**return_val) |
| 143 |
out, err = capfd.readouterr() |
| 144 |
|
| 145 |
assert json.loads(out) == expected |
| 146 |
|
| 147 |
@pytest.mark.parametrize('am, stdin, return_val, expected', |
| 148 |
[({'username': {}, 'password': {'no_log': True}, 'token': {'no_log': True}}, s, r, e) |
| 149 |
for s, r, e in DATA], |
| 150 |
indirect=['am', 'stdin']) |
| 151 |
def test_fail_json_removes_values(self, am, capfd, return_val, expected): |
| 152 |
expected['failed'] = True |
| 153 |
with pytest.raises(SystemExit): |
| 154 |
am.fail_json(**return_val) |
| 155 |
out, err = capfd.readouterr() |
| 156 |
|
| 157 |
assert json.loads(out) == expected |
| 158 |
|
| 159 |
def test_record_module_result(self, mocker: pytest_mock.MockerFixture, stdin) -> None: |
| 160 |
"""Ensure that the temporary _record_module_result hook is called correctly.""" |
| 161 |
recorded_result = None |
| 162 |
|
| 163 |
expected_result = dict(changed=False, worked="yay") |
| 164 |
|
| 165 |
def _record_module_result(_self, o: object) -> None: |
| 166 |
assert isinstance(o, dict) |
| 167 |
|
| 168 |
nonlocal recorded_result |
| 169 |
recorded_result = o |
| 170 |
|
| 171 |
from ansible.module_utils.basic import AnsibleModule |
| 172 |
|
| 173 |
mocker.patch.object(AnsibleModule, '_record_module_result', _record_module_result) |
| 174 |
|
| 175 |
am = AnsibleModule(argument_spec=dict()) |
| 176 |
|
| 177 |
with pytest.raises(SystemExit): |
| 178 |
am.exit_json(**expected_result) |
| 179 |
|
| 180 |
assert expected_result.items() <= recorded_result.items() |