[Checkins] SVN: zope.tal/trunk/src/zope/tal/ Make runtest.py use optparse.

Marius Gedminas cvs-admin at zope.org
Mon Feb 11 13:22:11 UTC 2013


Log message for revision 129261:
  Make runtest.py use optparse.
  
  Make python -m zope.tal.runtest work even when your current working
  directory is not src/zope/tal/

Changed:
  U   zope.tal/trunk/src/zope/tal/driver.py
  U   zope.tal/trunk/src/zope/tal/runtest.py
  U   zope.tal/trunk/src/zope/tal/tests/test_files.py

-=-
Modified: zope.tal/trunk/src/zope/tal/driver.py
===================================================================
--- zope.tal/trunk/src/zope/tal/driver.py	2013-02-11 13:22:08 UTC (rev 129260)
+++ zope.tal/trunk/src/zope/tal/driver.py	2013-02-11 13:22:10 UTC (rev 129261)
@@ -12,7 +12,8 @@
 # FOR A PARTICULAR PURPOSE.
 #
 ##############################################################################
-"""Driver program to test METAL and TAL implementation.
+"""Driver program to test METAL and TAL implementation:
+interprets a file, prints results to stdout.
 """
 
 from __future__ import print_function
@@ -77,30 +78,35 @@
            'test32.html': TestEngine,
            }
 
-def main():
-    parser = optparse.OptionParser('usage: %prog [options] testfile',
-                                   description=__doc__)
-    parser.add_option('-H', '--html',
+
+OPTIONS = [
+    optparse.make_option('-H', '--html',
             action='store_const', const='html', dest='mode',
-            help='explicitly choose HTML input (default: use file extension)')
-    parser.add_option('-x', '--xml',
+            help='explicitly choose HTML input (default: use file extension)'),
+    optparse.make_option('-x', '--xml',
             action='store_const', const='xml', dest='mode',
-            help='explicitly choose XML input (default: use file extension)')
-    parser.add_option('-l', '--lenient', action='store_true',
-            help='lenient structure insertion')
+            help='explicitly choose XML input (default: use file extension)'),
+    optparse.make_option('-l', '--lenient', action='store_true',
+            help='lenient structure insertion'),
             # aka don't validate HTML/XML inserted by
             # tal:content="structure expr"
-    parser.add_option('-m', '--macro-only', action='store_true',
-            help='macro expansion only')
-    parser.add_option('-s', '--show-code', action='store_true',
-            help='print intermediate opcodes only')
-    parser.add_option('-t', '--show-tal', action='store_true',
-            help='leave TAL/METAL attributes in output')
-    parser.add_option('-i', '--show-i18n', action='store_true',
-            help='leave I18N substitution string un-interpolated')
-    parser.add_option('-a', '--annotate', action='store_true',
-            help='enable source annotations')
-    opts, args = parser.parse_args()
+    optparse.make_option('-m', '--macro-only', action='store_true',
+            help='macro expansion only'),
+    optparse.make_option('-s', '--show-code', action='store_true',
+            help='print intermediate opcodes only'),
+    optparse.make_option('-t', '--show-tal', action='store_true',
+            help='leave TAL/METAL attributes in output'),
+    optparse.make_option('-i', '--show-i18n', action='store_true',
+            help='leave I18N substitution string un-interpolated'),
+    optparse.make_option('-a', '--annotate', action='store_true',
+            help='enable source annotations'),
+]
+
+def main(values=None):
+    parser = optparse.OptionParser('usage: %prog [options] testfile',
+                                   description=__doc__,
+                                   option_list=OPTIONS)
+    opts, args = parser.parse_args(values=values)
     if not args:
         parser.print_help()
         sys.exit(1)
@@ -144,12 +150,18 @@
             mode = "html"
         else:
             mode = "xml"
-    from zope.tal.talgenerator import TALGenerator
+    # make sure we can find the file
+    prefix = os.path.dirname(os.path.abspath(__file__)) + os.path.sep
+    if (not os.path.exists(file)
+        and os.path.exists(os.path.join(prefix, file))):
+        file = os.path.join(prefix, file)
+    # normalize filenames for test output
     filename = os.path.abspath(file)
-    prefix = os.path.dirname(os.path.abspath(__file__)) + os.path.sep
     if filename.startswith(prefix):
         filename = filename[len(prefix):]
     filename = filename.replace(os.sep, '/') # test files expect slashes
+    # parse
+    from zope.tal.talgenerator import TALGenerator
     if mode == "html":
         from zope.tal.htmltalparser import HTMLTALParser
         p = HTMLTALParser(gen=TALGenerator(source_file=filename, xml=0))

Modified: zope.tal/trunk/src/zope/tal/runtest.py
===================================================================
--- zope.tal/trunk/src/zope/tal/runtest.py	2013-02-11 13:22:08 UTC (rev 129260)
+++ zope.tal/trunk/src/zope/tal/runtest.py	2013-02-11 13:22:10 UTC (rev 129261)
@@ -12,7 +12,9 @@
 # FOR A PARTICULAR PURPOSE.
 #
 ##############################################################################
-"""Driver program to run METAL and TAL regression tests.
+"""Driver program to run METAL and TAL regression tests:
+compares interpeted test files with expected output files in a sibling
+directory.
 """
 
 from __future__ import print_function
@@ -22,6 +24,8 @@
 import sys
 import traceback
 import difflib
+import copy
+import optparse
 
 try:
     # Python 2.x
@@ -37,21 +41,25 @@
     print(''.join(difflib.ndiff(a, b)))
 
 def main():
-    opts = []
-    args = sys.argv[1:]
-    quiet = 0
-    unittesting = 0
-    if args and args[0] == "-q":
-        quiet = 1
-        del args[0]
-    if args and args[0] == "-Q":
-        unittesting = 1
-        del args[0]
-    while args and args[0].startswith('-'):
-        opts.append(args[0])
-        del args[0]
+    parser = optparse.OptionParser('usage: %prog [options] [testfile ...]',
+                                   description=__doc__)
+    parser.add_option('-q', '--quiet', action='store_true',
+            help="less verbose output")
+    internal_options = optparse.OptionGroup(parser, 'Internal options')
+    internal_options.add_option('-Q', '--very-quiet',
+            action='store_true', dest='unittesting',
+            help="no output on success, only diff/traceback on failure")
+    parser.add_option_group(internal_options)
+    driver_options = optparse.OptionGroup(parser, 'Driver options',
+            "(for debugging only; supplying these *will* cause test failures)")
+    for option in zope.tal.driver.OPTIONS:
+        driver_options.add_option(option)
+    parser.add_option_group(driver_options)
+    opts, args = parser.parse_args()
+
     if not args:
-        prefix = os.path.join("tests", "input", "test*.")
+        here = os.path.dirname(__file__)
+        prefix = os.path.join(here, "tests", "input", "test*.")
         if zope.tal.tests.utils.skipxml:
             xmlargs = []
         else:
@@ -66,11 +74,11 @@
     errors = 0
     for arg in args:
         locopts = []
-        if arg.find("metal") >= 0 and "-m" not in opts:
+        if arg.find("metal") >= 0 and not opts.macro_only:
             locopts.append("-m")
-        if arg.find("_sa") >= 0 and "-a" not in opts:
+        if arg.find("_sa") >= 0 and not opts.annotate:
             locopts.append("-a")
-        if not unittesting:
+        if not opts.unittesting:
             print(arg, end=' ')
             sys.stdout.flush()
         if zope.tal.tests.utils.skipxml and arg.endswith(".xml"):
@@ -80,19 +88,19 @@
         try:
             try:
                 sys.stdout = stdout = StringIO()
-                sys.argv = [""] + opts + locopts + [arg]
-                zope.tal.driver.main()
+                sys.argv = ["driver.py"] + locopts + [arg]
+                zope.tal.driver.main(copy.copy(opts))
             finally:
                 sys.stdout, sys.argv = save
         except SystemExit:
             raise
         except:
             errors = 1
-            if quiet:
-                print(sys.exc_info()[0])
+            if opts.quiet:
+                print(sys.exc_info()[0].__name__)
                 sys.stdout.flush()
             else:
-                if unittesting:
+                if opts.unittesting:
                     print()
                 else:
                     print("Failed:")
@@ -122,18 +130,18 @@
         actual = [l.replace('\r\n', '\n') for l in actual]
         expected = [l.replace('\r\n', '\n') for l in expected]
         if actual == expected:
-            if not unittesting:
+            if not opts.unittesting:
                 print("OK")
         else:
-            if unittesting:
+            if opts.unittesting:
                 print()
             else:
                 print("not OK")
             errors = 1
-            if not quiet and expected is not None:
+            if not opts.quiet and expected is not None:
                 showdiff(expected, actual)
     if errors:
-        if unittesting:
+        if opts.unittesting:
             return 1
         else:
             sys.exit(1)
@@ -148,4 +156,4 @@
     return L
 
 if __name__ == "__main__":
-    main()
+    sys.exit(main())

Modified: zope.tal/trunk/src/zope/tal/tests/test_files.py
===================================================================
--- zope.tal/trunk/src/zope/tal/tests/test_files.py	2013-02-11 13:22:08 UTC (rev 129260)
+++ zope.tal/trunk/src/zope/tal/tests/test_files.py	2013-02-11 13:22:10 UTC (rev 129261)
@@ -51,11 +51,11 @@
     def runTest(self):
         basename = os.path.basename(self.__file)
         if basename.startswith('test_sa'):
-            sys.argv = ["", "-Q", "-a", self.__file]
+            sys.argv = ["runtest.py", "-Q", "-a", self.__file]
         elif basename.startswith('test_metal'):
-            sys.argv = ["", "-Q", "-m", self.__file]
+            sys.argv = ["runtest.py", "-Q", "-m", self.__file]
         else:
-            sys.argv = ["", "-Q", self.__file]
+            sys.argv = ["runtest.py", "-Q", self.__file]
         pwd = os.getcwd()
         try:
             os.chdir(self.__dir)



More information about the checkins mailing list