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