[svn r63894] grand renaming on plugin-related mostly internal objects.

--HG--
branch : trunk
This commit is contained in:
hpk 2009-04-09 16:03:09 +02:00
parent 69aaef64de
commit 5d271b2bde
30 changed files with 206 additions and 210 deletions

View File

@ -25,8 +25,8 @@ version = "1.0.0b1"
initpkg(__name__, initpkg(__name__,
description = "pylib and py.test: agile development and test support library", description = "pylib and py.test: agile development and test support library",
revision = int('$LastChangedRevision: 63869 $'.split(':')[1][:-1]), revision = int('$LastChangedRevision: 63894 $'.split(':')[1][:-1]),
lastchangedate = '$LastChangedDate: 2009-04-08 19:50:14 +0200 (Wed, 08 Apr 2009) $', lastchangedate = '$LastChangedDate: 2009-04-09 16:03:09 +0200 (Thu, 09 Apr 2009) $',
version = version, version = version,
url = "http://pylib.org", url = "http://pylib.org",
download_url = "http://codespeak.net/py/%s/download.html" % version, download_url = "http://codespeak.net/py/%s/download.html" % version,
@ -54,9 +54,9 @@ initpkg(__name__,
exportdefs = { exportdefs = {
# py lib events and plugins # py lib events and plugins
'_com.PyPlugins' : ('./_com.py', 'PyPlugins'), '_com.Registry' : ('./_com.py', 'Registry'),
'_com.MultiCall' : ('./_com.py', 'MultiCall'), '_com.MultiCall' : ('./_com.py', 'MultiCall'),
'_com.pyplugins' : ('./_com.py', 'pyplugins'), '_com.comregistry' : ('./_com.py', 'comregistry'),
'_com.PluginAPI' : ('./_com.py', 'PluginAPI'), '_com.PluginAPI' : ('./_com.py', 'PluginAPI'),
# py lib cmdline tools # py lib cmdline tools
@ -70,7 +70,7 @@ initpkg(__name__,
# helpers for use from test functions or collectors # helpers for use from test functions or collectors
'test.__doc__' : ('./test/__init__.py', '__doc__'), 'test.__doc__' : ('./test/__init__.py', '__doc__'),
'test._PytestPlugins' : ('./test/pytestplugin.py', 'PytestPlugins'), 'test._PluginManager' : ('./test/pytestplugin.py', 'PluginManager'),
'test.raises' : ('./test/outcome.py', 'raises'), 'test.raises' : ('./test/outcome.py', 'raises'),
'test.mark' : ('./test/outcome.py', 'mark',), 'test.mark' : ('./test/outcome.py', 'mark',),
'test.deprecated_call' : ('./test/outcome.py', 'deprecated_call'), 'test.deprecated_call' : ('./test/outcome.py', 'deprecated_call'),
@ -199,6 +199,6 @@ initpkg(__name__,
}) })
import py import py
py._com.pyplugins.consider_env() py._com.comregistry.consider_env()

View File

@ -62,7 +62,7 @@ class MultiCall:
self._ex1 = True self._ex1 = True
class PyPlugins: class Registry:
""" """
Manage Plugins: Load plugins and manage calls to plugins. Manage Plugins: Load plugins and manage calls to plugins.
""" """
@ -71,7 +71,7 @@ class PyPlugins:
def __init__(self, plugins=None): def __init__(self, plugins=None):
if plugins is None: if plugins is None:
plugins = [] plugins = []
self._plugins = plugins self.plugins = plugins
def import_module(self, modspec): def import_module(self, modspec):
# XXX allow modspec to specify version / lookup # XXX allow modspec to specify version / lookup
@ -99,22 +99,22 @@ class PyPlugins:
def register(self, plugin): def register(self, plugin):
assert not isinstance(plugin, str) assert not isinstance(plugin, str)
self.call_each("pytest_plugin_registered", plugin) self.call_each("pytest_plugin_registered", plugin)
self._plugins.append(plugin) self.plugins.append(plugin)
def unregister(self, plugin): def unregister(self, plugin):
self.call_each("pytest_plugin_unregistered", plugin) self.call_each("pytest_plugin_unregistered", plugin)
self._plugins.remove(plugin) self.plugins.remove(plugin)
def getplugins(self): def getplugins(self):
return list(self._plugins) return list(self.plugins)
def isregistered(self, plugin): def isregistered(self, plugin):
return plugin in self._plugins return plugin in self.plugins
def listattr(self, attrname, plugins=None, extra=(), reverse=False): def listattr(self, attrname, plugins=None, extra=(), reverse=False):
l = [] l = []
if plugins is None: if plugins is None:
plugins = self._plugins plugins = self.plugins
if extra: if extra:
plugins += list(extra) plugins += list(extra)
for plugin in plugins: for plugin in plugins:
@ -143,15 +143,15 @@ class PluginAPI:
def __init__(self, apiclass, plugins=None): def __init__(self, apiclass, plugins=None):
self._apiclass = apiclass self._apiclass = apiclass
if plugins is None: if plugins is None:
plugins = pyplugins plugins = comregistry
self._plugins = plugins self.plugins = plugins
for name, method in vars(apiclass).items(): for name, method in vars(apiclass).items():
if name[:2] != "__": if name[:2] != "__":
firstresult = getattr(method, 'firstresult', False) firstresult = getattr(method, 'firstresult', False)
mm = ApiCall(plugins, name, firstresult=firstresult) mm = ApiCall(plugins, name, firstresult=firstresult)
setattr(self, name, mm) setattr(self, name, mm)
def __repr__(self): def __repr__(self):
return "<PluginAPI %r %r>" %(self._apiclass, self._plugins) return "<PluginAPI %r %r>" %(self._apiclass, self.plugins)
class ApiCall: class ApiCall:
def __init__(self, plugins, name, firstresult): def __init__(self, plugins, name, firstresult):
@ -168,4 +168,4 @@ class ApiCall:
#print "making multicall", self #print "making multicall", self
return mc.execute(firstresult=self.firstresult) return mc.execute(firstresult=self.firstresult)
pyplugins = PyPlugins() comregistry = Registry()

View File

@ -1,7 +1,7 @@
import py import py
import os import os
from py._com import PyPlugins, MultiCall from py._com import Registry, MultiCall
from py._com import PluginAPI from py._com import PluginAPI
pytest_plugins = "xfail" pytest_plugins = "xfail"
@ -75,13 +75,13 @@ class TestMultiCall:
#assert res == 10 #assert res == 10
class TestPyPlugins: class TestRegistry:
def test_MultiCall(self): def test_MultiCall(self):
plugins = PyPlugins() plugins = Registry()
assert hasattr(plugins, "MultiCall") assert hasattr(plugins, "MultiCall")
def test_register(self): def test_register(self):
plugins = PyPlugins() plugins = Registry()
class MyPlugin: class MyPlugin:
pass pass
my = MyPlugin() my = MyPlugin()
@ -98,7 +98,7 @@ class TestPyPlugins:
assert plugins.getplugins() == [my2] assert plugins.getplugins() == [my2]
def test_call_methods(self): def test_call_methods(self):
plugins = PyPlugins() plugins = Registry()
class api1: class api1:
def m(self, __call__, x): def m(self, __call__, x):
return x return x
@ -121,7 +121,7 @@ class TestPyPlugins:
assert plugins.call_plugin(api2(), 't') is None assert plugins.call_plugin(api2(), 't') is None
def test_call_none_is_no_result(self): def test_call_none_is_no_result(self):
plugins = PyPlugins() plugins = Registry()
class api1: class api1:
def m(self): def m(self):
return None return None
@ -135,7 +135,7 @@ class TestPyPlugins:
assert plugins.call_each('m') == [41] assert plugins.call_each('m') == [41]
def test_call_noneasresult(self): def test_call_noneasresult(self):
plugins = PyPlugins() plugins = Registry()
class api1: class api1:
def m(self, __call__): def m(self, __call__):
return __call__.NONEASRESULT return __call__.NONEASRESULT
@ -145,7 +145,7 @@ class TestPyPlugins:
assert plugins.call_each('m') == [None, None] assert plugins.call_each('m') == [None, None]
def test_listattr(self): def test_listattr(self):
plugins = PyPlugins() plugins = Registry()
class api1: class api1:
x = 41 x = 41
class api2: class api2:
@ -161,12 +161,12 @@ class TestPyPlugins:
assert l == [43, 42, 41] assert l == [43, 42, 41]
def test_consider_env(self, monkeypatch): def test_consider_env(self, monkeypatch):
plugins = PyPlugins() plugins = Registry()
monkeypatch.setitem(os.environ, 'PYLIB', "unknownconsider_env") monkeypatch.setitem(os.environ, 'PYLIB', "unknownconsider_env")
py.test.raises(ImportError, "plugins.consider_env()") py.test.raises(ImportError, "plugins.consider_env()")
def test_consider_module(self): def test_consider_module(self):
plugins = PyPlugins() plugins = Registry()
mod = py.std.new.module("temp") mod = py.std.new.module("temp")
mod.pylib = ["xxx nomod"] mod.pylib = ["xxx nomod"]
excinfo = py.test.raises(ImportError, "plugins.consider_module(mod)") excinfo = py.test.raises(ImportError, "plugins.consider_module(mod)")
@ -174,10 +174,10 @@ class TestPyPlugins:
plugins.consider_module(mod) plugins.consider_module(mod)
def test_api_and_defaults(): def test_api_and_defaults():
assert isinstance(py._com.pyplugins, PyPlugins) assert isinstance(py._com.comregistry, Registry)
def test_subprocess_env(testdir, monkeypatch): def test_subprocess_env(testdir, monkeypatch):
plugins = PyPlugins() plugins = Registry()
old = py.path.local(py.__file__).dirpath().dirpath().chdir() old = py.path.local(py.__file__).dirpath().dirpath().chdir()
try: try:
monkeypatch.setitem(os.environ, "PYLIB", 'unknownconsider') monkeypatch.setitem(os.environ, "PYLIB", 'unknownconsider')
@ -191,7 +191,7 @@ def test_subprocess_env(testdir, monkeypatch):
class TestPluginAPI: class TestPluginAPI:
def test_happypath(self): def test_happypath(self):
plugins = PyPlugins() plugins = Registry()
class Api: class Api:
def hello(self, arg): def hello(self, arg):
pass pass
@ -208,7 +208,7 @@ class TestPluginAPI:
assert not hasattr(mcm, 'world') assert not hasattr(mcm, 'world')
def test_firstresult(self): def test_firstresult(self):
plugins = PyPlugins() plugins = Registry()
class Api: class Api:
def hello(self, arg): pass def hello(self, arg): pass
hello.firstresult = True hello.firstresult = True
@ -224,4 +224,4 @@ class TestPluginAPI:
def test_default_plugins(self): def test_default_plugins(self):
class Api: pass class Api: pass
mcm = PluginAPI(apiclass=Api) mcm = PluginAPI(apiclass=Api)
assert mcm._plugins == py._com.pyplugins assert mcm.plugins == py._com.comregistry

View File

@ -4,9 +4,9 @@ mypath = py.magic.autopath()
class TestWarningPlugin: class TestWarningPlugin:
def setup_method(self, method): def setup_method(self, method):
self.bus = py._com.PyPlugins() self.pluginmanager = py._com.Registry()
self.wb = WarningPlugin(self.bus) self.wb = WarningPlugin(self.pluginmanager)
self.bus.register(self) self.pluginmanager.register(self)
self.warnings = [] self.warnings = []
def pyevent__WARNING(self, warning): def pyevent__WARNING(self, warning):
@ -46,4 +46,4 @@ class TestWarningPlugin:
def test_default(): def test_default():
from py.__.misc.warn import APIWARN from py.__.misc.warn import APIWARN
assert py._com.pyplugins.isregistered(APIWARN.im_self) assert py._com.comregistry.isregistered(APIWARN.im_self)

View File

@ -10,12 +10,12 @@ class Warning(py.std.exceptions.DeprecationWarning):
def __str__(self): def __str__(self):
return self.msg return self.msg
# XXX probably only apiwarn() + py._com.pyplugins forwarding # XXX probably only apiwarn() + py._com.comregistry forwarding
# warn_explicit is actually needed # warn_explicit is actually needed
class WarningPlugin(object): class WarningPlugin(object):
def __init__(self, bus): def __init__(self, bus):
self.bus = bus self.pluginmanager = bus
bus.register(self) bus.register(self)
def pyevent__WARNING(self, warning): def pyevent__WARNING(self, warning):
@ -62,8 +62,8 @@ class WarningPlugin(object):
filename = module filename = module
path = py.path.local(filename) path = py.path.local(filename)
warning = Warning(msg, path, lineno) warning = Warning(msg, path, lineno)
self.bus.call_each("pyevent__WARNING", warning) self.pluginmanager.call_each("pyevent__WARNING", warning)
# singleton api warner for py lib # singleton api warner for py lib
apiwarner = WarningPlugin(py._com.pyplugins) apiwarner = WarningPlugin(py._com.comregistry)
APIWARN = apiwarner.apiwarn APIWARN = apiwarner.apiwarn

View File

@ -11,10 +11,10 @@ def main(args=None):
config = py.test.config config = py.test.config
try: try:
config.parse(args) config.parse(args)
config.pytestplugins.do_configure(config) config.pluginmanager.do_configure(config)
session = config.initsession() session = config.initsession()
exitstatus = session.main() exitstatus = session.main()
config.pytestplugins.do_unconfigure(config) config.pluginmanager.do_unconfigure(config)
raise SystemExit(exitstatus) raise SystemExit(exitstatus)
except config.Error, e: except config.Error, e:
py.std.sys.stderr.write("ERROR: %s\n" %(e.args[0],)) py.std.sys.stderr.write("ERROR: %s\n" %(e.args[0],))

View File

@ -443,7 +443,7 @@ class Directory(FSCollector):
def consider_dir(self, path, usefilters=None): def consider_dir(self, path, usefilters=None):
if usefilters is not None: if usefilters is not None:
APIWARN("0.99", "usefilters argument not needed") APIWARN("0.99", "usefilters argument not needed")
res = self.config.pytestplugins.call_firstresult( res = self.config.pluginmanager.call_firstresult(
'pytest_collect_recurse', path=path, parent=self) 'pytest_collect_recurse', path=path, parent=self)
if res is None or res: if res is None or res:
return self.config.api.pytest_collect_directory( return self.config.api.pytest_collect_directory(

View File

@ -28,25 +28,24 @@ class Config(object):
basetemp = None basetemp = None
_sessionclass = None _sessionclass = None
def __init__(self, pytestplugins=None, topdir=None): def __init__(self, pluginmanager=None, topdir=None):
self.option = CmdOptions() self.option = CmdOptions()
self.topdir = topdir self.topdir = topdir
self._parser = parseopt.Parser( self._parser = parseopt.Parser(
usage="usage: %prog [options] [file_or_dir] [file_or_dir] [...]", usage="usage: %prog [options] [file_or_dir] [file_or_dir] [...]",
processopt=self._processopt, processopt=self._processopt,
) )
if pytestplugins is None: if pluginmanager is None:
pytestplugins = py.test._PytestPlugins() pluginmanager = py.test._PluginManager()
assert isinstance(pytestplugins, py.test._PytestPlugins) assert isinstance(pluginmanager, py.test._PluginManager)
self.bus = pytestplugins.pyplugins self.pluginmanager = pluginmanager
self.pytestplugins = pytestplugins
self._conftest = Conftest(onimport=self._onimportconftest) self._conftest = Conftest(onimport=self._onimportconftest)
self._setupstate = SetupState() self._setupstate = SetupState()
self.api = pytestplugins.api self.api = pluginmanager.api
def _onimportconftest(self, conftestmodule): def _onimportconftest(self, conftestmodule):
self.trace("loaded conftestmodule %r" %(conftestmodule,)) self.trace("loaded conftestmodule %r" %(conftestmodule,))
self.pytestplugins.consider_conftest(conftestmodule) self.pluginmanager.consider_conftest(conftestmodule)
def trace(self, msg): def trace(self, msg):
if getattr(self.option, 'traceconfig', None): if getattr(self.option, 'traceconfig', None):
@ -76,8 +75,8 @@ class Config(object):
def _preparse(self, args): def _preparse(self, args):
self._conftest.setinitial(args) self._conftest.setinitial(args)
self.pytestplugins.consider_env() self.pluginmanager.consider_env()
self.pytestplugins.do_addoption(self._parser) self.pluginmanager.do_addoption(self._parser)
def parse(self, args): def parse(self, args):
""" parse cmdline arguments into this config object. """ parse cmdline arguments into this config object.
@ -108,7 +107,7 @@ class Config(object):
# * registering to py lib plugins # * registering to py lib plugins
# * setting py.test.config # * setting py.test.config
self.__init__( self.__init__(
pytestplugins=py.test._PytestPlugins(py._com.pyplugins), pluginmanager=py.test._PluginManager(py._com.comregistry),
topdir=py.path.local(), topdir=py.path.local(),
) )
# we have to set py.test.config because preparse() # we have to set py.test.config because preparse()
@ -339,6 +338,6 @@ def gettopdir(args):
# this is the one per-process instance of py.test configuration # this is the one per-process instance of py.test configuration
config_per_process = Config( config_per_process = Config(
pytestplugins=py.test._PytestPlugins(py._com.pyplugins) pluginmanager=py.test._PluginManager(py._com.comregistry)
) )

View File

@ -121,11 +121,11 @@ class DSession(Session):
loopstate.exitstatus = outcome.EXIT_TESTSFAILED loopstate.exitstatus = outcome.EXIT_TESTSFAILED
else: else:
loopstate.exitstatus = outcome.EXIT_OK loopstate.exitstatus = outcome.EXIT_OK
#self.config.bus.unregister(loopstate) #self.config.pluginmanager.unregister(loopstate)
def _initloopstate(self, colitems): def _initloopstate(self, colitems):
loopstate = LoopState(self, colitems) loopstate = LoopState(self, colitems)
self.config.bus.register(loopstate) self.config.pluginmanager.register(loopstate)
return loopstate return loopstate
def loop(self, colitems): def loop(self, colitems):
@ -140,9 +140,9 @@ class DSession(Session):
except KeyboardInterrupt: except KeyboardInterrupt:
exitstatus = outcome.EXIT_INTERRUPTED exitstatus = outcome.EXIT_INTERRUPTED
except: except:
self.config.pytestplugins.notify_exception() self.config.pluginmanager.notify_exception()
exitstatus = outcome.EXIT_INTERNALERROR exitstatus = outcome.EXIT_INTERNALERROR
self.config.bus.unregister(loopstate) self.config.pluginmanager.unregister(loopstate)
if exitstatus == 0 and self._testsfailed: if exitstatus == 0 and self._testsfailed:
exitstatus = outcome.EXIT_TESTSFAILED exitstatus = outcome.EXIT_TESTSFAILED
return exitstatus return exitstatus

View File

@ -174,7 +174,7 @@ class TestDSession:
session.senditems_load([item1, item2]) session.senditems_load([item1, item2])
node = session.item2nodes[item1] [0] node = session.item2nodes[item1] [0]
session.queueevent("pytest_testnodedown", node, None) session.queueevent("pytest_testnodedown", node, None)
evrec = testdir.geteventrecorder(session.bus) evrec = testdir.geteventrecorder(session.pluginmanager)
print session.item2nodes print session.item2nodes
loopstate = session._initloopstate([]) loopstate = session._initloopstate([])
session.loop_once(loopstate) session.loop_once(loopstate)
@ -261,7 +261,7 @@ class TestDSession:
session.addnode(node) session.addnode(node)
loopstate = session._initloopstate([]) loopstate = session._initloopstate([])
loopstate.shuttingdown = True loopstate.shuttingdown = True
evrec = testdir.geteventrecorder(session.bus) evrec = testdir.geteventrecorder(session.pluginmanager)
session.queueevent("pytest_itemtestreport", rep=run(item, node)) session.queueevent("pytest_itemtestreport", rep=run(item, node))
session.loop_once(loopstate) session.loop_once(loopstate)
assert not evrec.getcalls("pytest_testnodedown") assert not evrec.getcalls("pytest_testnodedown")
@ -282,7 +282,7 @@ class TestDSession:
dsel = session.filteritems([modcol]) dsel = session.filteritems([modcol])
assert dsel == [modcol] assert dsel == [modcol]
items = modcol.collect() items = modcol.collect()
callrecorder = testdir.geteventrecorder(session.bus).callrecorder callrecorder = testdir.geteventrecorder(session.pluginmanager).callrecorder
remaining = session.filteritems(items) remaining = session.filteritems(items)
assert remaining == [] assert remaining == []
@ -355,7 +355,7 @@ class TestDSession:
""") """)
config = testdir.parseconfig('-d', p1, '--tx=popen') config = testdir.parseconfig('-d', p1, '--tx=popen')
dsession = DSession(config) dsession = DSession(config)
callrecorder = testdir.geteventrecorder(config.bus).callrecorder callrecorder = testdir.geteventrecorder(config.pluginmanager).callrecorder
dsession.main([config.getfsnode(p1)]) dsession.main([config.getfsnode(p1)])
rep = callrecorder.popcall("pytest_itemtestreport").rep rep = callrecorder.popcall("pytest_itemtestreport").rep
assert rep.passed assert rep.passed

View File

@ -104,7 +104,7 @@ class TestNodeManager:
config = py.test.config._reparse([source, '--debug']) config = py.test.config._reparse([source, '--debug'])
assert config.option.debug assert config.option.debug
nodemanager = NodeManager(config, specs) nodemanager = NodeManager(config, specs)
sorter = testdir.geteventrecorder(config.bus).callrecorder sorter = testdir.geteventrecorder(config.pluginmanager).callrecorder
nodemanager.setup_nodes(putevent=[].append) nodemanager.setup_nodes(putevent=[].append)
for spec in nodemanager.gwmanager.specs: for spec in nodemanager.gwmanager.specs:
l = sorter.getcalls("pytest_trace") l = sorter.getcalls("pytest_trace")

View File

@ -35,7 +35,7 @@ class MySetup:
self.pyfuncitem = pyfuncitem self.pyfuncitem = pyfuncitem
def geteventargs(self, eventname, timeout=2.0): def geteventargs(self, eventname, timeout=2.0):
eq = EventQueue(self.config.bus, self.queue) eq = EventQueue(self.config.pluginmanager, self.queue)
return eq.geteventargs(eventname, timeout=timeout) return eq.geteventargs(eventname, timeout=timeout)
def makenode(self, config=None): def makenode(self, config=None):

View File

@ -61,7 +61,7 @@ class TXNode(object):
except: except:
excinfo = py.code.ExceptionInfo() excinfo = py.code.ExceptionInfo()
print "!" * 20, excinfo print "!" * 20, excinfo
self.config.pytestplugins.notify_exception(excinfo) self.config.pluginmanager.notify_exception(excinfo)
def send(self, item): def send(self, item):
assert item is not None assert item is not None
@ -112,8 +112,8 @@ class SlaveNode(object):
self.config, basetemp = channel.receive() self.config, basetemp = channel.receive()
if basetemp: if basetemp:
self.config.basetemp = py.path.local(basetemp) self.config.basetemp = py.path.local(basetemp)
self.config.pytestplugins.do_configure(self.config) self.config.pluginmanager.do_configure(self.config)
self.config.pytestplugins.register(self) self.config.pluginmanager.register(self)
self.sendevent("slaveready") self.sendevent("slaveready")
try: try:
while 1: while 1:
@ -123,9 +123,9 @@ class SlaveNode(object):
break break
if isinstance(task, list): if isinstance(task, list):
for item in task: for item in task:
item.config.pytestplugins.do_itemrun(item) item.config.pluginmanager.do_itemrun(item)
else: else:
task.config.pytestplugins.do_itemrun(item=task) task.config.pluginmanager.do_itemrun(item=task)
except KeyboardInterrupt: except KeyboardInterrupt:
raise raise
except: except:

View File

@ -116,7 +116,7 @@ def slave_runsession(channel, config, fullwidth, hasmarkup):
config.option.looponfail = False config.option.looponfail = False
config.option.usepdb = False config.option.usepdb = False
trails = channel.receive() trails = channel.receive()
config.pytestplugins.do_configure(config) config.pluginmanager.do_configure(config)
DEBUG("SLAVE: initsession()") DEBUG("SLAVE: initsession()")
session = config.initsession() session = config.initsession()
# XXX configure the reporter object's terminal writer more directly # XXX configure the reporter object's terminal writer more directly
@ -143,7 +143,7 @@ def slave_runsession(channel, config, fullwidth, hasmarkup):
pytest_collectreport = pytest_itemtestreport pytest_collectreport = pytest_itemtestreport
failreports = Failures() failreports = Failures()
session.bus.register(failreports) session.pluginmanager.register(failreports)
DEBUG("SLAVE: starting session.main()") DEBUG("SLAVE: starting session.main()")
session.main(colitems) session.main(colitems)

View File

@ -8,10 +8,10 @@ class PytestArg:
def __init__(self, pyfuncitem): def __init__(self, pyfuncitem):
self.pyfuncitem = pyfuncitem self.pyfuncitem = pyfuncitem
def getcallrecorder(self, apiclass, pyplugins=None): def getcallrecorder(self, apiclass, comregistry=None):
if pyplugins is None: if comregistry is None:
pyplugins = self.pyfuncitem.config.pytestplugins.pyplugins comregistry = self.pyfuncitem.config.pluginmanager.comregistry
callrecorder = CallRecorder(pyplugins) callrecorder = CallRecorder(comregistry)
callrecorder.start_recording(apiclass) callrecorder.start_recording(apiclass)
self.pyfuncitem.addfinalizer(callrecorder.finalize) self.pyfuncitem.addfinalizer(callrecorder.finalize)
return callrecorder return callrecorder
@ -30,8 +30,8 @@ class ParsedCall:
return "<ParsedCall %r(**%r)>" %(self._name, d) return "<ParsedCall %r(**%r)>" %(self._name, d)
class CallRecorder: class CallRecorder:
def __init__(self, pyplugins): def __init__(self, comregistry):
self._pyplugins = pyplugins self._comregistry = comregistry
self.calls = [] self.calls = []
self._recorders = {} self._recorders = {}
@ -44,11 +44,11 @@ class CallRecorder:
setattr(RecordCalls, name, self._getcallparser(method)) setattr(RecordCalls, name, self._getcallparser(method))
recorder = RecordCalls() recorder = RecordCalls()
self._recorders[apiclass] = recorder self._recorders[apiclass] = recorder
self._pyplugins.register(recorder) self._comregistry.register(recorder)
def finalize(self): def finalize(self):
for recorder in self._recorders.values(): for recorder in self._recorders.values():
self._pyplugins.unregister(recorder) self._comregistry.unregister(recorder)
self._recorders.clear() self._recorders.clear()
def recordsmethod(self, name): def recordsmethod(self, name):
@ -99,13 +99,13 @@ def test_generic(plugintester):
plugintester.apicheck(_pytestPlugin) plugintester.apicheck(_pytestPlugin)
def test_callrecorder_basic(): def test_callrecorder_basic():
pyplugins = py._com.PyPlugins() comregistry = py._com.Registry()
rec = CallRecorder(pyplugins) rec = CallRecorder(comregistry)
class ApiClass: class ApiClass:
def xyz(self, arg): def xyz(self, arg):
pass pass
rec.start_recording(ApiClass) rec.start_recording(ApiClass)
pyplugins.call_each("xyz", 123) comregistry.call_each("xyz", 123)
call = rec.popcall("xyz") call = rec.popcall("xyz")
assert call.arg == 123 assert call.arg == 123
assert call._name == "xyz" assert call._name == "xyz"
@ -122,8 +122,8 @@ def test_functional(testdir, linecomp):
class Plugin: class Plugin:
def xyz(self, arg): def xyz(self, arg):
return arg + 1 return arg + 1
rec._pyplugins.register(Plugin()) rec._comregistry.register(Plugin())
res = rec._pyplugins.call_firstresult("xyz", 41) res = rec._comregistry.call_firstresult("xyz", 41)
assert res == 42 assert res == 42
""") """)
sorter.assertoutcome(passed=1) sorter.assertoutcome(passed=1)

View File

@ -158,7 +158,7 @@ class DefaultPlugin:
def loadplugins(self, config): def loadplugins(self, config):
for name in config.getvalue("plugin"): for name in config.getvalue("plugin"):
print "importing", name print "importing", name
config.pytestplugins.import_plugin(name) config.pluginmanager.import_plugin(name)
def setsession(self, config): def setsession(self, config):
val = config.getvalue val = config.getvalue
@ -177,7 +177,7 @@ def test_implied_different_sessions(tmpdir):
def x(*args): def x(*args):
config = py.test.config._reparse([tmpdir] + list(args)) config = py.test.config._reparse([tmpdir] + list(args))
try: try:
config.pytestplugins.do_configure(config) config.pluginmanager.do_configure(config)
except ValueError: except ValueError:
return Exception return Exception
return getattr(config._sessionclass, '__name__', None) return getattr(config._sessionclass, '__name__', None)
@ -194,13 +194,13 @@ def test_plugin_specify(testdir):
testdir.chdir() testdir.chdir()
config = testdir.parseconfig("-p", "nqweotexistent") config = testdir.parseconfig("-p", "nqweotexistent")
py.test.raises(ImportError, py.test.raises(ImportError,
"config.pytestplugins.do_configure(config)" "config.pluginmanager.do_configure(config)"
) )
def test_plugin_already_exists(testdir): def test_plugin_already_exists(testdir):
config = testdir.parseconfig("-p", "default") config = testdir.parseconfig("-p", "default")
assert config.option.plugin == ['default'] assert config.option.plugin == ['default']
config.pytestplugins.do_configure(config) config.pluginmanager.do_configure(config)
class TestDistOptions: class TestDistOptions:

View File

@ -27,7 +27,7 @@ class Support(object):
class PluginTester(Support): class PluginTester(Support):
def testdir(self): def testdir(self):
# XXX import differently, eg. # XXX import differently, eg.
# FSTester = self.pyfuncitem.config.pytestplugins.getpluginattr("pytester", "FSTester") # FSTester = self.pyfuncitem.config.pluginmanager.getpluginattr("pytester", "FSTester")
from pytest_pytester import TmpTestdir from pytest_pytester import TmpTestdir
crunner = TmpTestdir(self.pyfuncitem) crunner = TmpTestdir(self.pyfuncitem)
self.pyfuncitem.addfinalizer(crunner.finalize) self.pyfuncitem.addfinalizer(crunner.finalize)
@ -42,7 +42,7 @@ class PluginTester(Support):
def apicheck(self, pluginclass): def apicheck(self, pluginclass):
print "loading and checking", pluginclass print "loading and checking", pluginclass
fail = False fail = False
pm = py.test._PytestPlugins() pm = py.test._PluginManager()
methods = collectattr(pluginclass) methods = collectattr(pluginclass)
hooks = collectattr(api.PluginHooks) hooks = collectattr(api.PluginHooks)
getargs = py.std.inspect.getargs getargs = py.std.inspect.getargs

View File

@ -25,8 +25,8 @@ class PytesterPlugin:
# return EventRecorder # return EventRecorder
def pytest_funcarg__eventrecorder(self, pyfuncitem): def pytest_funcarg__eventrecorder(self, pyfuncitem):
evrec = EventRecorder(py._com.pyplugins) evrec = EventRecorder(py._com.comregistry)
pyfuncitem.addfinalizer(lambda: evrec.pyplugins.unregister(evrec)) pyfuncitem.addfinalizer(lambda: evrec.comregistry.unregister(evrec))
return evrec return evrec
def test_generic(plugintester): def test_generic(plugintester):
@ -65,10 +65,10 @@ class TmpTestdir:
def __repr__(self): def __repr__(self):
return "<TmpTestdir %r>" % (self.tmpdir,) return "<TmpTestdir %r>" % (self.tmpdir,)
def Config(self, pyplugins=None, topdir=None): def Config(self, comregistry=None, topdir=None):
if topdir is None: if topdir is None:
topdir = self.tmpdir.dirpath() topdir = self.tmpdir.dirpath()
return pytestConfig(pyplugins, topdir=topdir) return pytestConfig(comregistry, topdir=topdir)
def finalize(self): def finalize(self):
for p in self._syspathremove: for p in self._syspathremove:
@ -132,7 +132,7 @@ class TmpTestdir:
#config = self.parseconfig(*args) #config = self.parseconfig(*args)
config = self.parseconfig(*args) config = self.parseconfig(*args)
session = config.initsession() session = config.initsession()
rec = self.geteventrecorder(config.bus) rec = self.geteventrecorder(config.pluginmanager)
colitems = [config.getfsnode(arg) for arg in config.args] colitems = [config.getfsnode(arg) for arg in config.args]
items = list(session.genitems(colitems)) items = list(session.genitems(colitems))
return items, rec return items, rec
@ -152,20 +152,20 @@ class TmpTestdir:
def inline_run(self, *args): def inline_run(self, *args):
config = self.parseconfig(*args) config = self.parseconfig(*args)
config.pytestplugins.do_configure(config) config.pluginmanager.do_configure(config)
session = config.initsession() session = config.initsession()
sorter = self.geteventrecorder(config.bus) sorter = self.geteventrecorder(config.pluginmanager)
session.main() session.main()
config.pytestplugins.do_unconfigure(config) config.pluginmanager.do_unconfigure(config)
return sorter return sorter
def config_preparse(self): def config_preparse(self):
config = self.Config() config = self.Config()
for plugin in self.plugins: for plugin in self.plugins:
if isinstance(plugin, str): if isinstance(plugin, str):
config.pytestplugins.import_plugin(plugin) config.pluginmanager.import_plugin(plugin)
else: else:
config.pytestplugins.register(plugin) config.pluginmanager.register(plugin)
return config return config
def parseconfig(self, *args): def parseconfig(self, *args):
@ -178,7 +178,7 @@ class TmpTestdir:
def parseconfigure(self, *args): def parseconfigure(self, *args):
config = self.parseconfig(*args) config = self.parseconfig(*args)
config.pytestplugins.do_configure(config) config.pluginmanager.do_configure(config)
return config return config
def getitem(self, source, funcname="test_func"): def getitem(self, source, funcname="test_func"):
@ -279,10 +279,10 @@ class ParsedCall:
return "<ParsedCall %r>" %(self.__dict__,) return "<ParsedCall %r>" %(self.__dict__,)
class EventRecorder(object): class EventRecorder(object):
def __init__(self, pyplugins, debug=False): # True): def __init__(self, comregistry, debug=False): # True):
self.pyplugins = pyplugins self.comregistry = comregistry
self.debug = debug self.debug = debug
pyplugins.register(self) comregistry.register(self)
def getcall(self, name): def getcall(self, name):
l = self.getcalls(name) l = self.getcalls(name)
@ -360,11 +360,11 @@ class EventRecorder(object):
self.callrecorder.calls[:] = [] self.callrecorder.calls[:] = []
def unregister(self): def unregister(self):
self.pyplugins.unregister(self) self.comregistry.unregister(self)
self.callrecorder.finalize() self.callrecorder.finalize()
def test_eventrecorder(testdir): def test_eventrecorder(testdir):
bus = py._com.PyPlugins() bus = py._com.Registry()
recorder = testdir.geteventrecorder(bus) recorder = testdir.geteventrecorder(bus)
assert not recorder.getfailures() assert not recorder.getfailures()
rep = runner.ItemTestReport(None, None) rep = runner.ItemTestReport(None, None)

View File

@ -41,12 +41,12 @@ class ResultdbPlugin:
raise config.Error('Unknown --resultdb_format: %s' % raise config.Error('Unknown --resultdb_format: %s' %
config.option.resultdbformat) config.option.resultdbformat)
config.bus.register(self.resultdb) config.pluginmanager.register(self.resultdb)
def pytest_unconfigure(self, config): def pytest_unconfigure(self, config):
if hasattr(self, 'resultdb'): if hasattr(self, 'resultdb'):
del self.resultdb del self.resultdb
#config.bus.unregister(self.resultdb) #config.pluginmanager.unregister(self.resultdb)
class JSONResultArchive(object): class JSONResultArchive(object):

View File

@ -14,13 +14,13 @@ class ResultlogPlugin:
if resultlog: if resultlog:
logfile = open(resultlog, 'w', 1) # line buffered logfile = open(resultlog, 'w', 1) # line buffered
self.resultlog = ResultLog(logfile) self.resultlog = ResultLog(logfile)
config.bus.register(self.resultlog) config.pluginmanager.register(self.resultlog)
def pytest_unconfigure(self, config): def pytest_unconfigure(self, config):
if hasattr(self, 'resultlog'): if hasattr(self, 'resultlog'):
self.resultlog.logfile.close() self.resultlog.logfile.close()
del self.resultlog del self.resultlog
#config.bus.unregister(self.resultlog) #config.pluginmanager.unregister(self.resultlog)
def generic_path(item): def generic_path(item):
chain = item.listchain() chain = item.listchain()

View File

@ -208,7 +208,7 @@ class TestRunnerPlugin:
item = testdir.getitem("""def test_func(): pass""") item = testdir.getitem("""def test_func(): pass""")
plugin = RunnerPlugin() plugin = RunnerPlugin()
plugin.pytest_configure(item.config) plugin.pytest_configure(item.config)
sorter = testdir.geteventrecorder(item.config.bus) sorter = testdir.geteventrecorder(item.config.pluginmanager)
plugin.pytest_item_setup_and_runtest(item) plugin.pytest_item_setup_and_runtest(item)
rep = sorter.getcall("pytest_itemtestreport").rep rep = sorter.getcall("pytest_itemtestreport").rep
assert rep.passed assert rep.passed

View File

@ -15,7 +15,7 @@ class TerminalPlugin(object):
name = attr.split("_")[-1] name = attr.split("_")[-1]
assert hasattr(self.reporter._tw, name), name assert hasattr(self.reporter._tw, name), name
setattr(self.reporter._tw, name, getattr(config, attr)) setattr(self.reporter._tw, name, getattr(config, attr))
config.bus.register(self.reporter) config.pluginmanager.register(self.reporter)
class TerminalReporter: class TerminalReporter:
def __init__(self, config, file=None): def __init__(self, config, file=None):
@ -209,7 +209,7 @@ class TerminalReporter:
py.path.local(py.__file__).dirpath(), rev)) py.path.local(py.__file__).dirpath(), rev))
if self.config.option.traceconfig: if self.config.option.traceconfig:
plugins = [] plugins = []
for x in self.config.pytestplugins._plugins: for x in self.config.pluginmanager.plugins:
if isinstance(x, str) and x.startswith("pytest_"): if isinstance(x, str) and x.startswith("pytest_"):
plugins.append(x[7:]) plugins.append(x[7:])
else: else:
@ -368,7 +368,7 @@ class TestTerminal:
assert 0 assert 0
""") """)
rep = TerminalReporter(modcol.config, file=linecomp.stringio) rep = TerminalReporter(modcol.config, file=linecomp.stringio)
rep.config.bus.register(rep) rep.config.pluginmanager.register(rep)
rep.config.api.pytest_testrunstart() rep.config.api.pytest_testrunstart()
for item in testdir.genitems([modcol]): for item in testdir.genitems([modcol]):
@ -395,7 +395,7 @@ class TestTerminal:
assert 0 assert 0
""", configargs=("-v",)) """, configargs=("-v",))
rep = TerminalReporter(modcol.config, file=linecomp.stringio) rep = TerminalReporter(modcol.config, file=linecomp.stringio)
rep.config.bus.register(rep) rep.config.pluginmanager.register(rep)
rep.config.api.pytest_testrunstart() rep.config.api.pytest_testrunstart()
items = modcol.collect() items = modcol.collect()
rep.config.option.debug = True # rep.config.option.debug = True #
@ -420,7 +420,7 @@ class TestTerminal:
def test_collect_fail(self, testdir, linecomp): def test_collect_fail(self, testdir, linecomp):
modcol = testdir.getmodulecol("import xyz") modcol = testdir.getmodulecol("import xyz")
rep = TerminalReporter(modcol.config, file=linecomp.stringio) rep = TerminalReporter(modcol.config, file=linecomp.stringio)
rep.config.bus.register(rep) rep.config.pluginmanager.register(rep)
rep.config.api.pytest_testrunstart() rep.config.api.pytest_testrunstart()
l = list(testdir.genitems([modcol])) l = list(testdir.genitems([modcol]))
assert len(l) == 0 assert len(l) == 0
@ -516,7 +516,7 @@ class TestTerminal:
g() # --calling-- g() # --calling--
""", configargs=("--tb=%s" % tbopt,)) """, configargs=("--tb=%s" % tbopt,))
rep = TerminalReporter(modcol.config, file=linecomp.stringio) rep = TerminalReporter(modcol.config, file=linecomp.stringio)
rep.config.bus.register(rep) rep.config.pluginmanager.register(rep)
rep.config.api.pytest_testrunstart() rep.config.api.pytest_testrunstart()
for item in testdir.genitems([modcol]): for item in testdir.genitems([modcol]):
rep.config.api.pytest_itemtestreport( rep.config.api.pytest_itemtestreport(
@ -543,7 +543,7 @@ class TestTerminal:
pass pass
""") """)
rep = TerminalReporter(modcol.config, file=linecomp.stringio) rep = TerminalReporter(modcol.config, file=linecomp.stringio)
modcol.config.bus.register(rep) modcol.config.pluginmanager.register(rep)
l = list(testdir.genitems([modcol])) l = list(testdir.genitems([modcol]))
assert len(l) == 1 assert len(l) == 1
modcol.config.option.debug = True modcol.config.option.debug = True
@ -563,8 +563,8 @@ class TestTerminal:
""", configargs=("-v",)*verbose) """, configargs=("-v",)*verbose)
#""", configargs=("--showskipsummary",) + ("-v",)*verbose) #""", configargs=("--showskipsummary",) + ("-v",)*verbose)
rep = TerminalReporter(modcol.config, file=linecomp.stringio) rep = TerminalReporter(modcol.config, file=linecomp.stringio)
modcol.config.bus.register(rep) modcol.config.pluginmanager.register(rep)
bus = modcol.config.bus bus = modcol.config.pluginmanager
modcol.config.api.pytest_testrunstart() modcol.config.api.pytest_testrunstart()
try: try:
for item in testdir.genitems([modcol]): for item in testdir.genitems([modcol]):
@ -625,7 +625,7 @@ class TestCollectonly:
pass pass
""") """)
rep = CollectonlyReporter(modcol.config, out=linecomp.stringio) rep = CollectonlyReporter(modcol.config, out=linecomp.stringio)
modcol.config.bus.register(rep) modcol.config.pluginmanager.register(rep)
indent = rep.indent indent = rep.indent
rep.config.api.pytest_collectstart(collector=modcol) rep.config.api.pytest_collectstart(collector=modcol)
linecomp.assert_contains_lines([ linecomp.assert_contains_lines([
@ -646,7 +646,7 @@ class TestCollectonly:
py.test.skip("nomod") py.test.skip("nomod")
""") """)
rep = CollectonlyReporter(modcol.config, out=linecomp.stringio) rep = CollectonlyReporter(modcol.config, out=linecomp.stringio)
modcol.config.bus.register(rep) modcol.config.pluginmanager.register(rep)
cols = list(testdir.genitems([modcol])) cols = list(testdir.genitems([modcol]))
assert len(cols) == 0 assert len(cols) == 0
linecomp.assert_contains_lines(""" linecomp.assert_contains_lines("""
@ -659,7 +659,7 @@ class TestCollectonly:
raise ValueError(0) raise ValueError(0)
""") """)
rep = CollectonlyReporter(modcol.config, out=linecomp.stringio) rep = CollectonlyReporter(modcol.config, out=linecomp.stringio)
modcol.config.bus.register(rep) modcol.config.pluginmanager.register(rep)
cols = list(testdir.genitems([modcol])) cols = list(testdir.genitems([modcol]))
assert len(cols) == 0 assert len(cols) == 0
linecomp.assert_contains_lines(""" linecomp.assert_contains_lines("""

View File

@ -167,7 +167,7 @@ class Module(py.test.collect.File, PyCollectorMixin):
# we assume we are only called once per module # we assume we are only called once per module
mod = self.fspath.pyimport() mod = self.fspath.pyimport()
#print "imported test module", mod #print "imported test module", mod
self.config.pytestplugins.consider_module(mod) self.config.pluginmanager.consider_module(mod)
return mod return mod
def setup(self): def setup(self):
@ -177,7 +177,7 @@ class Module(py.test.collect.File, PyCollectorMixin):
#print "*" * 20, "INVOKE assertion", self #print "*" * 20, "INVOKE assertion", self
py.magic.invoke(assertion=1) py.magic.invoke(assertion=1)
mod = self.obj mod = self.obj
self.config.pytestplugins.register(mod) self.config.pluginmanager.register(mod)
if hasattr(mod, 'setup_module'): if hasattr(mod, 'setup_module'):
self.obj.setup_module(mod) self.obj.setup_module(mod)
@ -187,7 +187,7 @@ class Module(py.test.collect.File, PyCollectorMixin):
if not self.config.option.nomagic: if not self.config.option.nomagic:
#print "*" * 20, "revoke assertion", self #print "*" * 20, "revoke assertion", self
py.magic.revoke(assertion=1) py.magic.revoke(assertion=1)
self.config.pytestplugins.unregister(self.obj) self.config.pluginmanager.unregister(self.obj)
class Class(PyCollectorMixin, py.test.collect.Collector): class Class(PyCollectorMixin, py.test.collect.Collector):
@ -376,8 +376,8 @@ class Function(FunctionMixin, py.test.collect.Item):
def lookup_onearg(self, argname): def lookup_onearg(self, argname):
prefix = "pytest_funcarg__" prefix = "pytest_funcarg__"
#makerlist = self.config.pytestplugins.listattr(prefix + argname) #makerlist = self.config.pluginmanager.listattr(prefix + argname)
value = self.config.pytestplugins.call_firstresult(prefix + argname, pyfuncitem=self) value = self.config.pluginmanager.call_firstresult(prefix + argname, pyfuncitem=self)
if value is not None: if value is not None:
return value return value
else: else:
@ -386,8 +386,8 @@ class Function(FunctionMixin, py.test.collect.Item):
def _raisefuncargerror(self, argname, prefix="pytest_funcarg__"): def _raisefuncargerror(self, argname, prefix="pytest_funcarg__"):
metainfo = self.repr_metainfo() metainfo = self.repr_metainfo()
available = [] available = []
plugins = self.config.pytestplugins._plugins.values() plugins = self.config.pluginmanager.plugins.values()
plugins.extend(self.config.pytestplugins.pyplugins._plugins) plugins.extend(self.config.pluginmanager.comregistry.plugins)
for plugin in plugins: for plugin in plugins:
for name in vars(plugin.__class__): for name in vars(plugin.__class__):
if name.startswith(prefix): if name.startswith(prefix):

View File

@ -4,42 +4,42 @@ handling py.test plugins.
import py import py
from py.__.test.plugin import api from py.__.test.plugin import api
class PytestPlugins(object): class PluginManager(object):
def __init__(self, pyplugins=None): def __init__(self, comregistry=None):
if pyplugins is None: if comregistry is None:
pyplugins = py._com.PyPlugins() comregistry = py._com.Registry()
self.pyplugins = pyplugins self.comregistry = comregistry
self.MultiCall = self.pyplugins.MultiCall self.MultiCall = self.comregistry.MultiCall
self._plugins = {} self.plugins = {}
self.api = py._com.PluginAPI( self.api = py._com.PluginAPI(
apiclass=api.PluginHooks, apiclass=api.PluginHooks,
plugins=self.pyplugins) plugins=self.comregistry)
def register(self, plugin): def register(self, plugin):
self.pyplugins.register(plugin) self.comregistry.register(plugin)
def unregister(self, plugin): def unregister(self, plugin):
self.pyplugins.unregister(plugin) self.comregistry.unregister(plugin)
def isregistered(self, plugin): def isregistered(self, plugin):
return self.pyplugins.isregistered(plugin) return self.comregistry.isregistered(plugin)
def getplugins(self): def getplugins(self):
return self.pyplugins.getplugins() return self.comregistry.getplugins()
# API for bootstrapping # API for bootstrapping
# #
def getplugin(self, importname): def getplugin(self, importname):
impname, clsname = canonical_names(importname) impname, clsname = canonical_names(importname)
return self._plugins[impname] return self.plugins[impname]
def consider_env(self): def consider_env(self):
for spec in self.pyplugins._envlist("PYTEST_PLUGINS"): for spec in self.comregistry._envlist("PYTEST_PLUGINS"):
self.import_plugin(spec) self.import_plugin(spec)
def consider_conftest(self, conftestmodule): def consider_conftest(self, conftestmodule):
cls = getattr(conftestmodule, 'ConftestPlugin', None) cls = getattr(conftestmodule, 'ConftestPlugin', None)
if cls is not None and cls not in self._plugins: if cls is not None and cls not in self.plugins:
self._plugins[cls] = True self.plugins[cls] = True
self.register(cls()) self.register(cls())
self.consider_module(conftestmodule) self.consider_module(conftestmodule)
@ -54,11 +54,11 @@ class PytestPlugins(object):
def import_plugin(self, spec): def import_plugin(self, spec):
assert isinstance(spec, str) assert isinstance(spec, str)
modname, clsname = canonical_names(spec) modname, clsname = canonical_names(spec)
if modname in self._plugins: if modname in self.plugins:
return return
mod = importplugin(modname) mod = importplugin(modname)
plugin = registerplugin(self.pyplugins.register, mod, clsname) plugin = registerplugin(self.comregistry.register, mod, clsname)
self._plugins[modname] = plugin self.plugins[modname] = plugin
self.consider_module(mod) self.consider_module(mod)
# #
# #
@ -66,18 +66,18 @@ class PytestPlugins(object):
# #
# #
def getfirst(self, attrname): def getfirst(self, attrname):
for x in self.pyplugins.listattr(attrname): for x in self.comregistry.listattr(attrname):
return x return x
def listattr(self, attrname): def listattr(self, attrname):
return self.pyplugins.listattr(attrname) return self.comregistry.listattr(attrname)
def call_firstresult(self, *args, **kwargs): def call_firstresult(self, *args, **kwargs):
return self.pyplugins.call_firstresult(*args, **kwargs) return self.comregistry.call_firstresult(*args, **kwargs)
def call_each(self, *args, **kwargs): def call_each(self, *args, **kwargs):
#print "plugins.call_each", args[0], args[1:], kwargs #print "plugins.call_each", args[0], args[1:], kwargs
return self.pyplugins.call_each(*args, **kwargs) return self.comregistry.call_each(*args, **kwargs)
def notify_exception(self, excinfo=None): def notify_exception(self, excinfo=None):
if excinfo is None: if excinfo is None:
@ -86,18 +86,18 @@ class PytestPlugins(object):
return self.api.pytest_internalerror(excrepr=excrepr) return self.api.pytest_internalerror(excrepr=excrepr)
def do_addoption(self, parser): def do_addoption(self, parser):
methods = self.pyplugins.listattr("pytest_addoption", reverse=True) methods = self.comregistry.listattr("pytest_addoption", reverse=True)
mc = py._com.MultiCall(methods, parser=parser) mc = py._com.MultiCall(methods, parser=parser)
mc.execute() mc.execute()
def pytest_plugin_registered(self, plugin): def pytest_plugin_registered(self, plugin):
if hasattr(self, '_config'): if hasattr(self, '_config'):
self.pyplugins.call_plugin(plugin, "pytest_addoption", parser=self._config._parser) self.comregistry.call_plugin(plugin, "pytest_addoption", parser=self._config._parser)
self.pyplugins.call_plugin(plugin, "pytest_configure", config=self._config) self.comregistry.call_plugin(plugin, "pytest_configure", config=self._config)
def do_configure(self, config): def do_configure(self, config):
assert not hasattr(self, '_config') assert not hasattr(self, '_config')
config.bus.register(self) config.pluginmanager.register(self)
self._config = config self._config = config
config.api.pytest_configure(config=self._config) config.api.pytest_configure(config=self._config)
@ -105,10 +105,10 @@ class PytestPlugins(object):
config = self._config config = self._config
del self._config del self._config
config.api.pytest_unconfigure(config=config) config.api.pytest_unconfigure(config=config)
config.bus.unregister(self) config.pluginmanager.unregister(self)
def do_itemrun(self, item, pdb=None): def do_itemrun(self, item, pdb=None):
res = self.pyplugins.call_firstresult("pytest_itemrun", item=item, pdb=pdb) res = self.comregistry.call_firstresult("pytest_itemrun", item=item, pdb=pdb)
if res is None: if res is None:
raise ValueError("could not run %r" %(item,)) raise ValueError("could not run %r" %(item,))

View File

@ -20,8 +20,8 @@ class Session(object):
""" """
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config
self.bus = config.bus # shortcut self.pluginmanager = config.pluginmanager # shortcut
self.bus.register(self) self.pluginmanager.register(self)
self._testsfailed = False self._testsfailed = False
self._nomatch = False self._nomatch = False
self.shouldstop = False self.shouldstop = False
@ -33,7 +33,7 @@ class Session(object):
if isinstance(next, (tuple, list)): if isinstance(next, (tuple, list)):
colitems[:] = list(next) + colitems colitems[:] = list(next) + colitems
continue continue
assert self.bus is next.config.bus assert self.pluginmanager is next.config.pluginmanager
if isinstance(next, Item): if isinstance(next, Item):
remaining = self.filteritems([next]) remaining = self.filteritems([next])
if remaining: if remaining:
@ -120,7 +120,7 @@ class Session(object):
exitstatus = outcome.EXIT_INTERRUPTED exitstatus = outcome.EXIT_INTERRUPTED
except: except:
captured_excinfo = py.code.ExceptionInfo() captured_excinfo = py.code.ExceptionInfo()
self.config.pytestplugins.notify_exception(captured_excinfo) self.config.pluginmanager.notify_exception(captured_excinfo)
exitstatus = outcome.EXIT_INTERNALERROR exitstatus = outcome.EXIT_INTERNALERROR
if exitstatus == 0 and self._testsfailed: if exitstatus == 0 and self._testsfailed:
exitstatus = outcome.EXIT_TESTSFAILED exitstatus = outcome.EXIT_TESTSFAILED
@ -133,4 +133,4 @@ class Session(object):
def runtest(self, item): def runtest(self, item):
pdb = self.config.option.usepdb and self.runpdb or None pdb = self.config.option.usepdb and self.runpdb or None
item.config.pytestplugins.do_itemrun(item, pdb=pdb) item.config.pluginmanager.do_itemrun(item, pdb=pdb)

View File

@ -67,7 +67,7 @@ class TestCollector:
def test_listnames_and__getitembynames(self, testdir): def test_listnames_and__getitembynames(self, testdir):
modcol = testdir.getmodulecol("pass", withinit=True) modcol = testdir.getmodulecol("pass", withinit=True)
print modcol.config.pytestplugins.getplugins() print modcol.config.pluginmanager.getplugins()
names = modcol.listnames() names = modcol.listnames()
print names print names
dircol = modcol.config.getfsnode(modcol.config.topdir) dircol = modcol.config.getfsnode(modcol.config.topdir)
@ -145,7 +145,7 @@ class TestCollectPluginHooks:
def pytest_collect_file(self, path, parent): def pytest_collect_file(self, path, parent):
wascalled.append(path) wascalled.append(path)
config = testdir.Config() config = testdir.Config()
config.pytestplugins.register(Plugin()) config.pluginmanager.register(Plugin())
config.parse([tmpdir]) config.parse([tmpdir])
col = config.getfsnode(tmpdir) col = config.getfsnode(tmpdir)
testdir.makefile(".abc", "xyz") testdir.makefile(".abc", "xyz")

View File

@ -318,7 +318,7 @@ def test_options_on_small_file_do_not_blow_up(testdir):
runfiletest(opts + [path]) runfiletest(opts + [path])
def test_default_bus(): def test_default_bus():
assert py.test.config.bus is py._com.pyplugins assert py.test.config.pluginmanager.comregistry is py._com.comregistry
@py.test.mark.todo("test for deprecation") @py.test.mark.todo("test for deprecation")
def test_ensuretemp(): def test_ensuretemp():

View File

@ -4,22 +4,22 @@ def pytest_funcarg__pickletransport(pyfuncitem):
return ImmutablePickleTransport() return ImmutablePickleTransport()
def pytest_pyfunc_call(__call__, pyfuncitem, args, kwargs): def pytest_pyfunc_call(__call__, pyfuncitem, args, kwargs):
# for each function call we patch py._com.pyplugins # for each function call we patch py._com.comregistry
# so that the unpickling of config objects # so that the unpickling of config objects
# (which bind to this mechanism) doesn't do harm # (which bind to this mechanism) doesn't do harm
# usually config objects are no meant to be unpickled in # usually config objects are no meant to be unpickled in
# the same system # the same system
oldconfig = py.test.config oldconfig = py.test.config
oldcom = py._com.pyplugins oldcom = py._com.comregistry
print "setting py.test.config to None" print "setting py.test.config to None"
py.test.config = None py.test.config = None
py._com.pyplugins = py._com.PyPlugins() py._com.comregistry = py._com.Registry()
try: try:
return __call__.execute(firstresult=True) return __call__.execute(firstresult=True)
finally: finally:
print "setting py.test.config to", oldconfig print "setting py.test.config to", oldconfig
py.test.config = oldconfig py.test.config = oldconfig
py._com.pyplugins = oldcom py._com.comregistry = oldcom
class ImmutablePickleTransport: class ImmutablePickleTransport:
def __init__(self): def __init__(self):
@ -195,13 +195,10 @@ def test_config__setstate__wired_correctly_in_childprocess(testdir):
from py.__.test.dist.mypickle import PickleChannel from py.__.test.dist.mypickle import PickleChannel
channel = PickleChannel(channel) channel = PickleChannel(channel)
config = channel.receive() config = channel.receive()
assert py.test.config.pytestplugins.pyplugins == py._com.pyplugins, "pyplugins wrong" assert py.test.config.pluginmanager.comregistry == py._com.comregistry, "comregistry wrong"
assert py.test.config.bus == py._com.pyplugins, "bus wrong"
""") """)
channel = PickleChannel(channel) channel = PickleChannel(channel)
config = testdir.parseconfig() config = testdir.parseconfig()
channel.send(config) channel.send(config)
channel.waitclose() # this will raise channel.waitclose() # this will potentially raise
gw.exit() gw.exit()

View File

@ -37,11 +37,11 @@ class TestModule:
def test_module_participates_as_plugin(self, testdir): def test_module_participates_as_plugin(self, testdir):
modcol = testdir.getmodulecol("") modcol = testdir.getmodulecol("")
modcol.setup() modcol.setup()
assert modcol.config.pytestplugins.isregistered(modcol.obj) assert modcol.config.pluginmanager.isregistered(modcol.obj)
modcol.teardown() modcol.teardown()
assert not modcol.config.pytestplugins.isregistered(modcol.obj) assert not modcol.config.pluginmanager.isregistered(modcol.obj)
def test_module_considers_pytestplugins_at_import(self, testdir): def test_module_considers_pluginmanager_at_import(self, testdir):
modcol = testdir.getmodulecol("pytest_plugins='xasdlkj',") modcol = testdir.getmodulecol("pytest_plugins='xasdlkj',")
py.test.raises(ImportError, "modcol.obj") py.test.raises(ImportError, "modcol.obj")
@ -259,7 +259,7 @@ class TestFunction:
class Provider: class Provider:
def pytest_funcarg__some(self, pyfuncitem): def pytest_funcarg__some(self, pyfuncitem):
return pyfuncitem.name return pyfuncitem.name
item.config.pytestplugins.register(Provider()) item.config.pluginmanager.register(Provider())
item.setupargs() item.setupargs()
assert len(item.funcargs) == 1 assert len(item.funcargs) == 1
@ -268,7 +268,7 @@ class TestFunction:
class Provider: class Provider:
def pytest_funcarg__other(self, pyfuncitem): def pytest_funcarg__other(self, pyfuncitem):
return pyfuncitem.name return pyfuncitem.name
item.config.pytestplugins.register(Provider()) item.config.pluginmanager.register(Provider())
item.setupargs() item.setupargs()
assert len(item.funcargs) == 1 assert len(item.funcargs) == 1
name, value = item.funcargs.popitem() name, value = item.funcargs.popitem()
@ -282,7 +282,7 @@ class TestFunction:
return pyfuncitem.name return pyfuncitem.name
def pytest_funcarg__other(self, pyfuncitem): def pytest_funcarg__other(self, pyfuncitem):
return 42 return 42
item.config.pytestplugins.register(Provider()) item.config.pluginmanager.register(Provider())
item.setupargs() item.setupargs()
assert len(item.funcargs) == 2 assert len(item.funcargs) == 2
assert item.funcargs['some'] == "test_func" assert item.funcargs['some'] == "test_func"
@ -295,7 +295,7 @@ class TestFunction:
def pytest_funcarg__some(self, pyfuncitem): def pytest_funcarg__some(self, pyfuncitem):
pyfuncitem.addfinalizer(lambda: l.append(42)) pyfuncitem.addfinalizer(lambda: l.append(42))
return 3 return 3
item.config.pytestplugins.register(Provider()) item.config.pluginmanager.register(Provider())
item.setupargs() item.setupargs()
assert len(item.funcargs) == 1 assert len(item.funcargs) == 1
assert item.funcargs['some'] == 3 assert item.funcargs['some'] == 3
@ -317,13 +317,13 @@ class TestFunction:
""") """)
item1, item2 = testdir.genitems([modcol]) item1, item2 = testdir.genitems([modcol])
modcol.setup() modcol.setup()
assert modcol.config.pytestplugins.isregistered(modcol.obj) assert modcol.config.pluginmanager.isregistered(modcol.obj)
item1.setupargs() item1.setupargs()
assert item1.funcargs['something'] == "test_method" assert item1.funcargs['something'] == "test_method"
item2.setupargs() item2.setupargs()
assert item2.funcargs['something'] == "test_func" assert item2.funcargs['something'] == "test_func"
modcol.teardown() modcol.teardown()
assert not modcol.config.pytestplugins.isregistered(modcol.obj) assert not modcol.config.pluginmanager.isregistered(modcol.obj)
class TestSorting: class TestSorting:
def test_check_equality_and_cmp_basic(self, testdir): def test_check_equality_and_cmp_basic(self, testdir):

View File

@ -1,15 +1,15 @@
import py, os import py, os
from py.__.test.pytestplugin import PytestPlugins, canonical_names from py.__.test.pytestplugin import PluginManager, canonical_names
from py.__.test.pytestplugin import registerplugin, importplugin from py.__.test.pytestplugin import registerplugin, importplugin
class TestBootstrapping: class TestBootstrapping:
def test_consider_env_fails_to_import(self, monkeypatch): def test_consider_env_fails_to_import(self, monkeypatch):
plugins = PytestPlugins() plugins = PluginManager()
monkeypatch.setitem(os.environ, 'PYTEST_PLUGINS', 'nonexistingmodule') monkeypatch.setitem(os.environ, 'PYTEST_PLUGINS', 'nonexistingmodule')
py.test.raises(ImportError, "plugins.consider_env()") py.test.raises(ImportError, "plugins.consider_env()")
def test_consider_env_plugin_instantiation(self, testdir, monkeypatch): def test_consider_env_plugin_instantiation(self, testdir, monkeypatch):
plugins = PytestPlugins() plugins = PluginManager()
testdir.syspathinsert() testdir.syspathinsert()
testdir.makepyfile(pytest_xy123="class Xy123Plugin: pass") testdir.makepyfile(pytest_xy123="class Xy123Plugin: pass")
monkeypatch.setitem(os.environ, 'PYTEST_PLUGINS', 'xy123') monkeypatch.setitem(os.environ, 'PYTEST_PLUGINS', 'xy123')
@ -27,7 +27,7 @@ class TestBootstrapping:
p = testdir.makepyfile(""" p = testdir.makepyfile("""
import py import py
def test_hello(): def test_hello():
plugin = py.test.config.pytestplugins.getplugin('x500') plugin = py.test.config.pluginmanager.getplugin('x500')
assert plugin is not None assert plugin is not None
""") """)
new = str(x500.dirpath()) # "%s:%s" %(x500.dirpath(), os.environ.get('PYTHONPATH', '')) new = str(x500.dirpath()) # "%s:%s" %(x500.dirpath(), os.environ.get('PYTHONPATH', ''))
@ -38,7 +38,7 @@ class TestBootstrapping:
extra = result.stdout.fnmatch_lines(["*1 passed in*"]) extra = result.stdout.fnmatch_lines(["*1 passed in*"])
def test_import_plugin_importname(self, testdir): def test_import_plugin_importname(self, testdir):
plugins = PytestPlugins() plugins = PluginManager()
py.test.raises(ImportError, 'plugins.import_plugin("x.y")') py.test.raises(ImportError, 'plugins.import_plugin("x.y")')
py.test.raises(ImportError, 'plugins.import_plugin("pytest_x.y")') py.test.raises(ImportError, 'plugins.import_plugin("pytest_x.y")')
@ -59,7 +59,7 @@ class TestBootstrapping:
assert plugin2 is plugin1 assert plugin2 is plugin1
def test_consider_module(self, testdir): def test_consider_module(self, testdir):
plugins = PytestPlugins() plugins = PluginManager()
testdir.syspathinsert() testdir.syspathinsert()
testdir.makepyfile(pytest_plug1="class Plug1Plugin: pass") testdir.makepyfile(pytest_plug1="class Plug1Plugin: pass")
testdir.makepyfile(pytest_plug2="class Plug2Plugin: pass") testdir.makepyfile(pytest_plug2="class Plug2Plugin: pass")
@ -73,7 +73,7 @@ class TestBootstrapping:
mod = py.std.new.module("x") mod = py.std.new.module("x")
mod.pytest_plugins = "pytest_a" mod.pytest_plugins = "pytest_a"
aplugin = testdir.makepyfile(pytest_a="""class APlugin: pass""") aplugin = testdir.makepyfile(pytest_a="""class APlugin: pass""")
plugins = PytestPlugins() plugins = PluginManager()
sorter = testdir.geteventrecorder(plugins) sorter = testdir.geteventrecorder(plugins)
#syspath.prepend(aplugin.dirpath()) #syspath.prepend(aplugin.dirpath())
py.std.sys.path.insert(0, str(aplugin.dirpath())) py.std.sys.path.insert(0, str(aplugin.dirpath()))
@ -87,7 +87,7 @@ class TestBootstrapping:
assert len(l) == 1 assert len(l) == 1
def test_consider_conftest(self, testdir): def test_consider_conftest(self, testdir):
pp = PytestPlugins() pp = PluginManager()
mod = testdir.makepyfile("class ConftestPlugin: hello = 1").pyimport() mod = testdir.makepyfile("class ConftestPlugin: hello = 1").pyimport()
pp.consider_conftest(mod) pp.consider_conftest(mod)
l = [x for x in pp.getplugins() if isinstance(x, mod.ConftestPlugin)] l = [x for x in pp.getplugins() if isinstance(x, mod.ConftestPlugin)]
@ -104,11 +104,11 @@ class TestBootstrapping:
def test_consider_conftest_deps(self, testdir): def test_consider_conftest_deps(self, testdir):
mod = testdir.makepyfile("pytest_plugins='xyz'").pyimport() mod = testdir.makepyfile("pytest_plugins='xyz'").pyimport()
pp = PytestPlugins() pp = PluginManager()
py.test.raises(ImportError, "pp.consider_conftest(mod)") py.test.raises(ImportError, "pp.consider_conftest(mod)")
def test_registry(self): def test_registry(self):
pp = PytestPlugins() pp = PluginManager()
a1, a2 = object(), object() a1, a2 = object(), object()
pp.register(a1) pp.register(a1)
assert pp.isregistered(a1) assert pp.isregistered(a1)
@ -150,7 +150,7 @@ class TestPytestPluginInteractions:
""") """)
config = Config() config = Config()
config._conftest.importconftest(p) config._conftest.importconftest(p)
print config.pytestplugins.getplugins() print config.pluginmanager.getplugins()
config.parse([]) config.parse([])
assert not config.option.test123 assert not config.option.test123
@ -158,7 +158,7 @@ class TestPytestPluginInteractions:
from py.__.test.config import Config from py.__.test.config import Config
config = Config() config = Config()
config.parse([]) config.parse([])
config.pytestplugins.do_configure(config=config) config.pluginmanager.do_configure(config=config)
assert not hasattr(config.option, 'test123') assert not hasattr(config.option, 'test123')
p = testdir.makepyfile(""" p = testdir.makepyfile("""
class ConftestPlugin: class ConftestPlugin:
@ -179,30 +179,30 @@ class TestPytestPluginInteractions:
def xyz(self, obj): def xyz(self, obj):
events.append(obj) events.append(obj)
config.bus.register(A()) config.pluginmanager.register(A())
assert len(l) == 0 assert len(l) == 0
config.pytestplugins.do_configure(config=config) config.pluginmanager.do_configure(config=config)
assert len(l) == 1 assert len(l) == 1
config.bus.register(A()) # this should lead to a configured() plugin config.pluginmanager.register(A()) # this should lead to a configured() plugin
assert len(l) == 2 assert len(l) == 2
assert l[0] != l[1] assert l[0] != l[1]
config.bus.call_each("xyz", obj=42) config.pluginmanager.call_each("xyz", obj=42)
assert len(events) == 2 assert len(events) == 2
assert events == [42,42] assert events == [42,42]
config.pytestplugins.do_unconfigure(config=config) config.pluginmanager.do_unconfigure(config=config)
config.bus.register(A()) config.pluginmanager.register(A())
assert len(l) == 2 assert len(l) == 2
def test_MultiCall(self): def test_MultiCall(self):
pp = PytestPlugins() pp = PluginManager()
assert hasattr(pp, 'MultiCall') assert hasattr(pp, 'MultiCall')
# lower level API # lower level API
def test_getfirst(self): def test_getfirst(self):
plugins = PytestPlugins() plugins = PluginManager()
class My1: class My1:
x = 1 x = 1
assert plugins.getfirst("x") is None assert plugins.getfirst("x") is None
@ -210,7 +210,7 @@ class TestPytestPluginInteractions:
assert plugins.getfirst("x") == 1 assert plugins.getfirst("x") == 1
def test_call_each(self): def test_call_each(self):
plugins = PytestPlugins() plugins = PluginManager()
class My: class My:
def method(self, arg): def method(self, arg):
pass pass
@ -221,7 +221,7 @@ class TestPytestPluginInteractions:
py.test.raises(TypeError, 'plugins.call_each("method", arg=42, s=13)') py.test.raises(TypeError, 'plugins.call_each("method", arg=42, s=13)')
def test_call_firstresult(self): def test_call_firstresult(self):
plugins = PytestPlugins() plugins = PluginManager()
class My1: class My1:
def method(self): def method(self):
pass pass
@ -241,7 +241,7 @@ class TestPytestPluginInteractions:
assert plugins.call_firstresult("method") == True assert plugins.call_firstresult("method") == True
def test_listattr(self): def test_listattr(self):
plugins = PytestPlugins() plugins = PluginManager()
class My2: class My2:
x = 42 x = 42
plugins.register(My2()) plugins.register(My2())
@ -267,7 +267,7 @@ class TestPytestPluginInteractions:
return x+0 return x+0
""") """)
l = [] l = []
call = modcol.config.pytestplugins.setupcall(modcol, "pytest_method", 1) call = modcol.config.pluginmanager.setupcall(modcol, "pytest_method", 1)
assert len(call.methods) == 3 assert len(call.methods) == 3
results = call.execute() results = call.execute()
assert results == [1,2,2] assert results == [1,2,2]