[py-svn] r62176 - in py/branch/pytestplugin/py: . test test/dsession/testing test/plugin test/testing

hpk at codespeak.net hpk at codespeak.net
Thu Feb 26 11:31:44 CET 2009


Author: hpk
Date: Thu Feb 26 11:31:43 2009
New Revision: 62176

Modified:
   py/branch/pytestplugin/py/conftest.py
   py/branch/pytestplugin/py/test/config.py
   py/branch/pytestplugin/py/test/defaultconftest.py
   py/branch/pytestplugin/py/test/dsession/testing/test_hostmanage.py
   py/branch/pytestplugin/py/test/parseopt.py
   py/branch/pytestplugin/py/test/plugin/pytest_apigen.py
   py/branch/pytestplugin/py/test/plugin/pytest_pytester.py
   py/branch/pytestplugin/py/test/pytestplugin.py
   py/branch/pytestplugin/py/test/testing/test_config.py
   py/branch/pytestplugin/py/test/testing/test_parseopt.py
   py/branch/pytestplugin/py/test/testing/test_pytestplugin.py
Log:
port to use new parser


Modified: py/branch/pytestplugin/py/conftest.py
==============================================================================
--- py/branch/pytestplugin/py/conftest.py	(original)
+++ py/branch/pytestplugin/py/conftest.py	Thu Feb 26 11:31:43 2009
@@ -19,21 +19,21 @@
 import py
 Option = py.test.config.Option
 
-option = py.test.config.addoptions("py lib options", 
-        Option('-S', '',
+py.test.config.addoptions("py lib testing options", 
+        Option('--sshtarget', 
                action="store", dest="sshtarget", default=None,
                help=("target to run tests requiring ssh, e.g. "
                      "user at codespeak.net")),
-        Option('', '--apigenpath',
+        Option('--apigenpath',
                action="store", dest="apigenpath",
                default="../apigen", 
                type="string",
                help="relative path to apigen doc output location (relative from py/)"), 
-        Option('', '--docpath',
+        Option('--docpath',
                action='store', dest='docpath',
                default="doc", type='string',
                help="relative path to doc output location (relative from py/)"), 
-        Option('', '--runslowtests',
+        Option('--runslowtests',
                action="store_true", dest="runslowtests", default=False,
                help="run slow tests)"),
     )

Modified: py/branch/pytestplugin/py/test/config.py
==============================================================================
--- py/branch/pytestplugin/py/test/config.py	(original)
+++ py/branch/pytestplugin/py/test/config.py	Thu Feb 26 11:31:43 2009
@@ -4,7 +4,8 @@
 from conftesthandle import Conftest
 from py.__.test.defaultconftest import adddefaultoptions
 
-optparse = py.compat.optparse
+from py.__.test import parseopt
+from py.__.misc.warn import APIWARN
 
 # XXX move to Config class
 basetemp = None
@@ -26,13 +27,15 @@
 
 class Config(object): 
     """ central bus for dealing with configuration/initialization data. """ 
-    Option = optparse.Option
+    Option = py.compat.optparse.Option # deprecated
     _initialized = False
 
     def __init__(self, pytestplugins=None): 
         self.option = CmdOptions()
-        self._parser = optparse.OptionParser(
-            usage="usage: %prog [options] [query] [filenames of tests]")
+        self._parser = parseopt.Parser(
+            usage="usage: %prog [options] [file_or_dir] [file_or_dir] [...]",
+            processopt=self._processopt,
+        )
         if pytestplugins is None:
             pytestplugins = py.test._PytestPlugins()
         assert isinstance(pytestplugins, py.test._PytestPlugins)
@@ -40,6 +43,11 @@
         self.pytestplugins = pytestplugins
         self._conftest = Conftest(onimport=self.pytestplugins.consider_conftest)
 
+    def _processopt(self, opt):
+        if hasattr(opt, 'default') and opt.dest:
+            if not hasattr(self.option, opt.dest):
+                setattr(self.option, opt.dest, opt.default)
+
     def parse(self, args): 
         """ parse cmdline arguments into this config object. 
             Note that this can only be called once per testing process. 
@@ -52,8 +60,7 @@
         self.pytestplugins.consider_env()
         self.pytestplugins.do_addoption(self)
         args = [str(x) for x in args]
-        cmdlineoption, args = self._parser.parse_args(args) 
-        self.option.__dict__.update(vars(cmdlineoption))
+        args = self._parser.parse_setoption(args, self.option)
         if not args:
             args.append(py.std.os.getcwd())
         self.topdir = gettopdir(args)
@@ -132,27 +139,14 @@
         """ add a named group of options to the current testing session. 
             This function gets invoked during testing session initialization. 
         """ 
-        for spec in specs:
-            for shortopt in spec._short_opts:
-                if not shortopt.isupper(): 
-                    raise ValueError(
-                        "custom options must be capital letter "
-                        "got %r" %(spec,)
-                    )
-        return self._addoptions(groupname, *specs)
-
-    def addoption(self, *args, **kwargs):
-        return self.addoptions("misc", self.Option(*args, **kwargs))
-
-    def _addoptions(self, groupname, *specs):
-        optgroup = optparse.OptionGroup(self._parser, groupname) 
-        optgroup.add_options(specs) 
-        self._parser.add_option_group(optgroup)
-        for opt in specs: 
-            if hasattr(opt, 'default') and opt.dest:
-                if not hasattr(self.option, opt.dest):
-                    setattr(self.option, opt.dest, opt.default) 
-        return self.option
+        APIWARN("1.0", "define plugins to add options", stacklevel=2)
+        group = self._parser.addgroup(groupname)
+        for opt in specs:
+            group._addoption_instance(opt)
+        return self.option 
+
+    def addoption(self, *optnames, **attrs):
+        return self._parser.addoption(*optnames, **attrs)
 
     def getvalue(self, name, path=None): 
         """ return 'name' value looked up from the 'options'

Modified: py/branch/pytestplugin/py/test/defaultconftest.py
==============================================================================
--- py/branch/pytestplugin/py/test/defaultconftest.py	(original)
+++ py/branch/pytestplugin/py/test/defaultconftest.py	Thu Feb 26 11:31:43 2009
@@ -43,75 +43,72 @@
 
 def adddefaultoptions(config):
     Option = config.Option 
-    config._addoptions('general options',
-        Option('-v', '--verbose',
-               action="count", dest="verbose", default=0,
-               help="increase verbosity."),
-        Option('-x', '--exitfirst',
+    group = config._parser.addgroup("general", "general options")
+    group._addoption('-v', '--verbose', action="count", 
+               dest="verbose", default=0, help="increase verbosity."),
+    group._addoption('-x', '--exitfirst',
                action="store_true", dest="exitfirst", default=False,
                help="exit instantly on first error or failed test."),
-        Option('-s', '--nocapture',
+    group._addoption('-s', '--nocapture',
                action="store_true", dest="nocapture", default=False,
                help="disable catching of sys.stdout/stderr output."),
-        Option('-k',
+    group._addoption('-k',
                action="store", dest="keyword", default='',
                help="only run test items matching the given "
                     "keyword expression."),
-        Option('-l', '--showlocals',
+    group._addoption('-l', '--showlocals',
                action="store_true", dest="showlocals", default=False,
                help="show locals in tracebacks (disabled by default)."),
-        Option('--showskipsummary',
+    group._addoption('--showskipsummary',
                action="store_true", dest="showskipsummary", default=False,
                help="always show summary of skipped tests"), 
-        Option('', '--pdb',
+    group._addoption('', '--pdb',
                action="store_true", dest="usepdb", default=False,
                help="start pdb (the Python debugger) on errors."),
-        Option('', '--tb',
+    group._addoption('', '--tb',
                action="store", dest="tbstyle", default='long',
                type="choice", choices=['long', 'short', 'no'],
                help="traceback verboseness (long/short/no)."),
-        Option('', '--fulltrace',
+    group._addoption('', '--fulltrace',
                action="store_true", dest="fulltrace", default=False,
                help="don't cut any tracebacks (default is to cut)."),
-        Option('', '--nomagic',
+    group._addoption('', '--nomagic',
                action="store_true", dest="nomagic", default=False,
                help="refrain from using magic as much as possible."),
-        Option('', '--traceconfig',
+    group._addoption('', '--traceconfig',
                action="store_true", dest="traceconfig", default=False,
                help="trace considerations of conftest.py files."),
-        Option('-f', '--looponfailing',
+    group._addoption('-f', '--looponfailing',
                action="store_true", dest="looponfailing", default=False,
                help="loop on failing test set."),
-        Option('', '--exec',
+    group._addoption('', '--exec',
                action="store", dest="executable", default=None,
                help="python executable to run the tests with."),
-        Option('-n', '--numprocesses', dest="numprocesses", default=0, 
+    group._addoption('-n', '--numprocesses', dest="numprocesses", default=0, 
                action="store", type="int", 
                help="number of local test processes."),
-        Option('', '--debug',
+    group._addoption('', '--debug',
                action="store_true", dest="debug", default=False,
                help="turn on debugging information."),
-    )
 
-    config._addoptions('EXPERIMENTAL options',
-        Option('-d', '--dist',
+    group = config._parser.addgroup("experimental", "experimental options")
+    group._addoption('-d', '--dist',
                action="store_true", dest="dist", default=False,
                help="ad-hoc distribute tests across machines (requires conftest settings)"), 
-        Option('-w', '--startserver',
+    group._addoption('-w', '--startserver',
                action="store_true", dest="startserver", default=False,
                help="starts local web server for displaying test progress.", 
                ),
-        Option('-r', '--runbrowser',
+    group._addoption('-r', '--runbrowser',
                action="store_true", dest="runbrowser", default=False,
                help="run browser (implies --startserver)."
                ),
-        Option('', '--boxed',
+    group._addoption('', '--boxed',
                action="store_true", dest="boxed", default=False,
                help="box each test run in a separate process"), 
-        Option('', '--rest',
+    group._addoption('', '--rest',
                action='store_true', dest="restreport", default=False,
                help="restructured text output reporting."),
-        Option('', '--session',
+    group._addoption('', '--session',
                action="store", dest="session", default=None,
                help="lookup given sessioname in conftest.py files and use it."),
-    )

Modified: py/branch/pytestplugin/py/test/dsession/testing/test_hostmanage.py
==============================================================================
--- py/branch/pytestplugin/py/test/dsession/testing/test_hostmanage.py	(original)
+++ py/branch/pytestplugin/py/test/dsession/testing/test_hostmanage.py	Thu Feb 26 11:31:43 2009
@@ -96,8 +96,7 @@
         assert l[0] == host.python
 
     def test_initgateway_ssh_and_remotepath(self):
-        from py.__.conftest import option
-        if not option.sshtarget:
+        if not py.test.config.option.sshtarget:
             py.test.skip("no known ssh target, use -S to set one")
         host = Host("%s" % (option.sshtarget, ))
         # this test should be careful to not write/rsync anything

Modified: py/branch/pytestplugin/py/test/parseopt.py
==============================================================================
--- py/branch/pytestplugin/py/test/parseopt.py	(original)
+++ py/branch/pytestplugin/py/test/parseopt.py	Thu Feb 26 11:31:43 2009
@@ -18,17 +18,17 @@
 
 class Parser:
     """ Parser for command line arguments. """ 
-    _shortoptrestrict = True
 
-    def __init__(self, defaultget=None):
+    def __init__(self, usage=None, processopt=None):
         self._anonymous = OptionGroup("misc", parser=self)
         self._groups = [self._anonymous]
-        self._defaultget = defaultget
+        self._processopt = processopt
+        self._usage = usage 
 
     def processoption(self, option):
-        if self._defaultget:
+        if self._processopt:
             if option.dest:
-                option.default = self._defaultget(option)
+                self._processopt(option)
 
     def addgroup(self, name, description=""):
         for group in self._groups:
@@ -49,7 +49,7 @@
         self._anonymous.addoption(*opts, **attrs)
 
     def parse(self, args):
-        optparser = optparse.OptionParser()
+        optparser = optparse.OptionParser(usage=self._usage)
         for group in self._groups:
             if group.options:
                 optgroup = optparse.OptionGroup(optparser, group.name)
@@ -57,15 +57,12 @@
                 optparser.add_option_group(optgroup)
         return optparser.parse_args(args)
 
-    def _addoptions(self, groupname, *specs):
-        optgroup = optparse.OptionGroup(self._parser, groupname) 
-        optgroup.add_options(specs) 
-        self._parser.add_option_group(optgroup)
-        for opt in specs: 
-            if hasattr(opt, 'default') and opt.dest:
-                if not hasattr(self.option, opt.dest):
-                    setattr(self.option, opt.dest, opt.default) 
-        return self.option
+    def parse_setoption(self, args, option):
+        parsedoption, args = self.parse(args)
+        for name, value in parsedoption.__dict__.items():
+            setattr(option, name, value)
+        return args
+
 
 class OptionGroup:
     def __init__(self, name, description="", parser=None):
@@ -76,11 +73,20 @@
 
     def addoption(self, *optnames, **attrs):
         """ add an option to this group. """
-        if getattr(self.parser, '_shortoptrestrict', False):
-            for opt in optnames:
+        option = py.compat.optparse.Option(*optnames, **attrs)
+        self._addoption_instance(option, shortupper=False)
+
+    def _addoption(self, *optnames, **attrs):
+        option = py.compat.optparse.Option(*optnames, **attrs)
+        self._addoption_instance(option, shortupper=True)
+
+    def _addoption_instance(self, option, shortupper=False):
+        if not shortupper:
+            for opt in option._short_opts:
                 if opt[0] == '-' and opt[1].islower(): 
                     raise ValueError("lowercase shortoptions reserved")
-        option = py.compat.optparse.Option(*optnames, **attrs)
         if self.parser:
             self.parser.processoption(option)
         self.options.append(option)
+
+        

Modified: py/branch/pytestplugin/py/test/plugin/pytest_apigen.py
==============================================================================
--- py/branch/pytestplugin/py/test/plugin/pytest_apigen.py	(original)
+++ py/branch/pytestplugin/py/test/plugin/pytest_apigen.py	Thu Feb 26 11:31:43 2009
@@ -35,6 +35,9 @@
             tr = terminalreporter
             from py.__.apigen.tracer.docstorage import DocStorageAccessor
             terminalreporter.write_sep("=", "apigen: building documentation")
+            from py.__.doc.conftest import option
+            assert terminalreporter.config.option is option
+            assert hasattr(option, 'apigenpath'), option
             capture = py.io.StdCaptureFD()
             try:
                 self.apigenscript.build(
@@ -48,7 +51,7 @@
 def test_generic(plugintester):
     plugintester.apicheck(ApigenPlugin)
 
-def test_simple(testdir):
+def test_functional_simple(testdir):
     sub = testdir.tmpdir.mkdir("test_simple")
     sub.join("__init__.py").write(py.code.Source("""
         from py import initpkg 

Modified: py/branch/pytestplugin/py/test/plugin/pytest_pytester.py
==============================================================================
--- py/branch/pytestplugin/py/test/plugin/pytest_pytester.py	(original)
+++ py/branch/pytestplugin/py/test/plugin/pytest_pytester.py	Thu Feb 26 11:31:43 2009
@@ -49,14 +49,19 @@
         self.tmpdir = tmpdir.mkdir(name)
         self.plugins = []
         self._syspathremove = []
-        #self._olddir = py.std.os.getcwd()
         from py.__.test.config import Config
         self.Config = Config
 
     def finalize(self):
         for p in self._syspathremove:
             py.std.sys.path.remove(p)
-        #py.std.os.chdir(self._olddir)
+        if hasattr(self, '_olddir'):
+            self._olddir.chdir()
+
+    def chdir(self):
+        old = self.testdir.chdir()
+        if not hasattr(self, '_olddir'):
+            self._olddir = old 
 
     def _makefile(self, ext, args, kwargs):
         items = kwargs.items()
@@ -153,7 +158,7 @@
         config = self.Config()
         for plugin in self.plugins:
             if isinstance(plugin, str):
-                config.pytestplugins.import_module(plugin)
+                config.pytestplugins.import_plugin(plugin)
             else:
                 config.pytestplugins.register(plugin)
         return config

Modified: py/branch/pytestplugin/py/test/pytestplugin.py
==============================================================================
--- py/branch/pytestplugin/py/test/pytestplugin.py	(original)
+++ py/branch/pytestplugin/py/test/pytestplugin.py	Thu Feb 26 11:31:43 2009
@@ -82,6 +82,7 @@
 
     def pyevent_plugin_registered(self, plugin):
         if hasattr(self, '_config'):
+            self.pyplugins.call_plugin(plugin, "pytest_addoption", config=self._config._parser)
             self.pyplugins.call_plugin(plugin, "pytest_configure", config=self._config)
 
     def configure(self, config):

Modified: py/branch/pytestplugin/py/test/testing/test_config.py
==============================================================================
--- py/branch/pytestplugin/py/test/testing/test_config.py	(original)
+++ py/branch/pytestplugin/py/test/testing/test_config.py	Thu Feb 26 11:31:43 2009
@@ -1,15 +1,16 @@
 import py
 
+pytest_plugins = 'pytest_iocapture'
+
 class TestConfigCmdlineParsing:
     @py.test.keywords(xfail="commit parser")
-    def test_config_addoption(self):
+    def test_config_addoption(self, stdcapture):
         from py.__.test.config import Config
         config = Config()
         config.addoption("cat1", "--option1", action="store_true")
         config.addoption("cat1", "--option2", action="store_true")
-        cap = py.io.StdCapture()
         config.parse(["-h"])
-        out, err = cap.reset()
+        out, err = stdcapture.reset()
         assert out.count("cat1") == 1
         assert out.find("option1") != -1 
         assert out.find("option2") != -1 
@@ -28,11 +29,8 @@
                         help='t value'),
                 )
             """)
-        old = testdir.chdir() 
-        try: 
-            config = py.test.config._reparse(['-G', '17'])
-        finally: 
-            old.chdir() 
+        testdir.chdir() 
+        config = py.test.config._reparse(['-G', '17'])
         assert config.option.gdest == 17 
 
     def test_config_cmdline_options_only_lowercase(self, testdir): 

Modified: py/branch/pytestplugin/py/test/testing/test_parseopt.py
==============================================================================
--- py/branch/pytestplugin/py/test/testing/test_parseopt.py	(original)
+++ py/branch/pytestplugin/py/test/testing/test_parseopt.py	Thu Feb 26 11:31:43 2009
@@ -1,7 +1,15 @@
 import py
 from py.__.test import parseopt 
 
+pytest_plugins = 'pytest_iocapture'
+
 class TestParser:
+    def test_init(self, stdcapture):
+        parser = parseopt.Parser(usage="xyz")
+        py.test.raises(SystemExit, 'parser.parse(["-h"])')
+        out, err = stdcapture.reset()
+        assert out.find("xyz") != -1
+
     def test_group_add_and_get(self):
         parser = parseopt.Parser()
         group = parser.addgroup("hello", description="desc")
@@ -25,8 +33,7 @@
             group.addoption("-x", action="store_true")
         """)
         assert len(group.options) == 0
-        parser._shortoptrestrict = False
-        group.addoption("-x", action="store_true")
+        group._addoption("-x", action="store_true")
         assert len(group.options) == 1
 
     def test_parser_addoption(self):
@@ -43,13 +50,33 @@
         assert option.hello == "world"
         assert not args
 
+    def test_parse_will_set_default(self):
+        parser = parseopt.Parser()
+        parser.addoption("--hello", dest="hello", default="x", action="store")
+        option, args = parser.parse([])
+        assert option.hello == "x"
+        del option.hello
+        args = parser.parse_setoption([], option)
+        assert option.hello == "x"
+
+    def test_parse_setoption(self):
+        parser = parseopt.Parser()
+        parser.addoption("--hello", dest="hello", action="store")
+        parser.addoption("--world", dest="world", default=42)
+        class A: pass
+        option = A()
+        args = parser.parse_setoption(['--hello', 'world'], option)
+        assert option.hello == "world"
+        assert option.world == 42
+        assert not args
+
     def test_parse_defaultgetter(self):
         def defaultget(option):
             if option.type == "int":
-                return 42 
+                option.default = 42
             elif option.type == "string":
-                return "world"
-        parser = parseopt.Parser(defaultget=defaultget)
+                option.default = "world"
+        parser = parseopt.Parser(processopt=defaultget)
         parser.addoption("--this", dest="this", type="int", action="store")
         parser.addoption("--hello", dest="hello", type="string", action="store")
         parser.addoption("--no", dest="no", action="store_true")

Modified: py/branch/pytestplugin/py/test/testing/test_pytestplugin.py
==============================================================================
--- py/branch/pytestplugin/py/test/testing/test_pytestplugin.py	(original)
+++ py/branch/pytestplugin/py/test/testing/test_pytestplugin.py	Thu Feb 26 11:31:43 2009
@@ -154,6 +154,21 @@
         config.parse([])
         assert not config.option.test123
 
+    def test_do_option_postinitialize(self, testdir):
+        from py.__.test.config import Config 
+        config = Config() 
+        config.parse([])
+        config.pytestplugins.configure(config=config)
+        assert not hasattr(config.option, 'test123')
+        p = testdir.makepyfile("""
+            class ConftestPlugin:
+                def pytest_addoption(self, config):
+                    config.addoption('--test123', action="store_true", 
+                        default=True)
+        """)
+        config._conftest.importconftest(p)
+        assert config.option.test123
+
     def test_configure(self, testdir):
         config = testdir.parseconfig()
         l = []



More information about the pytest-commit mailing list