70e6d8c9c90929f519eecadc4a58042e4590299c
[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 copy_hosts_file():
40     LOG.info("Begin copying hosts file to Bottlenecks-Yardstick")
41     os.system('cp /etc/hosts /tmp/hosts')
42     yardstick_docker = docker_env.docker_find('Bottlenecks-Yardstick')
43     docker_env.docker_exec_cmd(yardstick_docker, 'sudo cp -f /tmp/hosts /etc/hosts')
44     LOG.info("Done with copying hosts file to Bottlenecks-Yardstick")
45
46
47 def posca_testcase_run(testsuite, testcase_script, test_config):
48
49     module_string = "testsuites.%s.testcase_script.%s" % (testsuite,
50                                                           testcase_script)
51     module = importlib.import_module(module_string)
52     module.run(test_config)
53
54
55 def report(testcase, start_date, stop_date, criteria, details_doc):
56     headers = {'Content-type': 'application/json'}
57     results = {
58         "project_name": "bottlenecks",
59         "case_name": testcase,
60         "description": ("test results for " + testcase),
61         "pod_name": os.environ.get('NODE_NAME', 'unknown'),
62         "installer": os.environ.get('INSTALLER_TYPE', 'unknown'),
63         "version": os.path.basename(os.environ.get('BRANCH', 'unknown')),
64         "build_tag": os.environ.get('BUILD_TAG', 'unknown'),
65         "stop_date": str(stop_date),
66         "start_date": str(start_date),
67         "criteria": criteria,
68         "scenario": os.environ.get('DEPLOY_SCENARIO', 'unknown')
69     }
70     results['details'] = {"test_results": details_doc}
71     target = os.environ.get(
72         'BOTTLENECKS_DB_TARGET',
73         'http://testresults.opnfv.org/test/api/v1/results')
74     print ('Address of the target DB is: %s.' % target)
75     timeout = 5
76     try:
77         LOG.debug('Test result : %s', jsonutils.dump_as_bytes(results))
78         res = requests.post(target,
79                             data=jsonutils.dump_as_bytes(results),
80                             headers=headers,
81                             timeout=timeout)
82         LOG.debug('Test result posting finished with status code'
83                   ' %d.' % res.status_code)
84     except Exception as err:
85         LOG.exception('Failed to record result data: %s', err)
86
87
88 def docker_env_prepare(config):
89     LOG.info("Begin to prepare docker environment")
90     if 'contexts' in config.keys() and config["contexts"] is not None:
91         context_config = config["contexts"]
92         if 'yardstick' in context_config.keys() and \
93            context_config["yardstick"] is not None:
94             docker_env.env_yardstick(context_config['yardstick'])
95             conf_parser.Parser.convert_docker_env(config, "yardstick")
96         if 'dashboard' in context_config.keys() and \
97            context_config["dashboard"] is not None:
98             docker_env.env_elk(context_config['dashboard'])
99             conf_parser.Parser.convert_docker_env(config, "dashboard")
100             LOG.debug('Waiting for ELK init')
101             time.sleep(15)
102     LOG.info("Docker environment have prepared")
103     return
104
105
106 def testsuite_run(test_level, test_name, REPORT="False"):
107     tester_parser = test_name.split("_")
108     if test_level == "testcase":
109         config = conf_parser.Parser.testcase_read(tester_parser[0], test_name)
110     elif test_level == "teststory":
111         config = conf_parser.Parser.story_read(tester_parser[0], test_name)
112     for testcase in config:
113         LOG.info("Begin to run %s testcase in POSCA testsuite", testcase)
114         config[testcase]['out_file'] =\
115             conf_parser.Parser.testcase_out_dir(testcase)
116         start_date = datetime.datetime.now()
117         docker_env_prepare(config[testcase])
118         #try:
119         #    posca_testcase_run(tester_parser[0], testcase, config[testcase])
120         #except Exception, e:
121         #    LOG.warning('e.message:\t%s', e.message)
122         posca_testcase_run(tester_parser[0], testcase, config[testcase])
123         stop_date = datetime.datetime.now()
124         LOG.info("End of %s testcase in POSCA testsuite", testcase)
125         criteria = "FAIL"
126         if REPORT == "True":
127             print ('Testing results are about to be sent to the target DB.')
128             details_doc = []
129             if os.path.exists(config[testcase]['out_file']):
130                 with open(config[testcase]['out_file']) as details_result:
131                     details_doc =[json.loads(data) for data in details_result.readlines()] # noqa
132                     if len(details_doc):
133                         criteria = "PASS"
134             report(testcase, start_date, stop_date, criteria, details_doc)
135         else:
136             print ('Testing results have not been sent to the target DB.')
137
138
139 def main():
140     test_level = sys.argv[1]
141     test_name = sys.argv[2]
142     REPORT = sys.argv[3]
143     copy_hosts_file()
144     testsuite_run(test_level, test_name, REPORT)
145
146
147 if __name__ == '__main__':
148     main()