Adapt functest testcase to APi refactoring
[functest.git] / testcases / Controllers / ODL / odlreport2db.py
1 #!/usr/bin/python
2 #
3 # Authors:
4 # - peter.bandzi@cisco.com
5 # - morgan.richomme@orange.com
6 #
7 # src: Peter Bandzi
8 # https://github.com/pbandzi/parse-robot/blob/master/convert_robot_to_json.py
9 #
10 # Copyright (c) 2015 All rights reserved
11 # This program and the accompanying materials
12 # are made available under the terms of the Apache License, Version 2.0
13 # which accompanies this distribution, and is available at
14 #
15 # http://www.apache.org/licenses/LICENSE-2.0
16 #
17 # 0.1: This script boots the VM1 and allocates IP address from Nova
18 # Later, the VM2 boots then execute cloud-init to ping VM1.
19 # After successful ping, both the VMs are deleted.
20 # 0.2: measure test duration and publish results under json format
21 # 0.3: adapt push 2 DB after Test API refacroting
22 #
23 #
24
25 import getopt
26 import json
27 import os
28 import sys
29 import time
30 import xmltodict
31 import yaml
32
33 import functest.utils.functest_utils as functest_utils
34
35
36 def usage():
37     print """Usage:
38     python odlreport2db.py --xml=<output.xml> --pod=<pod name>
39                            --installer=<installer> --database=<database url>
40                            --scenario=<scenario>
41     -x, --xml   xml file generated by robot test
42     -p, --pod   POD name where the test come from
43     -i, --installer
44     -s, --scenario
45     -h, --help  this message
46     """
47     sys.exit(2)
48
49
50 def populate_detail(test):
51     detail = {}
52     detail['test_name'] = test['@name']
53     detail['test_status'] = test['status']
54     detail['test_doc'] = test['doc']
55     return detail
56
57
58 def parse_test(tests, details):
59     try:
60         for test in tests:
61             details.append(populate_detail(test))
62     except TypeError:
63         # tests is not iterable
64         details.append(populate_detail(tests))
65     return details
66
67
68 def parse_suites(suites):
69     data = {}
70     details = []
71     try:
72         for suite in suites:
73             data['details'] = parse_test(suite['test'], details)
74     except TypeError:
75         # suites is not iterable
76         data['details'] = parse_test(suites['test'], details)
77     return data
78
79
80 def main(argv):
81     (xml_file, pod, installer, scenario) = None, None, None, None
82     try:
83         opts, args = getopt.getopt(argv,
84                                    'x:p:i:s:h',
85                                    ['xml=', 'pod=',
86                                     'installer=',
87                                     'scenario=',
88                                     'help'])
89     except getopt.GetoptError:
90         usage()
91
92     for opt, arg in opts:
93         if opt in ('-h', '--help'):
94             usage()
95         elif opt in ('-x', '--xml'):
96             xml_file = arg
97         elif opt in ('-p', '--pod'):
98             pod = arg
99         elif opt in ('-i', '--installer'):
100             installer = arg
101         elif opt in ('-s', '--scenario'):
102             scenario = arg
103         else:
104             usage()
105
106     if not all(x is not None for x in (xml_file, pod, installer, scenario)):
107         usage()
108
109     with open(xml_file, "r") as myfile:
110         xml_input = myfile.read().replace('\n', '')
111
112     # dictionary populated with data from xml file
113     all_data = xmltodict.parse(xml_input)['robot']
114
115     data = parse_suites(all_data['suite']['suite'])
116     data['description'] = all_data['suite']['@name']
117     data['version'] = all_data['@generator']
118     data['test_project'] = "functest"
119     data['case_name'] = "ODL"
120     data['pod_name'] = pod
121     data['installer'] = installer
122
123     json.dumps(data, indent=4, separators=(',', ': '))
124
125     # Only used from container, we can set up absolute path
126     with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
127         functest_yaml = yaml.safe_load(f)
128         f.close()
129
130     try:
131         # example:
132         # python odlreport2db.py -x ~/Pictures/Perso/odl/output3.xml
133         #                        -i fuel
134         #                        -p opnfv-jump-2
135         #                        -s os-odl_l2-ha
136
137         # success criteria for ODL = 100% of tests OK
138         status = "FAIL"
139         # TODO as part of the tests are executed before in the bash
140         # start and stoptime have no real meaning
141         start_time = time.time()
142         stop_time = start_time
143         try:
144             tests_passed = 0
145             tests_failed = 0
146             for v in data['details']:
147                 if v['test_status']['@status'] == "PASS":
148                     tests_passed += 1
149                 else:
150                     tests_failed += 1
151
152             if (tests_failed < 1):
153                 status = "PASS"
154         except:
155             print("Unable to set criteria" % sys.exc_info()[0])
156
157         functest_utils.push_results_to_db("functest",
158                                           data['case_name'],
159                                           None,
160                                           start_time,
161                                           stop_time,
162                                           status,
163                                           data)
164
165     except:
166         print("Error pushing results into Database '%s'" % sys.exc_info()[0])
167
168
169 if __name__ == "__main__":
170     main(sys.argv[1:])