本文整理汇总了Python中junit_xml.TestSuite.to_xml_string方法的典型用法代码示例。如果您正苦于以下问题:Python TestSuite.to_xml_string方法的具体用法?Python TestSuite.to_xml_string怎么用?Python TestSuite.to_xml_string使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类junit_xml.TestSuite
的用法示例。
在下文中一共展示了TestSuite.to_xml_string方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: serialize_and_read
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def serialize_and_read(test_suites, to_file=False, prettyprint=None):
"""writes the test suite to an XML string and then re-reads it using minidom,
returning => (test suite element, list of test case elements)"""
try:
iter(test_suites)
except TypeError:
test_suites = [test_suites]
if to_file:
fd, filename = tempfile.mkstemp(text=True)
with os.fdopen(fd, 'w') as f:
TestSuite.to_file(f, test_suites)
print("Serialized XML to temp file [%s]" % filename)
xmldoc = minidom.parse(filename)
os.remove(filename)
else:
if prettyprint is not None:
xml_string = TestSuite.to_xml_string(test_suites, prettyprint=prettyprint)
else:
xml_string = TestSuite.to_xml_string(test_suites)
print("Serialized XML to string:\n%s" % xml_string)
xmldoc = minidom.parseString(xml_string)
ret = []
suites = xmldoc.getElementsByTagName("testsuites")[0]
for suite in suites.getElementsByTagName("testsuite"):
cases = suite.getElementsByTagName("testcase")
ret.append((suite, cases))
return ret
示例2: test_to_xml_string_test_suites_not_a_list
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def test_to_xml_string_test_suites_not_a_list(self):
test_suites = TestSuite('suite1', [TestCase('Test1')])
try:
TestSuite.to_xml_string(test_suites)
except Exception as exc:
self.assertEqual(str(exc), 'test_suites must be a list of test suites')
示例3: exporter_junit_ioper
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def exporter_junit_ioper(self, test_result_ext, test_suite_properties=None):
from junit_xml import TestSuite, TestCase
test_suites = []
test_cases = []
for platform in sorted(test_result_ext.keys()):
# {platform : ['Platform', 'Result', 'Scope', 'Description'])
test_cases = []
for tr_result in test_result_ext[platform]:
result, name, scope, description = tr_result
classname = "test.ioper.%s.%s.%s" % (platform, name, scope)
elapsed_sec = 0
_stdout = description
_stderr = ""
# Test case
tc = TestCase(name, classname, elapsed_sec, _stdout, _stderr)
# Test case extra failure / error info
if result == "FAIL":
tc.add_failure_info(description, _stdout)
elif result == "ERROR":
tc.add_error_info(description, _stdout)
elif result == "SKIP" or result == "NOT_SUPPORTED":
tc.add_skipped_info(description, _stdout)
test_cases.append(tc)
ts = TestSuite("test.suite.ioper.%s" % (platform), test_cases)
test_suites.append(ts)
return TestSuite.to_xml_string(test_suites)
示例4: exporter_junit
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def exporter_junit(test_result_ext, test_suite_properties=None):
"""! Export test results in JUnit XML compliant format
@details This function will import junit_xml library to perform report conversion
@return String containing Junit XML formatted test result output
"""
from junit_xml import TestSuite, TestCase
test_suites = []
test_cases = []
targets = sorted(test_result_ext.keys())
for target in targets:
test_cases = []
tests = sorted(test_result_ext[target].keys())
for test in tests:
test_results = test_result_ext[target][test]
classname = 'test.%s.%s' % (target, test)
elapsed_sec = test_results['elapsed_time']
_stdout = test_results['single_test_output']
_stderr = ''
# Test case
tc = TestCase(test, classname, elapsed_sec, _stdout, _stderr)
# Test case extra failure / error info
if test_results['single_test_result'] == 'FAIL':
message = test_results['single_test_result']
tc.add_failure_info(message, _stdout)
elif test_results['single_test_result'] != 'OK':
message = test_results['single_test_result']
tc.add_error_info(message, _stdout)
test_cases.append(tc)
ts = TestSuite("test.suite.%s" % target, test_cases)
test_suites.append(ts)
return TestSuite.to_xml_string(test_suites)
示例5: parse
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def parse(infile, outfile, format_type, classname, suitename):
testcases = list()
testcase_logs = list()
current = None
test_block_delimiter = known_formats[format_type]['tb_delimiter']
# separate log file into test blocks by test block delimiter
for line in infile:
if test_block_delimiter(line):
if current: # non-empty list
testcase_logs.append(current)
current = list()
if current is not None:
current.append(line)
# add last record if present
if current not in testcase_logs:
testcase_logs.append(current)
# create test cases from test blocks
for entry in testcase_logs:
testcases.append(known_formats[format_type]['test_parser'](entry, classname))
# generate test suite result using provided test cases
test_suite = TestSuite(suitename, testcases)
# get rid of unnecessary 'disabled' strings in formatted xml string
s = TestSuite.to_xml_string([test_suite])
s = s.replace(' disabled=\"0\"', '')
# write xml to outfile
outfile.write(s)
示例6: execute
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def execute(self, log, keyvals, testDef):
testDef.logger.verbose_print("JunitXML Reporter")
# pickup the options
cmds = {}
testDef.parseOptions(log, self.options, keyvals, cmds)
if cmds['filename'] is not None:
self.fh = open(cmds['filename'] if os.path.isabs(cmds['filename']) \
else os.path.join(cmds['scratch'],cmds['filename']), 'w')
if testDef.options['description'] is not None:
print(testDef.options['description'], file=self.fh)
print(file=self.fh)
# Use the Junit classname field to store the list of inifiles
try:
classname = testDef.log['inifiles']
except KeyError:
classname = None
# get the entire log of results
fullLog = testDef.logger.getLog(None)
testCases = []
# TODO: ain't nobody got time for that. 8-).
time = 0
for lg in fullLog:
if 'stdout' in lg and lg['stdout'] is not None:
stdout = "\n".join(lg['stdout'])
else:
stdout = None
if 'stderr' in lg and lg['stderr'] is not None:
stderr = "\n".join(lg['stderr'])
else:
stderr = None
if 'time' in lg and lg['time'] is not None:
time = lg['time']
else:
time = 0
tc = TestCase(lg['section'], classname, time, stdout, stderr)
try:
if 0 != lg['status']:
# Find sections prefixed with 'TestRun'
if re.match("TestRun", lg['section']):
tc.add_failure_info("Test reported failure")
else:
tc.add_error_info("Test error")
except KeyError:
sys.exit(lg['section'] + " is missing status!")
testCases.append(tc)
# TODO: Pull in the resource manager jobid.
jobid = "job1"
ts = TestSuite(jobid, testCases)
print(TestSuite.to_xml_string([ts]), file=self.fh)
if cmds['filename'] is not None:
self.fh.close()
log['status'] = 0
return
示例7: take_action
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def take_action(self, args):
test_cases = []
if args.playbook is not None:
playbooks = args.playbook
results = (models.TaskResult().query
.join(models.Task)
.filter(models.TaskResult.task_id == models.Task.id)
.filter(models.Task.playbook_id.in_(playbooks)))
else:
results = models.TaskResult().query.all()
for result in results:
task_name = result.task.name
if not task_name:
task_name = result.task.action
additional_results = {
'host': result.host.name,
'playbook_path': result.task.playbook.path
}
result_str = jsonutils.dumps(additional_results)
test_path = \
u'{playbook_file}.{play_name}'.format(
playbook_file=os.path.basename(result.task.playbook.path),
play_name=result.task.play.name)
test_case = TestCase(
name=task_name,
classname=test_path,
elapsed_sec=result.duration.seconds,
stdout=result_str)
if result.status == 'skipped':
test_case.add_skipped_info(message=result.result)
elif ((result.status in ('failed', 'unreachable') and
result.ignore_errors is False and
'EXPECTED FAILURE' not in task_name and
'TOGGLE RESULT' not in task_name) or
(result.status == 'ok' and 'TOGGLE RESULT' in task_name)):
test_case.add_failure_info(message=result.result)
test_cases.append(test_case)
test_suite = TestSuite('Ansible Tasks', test_cases)
# TODO: junit_xml doesn't order the TestCase parameters.
# This makes it so the order of the parameters for the same exact
# TestCase is not guaranteed to be the same and thus results in a
# different stdout (or file). This is easily reproducible on Py3.
xml_string = six.text_type(test_suite.to_xml_string([test_suite]))
if args.output_file == '-':
if six.PY2:
sys.stdout.write(encodeutils.safe_encode(xml_string))
else:
sys.stdout.buffer.write(encodeutils.safe_encode(xml_string))
else:
with open(args.output_file, 'wb') as f:
f.write(encodeutils.safe_encode(xml_string))
示例8: exporter_junit
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def exporter_junit(self, test_result_ext, test_suite_properties=None):
""" Export test results in JUnit XML compliant format
"""
from junit_xml import TestSuite, TestCase
test_suites = []
test_cases = []
targets = sorted(test_result_ext.keys())
for target in targets:
toolchains = sorted(test_result_ext[target].keys())
for toolchain in toolchains:
test_cases = []
tests = sorted(test_result_ext[target][toolchain].keys())
for test in tests:
test_results = test_result_ext[target][toolchain][test]
for test_res in test_results:
test_ids = sorted(test_res.keys())
for test_no in test_ids:
test_result = test_res[test_no]
name = test_result["description"]
classname = "%s.%s.%s.%s" % (self.package, target, toolchain, test_result["id"])
elapsed_sec = test_result["elapsed_time"]
_stdout = test_result["output"]
if "target_name_unique" in test_result:
_stderr = test_result["target_name_unique"]
else:
_stderr = test_result["target_name"]
# Test case
tc = TestCase(name, classname, elapsed_sec, _stdout, _stderr)
# Test case extra failure / error info
message = test_result["result"]
if test_result["result"] == "FAIL":
tc.add_failure_info(message, _stdout)
elif test_result["result"] == "SKIP" or test_result["result"] == "NOT_SUPPORTED":
tc.add_skipped_info(message, _stdout)
elif test_result["result"] != "OK":
tc.add_error_info(message, _stdout)
test_cases.append(tc)
ts = TestSuite(
"test.suite.%s.%s" % (target, toolchain),
test_cases,
properties=test_suite_properties[target][toolchain],
)
test_suites.append(ts)
return TestSuite.to_xml_string(test_suites)
示例9: _generate_report
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def _generate_report(self):
""" generate a TestSuite report from the collected TaskData and HostData """
test_cases = []
for task_uuid, task_data in self._task_data.items():
for host_uuid, host_data in task_data.host_data.items():
test_cases.append(self._build_test_case(task_data, host_data))
test_suite = TestSuite(self._playbook_name, test_cases)
report = TestSuite.to_xml_string([test_suite])
output_file = os.path.join(self._output_dir, '%s-%s.xml' % (self._playbook_name, time.time()))
with open(output_file, 'wb') as xml:
xml.write(to_bytes(report, errors='strict'))
示例10: test_to_xml_string
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def test_to_xml_string(self):
test_suites = [TestSuite('suite1', [TestCase('Test1')]),
TestSuite('suite2', [TestCase('Test2')])]
xml_string = TestSuite.to_xml_string(test_suites)
expected_xml_string = textwrap.dedent("""
<?xml version="1.0" ?>
<testsuites>
\t<testsuite errors="0" failures="0" name="suite1" skipped="0" tests="1" time="0">
\t\t<testcase name="Test1"/>
\t</testsuite>
\t<testsuite errors="0" failures="0" name="suite2" skipped="0" tests="1" time="0">
\t\t<testcase name="Test2"/>
\t</testsuite>
</testsuites>
""".strip("\n"))
self.assertEqual(xml_string, expected_xml_string)
示例11: _test
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def _test():
test_case1 = TestCase('Testname1', 'SetupCluster.Name')
test_case2 = TestCase('Testname2', 'SetupCluster.Name')
test_case3 = TestCase('Testname3', 'SetupCluster.Misc')
test_case4 = TestCase('Testname4', 'SetupCluster.Misc')
test_cases = [test_case1, test_case2, test_case3, test_case4]
ts = TestSuite("My Test Suite", test_cases)
#Run and verify test case
assertCase(test_case1, _exampleFunc(True))
assertCase(test_case2, _exampleFunc(False))
assertCase(test_case3, _exampleFunc(True))
#Skip test case
skipCase(test_case4, "Skip Testname4.", "Testname2 is failed.")
print(ts.to_xml_string([ts]))
示例12: exporter_junit
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def exporter_junit(self, test_result_ext, test_suite_properties=None):
""" Export test results in JUnit XML compliant format
"""
from junit_xml import TestSuite, TestCase
test_suites = []
test_cases = []
targets = sorted(test_result_ext.keys())
for target in targets:
toolchains = sorted(test_result_ext[target].keys())
for toolchain in toolchains:
test_cases = []
tests = sorted(test_result_ext[target][toolchain].keys())
for test in tests:
test_results = test_result_ext[target][toolchain][test]
for test_res in test_results:
test_ids = sorted(test_res.keys())
for test_no in test_ids:
test_result = test_res[test_no]
name = test_result['description']
classname = '%s.%s.%s.%s'% (self.package, target, toolchain, test_result['id'])
elapsed_sec = test_result['elapsed_time']
_stdout = test_result['output']
if 'target_name_unique' in test_result:
_stderr = test_result['target_name_unique']
else:
_stderr = test_result['target_name']
# Test case
tc = TestCase(name, classname, elapsed_sec, _stdout, _stderr)
# Test case extra failure / error info
message = test_result['result']
if test_result['result'] == 'FAIL':
tc.add_failure_info(message, _stdout)
elif test_result['result'] == 'SKIP' or test_result["result"] == 'NOT_SUPPORTED':
tc.add_skipped_info(message, _stdout)
elif test_result['result'] != 'OK':
tc.add_error_info(message, _stdout)
test_cases.append(tc)
ts = TestSuite("test.suite.%s.%s"% (target, toolchain), test_cases, properties=test_suite_properties[target][toolchain])
test_suites.append(ts)
return TestSuite.to_xml_string(test_suites)
示例13: test_to_xml_string
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def test_to_xml_string(self):
test_suites = [TestSuite(name='suite1', test_cases=[TestCase(name='Test1')]),
TestSuite(name='suite2', test_cases=[TestCase(name='Test2')])]
xml_string = TestSuite.to_xml_string(test_suites)
if PY2:
self.assertTrue(isinstance(xml_string, unicode))
expected_xml_string = textwrap.dedent("""
<?xml version="1.0" ?>
<testsuites disabled="0" errors="0" failures="0" tests="2" time="0.0">
\t<testsuite disabled="0" errors="0" failures="0" name="suite1" skipped="0" tests="1" time="0">
\t\t<testcase name="Test1"/>
\t</testsuite>
\t<testsuite disabled="0" errors="0" failures="0" name="suite2" skipped="0" tests="1" time="0">
\t\t<testcase name="Test2"/>
\t</testsuite>
</testsuites>
""".strip("\n")) # NOQA
self.assertEqual(xml_string, expected_xml_string)
示例14: serialize_and_read
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def serialize_and_read(test_suites, to_file=False, prettyprint=False, encoding=None):
"""writes the test suite to an XML string and then re-reads it using minidom,
returning => (test suite element, list of test case elements)"""
try:
iter(test_suites)
except TypeError:
test_suites = [test_suites]
if to_file:
fd, filename = tempfile.mkstemp(text=True)
os.close(fd)
with codecs.open(filename, mode='w', encoding=encoding) as f:
TestSuite.to_file(f, test_suites, prettyprint=prettyprint, encoding=encoding)
print("Serialized XML to temp file [%s]" % filename)
xmldoc = minidom.parse(filename)
os.remove(filename)
else:
xml_string = TestSuite.to_xml_string(
test_suites, prettyprint=prettyprint, encoding=encoding)
if PY2:
assert isinstance(xml_string, unicode)
print("Serialized XML to string:\n%s" % xml_string)
if encoding:
xml_string = xml_string.encode(encoding)
xmldoc = minidom.parseString(xml_string)
def remove_blanks(node):
for x in node.childNodes:
if x.nodeType == minidom.Node.TEXT_NODE:
if x.nodeValue:
x.nodeValue = x.nodeValue.strip()
elif x.nodeType == minidom.Node.ELEMENT_NODE:
remove_blanks(x)
remove_blanks(xmldoc)
xmldoc.normalize()
ret = []
suites = xmldoc.getElementsByTagName("testsuites")[0]
for suite in suites.getElementsByTagName("testsuite"):
cases = suite.getElementsByTagName("testcase")
ret.append((suite, cases))
return ret
示例15: junit_xml
# 需要导入模块: from junit_xml import TestSuite [as 别名]
# 或者: from junit_xml.TestSuite import to_xml_string [as 别名]
def junit_xml(compmake_db):
from junit_xml import TestSuite
jobs = list(all_jobs(compmake_db))
logger.info('Loaded %d jobs' % len(jobs))
N = 10
if len(jobs) < N:
logger.error('too few jobs (I expect at least %s)' % N)
sys.exit(128)
test_cases = []
for job_id in jobs:
tc = junit_test_case_from_compmake(compmake_db, job_id)
test_cases.append(tc)
ts = TestSuite("comptests_test_suite", test_cases)
res = TestSuite.to_xml_string([ts])
check_isinstance(res, six.text_type)
return res