Best Python code snippet using unittest-xml-reporting_python
xmlrunner.py
Source:xmlrunner.py  
...154                flavour, test_info.get_elapsed_time(),155                test_info.get_description()))156            self.stream.writeln(self.separator2)157            self.stream.writeln('%s' % test_info.get_error_info())158    def _get_info_by_testcase(self):159        """This method organizes test results by TestCase module. This160        information is used during the report generation, where a XML report161        will be generated for each TestCase.162        """163        tests_by_testcase = {}164        for tests in (self.successes, self.failures, self.errors):165            for test_info in tests:166                testcase = type(test_info.test_method)167                # Ignore module name if it is '__main__'168                module = testcase.__module__ + '.'169                if module == '__main__.':170                    module = ''171                testcase_name = module + testcase.__name__172                if testcase_name not in tests_by_testcase:173                    tests_by_testcase[testcase_name] = []174                tests_by_testcase[testcase_name].append(test_info)175        return tests_by_testcase176    def _report_testsuite(suite_name, tests, xml_document):177        "Appends the testsuite section to the XML document."178        testsuite = xml_document.createElement('testsuite')179        xml_document.appendChild(testsuite)180        testsuite.setAttribute('name', str(suite_name))181        testsuite.setAttribute('tests', str(len(tests)))182        testsuite.setAttribute('time', '%.3f' %183            sum([e.get_elapsed_time() for e in tests]))184        failures = len([1 for e in tests if e.outcome == _TestInfo.FAILURE])185        testsuite.setAttribute('failures', str(failures))186        errors = len([1 for e in tests if e.outcome == _TestInfo.ERROR])187        testsuite.setAttribute('errors', str(errors))188        return testsuite189    _report_testsuite = staticmethod(_report_testsuite)190    def _report_testcase(suite_name, test_result, xml_testsuite, xml_document):191        "Appends a testcase section to the XML document."192        testcase = xml_document.createElement('testcase')193        xml_testsuite.appendChild(testcase)194        testcase.setAttribute('classname', str(suite_name))195        testcase.setAttribute('name', test_result.test_method.shortDescription()196                              or getattr(test_result.test_method, '_testMethodName',197                                         str(test_result.test_method)))198        testcase.setAttribute('time', '%.3f' % test_result.get_elapsed_time())199        if (test_result.outcome != _TestInfo.SUCCESS):200            elem_name = ('failure', 'error')[test_result.outcome-1]201            failure = xml_document.createElement(elem_name)202            testcase.appendChild(failure)203            failure.setAttribute('type', str(test_result.err[0].__name__))204            failure.setAttribute('message', str(test_result.err[1]))205            error_info = test_result.get_error_info()206            failureText = xml_document.createCDATAOrText(error_info)207            failure.appendChild(failureText)208    _report_testcase = staticmethod(_report_testcase)209    def _report_output(test_runner, xml_testsuite, xml_document, stdout, stderr):210        "Appends the system-out and system-err sections to the XML document."211        systemout = xml_document.createElement('system-out')212        xml_testsuite.appendChild(systemout)213        systemout_text = xml_document.createCDATAOrText(stdout)214        systemout.appendChild(systemout_text)215        systemerr = xml_document.createElement('system-err')216        xml_testsuite.appendChild(systemerr)217        systemerr_text = xml_document.createCDATAOrText(stderr)218        systemerr.appendChild(systemerr_text)219    _report_output = staticmethod(_report_output)220    def generate_reports(self, test_runner):221        "Generates the XML reports to a given XMLTestRunner object."222        all_results = self._get_info_by_testcase()223        if type(test_runner.output) == str and not \224            os.path.exists(test_runner.output):225            os.makedirs(test_runner.output)226        for suite, tests in all_results.items():227            doc = XMLDocument()228            # Build the XML file229            testsuite = _XMLTestResult._report_testsuite(suite, tests, doc)230            stdout, stderr = [], []231            for test in tests:232                _XMLTestResult._report_testcase(suite, test, testsuite, doc)233                if test.stdout:234                    stdout.extend(['*****************', test.get_description(), test.stdout])235                if test.stderr:236                    stderr.extend(['*****************', test.get_description(), test.stderr])...xml.py
Source:xml.py  
...32import os33from mule.runners.text import _TextTestResult, TextTestRunner, _TestInfo34class _XMLTestResult(_TextTestResult):35    "A test result class that can express test results in a XML report."36    def _get_info_by_testcase(self):37        """This method organizes test results by TestCase module. This38        information is used during the report generation, where a XML report39        will be generated for each TestCase.40        """41        tests_by_testcase = {}42        43        for tests in (self.successes, self.failures, self.errors, self.skipped):44            for test_info in tests:45                testcase = type(test_info.test_method)46                47                # Ignore module name if it is '__main__'48                module = testcase.__module__ + '.'49                if module == '__main__.':50                    module = ''51                testcase_name = module + testcase.__name__52                53                if not tests_by_testcase.has_key(testcase_name):54                    tests_by_testcase[testcase_name] = []55                tests_by_testcase[testcase_name].append(test_info)56        57        return tests_by_testcase58    59    @classmethod60    def _report_testsuite(cls, suite_name, tests, xml_document):61        "Appends the testsuite section to the XML document."62        testsuite = xml_document.createElement('testsuite')63        xml_document.appendChild(testsuite)64        65        testsuite.setAttribute('name', suite_name)66        testsuite.setAttribute('tests', str(len(tests)))67        68        testsuite.setAttribute('time', '%.3f' % \69            sum(map(lambda e: e.get_elapsed_time(), tests)))70        71        failures = filter(lambda e: e.outcome==_TestInfo.FAILURE, tests)72        testsuite.setAttribute('failures', str(len(failures)))73        74        errors = filter(lambda e: e.outcome==_TestInfo.ERROR, tests)75        testsuite.setAttribute('errors', str(len(errors)))76        skipped = filter(lambda e: e.outcome==_TestInfo.SKIPPED, tests)77        testsuite.setAttribute('skips', str(len(skipped)))78        79        return testsuite80    81    @classmethod82    def _report_testcase(cls, suite_name, test_result, xml_testsuite, xml_document):83        "Appends a testcase section to the XML document."84        testcase = xml_document.createElement('testcase')85        xml_testsuite.appendChild(testcase)86        87        testcase.setAttribute('classname', suite_name)88        testcase.setAttribute('name', test_result.test_method._testMethodName)89        testcase.setAttribute('time', '%.3f' % test_result.get_elapsed_time())90        91        if (test_result.outcome != _TestInfo.SUCCESS):92            elem_name = ('failure', 'error', 'skip')[test_result.outcome-1]93            failure = xml_document.createElement(elem_name)94            testcase.appendChild(failure)95            96            failure.setAttribute('type', test_result.err[0].__name__)97            failure.setAttribute('message', str(test_result.err[1]))98            99            error_info = test_result.get_error_info()100            failureText = xml_document.createCDATASection(error_info)101            failure.appendChild(failureText)102    103    @classmethod104    def _report_output(cls, suite, tests, test_runner, xml_testsuite, xml_document):105        "Appends the system-out and system-err sections to the XML document."106        systemout = xml_document.createElement('system-out')107        xml_testsuite.appendChild(systemout)108        109        stdout = '\n'.join(filter(None, (t.test_method.stdout.getvalue() for t in tests))).strip()110        systemout_text = xml_document.createCDATASection(stdout)111        systemout.appendChild(systemout_text)112        113        systemerr = xml_document.createElement('system-err')114        xml_testsuite.appendChild(systemerr)115        116        stderr = '\n'.join(filter(None, (t.test_method.stderr.getvalue() for t in tests))).strip()117        systemerr_text = xml_document.createCDATASection(stderr)118        systemerr.appendChild(systemerr_text)119    120    def generate_reports(self, test_runner):121        "Generates the XML reports to a given XMLTestRunner object."122        from xml.dom.minidom import Document123        all_results = self._get_info_by_testcase()124        125        if type(test_runner.output) == str and not \126            os.path.exists(test_runner.output):127            os.makedirs(test_runner.output)128        129        for suite, tests in all_results.items():130            doc = Document()131            132            # Build the XML file133            testsuite = _XMLTestResult._report_testsuite(suite, tests, doc)134            for test in tests:135                _XMLTestResult._report_testcase(suite, test, testsuite, doc)136            _XMLTestResult._report_output(suite, tests, test_runner, testsuite, doc)137            xml_content = doc.toprettyxml(indent='\t')...utils.py
Source:utils.py  
...6class PythonVersionModifiedResult(xmlrunner.result._XMLTestResult):  # pylint: disable=protected-access7    """A subclass of XMLTestResult that prefixes the classes with a short string containing the version of Python."""8    def generate_reports(self, test_runner):9        """Generate reports."""10        all_results = self._get_info_by_testcase()11        doc = xml.dom.minidom.Document()12        testsuite = doc.createElement('testsuites')13        doc.appendChild(testsuite)14        parent_element = testsuite15        xml_content = ""16        for suite, tests in all_results.items():17            suite_name = suite18            if test_runner.outsuffix:19                # not checking with 'is not None', empty means no suffix.20                suite_name = f'{suite}-{test_runner.outsuffix}'21            # Build the XML file22            testsuite = PythonVersionModifiedResult._report_testsuite(suite_name, tests, doc, parent_element,23                                                                      self.properties)24            for test_case in testsuite.getElementsByTagName("testcase"):...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
