bugfix: copy hosts file
[bottlenecks.git] / testsuites / run_testsuite.py
1 #!/usr/bin/env python
2 ##############################################################################
3 # Copyright (c) 2016 Huawei Technologies Co.,Ltd and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10 '''This file realize the function of how to run testsuite.
11 In this file, The first thing is to read testcase config
12 for example: you could run this by use
13 posca_run('testcase', "Which testcase you will run")
14 posca_run('teststory', "Which story you will run")
15 and if you run "python run_posca", this will run testcase,
16 posca_factor_system_bandwidth by default.'''
17
18 import importlib
19 import sys
20 import os
21
22 from oslo_serialization import jsonutils
23 import json
24 import time
25 import requests
26 import datetime
27
28 import utils.parser as conf_parser
29 import utils.logger as log
30 import utils.infra_setup.runner.docker_env as docker_env
31 INTERPRETER = "/usr/bin/python"
32
33 LOG = log.Logger(__name__).getLogger()
34 # ------------------------------------------------------
35 # run testcase in posca
36 # ------------------------------------------------------
37
38
39 def posca_testcase_run(testsuite, testcase_script, test_config):
40
41     module_string = "testsuites.%s.testcase_script.%s" % (testsuite,
42                                                           testcase_script)
43     module = importlib.import_module(module_string)
44     module.run(test_config)
45
46
47 def report(testcase, start_date, stop_date, criteria, details_doc):
48     headers = {'Content-type': 'application/json'}
49     results = {
50         "project_name": "bottlenecks",
51         "case_name": testcase,
52         "description": ("test results for " + testcase),
53         "pod_name": os.environ.get('NODE_NAME', 'unknown'),
54         "installer": os.environ.get('INSTALLER_TYPE', 'unknown'),
55         "version": os.environ.get('BRANCH', 'unknown'),
56         "build_tag": os.environ.get('BUILD_TAG', 'unknown'),
57         "stop_date": str(stop_date),
58         "start_date": str(start_date),
59         "criteria": criteria,
60         "scenario": os.environ.get('DEPLOY_SCENARIO', 'unknown')
61     }
62     results['details'] = {"test_results": details_doc}
63     target = os.environ.get(
64         'BOTTLENECKS_DB_TARGET',
65         'http://testresults.opnfv.org/test/api/v1/results')
66     print ('Address of the target DB is: %s.' % target)
67     timeout = 5
68     try:
69         LOG.debug('Test result : %s', jsonutils.dump_as_bytes(results))
70         res = requests.post(target,
71                             data=jsonutils.dump_as_bytes(results),
72                             headers=headers,
73                             timeout=timeout)
74         LOG.debug('Test result posting finished with status code'
75                   ' %d.' % res.status_code)
76     except Exception as err:
77         LOG.exception('Failed to record result data: %s', err)
78
79
80 def docker_env_prepare(config):
81     LOG.info("Begin to prepare docker environment")
82     if 'contexts' in config.keys() and config["contexts"] is not None:
83         context_config = config["contexts"]
84         if 'yardstick' in context_config.keys() and \
85            context_config["yardstick"] is not None:
86             docker_env.env_yardstick(context_config['yardstick'])
87             conf_parser.Parser.convert_docker_env(config, "yardstick")
88         if 'dashboard' in context_config.keys() and \
89            context_config["dashboard"] is not None:
90             docker_env.env_elk(context_config['dashboard'])
91             conf_parser.Parser.convert_docker_env(config, "dashboard")
92             LOG.debug('Waiting for ELK init')
93             time.sleep(15)
94     LOG.info("Docker environment have prepared")
95     return
96
97
98 def testsuite_run(test_level, test_name, REPORT="False"):
99     tester_parser = test_name.split("_")
100     if test_level == "testcase":
101         config = conf_parser.Parser.testcase_read(tester_parser[0], test_name)
102     elif test_level == "teststory":
103         config = conf_parser.Parser.story_read(tester_parser[0], test_name)
104     for testcase in config:
105         LOG.info("Begin to run %s testcase in POSCA testsuite", testcase)
106         config[testcase]['out_file'] =\
107             conf_parser.Parser.testcase_out_dir(testcase)
108         start_date = datetime.datetime.now()
109         docker_env_prepare(config[testcase])
110         posca_testcase_run(tester_parser[0], testcase, config[testcase])
111         stop_date = datetime.datetime.now()
112         LOG.info("End of %s testcase in POSCA testsuite", testcase)
113         criteria = "FAIL"
114         if REPORT == "True":
115             print ('Testing results are about to be sent to the target DB.')
116             details_doc = []
117             if os.path.exists(config[testcase]['out_file']):
118                 with open(config[testcase]['out_file']) as details_result:
119                     details_doc =[json.loads(data) for data in details_result.readlines()] # noqa
120                     if len(details_doc):
121                         criteria = "PASS"
122             report(testcase, start_date, stop_date, criteria, details_doc)
123         else:
124             print ('Testing results have not been sent to the target DB.')
125
126
127 def main():
128     test_level = sys.argv[1]
129     test_name = sys.argv[2]
130     REPORT = sys.argv[3]
131     testsuite_run(test_level, test_name, REPORT)
132
133
134 if __name__ == '__main__':
135     main()