d851d9ef3c207a4040365f7b15a23ed9ac50cbd9
[functest-kubernetes.git] / functest_kubernetes / k8stest.py
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2018 All rights reserved
4 # This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10
11 """
12 Define the parent for Kubernetes testing.
13 """
14
15 from __future__ import division
16
17 import logging
18 import os
19 import re
20 import subprocess
21 import time
22
23 from xtesting.core import testcase
24
25
26 class K8sTesting(testcase.TestCase):
27     """Kubernetes test runner"""
28
29     __logger = logging.getLogger(__name__)
30
31     def __init__(self, **kwargs):
32         super(K8sTesting, self).__init__(**kwargs)
33         self.config = '/root/.kube/config'
34         self.cmd = []
35         self.result = 0
36         self.start_time = 0
37         self.stop_time = 0
38
39     def run_kubetest(self):  # pylint: disable=too-many-branches
40         """Run the test suites"""
41         cmd_line = self.cmd
42         self.__logger.info("Starting k8s test: '%s'.", cmd_line)
43
44         process = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
45                                    stderr=subprocess.STDOUT)
46         output = process.stdout.read()
47         # Remove color code escape sequences
48         output = re.sub(r'\x1B\[[0-?]*[ -/]*[@-~]', '', str(output))
49
50         remarks = []
51         lines = output.split('\n')
52         i = 0
53         while i < len(lines):
54             if '[k8s.io]' in lines[i]:
55                 if i != 0 and 'seconds' in lines[i - 1]:
56                     self.__logger.debug(lines[i - 1])
57                 while lines[i] != '-' * len(lines[i]):
58                     if lines[i].startswith('STEP:') or ('INFO:' in lines[i]):
59                         break
60                     self.__logger.debug(lines[i])
61                     i = i + 1
62
63             success = 'SUCCESS!' in lines[i]
64             failure = 'FAIL!' in lines[i]
65             if success or failure:
66                 if i != 0 and 'seconds' in lines[i - 1]:
67                     remarks.append(lines[i - 1])
68                 remarks = remarks + lines[i].replace('--', '|').split('|')
69                 break
70             i = i + 1
71
72         self.__logger.debug('-' * 10)
73         self.__logger.info("Remarks:")
74         for remark in remarks:
75             if 'seconds' in remark:
76                 self.__logger.debug(remark)
77             elif 'Passed' in remark:
78                 self.__logger.info("Passed: %s", remark.split()[0])
79             elif 'Skipped' in remark:
80                 self.__logger.info("Skipped: %s", remark.split()[0])
81             elif 'Failed' in remark:
82                 self.__logger.info("Failed: %s", remark.split()[0])
83
84         if success:
85             self.result = 100
86         elif failure:
87             self.result = 0
88
89     def run(self, **kwargs):
90
91         if not os.path.isfile(self.config):
92             self.__logger.error(
93                 "Cannot run k8s testcases. Config file not found ")
94             return self.EX_RUN_ERROR
95
96         self.start_time = time.time()
97         try:
98             self.run_kubetest()
99             res = self.EX_OK
100         except Exception:  # pylint: disable=broad-except
101             self.__logger.exception("Error with running kubetest:")
102             res = self.EX_RUN_ERROR
103
104         self.stop_time = time.time()
105         return res
106
107     def check_envs(self):  # pylint: disable=no-self-use
108         """Check if required environment variables are set"""
109         try:
110             assert 'DEPLOY_SCENARIO' in os.environ
111             assert 'KUBE_MASTER_IP' in os.environ
112             assert 'KUBERNETES_PROVIDER' in os.environ
113             assert 'KUBE_MASTER_URL' in os.environ
114         except Exception as ex:
115             raise Exception("Cannot run k8s testcases. "
116                             "Please check env var: %s" % str(ex))
117
118
119 class K8sSmokeTest(K8sTesting):
120     """Kubernetes smoke test suite"""
121     def __init__(self, **kwargs):
122         if "case_name" not in kwargs:
123             kwargs.get("case_name", 'k8s_smoke')
124         super(K8sSmokeTest, self).__init__(**kwargs)
125         self.check_envs()
126         self.cmd = ['/src/k8s.io/kubernetes/cluster/test-smoke.sh', '--host',
127                     os.getenv('KUBE_MASTER_URL')]
128
129
130 class K8sConformanceTest(K8sTesting):
131     """Kubernetes conformance test suite"""
132     def __init__(self, **kwargs):
133         if "case_name" not in kwargs:
134             kwargs.get("case_name", 'k8s_conformance')
135         super(K8sConformanceTest, self).__init__(**kwargs)
136         self.check_envs()
137         self.cmd = ['/src/k8s.io/kubernetes/_output/bin/e2e.test',
138                     '-ginkgo.focus', 'Conformance',
139                     '-kubeconfig', self.config]