Unit tests: share common code (#31456)

* move set_module_args to units.modules.utils
* unit tests: reuse set_module_args
* unit tests: mock exit/fail_json in module.utils.ModuleTestCase
* unit tests: use module.utils.ModuleTestCase
* unit tests: fix 'import shadowed by loop variable'
This commit is contained in:
Pilou 2017-11-17 18:17:07 +01:00 committed by Matt Clay
commit a5c9726502
154 changed files with 671 additions and 1113 deletions

View file

@ -20,21 +20,13 @@ from __future__ import (absolute_import, division, print_function)
import os
import json
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch
from ansible.module_utils import basic
from ansible.module_utils._text import to_bytes
from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
def set_module_args(args):
args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
basic._ANSIBLE_ARGS = to_bytes(args)
def load_fixture(name):
path = os.path.join(fixture_path, name)
if path not in fixture_data:
@ -80,15 +72,7 @@ def mock_call(calls, url, data=None, headers=None, method=None):
return result
class AnsibleExitJson(Exception):
pass
class AnsibleFailJson(Exception):
pass
class TestNsoModule(unittest.TestCase):
class TestNsoModule(ModuleTestCase):
def execute_module(self, failed=False, changed=False, **kwargs):
if failed:
@ -104,27 +88,16 @@ class TestNsoModule(unittest.TestCase):
return result
def failed(self):
def fail_json(*args, **kwargs):
kwargs['failed'] = True
raise AnsibleFailJson(kwargs)
with patch.object(basic.AnsibleModule, 'fail_json', fail_json):
with self.assertRaises(AnsibleFailJson) as exc:
self.module.main()
with self.assertRaises(AnsibleFailJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertTrue(result['failed'], result)
return result
def changed(self, changed=False):
def exit_json(*args, **kwargs):
if 'changed' not in kwargs:
kwargs['changed'] = False
raise AnsibleExitJson(kwargs)
with patch.object(basic.AnsibleModule, 'exit_json', exit_json):
with self.assertRaises(AnsibleExitJson) as exc:
self.module.main()
with self.assertRaises(AnsibleExitJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertEqual(result['changed'], changed, result)