summaryrefslogtreecommitdiffstats
path: root/roles/lib_utils/src
diff options
context:
space:
mode:
Diffstat (limited to 'roles/lib_utils/src')
-rw-r--r--roles/lib_utils/src/ansible/repoquery.py1
-rw-r--r--roles/lib_utils/src/ansible/yedit.py24
-rw-r--r--roles/lib_utils/src/class/repoquery.py30
-rw-r--r--roles/lib_utils/src/class/yedit.py200
-rw-r--r--roles/lib_utils/src/doc/yedit16
-rw-r--r--roles/lib_utils/src/lib/import.py1
-rw-r--r--roles/lib_utils/src/test/integration/kube-manager-test.yaml.orig52
-rwxr-xr-xroles/lib_utils/src/test/integration/yedit.yml31
-rwxr-xr-xroles/lib_utils/src/test/unit/test_repoquery.py3
-rwxr-xr-xroles/lib_utils/src/test/unit/test_yedit.py86
10 files changed, 308 insertions, 136 deletions
diff --git a/roles/lib_utils/src/ansible/repoquery.py b/roles/lib_utils/src/ansible/repoquery.py
index cb4efa6c1..40773b1c1 100644
--- a/roles/lib_utils/src/ansible/repoquery.py
+++ b/roles/lib_utils/src/ansible/repoquery.py
@@ -18,6 +18,7 @@ def main():
verbose=dict(default=False, required=False, type='bool'),
show_duplicates=dict(default=False, required=False, type='bool'),
match_version=dict(default=None, required=False, type='str'),
+ ignore_excluders=dict(default=False, required=False, type='bool'),
),
supports_check_mode=False,
required_if=[('show_duplicates', True, ['name'])],
diff --git a/roles/lib_utils/src/ansible/yedit.py b/roles/lib_utils/src/ansible/yedit.py
index 8a1a7c2dc..c4b818cf1 100644
--- a/roles/lib_utils/src/ansible/yedit.py
+++ b/roles/lib_utils/src/ansible/yedit.py
@@ -26,12 +26,34 @@ def main():
type='str'),
backup=dict(default=True, type='bool'),
separator=dict(default='.', type='str'),
+ edits=dict(default=None, type='list'),
),
mutually_exclusive=[["curr_value", "index"], ['update', "append"]],
required_one_of=[["content", "src"]],
)
- rval = Yedit.run_ansible(module)
+ # Verify we recieved either a valid key or edits with valid keys when receiving a src file.
+ # A valid key being not None or not ''.
+ if module.params['src'] is not None:
+ key_error = False
+ edit_error = False
+
+ if module.params['key'] in [None, '']:
+ key_error = True
+
+ if module.params['edits'] in [None, []]:
+ edit_error = True
+
+ else:
+ for edit in module.params['edits']:
+ if edit.get('key') in [None, '']:
+ edit_error = True
+ break
+
+ if key_error and edit_error:
+ module.fail_json(failed=True, msg='Empty value for parameter key not allowed.')
+
+ rval = Yedit.run_ansible(module.params)
if 'failed' in rval and rval['failed']:
module.fail_json(**rval)
diff --git a/roles/lib_utils/src/class/repoquery.py b/roles/lib_utils/src/class/repoquery.py
index 82adcada5..e997780ad 100644
--- a/roles/lib_utils/src/class/repoquery.py
+++ b/roles/lib_utils/src/class/repoquery.py
@@ -5,15 +5,16 @@
class Repoquery(RepoqueryCLI):
''' Class to wrap the repoquery
'''
- # pylint: disable=too-many-arguments
+ # pylint: disable=too-many-arguments,too-many-instance-attributes
def __init__(self, name, query_type, show_duplicates,
- match_version, verbose):
+ match_version, ignore_excluders, verbose):
''' Constructor for YumList '''
super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.show_duplicates = show_duplicates
self.match_version = match_version
+ self.ignore_excluders = ignore_excluders
self.verbose = verbose
if self.match_version:
@@ -21,6 +22,8 @@ class Repoquery(RepoqueryCLI):
self.query_format = "%{version}|%{release}|%{arch}|%{repo}|%{version}-%{release}"
+ self.tmp_file = None
+
def build_cmd(self):
''' build the repoquery cmd options '''
@@ -32,6 +35,9 @@ class Repoquery(RepoqueryCLI):
if self.show_duplicates:
repo_cmd.append('--show-duplicates')
+ if self.ignore_excluders:
+ repo_cmd.append('--config=' + self.tmp_file.name)
+
repo_cmd.append(self.name)
return repo_cmd
@@ -42,7 +48,7 @@ class Repoquery(RepoqueryCLI):
version_dict = defaultdict(dict)
- for version in query_output.split('\n'):
+ for version in query_output.decode().split('\n'):
pkg_info = version.split("|")
pkg_version = {}
@@ -103,6 +109,20 @@ class Repoquery(RepoqueryCLI):
def repoquery(self):
'''perform a repoquery '''
+ if self.ignore_excluders:
+ # Duplicate yum.conf and reset exclude= line to an empty string
+ # to clear a list of all excluded packages
+ self.tmp_file = tempfile.NamedTemporaryFile()
+
+ with open("/etc/yum.conf", "r") as file_handler:
+ yum_conf_lines = file_handler.readlines()
+
+ yum_conf_lines = ["exclude=" if l.startswith("exclude=") else l for l in yum_conf_lines]
+
+ with open(self.tmp_file.name, "w") as file_handler:
+ file_handler.writelines(yum_conf_lines)
+ file_handler.flush()
+
repoquery_cmd = self.build_cmd()
rval = self._repoquery_cmd(repoquery_cmd, True, 'raw')
@@ -125,6 +145,9 @@ class Repoquery(RepoqueryCLI):
else:
rval['package_found'] = False
+ if self.ignore_excluders:
+ self.tmp_file.close()
+
return rval
@staticmethod
@@ -136,6 +159,7 @@ class Repoquery(RepoqueryCLI):
params['query_type'],
params['show_duplicates'],
params['match_version'],
+ params['ignore_excluders'],
params['verbose'],
)
diff --git a/roles/lib_utils/src/class/yedit.py b/roles/lib_utils/src/class/yedit.py
index 533665db2..957c35a06 100644
--- a/roles/lib_utils/src/class/yedit.py
+++ b/roles/lib_utils/src/class/yedit.py
@@ -1,6 +1,5 @@
# flake8: noqa
-# pylint: disable=undefined-variable,missing-docstring
-# noqa: E301,E302
+# pylint: skip-file
class YeditException(Exception):
@@ -12,7 +11,7 @@ class YeditException(Exception):
class Yedit(object):
''' Class to modify yaml files '''
re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
- re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
+ re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z{}/_-]+)"
com_sep = set(['.', '#', '|', ':'])
# pylint: disable=too-many-arguments
@@ -34,13 +33,13 @@ class Yedit(object):
@property
def separator(self):
- ''' getter method for yaml_dict '''
+ ''' getter method for separator '''
return self._separator
@separator.setter
- def separator(self):
- ''' getter method for yaml_dict '''
- return self._separator
+ def separator(self, inc_sep):
+ ''' setter method for separator '''
+ self._separator = inc_sep
@property
def yaml_dict(self):
@@ -56,13 +55,13 @@ class Yedit(object):
def parse_key(key, sep='.'):
'''parse the key allowing the appropriate separator'''
common_separators = list(Yedit.com_sep - set([sep]))
- return re.findall(Yedit.re_key % ''.join(common_separators), key)
+ return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
@staticmethod
def valid_key(key, sep='.'):
'''validate the incoming key'''
common_separators = list(Yedit.com_sep - set([sep]))
- if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
+ if not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key):
return False
return True
@@ -84,7 +83,7 @@ class Yedit(object):
key_indexes = Yedit.parse_key(key, sep)
for arr_ind, dict_key in key_indexes[:-1]:
if dict_key and isinstance(data, dict):
- data = data.get(dict_key, None)
+ data = data.get(dict_key)
elif (arr_ind and isinstance(data, list) and
int(arr_ind) <= len(data) - 1):
data = data[int(arr_ind)]
@@ -173,7 +172,7 @@ class Yedit(object):
key_indexes = Yedit.parse_key(key, sep)
for arr_ind, dict_key in key_indexes:
if dict_key and isinstance(data, dict):
- data = data.get(dict_key, None)
+ data = data.get(dict_key)
elif (arr_ind and isinstance(data, list) and
int(arr_ind) <= len(data) - 1):
data = data[int(arr_ind)]
@@ -273,7 +272,7 @@ class Yedit(object):
self.yaml_dict = json.loads(contents)
except yaml.YAMLError as err:
# Error loading yaml or json
- raise YeditException('Problem with loading yaml file. %s' % err)
+ raise YeditException('Problem with loading yaml file. {}'.format(err))
return self.yaml_dict
@@ -392,8 +391,8 @@ class Yedit(object):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
if not isinstance(value, dict):
- raise YeditException('Cannot replace key, value entry in ' +
- 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
+ raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' +
+ 'value=[{}] type=[{}]'.format(value, type(value)))
entry.update(value)
return (True, self.yaml_dict)
@@ -454,7 +453,17 @@ class Yedit(object):
pass
result = Yedit.add_entry(tmp_copy, path, value, self.separator)
- if not result:
+ if result is None:
+ return (False, self.yaml_dict)
+
+ # When path equals "" it is a special case.
+ # "" refers to the root of the document
+ # Only update the root path (entire document) when its a list or dict
+ if path == '':
+ if isinstance(result, list) or isinstance(result, dict):
+ self.yaml_dict = result
+ return (True, self.yaml_dict)
+
return (False, self.yaml_dict)
self.yaml_dict = tmp_copy
@@ -480,7 +489,7 @@ class Yedit(object):
pass
result = Yedit.add_entry(tmp_copy, path, value, self.separator)
- if result:
+ if result is not None:
self.yaml_dict = tmp_copy
return (True, self.yaml_dict)
@@ -512,112 +521,147 @@ class Yedit(object):
# we will convert to bool if it matches any of the above cases
if isinstance(inc_value, str) and 'bool' in vtype:
if inc_value not in true_bools and inc_value not in false_bools:
- raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
- % (inc_value, vtype))
+ raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype))
elif isinstance(inc_value, bool) and 'str' in vtype:
inc_value = str(inc_value)
+ # There is a special case where '' will turn into None after yaml loading it so skip
+ if isinstance(inc_value, str) and inc_value == '':
+ pass
# If vtype is not str then go ahead and attempt to yaml load it.
- if isinstance(inc_value, str) and 'str' not in vtype:
+ elif isinstance(inc_value, str) and 'str' not in vtype:
try:
- inc_value = yaml.load(inc_value)
+ inc_value = yaml.safe_load(inc_value)
except Exception:
- raise YeditException('Could not determine type of incoming ' +
- 'value. value=[%s] vtype=[%s]'
- % (type(inc_value), vtype))
+ raise YeditException('Could not determine type of incoming value. ' +
+ 'value=[{}] vtype=[{}]'.format(type(inc_value), vtype))
return inc_value
+ @staticmethod
+ def process_edits(edits, yamlfile):
+ '''run through a list of edits and process them one-by-one'''
+ results = []
+ for edit in edits:
+ value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
+ if edit.get('action') == 'update':
+ # pylint: disable=line-too-long
+ curr_value = Yedit.get_curr_value(
+ Yedit.parse_value(edit.get('curr_value')),
+ edit.get('curr_value_format'))
+
+ rval = yamlfile.update(edit['key'],
+ value,
+ edit.get('index'),
+ curr_value)
+
+ elif edit.get('action') == 'append':
+ rval = yamlfile.append(edit['key'], value)
+
+ else:
+ rval = yamlfile.put(edit['key'], value)
+
+ if rval[0]:
+ results.append({'key': edit['key'], 'edit': rval[1]})
+
+ return {'changed': len(results) > 0, 'results': results}
+
# pylint: disable=too-many-return-statements,too-many-branches
@staticmethod
- def run_ansible(module):
+ def run_ansible(params):
'''perform the idempotent crud operations'''
- yamlfile = Yedit(filename=module.params['src'],
- backup=module.params['backup'],
- separator=module.params['separator'])
+ yamlfile = Yedit(filename=params['src'],
+ backup=params['backup'],
+ separator=params['separator'])
+
+ state = params['state']
- if module.params['src']:
+ if params['src']:
rval = yamlfile.load()
- if yamlfile.yaml_dict is None and \
- module.params['state'] != 'present':
+ if yamlfile.yaml_dict is None and state != 'present':
return {'failed': True,
- 'msg': 'Error opening file [%s]. Verify that the ' +
- 'file exists, that it is has correct' +
- ' permissions, and is valid yaml.'}
-
- if module.params['state'] == 'list':
- if module.params['content']:
- content = Yedit.parse_value(module.params['content'],
- module.params['content_type'])
+ 'msg': 'Error opening file [{}]. Verify that the '.format(params['src']) +
+ 'file exists, that it is has correct permissions, and is valid yaml.'}
+
+ if state == 'list':
+ if params['content']:
+ content = Yedit.parse_value(params['content'], params['content_type'])
yamlfile.yaml_dict = content
- if module.params['key']:
- rval = yamlfile.get(module.params['key']) or {}
+ if params['key']:
+ rval = yamlfile.get(params['key']) or {}
- return {'changed': False, 'result': rval, 'state': "list"}
+ return {'changed': False, 'result': rval, 'state': state}
- elif module.params['state'] == 'absent':
- if module.params['content']:
- content = Yedit.parse_value(module.params['content'],
- module.params['content_type'])
+ elif state == 'absent':
+ if params['content']:
+ content = Yedit.parse_value(params['content'], params['content_type'])
yamlfile.yaml_dict = content
- if module.params['update']:
- rval = yamlfile.pop(module.params['key'],
- module.params['value'])
+ if params['update']:
+ rval = yamlfile.pop(params['key'], params['value'])
else:
- rval = yamlfile.delete(module.params['key'])
+ rval = yamlfile.delete(params['key'])
- if rval[0] and module.params['src']:
+ if rval[0] and params['src']:
yamlfile.write()
- return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
+ return {'changed': rval[0], 'result': rval[1], 'state': state}
- elif module.params['state'] == 'present':
+ elif state == 'present':
# check if content is different than what is in the file
- if module.params['content']:
- content = Yedit.parse_value(module.params['content'],
- module.params['content_type'])
+ if params['content']:
+ content = Yedit.parse_value(params['content'], params['content_type'])
# We had no edits to make and the contents are the same
if yamlfile.yaml_dict == content and \
- module.params['value'] is None:
- return {'changed': False,
- 'result': yamlfile.yaml_dict,
- 'state': "present"}
+ params['value'] is None:
+ return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
yamlfile.yaml_dict = content
- # we were passed a value; parse it
- if module.params['value']:
- value = Yedit.parse_value(module.params['value'],
- module.params['value_type'])
- key = module.params['key']
- if module.params['update']:
- # pylint: disable=line-too-long
- curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
- module.params['curr_value_format']) # noqa: E501
+ # If we were passed a key, value then
+ # we enapsulate it in a list and process it
+ # Key, Value passed to the module : Converted to Edits list #
+ edits = []
+ _edit = {}
+ if params['value'] is not None:
+ _edit['value'] = params['value']
+ _edit['value_type'] = params['value_type']
+ _edit['key'] = params['key']
- rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
+ if params['update']:
+ _edit['action'] = 'update'
+ _edit['curr_value'] = params['curr_value']
+ _edit['curr_value_format'] = params['curr_value_format']
+ _edit['index'] = params['index']
- elif module.params['append']:
- rval = yamlfile.append(key, value)
- else:
- rval = yamlfile.put(key, value)
+ elif params['append']:
+ _edit['action'] = 'append'
+
+ edits.append(_edit)
+
+ elif params['edits'] is not None:
+ edits = params['edits']
- if rval[0] and module.params['src']:
+ if edits:
+ results = Yedit.process_edits(edits, yamlfile)
+
+ # if there were changes and a src provided to us we need to write
+ if results['changed'] and params['src']:
yamlfile.write()
- return {'changed': rval[0],
- 'result': rval[1], 'state': "present"}
+ return {'changed': results['changed'], 'result': results['results'], 'state': state}
# no edits to make
- if module.params['src']:
+ if params['src']:
# pylint: disable=redefined-variable-type
rval = yamlfile.write()
return {'changed': rval[0],
'result': rval[1],
- 'state': "present"}
+ 'state': state}
+ # We were passed content but no src, key or value, or edits. Return contents in memory
+ return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
return {'failed': True, 'msg': 'Unkown state passed'}
diff --git a/roles/lib_utils/src/doc/yedit b/roles/lib_utils/src/doc/yedit
index 16b44943e..82af1f675 100644
--- a/roles/lib_utils/src/doc/yedit
+++ b/roles/lib_utils/src/doc/yedit
@@ -135,4 +135,20 @@ EXAMPLES = '''
# a:
# b:
# c: d
+#
+# multiple edits at the same time
+- name: perform multiple edits
+ yedit:
+ src: somefile.yml
+ edits:
+ - key: a#b#c
+ value: d
+ - key: a#b#c#d
+ value: e
+ state: present
+# Results:
+# a:
+# b:
+# c:
+# d: e
'''
diff --git a/roles/lib_utils/src/lib/import.py b/roles/lib_utils/src/lib/import.py
index b0ab7c92c..567f8c9e0 100644
--- a/roles/lib_utils/src/lib/import.py
+++ b/roles/lib_utils/src/lib/import.py
@@ -9,6 +9,7 @@ import json # noqa: F401
import os # noqa: F401
import re # noqa: F401
import shutil # noqa: F401
+import tempfile # noqa: F401
try:
import ruamel.yaml as yaml # noqa: F401
diff --git a/roles/lib_utils/src/test/integration/kube-manager-test.yaml.orig b/roles/lib_utils/src/test/integration/kube-manager-test.yaml.orig
deleted file mode 100644
index 5541c3dae..000000000
--- a/roles/lib_utils/src/test/integration/kube-manager-test.yaml.orig
+++ /dev/null
@@ -1,52 +0,0 @@
-apiVersion: v1
-kind: Pod
-metadata:
- name: kube-controller-manager
- namespace: kube-system
-spec:
- hostNetwork: true
- containers:
- - name: kube-controller-manager
- image: openshift/kube:v1.0.0
- command:
- - /hyperkube
- - controller-manager
- - --master=http://127.0.0.1:8080
- - --leader-elect=true
- - --service-account-private-key-file=/etc/kubernetes/ssl/apiserver-key.pem
- - --root-ca-file=/etc/k8s/ssl/my.pem
- - --my-new-parameter=openshift
- livenessProbe:
- httpGet:
- host: 127.0.0.1
- path: /healthz
- port: 10252
- initialDelaySeconds: 15
- timeoutSeconds: 1
- volumeMounts:
- - mountPath: /etc/kubernetes/ssl
- name: ssl-certs-kubernetes
- readOnly: true
- - mountPath: /etc/ssl/certs
- name: ssl-certs-host
- readOnly: 'true'
- volumes:
- - hostPath:
- path: /etc/kubernetes/ssl
- name: ssl-certs-kubernetes
- - hostPath:
- path: /usr/share/ca-certificates
- name: ssl-certs-host
-yedittest: yedittest
-metadata-namespace: openshift-is-awesome
-nonexistingkey:
-- --my-new-parameter=openshift
-a:
- b:
- c: d
-e:
- f:
- g:
- h:
- i:
- j: k
diff --git a/roles/lib_utils/src/test/integration/yedit.yml b/roles/lib_utils/src/test/integration/yedit.yml
index e3dfd490b..65209bade 100755
--- a/roles/lib_utils/src/test/integration/yedit.yml
+++ b/roles/lib_utils/src/test/integration/yedit.yml
@@ -219,4 +219,33 @@
assert:
that: results.result == [1, 2, 3]
msg: "Test: '[1, 2, 3]' != [{{ results.result }}]"
-###### end test create list value #####
+ ###### end test create list value #####
+
+ ###### test create multiple list value #####
+ - name: test multiple edits
+ yedit:
+ src: "{{ test_file }}"
+ edits:
+ - key: z.x.y
+ value:
+ - 1
+ - 2
+ - 3
+ - key: z.x.y
+ value: 4
+ action: append
+
+ - name: retrieve the key
+ yedit:
+ src: "{{ test_file }}"
+ state: list
+ key: z#x#y
+ separator: '#'
+ register: results
+ - debug: var=results
+
+ - name: Assert that the key was created
+ assert:
+ that: results.result == [1, 2, 3, 4]
+ msg: "Test: '[1, 2, 3, 4]' != [{{ results.result }}]"
+ ###### end test create multiple list value #####
diff --git a/roles/lib_utils/src/test/unit/test_repoquery.py b/roles/lib_utils/src/test/unit/test_repoquery.py
index e39d9d83f..325f41dab 100755
--- a/roles/lib_utils/src/test/unit/test_repoquery.py
+++ b/roles/lib_utils/src/test/unit/test_repoquery.py
@@ -37,6 +37,7 @@ class RepoQueryTest(unittest.TestCase):
'verbose': False,
'show_duplicates': False,
'match_version': None,
+ 'ignore_excluders': False,
}
valid_stderr = '''Repo rhel-7-server-extras-rpms forced skip_if_unavailable=True due to: /etc/pki/entitlement/3268107132875399464-key.pem
@@ -44,7 +45,7 @@ class RepoQueryTest(unittest.TestCase):
# Return values of our mocked function call. These get returned once per call.
mock_cmd.side_effect = [
- (0, '4.2.46|21.el7_3|x86_64|rhel-7-server-rpms|4.2.46-21.el7_3', valid_stderr), # first call to the mock
+ (0, b'4.2.46|21.el7_3|x86_64|rhel-7-server-rpms|4.2.46-21.el7_3', valid_stderr), # first call to the mock
]
# Act
diff --git a/roles/lib_utils/src/test/unit/test_yedit.py b/roles/lib_utils/src/test/unit/test_yedit.py
index 23a3f7353..f9f42843a 100755
--- a/roles/lib_utils/src/test/unit/test_yedit.py
+++ b/roles/lib_utils/src/test/unit/test_yedit.py
@@ -5,6 +5,7 @@
import os
import sys
import unittest
+import mock
# Removing invalid variable names for tests so that I can
# keep them brief
@@ -277,6 +278,91 @@ class YeditTest(unittest.TestCase):
with self.assertRaises(YeditException):
yed.put('new.stuff.here[0]', 'item')
+ def test_empty_key_with_int_value(self):
+ '''test editing top level with not list or dict'''
+ yed = Yedit(content={'a': {'b': 12}})
+ result = yed.put('', 'b')
+ self.assertFalse(result[0])
+
+ def test_setting_separator(self):
+ '''test editing top level with not list or dict'''
+ yed = Yedit(content={'a': {'b': 12}})
+ yed.separator = ':'
+ self.assertEqual(yed.separator, ':')
+
+ def test_remove_all(self):
+ '''test removing all data'''
+ data = Yedit.remove_entry({'a': {'b': 12}}, '')
+ self.assertTrue(data)
+
+ def test_remove_list_entry(self):
+ '''test removing list entry'''
+ data = {'a': {'b': [{'c': 3}]}}
+ results = Yedit.remove_entry(data, 'a.b[0]')
+ self.assertTrue(results)
+ self.assertTrue(data, {'a': {'b': []}})
+
+ def test_parse_value_string_true(self):
+ '''test parse_value'''
+ results = Yedit.parse_value('true', 'str')
+ self.assertEqual(results, 'true')
+
+ def test_parse_value_bool_true(self):
+ '''test parse_value'''
+ results = Yedit.parse_value('true', 'bool')
+ self.assertTrue(results)
+
+ def test_parse_value_bool_exception(self):
+ '''test parse_value'''
+ with self.assertRaises(YeditException):
+ Yedit.parse_value('TTT', 'bool')
+
+ @mock.patch('yedit.Yedit.write')
+ def test_run_ansible_basic(self, mock_write):
+ '''test parse_value'''
+ params = {
+ 'src': None,
+ 'backup': False,
+ 'separator': '.',
+ 'state': 'present',
+ 'edits': [],
+ 'value': None,
+ 'key': None,
+ 'content': {'a': {'b': {'c': 1}}},
+ 'content_type': '',
+ }
+
+ results = Yedit.run_ansible(params)
+
+ mock_write.side_effect = [
+ (True, params['content']),
+ ]
+
+ self.assertFalse(results['changed'])
+
+ @mock.patch('yedit.Yedit.write')
+ def test_run_ansible_and_write(self, mock_write):
+ '''test parse_value'''
+ params = {
+ 'src': '/tmp/test',
+ 'backup': False,
+ 'separator': '.',
+ 'state': 'present',
+ 'edits': [],
+ 'value': None,
+ 'key': None,
+ 'content': {'a': {'b': {'c': 1}}},
+ 'content_type': '',
+ }
+
+ results = Yedit.run_ansible(params)
+
+ mock_write.side_effect = [
+ (True, params['content']),
+ ]
+
+ self.assertTrue(results['changed'])
+
def tearDown(self):
'''TearDown method'''
os.unlink(YeditTest.filename)