summaryrefslogtreecommitdiffstats
path: root/roles/lib_openshift
diff options
context:
space:
mode:
Diffstat (limited to 'roles/lib_openshift')
-rw-r--r--roles/lib_openshift/library/oadm_manage_node.py67
-rw-r--r--roles/lib_openshift/library/oc_edit.py67
-rw-r--r--roles/lib_openshift/library/oc_label.py69
-rw-r--r--roles/lib_openshift/library/oc_obj.py69
-rw-r--r--roles/lib_openshift/library/oc_route.py67
-rw-r--r--roles/lib_openshift/library/oc_scale.py67
-rw-r--r--roles/lib_openshift/library/oc_secret.py75
-rw-r--r--roles/lib_openshift/library/oc_service.py67
-rw-r--r--roles/lib_openshift/library/oc_serviceaccount.py67
-rw-r--r--roles/lib_openshift/library/oc_serviceaccount_secret.py67
-rw-r--r--roles/lib_openshift/library/oc_version.py67
-rw-r--r--roles/lib_openshift/src/ansible/oc_label.py2
-rw-r--r--roles/lib_openshift/src/class/oc_obj.py2
-rw-r--r--roles/lib_openshift/src/class/oc_secret.py8
-rw-r--r--roles/lib_openshift/src/lib/base.py66
-rw-r--r--roles/lib_openshift/src/lib/import.py1
-rwxr-xr-xroles/lib_openshift/src/test/generate-and-run-tests.sh54
-rwxr-xr-xroles/lib_openshift/src/test/integration/oadm_manage_node.yml27
-rwxr-xr-xroles/lib_openshift/src/test/integration/oc_label.yml59
-rwxr-xr-xroles/lib_openshift/src/test/integration/oc_service.yml2
-rwxr-xr-xroles/lib_openshift/src/test/unit/oadm_manage_node.py15
-rwxr-xr-xroles/lib_openshift/src/test/unit/oc_label.py14
-rwxr-xr-xroles/lib_openshift/src/test/unit/oc_scale.py21
-rwxr-xr-xroles/lib_openshift/src/test/unit/oc_secret.py38
-rwxr-xr-xroles/lib_openshift/src/test/unit/oc_service.py14
-rwxr-xr-xroles/lib_openshift/src/test/unit/oc_serviceaccount.py7
-rwxr-xr-xroles/lib_openshift/src/test/unit/oc_serviceaccount_secret.py24
-rwxr-xr-xroles/lib_openshift/src/test/unit/oc_version.py7
28 files changed, 813 insertions, 297 deletions
diff --git a/roles/lib_openshift/library/oadm_manage_node.py b/roles/lib_openshift/library/oadm_manage_node.py
index 93c52e0df..8e217ac28 100644
--- a/roles/lib_openshift/library/oadm_manage_node.py
+++ b/roles/lib_openshift/library/oadm_manage_node.py
@@ -38,6 +38,7 @@ import os
import re
import shutil
import subprocess
+import tempfile
# pylint: disable=import-error
import ruamel.yaml as yaml
from ansible.module_utils.basic import AnsibleModule
@@ -730,7 +731,7 @@ class OpenShiftCLI(object):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
- self.kubeconfig = kubeconfig
+ self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
# Pylint allows only 5 arguments to be passed.
@@ -741,7 +742,8 @@ class OpenShiftCLI(object):
if not res['results']:
return res
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
+
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
@@ -765,7 +767,7 @@ class OpenShiftCLI(object):
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
@@ -808,7 +810,7 @@ class OpenShiftCLI(object):
if results['returncode'] != 0 or not create:
return results
- fname = '/tmp/%s' % template_name
+ fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
@@ -989,32 +991,61 @@ class OpenShiftCLI(object):
class Utils(object):
''' utilities for openshiftcli modules '''
+
@staticmethod
- def create_file(rname, data, ftype='yaml'):
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ with open(filename, 'w') as sfd:
+ sfd.write(contents)
+
+ @staticmethod
+ def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
- path = os.path.join('/tmp', rname)
- with open(path, 'w') as fds:
- if ftype == 'yaml':
- fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
- elif ftype == 'json':
- fds.write(json.dumps(data))
- else:
- fds.write(data)
+ tmp = Utils.create_tmpfile(prefix=rname)
+
+ if ftype == 'yaml':
+ Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
+ elif ftype == 'json':
+ Utils._write(tmp, json.dumps(data))
+ else:
+ Utils._write(tmp, data)
# Register cleanup when module is done
- atexit.register(Utils.cleanup, [path])
- return path
+ atexit.register(Utils.cleanup, [tmp])
+ return tmp
+
+ @staticmethod
+ def create_tmpfile_copy(inc_file):
+ '''create a temporary copy of a file'''
+ tmpfile = Utils.create_tmpfile('lib_openshift-')
+ Utils._write(tmpfile, open(inc_file).read())
+
+ # Cleanup the tmpfile
+ atexit.register(Utils.cleanup, [tmpfile])
+
+ return tmpfile
+
+ @staticmethod
+ def create_tmpfile(prefix='tmp'):
+ ''' Generates and returns a temporary file name '''
+
+ with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
+ return tmp.name
@staticmethod
- def create_files_from_contents(content, content_type=None):
+ def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
- path = Utils.create_file(item['path'], item['data'], ftype=content_type)
- files.append({'name': os.path.basename(path), 'path': path})
+ path = Utils.create_tmp_file_from_contents(item['path'] + '-',
+ item['data'],
+ ftype=content_type)
+ files.append({'name': os.path.basename(item['path']),
+ 'path': path})
return files
@staticmethod
diff --git a/roles/lib_openshift/library/oc_edit.py b/roles/lib_openshift/library/oc_edit.py
index e9011da42..11b87a015 100644
--- a/roles/lib_openshift/library/oc_edit.py
+++ b/roles/lib_openshift/library/oc_edit.py
@@ -38,6 +38,7 @@ import os
import re
import shutil
import subprocess
+import tempfile
# pylint: disable=import-error
import ruamel.yaml as yaml
from ansible.module_utils.basic import AnsibleModule
@@ -758,7 +759,7 @@ class OpenShiftCLI(object):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
- self.kubeconfig = kubeconfig
+ self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
# Pylint allows only 5 arguments to be passed.
@@ -769,7 +770,8 @@ class OpenShiftCLI(object):
if not res['results']:
return res
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
+
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
@@ -793,7 +795,7 @@ class OpenShiftCLI(object):
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
@@ -836,7 +838,7 @@ class OpenShiftCLI(object):
if results['returncode'] != 0 or not create:
return results
- fname = '/tmp/%s' % template_name
+ fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
@@ -1017,32 +1019,61 @@ class OpenShiftCLI(object):
class Utils(object):
''' utilities for openshiftcli modules '''
+
@staticmethod
- def create_file(rname, data, ftype='yaml'):
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ with open(filename, 'w') as sfd:
+ sfd.write(contents)
+
+ @staticmethod
+ def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
- path = os.path.join('/tmp', rname)
- with open(path, 'w') as fds:
- if ftype == 'yaml':
- fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
- elif ftype == 'json':
- fds.write(json.dumps(data))
- else:
- fds.write(data)
+ tmp = Utils.create_tmpfile(prefix=rname)
+
+ if ftype == 'yaml':
+ Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
+ elif ftype == 'json':
+ Utils._write(tmp, json.dumps(data))
+ else:
+ Utils._write(tmp, data)
# Register cleanup when module is done
- atexit.register(Utils.cleanup, [path])
- return path
+ atexit.register(Utils.cleanup, [tmp])
+ return tmp
+
+ @staticmethod
+ def create_tmpfile_copy(inc_file):
+ '''create a temporary copy of a file'''
+ tmpfile = Utils.create_tmpfile('lib_openshift-')
+ Utils._write(tmpfile, open(inc_file).read())
+
+ # Cleanup the tmpfile
+ atexit.register(Utils.cleanup, [tmpfile])
+
+ return tmpfile
+
+ @staticmethod
+ def create_tmpfile(prefix='tmp'):
+ ''' Generates and returns a temporary file name '''
+
+ with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
+ return tmp.name
@staticmethod
- def create_files_from_contents(content, content_type=None):
+ def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
- path = Utils.create_file(item['path'], item['data'], ftype=content_type)
- files.append({'name': os.path.basename(path), 'path': path})
+ path = Utils.create_tmp_file_from_contents(item['path'] + '-',
+ item['data'],
+ ftype=content_type)
+ files.append({'name': os.path.basename(item['path']),
+ 'path': path})
return files
@staticmethod
diff --git a/roles/lib_openshift/library/oc_label.py b/roles/lib_openshift/library/oc_label.py
index f2f5787f5..f67eb2552 100644
--- a/roles/lib_openshift/library/oc_label.py
+++ b/roles/lib_openshift/library/oc_label.py
@@ -38,6 +38,7 @@ import os
import re
import shutil
import subprocess
+import tempfile
# pylint: disable=import-error
import ruamel.yaml as yaml
from ansible.module_utils.basic import AnsibleModule
@@ -734,7 +735,7 @@ class OpenShiftCLI(object):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
- self.kubeconfig = kubeconfig
+ self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
# Pylint allows only 5 arguments to be passed.
@@ -745,7 +746,8 @@ class OpenShiftCLI(object):
if not res['results']:
return res
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
+
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
@@ -769,7 +771,7 @@ class OpenShiftCLI(object):
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
@@ -812,7 +814,7 @@ class OpenShiftCLI(object):
if results['returncode'] != 0 or not create:
return results
- fname = '/tmp/%s' % template_name
+ fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
@@ -993,32 +995,61 @@ class OpenShiftCLI(object):
class Utils(object):
''' utilities for openshiftcli modules '''
+
@staticmethod
- def create_file(rname, data, ftype='yaml'):
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ with open(filename, 'w') as sfd:
+ sfd.write(contents)
+
+ @staticmethod
+ def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
- path = os.path.join('/tmp', rname)
- with open(path, 'w') as fds:
- if ftype == 'yaml':
- fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
- elif ftype == 'json':
- fds.write(json.dumps(data))
- else:
- fds.write(data)
+ tmp = Utils.create_tmpfile(prefix=rname)
+
+ if ftype == 'yaml':
+ Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
+ elif ftype == 'json':
+ Utils._write(tmp, json.dumps(data))
+ else:
+ Utils._write(tmp, data)
# Register cleanup when module is done
- atexit.register(Utils.cleanup, [path])
- return path
+ atexit.register(Utils.cleanup, [tmp])
+ return tmp
+
+ @staticmethod
+ def create_tmpfile_copy(inc_file):
+ '''create a temporary copy of a file'''
+ tmpfile = Utils.create_tmpfile('lib_openshift-')
+ Utils._write(tmpfile, open(inc_file).read())
+
+ # Cleanup the tmpfile
+ atexit.register(Utils.cleanup, [tmpfile])
+
+ return tmpfile
+
+ @staticmethod
+ def create_tmpfile(prefix='tmp'):
+ ''' Generates and returns a temporary file name '''
+
+ with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
+ return tmp.name
@staticmethod
- def create_files_from_contents(content, content_type=None):
+ def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
- path = Utils.create_file(item['path'], item['data'], ftype=content_type)
- files.append({'name': os.path.basename(path), 'path': path})
+ path = Utils.create_tmp_file_from_contents(item['path'] + '-',
+ item['data'],
+ ftype=content_type)
+ files.append({'name': os.path.basename(item['path']),
+ 'path': path})
return files
@staticmethod
@@ -1552,7 +1583,7 @@ def main():
state=dict(default='present', type='str',
choices=['present', 'absent', 'list', 'add']),
debug=dict(default=False, type='bool'),
- kind=dict(default='node', type='str', required=True,
+ kind=dict(default='node', type='str',
choices=['node', 'pod', 'namespace']),
name=dict(default=None, type='str'),
namespace=dict(default=None, type='str'),
diff --git a/roles/lib_openshift/library/oc_obj.py b/roles/lib_openshift/library/oc_obj.py
index c55827c47..e4b8ac26c 100644
--- a/roles/lib_openshift/library/oc_obj.py
+++ b/roles/lib_openshift/library/oc_obj.py
@@ -38,6 +38,7 @@ import os
import re
import shutil
import subprocess
+import tempfile
# pylint: disable=import-error
import ruamel.yaml as yaml
from ansible.module_utils.basic import AnsibleModule
@@ -737,7 +738,7 @@ class OpenShiftCLI(object):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
- self.kubeconfig = kubeconfig
+ self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
# Pylint allows only 5 arguments to be passed.
@@ -748,7 +749,8 @@ class OpenShiftCLI(object):
if not res['results']:
return res
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
+
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
@@ -772,7 +774,7 @@ class OpenShiftCLI(object):
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
@@ -815,7 +817,7 @@ class OpenShiftCLI(object):
if results['returncode'] != 0 or not create:
return results
- fname = '/tmp/%s' % template_name
+ fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
@@ -996,32 +998,61 @@ class OpenShiftCLI(object):
class Utils(object):
''' utilities for openshiftcli modules '''
+
@staticmethod
- def create_file(rname, data, ftype='yaml'):
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ with open(filename, 'w') as sfd:
+ sfd.write(contents)
+
+ @staticmethod
+ def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
- path = os.path.join('/tmp', rname)
- with open(path, 'w') as fds:
- if ftype == 'yaml':
- fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
- elif ftype == 'json':
- fds.write(json.dumps(data))
- else:
- fds.write(data)
+ tmp = Utils.create_tmpfile(prefix=rname)
+
+ if ftype == 'yaml':
+ Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
+ elif ftype == 'json':
+ Utils._write(tmp, json.dumps(data))
+ else:
+ Utils._write(tmp, data)
# Register cleanup when module is done
- atexit.register(Utils.cleanup, [path])
- return path
+ atexit.register(Utils.cleanup, [tmp])
+ return tmp
+
+ @staticmethod
+ def create_tmpfile_copy(inc_file):
+ '''create a temporary copy of a file'''
+ tmpfile = Utils.create_tmpfile('lib_openshift-')
+ Utils._write(tmpfile, open(inc_file).read())
+
+ # Cleanup the tmpfile
+ atexit.register(Utils.cleanup, [tmpfile])
+
+ return tmpfile
+
+ @staticmethod
+ def create_tmpfile(prefix='tmp'):
+ ''' Generates and returns a temporary file name '''
+
+ with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
+ return tmp.name
@staticmethod
- def create_files_from_contents(content, content_type=None):
+ def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
- path = Utils.create_file(item['path'], item['data'], ftype=content_type)
- files.append({'name': os.path.basename(path), 'path': path})
+ path = Utils.create_tmp_file_from_contents(item['path'] + '-',
+ item['data'],
+ ftype=content_type)
+ files.append({'name': os.path.basename(item['path']),
+ 'path': path})
return files
@staticmethod
@@ -1298,7 +1329,7 @@ class OCObject(OpenShiftCLI):
return self._create(files[0])
content['data'] = yaml.dump(content['data'])
- content_file = Utils.create_files_from_contents(content)[0]
+ content_file = Utils.create_tmp_files_from_contents(content)[0]
return self._create(content_file['path'])
diff --git a/roles/lib_openshift/library/oc_route.py b/roles/lib_openshift/library/oc_route.py
index d1b2ccb14..7c4fa1fbd 100644
--- a/roles/lib_openshift/library/oc_route.py
+++ b/roles/lib_openshift/library/oc_route.py
@@ -38,6 +38,7 @@ import os
import re
import shutil
import subprocess
+import tempfile
# pylint: disable=import-error
import ruamel.yaml as yaml
from ansible.module_utils.basic import AnsibleModule
@@ -762,7 +763,7 @@ class OpenShiftCLI(object):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
- self.kubeconfig = kubeconfig
+ self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
# Pylint allows only 5 arguments to be passed.
@@ -773,7 +774,8 @@ class OpenShiftCLI(object):
if not res['results']:
return res
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
+
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
@@ -797,7 +799,7 @@ class OpenShiftCLI(object):
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
@@ -840,7 +842,7 @@ class OpenShiftCLI(object):
if results['returncode'] != 0 or not create:
return results
- fname = '/tmp/%s' % template_name
+ fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
@@ -1021,32 +1023,61 @@ class OpenShiftCLI(object):
class Utils(object):
''' utilities for openshiftcli modules '''
+
@staticmethod
- def create_file(rname, data, ftype='yaml'):
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ with open(filename, 'w') as sfd:
+ sfd.write(contents)
+
+ @staticmethod
+ def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
- path = os.path.join('/tmp', rname)
- with open(path, 'w') as fds:
- if ftype == 'yaml':
- fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
- elif ftype == 'json':
- fds.write(json.dumps(data))
- else:
- fds.write(data)
+ tmp = Utils.create_tmpfile(prefix=rname)
+
+ if ftype == 'yaml':
+ Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
+ elif ftype == 'json':
+ Utils._write(tmp, json.dumps(data))
+ else:
+ Utils._write(tmp, data)
# Register cleanup when module is done
- atexit.register(Utils.cleanup, [path])
- return path
+ atexit.register(Utils.cleanup, [tmp])
+ return tmp
+
+ @staticmethod
+ def create_tmpfile_copy(inc_file):
+ '''create a temporary copy of a file'''
+ tmpfile = Utils.create_tmpfile('lib_openshift-')
+ Utils._write(tmpfile, open(inc_file).read())
+
+ # Cleanup the tmpfile
+ atexit.register(Utils.cleanup, [tmpfile])
+
+ return tmpfile
+
+ @staticmethod
+ def create_tmpfile(prefix='tmp'):
+ ''' Generates and returns a temporary file name '''
+
+ with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
+ return tmp.name
@staticmethod
- def create_files_from_contents(content, content_type=None):
+ def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
- path = Utils.create_file(item['path'], item['data'], ftype=content_type)
- files.append({'name': os.path.basename(path), 'path': path})
+ path = Utils.create_tmp_file_from_contents(item['path'] + '-',
+ item['data'],
+ ftype=content_type)
+ files.append({'name': os.path.basename(item['path']),
+ 'path': path})
return files
@staticmethod
diff --git a/roles/lib_openshift/library/oc_scale.py b/roles/lib_openshift/library/oc_scale.py
index f2b96b6ad..48a629b5e 100644
--- a/roles/lib_openshift/library/oc_scale.py
+++ b/roles/lib_openshift/library/oc_scale.py
@@ -38,6 +38,7 @@ import os
import re
import shutil
import subprocess
+import tempfile
# pylint: disable=import-error
import ruamel.yaml as yaml
from ansible.module_utils.basic import AnsibleModule
@@ -712,7 +713,7 @@ class OpenShiftCLI(object):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
- self.kubeconfig = kubeconfig
+ self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
# Pylint allows only 5 arguments to be passed.
@@ -723,7 +724,8 @@ class OpenShiftCLI(object):
if not res['results']:
return res
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
+
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
@@ -747,7 +749,7 @@ class OpenShiftCLI(object):
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
@@ -790,7 +792,7 @@ class OpenShiftCLI(object):
if results['returncode'] != 0 or not create:
return results
- fname = '/tmp/%s' % template_name
+ fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
@@ -971,32 +973,61 @@ class OpenShiftCLI(object):
class Utils(object):
''' utilities for openshiftcli modules '''
+
@staticmethod
- def create_file(rname, data, ftype='yaml'):
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ with open(filename, 'w') as sfd:
+ sfd.write(contents)
+
+ @staticmethod
+ def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
- path = os.path.join('/tmp', rname)
- with open(path, 'w') as fds:
- if ftype == 'yaml':
- fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
- elif ftype == 'json':
- fds.write(json.dumps(data))
- else:
- fds.write(data)
+ tmp = Utils.create_tmpfile(prefix=rname)
+
+ if ftype == 'yaml':
+ Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
+ elif ftype == 'json':
+ Utils._write(tmp, json.dumps(data))
+ else:
+ Utils._write(tmp, data)
# Register cleanup when module is done
- atexit.register(Utils.cleanup, [path])
- return path
+ atexit.register(Utils.cleanup, [tmp])
+ return tmp
+
+ @staticmethod
+ def create_tmpfile_copy(inc_file):
+ '''create a temporary copy of a file'''
+ tmpfile = Utils.create_tmpfile('lib_openshift-')
+ Utils._write(tmpfile, open(inc_file).read())
+
+ # Cleanup the tmpfile
+ atexit.register(Utils.cleanup, [tmpfile])
+
+ return tmpfile
+
+ @staticmethod
+ def create_tmpfile(prefix='tmp'):
+ ''' Generates and returns a temporary file name '''
+
+ with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
+ return tmp.name
@staticmethod
- def create_files_from_contents(content, content_type=None):
+ def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
- path = Utils.create_file(item['path'], item['data'], ftype=content_type)
- files.append({'name': os.path.basename(path), 'path': path})
+ path = Utils.create_tmp_file_from_contents(item['path'] + '-',
+ item['data'],
+ ftype=content_type)
+ files.append({'name': os.path.basename(item['path']),
+ 'path': path})
return files
@staticmethod
diff --git a/roles/lib_openshift/library/oc_secret.py b/roles/lib_openshift/library/oc_secret.py
index d2ba1af51..526474f17 100644
--- a/roles/lib_openshift/library/oc_secret.py
+++ b/roles/lib_openshift/library/oc_secret.py
@@ -38,6 +38,7 @@ import os
import re
import shutil
import subprocess
+import tempfile
# pylint: disable=import-error
import ruamel.yaml as yaml
from ansible.module_utils.basic import AnsibleModule
@@ -758,7 +759,7 @@ class OpenShiftCLI(object):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
- self.kubeconfig = kubeconfig
+ self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
# Pylint allows only 5 arguments to be passed.
@@ -769,7 +770,8 @@ class OpenShiftCLI(object):
if not res['results']:
return res
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
+
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
@@ -793,7 +795,7 @@ class OpenShiftCLI(object):
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
@@ -836,7 +838,7 @@ class OpenShiftCLI(object):
if results['returncode'] != 0 or not create:
return results
- fname = '/tmp/%s' % template_name
+ fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
@@ -1017,32 +1019,61 @@ class OpenShiftCLI(object):
class Utils(object):
''' utilities for openshiftcli modules '''
+
@staticmethod
- def create_file(rname, data, ftype='yaml'):
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ with open(filename, 'w') as sfd:
+ sfd.write(contents)
+
+ @staticmethod
+ def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
- path = os.path.join('/tmp', rname)
- with open(path, 'w') as fds:
- if ftype == 'yaml':
- fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
- elif ftype == 'json':
- fds.write(json.dumps(data))
- else:
- fds.write(data)
+ tmp = Utils.create_tmpfile(prefix=rname)
+
+ if ftype == 'yaml':
+ Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
+ elif ftype == 'json':
+ Utils._write(tmp, json.dumps(data))
+ else:
+ Utils._write(tmp, data)
# Register cleanup when module is done
- atexit.register(Utils.cleanup, [path])
- return path
+ atexit.register(Utils.cleanup, [tmp])
+ return tmp
+
+ @staticmethod
+ def create_tmpfile_copy(inc_file):
+ '''create a temporary copy of a file'''
+ tmpfile = Utils.create_tmpfile('lib_openshift-')
+ Utils._write(tmpfile, open(inc_file).read())
+
+ # Cleanup the tmpfile
+ atexit.register(Utils.cleanup, [tmpfile])
+
+ return tmpfile
+
+ @staticmethod
+ def create_tmpfile(prefix='tmp'):
+ ''' Generates and returns a temporary file name '''
+
+ with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
+ return tmp.name
@staticmethod
- def create_files_from_contents(content, content_type=None):
+ def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
- path = Utils.create_file(item['path'], item['data'], ftype=content_type)
- files.append({'name': os.path.basename(path), 'path': path})
+ path = Utils.create_tmp_file_from_contents(item['path'] + '-',
+ item['data'],
+ ftype=content_type)
+ files.append({'name': os.path.basename(item['path']),
+ 'path': path})
return files
@staticmethod
@@ -1418,7 +1449,7 @@ class OCSecret(OpenShiftCLI):
def create(self, files=None, contents=None):
'''Create a secret '''
if not files:
- files = Utils.create_files_from_contents(contents)
+ files = Utils.create_tmp_files_from_contents(contents)
secrets = ["%s=%s" % (sfile['name'], sfile['path']) for sfile in files]
cmd = ['secrets', 'new', self.name]
@@ -1451,7 +1482,7 @@ class OCSecret(OpenShiftCLI):
This is accomplished by passing -ojson. This will most likely change in the future
'''
if not files:
- files = Utils.create_files_from_contents(contents)
+ files = Utils.create_tmp_files_from_contents(contents)
secrets = ["%s=%s" % (sfile['name'], sfile['path']) for sfile in files]
cmd = ['-ojson', 'secrets', 'new', self.name]
@@ -1502,7 +1533,7 @@ class OCSecret(OpenShiftCLI):
if params['files']:
files = params['files']
elif params['contents']:
- files = Utils.create_files_from_contents(params['contents'])
+ files = Utils.create_tmp_files_from_contents(params['contents'])
else:
return {'failed': True,
'msg': 'Either specify files or contents.'}
@@ -1516,7 +1547,7 @@ class OCSecret(OpenShiftCLI):
return {'changed': True,
'msg': 'Would have performed a create.'}
- api_rval = ocsecret.create(params['files'], params['contents'])
+ api_rval = ocsecret.create(files, params['contents'])
# Remove files
if files and params['delete_after']:
diff --git a/roles/lib_openshift/library/oc_service.py b/roles/lib_openshift/library/oc_service.py
index 0979f83c6..a9baef765 100644
--- a/roles/lib_openshift/library/oc_service.py
+++ b/roles/lib_openshift/library/oc_service.py
@@ -38,6 +38,7 @@ import os
import re
import shutil
import subprocess
+import tempfile
# pylint: disable=import-error
import ruamel.yaml as yaml
from ansible.module_utils.basic import AnsibleModule
@@ -764,7 +765,7 @@ class OpenShiftCLI(object):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
- self.kubeconfig = kubeconfig
+ self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
# Pylint allows only 5 arguments to be passed.
@@ -775,7 +776,8 @@ class OpenShiftCLI(object):
if not res['results']:
return res
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
+
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
@@ -799,7 +801,7 @@ class OpenShiftCLI(object):
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
@@ -842,7 +844,7 @@ class OpenShiftCLI(object):
if results['returncode'] != 0 or not create:
return results
- fname = '/tmp/%s' % template_name
+ fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
@@ -1023,32 +1025,61 @@ class OpenShiftCLI(object):
class Utils(object):
''' utilities for openshiftcli modules '''
+
@staticmethod
- def create_file(rname, data, ftype='yaml'):
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ with open(filename, 'w') as sfd:
+ sfd.write(contents)
+
+ @staticmethod
+ def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
- path = os.path.join('/tmp', rname)
- with open(path, 'w') as fds:
- if ftype == 'yaml':
- fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
- elif ftype == 'json':
- fds.write(json.dumps(data))
- else:
- fds.write(data)
+ tmp = Utils.create_tmpfile(prefix=rname)
+
+ if ftype == 'yaml':
+ Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
+ elif ftype == 'json':
+ Utils._write(tmp, json.dumps(data))
+ else:
+ Utils._write(tmp, data)
# Register cleanup when module is done
- atexit.register(Utils.cleanup, [path])
- return path
+ atexit.register(Utils.cleanup, [tmp])
+ return tmp
+
+ @staticmethod
+ def create_tmpfile_copy(inc_file):
+ '''create a temporary copy of a file'''
+ tmpfile = Utils.create_tmpfile('lib_openshift-')
+ Utils._write(tmpfile, open(inc_file).read())
+
+ # Cleanup the tmpfile
+ atexit.register(Utils.cleanup, [tmpfile])
+
+ return tmpfile
+
+ @staticmethod
+ def create_tmpfile(prefix='tmp'):
+ ''' Generates and returns a temporary file name '''
+
+ with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
+ return tmp.name
@staticmethod
- def create_files_from_contents(content, content_type=None):
+ def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
- path = Utils.create_file(item['path'], item['data'], ftype=content_type)
- files.append({'name': os.path.basename(path), 'path': path})
+ path = Utils.create_tmp_file_from_contents(item['path'] + '-',
+ item['data'],
+ ftype=content_type)
+ files.append({'name': os.path.basename(item['path']),
+ 'path': path})
return files
@staticmethod
diff --git a/roles/lib_openshift/library/oc_serviceaccount.py b/roles/lib_openshift/library/oc_serviceaccount.py
index 0db0d1219..cd0847963 100644
--- a/roles/lib_openshift/library/oc_serviceaccount.py
+++ b/roles/lib_openshift/library/oc_serviceaccount.py
@@ -38,6 +38,7 @@ import os
import re
import shutil
import subprocess
+import tempfile
# pylint: disable=import-error
import ruamel.yaml as yaml
from ansible.module_utils.basic import AnsibleModule
@@ -710,7 +711,7 @@ class OpenShiftCLI(object):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
- self.kubeconfig = kubeconfig
+ self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
# Pylint allows only 5 arguments to be passed.
@@ -721,7 +722,8 @@ class OpenShiftCLI(object):
if not res['results']:
return res
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
+
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
@@ -745,7 +747,7 @@ class OpenShiftCLI(object):
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
@@ -788,7 +790,7 @@ class OpenShiftCLI(object):
if results['returncode'] != 0 or not create:
return results
- fname = '/tmp/%s' % template_name
+ fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
@@ -969,32 +971,61 @@ class OpenShiftCLI(object):
class Utils(object):
''' utilities for openshiftcli modules '''
+
@staticmethod
- def create_file(rname, data, ftype='yaml'):
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ with open(filename, 'w') as sfd:
+ sfd.write(contents)
+
+ @staticmethod
+ def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
- path = os.path.join('/tmp', rname)
- with open(path, 'w') as fds:
- if ftype == 'yaml':
- fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
- elif ftype == 'json':
- fds.write(json.dumps(data))
- else:
- fds.write(data)
+ tmp = Utils.create_tmpfile(prefix=rname)
+
+ if ftype == 'yaml':
+ Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
+ elif ftype == 'json':
+ Utils._write(tmp, json.dumps(data))
+ else:
+ Utils._write(tmp, data)
# Register cleanup when module is done
- atexit.register(Utils.cleanup, [path])
- return path
+ atexit.register(Utils.cleanup, [tmp])
+ return tmp
+
+ @staticmethod
+ def create_tmpfile_copy(inc_file):
+ '''create a temporary copy of a file'''
+ tmpfile = Utils.create_tmpfile('lib_openshift-')
+ Utils._write(tmpfile, open(inc_file).read())
+
+ # Cleanup the tmpfile
+ atexit.register(Utils.cleanup, [tmpfile])
+
+ return tmpfile
+
+ @staticmethod
+ def create_tmpfile(prefix='tmp'):
+ ''' Generates and returns a temporary file name '''
+
+ with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
+ return tmp.name
@staticmethod
- def create_files_from_contents(content, content_type=None):
+ def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
- path = Utils.create_file(item['path'], item['data'], ftype=content_type)
- files.append({'name': os.path.basename(path), 'path': path})
+ path = Utils.create_tmp_file_from_contents(item['path'] + '-',
+ item['data'],
+ ftype=content_type)
+ files.append({'name': os.path.basename(item['path']),
+ 'path': path})
return files
@staticmethod
diff --git a/roles/lib_openshift/library/oc_serviceaccount_secret.py b/roles/lib_openshift/library/oc_serviceaccount_secret.py
index 29985d62f..e22ccbfc2 100644
--- a/roles/lib_openshift/library/oc_serviceaccount_secret.py
+++ b/roles/lib_openshift/library/oc_serviceaccount_secret.py
@@ -38,6 +38,7 @@ import os
import re
import shutil
import subprocess
+import tempfile
# pylint: disable=import-error
import ruamel.yaml as yaml
from ansible.module_utils.basic import AnsibleModule
@@ -710,7 +711,7 @@ class OpenShiftCLI(object):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
- self.kubeconfig = kubeconfig
+ self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
# Pylint allows only 5 arguments to be passed.
@@ -721,7 +722,8 @@ class OpenShiftCLI(object):
if not res['results']:
return res
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
+
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
@@ -745,7 +747,7 @@ class OpenShiftCLI(object):
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
@@ -788,7 +790,7 @@ class OpenShiftCLI(object):
if results['returncode'] != 0 or not create:
return results
- fname = '/tmp/%s' % template_name
+ fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
@@ -969,32 +971,61 @@ class OpenShiftCLI(object):
class Utils(object):
''' utilities for openshiftcli modules '''
+
@staticmethod
- def create_file(rname, data, ftype='yaml'):
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ with open(filename, 'w') as sfd:
+ sfd.write(contents)
+
+ @staticmethod
+ def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
- path = os.path.join('/tmp', rname)
- with open(path, 'w') as fds:
- if ftype == 'yaml':
- fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
- elif ftype == 'json':
- fds.write(json.dumps(data))
- else:
- fds.write(data)
+ tmp = Utils.create_tmpfile(prefix=rname)
+
+ if ftype == 'yaml':
+ Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
+ elif ftype == 'json':
+ Utils._write(tmp, json.dumps(data))
+ else:
+ Utils._write(tmp, data)
# Register cleanup when module is done
- atexit.register(Utils.cleanup, [path])
- return path
+ atexit.register(Utils.cleanup, [tmp])
+ return tmp
+
+ @staticmethod
+ def create_tmpfile_copy(inc_file):
+ '''create a temporary copy of a file'''
+ tmpfile = Utils.create_tmpfile('lib_openshift-')
+ Utils._write(tmpfile, open(inc_file).read())
+
+ # Cleanup the tmpfile
+ atexit.register(Utils.cleanup, [tmpfile])
+
+ return tmpfile
+
+ @staticmethod
+ def create_tmpfile(prefix='tmp'):
+ ''' Generates and returns a temporary file name '''
+
+ with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
+ return tmp.name
@staticmethod
- def create_files_from_contents(content, content_type=None):
+ def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
- path = Utils.create_file(item['path'], item['data'], ftype=content_type)
- files.append({'name': os.path.basename(path), 'path': path})
+ path = Utils.create_tmp_file_from_contents(item['path'] + '-',
+ item['data'],
+ ftype=content_type)
+ files.append({'name': os.path.basename(item['path']),
+ 'path': path})
return files
@staticmethod
diff --git a/roles/lib_openshift/library/oc_version.py b/roles/lib_openshift/library/oc_version.py
index 5c528b399..e44375ffa 100644
--- a/roles/lib_openshift/library/oc_version.py
+++ b/roles/lib_openshift/library/oc_version.py
@@ -38,6 +38,7 @@ import os
import re
import shutil
import subprocess
+import tempfile
# pylint: disable=import-error
import ruamel.yaml as yaml
from ansible.module_utils.basic import AnsibleModule
@@ -682,7 +683,7 @@ class OpenShiftCLI(object):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
- self.kubeconfig = kubeconfig
+ self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
# Pylint allows only 5 arguments to be passed.
@@ -693,7 +694,8 @@ class OpenShiftCLI(object):
if not res['results']:
return res
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
+
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
@@ -717,7 +719,7 @@ class OpenShiftCLI(object):
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
@@ -760,7 +762,7 @@ class OpenShiftCLI(object):
if results['returncode'] != 0 or not create:
return results
- fname = '/tmp/%s' % template_name
+ fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
@@ -941,32 +943,61 @@ class OpenShiftCLI(object):
class Utils(object):
''' utilities for openshiftcli modules '''
+
@staticmethod
- def create_file(rname, data, ftype='yaml'):
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ with open(filename, 'w') as sfd:
+ sfd.write(contents)
+
+ @staticmethod
+ def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
- path = os.path.join('/tmp', rname)
- with open(path, 'w') as fds:
- if ftype == 'yaml':
- fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
- elif ftype == 'json':
- fds.write(json.dumps(data))
- else:
- fds.write(data)
+ tmp = Utils.create_tmpfile(prefix=rname)
+
+ if ftype == 'yaml':
+ Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
+ elif ftype == 'json':
+ Utils._write(tmp, json.dumps(data))
+ else:
+ Utils._write(tmp, data)
# Register cleanup when module is done
- atexit.register(Utils.cleanup, [path])
- return path
+ atexit.register(Utils.cleanup, [tmp])
+ return tmp
+
+ @staticmethod
+ def create_tmpfile_copy(inc_file):
+ '''create a temporary copy of a file'''
+ tmpfile = Utils.create_tmpfile('lib_openshift-')
+ Utils._write(tmpfile, open(inc_file).read())
+
+ # Cleanup the tmpfile
+ atexit.register(Utils.cleanup, [tmpfile])
+
+ return tmpfile
+
+ @staticmethod
+ def create_tmpfile(prefix='tmp'):
+ ''' Generates and returns a temporary file name '''
+
+ with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
+ return tmp.name
@staticmethod
- def create_files_from_contents(content, content_type=None):
+ def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
- path = Utils.create_file(item['path'], item['data'], ftype=content_type)
- files.append({'name': os.path.basename(path), 'path': path})
+ path = Utils.create_tmp_file_from_contents(item['path'] + '-',
+ item['data'],
+ ftype=content_type)
+ files.append({'name': os.path.basename(item['path']),
+ 'path': path})
return files
@staticmethod
diff --git a/roles/lib_openshift/src/ansible/oc_label.py b/roles/lib_openshift/src/ansible/oc_label.py
index 28f004621..84c5e336a 100644
--- a/roles/lib_openshift/src/ansible/oc_label.py
+++ b/roles/lib_openshift/src/ansible/oc_label.py
@@ -10,7 +10,7 @@ def main():
state=dict(default='present', type='str',
choices=['present', 'absent', 'list', 'add']),
debug=dict(default=False, type='bool'),
- kind=dict(default='node', type='str', required=True,
+ kind=dict(default='node', type='str',
choices=['node', 'pod', 'namespace']),
name=dict(default=None, type='str'),
namespace=dict(default=None, type='str'),
diff --git a/roles/lib_openshift/src/class/oc_obj.py b/roles/lib_openshift/src/class/oc_obj.py
index 9d0b8e45b..2ec20e72c 100644
--- a/roles/lib_openshift/src/class/oc_obj.py
+++ b/roles/lib_openshift/src/class/oc_obj.py
@@ -49,7 +49,7 @@ class OCObject(OpenShiftCLI):
return self._create(files[0])
content['data'] = yaml.dump(content['data'])
- content_file = Utils.create_files_from_contents(content)[0]
+ content_file = Utils.create_tmp_files_from_contents(content)[0]
return self._create(content_file['path'])
diff --git a/roles/lib_openshift/src/class/oc_secret.py b/roles/lib_openshift/src/class/oc_secret.py
index 40b2aa4d1..e99999c37 100644
--- a/roles/lib_openshift/src/class/oc_secret.py
+++ b/roles/lib_openshift/src/class/oc_secret.py
@@ -48,7 +48,7 @@ class OCSecret(OpenShiftCLI):
def create(self, files=None, contents=None):
'''Create a secret '''
if not files:
- files = Utils.create_files_from_contents(contents)
+ files = Utils.create_tmp_files_from_contents(contents)
secrets = ["%s=%s" % (sfile['name'], sfile['path']) for sfile in files]
cmd = ['secrets', 'new', self.name]
@@ -81,7 +81,7 @@ class OCSecret(OpenShiftCLI):
This is accomplished by passing -ojson. This will most likely change in the future
'''
if not files:
- files = Utils.create_files_from_contents(contents)
+ files = Utils.create_tmp_files_from_contents(contents)
secrets = ["%s=%s" % (sfile['name'], sfile['path']) for sfile in files]
cmd = ['-ojson', 'secrets', 'new', self.name]
@@ -132,7 +132,7 @@ class OCSecret(OpenShiftCLI):
if params['files']:
files = params['files']
elif params['contents']:
- files = Utils.create_files_from_contents(params['contents'])
+ files = Utils.create_tmp_files_from_contents(params['contents'])
else:
return {'failed': True,
'msg': 'Either specify files or contents.'}
@@ -146,7 +146,7 @@ class OCSecret(OpenShiftCLI):
return {'changed': True,
'msg': 'Would have performed a create.'}
- api_rval = ocsecret.create(params['files'], params['contents'])
+ api_rval = ocsecret.create(files, params['contents'])
# Remove files
if files and params['delete_after']:
diff --git a/roles/lib_openshift/src/lib/base.py b/roles/lib_openshift/src/lib/base.py
index 55f7d3146..a895b40b3 100644
--- a/roles/lib_openshift/src/lib/base.py
+++ b/roles/lib_openshift/src/lib/base.py
@@ -20,7 +20,7 @@ class OpenShiftCLI(object):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
- self.kubeconfig = kubeconfig
+ self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
# Pylint allows only 5 arguments to be passed.
@@ -31,7 +31,8 @@ class OpenShiftCLI(object):
if not res['results']:
return res
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
+
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
@@ -55,7 +56,7 @@ class OpenShiftCLI(object):
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
- fname = '/tmp/%s' % rname
+ fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
@@ -98,7 +99,7 @@ class OpenShiftCLI(object):
if results['returncode'] != 0 or not create:
return results
- fname = '/tmp/%s' % template_name
+ fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
@@ -279,32 +280,61 @@ class OpenShiftCLI(object):
class Utils(object):
''' utilities for openshiftcli modules '''
+
+ @staticmethod
+ def _write(filename, contents):
+ ''' Actually write the file contents to disk. This helps with mocking. '''
+
+ with open(filename, 'w') as sfd:
+ sfd.write(contents)
+
@staticmethod
- def create_file(rname, data, ftype='yaml'):
+ def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
- path = os.path.join('/tmp', rname)
- with open(path, 'w') as fds:
- if ftype == 'yaml':
- fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
- elif ftype == 'json':
- fds.write(json.dumps(data))
- else:
- fds.write(data)
+ tmp = Utils.create_tmpfile(prefix=rname)
+
+ if ftype == 'yaml':
+ Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
+ elif ftype == 'json':
+ Utils._write(tmp, json.dumps(data))
+ else:
+ Utils._write(tmp, data)
# Register cleanup when module is done
- atexit.register(Utils.cleanup, [path])
- return path
+ atexit.register(Utils.cleanup, [tmp])
+ return tmp
+
+ @staticmethod
+ def create_tmpfile_copy(inc_file):
+ '''create a temporary copy of a file'''
+ tmpfile = Utils.create_tmpfile('lib_openshift-')
+ Utils._write(tmpfile, open(inc_file).read())
+
+ # Cleanup the tmpfile
+ atexit.register(Utils.cleanup, [tmpfile])
+
+ return tmpfile
+
+ @staticmethod
+ def create_tmpfile(prefix='tmp'):
+ ''' Generates and returns a temporary file name '''
+
+ with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
+ return tmp.name
@staticmethod
- def create_files_from_contents(content, content_type=None):
+ def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
- path = Utils.create_file(item['path'], item['data'], ftype=content_type)
- files.append({'name': os.path.basename(path), 'path': path})
+ path = Utils.create_tmp_file_from_contents(item['path'] + '-',
+ item['data'],
+ ftype=content_type)
+ files.append({'name': os.path.basename(item['path']),
+ 'path': path})
return files
@staticmethod
diff --git a/roles/lib_openshift/src/lib/import.py b/roles/lib_openshift/src/lib/import.py
index c2b30e019..6344c1a54 100644
--- a/roles/lib_openshift/src/lib/import.py
+++ b/roles/lib_openshift/src/lib/import.py
@@ -12,6 +12,7 @@ import os
import re
import shutil
import subprocess
+import tempfile
# pylint: disable=import-error
import ruamel.yaml as yaml
from ansible.module_utils.basic import AnsibleModule
diff --git a/roles/lib_openshift/src/test/generate-and-run-tests.sh b/roles/lib_openshift/src/test/generate-and-run-tests.sh
new file mode 100755
index 000000000..cd7571372
--- /dev/null
+++ b/roles/lib_openshift/src/test/generate-and-run-tests.sh
@@ -0,0 +1,54 @@
+#!/bin/bash -e
+
+
+if [ $# -ne 1 ] ; then
+ echo "Usage: $(basename $0) <master name>"
+ exit 1
+fi
+
+MASTER=$1
+
+
+
+# Put us in the same dir as the script.
+cd $(dirname $0)
+
+
+echo
+echo "Running lib_utils generate-and-run-tests.sh"
+echo "-------------------------------------------"
+../../../lib_utils/src/test/generate-and-run-tests.sh
+
+
+echo
+echo "Running lib_openshift generate"
+echo "------------------------------"
+../generate.py
+
+
+echo
+echo "Running lib_openshift Unit Tests"
+echo "----------------------------"
+cd unit
+
+for test in *.py; do
+ echo
+ echo "--------------------------------------------------------------------------------"
+ echo
+ echo "Running $test..."
+ ./$test
+done
+
+
+echo
+echo "Running lib_openshift Integration Tests"
+echo "-----------------------------------"
+cd ../integration
+
+for test in *.yml; do
+ echo
+ echo "--------------------------------------------------------------------------------"
+ echo
+ echo "Running $test..."
+ ./$test -vvv -e cli_master_test="$MASTER"
+done
diff --git a/roles/lib_openshift/src/test/integration/oadm_manage_node.yml b/roles/lib_openshift/src/test/integration/oadm_manage_node.yml
index 69a701b17..3ee13a409 100755
--- a/roles/lib_openshift/src/test/integration/oadm_manage_node.yml
+++ b/roles/lib_openshift/src/test/integration/oadm_manage_node.yml
@@ -1,40 +1,51 @@
#!/usr/bin/ansible-playbook --module-path=../../../library/
-# ./oadm_manage_node.yml -M ../../../library -e "cli_master_test=$OPENSHIFT_MASTER cli_node_test=$OPENSHIFT_NODE
+#
+# ./oadm_manage_node.yml -e "cli_master_test=$OPENSHIFT_MASTER
---
- hosts: "{{ cli_master_test }}"
gather_facts: no
user: root
tasks:
+ - name: get list of nodes
+ oc_obj:
+ state: list
+ kind: node
+ register: obj_out
+
+ - name: Set the node to work with
+ set_fact:
+ node_to_test: "{{ obj_out['results']['results'][0]['items'][0]['metadata']['name'] }}"
+
- name: list pods from a node
oadm_manage_node:
list_pods: True
node:
- - "{{ cli_node_test }}"
+ - "{{ node_to_test }}"
register: podout
- debug: var=podout
- assert:
- that: "'{{ cli_node_test }}' in podout.results.nodes"
+ that: "'{{ node_to_test }}' in podout.results.nodes"
msg: Pod data was not returned
- name: set node to unschedulable
oadm_manage_node:
schedulable: False
node:
- - "{{ cli_node_test }}"
+ - "{{ node_to_test }}"
register: nodeout
- debug: var=nodeout
- name: assert that schedulable=False
assert:
that: nodeout.results.nodes[0]['schedulable'] == False
- msg: "{{ cli_node_test }} schedulable set to True"
+ msg: "{{ node_to_test }} schedulable set to True"
- name: get node scheduable
oc_obj:
kind: node
state: list
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
namespace: None
register: nodeout
@@ -48,11 +59,11 @@
oadm_manage_node:
schedulable: True
node:
- - "{{ cli_node_test }}"
+ - "{{ node_to_test }}"
register: nodeout
- debug: var=nodeout
- name: assert that schedulable=False
assert:
that: nodeout.results.nodes[0]['schedulable']
- msg: "{{ cli_node_test }} schedulable set to False"
+ msg: "{{ node_to_test }} schedulable set to False"
diff --git a/roles/lib_openshift/src/test/integration/oc_label.yml b/roles/lib_openshift/src/test/integration/oc_label.yml
index ce9bc25bb..b4e721407 100755
--- a/roles/lib_openshift/src/test/integration/oc_label.yml
+++ b/roles/lib_openshift/src/test/integration/oc_label.yml
@@ -1,5 +1,7 @@
#!/usr/bin/ansible-playbook --module-path=../../../library/
-# ./oc_label.yml -e "cli_master_test=$OPENSHIFT_MASTER -e "cli_node_test=ip-172-0-31-1.ec2"
+#
+# ./oc_label.yml -e "cli_master_test=$OPENSHIFT_MASTER
+#
---
- hosts: "{{ cli_master_test }}"
gather_facts: no
@@ -15,16 +17,25 @@
msg: "{{ item }} not defined"
when: "{{ item }} is not defined"
with_items:
- - cli_node_test # openshift node to be used to add/remove labels to
- cli_master_test # ansible inventory instance to run playbook against
tasks:
+ - name: get list of nodes
+ oc_obj:
+ state: list
+ kind: node
+ register: obj_out
+
+ - name: Set the node to work with
+ set_fact:
+ node_to_test: "{{ obj_out['results']['results'][0]['items'][0]['metadata']['name'] }}"
+
- name: delete test labels (start from known starting position)
oc_label:
state: absent
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels:
- key: testlabel2
- key: testlabel3
@@ -34,7 +45,7 @@
state: list
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
register: original_labels
- name: assert that testlabel2 and testlabel3 test labels don't exist
assert:
@@ -47,7 +58,7 @@
state: add
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels:
- key: testlabel2
value: "yes"
@@ -62,7 +73,7 @@
state: list
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
register: label_out
- name: assert that testlabel2 label actually added
assert:
@@ -75,7 +86,7 @@
state: add
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels:
- key: testlabel2
value: "yes"
@@ -90,7 +101,7 @@
state: add
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels:
- key: testlabel2
value: "different"
@@ -105,7 +116,7 @@
state: list
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
register: label_out
- name: assert that testlabel2 label actually modified
assert:
@@ -118,7 +129,7 @@
state: absent
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels:
- key: testlabelnone
register: label_out
@@ -132,7 +143,7 @@
state: absent
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels:
- key: testlabel2
register: label_out
@@ -146,7 +157,7 @@
state: absent
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels:
- key: testlabel2
register: label_out
@@ -160,7 +171,7 @@
state: list
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
register: label_out
- name: assert label actually deleted
assert:
@@ -172,7 +183,7 @@
state: add
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels:
- key: testlabel2
value: "yes"
@@ -189,7 +200,7 @@
state: list
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
register: label_out
- name: assert that both labels actually exist
assert:
@@ -204,7 +215,7 @@
state: absent
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels:
- key: testlabel2
- key: testlabel3
@@ -219,7 +230,7 @@
state: absent
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels:
- key: testlabel2
- key: testlabel3
@@ -237,7 +248,7 @@
state: present
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels: "{{ original_labels_as_key_value_list }}"
register: label_out
- name: assert that no changes are made when current list matches existing list
@@ -250,7 +261,7 @@
state: present
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels: "{{ original_labels_as_key_value_list + [{'key': 'testlabel2', 'value': 'yes'}] }}"
register: label_out
- name: assert that changes were made
@@ -263,7 +274,7 @@
state: list
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
register: label_out
- name: asssert that new label was actually added
assert:
@@ -276,7 +287,7 @@
state: present
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels: "{{ original_labels_as_key_value_list + [{'key': 'testlabel2', 'value': 'different'}]}}"
register: label_out
- name: assert that changes were made when existing key's value is changed
@@ -289,7 +300,7 @@
state: list
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
register: label_out
- name: asssert that changed label was actually changed
assert:
@@ -302,7 +313,7 @@
state: present
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
labels: "{{ original_labels_as_key_value_list }}"
register: label_out
- name: assert that changes were made
@@ -315,7 +326,7 @@
state: list
namespace: "{{ def_namespace }}"
kind: "{{ def_kind }}"
- name: "{{ cli_node_test }}"
+ name: "{{ node_to_test }}"
register: label_out
- name: asssert that present-removed actually removed
assert:
diff --git a/roles/lib_openshift/src/test/integration/oc_service.yml b/roles/lib_openshift/src/test/integration/oc_service.yml
index 616694382..3eb6facef 100755
--- a/roles/lib_openshift/src/test/integration/oc_service.yml
+++ b/roles/lib_openshift/src/test/integration/oc_service.yml
@@ -123,6 +123,6 @@
- assert:
that:
- svc_out.changed == False
- - svc_out.results.returncode == 1
+ - svc_out.results.returncode == 0
- "'not found' in svc_out.results.stderr"
msg: service get failed
diff --git a/roles/lib_openshift/src/test/unit/oadm_manage_node.py b/roles/lib_openshift/src/test/unit/oadm_manage_node.py
index 8fd6f9c55..b0786dfac 100755
--- a/roles/lib_openshift/src/test/unit/oadm_manage_node.py
+++ b/roles/lib_openshift/src/test/unit/oadm_manage_node.py
@@ -35,8 +35,9 @@ class ManageNodeTest(unittest.TestCase):
''' setup method will create a file and set to known configuration '''
pass
+ @mock.patch('oadm_manage_node.Utils.create_tmpfile_copy')
@mock.patch('oadm_manage_node.ManageNode.openshift_cmd')
- def test_list_pods(self, mock_openshift_cmd):
+ def test_list_pods(self, mock_openshift_cmd, mock_tmpfile_copy):
''' Testing a get '''
params = {'node': ['ip-172-31-49-140.ec2.internal'],
'schedulable': None,
@@ -106,6 +107,10 @@ class ManageNodeTest(unittest.TestCase):
"returncode": 0}
]
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
+ ]
+
results = ManageNode.run_ansible(params, False)
# returned a single node
@@ -113,8 +118,9 @@ class ManageNodeTest(unittest.TestCase):
# returned 2 pods
self.assertTrue(len(results['results']['nodes']['ip-172-31-49-140.ec2.internal']) == 2)
+ @mock.patch('oadm_manage_node.Utils.create_tmpfile_copy')
@mock.patch('oadm_manage_node.ManageNode.openshift_cmd')
- def test_schedulable_false(self, mock_openshift_cmd):
+ def test_schedulable_false(self, mock_openshift_cmd, mock_tmpfile_copy):
''' Testing a get '''
params = {'node': ['ip-172-31-49-140.ec2.internal'],
'schedulable': False,
@@ -162,6 +168,11 @@ class ManageNodeTest(unittest.TestCase):
"results": "NAME STATUS AGE\n" +
"ip-172-31-49-140.ec2.internal Ready,SchedulingDisabled 5h\n",
"returncode": 0}]
+
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
+ ]
+
results = ManageNode.run_ansible(params, False)
self.assertTrue(results['changed'])
diff --git a/roles/lib_openshift/src/test/unit/oc_label.py b/roles/lib_openshift/src/test/unit/oc_label.py
index 3f7162070..3176987b0 100755
--- a/roles/lib_openshift/src/test/unit/oc_label.py
+++ b/roles/lib_openshift/src/test/unit/oc_label.py
@@ -35,8 +35,9 @@ class OCLabelTest(unittest.TestCase):
''' setup method will create a file and set to known configuration '''
pass
+ @mock.patch('oc_label.Utils.create_tmpfile_copy')
@mock.patch('oc_label.OCLabel._run')
- def test_state_list(self, mock_cmd):
+ def test_state_list(self, mock_cmd, mock_tmpfile_copy):
''' Testing a label list '''
params = {'name': 'default',
'namespace': 'default',
@@ -82,13 +83,18 @@ class OCLabelTest(unittest.TestCase):
(0, ns, ''),
]
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
+ ]
+
results = OCLabel.run_ansible(params, False)
self.assertFalse(results['changed'])
self.assertTrue(results['results']['labels'] == [{'storage_pv_quota': 'False'}])
+ @mock.patch('oc_label.Utils.create_tmpfile_copy')
@mock.patch('oc_label.OCLabel._run')
- def test_state_present(self, mock_cmd):
+ def test_state_present(self, mock_cmd, mock_tmpfile_copy):
''' Testing a label list '''
params = {'name': 'default',
'namespace': 'default',
@@ -171,6 +177,10 @@ class OCLabelTest(unittest.TestCase):
(0, ns1, ''),
]
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
+ ]
+
results = OCLabel.run_ansible(params, False)
self.assertTrue(results['changed'])
diff --git a/roles/lib_openshift/src/test/unit/oc_scale.py b/roles/lib_openshift/src/test/unit/oc_scale.py
index d8d5a231f..f15eb164d 100755
--- a/roles/lib_openshift/src/test/unit/oc_scale.py
+++ b/roles/lib_openshift/src/test/unit/oc_scale.py
@@ -35,8 +35,9 @@ class OCScaleTest(unittest.TestCase):
''' setup method will create a file and set to known configuration '''
pass
+ @mock.patch('oc_scale.Utils.create_tmpfile_copy')
@mock.patch('oc_scale.OCScale.openshift_cmd')
- def test_state_list(self, mock_openshift_cmd):
+ def test_state_list(self, mock_openshift_cmd, mock_tmpfile_copy):
''' Testing a get '''
params = {'name': 'router',
'namespace': 'default',
@@ -70,13 +71,18 @@ class OCScaleTest(unittest.TestCase):
'results': dc,
'returncode': 0}]
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
+ ]
+
results = OCScale.run_ansible(params, False)
self.assertFalse(results['changed'])
self.assertEqual(results['result'][0], 2)
+ @mock.patch('oc_scale.Utils.create_tmpfile_copy')
@mock.patch('oc_scale.OCScale.openshift_cmd')
- def test_scale(self, mock_openshift_cmd):
+ def test_scale(self, mock_openshift_cmd, mock_tmpfile_copy):
''' Testing a get '''
params = {'name': 'router',
'namespace': 'default',
@@ -114,13 +120,18 @@ class OCScaleTest(unittest.TestCase):
'returncode': 0}
]
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
+ ]
+
results = OCScale.run_ansible(params, False)
self.assertFalse(results['changed'])
self.assertEqual(results['result'][0], 3)
+ @mock.patch('oc_scale.Utils.create_tmpfile_copy')
@mock.patch('oc_scale.OCScale.openshift_cmd')
- def test_no_dc_scale(self, mock_openshift_cmd):
+ def test_no_dc_scale(self, mock_openshift_cmd, mock_tmpfile_copy):
''' Testing a get '''
params = {'name': 'not_there',
'namespace': 'default',
@@ -138,6 +149,10 @@ class OCScaleTest(unittest.TestCase):
'stdout': ""},
]
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
+ ]
+
results = OCScale.run_ansible(params, False)
self.assertTrue(results['failed'])
diff --git a/roles/lib_openshift/src/test/unit/oc_secret.py b/roles/lib_openshift/src/test/unit/oc_secret.py
index 835918b95..645aac82b 100755
--- a/roles/lib_openshift/src/test/unit/oc_secret.py
+++ b/roles/lib_openshift/src/test/unit/oc_secret.py
@@ -35,8 +35,10 @@ class OCSecretTest(unittest.TestCase):
''' setup method will create a file and set to known configuration '''
pass
- @mock.patch('oc_secret.OCSecret.openshift_cmd')
- def test_adding_a_secret(self, mock_openshift_cmd):
+ @mock.patch('oc_secret.Utils.create_tmpfile_copy')
+ @mock.patch('oc_secret.Utils._write')
+ @mock.patch('oc_secret.OCSecret._run')
+ def test_adding_a_secret(self, mock_cmd, mock_write, mock_tmpfile_copy):
''' Testing adding a secret '''
# Arrange
@@ -45,10 +47,10 @@ class OCSecretTest(unittest.TestCase):
params = {
'state': 'present',
'namespace': 'default',
- 'name': 'secretname',
+ 'name': 'testsecretname',
'contents': [{
'path': "/tmp/somesecret.json",
- 'data': "{'one': 1, 'two': 2, 'three', 3}",
+ 'data': "{'one': 1, 'two': 2, 'three': 3}",
}],
'decode': False,
'kubeconfig': '/etc/origin/master/admin.kubeconfig',
@@ -58,17 +60,13 @@ class OCSecretTest(unittest.TestCase):
}
# Return values of our mocked function call. These get returned once per call.
- mock_openshift_cmd.side_effect = [
- {
- "cmd": "/usr/bin/oc get secrets -o json secretname",
- "results": "",
- "returncode": 0,
- }, # oc output for first call to openshift_cmd (oc secrets get)
- {
- "cmd": "/usr/bin/oc secrets new secretname somesecret.json=/tmp/somesecret.json",
- "results": "",
- "returncode": 0,
- }, # oc output for second call to openshift_cmd (oc secrets new)
+ mock_cmd.side_effect = [
+ (1, '', 'Error from server: secrets "testsecretname" not found'),
+ (0, 'secret/testsecretname', ''),
+ ]
+
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
]
# Act
@@ -80,9 +78,13 @@ class OCSecretTest(unittest.TestCase):
self.assertEqual(results['state'], 'present')
# Making sure our mock was called as we expected
- mock_openshift_cmd.assert_has_calls([
- mock.call(['get', 'secrets', 'secretname', '-o', 'json'], output=True),
- mock.call(['secrets', 'new', 'secretname', 'somesecret.json=/tmp/somesecret.json']),
+ mock_cmd.assert_has_calls([
+ mock.call(['oc', '-n', 'default', 'get', 'secrets', 'testsecretname', '-o', 'json'], None),
+ mock.call(['oc', '-n', 'default', 'secrets', 'new', 'testsecretname', mock.ANY], None),
+ ])
+
+ mock_write.assert_has_calls([
+ mock.call(mock.ANY, "{'one': 1, 'two': 2, 'three': 3}"),
])
def tearDown(self):
diff --git a/roles/lib_openshift/src/test/unit/oc_service.py b/roles/lib_openshift/src/test/unit/oc_service.py
index 69f7dd49c..4a845e9f3 100755
--- a/roles/lib_openshift/src/test/unit/oc_service.py
+++ b/roles/lib_openshift/src/test/unit/oc_service.py
@@ -36,8 +36,9 @@ class OCServiceTest(unittest.TestCase):
''' setup method will create a file and set to known configuration '''
pass
+ @mock.patch('oc_service.Utils.create_tmpfile_copy')
@mock.patch('oc_service.OCService._run')
- def test_state_list(self, mock_cmd):
+ def test_state_list(self, mock_cmd, mock_tmpfile_copy):
''' Testing a get '''
params = {'name': 'router',
'namespace': 'default',
@@ -108,13 +109,18 @@ class OCServiceTest(unittest.TestCase):
(0, service, '')
]
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
+ ]
+
results = OCService.run_ansible(params, False)
self.assertFalse(results['changed'])
self.assertEqual(results['results']['results'][0]['metadata']['name'], 'router')
+ @mock.patch('oc_service.Utils.create_tmpfile_copy')
@mock.patch('oc_service.OCService._run')
- def test_create(self, mock_cmd):
+ def test_create(self, mock_cmd, mock_tmpfile_copy):
''' Testing a create service '''
params = {'name': 'router',
'namespace': 'default',
@@ -191,6 +197,10 @@ class OCServiceTest(unittest.TestCase):
(0, service, '')
]
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
+ ]
+
results = OCService.run_ansible(params, False)
self.assertTrue(results['changed'])
diff --git a/roles/lib_openshift/src/test/unit/oc_serviceaccount.py b/roles/lib_openshift/src/test/unit/oc_serviceaccount.py
index dab751bb9..256b569eb 100755
--- a/roles/lib_openshift/src/test/unit/oc_serviceaccount.py
+++ b/roles/lib_openshift/src/test/unit/oc_serviceaccount.py
@@ -35,8 +35,9 @@ class OCServiceAccountTest(unittest.TestCase):
''' setup method will create a file and set to known configuration '''
pass
+ @mock.patch('oc_serviceaccount.Utils.create_tmpfile_copy')
@mock.patch('oc_serviceaccount.OCServiceAccount._run')
- def test_adding_a_serviceaccount(self, mock_cmd):
+ def test_adding_a_serviceaccount(self, mock_cmd, mock_tmpfile_copy):
''' Testing adding a serviceaccount '''
# Arrange
@@ -90,6 +91,10 @@ class OCServiceAccountTest(unittest.TestCase):
(0, valid_result_json, ''),
]
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
+ ]
+
# Act
results = OCServiceAccount.run_ansible(params, False)
diff --git a/roles/lib_openshift/src/test/unit/oc_serviceaccount_secret.py b/roles/lib_openshift/src/test/unit/oc_serviceaccount_secret.py
index 342da961b..4d555d412 100755
--- a/roles/lib_openshift/src/test/unit/oc_serviceaccount_secret.py
+++ b/roles/lib_openshift/src/test/unit/oc_serviceaccount_secret.py
@@ -35,9 +35,10 @@ class OCServiceAccountSecretTest(unittest.TestCase):
''' setup method will create a file and set to known configuration '''
pass
+ @mock.patch('oc_serviceaccount_secret.Utils.create_tmpfile_copy')
@mock.patch('oc_serviceaccount_secret.Yedit._write')
@mock.patch('oc_serviceaccount_secret.OCServiceAccountSecret._run')
- def test_adding_a_secret_to_a_serviceaccount(self, mock_cmd, mock_write):
+ def test_adding_a_secret_to_a_serviceaccount(self, mock_cmd, mock_write, mock_tmpfile_copy):
''' Testing adding a secret to a service account '''
# Arrange
@@ -137,6 +138,10 @@ metadata:
(0, oc_get_sa_after, ''), # Fourth call to the mock
]
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
+ ]
+
# Act
results = OCServiceAccountSecret.run_ansible(params, False)
@@ -149,18 +154,19 @@ metadata:
mock_cmd.assert_has_calls([
mock.call(['oc', '-n', 'default', 'get', 'sa', 'builder', '-o', 'json'], None),
mock.call(['oc', '-n', 'default', 'get', 'sa', 'builder', '-o', 'json'], None),
- mock.call(['oc', '-n', 'default', 'replace', '-f', '/tmp/builder'], None),
+ mock.call(['oc', '-n', 'default', 'replace', '-f', mock.ANY], None),
mock.call(['oc', '-n', 'default', 'get', 'sa', 'builder', '-o', 'json'], None)
])
mock_write.assert_has_calls([
- mock.call('/tmp/builder', builder_yaml_file)
+ mock.call(mock.ANY, builder_yaml_file)
])
+ @mock.patch('oc_serviceaccount_secret.Utils.create_tmpfile_copy')
@mock.patch('oc_serviceaccount_secret.Yedit._write')
@mock.patch('oc_serviceaccount_secret.OCServiceAccountSecret._run')
- def test_removing_a_secret_to_a_serviceaccount(self, mock_cmd, mock_write):
- ''' Testing adding a secret to a service account '''
+ def test_removing_a_secret_to_a_serviceaccount(self, mock_cmd, mock_write, mock_tmpfile_copy):
+ ''' Testing removing a secret to a service account '''
# Arrange
@@ -229,6 +235,10 @@ metadata:
(0, 'serviceaccount "builder" replaced', ''), # Third call to the mock
]
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
+ ]
+
# Act
results = OCServiceAccountSecret.run_ansible(params, False)
@@ -241,11 +251,11 @@ metadata:
mock_cmd.assert_has_calls([
mock.call(['oc', '-n', 'default', 'get', 'sa', 'builder', '-o', 'json'], None),
mock.call(['oc', '-n', 'default', 'get', 'sa', 'builder', '-o', 'json'], None),
- mock.call(['oc', '-n', 'default', 'replace', '-f', '/tmp/builder'], None),
+ mock.call(['oc', '-n', 'default', 'replace', '-f', mock.ANY], None),
])
mock_write.assert_has_calls([
- mock.call('/tmp/builder', builder_yaml_file)
+ mock.call(mock.ANY, builder_yaml_file)
])
def tearDown(self):
diff --git a/roles/lib_openshift/src/test/unit/oc_version.py b/roles/lib_openshift/src/test/unit/oc_version.py
index f927948be..67dea415b 100755
--- a/roles/lib_openshift/src/test/unit/oc_version.py
+++ b/roles/lib_openshift/src/test/unit/oc_version.py
@@ -35,8 +35,9 @@ class OCVersionTest(unittest.TestCase):
''' setup method will create a file and set to known configuration '''
pass
+ @mock.patch('oc_version.Utils.create_tmpfile_copy')
@mock.patch('oc_version.OCVersion.openshift_cmd')
- def test_get(self, mock_openshift_cmd):
+ def test_get(self, mock_openshift_cmd, mock_tmpfile_copy):
''' Testing a get '''
params = {'kubeconfig': '/etc/origin/master/admin.kubeconfig',
'state': 'list',
@@ -52,6 +53,10 @@ class OCVersionTest(unittest.TestCase):
"returncode": 0}
]
+ mock_tmpfile_copy.side_effect = [
+ '/tmp/mocked_kubeconfig',
+ ]
+
results = OCVersion.run_ansible(params)
self.assertFalse(results['changed'])