unit test helper: big revamp (#8894)

* initial commit

* multiple changes:

- TestCaseContext fixture no longer need to autouse=True
- Helper.from_module() allows extra param to specify yaml file
- test_django_check: adjusted .py and .yaml

* set fixtures per testcase

* set fixtures per testcase

* rollback to original state

* patch_ansible_module fixture

- now it works not only in parametrized functions but also directly with args

* tests/unit/plugins/modules/helper.py

- improved encapsulation, class Helper no longer knows details about test cases
- test functions no longer parametrized, that allows using test case fixtures per test function
- renamed 'context' to 'mock'

* enable Helper.from_list(), better param name 'ansible_module'

* adjusted test fiels to new helper

* remove unnecessary .license file

* fix bracket

* fix reference name

* Update tests/unit/plugins/modules/helper.py

Co-authored-by: Felix Fontein <felix@fontein.de>

* revert to parametrized test func instead of multiple funcs

---------

Co-authored-by: Felix Fontein <felix@fontein.de>
pull/8908/head
Alexei Znamensky 2024-09-28 17:17:36 +12:00 committed by GitHub
parent fe18b05f08
commit 8ef77d8664
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
27 changed files with 611 additions and 478 deletions

View File

@ -16,22 +16,34 @@ from ansible.module_utils.common._collections_compat import MutableMapping
from ansible_collections.community.general.plugins.module_utils import deps
@pytest.fixture
def patch_ansible_module(request, mocker):
if isinstance(request.param, string_types):
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)
def fix_ansible_args(args):
if isinstance(args, string_types):
return args
if isinstance(args, MutableMapping):
if 'ANSIBLE_MODULE_ARGS' not in args:
args = {'ANSIBLE_MODULE_ARGS': args}
if '_ansible_remote_tmp' not in args['ANSIBLE_MODULE_ARGS']:
args['ANSIBLE_MODULE_ARGS']['_ansible_remote_tmp'] = '/tmp'
if '_ansible_keep_remote_files' not in args['ANSIBLE_MODULE_ARGS']:
args['ANSIBLE_MODULE_ARGS']['_ansible_keep_remote_files'] = False
args = json.dumps(args)
return args
else:
raise Exception('Malformed data to the patch_ansible_module pytest fixture')
mocker.patch('ansible.module_utils.basic._ANSIBLE_ARGS', to_bytes(args))
@pytest.fixture
def patch_ansible_module(request, mocker):
if hasattr(request, "param"):
args = fix_ansible_args(request.param)
mocker.patch('ansible.module_utils.basic._ANSIBLE_ARGS', to_bytes(args))
else:
def _patch(args):
args = fix_ansible_args(args)
mocker.patch('ansible.module_utils.basic._ANSIBLE_ARGS', to_bytes(args))
return _patch
@pytest.fixture(autouse=True)

View File

@ -8,75 +8,221 @@ __metaclass__ = type
import sys
import json
from collections import namedtuple
import pytest
import yaml
import pytest
ModuleTestCase = namedtuple("ModuleTestCase", ["id", "input", "output", "run_command_calls", "flags"])
RunCmdCall = namedtuple("RunCmdCall", ["command", "environ", "rc", "out", "err"])
class Helper(object):
@staticmethod
def from_list(test_module, ansible_module, test_cases):
helper = Helper(test_module, ansible_module, test_cases=test_cases)
return helper
@staticmethod
def from_file(test_module, ansible_module, filename):
with open(filename, "r") as test_cases:
test_cases_data = yaml.safe_load(test_cases)
return Helper.from_list(test_module, ansible_module, test_cases_data)
@staticmethod
def from_module(ansible_module, test_module_name, test_spec=None):
test_module = sys.modules[test_module_name]
if test_spec is None:
test_spec = test_module.__file__.replace('.py', '.yaml')
return Helper.from_file(test_module, ansible_module, test_spec)
def add_func_to_test_module(self, name, func):
setattr(self.test_module, name, func)
def __init__(self, test_module, ansible_module, test_cases):
self.test_module = test_module
self.ansible_module = ansible_module
self.test_cases = []
self.fixtures = {}
for test_case in test_cases:
tc = ModuleTestCase.make_test_case(test_case, test_module)
self.test_cases.append(tc)
self.fixtures.update(tc.fixtures)
self.set_test_func()
self.set_fixtures(self.fixtures)
@property
def runner(self):
return Runner(self.ansible_module.main)
def set_test_func(self):
@pytest.mark.parametrize('test_case', self.test_cases, ids=[tc.id for tc in self.test_cases])
@pytest.mark.usefixtures(*self.fixtures)
def _test_module(mocker, capfd, patch_ansible_module, test_case):
"""
Run unit tests for each test case in self.test_cases
"""
patch_ansible_module(test_case.input)
self.runner.run(mocker, capfd, test_case)
self.add_func_to_test_module("test_module", _test_module)
return _test_module
def set_fixtures(self, fixtures):
for name, fixture in fixtures.items():
self.add_func_to_test_module(name, fixture)
class _BaseContext(object):
def __init__(self, helper, testcase, mocker, capfd):
self.helper = helper
self.testcase = testcase
self.mocker = mocker
self.capfd = capfd
class Runner:
def __init__(self, module_main):
self.module_main = module_main
self.results = None
def __enter__(self):
return self
def run(self, mocker, capfd, test_case):
test_case.setup(mocker)
self.pytest_module(capfd, test_case.flags)
test_case.check(self.results)
def __exit__(self, exc_type, exc_val, exc_tb):
return False
def pytest_module(self, capfd, flags):
if flags.get("skip"):
pytest.skip(flags.get("skip"))
if flags.get("xfail"):
pytest.xfail(flags.get("xfail"))
def _run(self):
with pytest.raises(SystemExit):
self.helper.module_main()
(self.module_main)()
out, err = self.capfd.readouterr()
results = json.loads(out)
out, err = capfd.readouterr()
self.results = json.loads(out)
self.check_results(results)
def test_flags(self, flag=None):
flags = self.testcase.flags
if flag:
flags = flags.get(flag)
return flags
class ModuleTestCase:
def __init__(self, id, input, output, mocks, flags):
self.id = id
self.input = input
self.output = output
self._mocks = mocks
self.mocks = {}
self.flags = flags
def run(self):
func = self._run
self._fixtures = {}
test_flags = self.test_flags()
if test_flags.get("skip"):
pytest.skip(test_flags.get("skip"))
if test_flags.get("xfail"):
pytest.xfail(test_flags.get("xfail"))
def __str__(self):
return "<ModuleTestCase: id={id} {input}{output}mocks={mocks} flags={flags}>".format(
id=self.id,
input="input " if self.input else "",
output="output " if self.output else "",
mocks="({0})".format(", ".join(self.mocks.keys())),
flags=self.flags
)
func()
def __repr__(self):
return "ModuleTestCase(id={id}, input={input}, output={output}, mocks={mocks}, flags={flags})".format(
id=self.id,
input=self.input,
output=self.output,
mocks=repr(self.mocks),
flags=self.flags
)
def check_results(self, results):
print("testcase =\n%s" % str(self.testcase))
@staticmethod
def make_test_case(test_case, test_module):
tc = ModuleTestCase(
id=test_case["id"],
input=test_case.get("input", {}),
output=test_case.get("output", {}),
mocks=test_case.get("mocks", {}),
flags=test_case.get("flags", {})
)
tc.build_mocks(test_module)
return tc
def build_mocks(self, test_module):
for mock, mock_spec in self._mocks.items():
mock_class = self.get_mock_class(test_module, mock)
self.mocks[mock] = mock_class.build_mock(mock_spec)
self._fixtures.update(self.mocks[mock].fixtures())
@staticmethod
def get_mock_class(test_module, mock):
try:
class_name = "".join(x.capitalize() for x in mock.split("_")) + "Mock"
plugin_class = getattr(test_module, class_name)
assert issubclass(plugin_class, TestCaseMock), "Class {0} is not a subclass of TestCaseMock".format(class_name)
return plugin_class
except AttributeError:
raise ValueError("Cannot find class {0} for mock {1}".format(class_name, mock))
@property
def fixtures(self):
return dict(self._fixtures)
def setup(self, mocker):
self.setup_testcase(mocker)
self.setup_mocks(mocker)
def check(self, results):
self.check_testcase(results)
self.check_mocks(self, results)
def setup_testcase(self, mocker):
pass
def setup_mocks(self, mocker):
for mock in self.mocks.values():
mock.setup(mocker)
def check_testcase(self, results):
print("testcase =\n%s" % repr(self))
print("results =\n%s" % results)
if 'exception' in results:
print("exception = \n%s" % results["exception"])
for test_result in self.testcase.output:
assert results[test_result] == self.testcase.output[test_result], \
"'{0}': '{1}' != '{2}'".format(test_result, results[test_result], self.testcase.output[test_result])
for test_result in self.output:
assert results[test_result] == self.output[test_result], \
"'{0}': '{1}' != '{2}'".format(test_result, results[test_result], self.output[test_result])
def check_mocks(self, test_case, results):
for mock in self.mocks.values():
mock.check(test_case, results)
class _RunCmdContext(_BaseContext):
def __init__(self, *args, **kwargs):
super(_RunCmdContext, self).__init__(*args, **kwargs)
self.run_cmd_calls = self.testcase.run_command_calls
self.mock_run_cmd = self._make_mock_run_cmd()
class TestCaseMock:
@classmethod
def build_mock(cls, mock_specs):
return cls(mock_specs)
def _make_mock_run_cmd(self):
def __init__(self, mock_specs):
self.mock_specs = mock_specs
def fixtures(self):
return {}
def setup(self, mocker):
pass
def check(self, test_case, results):
raise NotImplementedError()
class RunCommandMock(TestCaseMock):
def __str__(self):
return "<RunCommandMock specs={specs}>".format(specs=self.mock_specs)
def __repr__(self):
return "RunCommandMock({specs})".format(specs=self.mock_specs)
def fixtures(self):
@pytest.fixture
def patch_bin(mocker):
def mockie(self, path, *args, **kwargs):
return "/testbin/{0}".format(path)
mocker.patch('ansible.module_utils.basic.AnsibleModule.get_bin_path', mockie)
return {"patch_bin": patch_bin}
def setup(self, mocker):
def _results():
for result in [(x.rc, x.out, x.err) for x in self.run_cmd_calls]:
for result in [(x['rc'], x['out'], x['err']) for x in self.mock_specs]:
yield result
raise Exception("testcase has not enough run_command calls")
@ -88,102 +234,14 @@ class _RunCmdContext(_BaseContext):
raise Exception("rc = {0}".format(result[0]))
return result
mock_run_command = self.mocker.patch('ansible.module_utils.basic.AnsibleModule.run_command',
side_effect=side_effect)
return mock_run_command
self.mock_run_cmd = mocker.patch('ansible.module_utils.basic.AnsibleModule.run_command', side_effect=side_effect)
def check_results(self, results):
super(_RunCmdContext, self).check_results(results)
def check(self, test_case, results):
call_args_list = [(item[0][0], item[1]) for item in self.mock_run_cmd.call_args_list]
expected_call_args_list = [(item.command, item.environ) for item in self.run_cmd_calls]
expected_call_args_list = [(item['command'], item['environ']) for item in self.mock_specs]
print("call args list =\n%s" % call_args_list)
print("expected args list =\n%s" % expected_call_args_list)
assert self.mock_run_cmd.call_count == len(self.run_cmd_calls), "{0} != {1}".format(self.mock_run_cmd.call_count, len(self.run_cmd_calls))
assert self.mock_run_cmd.call_count == len(self.mock_specs), "{0} != {1}".format(self.mock_run_cmd.call_count, len(self.mock_specs))
if self.mock_run_cmd.call_count:
assert call_args_list == expected_call_args_list
class Helper(object):
@staticmethod
def from_list(module_main, list_):
helper = Helper(module_main, test_cases=list_)
return helper
@staticmethod
def from_file(module_main, filename):
with open(filename, "r") as test_cases:
helper = Helper(module_main, test_cases=test_cases)
return helper
@staticmethod
def from_module(module, test_module_name):
basename = module.__name__.split(".")[-1]
test_spec = "tests/unit/plugins/modules/test_{0}.yaml".format(basename)
helper = Helper.from_file(module.main, test_spec)
setattr(sys.modules[test_module_name], "patch_bin", helper.cmd_fixture)
setattr(sys.modules[test_module_name], "test_module", helper.test_module)
def __init__(self, module_main, test_cases):
self.module_main = module_main
self._test_cases = test_cases
if isinstance(test_cases, (list, tuple)):
self.testcases = test_cases
else:
self.testcases = self._make_test_cases()
@property
def cmd_fixture(self):
@pytest.fixture
def patch_bin(mocker):
def mockie(self, path, *args, **kwargs):
return "/testbin/{0}".format(path)
mocker.patch('ansible.module_utils.basic.AnsibleModule.get_bin_path', mockie)
return patch_bin
def _make_test_cases(self):
test_cases = yaml.safe_load(self._test_cases)
results = []
for tc in test_cases:
for tc_param in ["input", "output", "flags"]:
if not tc.get(tc_param):
tc[tc_param] = {}
if tc.get("run_command_calls"):
tc["run_command_calls"] = [RunCmdCall(**r) for r in tc["run_command_calls"]]
else:
tc["run_command_calls"] = []
results.append(ModuleTestCase(**tc))
return results
@property
def testcases_params(self):
return [[x.input, x] for x in self.testcases]
@property
def testcases_ids(self):
return [item.id for item in self.testcases]
def __call__(self, *args, **kwargs):
return _RunCmdContext(self, *args, **kwargs)
@property
def test_module(self):
helper = self
@pytest.mark.parametrize('patch_ansible_module, testcase',
helper.testcases_params, ids=helper.testcases_ids,
indirect=['patch_ansible_module'])
@pytest.mark.usefixtures('patch_ansible_module')
def _test_module(mocker, capfd, patch_bin, testcase):
"""
Run unit tests for test cases listed in TEST_CASES
"""
with helper(testcase, mocker, capfd) as testcase_context:
testcase_context.run()
return _test_module

View File

@ -14,7 +14,7 @@ __metaclass__ = type
from ansible_collections.community.general.plugins.modules import cpanm
from .helper import Helper
from .helper import Helper, RunCommandMock # pylint: disable=unused-import
Helper.from_module(cpanm, __name__)

View File

@ -10,7 +10,8 @@
mode: compatibility
output:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/perl, -le, 'use Dancer;']
environ: &env-def-false {environ_update: {LANGUAGE: C, LC_ALL: C}, check_rc: false}
rc: 2
@ -27,7 +28,8 @@
mode: compatibility
output:
changed: false
run_command_calls:
mocks:
run_command:
- command: [/testbin/perl, -le, 'use Dancer;']
environ: *env-def-false
rc: 0
@ -38,7 +40,8 @@
name: Dancer
output:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/cpanm, Dancer]
environ: *env-def-true
rc: 0
@ -50,7 +53,8 @@
mode: compatibility
output:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/cpanm, MIYAGAWA/Plack-0.99_05.tar.gz]
environ: *env-def-true
rc: 0
@ -61,7 +65,8 @@
name: MIYAGAWA/Plack-0.99_05.tar.gz
output:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/cpanm, MIYAGAWA/Plack-0.99_05.tar.gz]
environ: *env-def-true
rc: 0
@ -74,7 +79,8 @@
locallib: /srv/webapps/my_app/extlib
output:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/cpanm, --local-lib, /srv/webapps/my_app/extlib, Dancer]
environ: *env-def-true
rc: 0
@ -86,7 +92,8 @@
mode: new
output:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/cpanm, /srv/webapps/my_app/src/]
environ: *env-def-true
rc: 0
@ -100,7 +107,8 @@
locallib: /srv/webapps/my_app/extlib
output:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/cpanm, --notest, --local-lib, /srv/webapps/my_app/extlib, Dancer]
environ: *env-def-true
rc: 0
@ -113,7 +121,8 @@
mirror: "http://cpan.cpantesters.org/"
output:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/cpanm, --mirror, "http://cpan.cpantesters.org/", Dancer]
environ: *env-def-true
rc: 0
@ -126,7 +135,8 @@
system_lib: true
output:
failed: true
run_command_calls: []
mocks:
run_command: []
- id: install_minversion_implicit
input:
name: Dancer
@ -134,7 +144,8 @@
version: "1.0"
output:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/cpanm, Dancer~1.0]
environ: *env-def-true
rc: 0
@ -147,7 +158,8 @@
version: "~1.5"
output:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/cpanm, Dancer~1.5]
environ: *env-def-true
rc: 0
@ -160,7 +172,8 @@
version: "@1.7"
output:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/cpanm, Dancer@1.7]
environ: *env-def-true
rc: 0
@ -174,7 +187,8 @@
output:
failed: true
msg: parameter 'version' must not be used when installing from a file
run_command_calls: []
mocks:
run_command: []
- id: install_specific_version_from_directory_error
input:
from_path: ~/
@ -183,7 +197,8 @@
output:
failed: true
msg: parameter 'version' must not be used when installing from a directory
run_command_calls: []
mocks:
run_command: []
- id: install_specific_version_from_git_url_explicit
input:
name: "git://github.com/plack/Plack.git"
@ -191,7 +206,8 @@
version: "@1.7"
output:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/cpanm, "git://github.com/plack/Plack.git@1.7"]
environ: *env-def-true
rc: 0
@ -204,7 +220,8 @@
version: "2.5"
output:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/cpanm, "git://github.com/plack/Plack.git@2.5"]
environ: *env-def-true
rc: 0
@ -218,4 +235,5 @@
output:
failed: true
msg: operator '~' not allowed in version parameter when installing from git repository
run_command_calls: []
mocks:
run_command: []

View File

@ -7,7 +7,7 @@ __metaclass__ = type
from ansible_collections.community.general.plugins.modules import django_check
from .helper import Helper
from .helper import Helper, RunCommandMock # pylint: disable=unused-import
Helper.from_module(django_check, __name__)

View File

@ -7,7 +7,8 @@
- id: success
input:
settings: whatever.settings
run_command_calls:
mocks:
run_command:
- command: [/testbin/python, -m, django, check, --no-color, --settings=whatever.settings]
environ: &env-def {environ_update: {LANGUAGE: C, LC_ALL: C}, check_rc: true}
rc: 0
@ -17,9 +18,10 @@
input:
settings: whatever.settings
database:
- abc
- def
run_command_calls:
- abc
- def
mocks:
run_command:
- command: [/testbin/python, -m, django, check, --no-color, --settings=whatever.settings, --database, abc, --database, def]
environ: *env-def
rc: 0

View File

@ -7,7 +7,7 @@ __metaclass__ = type
from ansible_collections.community.general.plugins.modules import django_command
from .helper import Helper
from .helper import Helper, RunCommandMock # pylint: disable=unused-import
Helper.from_module(django_command, __name__)

View File

@ -8,12 +8,13 @@
input:
command: check
extra_args:
- babaloo
- yaba
- daba
- doo
- babaloo
- yaba
- daba
- doo
settings: whatever.settings
run_command_calls:
mocks:
run_command:
- command: [/testbin/python, -m, django, check, --no-color, --settings=whatever.settings, babaloo, yaba, daba, doo]
environ: &env-def {environ_update: {LANGUAGE: C, LC_ALL: C}, check_rc: true}
rc: 0
@ -23,14 +24,15 @@
input:
command: check
extra_args:
- babaloo
- yaba
- daba
- doo
- babaloo
- yaba
- daba
- doo
settings: whatever.settings
output:
failed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/python, -m, django, check, --no-color, --settings=whatever.settings, babaloo, yaba, daba, doo]
environ: *env-def
rc: 1

View File

@ -7,7 +7,7 @@ __metaclass__ = type
from ansible_collections.community.general.plugins.modules import django_createcachetable
from .helper import Helper
from .helper import Helper, RunCommandMock # pylint: disable=unused-import
Helper.from_module(django_createcachetable, __name__)

View File

@ -7,9 +7,10 @@
- id: command_success
input:
settings: whatever.settings
run_command_calls:
mocks:
run_command:
- command: [/testbin/python, -m, django, createcachetable, --no-color, --settings=whatever.settings, --noinput, --database=default]
environ: &env-def {environ_update: {LANGUAGE: C, LC_ALL: C}, check_rc: true}
environ: {environ_update: {LANGUAGE: C, LC_ALL: C}, check_rc: true}
rc: 0
out: "whatever\n"
err: ""

View File

@ -8,7 +8,7 @@ __metaclass__ = type
from ansible_collections.community.general.plugins.modules import facter_facts
from .helper import Helper
from .helper import Helper, RunCommandMock # pylint: disable=unused-import
Helper.from_module(facter_facts, __name__)

View File

@ -11,7 +11,8 @@
a: 1
b: 2
c: 3
run_command_calls:
mocks:
run_command:
- command: [/testbin/facter, --json]
environ: &env-def {check_rc: true}
rc: 0
@ -21,17 +22,18 @@
- id: with args
input:
arguments:
- -p
- system_uptime
- timezone
- is_virtual
- -p
- system_uptime
- timezone
- is_virtual
output:
ansible_facts:
facter:
a: 1
b: 2
c: 3
run_command_calls:
mocks:
run_command:
- command: [/testbin/facter, --json, -p, system_uptime, timezone, is_virtual]
environ: *env-def
rc: 0

View File

@ -8,7 +8,7 @@ __metaclass__ = type
from ansible_collections.community.general.plugins.modules import gconftool2
from .helper import Helper
from .helper import Helper, RunCommandMock # pylint: disable=unused-import
Helper.from_module(gconftool2, __name__)

View File

@ -13,7 +13,8 @@
output:
new_value: '200'
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/gconftool-2, --get, /desktop/gnome/background/picture_filename]
environ: &env-def {environ_update: {LANGUAGE: C, LC_ALL: C}, check_rc: true}
rc: 0
@ -38,7 +39,8 @@
output:
new_value: '200'
changed: false
run_command_calls:
mocks:
run_command:
- command: [/testbin/gconftool-2, --get, /desktop/gnome/background/picture_filename]
environ: *env-def
rc: 0
@ -63,7 +65,8 @@
output:
new_value: 'false'
changed: false
run_command_calls:
mocks:
run_command:
- command: [/testbin/gconftool-2, --get, /apps/gnome_settings_daemon/screensaver/start_screensaver]
environ: *env-def
rc: 0
@ -84,9 +87,10 @@
state: absent
key: /desktop/gnome/background/picture_filename
output:
new_value: null
new_value:
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/gconftool-2, --get, /desktop/gnome/background/picture_filename]
environ: *env-def
rc: 0
@ -102,9 +106,10 @@
state: absent
key: /apps/gnome_settings_daemon/screensaver/start_screensaver
output:
new_value: null
new_value:
changed: false
run_command_calls:
mocks:
run_command:
- command: [/testbin/gconftool-2, --get, /apps/gnome_settings_daemon/screensaver/start_screensaver]
environ: *env-def
rc: 0

View File

@ -8,7 +8,7 @@ __metaclass__ = type
from ansible_collections.community.general.plugins.modules import gconftool2_info
from .helper import Helper
from .helper import Helper, RunCommandMock # pylint: disable=unused-import
Helper.from_module(gconftool2_info, __name__)

View File

@ -9,7 +9,8 @@
key: /desktop/gnome/background/picture_filename
output:
value: '100'
run_command_calls:
mocks:
run_command:
- command: [/testbin/gconftool-2, --get, /desktop/gnome/background/picture_filename]
environ: &env-def {environ_update: {LANGUAGE: C, LC_ALL: C}, check_rc: true}
rc: 0
@ -19,8 +20,9 @@
input:
key: /desktop/gnome/background/picture_filename
output:
value: null
run_command_calls:
value:
mocks:
run_command:
- command: [/testbin/gconftool-2, --get, /desktop/gnome/background/picture_filename]
environ: *env-def
rc: 0

View File

@ -8,7 +8,7 @@ __metaclass__ = type
from ansible_collections.community.general.plugins.modules import gio_mime
from .helper import Helper
from .helper import Helper, RunCommandMock # pylint: disable=unused-import
Helper.from_module(gio_mime, __name__)

View File

@ -11,7 +11,8 @@
output:
handler: google-chrome.desktop
changed: true
run_command_calls:
mocks:
run_command:
- command: [/testbin/gio, mime, x-scheme-handler/http]
environ: &env-def {environ_update: {LANGUAGE: C, LC_ALL: C}, check_rc: true}
rc: 0
@ -32,7 +33,8 @@
changed: true
flags:
skip: test helper does not support check mode yet
run_command_calls:
mocks:
run_command:
- command: [/testbin/gio, mime, x-scheme-handler/http]
environ: *env-def
rc: 0
@ -51,7 +53,8 @@
output:
handler: google-chrome.desktop
changed: false
run_command_calls:
mocks:
run_command:
- command: [/testbin/gio, mime, x-scheme-handler/http]
environ: *env-def
rc: 0

View File

@ -8,7 +8,7 @@ __metaclass__ = type
from ansible_collections.community.general.plugins.modules import opkg
from .helper import Helper
from .helper import Helper, RunCommandMock # pylint: disable=unused-import
Helper.from_module(opkg, __name__)

View File

@ -10,7 +10,8 @@
state: present
output:
msg: installed 1 package(s)
run_command_calls:
mocks:
run_command:
- command: [/testbin/opkg, list-installed, zlib-dev]
environ: &env-def {environ_update: {LANGUAGE: C, LC_ALL: C}, check_rc: false}
rc: 0
@ -39,7 +40,8 @@
state: present
output:
msg: package(s) already present
run_command_calls:
mocks:
run_command:
- command: [/testbin/opkg, list-installed, zlib-dev]
environ: *env-def
rc: 0
@ -53,7 +55,8 @@
force: reinstall
output:
msg: installed 1 package(s)
run_command_calls:
mocks:
run_command:
- command: [/testbin/opkg, list-installed, zlib-dev]
environ: *env-def
rc: 0
@ -80,7 +83,8 @@
state: present
output:
msg: installed 1 package(s)
run_command_calls:
mocks:
run_command:
- command: [/testbin/opkg, list-installed, zlib-dev]
environ: *env-def
rc: 0
@ -109,7 +113,8 @@
update_cache: true
output:
msg: installed 1 package(s)
run_command_calls:
mocks:
run_command:
- command: [/testbin/opkg, update]
environ: *env-def
rc: 0

View File

@ -14,7 +14,7 @@ __metaclass__ = type
from ansible_collections.community.general.plugins.modules import puppet
from .helper import Helper
from .helper import Helper, RunCommandMock # pylint: disable=unused-import
Helper.from_module(puppet, __name__)

View File

@ -8,27 +8,28 @@
input: {}
output:
changed: false
run_command_calls:
mocks:
run_command:
- command: [/testbin/puppet, config, print, agent_disabled_lockfile]
environ: &env-def {environ_update: {LANGUAGE: C, LC_ALL: C}, check_rc: false}
rc: 0
out: "blah, anything"
err: ""
- command:
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
environ: *env-def
rc: 0
out: ""
@ -38,28 +39,29 @@
certname: potatobox
output:
changed: false
run_command_calls:
mocks:
run_command:
- command: [/testbin/puppet, config, print, agent_disabled_lockfile]
environ: *env-def
rc: 0
out: "blah, anything"
err: ""
- command:
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
- --certname=potatobox
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
- --certname=potatobox
environ: *env-def
rc: 0
out: ""
@ -69,29 +71,30 @@
tags: [a, b, c]
output:
changed: false
run_command_calls:
mocks:
run_command:
- command: [/testbin/puppet, config, print, agent_disabled_lockfile]
environ: *env-def
rc: 0
out: "blah, anything"
err: ""
- command:
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
- --tags
- a,b,c
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
- --tags
- a,b,c
environ: *env-def
rc: 0
out: ""
@ -101,29 +104,30 @@
skip_tags: [d, e, f]
output:
changed: false
run_command_calls:
mocks:
run_command:
- command: [/testbin/puppet, config, print, agent_disabled_lockfile]
environ: *env-def
rc: 0
out: "blah, anything"
err: ""
- command:
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
- --skip_tags
- d,e,f
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
- --skip_tags
- d,e,f
environ: *env-def
rc: 0
out: ""
@ -133,28 +137,29 @@
noop: false
output:
changed: false
run_command_calls:
mocks:
run_command:
- command: [/testbin/puppet, config, print, agent_disabled_lockfile]
environ: *env-def
rc: 0
out: "blah, anything"
err: ""
- command:
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
- --no-noop
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
- --no-noop
environ: *env-def
rc: 0
out: ""
@ -164,28 +169,29 @@
noop: true
output:
changed: false
run_command_calls:
mocks:
run_command:
- command: [/testbin/puppet, config, print, agent_disabled_lockfile]
environ: *env-def
rc: 0
out: "blah, anything"
err: ""
- command:
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
- --noop
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
- --noop
environ: *env-def
rc: 0
out: ""
@ -195,29 +201,30 @@
waitforlock: 30
output:
changed: false
run_command_calls:
mocks:
run_command:
- command: [/testbin/puppet, config, print, agent_disabled_lockfile]
environ: *env-def
rc: 0
out: "blah, anything"
err: ""
- command:
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
- --waitforlock
- "30"
- /testbin/timeout
- -s
- "9"
- 30m
- /testbin/puppet
- agent
- --onetime
- --no-daemonize
- --no-usecacheonfailure
- --no-splay
- --detailed-exitcodes
- --verbose
- --color
- "0"
- --waitforlock
- "30"
environ: *env-def
rc: 0
out: ""

View File

@ -6,8 +6,10 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from .helper import Helper, ModuleTestCase, RunCmdCall
import sys
from ansible_collections.community.general.plugins.modules import snap
from .helper import Helper, RunCommandMock # pylint: disable=unused-import
issue_6803_status_out = """Name Version Rev Tracking Publisher Notes
@ -375,100 +377,102 @@ issue_6803_kubectl_out = (
)
TEST_CASES = [
ModuleTestCase(
dict(
id="simple case",
input={"name": ["hello-world"]},
output=dict(changed=True, snaps_installed=["hello-world"]),
flags={},
run_command_calls=[
RunCmdCall(
command=['/testbin/snap', 'info', 'hello-world'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out='name: hello-world\n',
err="",
),
RunCmdCall(
command=['/testbin/snap', 'list'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out="",
err="",
),
RunCmdCall(
command=['/testbin/snap', 'install', 'hello-world'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out="hello-world (12345/stable) v12345 from Canonical** installed\n",
err="",
),
RunCmdCall(
command=['/testbin/snap', 'list'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out=(
"Name Version Rev Tracking Publisher Notes"
"core20 20220826 1623 latest/stable canonical** base"
"lxd 5.6-794016a 23680 latest/stable/… canonical** -"
"hello-world 5.6-794016a 23680 latest/stable/… canonical** -"
"snapd 2.57.4 17336 latest/stable canonical** snapd"
""),
err="",
),
]
mocks=dict(
run_command=[
dict(
command=['/testbin/snap', 'info', 'hello-world'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out='name: hello-world\n',
err="",
),
dict(
command=['/testbin/snap', 'list'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out="",
err="",
),
dict(
command=['/testbin/snap', 'install', 'hello-world'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out="hello-world (12345/stable) v12345 from Canonical** installed\n",
err="",
),
dict(
command=['/testbin/snap', 'list'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out=(
"Name Version Rev Tracking Publisher Notes"
"core20 20220826 1623 latest/stable canonical** base"
"lxd 5.6-794016a 23680 latest/stable/… canonical** -"
"hello-world 5.6-794016a 23680 latest/stable/… canonical** -"
"snapd 2.57.4 17336 latest/stable canonical** snapd"
""),
err="",
),
],
),
),
ModuleTestCase(
dict(
id="issue_6803",
input={"name": ["microk8s", "kubectl"], "classic": True},
output=dict(changed=True, snaps_installed=["microk8s", "kubectl"]),
flags={},
run_command_calls=[
RunCmdCall(
command=['/testbin/snap', 'info', 'microk8s', 'kubectl'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out='name: microk8s\n---\nname: kubectl\n',
err="",
),
RunCmdCall(
command=['/testbin/snap', 'list'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out=issue_6803_status_out,
err="",
),
RunCmdCall(
command=['/testbin/snap', 'install', '--classic', 'microk8s'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out=issue_6803_microk8s_out,
err="",
),
RunCmdCall(
command=['/testbin/snap', 'install', '--classic', 'kubectl'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out=issue_6803_kubectl_out,
err="",
),
RunCmdCall(
command=['/testbin/snap', 'list'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out=(
"Name Version Rev Tracking Publisher Notes"
"core20 20220826 1623 latest/stable canonical** base"
"lxd 5.6-794016a 23680 latest/stable/… canonical** -"
"microk8s 5.6-794016a 23680 latest/stable/… canonical** -"
"kubectl 5.6-794016a 23680 latest/stable/… canonical** -"
"snapd 2.57.4 17336 latest/stable canonical** snapd"
""),
err="",
),
]
mocks=dict(
run_command=[
dict(
command=['/testbin/snap', 'info', 'microk8s', 'kubectl'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out='name: microk8s\n---\nname: kubectl\n',
err="",
),
dict(
command=['/testbin/snap', 'list'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out=issue_6803_status_out,
err="",
),
dict(
command=['/testbin/snap', 'install', '--classic', 'microk8s'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out=issue_6803_microk8s_out,
err="",
),
dict(
command=['/testbin/snap', 'install', '--classic', 'kubectl'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out=issue_6803_kubectl_out,
err="",
),
dict(
command=['/testbin/snap', 'list'],
environ={'environ_update': {'LANGUAGE': 'C', 'LC_ALL': 'C'}, 'check_rc': False},
rc=0,
out=(
"Name Version Rev Tracking Publisher Notes"
"core20 20220826 1623 latest/stable canonical** base"
"lxd 5.6-794016a 23680 latest/stable/… canonical** -"
"microk8s 5.6-794016a 23680 latest/stable/… canonical** -"
"kubectl 5.6-794016a 23680 latest/stable/… canonical** -"
"snapd 2.57.4 17336 latest/stable canonical** snapd"
""),
err="",
),
],
),
),
]
helper = Helper.from_list(snap.main, TEST_CASES)
patch_bin = helper.cmd_fixture
test_module = helper.test_module
Helper.from_list(sys.modules[__name__], snap, TEST_CASES)

View File

@ -14,7 +14,7 @@ __metaclass__ = type
from ansible_collections.community.general.plugins.modules import xfconf
from .helper import Helper
from .helper import Helper, RunCommandMock # pylint: disable=unused-import
Helper.from_module(xfconf, __name__)

View File

@ -21,7 +21,8 @@
previous_value: '100'
type: int
value: '90'
run_command_calls:
mocks:
run_command:
- command: [/testbin/xfconf-query, --channel, xfwm4, --property, /general/inactive_opacity]
environ: &env-def {environ_update: {LANGUAGE: C, LC_ALL: C}, check_rc: false}
rc: 0
@ -44,7 +45,8 @@
previous_value: '90'
type: int
value: '90'
run_command_calls:
mocks:
run_command:
- command: [/testbin/xfconf-query, --channel, xfwm4, --property, /general/inactive_opacity]
environ: *env-def
rc: 0
@ -61,13 +63,14 @@
property: /general/SaveOnExit
state: present
value_type: bool
value: False
value: false
output:
changed: true
previous_value: 'true'
type: bool
value: 'False'
run_command_calls:
mocks:
run_command:
- command: [/testbin/xfconf-query, --channel, xfce4-session, --property, /general/SaveOnExit]
environ: *env-def
rc: 0
@ -90,32 +93,33 @@
previous_value: [Main, Work, Tmp]
type: [string, string, string]
value: [A, B, C]
run_command_calls:
mocks:
run_command:
- command: [/testbin/xfconf-query, --channel, xfwm4, --property, /general/workspace_names]
environ: *env-def
rc: 0
out: "Value is an array with 3 items:\n\nMain\nWork\nTmp\n"
err: ""
- command:
- /testbin/xfconf-query
- --channel
- xfwm4
- --property
- /general/workspace_names
- --create
- --force-array
- --type
- string
- --set
- A
- --type
- string
- --set
- B
- --type
- string
- --set
- C
- /testbin/xfconf-query
- --channel
- xfwm4
- --property
- /general/workspace_names
- --create
- --force-array
- --type
- string
- --set
- A
- --type
- string
- --set
- B
- --type
- string
- --set
- C
environ: *env-def
rc: 0
out: ""
@ -132,32 +136,33 @@
previous_value: [A, B, C]
type: [string, string, string]
value: [A, B, C]
run_command_calls:
mocks:
run_command:
- command: [/testbin/xfconf-query, --channel, xfwm4, --property, /general/workspace_names]
environ: *env-def
rc: 0
out: "Value is an array with 3 items:\n\nA\nB\nC\n"
err: ""
- command:
- /testbin/xfconf-query
- --channel
- xfwm4
- --property
- /general/workspace_names
- --create
- --force-array
- --type
- string
- --set
- A
- --type
- string
- --set
- B
- --type
- string
- --set
- C
- /testbin/xfconf-query
- --channel
- xfwm4
- --property
- /general/workspace_names
- --create
- --force-array
- --type
- string
- --set
- A
- --type
- string
- --set
- B
- --type
- string
- --set
- C
environ: *env-def
rc: 0
out: ""
@ -170,9 +175,10 @@
output:
changed: true
previous_value: [A, B, C]
type: null
value: null
run_command_calls:
type:
value:
mocks:
run_command:
- command: [/testbin/xfconf-query, --channel, xfwm4, --property, /general/workspace_names]
environ: *env-def
rc: 0

View File

@ -7,7 +7,7 @@ __metaclass__ = type
from ansible_collections.community.general.plugins.modules import xfconf_info
from .helper import Helper
from .helper import Helper, RunCommandMock # pylint: disable=unused-import
Helper.from_module(xfconf_info, __name__)

View File

@ -11,7 +11,8 @@
output:
value: '100'
is_array: false
run_command_calls:
mocks:
run_command:
- command: [/testbin/xfconf-query, --channel, xfwm4, --property, /general/inactive_opacity]
environ: &env-def {environ_update: {LANGUAGE: C, LC_ALL: C}, check_rc: true}
rc: 0
@ -22,7 +23,8 @@
channel: xfwm4
property: /general/i_dont_exist
output: {}
run_command_calls:
mocks:
run_command:
- command: [/testbin/xfconf-query, --channel, xfwm4, --property, /general/i_dont_exist]
environ: *env-def
rc: 1
@ -34,7 +36,8 @@
output:
failed: true
msg: "missing parameter(s) required by 'property': channel"
run_command_calls: []
mocks:
run_command: []
- id: test_property_get_array
input:
channel: xfwm4
@ -42,7 +45,8 @@
output:
is_array: true
value_array: [Main, Work, Tmp]
run_command_calls:
mocks:
run_command:
- command: [/testbin/xfconf-query, --channel, xfwm4, --property, /general/workspace_names]
environ: *env-def
rc: 0
@ -52,7 +56,8 @@
input: {}
output:
channels: [a, b, c]
run_command_calls:
mocks:
run_command:
- command: [/testbin/xfconf-query, --list]
environ: *env-def
rc: 0
@ -63,13 +68,14 @@
channel: xfwm4
output:
properties:
- /general/wrap_cycle
- /general/wrap_layout
- /general/wrap_resistance
- /general/wrap_windows
- /general/wrap_workspaces
- /general/zoom_desktop
run_command_calls:
- /general/wrap_cycle
- /general/wrap_layout
- /general/wrap_resistance
- /general/wrap_windows
- /general/wrap_workspaces
- /general/zoom_desktop
mocks:
run_command:
- command: [/testbin/xfconf-query, --list, --channel, xfwm4]
environ: *env-def
rc: 0