UTI: Export results
[csit.git] / resources / libraries / python / model / export_json.py
1 # Copyright (c) 2021 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """Module tracking json in-memory data and saving it to files.
15
16 The current implementation tracks data for raw output,
17 and info output is created from raw output on disk (see raw2info module).
18 Raw file contains all log items but no derived quantities,
19 info file contains only important log items but also derived quantities.
20 The overlap between two files is big.
21
22 Each test case, suite setup (hierarchical) and teardown has its own file pair.
23
24 Validation is performed for output files with available JSON schema.
25 Validation is performed in data deserialized from disk,
26 as serialization might have introduced subtle errors.
27 """
28
29 import datetime
30 import os.path
31
32 from robot.api import logger
33 from robot.libraries.BuiltIn import BuiltIn
34
35 from resources.libraries.python.Constants import Constants
36 from resources.libraries.python.model.ExportResult import (
37     export_dut_type_and_version
38 )
39 from resources.libraries.python.model.mem2raw import write_raw_output
40 from resources.libraries.python.model.raw2info import convert_content_to_info
41 from resources.libraries.python.model.validate import (get_validators, validate)
42
43
44 class export_json():
45     """Class handling the json data setting and export."""
46
47     ROBOT_LIBRARY_SCOPE = u"GLOBAL"
48
49     def __init__(self):
50         """Declare required fields, cache output dir.
51
52         Also memorize schema validator instances.
53         """
54         self.output_dir = BuiltIn().get_variable_value(u"\\${OUTPUT_DIR}", ".")
55         self.raw_file_path = None
56         self.raw_data = None
57         self.validators = get_validators()
58
59     def export_pending_data(self):
60         """Write the accumulated data to disk.
61
62         Create missing directories.
63         Reset both file path and data to avoid writing multiple times.
64
65         Functions which finalize content for given file are calling this,
66         so make sure each test and non-empty suite setup or teardown
67         is calling this as their last keyword.
68
69         If no file path is set, do not write anything,
70         as that is the failsafe behavior when caller from unexpected place.
71         Aso do not write anything when EXPORT_JSON constant is false.
72
73         Regardless of whether data was written, it is cleared.
74         """
75         if not Constants.EXPORT_JSON or not self.raw_file_path:
76             self.raw_data = None
77             self.raw_file_path = None
78             return
79         write_raw_output(self.raw_file_path, self.raw_data)
80         # Raw data is going to be cleared (as a sign that raw export succeeded),
81         # so this is the last chance to detect if it was for a test case.
82         is_testcase = u"result" in self.raw_data
83         self.raw_data = None
84         # Validation for raw output goes here when ready.
85         info_file_path = convert_content_to_info(self.raw_file_path)
86         self.raw_file_path = None
87         # If "result" is missing from info content,
88         # it could be a bug in conversion from raw test case content,
89         # so instead of that we use the flag detected earlier.
90         if is_testcase:
91             validate(info_file_path, self.validators[u"tc_info"])
92
93     def warn_on_bad_export(self):
94         """If bad state is detected, log a warning and clean up state."""
95         if self.raw_file_path is not None or self.raw_data is not None:
96             logger.warn(
97                 f"Previous export not clean, path {self.raw_file_path}\n"
98                 f"data: {self.raw_data}"
99             )
100             self.raw_data = None
101             self.raw_file_path = None
102
103     def start_suite_setup_export(self):
104         """Set new file path, initialize data for the suite setup.
105
106         This has to be called explicitly at start of suite setup,
107         otherwise Robot likes to postpone initialization
108         until first call by a data-adding keyword.
109
110         File path is set based on suite.
111         """
112         self.warn_on_bad_export()
113         start_time = datetime.datetime.utcnow().strftime(
114             u"%Y-%m-%dT%H:%M:%S.%fZ"
115         )
116         suite_name = BuiltIn().get_variable_value(u"\\${SUITE_NAME}")
117         suite_id = suite_name.lower().replace(u" ", u"_")
118         suite_path_part = os.path.join(*suite_id.split(u"."))
119         output_dir = self.output_dir
120         self.raw_file_path = os.path.join(
121             output_dir, suite_path_part, u"setup.raw.json"
122         )
123         self.raw_data = dict()
124         self.raw_data[u"version"] = Constants.MODEL_VERSION
125         self.raw_data[u"start_time"] = start_time
126         self.raw_data[u"suite_name"] = suite_name
127         self.raw_data[u"suite_documentation"] = BuiltIn().get_variable_value(
128             u"\\${SUITE_DOCUMENTATION}"
129         )
130         # "end_time" and "duration" is added on flush.
131         self.raw_data[u"hosts"] = set()
132         self.raw_data[u"log"] = list()
133
134     def start_test_export(self):
135         """Set new file path, initialize data to minimal tree for the test case.
136
137         It is assumed Robot variables DUT_TYPE and DUT_VERSION
138         are already set (in suite setup) to correct values.
139
140         This function has to be called explicitly at the start of test setup,
141         otherwise Robot likes to postpone initialization
142         until first call by a data-adding keyword.
143
144         File path is set based on suite and test.
145         """
146         self.warn_on_bad_export()
147         start_time = datetime.datetime.utcnow().strftime(
148             u"%Y-%m-%dT%H:%M:%S.%fZ"
149         )
150         suite_name = BuiltIn().get_variable_value(u"\\${SUITE_NAME}")
151         suite_id = suite_name.lower().replace(u" ", u"_")
152         suite_path_part = os.path.join(*suite_id.split(u"."))
153         test_name = BuiltIn().get_variable_value(u"\\${TEST_NAME}")
154         self.raw_file_path = os.path.join(
155             self.output_dir, suite_path_part,
156             test_name.lower().replace(u" ", u"_") + u".raw.json"
157         )
158         self.raw_data = dict()
159         self.raw_data[u"version"] = Constants.MODEL_VERSION
160         self.raw_data[u"start_time"] = start_time
161         self.raw_data[u"suite_name"] = suite_name
162         self.raw_data[u"test_name"] = test_name
163         test_doc = BuiltIn().get_variable_value(u"\\${TEST_DOCUMENTATION}", u"")
164         self.raw_data[u"test_documentation"] = test_doc
165         # "test_type" is added when converting to info.
166         # "tags" is detected and added on flush.
167         # "end_time" and "duration" is added on flush.
168         # Robot status and message are added on flush.
169         self.raw_data[u"result"] = dict(type=u"unknown")
170         self.raw_data[u"hosts"] = set()
171         self.raw_data[u"log"] = list()
172         export_dut_type_and_version()
173
174     def start_suite_teardown_export(self):
175         """Set new file path, initialize data for the suite teardown.
176
177         This has to be called explicitly at start of suite teardown,
178         otherwise Robot likes to postpone initialization
179         until first call by a data-adding keyword.
180
181         File path is set based on suite.
182         """
183         self.warn_on_bad_export()
184         start_time = datetime.datetime.utcnow().strftime(
185             u"%Y-%m-%dT%H:%M:%S.%fZ"
186         )
187         suite_name = BuiltIn().get_variable_value(u"\\${SUITE_NAME}")
188         suite_id = suite_name.lower().replace(u" ", u"_")
189         suite_path_part = os.path.join(*suite_id.split(u"."))
190         self.raw_file_path = os.path.join(
191             self.output_dir, suite_path_part, u"teardown.raw.json"
192         )
193         self.raw_data = dict()
194         self.raw_data[u"version"] = Constants.MODEL_VERSION
195         self.raw_data[u"start_time"] = start_time
196         self.raw_data[u"suite_name"] = suite_name
197         # "end_time" and "duration" is added on flush.
198         self.raw_data[u"hosts"] = set()
199         self.raw_data[u"log"] = list()
200
201     def finalize_suite_setup_export(self):
202         """Add the missing fields to data. Do not write yet.
203
204         Should be run at the end of suite setup.
205         The write is done at next start (or at the end of global teardown).
206         """
207         end_time = datetime.datetime.utcnow().strftime(u"%Y-%m-%dT%H:%M:%S.%fZ")
208         self.raw_data[u"end_time"] = end_time
209         self.export_pending_data()
210
211     def finalize_test_export(self):
212         """Add the missing fields to data. Do not write yet.
213
214         Should be at the end of test teardown, as the implementation
215         reads various Robot variables, some of them only available at teardown.
216
217         The write is done at next start (or at the end of global teardown).
218         """
219         end_time = datetime.datetime.utcnow().strftime(u"%Y-%m-%dT%H:%M:%S.%fZ")
220         message = BuiltIn().get_variable_value(u"\\${TEST_MESSAGE}")
221         status = BuiltIn().get_variable_value(u"\\${TEST_STATUS}")
222         test_tags = BuiltIn().get_variable_value(u"\\${TEST_TAGS}")
223         self.raw_data[u"end_time"] = end_time
224         self.raw_data[u"tags"] = list(test_tags)
225         self.raw_data[u"status"] = status
226         self.raw_data[u"message"] = message
227         self.export_pending_data()
228
229     def finalize_suite_teardown_export(self):
230         """Add the missing fields to data. Do not write yet.
231
232         Should be run at the end of suite teardown
233         (but before the explicit write in the global suite teardown).
234         The write is done at next start (or explicitly for global teardown).
235         """
236         end_time = datetime.datetime.utcnow().strftime(u"%Y-%m-%dT%H:%M:%S.%fZ")
237         self.raw_data[u"end_time"] = end_time
238         self.export_pending_data()