1717 has_lxml = False
1818
1919
20- def get_expected_xml (test_case_name : str , test_suites : bool = True ):
20+ def get_expected_xml (test_case_name : str , test_suites : bool = True , newlines : bool = False ):
2121 if sys .version .startswith ("3.6." ) and not has_lxml :
2222 expected_test_suite = '<testsuite errors="0" failures="0" name="suite1" skipped="0" tests="1" time="0">'
2323 else :
@@ -37,9 +37,13 @@ def get_expected_xml(test_case_name: str, test_suites: bool = True):
3737 start_test_suites = ""
3838 end_test_suites = ""
3939
40+ eol = "\n " if newlines else ""
41+ indent = " " if newlines else ""
4042 return (
4143 f"<?xml version='1.0' encoding='{ encoding } '?>\n "
42- f'{ start_test_suites } { expected_test_suite } <testcase name="{ test_case_name } "{ closing_tag } ></testsuite>{ end_test_suites } '
44+ f'{ start_test_suites } { expected_test_suite } { eol } '
45+ f'{ indent } <testcase name="{ test_case_name } "{ closing_tag } >{ eol } '
46+ f'</testsuite>{ end_test_suites } '
4347 )
4448
4549
@@ -129,6 +133,31 @@ def test_write_nonascii():
129133 assert xmlfile .getvalue ().decode ("utf-8" ) == get_expected_xml ("用例1" )
130134
131135
136+ def test_write_no_testsuites ():
137+ # Has to be a binary string to include xml declarations.
138+ text = b"""<?xml version='1.0' encoding='UTF-8'?>
139+ <testsuite name="suite1" tests="1" errors="0" failures="0" skipped="0" time="0">
140+ <testcase name="case1"/>
141+ </testsuite>"""
142+ xml = JUnitXml .fromstring (text )
143+ assert isinstance (xml , JUnitXml )
144+ suite = next (iter (xml ))
145+ assert isinstance (suite , TestSuite )
146+ case = next (iter (suite ))
147+ assert isinstance (case , TestCase )
148+ assert len (case .result ) == 0
149+
150+ # writing this JUnitXml object contains a root <testsuites> element
151+ xmlfile = BytesIO ()
152+ xml .write (xmlfile )
153+ assert xmlfile .getvalue ().decode ("utf-8" ) == get_expected_xml ("case1" , test_suites = True , newlines = True )
154+
155+ # writing the inner testsuite reproduces the input string
156+ xmlfile = BytesIO ()
157+ suite .write (xmlfile )
158+ assert xmlfile .getvalue ().decode ("utf-8" ) == get_expected_xml ("case1" , test_suites = False , newlines = True )
159+
160+
132161def test_read_written_xml ():
133162 suite1 = TestSuite ()
134163 suite1 .name = "suite1"
0 commit comments