-
Notifications
You must be signed in to change notification settings - Fork 7
/
testcases_exporter.py
397 lines (332 loc) · 14.5 KB
/
testcases_exporter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# -*- coding: utf-8 -*-
"""
Creates a Testcase XML file for submitting to the Polarion Importer.
Example of input testcases_data:
testcases_data = [
{
"id": "ITEM01",
"title": "test_manual",
"description": "Manual tests with all supported fields.",
"approver-ids": "mkourim:approved",
"assignee-id": "mkourim",
"due-date": "2018-09-30",
"initial-estimate": "1/4h",
"caseautomation": "manualonly",
"caseimportance": "high",
"caselevel": "component",
"caseposneg": "positive",
"testtype": "functional",
"subtype1": "-",
"subtype2": "-",
"upstream": "yes",
"tags": "tag1, tag2",
"setup": "Do this first",
"teardown": "Clean up",
"automation_script": "https://gitlab.com/foo",
"testSteps": ["step1", "step2"],
"expectedResults": ["result1", "result2"],
"linked-items": "ITEM01",
},
{
"title": "test_minimal_param",
"params": ["param1", "param2"],
"linked-items": [{"id": "ITEM01", "role": "derived_from"}],
},
]
"""
from __future__ import absolute_import, unicode_literals
import datetime
import logging
import re
import six
from lxml import etree
from dump2polarion import utils
from dump2polarion.exceptions import Dump2PolarionException, NothingToDoException
from dump2polarion.exporters import transform_projects
# pylint: disable=invalid-name
logger = logging.getLogger(__name__)
class TestcaseTransform(object):
"""Transforms testcase data and fills in default keys and values."""
TESTCASE_DATA = {
"approver-ids": None,
"assignee-id": None,
"due-date": None,
"id": None,
"initial-estimate": None,
}
FIELD_MAPPING = {"assignee-id": "assignee", "initial-estimate": "initialEstimate"}
CUSTOM_FIELDS = {
"arch": None,
"automation_script": None,
"caseautomation": "automated",
"casecomponent": None,
"caseimportance": "high",
"caselevel": "component",
"caseposneg": "positive",
"customerscenario": None,
"endsin": None,
"legacytest": None,
"multiproduct": None,
"reqverify": None,
"setup": None,
"startsin": None,
"subcomponent": None,
"subtype1": "-",
"subtype2": "-",
"tags": None,
"teardown": None,
"testtier": None,
"testtype": "functional",
"upstream": None,
}
def __init__(self, config, transform_func=None):
self.config = config
self._transform_func = transform_func or transform_projects.get_testcases_transform(config)
default_fields = self.config.get("default_fields") or {}
default_fields = {k: utils.get_unicode_str(v) for k, v in default_fields.items() if v}
self.default_fields = utils.sorted_dict(default_fields)
def _fill_project_defaults(self, testcase_data):
filled = self.default_fields.copy()
filled.update(testcase_data)
return filled
def _fill_automation_repo(self, testcase_data):
repo_address = self.config.get("repo_address")
automation_script = testcase_data.get("automation_script")
if not (repo_address and automation_script):
return testcase_data
# the master here should probably link the latest "commit" eventually
testcase_data["automation_script"] = "{}/blob/master/{}".format(
repo_address, automation_script
)
return testcase_data
def _run_transform_func(self, testcase_data):
"""Calls transform function on testcase data."""
if self._transform_func:
testcase_data = self._transform_func(testcase_data)
return testcase_data or None
def _fill_polarion_fields(self, testcase_data):
"""Sets importer field value from polarion field if available."""
for importer_field, polarion_field in self.FIELD_MAPPING.items():
polarion_value = testcase_data.get(polarion_field)
xml_value = testcase_data.get(importer_field)
if polarion_value and not xml_value:
testcase_data[importer_field] = polarion_value
return testcase_data
def _fill_defaults(self, testcase_data):
for defaults in self.TESTCASE_DATA, self.CUSTOM_FIELDS:
for key, value in six.iteritems(defaults):
if value and not testcase_data.get(key):
testcase_data[key] = value
return testcase_data
def transform(self, testcase_data):
"""Transforms testcase data."""
testcase_data = self._fill_project_defaults(testcase_data)
testcase_data = self._fill_automation_repo(testcase_data)
testcase_data = self._fill_polarion_fields(testcase_data)
testcase_data = self._run_transform_func(testcase_data)
if not testcase_data:
return None
testcase_data = self._fill_defaults(testcase_data)
return testcase_data
class TestcaseExport(object):
"""Exports testcases data into XML representation."""
def __init__(self, testcases_data, config, transform_func=None):
self.testcases_data = testcases_data
self.config = config
self._lookup_prop = ""
self.testcases_transform = TestcaseTransform(config, transform_func)
self.known_custom_fields = set(self.testcases_transform.CUSTOM_FIELDS)
self.known_custom_fields.update(self.config.get("custom_fields") or ())
self._compiled_whitelist = None
self._compiled_blacklist = None
if self.config.get("whitelisted_tests"):
self._compiled_whitelist = re.compile(
"(" + ")|(".join(self.config.get("whitelisted_tests")) + ")"
)
if self.config.get("blacklisted_tests"):
self._compiled_blacklist = re.compile(
"(" + ")|(".join(self.config.get("blacklisted_tests")) + ")"
)
def _top_element(self):
"""Returns top XML element."""
attrs = {"project-id": self.config["polarion-project-id"]}
top = etree.Element("testcases", attrs)
return top
def _properties_element(self, parent_element):
"""Returns properties XML element."""
testcases_properties = etree.SubElement(parent_element, "properties")
testcases_properties_conf = self.config.get("testcase_import_properties") or {}
for name, value in sorted(six.iteritems(testcases_properties_conf)):
if name == "lookup-method":
lookup_prop = str(value).lower()
if lookup_prop not in ("id", "name", "custom"):
raise Dump2PolarionException(
"Invalid value '{}' for the 'lookup-method' property".format(str(value))
)
self._lookup_prop = lookup_prop
else:
etree.SubElement(
testcases_properties, "property", {"name": name, "value": str(value)}
)
return testcases_properties
def _fill_lookup_prop(self, testcases_properties):
"""Fills the polarion-lookup-method property."""
if not self._lookup_prop:
raise Dump2PolarionException("Failed to set the 'polarion-lookup-method' property")
etree.SubElement(
testcases_properties, "property", {"name": "lookup-method", "value": self._lookup_prop}
)
def _set_lookup_prop(self, testcase_data):
"""Set lookup property based on processed testcases if not configured."""
if self._lookup_prop:
return
if testcase_data.get("id"):
self._lookup_prop = "id"
elif testcase_data.get("title"):
self._lookup_prop = "name"
else:
return
logger.debug("Setting lookup method for testcases to `%s`", self._lookup_prop)
def _check_lookup_prop(self, testcase_data):
"""Checks that selected lookup property can be used for this testcase."""
if not self._lookup_prop:
return False
if not testcase_data.get("id") and self._lookup_prop != "name":
return False
if not testcase_data.get("title") and self._lookup_prop == "name":
return False
return True
def _get_testcase_id(self, testcase_data):
"""Returns testcase id when possible."""
testcase_id = testcase_data.get("id")
if testcase_id:
return testcase_id
if self._lookup_prop != "name":
return None
return testcase_data.get("title")
def _classify_data(self, testcase_data):
attrs, custom_fields = {}, {}
for key, value in six.iteritems(testcase_data):
if not value:
continue
if key in self.testcases_transform.TESTCASE_DATA:
attrs[key] = value
elif key in self.known_custom_fields:
custom_fields[key] = value
return attrs, custom_fields
@staticmethod
def _add_test_steps(parent, testcase_data):
steps = testcase_data.get("testSteps")
results = testcase_data.get("expectedResults")
params = testcase_data.get("params") or ()
test_steps = etree.SubElement(parent, "test-steps")
if steps and testcase_data["caseautomation"] != "automated":
for index, step in enumerate(steps):
test_step = etree.SubElement(test_steps, "test-step")
test_step_col = etree.SubElement(test_step, "test-step-column", id="step")
test_step_col.text = utils.get_unicode_str(step)
test_res_col = etree.SubElement(test_step, "test-step-column", id="expectedResult")
try:
test_res_col.text = utils.get_unicode_str(results[index])
except IndexError:
test_res_col.text = ""
else:
test_step = etree.SubElement(test_steps, "test-step")
test_step_col = etree.SubElement(test_step, "test-step-column", id="step")
for param in params:
param_el = etree.Element("parameter", name=param, scope="local")
test_step_col.append(param_el)
@staticmethod
def _add_linked_items(parent, testcase_data):
linked_items = testcase_data.get("linked-items") or testcase_data.get("linked-work-items")
if not linked_items:
return
if isinstance(linked_items, (dict, six.string_types)):
linked_items = [linked_items]
linked_work_items = etree.SubElement(parent, "linked-work-items")
for work_item in linked_items:
if isinstance(work_item, six.string_types):
work_item_id = work_item
work_item_role = "verifies"
else:
work_item_id = work_item.get("id")
work_item_role = work_item.get("role") or "verifies"
if not work_item_id:
continue
work_item_el = etree.SubElement(linked_work_items, "linked-work-item")
work_item_el.attrib["workitem-id"] = work_item_id
work_item_el.attrib["role-id"] = work_item_role
lookup_method = testcase_data.get("linked-items-lookup-method")
if lookup_method in ("name", "id"):
work_item_el.attrib["lookup-method"] = lookup_method
@staticmethod
def _fill_custom_fields(parent, custom_fields):
if not custom_fields:
return
custom_fields_el = etree.SubElement(parent, "custom-fields")
for field, content in six.iteritems(custom_fields):
etree.SubElement(
custom_fields_el,
"custom-field",
utils.sorted_dict({"id": field, "content": utils.get_unicode_str(content)}),
)
def _is_whitelisted(self, nodeid):
"""Checks if the nodeid is whitelisted."""
if not nodeid:
return True
if self._compiled_whitelist and self._compiled_whitelist.search(nodeid):
return True
if self._compiled_blacklist and self._compiled_blacklist.search(nodeid):
return False
return True
def _testcase_element(self, parent_element, testcase_data):
"""Adds testcase XML element."""
nodeid = testcase_data.get("nodeid")
if not self._is_whitelisted(nodeid):
logger.debug("Skipping blacklisted node: %s", nodeid)
return
testcase_data = self.testcases_transform.transform(testcase_data)
if not testcase_data:
return
testcase_title = testcase_data.get("title")
self._set_lookup_prop(testcase_data)
if not self._check_lookup_prop(testcase_data):
logger.warning(
"Skipping testcase `%s`, data missing for selected lookup method",
testcase_data.get("id") or testcase_title,
)
return
# make sure that ID is set even for "name" lookup method
testcase_data["id"] = self._get_testcase_id(testcase_data)
attrs, custom_fields = self._classify_data(testcase_data)
# For testing purposes, the order of fields in resulting XML
# needs to be always the same.
attrs = utils.sorted_dict(attrs)
custom_fields = utils.sorted_dict(custom_fields)
testcase = etree.SubElement(parent_element, "testcase", attrs)
title_el = etree.SubElement(testcase, "title")
title_el.text = utils.get_unicode_str(testcase_title)
description = testcase_data.get("description")
if description:
description_el = etree.SubElement(testcase, "description")
description_el.text = utils.get_unicode_str(description)
self._add_test_steps(testcase, testcase_data)
self._fill_custom_fields(testcase, custom_fields)
self._add_linked_items(testcase, testcase_data)
def _fill_testcases(self, parent_element):
if not self.testcases_data:
raise NothingToDoException("Nothing to export")
for testcase_data in self.testcases_data:
self._testcase_element(parent_element, testcase_data)
def export(self):
"""Returns testcases XML."""
top = self._top_element()
properties = self._properties_element(top)
self._fill_testcases(top)
self._fill_lookup_prop(properties)
return utils.prettify_xml(top)
@staticmethod
def write_xml(xml, output_file=None):
"""Outputs the XML content into a file."""
gen_filename = "testcases-{:%Y%m%d%H%M%S}.xml".format(datetime.datetime.now())
utils.write_xml(xml, output_loc=output_file, filename=gen_filename)