changeset 221:17e4b8d01db6

* Get rid of `xmlio.SubElement`. * Make the testrunner usable standalone (outside of `setup.py`).
author cmlenz
date Sat, 24 Sep 2005 12:21:34 +0000
parents 3ab0004a6fd9
children 206711a0b276
files bitten/build/ctools.py bitten/build/pythontools.py bitten/build/shtools.py bitten/build/tests/pythontools.py bitten/slave.py bitten/util/beep.py bitten/util/testrunner.py bitten/util/xmlio.py setup.cfg
diffstat 9 files changed, 74 insertions(+), 50 deletions(-) [+]
line wrap: on
line diff
--- a/bitten/build/ctools.py
+++ b/bitten/build/ctools.py
@@ -29,10 +29,10 @@
     for out, err in cmdline.execute():
         if out is not None:
             log.info(out)
-            xmlio.SubElement(log_elem, 'message', level='info')[out]
+            log_elem.append(xmlio.Element('message', level='info')[out])
         if err is not None:
             log.error(err)
-            xmlio.SubElement(log_elem, 'message', level='error')[err]
+            log_elem.append(xmlio.Element('message', level='error')[err])
     ctxt.log(log_elem)
 
     if cmdline.returncode != 0:
--- a/bitten/build/pythontools.py
+++ b/bitten/build/pythontools.py
@@ -27,7 +27,7 @@
     for out, err in cmdline.execute():
         if out is not None:
             log.info(out)
-            xmlio.SubElement(log_elem, 'message', level='info')[out]
+            log_elem.append(xmlio.Element('message', level='info')[out])
         if err is not None:
             level = 'error'
             if err.startswith('warning: '):
@@ -36,7 +36,7 @@
                 log.warning(err)
             else:
                 log.error(err)
-            xmlio.SubElement(log_elem, 'message', level=level)[err]
+            log_elem.append(xmlio.Element('message', level=level)[err])
     ctxt.log(log_elem)
     if cmdline.returncode != 0:
         ctxt.error('distutils failed (%s)' % cmdline.returncode)
@@ -83,13 +83,14 @@
                     filename = os.path.realpath(match.group('file'))
                     if filename.startswith(ctxt.basedir):
                         filename = filename[len(ctxt.basedir) + 1:]
+                    filename = filename.replace(os.sep, '/')
                     lineno = int(match.group('line'))
                     tag = match.group('tag')
-                    xmlio.SubElement(problems, 'problem', category=category,
-                                     type=msg_type, tag=tag, line=lineno,
-                                     file=filename.replace(os.sep, '/'))[
+                    problems.append(xmlio.Element('problem', category=category,
+                                                  type=msg_type, tag=tag,
+                                                  line=lineno, file=filename)[
                         match.group('msg') or ''
-                    ]
+                    ])
             ctxt.report('lint', problems)
         finally:
             fd.close()
--- a/bitten/build/shtools.py
+++ b/bitten/build/shtools.py
@@ -42,12 +42,12 @@
         for out, err in cmdline.execute():
             if out is not None:
                 log.info(out)
-                xmlio.SubElement(log_elem, 'message', level='info')[out]
+                log_elem.append(xmlio.Element('message', level='info')[out])
                 if output:
                     output_file.write(out + os.linesep)
             if err is not None:
                 log.error(err)
-                xmlio.SubElement(log_elem, 'message', level='error')[err]
+                log_elem.append(xmlio.Element('message', level='error')[err])
                 if output:
                     output_file.write(err + os.linesep)
         ctxt.log(log_elem)
@@ -92,12 +92,12 @@
         for out, err in cmdline.execute():
             if out is not None:
                 log.info(out)
-                xmlio.SubElement(log_elem, 'message', level='info')[out]
+                log_elem.append(xmlio.Element('message', level='info')[out])
                 if output:
                     output_file.write(out + os.linesep)
             if err is not None:
                 log.error(err)
-                xmlio.SubElement(log_elem, 'message', level='error')[err]
+                log_elem.append(xmlio.Element('message', level='error')[err])
                 if output:
                     output_file.write(err + os.linesep)
         ctxt.log(log_elem)
--- a/bitten/build/tests/pythontools.py
+++ b/bitten/build/tests/pythontools.py
@@ -12,7 +12,7 @@
 import tempfile
 import unittest
 
-from bitten.build import pythontools, BuildError
+from bitten.build import pythontools
 from bitten.recipe import Context, Recipe
 
 
--- a/bitten/slave.py
+++ b/bitten/slave.py
@@ -184,8 +184,10 @@
                                 step.execute(recipe.ctxt):
                             if type == Recipe.ERROR:
                                 step_failed = True
-                            xmlio.SubElement(xml, type, category=category,
-                                             generator=generator)[output]
+                            xml.append(xmlio.Element(type, category=category,
+                                                     generator=generator)[
+                                output
+                            ])
                     except BuildError, e:
                         log.error('Build step %s failed', step.id)
                         failed = True
@@ -206,7 +208,9 @@
                     xml = xmlio.Element('step', id=step.id, result='failure',
                                         description=step.description,
                                         time=started.isoformat(),
-                                        duration=duration.seconds)[e]
+                                        duration=duration.seconds)[
+                        xmlio.Element('error')[e]
+                    ]
                     if not self.session.dry_run:
                         self.channel.send_ans(msgno, beep.Payload(xml))
 
--- a/bitten/util/beep.py
+++ b/bitten/util/beep.py
@@ -721,7 +721,7 @@
             data = ''
         if isinstance(data, xmlio.Element):
             self.body = StringIO(str(data))
-        elif isinstance(data, (str, unicode)):
+        elif isinstance(data, basestring):
             self.body = StringIO(data)
         else:
             assert hasattr(data, 'read'), \
--- a/bitten/util/testrunner.py
+++ b/bitten/util/testrunner.py
@@ -19,7 +19,8 @@
 from distutils.errors import DistutilsExecError, DistutilsOptionError
 from unittest import _TextTestResult, TextTestRunner
 
-from bitten.util.xmlio import Element, SubElement
+from bitten import __version__ as VERSION
+from bitten.util import xmlio
 
 
 class XMLTestResult(_TextTestResult):
@@ -65,7 +66,7 @@
         if not self.xml_stream:
             return result
 
-        root = Element('unittest-results')
+        root = xmlio.Element('unittest-results')
         for testcase, filename, timetaken, stdout, stderr in result.tests:
             status = 'success'
             tb = None
@@ -90,17 +91,18 @@
                     name = match.group(1)
                     fixture = match.group(2)
 
-            test_elem = SubElement(root, 'test', file=filename, name=name,
-                                   fixture=fixture, status=status,
-                                   duration=timetaken)
+            test_elem = xmlio.Element('test', file=filename, name=name,
+                                      fixture=fixture, status=status,
+                                      duration=timetaken)
             if description:
-                SubElement(test_elem, 'description')[description]
+                test_elem.append(xmlio.Element('description')[description])
             if stdout:
-                SubElement(test_elem, 'stdout')[stdout]
+                test_elem.append(xmlio.Element('stdout')[stdout])
             if stderr:
-                SubElement(test_elem, 'stdout')[stderr]
-            if tb:
-                SubElement(test_elem, 'traceback')[tb]
+                test_elem.append(xmlio.Element('stdout')[stderr])
+            if tb:         
+                test_elem.append(xmlio.Element('traceback')[tb])
+            root.append(test_elem)
 
         root.write(self.xml_stream, newlines=True)
         return result
@@ -111,16 +113,16 @@
     user_options = [('test-suite=', 's',
                      'Name of the unittest suite to run'),
                     ('xml-output=', None,
-                     'Path of the XML file where test results are written to'),
+                     'Path to the XML file where test results are written to'),
                     ('coverage-dir=', None,
                      'Directory where coverage files are to be stored'),
-                     ('coverage-results=', None,
-                     'Name of the file where the coverage summary should be stored')]
+                     ('coverage-summary=', None,
+                     'Path to the file where the coverage summary should be stored')]
 
     def initialize_options(self):
         self.test_suite = None
         self.xml_results = None
-        self.coverage_results = None
+        self.coverage_summary = None
         self.coverage_dir = None
 
     def finalize_options(self):
@@ -141,7 +143,7 @@
             finally:
                 results = trace.results()
                 real_stdout = sys.stdout
-                sys.stdout = open(self.coverage_results, 'w')
+                sys.stdout = open(self.coverage_summary, 'w')
                 try:
                     results.write_results(show_missing=True, summary=True,
                                           coverdir=self.coverage_dir)
@@ -160,3 +162,37 @@
         result = runner.run(suite.suite())
         if result.failures or result.errors:
             raise DistutilsExecError, 'unit tests failed'
+
+
+def main(argv):
+    from distutils.dist import Distribution
+    from optparse import OptionParser
+
+    parser = OptionParser(usage='usage: %prog [options] test_suite ...',
+                          version='%%prog %s' % VERSION)
+    parser.add_option('-o', '--xml-results', action='store', dest='xml_results',
+                      metavar='FILE', help='write XML test results to FILE')
+    parser.add_option('-d', '--coverage-dir', action='store',
+                      dest='coverage_dir', metavar='DIR',
+                      help='store coverage results in DIR')
+    parser.add_option('-s', '--coverage-summary', action='store',
+                      dest='coverage_summary', metavar='FILE',
+                      help='write coverage summary to FILE')
+    options, args = parser.parse_args()
+    if len(args) < 1:
+        parser.error('incorrect number of arguments')
+
+    cmd = unittest(Distribution())
+    cmd.initialize_options()
+    cmd.test_suite = args[0]
+    if hasattr(options, 'xml_results'):
+        cmd.xml_results = options.xml_results
+    if hasattr(options, 'coverage_summary'):
+        cmd.coverage_summary = options.coverage_summary
+    if hasattr(options, 'coverage_dir'):
+        cmd.coverage_dir = options.coverage_dir
+    cmd.finalize_options()
+    cmd.run()
+
+if __name__ == '__main__':
+    main(sys.argv)
--- a/bitten/util/xmlio.py
+++ b/bitten/util/xmlio.py
@@ -160,23 +160,6 @@
             out.write(os.linesep)
 
 
-class SubElement(Element):
-    """Element that is appended as a new child to another element on
-    construction.
-    """
-    __slots__ = []
-
-    def __init__(self, parent_, name_, **attr):
-        """Create an XML element using the specified tag name.
-        
-        The first argument is the instance of the parent element that this
-        subelement should be appended to; the second argument is the name of the
-        tag. All keyword arguments are added as attributes of the element.
-        """
-        Element.__init__(self, name_, **attr)
-        parent_.append(self)
-
-
 class ParseError(Exception):
     """Exception thrown when there's an error parsing an XML document."""
 
--- a/setup.cfg
+++ b/setup.cfg
@@ -8,5 +8,5 @@
 [unittest]
 test-suite = bitten.tests
 xml-results = build/test-results.xml
-coverage-results = build/test-coverage.txt
+coverage-summary = build/test-coverage.txt
 coverage-dir = build/coverage
Copyright (C) 2012-2017 Edgewall Software