Browse Source

Added unit integration tests. Enhanced unit tests. Fixed an issue in openshift_cmd for namespace.

Kenny Woodson 8 years ago
parent
commit
853170d0e4

+ 20 - 7
roles/lib_openshift/library/oadm_manage_node.py

@@ -920,7 +920,7 @@ class OpenShiftCLI(object):
 
         if self.all_namespaces:
             cmds.extend(['--all-namespaces'])
-        elif self.namespace:
+        elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']:  # E501
             cmds.extend(['-n', self.namespace])
 
         cmds.extend(cmd)
@@ -1358,9 +1358,11 @@ class ManageNode(OpenShiftCLI):
                 if isinstance(tmp_result, dict):
                     tmp_nodes.append(tmp_result)
                     continue
-                tmp_nodes.extend(self.get_nodes(name))
+                tmp_nodes.extend(tmp_result)
             nodes = tmp_nodes
 
+        # This is a short circuit based on the way we fetch nodes.
+        # If node is a dict/list then we've already fetched them.
         for node in nodes:
             if isinstance(node, dict) and node.has_key('returncode'):
                 return {'results': nodes, 'returncode': node['returncode']}
@@ -1370,10 +1372,21 @@ class ManageNode(OpenShiftCLI):
         # node['schedulable'] == self.config.config_options['schedulable']['value']
         if any([node['schedulable'] != self.config.config_options['schedulable']['value'] for node in nodes]):
 
-            return self._schedulable(node=self.config.config_options['node']['value'],
-                                     selector=self.config.config_options['selector']['value'],
-                                     schedulable=self.config.config_options['schedulable']['value'],
-                                    )
+            results = self._schedulable(node=self.config.config_options['node']['value'],
+                                        selector=self.config.config_options['selector']['value'],
+                                        schedulable=self.config.config_options['schedulable']['value'])
+
+            # 'NAME                            STATUS    AGE\\nip-172-31-49-140.ec2.internal   Ready     4h\\n'  # E501
+            # normalize formatting with previous return objects
+            if results['results'].startswith('NAME'):
+                nodes = []
+                # removing header line and trailing new line character of node lines
+                for node_results in results['results'].split('\n')[1:-1]:
+                    parts = node_results.split()
+                    nodes.append({'name': parts[0], 'schedulable': 'Ready' == parts[1]})
+                results['nodes'] = nodes
+
+            return results
 
         results = {}
         results['returncode'] = 0
@@ -1435,7 +1448,7 @@ def main():
             node=dict(default=None, type='list'),
             selector=dict(default=None, type='str'),
             pod_selector=dict(default=None, type='str'),
-            schedulable=dict(default=False, type='bool'),
+            schedulable=dict(default=None, type='bool'),
             list_pods=dict(default=False, type='bool'),
             evacuate=dict(default=False, type='bool'),
             dry_run=dict(default=False, type='bool'),

+ 1 - 1
roles/lib_openshift/library/oc_edit.py

@@ -947,7 +947,7 @@ class OpenShiftCLI(object):
 
         if self.all_namespaces:
             cmds.extend(['--all-namespaces'])
-        elif self.namespace:
+        elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']:  # E501
             cmds.extend(['-n', self.namespace])
 
         cmds.extend(cmd)

+ 1 - 1
roles/lib_openshift/library/oc_obj.py

@@ -926,7 +926,7 @@ class OpenShiftCLI(object):
 
         if self.all_namespaces:
             cmds.extend(['--all-namespaces'])
-        elif self.namespace:
+        elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']:  # E501
             cmds.extend(['-n', self.namespace])
 
         cmds.extend(cmd)

+ 1 - 1
roles/lib_openshift/library/oc_route.py

@@ -951,7 +951,7 @@ class OpenShiftCLI(object):
 
         if self.all_namespaces:
             cmds.extend(['--all-namespaces'])
-        elif self.namespace:
+        elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']:  # E501
             cmds.extend(['-n', self.namespace])
 
         cmds.extend(cmd)

+ 1 - 1
roles/lib_openshift/library/oc_secret.py

@@ -947,7 +947,7 @@ class OpenShiftCLI(object):
 
         if self.all_namespaces:
             cmds.extend(['--all-namespaces'])
-        elif self.namespace:
+        elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']:  # E501
             cmds.extend(['-n', self.namespace])
 
         cmds.extend(cmd)

+ 1 - 1
roles/lib_openshift/library/oc_version.py

@@ -871,7 +871,7 @@ class OpenShiftCLI(object):
 
         if self.all_namespaces:
             cmds.extend(['--all-namespaces'])
-        elif self.namespace:
+        elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']:  # E501
             cmds.extend(['-n', self.namespace])
 
         cmds.extend(cmd)

+ 1 - 1
roles/lib_openshift/src/ansible/oadm_manage_node.py

@@ -14,7 +14,7 @@ def main():
             node=dict(default=None, type='list'),
             selector=dict(default=None, type='str'),
             pod_selector=dict(default=None, type='str'),
-            schedulable=dict(default=False, type='bool'),
+            schedulable=dict(default=None, type='bool'),
             list_pods=dict(default=False, type='bool'),
             evacuate=dict(default=False, type='bool'),
             dry_run=dict(default=False, type='bool'),

+ 18 - 5
roles/lib_openshift/src/class/oadm_manage_node.py

@@ -131,9 +131,11 @@ class ManageNode(OpenShiftCLI):
                 if isinstance(tmp_result, dict):
                     tmp_nodes.append(tmp_result)
                     continue
-                tmp_nodes.extend(self.get_nodes(name))
+                tmp_nodes.extend(tmp_result)
             nodes = tmp_nodes
 
+        # This is a short circuit based on the way we fetch nodes.
+        # If node is a dict/list then we've already fetched them.
         for node in nodes:
             if isinstance(node, dict) and node.has_key('returncode'):
                 return {'results': nodes, 'returncode': node['returncode']}
@@ -143,10 +145,21 @@ class ManageNode(OpenShiftCLI):
         # node['schedulable'] == self.config.config_options['schedulable']['value']
         if any([node['schedulable'] != self.config.config_options['schedulable']['value'] for node in nodes]):
 
-            return self._schedulable(node=self.config.config_options['node']['value'],
-                                     selector=self.config.config_options['selector']['value'],
-                                     schedulable=self.config.config_options['schedulable']['value'],
-                                    )
+            results = self._schedulable(node=self.config.config_options['node']['value'],
+                                        selector=self.config.config_options['selector']['value'],
+                                        schedulable=self.config.config_options['schedulable']['value'])
+
+            # 'NAME                            STATUS    AGE\\nip-172-31-49-140.ec2.internal   Ready     4h\\n'  # E501
+            # normalize formatting with previous return objects
+            if results['results'].startswith('NAME'):
+                nodes = []
+                # removing header line and trailing new line character of node lines
+                for node_results in results['results'].split('\n')[1:-1]:
+                    parts = node_results.split()
+                    nodes.append({'name': parts[0], 'schedulable': 'Ready' == parts[1]})
+                results['nodes'] = nodes
+
+            return results
 
         results = {}
         results['returncode'] = 0

+ 1 - 1
roles/lib_openshift/src/lib/base.py

@@ -216,7 +216,7 @@ class OpenShiftCLI(object):
 
         if self.all_namespaces:
             cmds.extend(['--all-namespaces'])
-        elif self.namespace:
+        elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']:  # E501
             cmds.extend(['-n', self.namespace])
 
         cmds.extend(cmd)

+ 58 - 0
roles/lib_openshift/src/test/integration/oadm_manage_node.yml

@@ -0,0 +1,58 @@
+#!/usr/bin/ansible-playbook --module-path=../../../library/
+# ./oadm_manage_node.yml -M ../../../library -e "cli_master_test=$OPENSHIFT_MASTER cli_node_test=$OPENSHIFT_NODE
+---
+- hosts: "{{ cli_master_test }}"
+  gather_facts: no
+  user: root
+  tasks:
+  - name: list pods from a node
+    oadm_manage_node:
+      list_pods: True
+      node:
+      - "{{ cli_node_test }}"
+    register: podout
+  - debug: var=podout
+
+  - assert:
+      that: "'{{ cli_node_test }}' in podout.results.nodes"
+      msg: Pod data was not returned
+
+  - name: set node to unschedulable
+    oadm_manage_node:
+      schedulable: False
+      node:
+      - "{{ cli_node_test }}"
+    register: nodeout
+  - debug: var=nodeout
+
+  - name: assert that schedulable=False
+    assert:
+      that: nodeout.results.nodes[0]['schedulable'] == False
+      msg: "{{ cli_node_test }} schedulable set to True"
+
+  - name: get node scheduable
+    oc_obj:
+      kind: node
+      state: list
+      name: "{{ cli_node_test }}"
+      namespace: None
+    register: nodeout
+
+  - debug: var=nodeout
+
+  - name: assert that schedulable=False
+    assert:
+      that: nodeout.results.results[0]['spec']['unschedulable']
+
+  - name: set node to schedulable
+    oadm_manage_node:
+      schedulable: True
+      node:
+      - "{{ cli_node_test }}"
+    register: nodeout
+  - debug: var=nodeout
+
+  - name: assert that schedulable=False
+    assert:
+      that: nodeout.results.nodes[0]['schedulable']
+      msg: "{{ cli_node_test }} schedulable set to False"

+ 115 - 67
roles/lib_openshift/src/test/unit/oadm_manage_node.py

@@ -6,7 +6,7 @@
 # python -m unittest version
 #
 # .
-# Ran 1 test in 0.597s
+# Ran 2 tests in 0.001s
 #
 # OK
 
@@ -36,10 +36,10 @@ class ManageNodeTest(unittest.TestCase):
         pass
 
     @mock.patch('oadm_manage_node.ManageNode.openshift_cmd')
-    def test_state_list(self, mock_openshift_cmd):
+    def test_list_pods(self, mock_openshift_cmd):
         ''' Testing a get '''
-        params = {'node': 'test-node-1',
-                  'namespace': 'default',
+        params = {'node': ['ip-172-31-49-140.ec2.internal'],
+                  'schedulable': None,
                   'selector': None,
                   'pod_selector': None,
                   'list_pods': True,
@@ -49,78 +49,126 @@ class ManageNodeTest(unittest.TestCase):
                   'dry_run': False,
                   'force': 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,
-               }
-           }'''
+        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/oc get dc router -n default',
-             'results': dc,
-             'returncode': 0}]
+            {"cmd": "/usr/bin/oadm manage-node ip-172-31-49-140.ec2.internal --list-pods",
+             "results": pod_list,
+             "returncode": 0}
+        ]
 
-        results = OCScale.run_ansible(params, False)
+        results = ManageNode.run_ansible(params, False)
 
-        self.assertFalse(results['changed'])
-        self.assertEqual(results['result'][0], 2)
+        # 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('oc_scale.OCScale.openshift_cmd')
-    def test_scale(self, mock_openshift_cmd):
+    @mock.patch('oadm_manage_node.ManageNode.openshift_cmd')
+    def test_schedulable_false(self, mock_openshift_cmd):
         ''' Testing a get '''
-        params = {'name': 'router',
-                  'namespace': 'default',
-                  'replicas': 3,
-                  'state': 'list',
-                  'kind': 'dc',
+        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',
-                  '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}
-        ]
+                  'evacuate': False,
+                  'grace_period': False,
+                  'dry_run': False,
+                  'force': False}
 
-        results = OCScale.run_ansible(params, False)
 
-        self.assertFalse(results['changed'])
-        self.assertEqual(results['result'][0], 3)
+        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",
+            }}]
+
+                #"unschedulable": True
+        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\nip-172-31-49-140.ec2.internal   Ready,SchedulingDisabled     5h\n",
+             "returncode": 0}]
+        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'''