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:
6 # http://www.apache.org/licenses/LICENSE-2.0
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.
14 """Module tracking json in-memory data and saving it to files.
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.
22 Each test case, suite setup (hierarchical) and teardown has its own file pair.
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.
32 from robot.api import logger
33 from robot.libraries.BuiltIn import BuiltIn
35 from resources.libraries.python.Constants import Constants
36 from resources.libraries.python.model.ExportResult import (
37 export_dut_type_and_version
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)
45 """Class handling the json data setting and export."""
47 ROBOT_LIBRARY_SCOPE = u"GLOBAL"
50 """Declare required fields, cache output dir.
52 Also memorize schema validator instances.
54 self.output_dir = BuiltIn().get_variable_value(u"\\${OUTPUT_DIR}", ".")
55 self.raw_file_path = None
57 self.validators = get_validators()
59 def export_pending_data(self):
60 """Write the accumulated data to disk.
62 Create missing directories.
63 Reset both file path and data to avoid writing multiple times.
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.
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.
73 Regardless of whether data was written, it is cleared.
75 if not Constants.EXPORT_JSON or not self.raw_file_path:
77 self.raw_file_path = None
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
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.
91 validate(info_file_path, self.validators[u"tc_info"])
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:
97 f"Previous export not clean, path {self.raw_file_path}\n"
98 f"data: {self.raw_data}"
101 self.raw_file_path = None
103 def start_suite_setup_export(self):
104 """Set new file path, initialize data for the suite setup.
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.
110 File path is set based on suite.
112 self.warn_on_bad_export()
113 start_time = datetime.datetime.utcnow().strftime(
114 u"%Y-%m-%dT%H:%M:%S.%fZ"
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"
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}"
130 # "end_time" and "duration" is added on flush.
131 self.raw_data[u"hosts"] = set()
132 self.raw_data[u"log"] = list()
134 def start_test_export(self):
135 """Set new file path, initialize data to minimal tree for the test case.
137 It is assumed Robot variables DUT_TYPE and DUT_VERSION
138 are already set (in suite setup) to correct values.
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.
144 File path is set based on suite and test.
146 self.warn_on_bad_export()
147 start_time = datetime.datetime.utcnow().strftime(
148 u"%Y-%m-%dT%H:%M:%S.%fZ"
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"
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()
174 def start_suite_teardown_export(self):
175 """Set new file path, initialize data for the suite teardown.
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.
181 File path is set based on suite.
183 self.warn_on_bad_export()
184 start_time = datetime.datetime.utcnow().strftime(
185 u"%Y-%m-%dT%H:%M:%S.%fZ"
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"
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()
201 def finalize_suite_setup_export(self):
202 """Add the missing fields to data. Do not write yet.
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).
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()
211 def finalize_test_export(self):
212 """Add the missing fields to data. Do not write yet.
214 Should be at the end of test teardown, as the implementation
215 reads various Robot variables, some of them only available at teardown.
217 The write is done at next start (or at the end of global teardown).
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()
229 def finalize_suite_teardown_export(self):
230 """Add the missing fields to data. Do not write yet.
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).
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()