Set Ginkgo's reporter not to print out in color
[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     config = '/root/.kube/config'
32
33     def __init__(self, **kwargs):
34         super(K8sTesting, self).__init__(**kwargs)
35         self.cmd = []
36         self.result = 0
37         self.start_time = 0
38         self.stop_time = 0
39
40     def run_kubetest(self):  # pylint: disable=too-many-branches
41         """Run the test suites"""
42         cmd_line = self.cmd
43         self.__logger.info("Starting k8s test: '%s'.", cmd_line)
44
45         process = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
46                                    stderr=subprocess.STDOUT)
47         output = process.stdout.read()
48         if ('Error loading client' in output or
49                 'Unexpected error' in output):
50             raise Exception(output)
51
52         remarks = []
53         lines = output.split('\n')
54         success = False
55         failure = False
56         i = 0
57         while i < len(lines):
58             if '[Fail]' in lines[i] or 'Failures:' in lines[i]:
59                 self.__logger.error(lines[i])
60             if re.search(r'\[(.)*[0-9]+ seconds\]', lines[i]):
61                 self.__logger.debug(lines[i])
62                 i = i + 1
63                 while i < len(lines) and lines[i] != '-' * len(lines[i]):
64                     if lines[i].startswith('STEP:') or ('INFO:' in lines[i]):
65                         break
66                     self.__logger.debug(lines[i])
67                     i = i + 1
68             if i >= len(lines):
69                 break
70             success = 'SUCCESS!' in lines[i]
71             failure = 'FAIL!' in lines[i]
72             if success or failure:
73                 if i != 0 and 'seconds' in lines[i - 1]:
74                     remarks.append(lines[i - 1])
75                 remarks = remarks + lines[i].replace('--', '|').split('|')
76                 break
77             i = i + 1
78
79         self.__logger.debug('-' * 10)
80         self.__logger.info("Remarks:")
81         for remark in remarks:
82             if 'seconds' in remark:
83                 self.__logger.debug(remark)
84             elif 'Passed' in remark:
85                 self.__logger.info("Passed: %s", remark.split()[0])
86             elif 'Skipped' in remark:
87                 self.__logger.info("Skipped: %s", remark.split()[0])
88             elif 'Failed' in remark:
89                 self.__logger.info("Failed: %s", remark.split()[0])
90
91         if success:
92             self.result = 100
93         elif failure:
94             self.result = 0
95
96     def run(self, **kwargs):
97
98         if not os.path.isfile(self.config):
99             self.__logger.error(
100                 "Cannot run k8s testcases. Config file not found")
101             return self.EX_RUN_ERROR
102
103         self.start_time = time.time()
104         try:
105             self.run_kubetest()
106             res = self.EX_OK
107         except Exception:  # pylint: disable=broad-except
108             self.__logger.exception("Error with running kubetest:")
109             res = self.EX_RUN_ERROR
110
111         self.stop_time = time.time()
112         return res
113
114
115 class K8sSmokeTest(K8sTesting):
116     """Kubernetes smoke test suite"""
117     def __init__(self, **kwargs):
118         if "case_name" not in kwargs:
119             kwargs.get("case_name", 'k8s_smoke')
120         super(K8sSmokeTest, self).__init__(**kwargs)
121         self.cmd = ['e2e.test', '-ginkgo.focus', 'Guestbook.application',
122                     '-ginkgo.noColor', '-kubeconfig', self.config,
123                     '--provider', 'local']
124
125
126 class K8sConformanceTest(K8sTesting):
127     """Kubernetes conformance test suite"""
128     def __init__(self, **kwargs):
129         if "case_name" not in kwargs:
130             kwargs.get("case_name", 'k8s_conformance')
131         super(K8sConformanceTest, self).__init__(**kwargs)
132         self.cmd = ['e2e.test', '-ginkgo.focus', 'Conformance',
133                     '-ginkgo.noColor', '-kubeconfig', self.config,
134                     '--provider', 'local']