From c321abec1294f0a76defa9b794edfbf05cded588 Mon Sep 17 00:00:00 2001 From: Rodolfo Carvalho Date: Sat, 18 Feb 2017 19:24:38 +0100 Subject: Fix tests on Python 3 Unlike in Python 2: - `range` doesn't return a list. - `dict.keys` doesn't return a list. --- roles/lib_utils/library/repoquery.py | 2 +- roles/lib_utils/src/test/unit/yedit_test.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'roles') diff --git a/roles/lib_utils/library/repoquery.py b/roles/lib_utils/library/repoquery.py index cc7aa04fd..f31c8911b 100644 --- a/roles/lib_utils/library/repoquery.py +++ b/roles/lib_utils/library/repoquery.py @@ -477,7 +477,7 @@ class Repoquery(RepoqueryCLI): ''' Gather and present the versions of each package ''' versions_dict = {} - versions_dict['available_versions_full'] = formatted_versions.keys() + versions_dict['available_versions_full'] = list(formatted_versions.keys()) # set the match version, if called if self.match_version: diff --git a/roles/lib_utils/src/test/unit/yedit_test.py b/roles/lib_utils/src/test/unit/yedit_test.py index 2793c5c1a..ed07ac96e 100755 --- a/roles/lib_utils/src/test/unit/yedit_test.py +++ b/roles/lib_utils/src/test/unit/yedit_test.py @@ -256,7 +256,7 @@ class YeditTest(unittest.TestCase): def test_pop_list_item_2(self): '''test dict value with none value''' - z = range(10) + z = list(range(10)) yed = Yedit(content=z, separator=':') yed.pop('', 5) z.pop(5) -- cgit v1.2.3 From 6ea3e740607297a9800a6ef24d6c07dfae1c873d Mon Sep 17 00:00:00 2001 From: Rodolfo Carvalho Date: Sat, 18 Feb 2017 19:52:37 +0100 Subject: Include missing unit tests to test runner config We were not running those tests in CI, bad :( --- .../src/test/unit/oadm_manage_node.py | 188 -------- roles/lib_openshift/src/test/unit/oc_env.py | 444 ------------------- roles/lib_openshift/src/test/unit/oc_label.py | 196 --------- roles/lib_openshift/src/test/unit/oc_process.py | 483 --------------------- roles/lib_openshift/src/test/unit/oc_route.py | 268 ------------ roles/lib_openshift/src/test/unit/oc_scale.py | 167 ------- roles/lib_openshift/src/test/unit/oc_secret.py | 96 ---- roles/lib_openshift/src/test/unit/oc_service.py | 216 --------- .../src/test/unit/oc_serviceaccount.py | 119 ----- .../src/test/unit/oc_serviceaccount_secret.py | 315 -------------- roles/lib_openshift/src/test/unit/oc_version.py | 73 ---- .../src/test/unit/test_oadm_manage_node.py | 188 ++++++++ roles/lib_openshift/src/test/unit/test_oc_env.py | 444 +++++++++++++++++++ roles/lib_openshift/src/test/unit/test_oc_label.py | 196 +++++++++ .../lib_openshift/src/test/unit/test_oc_process.py | 483 +++++++++++++++++++++ roles/lib_openshift/src/test/unit/test_oc_route.py | 268 ++++++++++++ roles/lib_openshift/src/test/unit/test_oc_scale.py | 167 +++++++ .../lib_openshift/src/test/unit/test_oc_secret.py | 96 ++++ .../lib_openshift/src/test/unit/test_oc_service.py | 216 +++++++++ .../src/test/unit/test_oc_serviceaccount.py | 119 +++++ .../src/test/unit/test_oc_serviceaccount_secret.py | 315 ++++++++++++++ .../lib_openshift/src/test/unit/test_oc_version.py | 73 ++++ roles/lib_utils/src/test/unit/repoquery.py | 87 ---- roles/lib_utils/src/test/unit/test_repoquery.py | 87 ++++ roles/lib_utils/src/test/unit/test_yedit.py | 277 ++++++++++++ roles/lib_utils/src/test/unit/yedit_test.py | 277 ------------ 26 files changed, 2929 insertions(+), 2929 deletions(-) delete mode 100755 roles/lib_openshift/src/test/unit/oadm_manage_node.py delete mode 100755 roles/lib_openshift/src/test/unit/oc_env.py delete mode 100755 roles/lib_openshift/src/test/unit/oc_label.py delete mode 100755 roles/lib_openshift/src/test/unit/oc_process.py delete mode 100755 roles/lib_openshift/src/test/unit/oc_route.py delete mode 100755 roles/lib_openshift/src/test/unit/oc_scale.py delete mode 100755 roles/lib_openshift/src/test/unit/oc_secret.py delete mode 100755 roles/lib_openshift/src/test/unit/oc_service.py delete mode 100755 roles/lib_openshift/src/test/unit/oc_serviceaccount.py delete mode 100755 roles/lib_openshift/src/test/unit/oc_serviceaccount_secret.py delete mode 100755 roles/lib_openshift/src/test/unit/oc_version.py create mode 100755 roles/lib_openshift/src/test/unit/test_oadm_manage_node.py create mode 100755 roles/lib_openshift/src/test/unit/test_oc_env.py create mode 100755 roles/lib_openshift/src/test/unit/test_oc_label.py create mode 100755 roles/lib_openshift/src/test/unit/test_oc_process.py create mode 100755 roles/lib_openshift/src/test/unit/test_oc_route.py create mode 100755 roles/lib_openshift/src/test/unit/test_oc_scale.py create mode 100755 roles/lib_openshift/src/test/unit/test_oc_secret.py create mode 100755 roles/lib_openshift/src/test/unit/test_oc_service.py create mode 100755 roles/lib_openshift/src/test/unit/test_oc_serviceaccount.py create mode 100755 roles/lib_openshift/src/test/unit/test_oc_serviceaccount_secret.py create mode 100755 roles/lib_openshift/src/test/unit/test_oc_version.py delete mode 100755 roles/lib_utils/src/test/unit/repoquery.py create mode 100755 roles/lib_utils/src/test/unit/test_repoquery.py create mode 100755 roles/lib_utils/src/test/unit/test_yedit.py delete mode 100755 roles/lib_utils/src/test/unit/yedit_test.py (limited to 'roles') diff --git a/roles/lib_openshift/src/test/unit/oadm_manage_node.py b/roles/lib_openshift/src/test/unit/oadm_manage_node.py deleted file mode 100755 index b0786dfac..000000000 --- a/roles/lib_openshift/src/test/unit/oadm_manage_node.py +++ /dev/null @@ -1,188 +0,0 @@ -#!/usr/bin/env python2 -''' - Unit tests for oadm_manage_node -''' -# To run -# python -m unittest version -# -# . -# Ran 2 tests in 0.001s -# -# OK - -import os -import sys -import unittest -import mock - -# Removing invalid variable names for tests so that I can -# keep them brief -# pylint: disable=invalid-name,no-name-in-module -# Disable import-error b/c our libraries aren't loaded in jenkins -# pylint: disable=import-error -# place class in our python path -module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 -sys.path.insert(0, module_path) -from oadm_manage_node import ManageNode # noqa: E402 - - -class ManageNodeTest(unittest.TestCase): - ''' - Test class for oadm_manage_node - ''' - - def setUp(self): - ''' 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, mock_tmpfile_copy): - ''' Testing a get ''' - params = {'node': ['ip-172-31-49-140.ec2.internal'], - 'schedulable': None, - 'selector': None, - 'pod_selector': None, - 'list_pods': True, - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'evacuate': False, - 'grace_period': False, - 'dry_run': False, - 'force': False} - - pod_list = '''{ - "metadata": {}, - "items": [ - { - "metadata": { - "name": "docker-registry-1-xuhik", - "generateName": "docker-registry-1-", - "namespace": "default", - "selfLink": "/api/v1/namespaces/default/pods/docker-registry-1-xuhik", - "uid": "ae2a25a2-e316-11e6-80eb-0ecdc51fcfc4", - "resourceVersion": "1501", - "creationTimestamp": "2017-01-25T15:55:23Z", - "labels": { - "deployment": "docker-registry-1", - "deploymentconfig": "docker-registry", - "docker-registry": "default" - }, - "annotations": { - "openshift.io/deployment-config.latest-version": "1", - "openshift.io/deployment-config.name": "docker-registry", - "openshift.io/deployment.name": "docker-registry-1", - "openshift.io/scc": "restricted" - } - }, - "spec": {} - }, - { - "metadata": { - "name": "router-1-kp3m3", - "generateName": "router-1-", - "namespace": "default", - "selfLink": "/api/v1/namespaces/default/pods/router-1-kp3m3", - "uid": "9e71f4a5-e316-11e6-80eb-0ecdc51fcfc4", - "resourceVersion": "1456", - "creationTimestamp": "2017-01-25T15:54:56Z", - "labels": { - "deployment": "router-1", - "deploymentconfig": "router", - "router": "router" - }, - "annotations": { - "openshift.io/deployment-config.latest-version": "1", - "openshift.io/deployment-config.name": "router", - "openshift.io/deployment.name": "router-1", - "openshift.io/scc": "hostnetwork" - } - }, - "spec": {} - }] -}''' - - mock_openshift_cmd.side_effect = [ - {"cmd": "/usr/bin/oadm manage-node ip-172-31-49-140.ec2.internal --list-pods", - "results": pod_list, - "returncode": 0} - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mocked_kubeconfig', - ] - - results = ManageNode.run_ansible(params, False) - - # returned a single node - self.assertTrue(len(results['results']['nodes']) == 1) - # 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, mock_tmpfile_copy): - ''' Testing a get ''' - params = {'node': ['ip-172-31-49-140.ec2.internal'], - 'schedulable': False, - 'selector': None, - 'pod_selector': None, - 'list_pods': False, - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'evacuate': False, - 'grace_period': False, - 'dry_run': False, - 'force': False} - - node = [{ - "apiVersion": "v1", - "kind": "Node", - "metadata": { - "creationTimestamp": "2017-01-26T14:34:43Z", - "labels": { - "beta.kubernetes.io/arch": "amd64", - "beta.kubernetes.io/instance-type": "m4.large", - "beta.kubernetes.io/os": "linux", - "failure-domain.beta.kubernetes.io/region": "us-east-1", - "failure-domain.beta.kubernetes.io/zone": "us-east-1c", - "hostname": "opstest-node-compute-0daaf", - "kubernetes.io/hostname": "ip-172-31-51-111.ec2.internal", - "ops_node": "old", - "region": "us-east-1", - "type": "compute" - }, - "name": "ip-172-31-51-111.ec2.internal", - "resourceVersion": "6936", - "selfLink": "/api/v1/nodes/ip-172-31-51-111.ec2.internal", - "uid": "93d7fdfb-e3d4-11e6-a982-0e84250fc302" - }, - "spec": { - "externalID": "i-06bb330e55c699b0f", - "providerID": "aws:///us-east-1c/i-06bb330e55c699b0f", - }}] - - mock_openshift_cmd.side_effect = [ - {"cmd": "/usr/bin/oc get node -o json ip-172-31-49-140.ec2.internal", - "results": node, - "returncode": 0}, - {"cmd": "/usr/bin/oadm manage-node ip-172-31-49-140.ec2.internal --schedulable=False", - "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']) - self.assertEqual(results['results']['nodes'][0]['name'], 'ip-172-31-49-140.ec2.internal') - self.assertEqual(results['results']['nodes'][0]['schedulable'], False) - - def tearDown(self): - '''TearDown method''' - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/roles/lib_openshift/src/test/unit/oc_env.py b/roles/lib_openshift/src/test/unit/oc_env.py deleted file mode 100755 index 15bd7e464..000000000 --- a/roles/lib_openshift/src/test/unit/oc_env.py +++ /dev/null @@ -1,444 +0,0 @@ -#!/usr/bin/env python2 -''' - Unit tests for oc_env -''' -# To run: -# ./oc_env.py -# -# . -# Ran 1 test in 0.002s -# -# OK - -import os -import sys -import unittest -import mock - -# Removing invalid variable names for tests so that I can -# keep them brief -# pylint: disable=invalid-name,no-name-in-module -# Disable import-error b/c our libraries aren't loaded in jenkins -# pylint: disable=import-error,wrong-import-position -# place class in our python path -module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 -sys.path.insert(0, module_path) -from oc_env import OCEnv # noqa: E402 - - -class OCEnvTest(unittest.TestCase): - ''' - Test class for OCEnv - ''' - - def setUp(self): - ''' setup method will create a file and set to known configuration ''' - pass - - @mock.patch('oc_env.Utils.create_tmpfile_copy') - @mock.patch('oc_env.OCEnv._run') - def test_listing_all_env_vars(self, mock_cmd, mock_tmpfile_copy): - ''' Testing listing all environment variables from a dc''' - - # Arrange - - # run_ansible input parameters - params = { - 'state': 'list', - 'namespace': 'default', - 'name': 'router', - 'kind': 'dc', - 'env_vars': None, - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False, - } - - dc_results = '''{ - "apiVersion": "v1", - "kind": "DeploymentConfig", - "metadata": { - "creationTimestamp": "2017-02-02T15:58:49Z", - "generation": 8, - "labels": { - "router": "router" - }, - "name": "router", - "namespace": "default", - "resourceVersion": "513678" - }, - "spec": { - "replicas": 2, - "selector": { - "router": "router" - }, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "router": "router" - } - }, - "spec": { - "containers": [ - { - "env": [ - { - "name": "DEFAULT_CERTIFICATE_DIR", - "value": "/etc/pki/tls/private" - }, - { - "name": "DEFAULT_CERTIFICATE_PATH", - "value": "/etc/pki/tls/private/tls.crt" - }, - { - "name": "ROUTER_EXTERNAL_HOST_HOSTNAME" - }, - { - "name": "ROUTER_EXTERNAL_HOST_HTTPS_VSERVER" - }, - { - "name": "ROUTER_EXTERNAL_HOST_HTTP_VSERVER" - }, - { - "name": "ROUTER_EXTERNAL_HOST_INSECURE", - "value": "false" - } - ], - "name": "router" - } - ] - } - }, - "test": false, - "triggers": [ - { - "type": "ConfigChange" - } - ] - } - }''' - - # Return values of our mocked function call. These get returned once per call. - mock_cmd.side_effect = [ - (0, dc_results, ''), # First call to the mock - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mock_adminkubeconfig', - ] - - # Act - results = OCEnv.run_ansible(params, False) - - # Assert - self.assertFalse(results['changed']) - for env_var in results['results']: - if env_var == {'name': 'DEFAULT_CERTIFICATE_DIR', 'value': '/etc/pki/tls/private'}: - break - else: - self.fail('Did not find environment variables in results.') - self.assertEqual(results['state'], 'list') - - # Making sure our mocks were called as we expected - mock_cmd.assert_has_calls([ - mock.call(['oc', '-n', 'default', 'get', 'dc', 'router', '-o', 'json'], None), - ]) - - @mock.patch('oc_env.Utils.create_tmpfile_copy') - @mock.patch('oc_env.OCEnv._run') - def test_adding_env_vars(self, mock_cmd, mock_tmpfile_copy): - ''' Test add environment variables to a dc''' - - # Arrange - - # run_ansible input parameters - params = { - 'state': 'present', - 'namespace': 'default', - 'name': 'router', - 'kind': 'dc', - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False, - 'env_vars': {'SOMEKEY': 'SOMEVALUE'}, - } - - dc_results = '''{ - "apiVersion": "v1", - "kind": "DeploymentConfig", - "metadata": { - "creationTimestamp": "2017-02-02T15:58:49Z", - "generation": 8, - "labels": { - "router": "router" - }, - "name": "router", - "namespace": "default", - "resourceVersion": "513678" - }, - "spec": { - "replicas": 2, - "selector": { - "router": "router" - }, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "router": "router" - } - }, - "spec": { - "containers": [ - { - "env": [ - { - "name": "DEFAULT_CERTIFICATE_DIR", - "value": "/etc/pki/tls/private" - }, - { - "name": "DEFAULT_CERTIFICATE_PATH", - "value": "/etc/pki/tls/private/tls.crt" - }, - { - "name": "ROUTER_EXTERNAL_HOST_HOSTNAME" - }, - { - "name": "ROUTER_EXTERNAL_HOST_HTTPS_VSERVER" - }, - { - "name": "ROUTER_EXTERNAL_HOST_HTTP_VSERVER" - }, - { - "name": "ROUTER_EXTERNAL_HOST_INSECURE", - "value": "false" - } - ], - "name": "router" - } - ] - } - }, - "test": false, - "triggers": [ - { - "type": "ConfigChange" - } - ] - } - }''' - - dc_results_after = '''{ - "apiVersion": "v1", - "kind": "DeploymentConfig", - "metadata": { - "creationTimestamp": "2017-02-02T15:58:49Z", - "generation": 8, - "labels": { - "router": "router" - }, - "name": "router", - "namespace": "default", - "resourceVersion": "513678" - }, - "spec": { - "replicas": 2, - "selector": { - "router": "router" - }, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "router": "router" - } - }, - "spec": { - "containers": [ - { - "env": [ - { - "name": "DEFAULT_CERTIFICATE_DIR", - "value": "/etc/pki/tls/private" - }, - { - "name": "DEFAULT_CERTIFICATE_PATH", - "value": "/etc/pki/tls/private/tls.crt" - }, - { - "name": "ROUTER_EXTERNAL_HOST_HOSTNAME" - }, - { - "name": "ROUTER_EXTERNAL_HOST_HTTPS_VSERVER" - }, - { - "name": "ROUTER_EXTERNAL_HOST_HTTP_VSERVER" - }, - { - "name": "ROUTER_EXTERNAL_HOST_INSECURE", - "value": "false" - }, - { - "name": "SOMEKEY", - "value": "SOMEVALUE" - } - ], - "name": "router" - } - ] - } - }, - "test": false, - "triggers": [ - { - "type": "ConfigChange" - } - ] - } - }''' - - # Return values of our mocked function call. These get returned once per call. - mock_cmd.side_effect = [ - (0, dc_results, ''), - (0, dc_results, ''), - (0, dc_results_after, ''), - (0, dc_results_after, ''), - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mock_adminkubeconfig', - ] - - # Act - results = OCEnv.run_ansible(params, False) - - # Assert - self.assertTrue(results['changed']) - for env_var in results['results']: - if env_var == {'name': 'SOMEKEY', 'value': 'SOMEVALUE'}: - break - else: - self.fail('Did not find environment variables in results.') - self.assertEqual(results['state'], 'present') - - # Making sure our mocks were called as we expected - mock_cmd.assert_has_calls([ - mock.call(['oc', '-n', 'default', 'get', 'dc', 'router', '-o', 'json'], None), - ]) - - @mock.patch('oc_env.Utils.create_tmpfile_copy') - @mock.patch('oc_env.OCEnv._run') - def test_removing_env_vars(self, mock_cmd, mock_tmpfile_copy): - ''' Test add environment variables to a dc''' - - # Arrange - - # run_ansible input parameters - params = { - 'state': 'absent', - 'namespace': 'default', - 'name': 'router', - 'kind': 'dc', - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False, - 'env_vars': {'SOMEKEY': 'SOMEVALUE'}, - } - - dc_results_before = '''{ - "apiVersion": "v1", - "kind": "DeploymentConfig", - "metadata": { - "creationTimestamp": "2017-02-02T15:58:49Z", - "generation": 8, - "labels": { - "router": "router" - }, - "name": "router", - "namespace": "default", - "resourceVersion": "513678" - }, - "spec": { - "replicas": 2, - "selector": { - "router": "router" - }, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "router": "router" - } - }, - "spec": { - "containers": [ - { - "env": [ - { - "name": "DEFAULT_CERTIFICATE_DIR", - "value": "/etc/pki/tls/private" - }, - { - "name": "DEFAULT_CERTIFICATE_PATH", - "value": "/etc/pki/tls/private/tls.crt" - }, - { - "name": "ROUTER_EXTERNAL_HOST_HOSTNAME" - }, - { - "name": "ROUTER_EXTERNAL_HOST_HTTPS_VSERVER" - }, - { - "name": "ROUTER_EXTERNAL_HOST_HTTP_VSERVER" - }, - { - "name": "ROUTER_EXTERNAL_HOST_INSECURE", - "value": "false" - }, - { - "name": "SOMEKEY", - "value": "SOMEVALUE" - } - ], - "name": "router" - } - ] - } - }, - "test": false, - "triggers": [ - { - "type": "ConfigChange" - } - ] - } - }''' - - # Return values of our mocked function call. These get returned once per call. - mock_cmd.side_effect = [ - (0, dc_results_before, ''), - (0, dc_results_before, ''), - (0, '', ''), - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mock_adminkubeconfig', - ] - - # Act - results = OCEnv.run_ansible(params, False) - - # Assert - self.assertTrue(results['changed']) - self.assertEqual(results['state'], 'absent') - - # Making sure our mocks were called as we expected - mock_cmd.assert_has_calls([ - mock.call(['oc', '-n', 'default', 'get', 'dc', 'router', '-o', 'json'], None), - ]) - - def tearDown(self): - '''TearDown method''' - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/roles/lib_openshift/src/test/unit/oc_label.py b/roles/lib_openshift/src/test/unit/oc_label.py deleted file mode 100755 index 3176987b0..000000000 --- a/roles/lib_openshift/src/test/unit/oc_label.py +++ /dev/null @@ -1,196 +0,0 @@ -#!/usr/bin/env python2 -''' - Unit tests for oc label -''' -# To run -# python -m unittest version -# -# . -# Ran 1 test in 0.597s -# -# OK - -import os -import sys -import unittest -import mock - -# Removing invalid variable names for tests so that I can -# keep them brief -# pylint: disable=invalid-name,no-name-in-module -# Disable import-error b/c our libraries aren't loaded in jenkins -# pylint: disable=import-error -# place class in our python path -module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 -sys.path.insert(0, module_path) -from oc_label import OCLabel # noqa: E402 - - -class OCLabelTest(unittest.TestCase): - ''' - Test class for OCLabel - ''' - - def setUp(self): - ''' 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, mock_tmpfile_copy): - ''' Testing a label list ''' - params = {'name': 'default', - 'namespace': 'default', - 'labels': None, - 'state': 'list', - 'kind': 'namespace', - 'selector': None, - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False} - - ns = '''{ - "kind": "Namespace", - "apiVersion": "v1", - "metadata": { - "name": "default", - "selfLink": "/api/v1/namespaces/default", - "uid": "c45b9547-e3d3-11e6-ba9c-0eece8f2ce22", - "resourceVersion": "403024", - "creationTimestamp": "2017-01-26T14:28:55Z", - "labels": { - "storage_pv_quota": "False" - }, - "annotations": { - "openshift.io/node-selector": "", - "openshift.io/sa.initialized-roles": "true", - "openshift.io/sa.scc.mcs": "s0:c1,c0", - "openshift.io/sa.scc.supplemental-groups": "1000000000/10000", - "openshift.io/sa.scc.uid-range": "1000000000/10000" - } - }, - "spec": { - "finalizers": [ - "kubernetes", - "openshift.io/origin" - ] - }, - "status": { - "phase": "Active" - } - }''' - - mock_cmd.side_effect = [ - (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, mock_tmpfile_copy): - ''' Testing a label list ''' - params = {'name': 'default', - 'namespace': 'default', - 'labels': [ - {'key': 'awesomens', 'value': 'testinglabel'}, - {'key': 'storage_pv_quota', 'value': 'False'} - ], - 'state': 'present', - 'kind': 'namespace', - 'selector': None, - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False} - - ns = '''{ - "kind": "Namespace", - "apiVersion": "v1", - "metadata": { - "name": "default", - "selfLink": "/api/v1/namespaces/default", - "uid": "c45b9547-e3d3-11e6-ba9c-0eece8f2ce22", - "resourceVersion": "403024", - "creationTimestamp": "2017-01-26T14:28:55Z", - "labels": { - "storage_pv_quota": "False" - }, - "annotations": { - "openshift.io/node-selector": "", - "openshift.io/sa.initialized-roles": "true", - "openshift.io/sa.scc.mcs": "s0:c1,c0", - "openshift.io/sa.scc.supplemental-groups": "1000000000/10000", - "openshift.io/sa.scc.uid-range": "1000000000/10000" - } - }, - "spec": { - "finalizers": [ - "kubernetes", - "openshift.io/origin" - ] - }, - "status": { - "phase": "Active" - } - }''' - - ns1 = '''{ - "kind": "Namespace", - "apiVersion": "v1", - "metadata": { - "name": "default", - "selfLink": "/api/v1/namespaces/default", - "uid": "c45b9547-e3d3-11e6-ba9c-0eece8f2ce22", - "resourceVersion": "403024", - "creationTimestamp": "2017-01-26T14:28:55Z", - "labels": { - "storage_pv_quota": "False", - "awesomens": "testinglabel" - }, - "annotations": { - "openshift.io/node-selector": "", - "openshift.io/sa.initialized-roles": "true", - "openshift.io/sa.scc.mcs": "s0:c1,c0", - "openshift.io/sa.scc.supplemental-groups": "1000000000/10000", - "openshift.io/sa.scc.uid-range": "1000000000/10000" - } - }, - "spec": { - "finalizers": [ - "kubernetes", - "openshift.io/origin" - ] - }, - "status": { - "phase": "Active" - } - }''' - - mock_cmd.side_effect = [ - (0, ns, ''), - (0, '', ''), - (0, ns1, ''), - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mocked_kubeconfig', - ] - - results = OCLabel.run_ansible(params, False) - - self.assertTrue(results['changed']) - self.assertTrue(results['results']['results']['labels'][0] == - {'storage_pv_quota': 'False', 'awesomens': 'testinglabel'}) - - def tearDown(self): - '''TearDown method''' - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/roles/lib_openshift/src/test/unit/oc_process.py b/roles/lib_openshift/src/test/unit/oc_process.py deleted file mode 100755 index 450ff7071..000000000 --- a/roles/lib_openshift/src/test/unit/oc_process.py +++ /dev/null @@ -1,483 +0,0 @@ -#!/usr/bin/env python2 -''' - Unit tests for oc process -''' -# To run -# python -m unittest version -# -# . -# Ran 1 test in 0.597s -# -# OK - -import os -import sys -import unittest -import mock - -# Removing invalid variable names for tests so that I can -# keep them brief -# pylint: disable=invalid-name,no-name-in-module -# Disable import-error b/c our libraries aren't loaded in jenkins -# pylint: disable=import-error -# place class in our python path -module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 -sys.path.insert(0, module_path) -from oc_process import OCProcess # noqa: E402 - - -# pylint: disable=too-many-public-methods -class OCProcessTest(unittest.TestCase): - ''' - Test class for OCProcess - ''' - mysql = '''{ - "kind": "Template", - "apiVersion": "v1", - "metadata": { - "name": "mysql-ephemeral", - "namespace": "openshift", - "selfLink": "/oapi/v1/namespaces/openshift/templates/mysql-ephemeral", - "uid": "fb8b5f04-e3d3-11e6-a982-0e84250fc302", - "resourceVersion": "480", - "creationTimestamp": "2017-01-26T14:30:27Z", - "annotations": { - "iconClass": "icon-mysql-database", - "openshift.io/display-name": "MySQL (Ephemeral)", - "tags": "database,mysql" - } - }, - "objects": [ - { - "apiVersion": "v1", - "kind": "Service", - "metadata": { - "creationTimestamp": null, - "name": "${DATABASE_SERVICE_NAME}" - }, - "spec": { - "ports": [ - { - "name": "mysql", - "nodePort": 0, - "port": 3306, - "protocol": "TCP", - "targetPort": 3306 - } - ], - "selector": { - "name": "${DATABASE_SERVICE_NAME}" - }, - "sessionAffinity": "None", - "type": "ClusterIP" - }, - "status": { - "loadBalancer": {} - } - }, - { - "apiVersion": "v1", - "kind": "DeploymentConfig", - "metadata": { - "creationTimestamp": null, - "name": "${DATABASE_SERVICE_NAME}" - }, - "spec": { - "replicas": 1, - "selector": { - "name": "${DATABASE_SERVICE_NAME}" - }, - "strategy": { - "type": "Recreate" - }, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "name": "${DATABASE_SERVICE_NAME}" - } - }, - "spec": { - "containers": [ - { - "capabilities": {}, - "env": [ - { - "name": "MYSQL_USER", - "value": "${MYSQL_USER}" - }, - { - "name": "MYSQL_PASSWORD", - "value": "${MYSQL_PASSWORD}" - }, - { - "name": "MYSQL_DATABASE", - "value": "${MYSQL_DATABASE}" - } - ], - "image": " ", - "imagePullPolicy": "IfNotPresent", - "livenessProbe": { - "initialDelaySeconds": 30, - "tcpSocket": { - "port": 3306 - }, - "timeoutSeconds": 1 - }, - "name": "mysql", - "ports": [ - { - "containerPort": 3306, - "protocol": "TCP" - } - ], - "readinessProbe": { - "exec": { - "command": [ - "/bin/sh", - "-i", - "-c", - "MYSQL_PWD=$MYSQL_PASSWORD mysql -h 127.0.0.1 -u $MYSQL_USER -D $MYSQL_DATABASE -e 'SELECT 1'" - ] - }, - "initialDelaySeconds": 5, - "timeoutSeconds": 1 - }, - "resources": { - "limits": { - "memory": "${MEMORY_LIMIT}" - } - }, - "securityContext": { - "capabilities": {}, - "privileged": false - }, - "terminationMessagePath": "/dev/termination-log", - "volumeMounts": [ - { - "mountPath": "/var/lib/mysql/data", - "name": "${DATABASE_SERVICE_NAME}-data" - } - ] - } - ], - "dnsPolicy": "ClusterFirst", - "restartPolicy": "Always", - "volumes": [ - { - "emptyDir": { - "medium": "" - }, - "name": "${DATABASE_SERVICE_NAME}-data" - } - ] - } - }, - "triggers": [ - { - "imageChangeParams": { - "automatic": true, - "containerNames": [ - "mysql" - ], - "from": { - "kind": "ImageStreamTag", - "name": "mysql:${MYSQL_VERSION}", - "namespace": "${NAMESPACE}" - }, - "lastTriggeredImage": "" - }, - "type": "ImageChange" - }, - { - "type": "ConfigChange" - } - ] - }, - "status": {} - } - ], - "parameters": [ - { - "name": "MEMORY_LIMIT", - "displayName": "Memory Limit", - "description": "Maximum amount of memory the container can use.", - "value": "512Mi" - }, - { - "name": "NAMESPACE", - "displayName": "Namespace", - "description": "The OpenShift Namespace where the ImageStream resides.", - "value": "openshift" - }, - { - "name": "DATABASE_SERVICE_NAME", - "displayName": "Database Service Name", - "description": "The name of the OpenShift Service exposed for the database.", - "value": "mysql", - "required": true - }, - { - "name": "MYSQL_USER", - "displayName": "MySQL Connection Username", - "description": "Username for MySQL user that will be used for accessing the database.", - "generate": "expression", - "from": "user[A-Z0-9]{3}", - "required": true - }, - { - "name": "MYSQL_PASSWORD", - "displayName": "MySQL Connection Password", - "description": "Password for the MySQL connection user.", - "generate": "expression", - "from": "[a-zA-Z0-9]{16}", - "required": true - }, - { - "name": "MYSQL_DATABASE", - "displayName": "MySQL Database Name", - "description": "Name of the MySQL database accessed.", - "value": "sampledb", - "required": true - }, - { - "name": "MYSQL_VERSION", - "displayName": "Version of MySQL Image", - "description": "Version of MySQL image to be used (5.5, 5.6 or latest).", - "value": "5.6", - "required": true - } - ], - "labels": { - "template": "mysql-ephemeral-template" - } -}''' - - def setUp(self): - ''' setup method will set to known configuration ''' - pass - - @mock.patch('oc_process.Utils.create_tmpfile_copy') - @mock.patch('oc_process.OCProcess._run') - def test_state_list(self, mock_cmd, mock_tmpfile_copy): - ''' Testing a get ''' - params = {'template_name': 'mysql-ephermeral', - 'namespace': 'test', - 'content': None, - 'state': 'list', - 'reconcile': False, - 'create': False, - 'params': {'NAMESPACE': 'test', 'DATABASE_SERVICE_NAME': 'testdb'}, - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False} - - mock_cmd.side_effect = [ - (0, OCProcessTest.mysql, '') - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mock_kubeconfig', - ] - - results = OCProcess.run_ansible(params, False) - - self.assertFalse(results['changed']) - self.assertEqual(results['results']['results'][0]['metadata']['name'], 'mysql-ephemeral') - - @mock.patch('oc_process.Utils.create_tmpfile_copy') - @mock.patch('oc_process.OCProcess._run') - def test_process_no_create(self, mock_cmd, mock_tmpfile_copy): - ''' Testing a process with no create ''' - params = {'template_name': 'mysql-ephermeral', - 'namespace': 'test', - 'content': None, - 'state': 'present', - 'reconcile': False, - 'create': False, - 'params': {'NAMESPACE': 'test', 'DATABASE_SERVICE_NAME': 'testdb'}, - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False} - - mysqlproc = '''{ - "kind": "List", - "apiVersion": "v1", - "metadata": {}, - "items": [ - { - "apiVersion": "v1", - "kind": "Service", - "metadata": { - "creationTimestamp": null, - "labels": { - "template": "mysql-ephemeral-template" - }, - "name": "testdb" - }, - "spec": { - "ports": [ - { - "name": "mysql", - "nodePort": 0, - "port": 3306, - "protocol": "TCP", - "targetPort": 3306 - } - ], - "selector": { - "name": "testdb" - }, - "sessionAffinity": "None", - "type": "ClusterIP" - }, - "status": { - "loadBalancer": {} - } - }, - { - "apiVersion": "v1", - "kind": "DeploymentConfig", - "metadata": { - "creationTimestamp": null, - "labels": { - "template": "mysql-ephemeral-template" - }, - "name": "testdb" - }, - "spec": { - "replicas": 1, - "selector": { - "name": "testdb" - }, - "strategy": { - "type": "Recreate" - }, - "template": { - "metadata": { - "creationTimestamp": null, - "labels": { - "name": "testdb" - } - }, - "spec": { - "containers": [ - { - "capabilities": {}, - "env": [ - { - "name": "MYSQL_USER", - "value": "userHJJ" - }, - { - "name": "MYSQL_PASSWORD", - "value": "GITOAduAMaV6k688" - }, - { - "name": "MYSQL_DATABASE", - "value": "sampledb" - } - ], - "image": " ", - "imagePullPolicy": "IfNotPresent", - "livenessProbe": { - "initialDelaySeconds": 30, - "tcpSocket": { - "port": 3306 - }, - "timeoutSeconds": 1 - }, - "name": "mysql", - "ports": [ - { - "containerPort": 3306, - "protocol": "TCP" - } - ], - "readinessProbe": { - "exec": { - "command": [ - "/bin/sh", - "-i", - "-c", - "MYSQL_PWD=$MYSQL_PASSWORD mysql -h 127.0.0.1 -u $MYSQL_USER -D $MYSQL_DATABASE -e 'SELECT 1'" - ] - }, - "initialDelaySeconds": 5, - "timeoutSeconds": 1 - }, - "resources": { - "limits": { - "memory": "512Mi" - } - }, - "securityContext": { - "capabilities": {}, - "privileged": false - }, - "terminationMessagePath": "/dev/termination-log", - "volumeMounts": [ - { - "mountPath": "/var/lib/mysql/data", - "name": "testdb-data" - } - ] - } - ], - "dnsPolicy": "ClusterFirst", - "restartPolicy": "Always", - "volumes": [ - { - "emptyDir": { - "medium": "" - }, - "name": "testdb-data" - } - ] - } - }, - "triggers": [ - { - "imageChangeParams": { - "automatic": true, - "containerNames": [ - "mysql" - ], - "from": { - "kind": "ImageStreamTag", - "name": "mysql:5.6", - "namespace": "test" - }, - "lastTriggeredImage": "" - }, - "type": "ImageChange" - }, - { - "type": "ConfigChange" - } - ] - } - } - ] -}''' - - mock_cmd.side_effect = [ - (0, OCProcessTest.mysql, ''), - (0, OCProcessTest.mysql, ''), - (0, mysqlproc, ''), - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mock_kubeconfig', - ] - - results = OCProcess.run_ansible(params, False) - - self.assertFalse(results['changed']) - self.assertEqual(results['results']['results']['items'][0]['metadata']['name'], 'testdb') - - def tearDown(self): - '''TearDown method''' - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/roles/lib_openshift/src/test/unit/oc_route.py b/roles/lib_openshift/src/test/unit/oc_route.py deleted file mode 100755 index 361b61f4b..000000000 --- a/roles/lib_openshift/src/test/unit/oc_route.py +++ /dev/null @@ -1,268 +0,0 @@ -#!/usr/bin/env python2 -''' - Unit tests for oc route -''' -# To run: -# ./oc_serviceaccount.py -# -# . -# Ran 1 test in 0.002s -# -# OK - -import os -import sys -import unittest -import mock - -# Removing invalid variable names for tests so that I can -# keep them brief -# pylint: disable=invalid-name,no-name-in-module -# Disable import-error b/c our libraries aren't loaded in jenkins -# pylint: disable=import-error,wrong-import-position -# place class in our python path -module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 -sys.path.insert(0, module_path) -from oc_route import OCRoute # noqa: E402 - - -class OCRouteTest(unittest.TestCase): - ''' - Test class for OCServiceAccount - ''' - - def setUp(self): - ''' setup method will create a file and set to known configuration ''' - pass - - @mock.patch('oc_route.Utils.create_tmpfile_copy') - @mock.patch('oc_route.OCRoute._run') - def test_list_route(self, mock_cmd, mock_tmpfile_copy): - ''' Testing getting a route ''' - - # Arrange - - # run_ansible input parameters - params = { - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'state': 'list', - 'debug': False, - 'name': 'test', - 'namespace': 'default', - 'tls_termination': 'passthrough', - 'dest_cacert_path': None, - 'cacert_path': None, - 'cert_path': None, - 'key_path': None, - 'dest_cacert_content': None, - 'cacert_content': None, - 'cert_content': None, - 'key_content': None, - 'service_name': 'testservice', - 'host': 'test.openshift.com', - 'wildcard_policy': None, - 'weight': None, - 'port': None - } - - route_result = '''{ - "kind": "Route", - "apiVersion": "v1", - "metadata": { - "name": "test", - "namespace": "default", - "selfLink": "/oapi/v1/namespaces/default/routes/test", - "uid": "1b127c67-ecd9-11e6-96eb-0e0d9bdacd26", - "resourceVersion": "439182", - "creationTimestamp": "2017-02-07T01:59:48Z" - }, - "spec": { - "host": "test.example", - "to": { - "kind": "Service", - "name": "test", - "weight": 100 - }, - "port": { - "targetPort": 8443 - }, - "tls": { - "termination": "passthrough" - }, - "wildcardPolicy": "None" - }, - "status": { - "ingress": [ - { - "host": "test.example", - "routerName": "router", - "conditions": [ - { - "type": "Admitted", - "status": "True", - "lastTransitionTime": "2017-02-07T01:59:48Z" - } - ], - "wildcardPolicy": "None" - } - ] - } - }''' - - # Return values of our mocked function call. These get returned once per call. - mock_cmd.side_effect = [ - # First call to mock - (0, route_result, ''), - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mock.kubeconfig', - ] - - # Act - results = OCRoute.run_ansible(params, False) - - # Assert - self.assertFalse(results['changed']) - self.assertEqual(results['state'], 'list') - self.assertEqual(results['results'][0]['metadata']['name'], 'test') - - # Making sure our mock was called as we expected - mock_cmd.assert_has_calls([ - mock.call(['oc', '-n', 'default', 'get', 'route', 'test', '-o', 'json'], None), - ]) - - @mock.patch('oc_route.Utils.create_tmpfile_copy') - @mock.patch('oc_route.Yedit._write') - @mock.patch('oc_route.OCRoute._run') - def test_create_route(self, mock_cmd, mock_write, mock_tmpfile_copy): - ''' Testing getting a route ''' - # Arrange - - # run_ansible input parameters - params = { - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'state': 'present', - 'debug': False, - 'name': 'test', - 'namespace': 'default', - 'tls_termination': 'edge', - 'dest_cacert_path': None, - 'cacert_path': None, - 'cert_path': None, - 'key_path': None, - 'dest_cacert_content': None, - 'cacert_content': 'testing', - 'cert_content': 'testing', - 'key_content': 'testing', - 'service_name': 'testservice', - 'host': 'test.openshift.com', - 'wildcard_policy': None, - 'weight': None, - 'port': None - } - - route_result = '''{ - "apiVersion": "v1", - "kind": "Route", - "metadata": { - "creationTimestamp": "2017-02-07T20:55:10Z", - "name": "test", - "namespace": "default", - "resourceVersion": "517745", - "selfLink": "/oapi/v1/namespaces/default/routes/test", - "uid": "b6f25898-ed77-11e6-9755-0e737db1e63a" - }, - "spec": { - "host": "test.openshift.com", - "tls": { - "caCertificate": "testing", - "certificate": "testing", - "key": "testing", - "termination": "edge" - }, - "to": { - "kind": "Service", - "name": "testservice", - "weight": 100 - }, - "wildcardPolicy": "None" - }, - "status": { - "ingress": [ - { - "conditions": [ - { - "lastTransitionTime": "2017-02-07T20:55:10Z", - "status": "True", - "type": "Admitted" - } - ], - "host": "test.openshift.com", - "routerName": "router", - "wildcardPolicy": "None" - } - ] - } - }''' - - test_route = '''\ -kind: Route -spec: - tls: - caCertificate: testing - termination: edge - certificate: testing - key: testing - to: - kind: Service - name: testservice - weight: 100 - host: test.openshift.com - wildcardPolicy: None -apiVersion: v1 -metadata: - namespace: default - name: test -''' - - # Return values of our mocked function call. These get returned once per call. - mock_cmd.side_effect = [ - # First call to mock - (1, '', 'Error from server: routes "test" not found'), - (1, '', 'Error from server: routes "test" not found'), - (0, 'route "test" created', ''), - (0, route_result, ''), - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mock.kubeconfig', - ] - - mock_write.assert_has_calls = [ - # First call to mock - mock.call('/tmp/test', test_route) - ] - - # Act - results = OCRoute.run_ansible(params, False) - - # Assert - self.assertTrue(results['changed']) - self.assertEqual(results['state'], 'present') - self.assertEqual(results['results']['results'][0]['metadata']['name'], 'test') - - # Making sure our mock was called as we expected - mock_cmd.assert_has_calls([ - mock.call(['oc', '-n', 'default', 'get', 'route', 'test', '-o', 'json'], None), - mock.call(['oc', '-n', 'default', 'create', '-f', mock.ANY], None), - mock.call(['oc', '-n', 'default', 'get', 'route', 'test', '-o', 'json'], None), - ]) - - def tearDown(self): - '''TearDown method''' - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/roles/lib_openshift/src/test/unit/oc_scale.py b/roles/lib_openshift/src/test/unit/oc_scale.py deleted file mode 100755 index f15eb164d..000000000 --- a/roles/lib_openshift/src/test/unit/oc_scale.py +++ /dev/null @@ -1,167 +0,0 @@ -#!/usr/bin/env python2 -''' - Unit tests for oc scale -''' -# To run -# python -m unittest version -# -# . -# Ran 1 test in 0.597s -# -# OK - -import os -import sys -import unittest -import mock - -# Removing invalid variable names for tests so that I can -# keep them brief -# pylint: disable=invalid-name,no-name-in-module -# Disable import-error b/c our libraries aren't loaded in jenkins -# pylint: disable=import-error -# place class in our python path -module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 -sys.path.insert(0, module_path) -from oc_scale import OCScale # noqa: E402 - - -class OCScaleTest(unittest.TestCase): - ''' - Test class for OCVersion - ''' - - def setUp(self): - ''' 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, mock_tmpfile_copy): - ''' Testing a get ''' - params = {'name': 'router', - 'namespace': 'default', - 'replicas': 2, - 'state': 'list', - 'kind': 'dc', - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False} - - dc = '''{"kind": "DeploymentConfig", - "apiVersion": "v1", - "metadata": { - "name": "router", - "namespace": "default", - "selfLink": "/oapi/v1/namespaces/default/deploymentconfigs/router", - "uid": "a441eedc-e1ae-11e6-a2d5-0e6967f34d42", - "resourceVersion": "6558", - "generation": 8, - "creationTimestamp": "2017-01-23T20:58:07Z", - "labels": { - "router": "router" - } - }, - "spec": { - "replicas": 2, - } - }''' - - mock_openshift_cmd.side_effect = [ - {"cmd": '/usr/bin/oc get dc router -n default', - '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, mock_tmpfile_copy): - ''' Testing a get ''' - params = {'name': 'router', - 'namespace': 'default', - 'replicas': 3, - 'state': 'list', - 'kind': 'dc', - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False} - - dc = '''{"kind": "DeploymentConfig", - "apiVersion": "v1", - "metadata": { - "name": "router", - "namespace": "default", - "selfLink": "/oapi/v1/namespaces/default/deploymentconfigs/router", - "uid": "a441eedc-e1ae-11e6-a2d5-0e6967f34d42", - "resourceVersion": "6558", - "generation": 8, - "creationTimestamp": "2017-01-23T20:58:07Z", - "labels": { - "router": "router" - } - }, - "spec": { - "replicas": 3, - } - }''' - - mock_openshift_cmd.side_effect = [ - {"cmd": '/usr/bin/oc get dc router -n default', - 'results': dc, - 'returncode': 0}, - {"cmd": '/usr/bin/oc create -f /tmp/router -n default', - 'results': '', - '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, mock_tmpfile_copy): - ''' Testing a get ''' - params = {'name': 'not_there', - 'namespace': 'default', - 'replicas': 3, - 'state': 'present', - 'kind': 'dc', - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False} - - mock_openshift_cmd.side_effect = [ - {"cmd": '/usr/bin/oc -n default get dc not_there -o json', - 'results': [{}], - 'returncode': 1, - 'stderr': "Error from server: deploymentconfigs \"not_there\" not found\n", - 'stdout': ""}, - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mocked_kubeconfig', - ] - - results = OCScale.run_ansible(params, False) - - self.assertTrue(results['failed']) - self.assertEqual(results['msg']['returncode'], 1) - - def tearDown(self): - '''TearDown method''' - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/roles/lib_openshift/src/test/unit/oc_secret.py b/roles/lib_openshift/src/test/unit/oc_secret.py deleted file mode 100755 index 645aac82b..000000000 --- a/roles/lib_openshift/src/test/unit/oc_secret.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python2 -''' - Unit tests for oc secret -''' -# To run: -# ./oc_secret.py -# -# . -# Ran 1 test in 0.002s -# -# OK - -import os -import sys -import unittest -import mock - -# Removing invalid variable names for tests so that I can -# keep them brief -# pylint: disable=invalid-name,no-name-in-module -# Disable import-error b/c our libraries aren't loaded in jenkins -# pylint: disable=import-error,wrong-import-position -# place class in our python path -module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 -sys.path.insert(0, module_path) -from oc_secret import OCSecret # noqa: E402 - - -class OCSecretTest(unittest.TestCase): - ''' - Test class for OCSecret - ''' - - def setUp(self): - ''' setup method will create a file and set to known configuration ''' - pass - - @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 - - # run_ansible input parameters - params = { - 'state': 'present', - 'namespace': 'default', - 'name': 'testsecretname', - 'contents': [{ - 'path': "/tmp/somesecret.json", - 'data': "{'one': 1, 'two': 2, 'three': 3}", - }], - 'decode': False, - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False, - 'files': None, - 'delete_after': True, - } - - # Return values of our mocked function call. These get returned once per call. - mock_cmd.side_effect = [ - (1, '', 'Error from server: secrets "testsecretname" not found'), - (0, 'secret/testsecretname', ''), - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mocked_kubeconfig', - ] - - # Act - results = OCSecret.run_ansible(params, False) - - # Assert - self.assertTrue(results['changed']) - self.assertEqual(results['results']['returncode'], 0) - self.assertEqual(results['state'], 'present') - - # Making sure our mock was called as we expected - 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): - '''TearDown method''' - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/roles/lib_openshift/src/test/unit/oc_service.py b/roles/lib_openshift/src/test/unit/oc_service.py deleted file mode 100755 index 4a845e9f3..000000000 --- a/roles/lib_openshift/src/test/unit/oc_service.py +++ /dev/null @@ -1,216 +0,0 @@ -#!/usr/bin/env python2 -''' - Unit tests for oc service -''' -# To run -# python -m unittest version -# -# . -# Ran 1 test in 0.597s -# -# OK - -import os -import sys -import unittest -import mock - -# Removing invalid variable names for tests so that I can -# keep them brief -# pylint: disable=invalid-name,no-name-in-module -# Disable import-error b/c our libraries aren't loaded in jenkins -# pylint: disable=import-error -# place class in our python path -module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 -sys.path.insert(0, module_path) -from oc_service import OCService # noqa: E402 - - -# pylint: disable=too-many-public-methods -class OCServiceTest(unittest.TestCase): - ''' - Test class for OCService - ''' - - def setUp(self): - ''' 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, mock_tmpfile_copy): - ''' Testing a get ''' - params = {'name': 'router', - 'namespace': 'default', - 'ports': None, - 'state': 'list', - 'labels': None, - 'clusterip': None, - 'portalip': None, - 'selector': None, - 'session_affinity': None, - 'service_type': None, - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False} - - service = '''{ - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "router", - "namespace": "default", - "selfLink": "/api/v1/namespaces/default/services/router", - "uid": "fabd2440-e3d8-11e6-951c-0e3dd518cefa", - "resourceVersion": "3206", - "creationTimestamp": "2017-01-26T15:06:14Z", - "labels": { - "router": "router" - } - }, - "spec": { - "ports": [ - { - "name": "80-tcp", - "protocol": "TCP", - "port": 80, - "targetPort": 80 - }, - { - "name": "443-tcp", - "protocol": "TCP", - "port": 443, - "targetPort": 443 - }, - { - "name": "1936-tcp", - "protocol": "TCP", - "port": 1936, - "targetPort": 1936 - }, - { - "name": "5000-tcp", - "protocol": "TCP", - "port": 5000, - "targetPort": 5000 - } - ], - "selector": { - "router": "router" - }, - "clusterIP": "172.30.129.161", - "type": "ClusterIP", - "sessionAffinity": "None" - }, - "status": { - "loadBalancer": {} - } - }''' - mock_cmd.side_effect = [ - (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, mock_tmpfile_copy): - ''' Testing a create service ''' - params = {'name': 'router', - 'namespace': 'default', - 'ports': {'name': '9000-tcp', - 'port': 9000, - 'protocol': 'TCP', - 'targetPOrt': 9000}, - 'state': 'present', - 'labels': None, - 'clusterip': None, - 'portalip': None, - 'selector': {'router': 'router'}, - 'session_affinity': 'ClientIP', - 'service_type': 'ClusterIP', - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False} - - service = '''{ - "kind": "Service", - "apiVersion": "v1", - "metadata": { - "name": "router", - "namespace": "default", - "selfLink": "/api/v1/namespaces/default/services/router", - "uid": "fabd2440-e3d8-11e6-951c-0e3dd518cefa", - "resourceVersion": "3206", - "creationTimestamp": "2017-01-26T15:06:14Z", - "labels": { - "router": "router" - } - }, - "spec": { - "ports": [ - { - "name": "80-tcp", - "protocol": "TCP", - "port": 80, - "targetPort": 80 - }, - { - "name": "443-tcp", - "protocol": "TCP", - "port": 443, - "targetPort": 443 - }, - { - "name": "1936-tcp", - "protocol": "TCP", - "port": 1936, - "targetPort": 1936 - }, - { - "name": "5000-tcp", - "protocol": "TCP", - "port": 5000, - "targetPort": 5000 - } - ], - "selector": { - "router": "router" - }, - "clusterIP": "172.30.129.161", - "type": "ClusterIP", - "sessionAffinity": "None" - }, - "status": { - "loadBalancer": {} - } - }''' - mock_cmd.side_effect = [ - (1, '', 'Error from server: services "router" not found'), - (1, '', 'Error from server: services "router" not found'), - (0, service, ''), - (0, service, '') - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mocked_kubeconfig', - ] - - results = OCService.run_ansible(params, False) - - self.assertTrue(results['changed']) - self.assertTrue(results['results']['returncode'] == 0) - self.assertEqual(results['results']['results'][0]['metadata']['name'], 'router') - - def tearDown(self): - '''TearDown method''' - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/roles/lib_openshift/src/test/unit/oc_serviceaccount.py b/roles/lib_openshift/src/test/unit/oc_serviceaccount.py deleted file mode 100755 index 256b569eb..000000000 --- a/roles/lib_openshift/src/test/unit/oc_serviceaccount.py +++ /dev/null @@ -1,119 +0,0 @@ -#!/usr/bin/env python2 -''' - Unit tests for oc serviceaccount -''' -# To run: -# ./oc_serviceaccount.py -# -# . -# Ran 1 test in 0.002s -# -# OK - -import os -import sys -import unittest -import mock - -# Removing invalid variable names for tests so that I can -# keep them brief -# pylint: disable=invalid-name,no-name-in-module -# Disable import-error b/c our libraries aren't loaded in jenkins -# pylint: disable=import-error,wrong-import-position -# place class in our python path -module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 -sys.path.insert(0, module_path) -from oc_serviceaccount import OCServiceAccount # noqa: E402 - - -class OCServiceAccountTest(unittest.TestCase): - ''' - Test class for OCServiceAccount - ''' - - def setUp(self): - ''' 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, mock_tmpfile_copy): - ''' Testing adding a serviceaccount ''' - - # Arrange - - # run_ansible input parameters - params = { - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'state': 'present', - 'debug': False, - 'name': 'testserviceaccountname', - 'namespace': 'default', - 'secrets': None, - 'image_pull_secrets': None, - } - - valid_result_json = '''{ - "kind": "ServiceAccount", - "apiVersion": "v1", - "metadata": { - "name": "testserviceaccountname", - "namespace": "default", - "selfLink": "/api/v1/namespaces/default/serviceaccounts/testserviceaccountname", - "uid": "4d8320c9-e66f-11e6-8edc-0eece8f2ce22", - "resourceVersion": "328450", - "creationTimestamp": "2017-01-29T22:07:19Z" - }, - "secrets": [ - { - "name": "testserviceaccountname-dockercfg-4lqd0" - }, - { - "name": "testserviceaccountname-token-9h0ej" - } - ], - "imagePullSecrets": [ - { - "name": "testserviceaccountname-dockercfg-4lqd0" - } - ] - }''' - - # Return values of our mocked function call. These get returned once per call. - mock_cmd.side_effect = [ - # First call to mock - (1, '', 'Error from server: serviceaccounts "testserviceaccountname" not found'), - - # Second call to mock - (0, 'serviceaccount "testserviceaccountname" created', ''), - - # Third call to mock - (0, valid_result_json, ''), - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mocked_kubeconfig', - ] - - # Act - results = OCServiceAccount.run_ansible(params, False) - - # Assert - self.assertTrue(results['changed']) - self.assertEqual(results['results']['returncode'], 0) - self.assertEqual(results['state'], 'present') - - # Making sure our mock was called as we expected - mock_cmd.assert_has_calls([ - mock.call(['oc', '-n', 'default', 'get', 'sa', 'testserviceaccountname', '-o', 'json'], None), - mock.call(['oc', '-n', 'default', 'create', '-f', mock.ANY], None), - mock.call(['oc', '-n', 'default', 'get', 'sa', 'testserviceaccountname', '-o', 'json'], None), - ]) - - def tearDown(self): - '''TearDown method''' - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/roles/lib_openshift/src/test/unit/oc_serviceaccount_secret.py b/roles/lib_openshift/src/test/unit/oc_serviceaccount_secret.py deleted file mode 100755 index 213c581aa..000000000 --- a/roles/lib_openshift/src/test/unit/oc_serviceaccount_secret.py +++ /dev/null @@ -1,315 +0,0 @@ -#!/usr/bin/env python2 -''' - Unit tests for oc secret add -''' -# To run: -# ./oc_serviceaccount_secret.py -# -# . -# Ran 1 test in 0.002s -# -# OK - -import os -import sys -import unittest -import mock - -# Removing invalid variable names for tests so that I can -# keep them brief -# pylint: disable=invalid-name,no-name-in-module -# Disable import-error b/c our libraries aren't loaded in jenkins -# pylint: disable=import-error,wrong-import-position -# place class in our python path -module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 -sys.path.insert(0, module_path) -from oc_serviceaccount_secret import OCServiceAccountSecret # noqa: E402 - -try: - import ruamel.yaml as yaml # noqa: EF401 - YAML_TYPE = 'ruamel' -except ImportError: - YAML_TYPE = 'pyyaml' - - -class OCServiceAccountSecretTest(unittest.TestCase): - ''' - Test class for OCServiceAccountSecret - ''' - - def setUp(self): - ''' 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, mock_tmpfile_copy): - ''' Testing adding a secret to a service account ''' - - # Arrange - - # run_ansible input parameters - params = { - 'state': 'present', - 'namespace': 'default', - 'secret': 'newsecret', - 'service_account': 'builder', - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False, - } - - oc_get_sa_before = '''{ - "apiVersion": "v1", - "imagePullSecrets": [ - { - "name": "builder-dockercfg-rsrua" - } - ], - "kind": "ServiceAccount", - "metadata": { - "name": "builder", - "namespace": "default", - "selfLink": "/api/v1/namespaces/default/serviceaccounts/builder", - "uid": "cf47bca7-ebc4-11e6-b041-0ed9df7abc38", - "resourceVersion": "302879", - "creationTimestamp": "2017-02-05T17:02:00Z" - }, - "secrets": [ - { - "name": "builder-dockercfg-rsrua" - }, - { - "name": "builder-token-akqxi" - } - - ] - } - ''' - - oc_get_sa_after = '''{ - "apiVersion": "v1", - "imagePullSecrets": [ - { - "name": "builder-dockercfg-rsrua" - } - ], - "kind": "ServiceAccount", - "metadata": { - "name": "builder", - "namespace": "default", - "selfLink": "/api/v1/namespaces/default/serviceaccounts/builder", - "uid": "cf47bca7-ebc4-11e6-b041-0ed9df7abc38", - "resourceVersion": "302879", - "creationTimestamp": "2017-02-05T17:02:00Z" - }, - "secrets": [ - { - "name": "builder-dockercfg-rsrua" - }, - { - "name": "builder-token-akqxi" - }, - { - "name": "newsecret" - } - - ] - } - ''' - builder_ryaml_file = '''\ -secrets: -- name: builder-dockercfg-rsrua -- name: builder-token-akqxi -- name: newsecret -kind: ServiceAccount -imagePullSecrets: -- name: builder-dockercfg-rsrua -apiVersion: v1 -metadata: - name: builder - namespace: default - resourceVersion: '302879' - creationTimestamp: '2017-02-05T17:02:00Z' - selfLink: /api/v1/namespaces/default/serviceaccounts/builder - uid: cf47bca7-ebc4-11e6-b041-0ed9df7abc38 -''' - - builder_pyyaml_file = '''\ -apiVersion: v1 -imagePullSecrets: -- name: builder-dockercfg-rsrua -kind: ServiceAccount -metadata: - creationTimestamp: '2017-02-05T17:02:00Z' - name: builder - namespace: default - resourceVersion: '302879' - selfLink: /api/v1/namespaces/default/serviceaccounts/builder - uid: cf47bca7-ebc4-11e6-b041-0ed9df7abc38 -secrets: -- name: builder-dockercfg-rsrua -- name: builder-token-akqxi -- name: newsecret -''' - - # Return values of our mocked function call. These get returned once per call. - mock_cmd.side_effect = [ - (0, oc_get_sa_before, ''), # First call to the mock - (0, oc_get_sa_before, ''), # Second call to the mock - (0, 'serviceaccount "builder" replaced', ''), # Third call to the mock - (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) - - # Assert - self.assertTrue(results['changed']) - self.assertEqual(results['results']['returncode'], 0) - self.assertEqual(results['state'], 'present') - - # Making sure our mocks were called as we expected - 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', mock.ANY], None), - mock.call(['oc', '-n', 'default', 'get', 'sa', 'builder', '-o', 'json'], None) - ]) - - yaml_file = builder_pyyaml_file - - if YAML_TYPE == 'ruamel': - yaml_file = builder_ryaml_file - mock_write.assert_has_calls([ - mock.call(mock.ANY, 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, mock_tmpfile_copy): - ''' Testing removing a secret to a service account ''' - - # Arrange - - # run_ansible input parameters - params = { - 'state': 'absent', - 'namespace': 'default', - 'secret': 'newsecret', - 'service_account': 'builder', - 'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'debug': False, - } - - oc_get_sa_before = '''{ - "apiVersion": "v1", - "imagePullSecrets": [ - { - "name": "builder-dockercfg-rsrua" - } - ], - "kind": "ServiceAccount", - "metadata": { - "name": "builder", - "namespace": "default", - "selfLink": "/api/v1/namespaces/default/serviceaccounts/builder", - "uid": "cf47bca7-ebc4-11e6-b041-0ed9df7abc38", - "resourceVersion": "302879", - "creationTimestamp": "2017-02-05T17:02:00Z" - }, - "secrets": [ - { - "name": "builder-dockercfg-rsrua" - }, - { - "name": "builder-token-akqxi" - }, - { - "name": "newsecret" - } - - ] - } - ''' - - builder_ryaml_file = '''\ -secrets: -- name: builder-dockercfg-rsrua -- name: builder-token-akqxi -kind: ServiceAccount -imagePullSecrets: -- name: builder-dockercfg-rsrua -apiVersion: v1 -metadata: - name: builder - namespace: default - resourceVersion: '302879' - creationTimestamp: '2017-02-05T17:02:00Z' - selfLink: /api/v1/namespaces/default/serviceaccounts/builder - uid: cf47bca7-ebc4-11e6-b041-0ed9df7abc38 -''' - - builder_pyyaml_file = '''\ -apiVersion: v1 -imagePullSecrets: -- name: builder-dockercfg-rsrua -kind: ServiceAccount -metadata: - creationTimestamp: '2017-02-05T17:02:00Z' - name: builder - namespace: default - resourceVersion: '302879' - selfLink: /api/v1/namespaces/default/serviceaccounts/builder - uid: cf47bca7-ebc4-11e6-b041-0ed9df7abc38 -secrets: -- name: builder-dockercfg-rsrua -- name: builder-token-akqxi -''' - - # Return values of our mocked function call. These get returned once per call. - mock_cmd.side_effect = [ - (0, oc_get_sa_before, ''), # First call to the mock - (0, oc_get_sa_before, ''), # Second call to the mock - (0, 'serviceaccount "builder" replaced', ''), # Third call to the mock - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mocked_kubeconfig', - ] - - # Act - results = OCServiceAccountSecret.run_ansible(params, False) - - # Assert - self.assertTrue(results['changed']) - self.assertEqual(results['results']['returncode'], 0) - self.assertEqual(results['state'], 'absent') - - # Making sure our mocks were called as we expected - 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', mock.ANY], None), - ]) - - yaml_file = builder_pyyaml_file - - if YAML_TYPE == 'ruamel': - yaml_file = builder_ryaml_file - mock_write.assert_has_calls([ - mock.call(mock.ANY, yaml_file) - ]) - - def tearDown(self): - '''TearDown method''' - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/roles/lib_openshift/src/test/unit/oc_version.py b/roles/lib_openshift/src/test/unit/oc_version.py deleted file mode 100755 index 67dea415b..000000000 --- a/roles/lib_openshift/src/test/unit/oc_version.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python2 -''' - Unit tests for oc version -''' -# To run -# python -m unittest version -# -# . -# Ran 1 test in 0.597s -# -# OK - -import os -import sys -import unittest -import mock - -# Removing invalid variable names for tests so that I can -# keep them brief -# pylint: disable=invalid-name,no-name-in-module -# Disable import-error b/c our libraries aren't loaded in jenkins -# pylint: disable=import-error,wrong-import-position -# place class in our python path -module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 -sys.path.insert(0, module_path) -from oc_version import OCVersion # noqa: E402 - - -class OCVersionTest(unittest.TestCase): - ''' - Test class for OCVersion - ''' - - def setUp(self): - ''' 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, mock_tmpfile_copy): - ''' Testing a get ''' - params = {'kubeconfig': '/etc/origin/master/admin.kubeconfig', - 'state': 'list', - 'debug': False} - - mock_openshift_cmd.side_effect = [ - {"cmd": "oc version", - "results": "oc v3.4.0.39\nkubernetes v1.4.0+776c994\n" + - "features: Basic-Auth GSSAPI Kerberos SPNEGO\n\n" + - "Server https://internal.api.opstest.openshift.com" + - "openshift v3.4.0.39\n" + - "kubernetes v1.4.0+776c994\n", - "returncode": 0} - ] - - mock_tmpfile_copy.side_effect = [ - '/tmp/mocked_kubeconfig', - ] - - results = OCVersion.run_ansible(params) - - self.assertFalse(results['changed']) - self.assertEqual(results['results']['oc_short'], '3.4') - self.assertEqual(results['results']['oc_numeric'], '3.4.0.39') - self.assertEqual(results['results']['kubernetes_numeric'], '1.4.0') - - def tearDown(self): - '''TearDown method''' - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/roles/lib_openshift/src/test/unit/test_oadm_manage_node.py b/roles/lib_openshift/src/test/unit/test_oadm_manage_node.py new file mode 100755 index 000000000..b0786dfac --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oadm_manage_node.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python2 +''' + Unit tests for oadm_manage_node +''' +# To run +# python -m unittest version +# +# . +# Ran 2 tests in 0.001s +# +# OK + +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oadm_manage_node import ManageNode # noqa: E402 + + +class ManageNodeTest(unittest.TestCase): + ''' + Test class for oadm_manage_node + ''' + + def setUp(self): + ''' 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, mock_tmpfile_copy): + ''' Testing a get ''' + params = {'node': ['ip-172-31-49-140.ec2.internal'], + 'schedulable': None, + 'selector': None, + 'pod_selector': None, + 'list_pods': True, + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'evacuate': False, + 'grace_period': False, + 'dry_run': False, + 'force': False} + + pod_list = '''{ + "metadata": {}, + "items": [ + { + "metadata": { + "name": "docker-registry-1-xuhik", + "generateName": "docker-registry-1-", + "namespace": "default", + "selfLink": "/api/v1/namespaces/default/pods/docker-registry-1-xuhik", + "uid": "ae2a25a2-e316-11e6-80eb-0ecdc51fcfc4", + "resourceVersion": "1501", + "creationTimestamp": "2017-01-25T15:55:23Z", + "labels": { + "deployment": "docker-registry-1", + "deploymentconfig": "docker-registry", + "docker-registry": "default" + }, + "annotations": { + "openshift.io/deployment-config.latest-version": "1", + "openshift.io/deployment-config.name": "docker-registry", + "openshift.io/deployment.name": "docker-registry-1", + "openshift.io/scc": "restricted" + } + }, + "spec": {} + }, + { + "metadata": { + "name": "router-1-kp3m3", + "generateName": "router-1-", + "namespace": "default", + "selfLink": "/api/v1/namespaces/default/pods/router-1-kp3m3", + "uid": "9e71f4a5-e316-11e6-80eb-0ecdc51fcfc4", + "resourceVersion": "1456", + "creationTimestamp": "2017-01-25T15:54:56Z", + "labels": { + "deployment": "router-1", + "deploymentconfig": "router", + "router": "router" + }, + "annotations": { + "openshift.io/deployment-config.latest-version": "1", + "openshift.io/deployment-config.name": "router", + "openshift.io/deployment.name": "router-1", + "openshift.io/scc": "hostnetwork" + } + }, + "spec": {} + }] +}''' + + mock_openshift_cmd.side_effect = [ + {"cmd": "/usr/bin/oadm manage-node ip-172-31-49-140.ec2.internal --list-pods", + "results": pod_list, + "returncode": 0} + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + results = ManageNode.run_ansible(params, False) + + # returned a single node + self.assertTrue(len(results['results']['nodes']) == 1) + # 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, mock_tmpfile_copy): + ''' Testing a get ''' + params = {'node': ['ip-172-31-49-140.ec2.internal'], + 'schedulable': False, + 'selector': None, + 'pod_selector': None, + 'list_pods': False, + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'evacuate': False, + 'grace_period': False, + 'dry_run': False, + 'force': False} + + node = [{ + "apiVersion": "v1", + "kind": "Node", + "metadata": { + "creationTimestamp": "2017-01-26T14:34:43Z", + "labels": { + "beta.kubernetes.io/arch": "amd64", + "beta.kubernetes.io/instance-type": "m4.large", + "beta.kubernetes.io/os": "linux", + "failure-domain.beta.kubernetes.io/region": "us-east-1", + "failure-domain.beta.kubernetes.io/zone": "us-east-1c", + "hostname": "opstest-node-compute-0daaf", + "kubernetes.io/hostname": "ip-172-31-51-111.ec2.internal", + "ops_node": "old", + "region": "us-east-1", + "type": "compute" + }, + "name": "ip-172-31-51-111.ec2.internal", + "resourceVersion": "6936", + "selfLink": "/api/v1/nodes/ip-172-31-51-111.ec2.internal", + "uid": "93d7fdfb-e3d4-11e6-a982-0e84250fc302" + }, + "spec": { + "externalID": "i-06bb330e55c699b0f", + "providerID": "aws:///us-east-1c/i-06bb330e55c699b0f", + }}] + + mock_openshift_cmd.side_effect = [ + {"cmd": "/usr/bin/oc get node -o json ip-172-31-49-140.ec2.internal", + "results": node, + "returncode": 0}, + {"cmd": "/usr/bin/oadm manage-node ip-172-31-49-140.ec2.internal --schedulable=False", + "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']) + self.assertEqual(results['results']['nodes'][0]['name'], 'ip-172-31-49-140.ec2.internal') + self.assertEqual(results['results']['nodes'][0]['schedulable'], False) + + def tearDown(self): + '''TearDown method''' + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/roles/lib_openshift/src/test/unit/test_oc_env.py b/roles/lib_openshift/src/test/unit/test_oc_env.py new file mode 100755 index 000000000..15bd7e464 --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_env.py @@ -0,0 +1,444 @@ +#!/usr/bin/env python2 +''' + Unit tests for oc_env +''' +# To run: +# ./oc_env.py +# +# . +# Ran 1 test in 0.002s +# +# OK + +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error,wrong-import-position +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_env import OCEnv # noqa: E402 + + +class OCEnvTest(unittest.TestCase): + ''' + Test class for OCEnv + ''' + + def setUp(self): + ''' setup method will create a file and set to known configuration ''' + pass + + @mock.patch('oc_env.Utils.create_tmpfile_copy') + @mock.patch('oc_env.OCEnv._run') + def test_listing_all_env_vars(self, mock_cmd, mock_tmpfile_copy): + ''' Testing listing all environment variables from a dc''' + + # Arrange + + # run_ansible input parameters + params = { + 'state': 'list', + 'namespace': 'default', + 'name': 'router', + 'kind': 'dc', + 'env_vars': None, + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False, + } + + dc_results = '''{ + "apiVersion": "v1", + "kind": "DeploymentConfig", + "metadata": { + "creationTimestamp": "2017-02-02T15:58:49Z", + "generation": 8, + "labels": { + "router": "router" + }, + "name": "router", + "namespace": "default", + "resourceVersion": "513678" + }, + "spec": { + "replicas": 2, + "selector": { + "router": "router" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "router": "router" + } + }, + "spec": { + "containers": [ + { + "env": [ + { + "name": "DEFAULT_CERTIFICATE_DIR", + "value": "/etc/pki/tls/private" + }, + { + "name": "DEFAULT_CERTIFICATE_PATH", + "value": "/etc/pki/tls/private/tls.crt" + }, + { + "name": "ROUTER_EXTERNAL_HOST_HOSTNAME" + }, + { + "name": "ROUTER_EXTERNAL_HOST_HTTPS_VSERVER" + }, + { + "name": "ROUTER_EXTERNAL_HOST_HTTP_VSERVER" + }, + { + "name": "ROUTER_EXTERNAL_HOST_INSECURE", + "value": "false" + } + ], + "name": "router" + } + ] + } + }, + "test": false, + "triggers": [ + { + "type": "ConfigChange" + } + ] + } + }''' + + # Return values of our mocked function call. These get returned once per call. + mock_cmd.side_effect = [ + (0, dc_results, ''), # First call to the mock + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mock_adminkubeconfig', + ] + + # Act + results = OCEnv.run_ansible(params, False) + + # Assert + self.assertFalse(results['changed']) + for env_var in results['results']: + if env_var == {'name': 'DEFAULT_CERTIFICATE_DIR', 'value': '/etc/pki/tls/private'}: + break + else: + self.fail('Did not find environment variables in results.') + self.assertEqual(results['state'], 'list') + + # Making sure our mocks were called as we expected + mock_cmd.assert_has_calls([ + mock.call(['oc', '-n', 'default', 'get', 'dc', 'router', '-o', 'json'], None), + ]) + + @mock.patch('oc_env.Utils.create_tmpfile_copy') + @mock.patch('oc_env.OCEnv._run') + def test_adding_env_vars(self, mock_cmd, mock_tmpfile_copy): + ''' Test add environment variables to a dc''' + + # Arrange + + # run_ansible input parameters + params = { + 'state': 'present', + 'namespace': 'default', + 'name': 'router', + 'kind': 'dc', + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False, + 'env_vars': {'SOMEKEY': 'SOMEVALUE'}, + } + + dc_results = '''{ + "apiVersion": "v1", + "kind": "DeploymentConfig", + "metadata": { + "creationTimestamp": "2017-02-02T15:58:49Z", + "generation": 8, + "labels": { + "router": "router" + }, + "name": "router", + "namespace": "default", + "resourceVersion": "513678" + }, + "spec": { + "replicas": 2, + "selector": { + "router": "router" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "router": "router" + } + }, + "spec": { + "containers": [ + { + "env": [ + { + "name": "DEFAULT_CERTIFICATE_DIR", + "value": "/etc/pki/tls/private" + }, + { + "name": "DEFAULT_CERTIFICATE_PATH", + "value": "/etc/pki/tls/private/tls.crt" + }, + { + "name": "ROUTER_EXTERNAL_HOST_HOSTNAME" + }, + { + "name": "ROUTER_EXTERNAL_HOST_HTTPS_VSERVER" + }, + { + "name": "ROUTER_EXTERNAL_HOST_HTTP_VSERVER" + }, + { + "name": "ROUTER_EXTERNAL_HOST_INSECURE", + "value": "false" + } + ], + "name": "router" + } + ] + } + }, + "test": false, + "triggers": [ + { + "type": "ConfigChange" + } + ] + } + }''' + + dc_results_after = '''{ + "apiVersion": "v1", + "kind": "DeploymentConfig", + "metadata": { + "creationTimestamp": "2017-02-02T15:58:49Z", + "generation": 8, + "labels": { + "router": "router" + }, + "name": "router", + "namespace": "default", + "resourceVersion": "513678" + }, + "spec": { + "replicas": 2, + "selector": { + "router": "router" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "router": "router" + } + }, + "spec": { + "containers": [ + { + "env": [ + { + "name": "DEFAULT_CERTIFICATE_DIR", + "value": "/etc/pki/tls/private" + }, + { + "name": "DEFAULT_CERTIFICATE_PATH", + "value": "/etc/pki/tls/private/tls.crt" + }, + { + "name": "ROUTER_EXTERNAL_HOST_HOSTNAME" + }, + { + "name": "ROUTER_EXTERNAL_HOST_HTTPS_VSERVER" + }, + { + "name": "ROUTER_EXTERNAL_HOST_HTTP_VSERVER" + }, + { + "name": "ROUTER_EXTERNAL_HOST_INSECURE", + "value": "false" + }, + { + "name": "SOMEKEY", + "value": "SOMEVALUE" + } + ], + "name": "router" + } + ] + } + }, + "test": false, + "triggers": [ + { + "type": "ConfigChange" + } + ] + } + }''' + + # Return values of our mocked function call. These get returned once per call. + mock_cmd.side_effect = [ + (0, dc_results, ''), + (0, dc_results, ''), + (0, dc_results_after, ''), + (0, dc_results_after, ''), + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mock_adminkubeconfig', + ] + + # Act + results = OCEnv.run_ansible(params, False) + + # Assert + self.assertTrue(results['changed']) + for env_var in results['results']: + if env_var == {'name': 'SOMEKEY', 'value': 'SOMEVALUE'}: + break + else: + self.fail('Did not find environment variables in results.') + self.assertEqual(results['state'], 'present') + + # Making sure our mocks were called as we expected + mock_cmd.assert_has_calls([ + mock.call(['oc', '-n', 'default', 'get', 'dc', 'router', '-o', 'json'], None), + ]) + + @mock.patch('oc_env.Utils.create_tmpfile_copy') + @mock.patch('oc_env.OCEnv._run') + def test_removing_env_vars(self, mock_cmd, mock_tmpfile_copy): + ''' Test add environment variables to a dc''' + + # Arrange + + # run_ansible input parameters + params = { + 'state': 'absent', + 'namespace': 'default', + 'name': 'router', + 'kind': 'dc', + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False, + 'env_vars': {'SOMEKEY': 'SOMEVALUE'}, + } + + dc_results_before = '''{ + "apiVersion": "v1", + "kind": "DeploymentConfig", + "metadata": { + "creationTimestamp": "2017-02-02T15:58:49Z", + "generation": 8, + "labels": { + "router": "router" + }, + "name": "router", + "namespace": "default", + "resourceVersion": "513678" + }, + "spec": { + "replicas": 2, + "selector": { + "router": "router" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "router": "router" + } + }, + "spec": { + "containers": [ + { + "env": [ + { + "name": "DEFAULT_CERTIFICATE_DIR", + "value": "/etc/pki/tls/private" + }, + { + "name": "DEFAULT_CERTIFICATE_PATH", + "value": "/etc/pki/tls/private/tls.crt" + }, + { + "name": "ROUTER_EXTERNAL_HOST_HOSTNAME" + }, + { + "name": "ROUTER_EXTERNAL_HOST_HTTPS_VSERVER" + }, + { + "name": "ROUTER_EXTERNAL_HOST_HTTP_VSERVER" + }, + { + "name": "ROUTER_EXTERNAL_HOST_INSECURE", + "value": "false" + }, + { + "name": "SOMEKEY", + "value": "SOMEVALUE" + } + ], + "name": "router" + } + ] + } + }, + "test": false, + "triggers": [ + { + "type": "ConfigChange" + } + ] + } + }''' + + # Return values of our mocked function call. These get returned once per call. + mock_cmd.side_effect = [ + (0, dc_results_before, ''), + (0, dc_results_before, ''), + (0, '', ''), + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mock_adminkubeconfig', + ] + + # Act + results = OCEnv.run_ansible(params, False) + + # Assert + self.assertTrue(results['changed']) + self.assertEqual(results['state'], 'absent') + + # Making sure our mocks were called as we expected + mock_cmd.assert_has_calls([ + mock.call(['oc', '-n', 'default', 'get', 'dc', 'router', '-o', 'json'], None), + ]) + + def tearDown(self): + '''TearDown method''' + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/roles/lib_openshift/src/test/unit/test_oc_label.py b/roles/lib_openshift/src/test/unit/test_oc_label.py new file mode 100755 index 000000000..3176987b0 --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_label.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python2 +''' + Unit tests for oc label +''' +# To run +# python -m unittest version +# +# . +# Ran 1 test in 0.597s +# +# OK + +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_label import OCLabel # noqa: E402 + + +class OCLabelTest(unittest.TestCase): + ''' + Test class for OCLabel + ''' + + def setUp(self): + ''' 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, mock_tmpfile_copy): + ''' Testing a label list ''' + params = {'name': 'default', + 'namespace': 'default', + 'labels': None, + 'state': 'list', + 'kind': 'namespace', + 'selector': None, + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False} + + ns = '''{ + "kind": "Namespace", + "apiVersion": "v1", + "metadata": { + "name": "default", + "selfLink": "/api/v1/namespaces/default", + "uid": "c45b9547-e3d3-11e6-ba9c-0eece8f2ce22", + "resourceVersion": "403024", + "creationTimestamp": "2017-01-26T14:28:55Z", + "labels": { + "storage_pv_quota": "False" + }, + "annotations": { + "openshift.io/node-selector": "", + "openshift.io/sa.initialized-roles": "true", + "openshift.io/sa.scc.mcs": "s0:c1,c0", + "openshift.io/sa.scc.supplemental-groups": "1000000000/10000", + "openshift.io/sa.scc.uid-range": "1000000000/10000" + } + }, + "spec": { + "finalizers": [ + "kubernetes", + "openshift.io/origin" + ] + }, + "status": { + "phase": "Active" + } + }''' + + mock_cmd.side_effect = [ + (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, mock_tmpfile_copy): + ''' Testing a label list ''' + params = {'name': 'default', + 'namespace': 'default', + 'labels': [ + {'key': 'awesomens', 'value': 'testinglabel'}, + {'key': 'storage_pv_quota', 'value': 'False'} + ], + 'state': 'present', + 'kind': 'namespace', + 'selector': None, + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False} + + ns = '''{ + "kind": "Namespace", + "apiVersion": "v1", + "metadata": { + "name": "default", + "selfLink": "/api/v1/namespaces/default", + "uid": "c45b9547-e3d3-11e6-ba9c-0eece8f2ce22", + "resourceVersion": "403024", + "creationTimestamp": "2017-01-26T14:28:55Z", + "labels": { + "storage_pv_quota": "False" + }, + "annotations": { + "openshift.io/node-selector": "", + "openshift.io/sa.initialized-roles": "true", + "openshift.io/sa.scc.mcs": "s0:c1,c0", + "openshift.io/sa.scc.supplemental-groups": "1000000000/10000", + "openshift.io/sa.scc.uid-range": "1000000000/10000" + } + }, + "spec": { + "finalizers": [ + "kubernetes", + "openshift.io/origin" + ] + }, + "status": { + "phase": "Active" + } + }''' + + ns1 = '''{ + "kind": "Namespace", + "apiVersion": "v1", + "metadata": { + "name": "default", + "selfLink": "/api/v1/namespaces/default", + "uid": "c45b9547-e3d3-11e6-ba9c-0eece8f2ce22", + "resourceVersion": "403024", + "creationTimestamp": "2017-01-26T14:28:55Z", + "labels": { + "storage_pv_quota": "False", + "awesomens": "testinglabel" + }, + "annotations": { + "openshift.io/node-selector": "", + "openshift.io/sa.initialized-roles": "true", + "openshift.io/sa.scc.mcs": "s0:c1,c0", + "openshift.io/sa.scc.supplemental-groups": "1000000000/10000", + "openshift.io/sa.scc.uid-range": "1000000000/10000" + } + }, + "spec": { + "finalizers": [ + "kubernetes", + "openshift.io/origin" + ] + }, + "status": { + "phase": "Active" + } + }''' + + mock_cmd.side_effect = [ + (0, ns, ''), + (0, '', ''), + (0, ns1, ''), + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + results = OCLabel.run_ansible(params, False) + + self.assertTrue(results['changed']) + self.assertTrue(results['results']['results']['labels'][0] == + {'storage_pv_quota': 'False', 'awesomens': 'testinglabel'}) + + def tearDown(self): + '''TearDown method''' + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/roles/lib_openshift/src/test/unit/test_oc_process.py b/roles/lib_openshift/src/test/unit/test_oc_process.py new file mode 100755 index 000000000..450ff7071 --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_process.py @@ -0,0 +1,483 @@ +#!/usr/bin/env python2 +''' + Unit tests for oc process +''' +# To run +# python -m unittest version +# +# . +# Ran 1 test in 0.597s +# +# OK + +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_process import OCProcess # noqa: E402 + + +# pylint: disable=too-many-public-methods +class OCProcessTest(unittest.TestCase): + ''' + Test class for OCProcess + ''' + mysql = '''{ + "kind": "Template", + "apiVersion": "v1", + "metadata": { + "name": "mysql-ephemeral", + "namespace": "openshift", + "selfLink": "/oapi/v1/namespaces/openshift/templates/mysql-ephemeral", + "uid": "fb8b5f04-e3d3-11e6-a982-0e84250fc302", + "resourceVersion": "480", + "creationTimestamp": "2017-01-26T14:30:27Z", + "annotations": { + "iconClass": "icon-mysql-database", + "openshift.io/display-name": "MySQL (Ephemeral)", + "tags": "database,mysql" + } + }, + "objects": [ + { + "apiVersion": "v1", + "kind": "Service", + "metadata": { + "creationTimestamp": null, + "name": "${DATABASE_SERVICE_NAME}" + }, + "spec": { + "ports": [ + { + "name": "mysql", + "nodePort": 0, + "port": 3306, + "protocol": "TCP", + "targetPort": 3306 + } + ], + "selector": { + "name": "${DATABASE_SERVICE_NAME}" + }, + "sessionAffinity": "None", + "type": "ClusterIP" + }, + "status": { + "loadBalancer": {} + } + }, + { + "apiVersion": "v1", + "kind": "DeploymentConfig", + "metadata": { + "creationTimestamp": null, + "name": "${DATABASE_SERVICE_NAME}" + }, + "spec": { + "replicas": 1, + "selector": { + "name": "${DATABASE_SERVICE_NAME}" + }, + "strategy": { + "type": "Recreate" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "name": "${DATABASE_SERVICE_NAME}" + } + }, + "spec": { + "containers": [ + { + "capabilities": {}, + "env": [ + { + "name": "MYSQL_USER", + "value": "${MYSQL_USER}" + }, + { + "name": "MYSQL_PASSWORD", + "value": "${MYSQL_PASSWORD}" + }, + { + "name": "MYSQL_DATABASE", + "value": "${MYSQL_DATABASE}" + } + ], + "image": " ", + "imagePullPolicy": "IfNotPresent", + "livenessProbe": { + "initialDelaySeconds": 30, + "tcpSocket": { + "port": 3306 + }, + "timeoutSeconds": 1 + }, + "name": "mysql", + "ports": [ + { + "containerPort": 3306, + "protocol": "TCP" + } + ], + "readinessProbe": { + "exec": { + "command": [ + "/bin/sh", + "-i", + "-c", + "MYSQL_PWD=$MYSQL_PASSWORD mysql -h 127.0.0.1 -u $MYSQL_USER -D $MYSQL_DATABASE -e 'SELECT 1'" + ] + }, + "initialDelaySeconds": 5, + "timeoutSeconds": 1 + }, + "resources": { + "limits": { + "memory": "${MEMORY_LIMIT}" + } + }, + "securityContext": { + "capabilities": {}, + "privileged": false + }, + "terminationMessagePath": "/dev/termination-log", + "volumeMounts": [ + { + "mountPath": "/var/lib/mysql/data", + "name": "${DATABASE_SERVICE_NAME}-data" + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "restartPolicy": "Always", + "volumes": [ + { + "emptyDir": { + "medium": "" + }, + "name": "${DATABASE_SERVICE_NAME}-data" + } + ] + } + }, + "triggers": [ + { + "imageChangeParams": { + "automatic": true, + "containerNames": [ + "mysql" + ], + "from": { + "kind": "ImageStreamTag", + "name": "mysql:${MYSQL_VERSION}", + "namespace": "${NAMESPACE}" + }, + "lastTriggeredImage": "" + }, + "type": "ImageChange" + }, + { + "type": "ConfigChange" + } + ] + }, + "status": {} + } + ], + "parameters": [ + { + "name": "MEMORY_LIMIT", + "displayName": "Memory Limit", + "description": "Maximum amount of memory the container can use.", + "value": "512Mi" + }, + { + "name": "NAMESPACE", + "displayName": "Namespace", + "description": "The OpenShift Namespace where the ImageStream resides.", + "value": "openshift" + }, + { + "name": "DATABASE_SERVICE_NAME", + "displayName": "Database Service Name", + "description": "The name of the OpenShift Service exposed for the database.", + "value": "mysql", + "required": true + }, + { + "name": "MYSQL_USER", + "displayName": "MySQL Connection Username", + "description": "Username for MySQL user that will be used for accessing the database.", + "generate": "expression", + "from": "user[A-Z0-9]{3}", + "required": true + }, + { + "name": "MYSQL_PASSWORD", + "displayName": "MySQL Connection Password", + "description": "Password for the MySQL connection user.", + "generate": "expression", + "from": "[a-zA-Z0-9]{16}", + "required": true + }, + { + "name": "MYSQL_DATABASE", + "displayName": "MySQL Database Name", + "description": "Name of the MySQL database accessed.", + "value": "sampledb", + "required": true + }, + { + "name": "MYSQL_VERSION", + "displayName": "Version of MySQL Image", + "description": "Version of MySQL image to be used (5.5, 5.6 or latest).", + "value": "5.6", + "required": true + } + ], + "labels": { + "template": "mysql-ephemeral-template" + } +}''' + + def setUp(self): + ''' setup method will set to known configuration ''' + pass + + @mock.patch('oc_process.Utils.create_tmpfile_copy') + @mock.patch('oc_process.OCProcess._run') + def test_state_list(self, mock_cmd, mock_tmpfile_copy): + ''' Testing a get ''' + params = {'template_name': 'mysql-ephermeral', + 'namespace': 'test', + 'content': None, + 'state': 'list', + 'reconcile': False, + 'create': False, + 'params': {'NAMESPACE': 'test', 'DATABASE_SERVICE_NAME': 'testdb'}, + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False} + + mock_cmd.side_effect = [ + (0, OCProcessTest.mysql, '') + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mock_kubeconfig', + ] + + results = OCProcess.run_ansible(params, False) + + self.assertFalse(results['changed']) + self.assertEqual(results['results']['results'][0]['metadata']['name'], 'mysql-ephemeral') + + @mock.patch('oc_process.Utils.create_tmpfile_copy') + @mock.patch('oc_process.OCProcess._run') + def test_process_no_create(self, mock_cmd, mock_tmpfile_copy): + ''' Testing a process with no create ''' + params = {'template_name': 'mysql-ephermeral', + 'namespace': 'test', + 'content': None, + 'state': 'present', + 'reconcile': False, + 'create': False, + 'params': {'NAMESPACE': 'test', 'DATABASE_SERVICE_NAME': 'testdb'}, + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False} + + mysqlproc = '''{ + "kind": "List", + "apiVersion": "v1", + "metadata": {}, + "items": [ + { + "apiVersion": "v1", + "kind": "Service", + "metadata": { + "creationTimestamp": null, + "labels": { + "template": "mysql-ephemeral-template" + }, + "name": "testdb" + }, + "spec": { + "ports": [ + { + "name": "mysql", + "nodePort": 0, + "port": 3306, + "protocol": "TCP", + "targetPort": 3306 + } + ], + "selector": { + "name": "testdb" + }, + "sessionAffinity": "None", + "type": "ClusterIP" + }, + "status": { + "loadBalancer": {} + } + }, + { + "apiVersion": "v1", + "kind": "DeploymentConfig", + "metadata": { + "creationTimestamp": null, + "labels": { + "template": "mysql-ephemeral-template" + }, + "name": "testdb" + }, + "spec": { + "replicas": 1, + "selector": { + "name": "testdb" + }, + "strategy": { + "type": "Recreate" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "name": "testdb" + } + }, + "spec": { + "containers": [ + { + "capabilities": {}, + "env": [ + { + "name": "MYSQL_USER", + "value": "userHJJ" + }, + { + "name": "MYSQL_PASSWORD", + "value": "GITOAduAMaV6k688" + }, + { + "name": "MYSQL_DATABASE", + "value": "sampledb" + } + ], + "image": " ", + "imagePullPolicy": "IfNotPresent", + "livenessProbe": { + "initialDelaySeconds": 30, + "tcpSocket": { + "port": 3306 + }, + "timeoutSeconds": 1 + }, + "name": "mysql", + "ports": [ + { + "containerPort": 3306, + "protocol": "TCP" + } + ], + "readinessProbe": { + "exec": { + "command": [ + "/bin/sh", + "-i", + "-c", + "MYSQL_PWD=$MYSQL_PASSWORD mysql -h 127.0.0.1 -u $MYSQL_USER -D $MYSQL_DATABASE -e 'SELECT 1'" + ] + }, + "initialDelaySeconds": 5, + "timeoutSeconds": 1 + }, + "resources": { + "limits": { + "memory": "512Mi" + } + }, + "securityContext": { + "capabilities": {}, + "privileged": false + }, + "terminationMessagePath": "/dev/termination-log", + "volumeMounts": [ + { + "mountPath": "/var/lib/mysql/data", + "name": "testdb-data" + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "restartPolicy": "Always", + "volumes": [ + { + "emptyDir": { + "medium": "" + }, + "name": "testdb-data" + } + ] + } + }, + "triggers": [ + { + "imageChangeParams": { + "automatic": true, + "containerNames": [ + "mysql" + ], + "from": { + "kind": "ImageStreamTag", + "name": "mysql:5.6", + "namespace": "test" + }, + "lastTriggeredImage": "" + }, + "type": "ImageChange" + }, + { + "type": "ConfigChange" + } + ] + } + } + ] +}''' + + mock_cmd.side_effect = [ + (0, OCProcessTest.mysql, ''), + (0, OCProcessTest.mysql, ''), + (0, mysqlproc, ''), + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mock_kubeconfig', + ] + + results = OCProcess.run_ansible(params, False) + + self.assertFalse(results['changed']) + self.assertEqual(results['results']['results']['items'][0]['metadata']['name'], 'testdb') + + def tearDown(self): + '''TearDown method''' + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/roles/lib_openshift/src/test/unit/test_oc_route.py b/roles/lib_openshift/src/test/unit/test_oc_route.py new file mode 100755 index 000000000..361b61f4b --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_route.py @@ -0,0 +1,268 @@ +#!/usr/bin/env python2 +''' + Unit tests for oc route +''' +# To run: +# ./oc_serviceaccount.py +# +# . +# Ran 1 test in 0.002s +# +# OK + +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error,wrong-import-position +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_route import OCRoute # noqa: E402 + + +class OCRouteTest(unittest.TestCase): + ''' + Test class for OCServiceAccount + ''' + + def setUp(self): + ''' setup method will create a file and set to known configuration ''' + pass + + @mock.patch('oc_route.Utils.create_tmpfile_copy') + @mock.patch('oc_route.OCRoute._run') + def test_list_route(self, mock_cmd, mock_tmpfile_copy): + ''' Testing getting a route ''' + + # Arrange + + # run_ansible input parameters + params = { + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'state': 'list', + 'debug': False, + 'name': 'test', + 'namespace': 'default', + 'tls_termination': 'passthrough', + 'dest_cacert_path': None, + 'cacert_path': None, + 'cert_path': None, + 'key_path': None, + 'dest_cacert_content': None, + 'cacert_content': None, + 'cert_content': None, + 'key_content': None, + 'service_name': 'testservice', + 'host': 'test.openshift.com', + 'wildcard_policy': None, + 'weight': None, + 'port': None + } + + route_result = '''{ + "kind": "Route", + "apiVersion": "v1", + "metadata": { + "name": "test", + "namespace": "default", + "selfLink": "/oapi/v1/namespaces/default/routes/test", + "uid": "1b127c67-ecd9-11e6-96eb-0e0d9bdacd26", + "resourceVersion": "439182", + "creationTimestamp": "2017-02-07T01:59:48Z" + }, + "spec": { + "host": "test.example", + "to": { + "kind": "Service", + "name": "test", + "weight": 100 + }, + "port": { + "targetPort": 8443 + }, + "tls": { + "termination": "passthrough" + }, + "wildcardPolicy": "None" + }, + "status": { + "ingress": [ + { + "host": "test.example", + "routerName": "router", + "conditions": [ + { + "type": "Admitted", + "status": "True", + "lastTransitionTime": "2017-02-07T01:59:48Z" + } + ], + "wildcardPolicy": "None" + } + ] + } + }''' + + # Return values of our mocked function call. These get returned once per call. + mock_cmd.side_effect = [ + # First call to mock + (0, route_result, ''), + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mock.kubeconfig', + ] + + # Act + results = OCRoute.run_ansible(params, False) + + # Assert + self.assertFalse(results['changed']) + self.assertEqual(results['state'], 'list') + self.assertEqual(results['results'][0]['metadata']['name'], 'test') + + # Making sure our mock was called as we expected + mock_cmd.assert_has_calls([ + mock.call(['oc', '-n', 'default', 'get', 'route', 'test', '-o', 'json'], None), + ]) + + @mock.patch('oc_route.Utils.create_tmpfile_copy') + @mock.patch('oc_route.Yedit._write') + @mock.patch('oc_route.OCRoute._run') + def test_create_route(self, mock_cmd, mock_write, mock_tmpfile_copy): + ''' Testing getting a route ''' + # Arrange + + # run_ansible input parameters + params = { + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'state': 'present', + 'debug': False, + 'name': 'test', + 'namespace': 'default', + 'tls_termination': 'edge', + 'dest_cacert_path': None, + 'cacert_path': None, + 'cert_path': None, + 'key_path': None, + 'dest_cacert_content': None, + 'cacert_content': 'testing', + 'cert_content': 'testing', + 'key_content': 'testing', + 'service_name': 'testservice', + 'host': 'test.openshift.com', + 'wildcard_policy': None, + 'weight': None, + 'port': None + } + + route_result = '''{ + "apiVersion": "v1", + "kind": "Route", + "metadata": { + "creationTimestamp": "2017-02-07T20:55:10Z", + "name": "test", + "namespace": "default", + "resourceVersion": "517745", + "selfLink": "/oapi/v1/namespaces/default/routes/test", + "uid": "b6f25898-ed77-11e6-9755-0e737db1e63a" + }, + "spec": { + "host": "test.openshift.com", + "tls": { + "caCertificate": "testing", + "certificate": "testing", + "key": "testing", + "termination": "edge" + }, + "to": { + "kind": "Service", + "name": "testservice", + "weight": 100 + }, + "wildcardPolicy": "None" + }, + "status": { + "ingress": [ + { + "conditions": [ + { + "lastTransitionTime": "2017-02-07T20:55:10Z", + "status": "True", + "type": "Admitted" + } + ], + "host": "test.openshift.com", + "routerName": "router", + "wildcardPolicy": "None" + } + ] + } + }''' + + test_route = '''\ +kind: Route +spec: + tls: + caCertificate: testing + termination: edge + certificate: testing + key: testing + to: + kind: Service + name: testservice + weight: 100 + host: test.openshift.com + wildcardPolicy: None +apiVersion: v1 +metadata: + namespace: default + name: test +''' + + # Return values of our mocked function call. These get returned once per call. + mock_cmd.side_effect = [ + # First call to mock + (1, '', 'Error from server: routes "test" not found'), + (1, '', 'Error from server: routes "test" not found'), + (0, 'route "test" created', ''), + (0, route_result, ''), + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mock.kubeconfig', + ] + + mock_write.assert_has_calls = [ + # First call to mock + mock.call('/tmp/test', test_route) + ] + + # Act + results = OCRoute.run_ansible(params, False) + + # Assert + self.assertTrue(results['changed']) + self.assertEqual(results['state'], 'present') + self.assertEqual(results['results']['results'][0]['metadata']['name'], 'test') + + # Making sure our mock was called as we expected + mock_cmd.assert_has_calls([ + mock.call(['oc', '-n', 'default', 'get', 'route', 'test', '-o', 'json'], None), + mock.call(['oc', '-n', 'default', 'create', '-f', mock.ANY], None), + mock.call(['oc', '-n', 'default', 'get', 'route', 'test', '-o', 'json'], None), + ]) + + def tearDown(self): + '''TearDown method''' + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/roles/lib_openshift/src/test/unit/test_oc_scale.py b/roles/lib_openshift/src/test/unit/test_oc_scale.py new file mode 100755 index 000000000..f15eb164d --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_scale.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python2 +''' + Unit tests for oc scale +''' +# To run +# python -m unittest version +# +# . +# Ran 1 test in 0.597s +# +# OK + +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_scale import OCScale # noqa: E402 + + +class OCScaleTest(unittest.TestCase): + ''' + Test class for OCVersion + ''' + + def setUp(self): + ''' 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, mock_tmpfile_copy): + ''' Testing a get ''' + params = {'name': 'router', + 'namespace': 'default', + 'replicas': 2, + 'state': 'list', + 'kind': 'dc', + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False} + + dc = '''{"kind": "DeploymentConfig", + "apiVersion": "v1", + "metadata": { + "name": "router", + "namespace": "default", + "selfLink": "/oapi/v1/namespaces/default/deploymentconfigs/router", + "uid": "a441eedc-e1ae-11e6-a2d5-0e6967f34d42", + "resourceVersion": "6558", + "generation": 8, + "creationTimestamp": "2017-01-23T20:58:07Z", + "labels": { + "router": "router" + } + }, + "spec": { + "replicas": 2, + } + }''' + + mock_openshift_cmd.side_effect = [ + {"cmd": '/usr/bin/oc get dc router -n default', + '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, mock_tmpfile_copy): + ''' Testing a get ''' + params = {'name': 'router', + 'namespace': 'default', + 'replicas': 3, + 'state': 'list', + 'kind': 'dc', + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False} + + dc = '''{"kind": "DeploymentConfig", + "apiVersion": "v1", + "metadata": { + "name": "router", + "namespace": "default", + "selfLink": "/oapi/v1/namespaces/default/deploymentconfigs/router", + "uid": "a441eedc-e1ae-11e6-a2d5-0e6967f34d42", + "resourceVersion": "6558", + "generation": 8, + "creationTimestamp": "2017-01-23T20:58:07Z", + "labels": { + "router": "router" + } + }, + "spec": { + "replicas": 3, + } + }''' + + mock_openshift_cmd.side_effect = [ + {"cmd": '/usr/bin/oc get dc router -n default', + 'results': dc, + 'returncode': 0}, + {"cmd": '/usr/bin/oc create -f /tmp/router -n default', + 'results': '', + '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, mock_tmpfile_copy): + ''' Testing a get ''' + params = {'name': 'not_there', + 'namespace': 'default', + 'replicas': 3, + 'state': 'present', + 'kind': 'dc', + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False} + + mock_openshift_cmd.side_effect = [ + {"cmd": '/usr/bin/oc -n default get dc not_there -o json', + 'results': [{}], + 'returncode': 1, + 'stderr': "Error from server: deploymentconfigs \"not_there\" not found\n", + 'stdout': ""}, + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + results = OCScale.run_ansible(params, False) + + self.assertTrue(results['failed']) + self.assertEqual(results['msg']['returncode'], 1) + + def tearDown(self): + '''TearDown method''' + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/roles/lib_openshift/src/test/unit/test_oc_secret.py b/roles/lib_openshift/src/test/unit/test_oc_secret.py new file mode 100755 index 000000000..645aac82b --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_secret.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python2 +''' + Unit tests for oc secret +''' +# To run: +# ./oc_secret.py +# +# . +# Ran 1 test in 0.002s +# +# OK + +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error,wrong-import-position +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_secret import OCSecret # noqa: E402 + + +class OCSecretTest(unittest.TestCase): + ''' + Test class for OCSecret + ''' + + def setUp(self): + ''' setup method will create a file and set to known configuration ''' + pass + + @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 + + # run_ansible input parameters + params = { + 'state': 'present', + 'namespace': 'default', + 'name': 'testsecretname', + 'contents': [{ + 'path': "/tmp/somesecret.json", + 'data': "{'one': 1, 'two': 2, 'three': 3}", + }], + 'decode': False, + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False, + 'files': None, + 'delete_after': True, + } + + # Return values of our mocked function call. These get returned once per call. + mock_cmd.side_effect = [ + (1, '', 'Error from server: secrets "testsecretname" not found'), + (0, 'secret/testsecretname', ''), + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + # Act + results = OCSecret.run_ansible(params, False) + + # Assert + self.assertTrue(results['changed']) + self.assertEqual(results['results']['returncode'], 0) + self.assertEqual(results['state'], 'present') + + # Making sure our mock was called as we expected + 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): + '''TearDown method''' + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/roles/lib_openshift/src/test/unit/test_oc_service.py b/roles/lib_openshift/src/test/unit/test_oc_service.py new file mode 100755 index 000000000..4a845e9f3 --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_service.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python2 +''' + Unit tests for oc service +''' +# To run +# python -m unittest version +# +# . +# Ran 1 test in 0.597s +# +# OK + +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_service import OCService # noqa: E402 + + +# pylint: disable=too-many-public-methods +class OCServiceTest(unittest.TestCase): + ''' + Test class for OCService + ''' + + def setUp(self): + ''' 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, mock_tmpfile_copy): + ''' Testing a get ''' + params = {'name': 'router', + 'namespace': 'default', + 'ports': None, + 'state': 'list', + 'labels': None, + 'clusterip': None, + 'portalip': None, + 'selector': None, + 'session_affinity': None, + 'service_type': None, + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False} + + service = '''{ + "kind": "Service", + "apiVersion": "v1", + "metadata": { + "name": "router", + "namespace": "default", + "selfLink": "/api/v1/namespaces/default/services/router", + "uid": "fabd2440-e3d8-11e6-951c-0e3dd518cefa", + "resourceVersion": "3206", + "creationTimestamp": "2017-01-26T15:06:14Z", + "labels": { + "router": "router" + } + }, + "spec": { + "ports": [ + { + "name": "80-tcp", + "protocol": "TCP", + "port": 80, + "targetPort": 80 + }, + { + "name": "443-tcp", + "protocol": "TCP", + "port": 443, + "targetPort": 443 + }, + { + "name": "1936-tcp", + "protocol": "TCP", + "port": 1936, + "targetPort": 1936 + }, + { + "name": "5000-tcp", + "protocol": "TCP", + "port": 5000, + "targetPort": 5000 + } + ], + "selector": { + "router": "router" + }, + "clusterIP": "172.30.129.161", + "type": "ClusterIP", + "sessionAffinity": "None" + }, + "status": { + "loadBalancer": {} + } + }''' + mock_cmd.side_effect = [ + (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, mock_tmpfile_copy): + ''' Testing a create service ''' + params = {'name': 'router', + 'namespace': 'default', + 'ports': {'name': '9000-tcp', + 'port': 9000, + 'protocol': 'TCP', + 'targetPOrt': 9000}, + 'state': 'present', + 'labels': None, + 'clusterip': None, + 'portalip': None, + 'selector': {'router': 'router'}, + 'session_affinity': 'ClientIP', + 'service_type': 'ClusterIP', + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False} + + service = '''{ + "kind": "Service", + "apiVersion": "v1", + "metadata": { + "name": "router", + "namespace": "default", + "selfLink": "/api/v1/namespaces/default/services/router", + "uid": "fabd2440-e3d8-11e6-951c-0e3dd518cefa", + "resourceVersion": "3206", + "creationTimestamp": "2017-01-26T15:06:14Z", + "labels": { + "router": "router" + } + }, + "spec": { + "ports": [ + { + "name": "80-tcp", + "protocol": "TCP", + "port": 80, + "targetPort": 80 + }, + { + "name": "443-tcp", + "protocol": "TCP", + "port": 443, + "targetPort": 443 + }, + { + "name": "1936-tcp", + "protocol": "TCP", + "port": 1936, + "targetPort": 1936 + }, + { + "name": "5000-tcp", + "protocol": "TCP", + "port": 5000, + "targetPort": 5000 + } + ], + "selector": { + "router": "router" + }, + "clusterIP": "172.30.129.161", + "type": "ClusterIP", + "sessionAffinity": "None" + }, + "status": { + "loadBalancer": {} + } + }''' + mock_cmd.side_effect = [ + (1, '', 'Error from server: services "router" not found'), + (1, '', 'Error from server: services "router" not found'), + (0, service, ''), + (0, service, '') + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + results = OCService.run_ansible(params, False) + + self.assertTrue(results['changed']) + self.assertTrue(results['results']['returncode'] == 0) + self.assertEqual(results['results']['results'][0]['metadata']['name'], 'router') + + def tearDown(self): + '''TearDown method''' + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/roles/lib_openshift/src/test/unit/test_oc_serviceaccount.py b/roles/lib_openshift/src/test/unit/test_oc_serviceaccount.py new file mode 100755 index 000000000..256b569eb --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_serviceaccount.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python2 +''' + Unit tests for oc serviceaccount +''' +# To run: +# ./oc_serviceaccount.py +# +# . +# Ran 1 test in 0.002s +# +# OK + +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error,wrong-import-position +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_serviceaccount import OCServiceAccount # noqa: E402 + + +class OCServiceAccountTest(unittest.TestCase): + ''' + Test class for OCServiceAccount + ''' + + def setUp(self): + ''' 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, mock_tmpfile_copy): + ''' Testing adding a serviceaccount ''' + + # Arrange + + # run_ansible input parameters + params = { + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'state': 'present', + 'debug': False, + 'name': 'testserviceaccountname', + 'namespace': 'default', + 'secrets': None, + 'image_pull_secrets': None, + } + + valid_result_json = '''{ + "kind": "ServiceAccount", + "apiVersion": "v1", + "metadata": { + "name": "testserviceaccountname", + "namespace": "default", + "selfLink": "/api/v1/namespaces/default/serviceaccounts/testserviceaccountname", + "uid": "4d8320c9-e66f-11e6-8edc-0eece8f2ce22", + "resourceVersion": "328450", + "creationTimestamp": "2017-01-29T22:07:19Z" + }, + "secrets": [ + { + "name": "testserviceaccountname-dockercfg-4lqd0" + }, + { + "name": "testserviceaccountname-token-9h0ej" + } + ], + "imagePullSecrets": [ + { + "name": "testserviceaccountname-dockercfg-4lqd0" + } + ] + }''' + + # Return values of our mocked function call. These get returned once per call. + mock_cmd.side_effect = [ + # First call to mock + (1, '', 'Error from server: serviceaccounts "testserviceaccountname" not found'), + + # Second call to mock + (0, 'serviceaccount "testserviceaccountname" created', ''), + + # Third call to mock + (0, valid_result_json, ''), + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + # Act + results = OCServiceAccount.run_ansible(params, False) + + # Assert + self.assertTrue(results['changed']) + self.assertEqual(results['results']['returncode'], 0) + self.assertEqual(results['state'], 'present') + + # Making sure our mock was called as we expected + mock_cmd.assert_has_calls([ + mock.call(['oc', '-n', 'default', 'get', 'sa', 'testserviceaccountname', '-o', 'json'], None), + mock.call(['oc', '-n', 'default', 'create', '-f', mock.ANY], None), + mock.call(['oc', '-n', 'default', 'get', 'sa', 'testserviceaccountname', '-o', 'json'], None), + ]) + + def tearDown(self): + '''TearDown method''' + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/roles/lib_openshift/src/test/unit/test_oc_serviceaccount_secret.py b/roles/lib_openshift/src/test/unit/test_oc_serviceaccount_secret.py new file mode 100755 index 000000000..213c581aa --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_serviceaccount_secret.py @@ -0,0 +1,315 @@ +#!/usr/bin/env python2 +''' + Unit tests for oc secret add +''' +# To run: +# ./oc_serviceaccount_secret.py +# +# . +# Ran 1 test in 0.002s +# +# OK + +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error,wrong-import-position +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_serviceaccount_secret import OCServiceAccountSecret # noqa: E402 + +try: + import ruamel.yaml as yaml # noqa: EF401 + YAML_TYPE = 'ruamel' +except ImportError: + YAML_TYPE = 'pyyaml' + + +class OCServiceAccountSecretTest(unittest.TestCase): + ''' + Test class for OCServiceAccountSecret + ''' + + def setUp(self): + ''' 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, mock_tmpfile_copy): + ''' Testing adding a secret to a service account ''' + + # Arrange + + # run_ansible input parameters + params = { + 'state': 'present', + 'namespace': 'default', + 'secret': 'newsecret', + 'service_account': 'builder', + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False, + } + + oc_get_sa_before = '''{ + "apiVersion": "v1", + "imagePullSecrets": [ + { + "name": "builder-dockercfg-rsrua" + } + ], + "kind": "ServiceAccount", + "metadata": { + "name": "builder", + "namespace": "default", + "selfLink": "/api/v1/namespaces/default/serviceaccounts/builder", + "uid": "cf47bca7-ebc4-11e6-b041-0ed9df7abc38", + "resourceVersion": "302879", + "creationTimestamp": "2017-02-05T17:02:00Z" + }, + "secrets": [ + { + "name": "builder-dockercfg-rsrua" + }, + { + "name": "builder-token-akqxi" + } + + ] + } + ''' + + oc_get_sa_after = '''{ + "apiVersion": "v1", + "imagePullSecrets": [ + { + "name": "builder-dockercfg-rsrua" + } + ], + "kind": "ServiceAccount", + "metadata": { + "name": "builder", + "namespace": "default", + "selfLink": "/api/v1/namespaces/default/serviceaccounts/builder", + "uid": "cf47bca7-ebc4-11e6-b041-0ed9df7abc38", + "resourceVersion": "302879", + "creationTimestamp": "2017-02-05T17:02:00Z" + }, + "secrets": [ + { + "name": "builder-dockercfg-rsrua" + }, + { + "name": "builder-token-akqxi" + }, + { + "name": "newsecret" + } + + ] + } + ''' + builder_ryaml_file = '''\ +secrets: +- name: builder-dockercfg-rsrua +- name: builder-token-akqxi +- name: newsecret +kind: ServiceAccount +imagePullSecrets: +- name: builder-dockercfg-rsrua +apiVersion: v1 +metadata: + name: builder + namespace: default + resourceVersion: '302879' + creationTimestamp: '2017-02-05T17:02:00Z' + selfLink: /api/v1/namespaces/default/serviceaccounts/builder + uid: cf47bca7-ebc4-11e6-b041-0ed9df7abc38 +''' + + builder_pyyaml_file = '''\ +apiVersion: v1 +imagePullSecrets: +- name: builder-dockercfg-rsrua +kind: ServiceAccount +metadata: + creationTimestamp: '2017-02-05T17:02:00Z' + name: builder + namespace: default + resourceVersion: '302879' + selfLink: /api/v1/namespaces/default/serviceaccounts/builder + uid: cf47bca7-ebc4-11e6-b041-0ed9df7abc38 +secrets: +- name: builder-dockercfg-rsrua +- name: builder-token-akqxi +- name: newsecret +''' + + # Return values of our mocked function call. These get returned once per call. + mock_cmd.side_effect = [ + (0, oc_get_sa_before, ''), # First call to the mock + (0, oc_get_sa_before, ''), # Second call to the mock + (0, 'serviceaccount "builder" replaced', ''), # Third call to the mock + (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) + + # Assert + self.assertTrue(results['changed']) + self.assertEqual(results['results']['returncode'], 0) + self.assertEqual(results['state'], 'present') + + # Making sure our mocks were called as we expected + 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', mock.ANY], None), + mock.call(['oc', '-n', 'default', 'get', 'sa', 'builder', '-o', 'json'], None) + ]) + + yaml_file = builder_pyyaml_file + + if YAML_TYPE == 'ruamel': + yaml_file = builder_ryaml_file + mock_write.assert_has_calls([ + mock.call(mock.ANY, 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, mock_tmpfile_copy): + ''' Testing removing a secret to a service account ''' + + # Arrange + + # run_ansible input parameters + params = { + 'state': 'absent', + 'namespace': 'default', + 'secret': 'newsecret', + 'service_account': 'builder', + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False, + } + + oc_get_sa_before = '''{ + "apiVersion": "v1", + "imagePullSecrets": [ + { + "name": "builder-dockercfg-rsrua" + } + ], + "kind": "ServiceAccount", + "metadata": { + "name": "builder", + "namespace": "default", + "selfLink": "/api/v1/namespaces/default/serviceaccounts/builder", + "uid": "cf47bca7-ebc4-11e6-b041-0ed9df7abc38", + "resourceVersion": "302879", + "creationTimestamp": "2017-02-05T17:02:00Z" + }, + "secrets": [ + { + "name": "builder-dockercfg-rsrua" + }, + { + "name": "builder-token-akqxi" + }, + { + "name": "newsecret" + } + + ] + } + ''' + + builder_ryaml_file = '''\ +secrets: +- name: builder-dockercfg-rsrua +- name: builder-token-akqxi +kind: ServiceAccount +imagePullSecrets: +- name: builder-dockercfg-rsrua +apiVersion: v1 +metadata: + name: builder + namespace: default + resourceVersion: '302879' + creationTimestamp: '2017-02-05T17:02:00Z' + selfLink: /api/v1/namespaces/default/serviceaccounts/builder + uid: cf47bca7-ebc4-11e6-b041-0ed9df7abc38 +''' + + builder_pyyaml_file = '''\ +apiVersion: v1 +imagePullSecrets: +- name: builder-dockercfg-rsrua +kind: ServiceAccount +metadata: + creationTimestamp: '2017-02-05T17:02:00Z' + name: builder + namespace: default + resourceVersion: '302879' + selfLink: /api/v1/namespaces/default/serviceaccounts/builder + uid: cf47bca7-ebc4-11e6-b041-0ed9df7abc38 +secrets: +- name: builder-dockercfg-rsrua +- name: builder-token-akqxi +''' + + # Return values of our mocked function call. These get returned once per call. + mock_cmd.side_effect = [ + (0, oc_get_sa_before, ''), # First call to the mock + (0, oc_get_sa_before, ''), # Second call to the mock + (0, 'serviceaccount "builder" replaced', ''), # Third call to the mock + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + # Act + results = OCServiceAccountSecret.run_ansible(params, False) + + # Assert + self.assertTrue(results['changed']) + self.assertEqual(results['results']['returncode'], 0) + self.assertEqual(results['state'], 'absent') + + # Making sure our mocks were called as we expected + 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', mock.ANY], None), + ]) + + yaml_file = builder_pyyaml_file + + if YAML_TYPE == 'ruamel': + yaml_file = builder_ryaml_file + mock_write.assert_has_calls([ + mock.call(mock.ANY, yaml_file) + ]) + + def tearDown(self): + '''TearDown method''' + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/roles/lib_openshift/src/test/unit/test_oc_version.py b/roles/lib_openshift/src/test/unit/test_oc_version.py new file mode 100755 index 000000000..67dea415b --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_version.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python2 +''' + Unit tests for oc version +''' +# To run +# python -m unittest version +# +# . +# Ran 1 test in 0.597s +# +# OK + +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error,wrong-import-position +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_version import OCVersion # noqa: E402 + + +class OCVersionTest(unittest.TestCase): + ''' + Test class for OCVersion + ''' + + def setUp(self): + ''' 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, mock_tmpfile_copy): + ''' Testing a get ''' + params = {'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'state': 'list', + 'debug': False} + + mock_openshift_cmd.side_effect = [ + {"cmd": "oc version", + "results": "oc v3.4.0.39\nkubernetes v1.4.0+776c994\n" + + "features: Basic-Auth GSSAPI Kerberos SPNEGO\n\n" + + "Server https://internal.api.opstest.openshift.com" + + "openshift v3.4.0.39\n" + + "kubernetes v1.4.0+776c994\n", + "returncode": 0} + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + results = OCVersion.run_ansible(params) + + self.assertFalse(results['changed']) + self.assertEqual(results['results']['oc_short'], '3.4') + self.assertEqual(results['results']['oc_numeric'], '3.4.0.39') + self.assertEqual(results['results']['kubernetes_numeric'], '1.4.0') + + def tearDown(self): + '''TearDown method''' + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/roles/lib_utils/src/test/unit/repoquery.py b/roles/lib_utils/src/test/unit/repoquery.py deleted file mode 100755 index c487ab254..000000000 --- a/roles/lib_utils/src/test/unit/repoquery.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python2 -''' - Unit tests for repoquery -''' -# To run: -# ./repoquery.py -# -# . -# Ran 1 test in 0.002s -# -# OK - -import os -import sys -import unittest -import mock - -# Removing invalid variable names for tests so that I can -# keep them brief -# pylint: disable=invalid-name,no-name-in-module -# Disable import-error b/c our libraries aren't loaded in jenkins -# pylint: disable=import-error,wrong-import-position -# place class in our python path -module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 -sys.path.insert(0, module_path) -from repoquery import Repoquery # noqa: E402 - - -class RepoQueryTest(unittest.TestCase): - ''' - Test class for RepoQuery - ''' - - def setUp(self): - ''' setup method for other tests ''' - pass - - @mock.patch('repoquery._run') - def test_querying_a_package(self, mock_cmd): - ''' Testing querying a package ''' - - # Arrange - - # run_ansible input parameters - params = { - 'state': 'list', - 'name': 'bash', - 'query_type': 'repos', - 'verbose': False, - 'show_duplicates': False, - 'match_version': None, - } - - valid_stderr = '''Repo rhel-7-server-extras-rpms forced skip_if_unavailable=True due to: /etc/pki/entitlement/3268107132875399464-key.pem - Repo rhel-7-server-rpms forced skip_if_unavailable=True due to: /etc/pki/entitlement/4128505182875899164-key.pem''' # not real - - # 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 - ] - - # Act - results = Repoquery.run_ansible(params, False) - - # Assert - self.assertEqual(results['state'], 'list') - self.assertFalse(results['changed']) - self.assertTrue(results['results']['package_found']) - self.assertEqual(results['results']['returncode'], 0) - self.assertEqual(results['results']['package_name'], 'bash') - self.assertEqual(results['results']['versions'], {'latest_full': '4.2.46-21.el7_3', - 'available_versions': ['4.2.46'], - 'available_versions_full': ['4.2.46-21.el7_3'], - 'latest': '4.2.46'}) - - # Making sure our mock was called as we expected - mock_cmd.assert_has_calls([ - mock.call(['/usr/bin/repoquery', '--plugins', '--quiet', '--pkgnarrow=repos', '--queryformat=%{version}|%{release}|%{arch}|%{repo}|%{version}-%{release}', 'bash']), - ]) - - def tearDown(self): - '''TearDown method''' - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/roles/lib_utils/src/test/unit/test_repoquery.py b/roles/lib_utils/src/test/unit/test_repoquery.py new file mode 100755 index 000000000..c487ab254 --- /dev/null +++ b/roles/lib_utils/src/test/unit/test_repoquery.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python2 +''' + Unit tests for repoquery +''' +# To run: +# ./repoquery.py +# +# . +# Ran 1 test in 0.002s +# +# OK + +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error,wrong-import-position +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from repoquery import Repoquery # noqa: E402 + + +class RepoQueryTest(unittest.TestCase): + ''' + Test class for RepoQuery + ''' + + def setUp(self): + ''' setup method for other tests ''' + pass + + @mock.patch('repoquery._run') + def test_querying_a_package(self, mock_cmd): + ''' Testing querying a package ''' + + # Arrange + + # run_ansible input parameters + params = { + 'state': 'list', + 'name': 'bash', + 'query_type': 'repos', + 'verbose': False, + 'show_duplicates': False, + 'match_version': None, + } + + valid_stderr = '''Repo rhel-7-server-extras-rpms forced skip_if_unavailable=True due to: /etc/pki/entitlement/3268107132875399464-key.pem + Repo rhel-7-server-rpms forced skip_if_unavailable=True due to: /etc/pki/entitlement/4128505182875899164-key.pem''' # not real + + # 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 + ] + + # Act + results = Repoquery.run_ansible(params, False) + + # Assert + self.assertEqual(results['state'], 'list') + self.assertFalse(results['changed']) + self.assertTrue(results['results']['package_found']) + self.assertEqual(results['results']['returncode'], 0) + self.assertEqual(results['results']['package_name'], 'bash') + self.assertEqual(results['results']['versions'], {'latest_full': '4.2.46-21.el7_3', + 'available_versions': ['4.2.46'], + 'available_versions_full': ['4.2.46-21.el7_3'], + 'latest': '4.2.46'}) + + # Making sure our mock was called as we expected + mock_cmd.assert_has_calls([ + mock.call(['/usr/bin/repoquery', '--plugins', '--quiet', '--pkgnarrow=repos', '--queryformat=%{version}|%{release}|%{arch}|%{repo}|%{version}-%{release}', 'bash']), + ]) + + def tearDown(self): + '''TearDown method''' + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/roles/lib_utils/src/test/unit/test_yedit.py b/roles/lib_utils/src/test/unit/test_yedit.py new file mode 100755 index 000000000..ed07ac96e --- /dev/null +++ b/roles/lib_utils/src/test/unit/test_yedit.py @@ -0,0 +1,277 @@ +#!/usr/bin/env python2 +''' + Unit tests for yedit +''' +# To run +# python -m unittest yedit_test +# +# ............................. +# ---------------------------------------------------------------------- +# Ran 29 tests in 0.133s +# OK + +import os +import sys +import unittest + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error +# place yedit in our path +yedit_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, yedit_path) + +from yedit import Yedit # noqa: E402 + +# pylint: disable=too-many-public-methods +# Silly pylint, moar tests! + + +class YeditTest(unittest.TestCase): + ''' + Test class for yedit + ''' + data = {'a': 'a', + 'b': {'c': {'d': [{'e': 'x'}, 'f', 'g']}}, + } # noqa: E124 + + filename = 'yedit_test.yml' + + def setUp(self): + ''' setup method will create a file and set to known configuration ''' + yed = Yedit(YeditTest.filename) + yed.yaml_dict = YeditTest.data + yed.write() + + def test_load(self): + ''' Testing a get ''' + yed = Yedit('yedit_test.yml') + self.assertEqual(yed.yaml_dict, self.data) + + def test_write(self): + ''' Testing a simple write ''' + yed = Yedit('yedit_test.yml') + yed.put('key1', 1) + yed.write() + self.assertTrue('key1' in yed.yaml_dict) + self.assertEqual(yed.yaml_dict['key1'], 1) + + def test_write_x_y_z(self): + '''Testing a write of multilayer key''' + yed = Yedit('yedit_test.yml') + yed.put('x.y.z', 'modified') + yed.write() + yed.load() + self.assertEqual(yed.get('x.y.z'), 'modified') + + def test_delete_a(self): + '''Testing a simple delete ''' + yed = Yedit('yedit_test.yml') + yed.delete('a') + yed.write() + yed.load() + self.assertTrue('a' not in yed.yaml_dict) + + def test_delete_b_c(self): + '''Testing delete of layered key ''' + yed = Yedit('yedit_test.yml', separator=':') + yed.delete('b:c') + yed.write() + yed.load() + self.assertTrue('b' in yed.yaml_dict) + self.assertFalse('c' in yed.yaml_dict['b']) + + def test_create(self): + '''Testing a create ''' + os.unlink(YeditTest.filename) + yed = Yedit('yedit_test.yml') + yed.create('foo', 'bar') + yed.write() + yed.load() + self.assertTrue('foo' in yed.yaml_dict) + self.assertTrue(yed.yaml_dict['foo'] == 'bar') + + def test_create_content(self): + '''Testing a create with content ''' + content = {"foo": "bar"} + yed = Yedit("yedit_test.yml", content) + yed.write() + yed.load() + self.assertTrue('foo' in yed.yaml_dict) + self.assertTrue(yed.yaml_dict['foo'], 'bar') + + def test_array_insert(self): + '''Testing a create with content ''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('b:c:d[0]', 'inject') + self.assertTrue(yed.get('b:c:d[0]') == 'inject') + + def test_array_insert_first_index(self): + '''Testing a create with content ''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('b:c:d[0]', 'inject') + self.assertTrue(yed.get('b:c:d[1]') == 'f') + + def test_array_insert_second_index(self): + '''Testing a create with content ''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('b:c:d[0]', 'inject') + self.assertTrue(yed.get('b:c:d[2]') == 'g') + + def test_dict_array_dict_access(self): + '''Testing a create with content''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}]) + self.assertTrue(yed.get('b:c:d[0]:[0]:x:y') == 'inject') + + def test_dict_array_dict_replace(self): + '''Testing multilevel delete''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}]) + yed.put('b:c:d[0]:[0]:x:y', 'testing') + self.assertTrue('b' in yed.yaml_dict) + self.assertTrue('c' in yed.yaml_dict['b']) + self.assertTrue('d' in yed.yaml_dict['b']['c']) + self.assertTrue(isinstance(yed.yaml_dict['b']['c']['d'], list)) + self.assertTrue(isinstance(yed.yaml_dict['b']['c']['d'][0], list)) + self.assertTrue(isinstance(yed.yaml_dict['b']['c']['d'][0][0], dict)) + self.assertTrue('y' in yed.yaml_dict['b']['c']['d'][0][0]['x']) + self.assertTrue(yed.yaml_dict['b']['c']['d'][0][0]['x']['y'] == 'testing') # noqa: E501 + + def test_dict_array_dict_remove(self): + '''Testing multilevel delete''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}]) + yed.delete('b:c:d[0]:[0]:x:y') + self.assertTrue('b' in yed.yaml_dict) + self.assertTrue('c' in yed.yaml_dict['b']) + self.assertTrue('d' in yed.yaml_dict['b']['c']) + self.assertTrue(isinstance(yed.yaml_dict['b']['c']['d'], list)) + self.assertTrue(isinstance(yed.yaml_dict['b']['c']['d'][0], list)) + self.assertTrue(isinstance(yed.yaml_dict['b']['c']['d'][0][0], dict)) + self.assertFalse('y' in yed.yaml_dict['b']['c']['d'][0][0]['x']) + + def test_key_exists_in_dict(self): + '''Testing exist in dict''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}]) + self.assertTrue(yed.exists('b:c', 'd')) + + def test_key_exists_in_list(self): + '''Testing exist in list''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}]) + self.assertTrue(yed.exists('b:c:d', [{'x': {'y': 'inject'}}])) + self.assertFalse(yed.exists('b:c:d', [{'x': {'y': 'test'}}])) + + def test_update_to_list_with_index(self): + '''Testing update to list with index''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('x:y:z', [1, 2, 3]) + yed.update('x:y:z', [5, 6], index=2) + self.assertTrue(yed.get('x:y:z') == [1, 2, [5, 6]]) + self.assertTrue(yed.exists('x:y:z', [5, 6])) + self.assertFalse(yed.exists('x:y:z', 4)) + + def test_update_to_list_with_curr_value(self): + '''Testing update to list with index''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('x:y:z', [1, 2, 3]) + yed.update('x:y:z', [5, 6], curr_value=3) + self.assertTrue(yed.get('x:y:z') == [1, 2, [5, 6]]) + self.assertTrue(yed.exists('x:y:z', [5, 6])) + self.assertFalse(yed.exists('x:y:z', 4)) + + def test_update_to_list(self): + '''Testing update to list''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('x:y:z', [1, 2, 3]) + yed.update('x:y:z', [5, 6]) + self.assertTrue(yed.get('x:y:z') == [1, 2, 3, [5, 6]]) + self.assertTrue(yed.exists('x:y:z', [5, 6])) + self.assertFalse(yed.exists('x:y:z', 4)) + + def test_append_twice_to_list(self): + '''Testing append to list''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('x:y:z', [1, 2, 3]) + yed.append('x:y:z', [5, 6]) + yed.append('x:y:z', [5, 6]) + self.assertTrue(yed.get('x:y:z') == [1, 2, 3, [5, 6], [5, 6]]) + self.assertTrue(2 == yed.get('x:y:z').count([5, 6])) + self.assertFalse(yed.exists('x:y:z', 4)) + + def test_add_item_to_dict(self): + '''Testing update to dict''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('x:y:z', {'a': 1, 'b': 2}) + yed.update('x:y:z', {'c': 3, 'd': 4}) + self.assertTrue(yed.get('x:y:z') == {'a': 1, 'b': 2, 'c': 3, 'd': 4}) + self.assertTrue(yed.exists('x:y:z', {'c': 3})) + + def test_first_level_dict_with_none_value(self): + '''test dict value with none value''' + yed = Yedit(content={'a': None}, separator=":") + yed.put('a:b:c', 'test') + self.assertTrue(yed.get('a:b:c') == 'test') + self.assertTrue(yed.get('a:b'), {'c': 'test'}) + + def test_adding_yaml_variable(self): + '''test dict value with none value''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('z:y', '{{test}}') + self.assertTrue(yed.get('z:y') == '{{test}}') + + def test_keys_with_underscore(self): + '''test dict value with none value''' + yed = Yedit("yedit_test.yml", separator=':') + yed.put('z_:y_y', {'test': '{{test}}'}) + self.assertTrue(yed.get('z_:y_y') == {'test': '{{test}}'}) + + def test_first_level_array_update(self): + '''test update on top level array''' + yed = Yedit(content=[{'a': 1}, {'b': 2}, {'b': 3}], separator=':') + yed.update('', {'c': 4}) + self.assertTrue({'c': 4} in yed.get('')) + + def test_first_level_array_delete(self): + '''test remove top level key''' + yed = Yedit(content=[{'a': 1}, {'b': 2}, {'b': 3}]) + yed.delete('') + self.assertTrue({'b': 3} not in yed.get('')) + + def test_first_level_array_get(self): + '''test dict value with none value''' + yed = Yedit(content=[{'a': 1}, {'b': 2}, {'b': 3}]) + yed.get('') + self.assertTrue([{'a': 1}, {'b': 2}, {'b': 3}] == yed.yaml_dict) + + def test_pop_list_item(self): + '''test dict value with none value''' + yed = Yedit(content=[{'a': 1}, {'b': 2}, {'b': 3}], separator=':') + yed.pop('', {'b': 2}) + self.assertTrue([{'a': 1}, {'b': 3}] == yed.yaml_dict) + + def test_pop_list_item_2(self): + '''test dict value with none value''' + z = list(range(10)) + yed = Yedit(content=z, separator=':') + yed.pop('', 5) + z.pop(5) + self.assertTrue(z == yed.yaml_dict) + + def test_pop_dict_key(self): + '''test dict value with none value''' + yed = Yedit(content={'a': {'b': {'c': 1, 'd': 2}}}, separator='#') + yed.pop('a#b', 'c') + self.assertTrue({'a': {'b': {'d': 2}}} == yed.yaml_dict) + + def tearDown(self): + '''TearDown method''' + os.unlink(YeditTest.filename) + + +if __name__ == "__main__": + unittest.main() diff --git a/roles/lib_utils/src/test/unit/yedit_test.py b/roles/lib_utils/src/test/unit/yedit_test.py deleted file mode 100755 index ed07ac96e..000000000 --- a/roles/lib_utils/src/test/unit/yedit_test.py +++ /dev/null @@ -1,277 +0,0 @@ -#!/usr/bin/env python2 -''' - Unit tests for yedit -''' -# To run -# python -m unittest yedit_test -# -# ............................. -# ---------------------------------------------------------------------- -# Ran 29 tests in 0.133s -# OK - -import os -import sys -import unittest - -# Removing invalid variable names for tests so that I can -# keep them brief -# pylint: disable=invalid-name,no-name-in-module -# Disable import-error b/c our libraries aren't loaded in jenkins -# pylint: disable=import-error -# place yedit in our path -yedit_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 -sys.path.insert(0, yedit_path) - -from yedit import Yedit # noqa: E402 - -# pylint: disable=too-many-public-methods -# Silly pylint, moar tests! - - -class YeditTest(unittest.TestCase): - ''' - Test class for yedit - ''' - data = {'a': 'a', - 'b': {'c': {'d': [{'e': 'x'}, 'f', 'g']}}, - } # noqa: E124 - - filename = 'yedit_test.yml' - - def setUp(self): - ''' setup method will create a file and set to known configuration ''' - yed = Yedit(YeditTest.filename) - yed.yaml_dict = YeditTest.data - yed.write() - - def test_load(self): - ''' Testing a get ''' - yed = Yedit('yedit_test.yml') - self.assertEqual(yed.yaml_dict, self.data) - - def test_write(self): - ''' Testing a simple write ''' - yed = Yedit('yedit_test.yml') - yed.put('key1', 1) - yed.write() - self.assertTrue('key1' in yed.yaml_dict) - self.assertEqual(yed.yaml_dict['key1'], 1) - - def test_write_x_y_z(self): - '''Testing a write of multilayer key''' - yed = Yedit('yedit_test.yml') - yed.put('x.y.z', 'modified') - yed.write() - yed.load() - self.assertEqual(yed.get('x.y.z'), 'modified') - - def test_delete_a(self): - '''Testing a simple delete ''' - yed = Yedit('yedit_test.yml') - yed.delete('a') - yed.write() - yed.load() - self.assertTrue('a' not in yed.yaml_dict) - - def test_delete_b_c(self): - '''Testing delete of layered key ''' - yed = Yedit('yedit_test.yml', separator=':') - yed.delete('b:c') - yed.write() - yed.load() - self.assertTrue('b' in yed.yaml_dict) - self.assertFalse('c' in yed.yaml_dict['b']) - - def test_create(self): - '''Testing a create ''' - os.unlink(YeditTest.filename) - yed = Yedit('yedit_test.yml') - yed.create('foo', 'bar') - yed.write() - yed.load() - self.assertTrue('foo' in yed.yaml_dict) - self.assertTrue(yed.yaml_dict['foo'] == 'bar') - - def test_create_content(self): - '''Testing a create with content ''' - content = {"foo": "bar"} - yed = Yedit("yedit_test.yml", content) - yed.write() - yed.load() - self.assertTrue('foo' in yed.yaml_dict) - self.assertTrue(yed.yaml_dict['foo'], 'bar') - - def test_array_insert(self): - '''Testing a create with content ''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('b:c:d[0]', 'inject') - self.assertTrue(yed.get('b:c:d[0]') == 'inject') - - def test_array_insert_first_index(self): - '''Testing a create with content ''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('b:c:d[0]', 'inject') - self.assertTrue(yed.get('b:c:d[1]') == 'f') - - def test_array_insert_second_index(self): - '''Testing a create with content ''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('b:c:d[0]', 'inject') - self.assertTrue(yed.get('b:c:d[2]') == 'g') - - def test_dict_array_dict_access(self): - '''Testing a create with content''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}]) - self.assertTrue(yed.get('b:c:d[0]:[0]:x:y') == 'inject') - - def test_dict_array_dict_replace(self): - '''Testing multilevel delete''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}]) - yed.put('b:c:d[0]:[0]:x:y', 'testing') - self.assertTrue('b' in yed.yaml_dict) - self.assertTrue('c' in yed.yaml_dict['b']) - self.assertTrue('d' in yed.yaml_dict['b']['c']) - self.assertTrue(isinstance(yed.yaml_dict['b']['c']['d'], list)) - self.assertTrue(isinstance(yed.yaml_dict['b']['c']['d'][0], list)) - self.assertTrue(isinstance(yed.yaml_dict['b']['c']['d'][0][0], dict)) - self.assertTrue('y' in yed.yaml_dict['b']['c']['d'][0][0]['x']) - self.assertTrue(yed.yaml_dict['b']['c']['d'][0][0]['x']['y'] == 'testing') # noqa: E501 - - def test_dict_array_dict_remove(self): - '''Testing multilevel delete''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}]) - yed.delete('b:c:d[0]:[0]:x:y') - self.assertTrue('b' in yed.yaml_dict) - self.assertTrue('c' in yed.yaml_dict['b']) - self.assertTrue('d' in yed.yaml_dict['b']['c']) - self.assertTrue(isinstance(yed.yaml_dict['b']['c']['d'], list)) - self.assertTrue(isinstance(yed.yaml_dict['b']['c']['d'][0], list)) - self.assertTrue(isinstance(yed.yaml_dict['b']['c']['d'][0][0], dict)) - self.assertFalse('y' in yed.yaml_dict['b']['c']['d'][0][0]['x']) - - def test_key_exists_in_dict(self): - '''Testing exist in dict''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}]) - self.assertTrue(yed.exists('b:c', 'd')) - - def test_key_exists_in_list(self): - '''Testing exist in list''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('b:c:d[0]', [{'x': {'y': 'inject'}}]) - self.assertTrue(yed.exists('b:c:d', [{'x': {'y': 'inject'}}])) - self.assertFalse(yed.exists('b:c:d', [{'x': {'y': 'test'}}])) - - def test_update_to_list_with_index(self): - '''Testing update to list with index''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('x:y:z', [1, 2, 3]) - yed.update('x:y:z', [5, 6], index=2) - self.assertTrue(yed.get('x:y:z') == [1, 2, [5, 6]]) - self.assertTrue(yed.exists('x:y:z', [5, 6])) - self.assertFalse(yed.exists('x:y:z', 4)) - - def test_update_to_list_with_curr_value(self): - '''Testing update to list with index''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('x:y:z', [1, 2, 3]) - yed.update('x:y:z', [5, 6], curr_value=3) - self.assertTrue(yed.get('x:y:z') == [1, 2, [5, 6]]) - self.assertTrue(yed.exists('x:y:z', [5, 6])) - self.assertFalse(yed.exists('x:y:z', 4)) - - def test_update_to_list(self): - '''Testing update to list''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('x:y:z', [1, 2, 3]) - yed.update('x:y:z', [5, 6]) - self.assertTrue(yed.get('x:y:z') == [1, 2, 3, [5, 6]]) - self.assertTrue(yed.exists('x:y:z', [5, 6])) - self.assertFalse(yed.exists('x:y:z', 4)) - - def test_append_twice_to_list(self): - '''Testing append to list''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('x:y:z', [1, 2, 3]) - yed.append('x:y:z', [5, 6]) - yed.append('x:y:z', [5, 6]) - self.assertTrue(yed.get('x:y:z') == [1, 2, 3, [5, 6], [5, 6]]) - self.assertTrue(2 == yed.get('x:y:z').count([5, 6])) - self.assertFalse(yed.exists('x:y:z', 4)) - - def test_add_item_to_dict(self): - '''Testing update to dict''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('x:y:z', {'a': 1, 'b': 2}) - yed.update('x:y:z', {'c': 3, 'd': 4}) - self.assertTrue(yed.get('x:y:z') == {'a': 1, 'b': 2, 'c': 3, 'd': 4}) - self.assertTrue(yed.exists('x:y:z', {'c': 3})) - - def test_first_level_dict_with_none_value(self): - '''test dict value with none value''' - yed = Yedit(content={'a': None}, separator=":") - yed.put('a:b:c', 'test') - self.assertTrue(yed.get('a:b:c') == 'test') - self.assertTrue(yed.get('a:b'), {'c': 'test'}) - - def test_adding_yaml_variable(self): - '''test dict value with none value''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('z:y', '{{test}}') - self.assertTrue(yed.get('z:y') == '{{test}}') - - def test_keys_with_underscore(self): - '''test dict value with none value''' - yed = Yedit("yedit_test.yml", separator=':') - yed.put('z_:y_y', {'test': '{{test}}'}) - self.assertTrue(yed.get('z_:y_y') == {'test': '{{test}}'}) - - def test_first_level_array_update(self): - '''test update on top level array''' - yed = Yedit(content=[{'a': 1}, {'b': 2}, {'b': 3}], separator=':') - yed.update('', {'c': 4}) - self.assertTrue({'c': 4} in yed.get('')) - - def test_first_level_array_delete(self): - '''test remove top level key''' - yed = Yedit(content=[{'a': 1}, {'b': 2}, {'b': 3}]) - yed.delete('') - self.assertTrue({'b': 3} not in yed.get('')) - - def test_first_level_array_get(self): - '''test dict value with none value''' - yed = Yedit(content=[{'a': 1}, {'b': 2}, {'b': 3}]) - yed.get('') - self.assertTrue([{'a': 1}, {'b': 2}, {'b': 3}] == yed.yaml_dict) - - def test_pop_list_item(self): - '''test dict value with none value''' - yed = Yedit(content=[{'a': 1}, {'b': 2}, {'b': 3}], separator=':') - yed.pop('', {'b': 2}) - self.assertTrue([{'a': 1}, {'b': 3}] == yed.yaml_dict) - - def test_pop_list_item_2(self): - '''test dict value with none value''' - z = list(range(10)) - yed = Yedit(content=z, separator=':') - yed.pop('', 5) - z.pop(5) - self.assertTrue(z == yed.yaml_dict) - - def test_pop_dict_key(self): - '''test dict value with none value''' - yed = Yedit(content={'a': {'b': {'c': 1, 'd': 2}}}, separator='#') - yed.pop('a#b', 'c') - self.assertTrue({'a': {'b': {'d': 2}}} == yed.yaml_dict) - - def tearDown(self): - '''TearDown method''' - os.unlink(YeditTest.filename) - - -if __name__ == "__main__": - unittest.main() -- cgit v1.2.3 From 218af8732f39cb5e129be8bdb9c7ae4a8e9f6067 Mon Sep 17 00:00:00 2001 From: Jason DeTiberus Date: Sat, 18 Feb 2017 18:25:57 -0500 Subject: Unset exec bit in tests, add missing requirements was: separate lib_ unit tests from other unit tests --- roles/lib_openshift/src/test/unit/test_oadm_manage_node.py | 0 roles/lib_openshift/src/test/unit/test_oc_env.py | 0 roles/lib_openshift/src/test/unit/test_oc_label.py | 0 roles/lib_openshift/src/test/unit/test_oc_process.py | 0 roles/lib_openshift/src/test/unit/test_oc_route.py | 0 roles/lib_openshift/src/test/unit/test_oc_scale.py | 0 roles/lib_openshift/src/test/unit/test_oc_secret.py | 0 roles/lib_openshift/src/test/unit/test_oc_service.py | 0 roles/lib_openshift/src/test/unit/test_oc_serviceaccount.py | 0 roles/lib_openshift/src/test/unit/test_oc_serviceaccount_secret.py | 0 roles/lib_openshift/src/test/unit/test_oc_version.py | 0 roles/lib_utils/src/test/unit/test_repoquery.py | 0 roles/lib_utils/src/test/unit/test_yedit.py | 0 13 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 roles/lib_openshift/src/test/unit/test_oadm_manage_node.py mode change 100755 => 100644 roles/lib_openshift/src/test/unit/test_oc_env.py mode change 100755 => 100644 roles/lib_openshift/src/test/unit/test_oc_label.py mode change 100755 => 100644 roles/lib_openshift/src/test/unit/test_oc_process.py mode change 100755 => 100644 roles/lib_openshift/src/test/unit/test_oc_route.py mode change 100755 => 100644 roles/lib_openshift/src/test/unit/test_oc_scale.py mode change 100755 => 100644 roles/lib_openshift/src/test/unit/test_oc_secret.py mode change 100755 => 100644 roles/lib_openshift/src/test/unit/test_oc_service.py mode change 100755 => 100644 roles/lib_openshift/src/test/unit/test_oc_serviceaccount.py mode change 100755 => 100644 roles/lib_openshift/src/test/unit/test_oc_serviceaccount_secret.py mode change 100755 => 100644 roles/lib_openshift/src/test/unit/test_oc_version.py mode change 100755 => 100644 roles/lib_utils/src/test/unit/test_repoquery.py mode change 100755 => 100644 roles/lib_utils/src/test/unit/test_yedit.py (limited to 'roles') diff --git a/roles/lib_openshift/src/test/unit/test_oadm_manage_node.py b/roles/lib_openshift/src/test/unit/test_oadm_manage_node.py old mode 100755 new mode 100644 diff --git a/roles/lib_openshift/src/test/unit/test_oc_env.py b/roles/lib_openshift/src/test/unit/test_oc_env.py old mode 100755 new mode 100644 diff --git a/roles/lib_openshift/src/test/unit/test_oc_label.py b/roles/lib_openshift/src/test/unit/test_oc_label.py old mode 100755 new mode 100644 diff --git a/roles/lib_openshift/src/test/unit/test_oc_process.py b/roles/lib_openshift/src/test/unit/test_oc_process.py old mode 100755 new mode 100644 diff --git a/roles/lib_openshift/src/test/unit/test_oc_route.py b/roles/lib_openshift/src/test/unit/test_oc_route.py old mode 100755 new mode 100644 diff --git a/roles/lib_openshift/src/test/unit/test_oc_scale.py b/roles/lib_openshift/src/test/unit/test_oc_scale.py old mode 100755 new mode 100644 diff --git a/roles/lib_openshift/src/test/unit/test_oc_secret.py b/roles/lib_openshift/src/test/unit/test_oc_secret.py old mode 100755 new mode 100644 diff --git a/roles/lib_openshift/src/test/unit/test_oc_service.py b/roles/lib_openshift/src/test/unit/test_oc_service.py old mode 100755 new mode 100644 diff --git a/roles/lib_openshift/src/test/unit/test_oc_serviceaccount.py b/roles/lib_openshift/src/test/unit/test_oc_serviceaccount.py old mode 100755 new mode 100644 diff --git a/roles/lib_openshift/src/test/unit/test_oc_serviceaccount_secret.py b/roles/lib_openshift/src/test/unit/test_oc_serviceaccount_secret.py old mode 100755 new mode 100644 diff --git a/roles/lib_openshift/src/test/unit/test_oc_version.py b/roles/lib_openshift/src/test/unit/test_oc_version.py old mode 100755 new mode 100644 diff --git a/roles/lib_utils/src/test/unit/test_repoquery.py b/roles/lib_utils/src/test/unit/test_repoquery.py old mode 100755 new mode 100644 diff --git a/roles/lib_utils/src/test/unit/test_yedit.py b/roles/lib_utils/src/test/unit/test_yedit.py old mode 100755 new mode 100644 -- cgit v1.2.3