job.py 8.2 KB
Newer Older
A
air9 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#!/usr/bin/env python
# coding: utf-8

# Copyright (c) 2020 Huawei Technologies Co., Ltd.
# oec-hardware is licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Create: 2020-04-01

import os
import sys
import string
import random
import argparse

from .test import Test
from .env import CertEnv
from .command import Command, CertCommandError
from .commandUI import CommandUI
from .log import Logger
from .reboot import Reboot


class Job(object):
C
cuixucui 已提交
30 31 32
    """
    Test task management
    """
A
air9 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
    def __init__(self, args=None):
        """
        Creates an instance of Job class.

        :param args: the job configuration, usually set by command
                     line options and argument parsing
        :type args: :class:`argparse.Namespace`
        """
        self.args = args or argparse.Namespace()
        self.test_factory = getattr(args, "test_factory", [])
        self.test_suite = []
        self.job_id = ''.join(random.sample(string.ascii_letters + string.digits, 10))
        self.ui = CommandUI()
        self.subtests_filter = getattr(args, "subtests_filter", None)

        self.test_parameters = None
        if "test_parameters" in self.args:
            self.test_parameters = {}
            for parameter_name, parameter_value in self.args.test_parameters:
                self.test_parameters[parameter_name] = parameter_value

C
cuixucui 已提交
54
    def discover(self, testname, subtests_filter=None):
C
cuixucui 已提交
55 56 57 58 59 60
        """
        discover test
        :param testname:
        :param subtests_filter:
        :return:
        """
A
air9 已提交
61 62 63 64 65
        if not testname:
            print("testname not specified, discover test failed")
            return None

        filename = testname + ".py"
C
cuixucui 已提交
66
        dirpath = ''
A
air9 已提交
67 68 69 70 71 72 73 74 75 76
        for (dirpath, dirs, files) in os.walk(CertEnv.testdirectoy):
            if filename in files:
                break
        pth = os.path.join(dirpath, filename)
        if not os.access(pth, os.R_OK):
            return None

        sys.path.insert(0, dirpath)
        try:
            module = __import__(testname, globals(), locals())
C
cuixucui 已提交
77
        except Exception as e:
A
air9 已提交
78 79 80 81 82 83 84
            print("Error: module import failed for %s" % testname)
            print(e)
            return None

        for thing in dir(module):
            test_class = getattr(module, thing)
            try:
C
cuixucui 已提交
85
                from types import ClassType as ct
A
air9 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
            except ImportError:
                ct = type
            if isinstance(test_class, ct) and issubclass(test_class, Test):
                if "test" not in dir(test_class):
                    continue
                if (subtests_filter and not subtests_filter in dir(test_class)):
                    continue
                test = test_class()
                if "pri" not in dir(test):
                    continue
                return test

        return None

    def create_test_suite(self, subtests_filter=None):
C
cuixucui 已提交
101 102 103 104 105
        """
        Create test suites
        :param subtests_filter:
        :return:
        """
A
air9 已提交
106 107 108 109 110 111
        if self.test_suite:
            return

        self.test_suite = []
        for test in self.test_factory:
            if test["run"]:
C
cuixucui 已提交
112
                testclass = self.discover(test["name"], subtests_filter)
A
air9 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
                if testclass:
                    testcase = dict()
                    testcase["test"] = testclass
                    testcase["name"] = test["name"]
                    testcase["device"] = test["device"]
                    testcase["status"] = "FAIL"
                    self.test_suite.append(testcase)
                else:
                    if not subtests_filter:
                        test["status"] = "FAIL"
                        print("not found %s" % test["name"])

        if not len(self.test_suite):
            print("No test found")

    def check_test_depends(self):
C
cuixucui 已提交
129 130 131 132
        """
        Install  dependency packages
        :return: depending
        """
A
air9 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
        required_rpms = []
        for tests in self.test_suite:
            for pkg in tests["test"].requirements:
                try:
                    Command("rpm -q " + pkg).run_quiet()
                except CertCommandError:
                    if not pkg in required_rpms:
                        required_rpms.append(pkg)

        if len(required_rpms):
            print("Installing required packages: %s" % ", ".join(required_rpms))
            try:
                cmd = Command("yum install -y " + " ".join(required_rpms))
                cmd.echo()
            except CertCommandError as e:
                print(e)
                print("Fail to install required packages.")
                return False

        return True

    def _run_test(self, testcase, subtests_filter=None):
C
cuixucui 已提交
155 156 157 158 159 160
        """
        Start a testing item
        :param testcase:
        :param subtests_filter:
        :return:
        """
A
air9 已提交
161 162 163 164 165
        name = testcase["name"]
        if testcase["device"].get_name():
            name = testcase["name"] + "-" + testcase["device"].get_name()
        logname = name + ".log"
        reboot = None
C
cuixucui 已提交
166 167
        test = None
        logger = None
A
air9 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
        try:
            test = testcase["test"]
            logger = Logger(logname, self.job_id, sys.stdout, sys.stderr)
            logger.start()
            if subtests_filter:
                return_code = getattr(test, subtests_filter)()
            else:
                print("----  start to run test %s  ----" % name)
                args = argparse.Namespace(device=testcase["device"], logdir=logger.log.dir)
                test.setup(args)
                if test.reboot:
                    reboot = Reboot(testcase["name"], self, test.rebootup)
                    return_code = False
                    if reboot.setup():
                        return_code = test.test()
                else:
                    return_code = test.test()
C
cuixucui 已提交
185
        except Exception as e:
A
air9 已提交
186 187 188 189 190 191 192 193 194 195 196 197
            print(e)
            return_code = False

        if reboot:
            reboot.clean()
        if not subtests_filter:
            test.teardown()
        logger.stop()
        print("")
        return return_code

    def run_tests(self, subtests_filter=None):
C
cuixucui 已提交
198 199 200 201 202
        """
        Start testing
        :param subtests_filter:
        :return:
        """
A
air9 已提交
203 204 205 206 207 208 209 210 211 212 213 214
        if not len(self.test_suite):
            print("No test to run.")
            return

        self.test_suite.sort(key=lambda k: k["test"].pri)
        for testcase in self.test_suite:
            if self._run_test(testcase, subtests_filter):
                testcase["status"] = "PASS"
            else:
                testcase["status"] = "FAIL"

    def run(self):
C
cuixucui 已提交
215 216 217 218
        """
        Test entrance
        :return:
        """
A
air9 已提交
219 220 221 222 223
        logger = Logger("job.log", self.job_id, sys.stdout, sys.stderr)
        logger.start()
        self.create_test_suite(self.subtests_filter)
        if not self.check_test_depends():
            print("Required rpm package not installed, test stopped.")
L
ltx 已提交
224 225
        else:
            self.run_tests(self.subtests_filter)
A
air9 已提交
226 227 228 229 230
        self.save_result()
        logger.stop()
        self.show_summary()

    def show_summary(self):
C
cuixucui 已提交
231 232 233 234
        """
        Command line interface display summary
        :return:
        """
A
air9 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247
        print("-------------  Summary  -------------")
        for test in self.test_factory:
            if test["run"]:
                name = test["name"]
                if test["device"].get_name():
                    name = test["name"] + "-" + test["device"].get_name()
                if test["status"] == "PASS":
                    print(name.ljust(33) + "\033[0;32mPASS\033[0m")
                else:
                    print(name.ljust(33) + "\033[0;31mFAIL\033[0m")
        print("")

    def save_result(self):
C
cuixucui 已提交
248 249 250 251
        """
        Get test status
        :return:
        """
A
air9 已提交
252 253 254 255
        for test in self.test_factory:
            for testcase in self.test_suite:
                if test["name"] == testcase["name"] and test["device"].path == testcase["device"].path:
                    test["status"] = testcase["status"]