desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
def setdefault(self, key, default=None):
if (key in self): return self[key] self[key] = default return default
'od.__repr__() <==> repr(od)'
def __repr__(self, _repr_running={}):
call_key = (id(self), _get_ident()) if (call_key in _repr_running): return '...' _repr_running[call_key] = 1 try: if (not self): return ('%s()' % (self.__class__.__name__,)) return ('%s(%r)' % (self.__class__.__name__, self.items())) finally: del _repr_running[call_key]
'Return state information for pickling'
def __reduce__(self):
items = [[k, self[k]] for k in self] inst_dict = vars(self).copy() for k in vars(OrderedDict()): inst_dict.pop(k, None) if inst_dict: return (self.__class__, (items,), inst_dict) return (self.__class__, (items,))
'od.copy() -> a shallow copy of od'
def copy(self):
return self.__class__(self)
'OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None).'
@classmethod def fromkeys(cls, iterable, value=None):
d = cls() for key in iterable: d[key] = value return d
'od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive.'
def __eq__(self, other):
if isinstance(other, OrderedDict): return ((len(self) == len(other)) and (self.items() == other.items())) return dict.__eq__(self, other)
'od.viewkeys() -> a set-like object providing a view on od\'s keys'
def viewkeys(self):
return KeysView(self)
'od.viewvalues() -> an object providing a view on od\'s values'
def viewvalues(self):
return ValuesView(self)
'od.viewitems() -> a set-like object providing a view on od\'s items'
def viewitems(self):
return ItemsView(self)
'return a testreport whose dotted import path matches'
def matchreport(self, inamepart='', names='pytest_runtest_logreport pytest_collectreport', when=None):
l = [] for rep in self.getreports(names=names): try: if ((not when) and (rep.when != 'call') and rep.passed): continue except AttributeError: pass if (when and (getattr(rep, 'when', None) != when)): continue if ((not inamepart) or (inamepart in rep.nodeid.split('::'))): l.append(rep) if (not l): raise ValueError(('could not find test report matching %r: no test reports at all!' % (inamepart,))) if (len(l) > 1): raise ValueError(('found 2 or more testreports matching %r: %s' % (inamepart, l))) return l[0]
'Return a dictionary of outcomestring->num from parsing the terminal output that the test process produced.'
def parseoutcomes(self):
for line in reversed(self.outlines): if ('seconds' in line): outcomes = rex_outcome.findall(line) if outcomes: d = {} for (num, cat) in outcomes: d[cat] = int(num) return d
'assert that the specified outcomes appear with the respective numbers (0 means it didn\'t occur) in the text output from a test run.'
def assert_outcomes(self, passed=0, skipped=0, failed=0):
d = self.parseoutcomes() assert (passed == d.get('passed', 0)) assert (skipped == d.get('skipped', 0)) assert (failed == d.get('failed', 0))
'Clean up global state artifacts. Some methods modify the global interpreter state and this tries to clean this up. It does not remove the temporary directory however so it can be looked at after the test run has finished.'
def finalize(self):
(sys.path[:], sys.meta_path[:]) = self._savesyspath if hasattr(self, '_olddir'): self._olddir.chdir() self.delete_loaded_modules()
'Delete modules that have been loaded during a test. This allows the interpreter to catch module changes in case the module is re-imported.'
def delete_loaded_modules(self):
for name in set(sys.modules).difference(self._savemodulekeys): if (name != 'zope.interface'): del sys.modules[name]
'Create a new :py:class:`HookRecorder` for a PluginManager.'
def make_hook_recorder(self, pluginmanager):
assert (not hasattr(pluginmanager, 'reprec')) pluginmanager.reprec = reprec = HookRecorder(pluginmanager) self.request.addfinalizer(reprec.finish_recording) return reprec
'Cd into the temporary directory. This is done automatically upon instantiation.'
def chdir(self):
old = self.tmpdir.chdir() if (not hasattr(self, '_olddir')): self._olddir = old
'Create a new file in the testdir. ext: The extension the file should use, including the dot. E.g. ".py". args: All args will be treated as strings and joined using newlines. The result will be written as contents to the file. The name of the file will be based on the test function requesting this fixture. E.g. "testdir.makefile(\'.txt\', \'line1\', \'line2\')" kwargs: Each keyword is the name of a file, while the value of it will be written as contents of the file. E.g. "testdir.makefile(\'.ini\', pytest=\'[pytest] addopts=-rs'
def makefile(self, ext, *args, **kwargs):
return self._makefile(ext, args, kwargs)
'Write a contest.py file with \'source\' as contents.'
def makeconftest(self, source):
return self.makepyfile(conftest=source)
'Write a tox.ini file with \'source\' as contents.'
def makeini(self, source):
return self.makefile('.ini', tox=source)
'Return the pytest section from the tox.ini config file.'
def getinicfg(self, source):
p = self.makeini(source) return py.iniconfig.IniConfig(p)['pytest']
'Shortcut for .makefile() with a .py extension.'
def makepyfile(self, *args, **kwargs):
return self._makefile('.py', args, kwargs)
'Shortcut for .makefile() with a .txt extension.'
def maketxtfile(self, *args, **kwargs):
return self._makefile('.txt', args, kwargs)
'Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`. This is undone automatically after the test.'
def syspathinsert(self, path=None):
if (path is None): path = self.tmpdir sys.path.insert(0, str(path)) self._possibly_invalidate_import_caches()
'Create a new (sub)directory.'
def mkdir(self, name):
return self.tmpdir.mkdir(name)
'Create a new python package. This creates a (sub)direcotry with an empty ``__init__.py`` file so that is recognised as a python package.'
def mkpydir(self, name):
p = self.mkdir(name) p.ensure('__init__.py') return p
'Return the collection node of a file. :param config: :py:class:`_pytest.config.Config` instance, see :py:meth:`parseconfig` and :py:meth:`parseconfigure` to create the configuration. :param arg: A :py:class:`py.path.local` instance of the file.'
def getnode(self, config, arg):
session = Session(config) assert ('::' not in str(arg)) p = py.path.local(arg) config.hook.pytest_sessionstart(session=session) res = session.perform_collect([str(p)], genitems=False)[0] config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK) return res
'Return the collection node of a file. This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to create the (configured) pytest Config instance. :param path: A :py:class:`py.path.local` instance of the file.'
def getpathnode(self, path):
config = self.parseconfigure(path) session = Session(config) x = session.fspath.bestrelpath(path) config.hook.pytest_sessionstart(session=session) res = session.perform_collect([x], genitems=False)[0] config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK) return res
'Generate all test items from a collection node. This recurses into the collection node and returns a list of all the test items contained within.'
def genitems(self, colitems):
session = colitems[0].session result = [] for colitem in colitems: result.extend(session.genitems(colitem)) return result
'Run the "test_func" Item. The calling test instance (the class which contains the test method) must provide a ``.getrunner()`` method which should return a runner which can run the test protocol for a single item, like e.g. :py:func:`_pytest.runner.runtestprotocol`.'
def runitem(self, source):
item = self.getitem(source) testclassinstance = self.request.instance runner = testclassinstance.getrunner() return runner(item)
'Run a test module in process using ``pytest.main()``. This run writes "source" into a temporary file and runs ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance for the result. :param source: The source code of the test module. :param cmdlineargs: Any extra command line arguments to use. :return: :py:class:`HookRecorder` instance of the result.'
def inline_runsource(self, source, *cmdlineargs):
p = self.makepyfile(source) l = (list(cmdlineargs) + [p]) return self.inline_run(*l)
'Run ``pytest.main([\'--collectonly\'])`` in-process. Retuns a tuple of the collected items and a :py:class:`HookRecorder` instance. This runs the :py:func:`pytest.main` function to run all of pytest inside the test process itself like :py:meth:`inline_run`. However the return value is a tuple of the collection items and a :py:class:`HookRecorder` instance.'
def inline_genitems(self, *args):
rec = self.inline_run('--collect-only', *args) items = [x.item for x in rec.getcalls('pytest_itemcollected')] return (items, rec)
'Run ``pytest.main()`` in-process, returning a HookRecorder. This runs the :py:func:`pytest.main` function to run all of pytest inside the test process itself. This means it can return a :py:class:`HookRecorder` instance which gives more detailed results from then run then can be done by matching stdout/stderr from :py:meth:`runpytest`. :param args: Any command line arguments to pass to :py:func:`pytest.main`. :param plugin: (keyword-only) Extra plugin instances the ``pytest.main()`` instance should use. :return: A :py:class:`HookRecorder` instance.'
def inline_run(self, *args, **kwargs):
orig_warn = AssertionRewritingHook._warn_already_imported def revert(): AssertionRewritingHook._warn_already_imported = orig_warn self.request.addfinalizer(revert) AssertionRewritingHook._warn_already_imported = (lambda *a: None) rec = [] class Collect: def pytest_configure(x, config): rec.append(self.make_hook_recorder(config.pluginmanager)) plugins = (kwargs.get('plugins') or []) plugins.append(Collect()) ret = pytest.main(list(args), plugins=plugins) self.delete_loaded_modules() if (len(rec) == 1): reprec = rec.pop() else: class reprec: pass reprec.ret = ret if ((ret == 2) and (not kwargs.get('no_reraise_ctrlc'))): calls = reprec.getcalls('pytest_keyboard_interrupt') if (calls and (calls[(-1)].excinfo.type == KeyboardInterrupt)): raise KeyboardInterrupt() return reprec
'Return result of running pytest in-process, providing a similar interface to what self.runpytest() provides.'
def runpytest_inprocess(self, *args, **kwargs):
if kwargs.get('syspathinsert'): self.syspathinsert() now = time.time() capture = py.io.StdCapture() try: reprec = self.inline_run(*args, **kwargs) except SystemExit as e: class reprec: ret = e.args[0] except Exception: traceback.print_exc() class reprec: ret = 3 finally: (out, err) = capture.reset() sys.stdout.write(out) sys.stderr.write(err) res = RunResult(reprec.ret, out.split('\n'), err.split('\n'), (time.time() - now)) res.reprec = reprec return res
'Run pytest inline or in a subprocess, depending on the command line option "--runpytest" and return a :py:class:`RunResult`.'
def runpytest(self, *args, **kwargs):
args = self._ensure_basetemp(args) return self._runpytest_method(*args, **kwargs)
'Return a new pytest Config instance from given commandline args. This invokes the pytest bootstrapping code in _pytest.config to create a new :py:class:`_pytest.core.PluginManager` and call the pytest_cmdline_parse hook to create new :py:class:`_pytest.config.Config` instance. If :py:attr:`plugins` has been populated they should be plugin modules which will be registered with the PluginManager.'
def parseconfig(self, *args):
args = self._ensure_basetemp(args) import _pytest.config config = _pytest.config._prepareconfig(args, self.plugins) self.request.addfinalizer(config._ensure_unconfigure) return config
'Return a new pytest configured Config instance. This returns a new :py:class:`_pytest.config.Config` instance like :py:meth:`parseconfig`, but also calls the pytest_configure hook.'
def parseconfigure(self, *args):
config = self.parseconfig(*args) config._do_configure() self.request.addfinalizer(config._ensure_unconfigure) return config
'Return the test item for a test function. This writes the source to a python file and runs pytest\'s collection on the resulting module, returning the test item for the requested function name. :param source: The module source. :param funcname: The name of the test function for which the Item must be returned.'
def getitem(self, source, funcname='test_func'):
items = self.getitems(source) for item in items: if (item.name == funcname): return item assert 0, ('%r item not found in module:\n%s\nitems: %s' % (funcname, source, items))
'Return all test items collected from the module. This writes the source to a python file and runs pytest\'s collection on the resulting module, returning all test items contained within.'
def getitems(self, source):
modcol = self.getmodulecol(source) return self.genitems([modcol])
'Return the module collection node for ``source``. This writes ``source`` to a file using :py:meth:`makepyfile` and then runs the pytest collection on it, returning the collection node for the test module. :param source: The source code of the module to collect. :param configargs: Any extra arguments to pass to :py:meth:`parseconfigure`. :param withinit: Whether to also write a ``__init__.py`` file to the temporarly directory to ensure it is a package.'
def getmodulecol(self, source, configargs=(), withinit=False):
kw = {self.request.function.__name__: Source(source).strip()} path = self.makepyfile(**kw) if withinit: self.makepyfile(__init__='#') self.config = config = self.parseconfigure(path, *configargs) node = self.getnode(config, path) return node
'Return the collection node for name from the module collection. This will search a module collection node for a collection node matching the given name. :param modcol: A module collection node, see :py:meth:`getmodulecol`. :param name: The name of the node to return.'
def collect_by_name(self, modcol, name):
for colitem in modcol._memocollect(): if (colitem.name == name): return colitem
'Invoke subprocess.Popen. This calls subprocess.Popen making sure the current working directory is the PYTHONPATH. You probably want to use :py:meth:`run` instead.'
def popen(self, cmdargs, stdout, stderr, **kw):
env = os.environ.copy() env['PYTHONPATH'] = os.pathsep.join(filter(None, [str(os.getcwd()), env.get('PYTHONPATH', '')])) kw['env'] = env return subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, **kw)
'Run a command with arguments. Run a process using subprocess.Popen saving the stdout and stderr. Returns a :py:class:`RunResult`.'
def run(self, *cmdargs):
return self._run(*cmdargs)
'Run a python script using sys.executable as interpreter. Returns a :py:class:`RunResult`.'
def runpython(self, script):
return self.run(sys.executable, script)
'Run python -c "command", return a :py:class:`RunResult`.'
def runpython_c(self, command):
return self.run(sys.executable, '-c', command)
'Run pytest as a subprocess with given arguments. Any plugins added to the :py:attr:`plugins` list will added using the ``-p`` command line option. Addtionally ``--basetemp`` is used put any temporary files and directories in a numbered directory prefixed with "runpytest-" so they do not conflict with the normal numberd pytest location for temporary files and directories. Returns a :py:class:`RunResult`.'
def runpytest_subprocess(self, *args, **kwargs):
p = py.path.local.make_numbered_dir(prefix='runpytest-', keep=None, rootdir=self.tmpdir) args = ((('--basetemp=%s' % p),) + args) plugins = [x for x in self.plugins if isinstance(x, str)] if plugins: args = (('-p', plugins[0]) + args) args = (self._getpytestargs() + args) return self.run(*args)
'Run pytest using pexpect. This makes sure to use the right pytest and sets up the temporary directory locations. The pexpect child is returned.'
def spawn_pytest(self, string, expect_timeout=10.0):
basetemp = self.tmpdir.mkdir('pexpect') invoke = ' '.join(map(str, self._getpytestargs())) cmd = ('%s --basetemp=%s %s' % (invoke, basetemp, string)) return self.spawn(cmd, expect_timeout=expect_timeout)
'Run a command using pexpect. The pexpect child is returned.'
def spawn(self, cmd, expect_timeout=10.0):
pexpect = pytest.importorskip('pexpect', '3.0') if (hasattr(sys, 'pypy_version_info') and ('64' in platform.machine())): pytest.skip('pypy-64 bit not supported') if sys.platform.startswith('freebsd'): pytest.xfail('pexpect does not work reliably on freebsd') logfile = self.tmpdir.join('spawn.out').open('wb') child = pexpect.spawn(cmd, logfile=logfile) self.request.addfinalizer(logfile.close) child.timeout = expect_timeout return child
'assert that lines2 are contained (linearly) in lines1. return a list of extralines found.'
def assert_contains_lines(self, lines2):
__tracebackhide__ = True val = self.stringio.getvalue() self.stringio.truncate(0) self.stringio.seek(0) lines1 = val.split('\n') return LineMatcher(lines1).fnmatch_lines(lines2)
'Return the entire original text.'
def str(self):
return '\n'.join(self.lines)
'Check lines exist in the output. The argument is a list of lines which have to occur in the output, in any order. Each line can contain glob whildcards.'
def fnmatch_lines_random(self, lines2):
lines2 = self._getlines(lines2) for line in lines2: for x in self.lines: if ((line == x) or fnmatch(x, line)): self._log('matched: ', repr(line)) break else: self._log(('line %r not found in output' % line)) raise ValueError(self._log_text)
'Return all lines following the given line in the text. The given line can contain glob wildcards.'
def get_lines_after(self, fnline):
for (i, line) in enumerate(self.lines): if ((fnline == line) or fnmatch(line, fnline)): return self.lines[(i + 1):] raise ValueError(('line %r not found in output' % fnline))
'Search the text for matching lines. The argument is a list of lines which have to match and can use glob wildcards. If they do not match an pytest.fail() is called. The matches and non-matches are also printed on stdout.'
def fnmatch_lines(self, lines2):
lines2 = self._getlines(lines2) lines1 = self.lines[:] nextline = None extralines = [] __tracebackhide__ = True for line in lines2: nomatchprinted = False while lines1: nextline = lines1.pop(0) if (line == nextline): self._log('exact match:', repr(line)) break elif fnmatch(nextline, line): self._log('fnmatch:', repr(line)) self._log(' with:', repr(nextline)) break else: if (not nomatchprinted): self._log('nomatch:', repr(line)) nomatchprinted = True self._log(' and:', repr(nextline)) extralines.append(nextline) else: self._log(('remains unmatched: %r' % (line,))) pytest.fail(self._log_text)
'Set attribute value on target, memorizing the old value. By default raise AttributeError if the attribute did not exist. For convenience you can specify a string as ``target`` which will be interpreted as a dotted import path, with the last part being the attribute name. Example: ``monkeypatch.setattr("os.getcwd", lambda x: "/")`` would set the ``getcwd`` function of the ``os`` module. The ``raising`` value determines if the setattr should fail if the attribute is not already present (defaults to True which means it will raise).'
def setattr(self, target, name, value=notset, raising=True):
__tracebackhide__ = True import inspect if (value is notset): if (not isinstance(target, _basestring)): raise TypeError('use setattr(target, name, value) or setattr(target, value) with target being a dotted import string') value = name (name, target) = derive_importpath(target, raising) oldval = getattr(target, name, notset) if (raising and (oldval is notset)): raise AttributeError(('%r has no attribute %r' % (target, name))) if inspect.isclass(target): oldval = target.__dict__.get(name, notset) self._setattr.append((target, name, oldval)) setattr(target, name, value)
'Delete attribute ``name`` from ``target``, by default raise AttributeError it the attribute did not previously exist. If no ``name`` is specified and ``target`` is a string it will be interpreted as a dotted import path with the last part being the attribute name. If ``raising`` is set to False, no exception will be raised if the attribute is missing.'
def delattr(self, target, name=notset, raising=True):
__tracebackhide__ = True if (name is notset): if (not isinstance(target, _basestring)): raise TypeError('use delattr(target, name) or delattr(target) with target being a dotted import string') (name, target) = derive_importpath(target, raising) if (not hasattr(target, name)): if raising: raise AttributeError(name) else: self._setattr.append((target, name, getattr(target, name, notset))) delattr(target, name)
'Set dictionary entry ``name`` to value.'
def setitem(self, dic, name, value):
self._setitem.append((dic, name, dic.get(name, notset))) dic[name] = value
'Delete ``name`` from dict. Raise KeyError if it doesn\'t exist. If ``raising`` is set to False, no exception will be raised if the key is missing.'
def delitem(self, dic, name, raising=True):
if (name not in dic): if raising: raise KeyError(name) else: self._setitem.append((dic, name, dic.get(name, notset))) del dic[name]
'Set environment variable ``name`` to ``value``. If ``prepend`` is a character, read the current environment variable value and prepend the ``value`` adjoined with the ``prepend`` character.'
def setenv(self, name, value, prepend=None):
value = str(value) if (prepend and (name in os.environ)): value = ((value + prepend) + os.environ[name]) self.setitem(os.environ, name, value)
'Delete ``name`` from the environment. Raise KeyError it does not exist. If ``raising`` is set to False, no exception will be raised if the environment variable is missing.'
def delenv(self, name, raising=True):
self.delitem(os.environ, name, raising=raising)
'Prepend ``path`` to ``sys.path`` list of import locations.'
def syspath_prepend(self, path):
if (self._savesyspath is None): self._savesyspath = sys.path[:] sys.path.insert(0, str(path))
'Change the current working directory to the specified path. Path can be a string or a py.path.local object.'
def chdir(self, path):
if (self._cwd is None): self._cwd = os.getcwd() if hasattr(path, 'chdir'): path.chdir() else: os.chdir(path)
'Undo previous changes. This call consumes the undo stack. Calling it a second time has no effect unless you do more monkeypatching after the undo call. There is generally no need to call `undo()`, since it is called automatically during tear-down. Note that the same `monkeypatch` fixture is used across a single test function invocation. If `monkeypatch` is used both by the test function itself and one of the test fixtures, calling `undo()` will undo all of the changes made in both functions.'
def undo(self):
for (obj, name, value) in reversed(self._setattr): if (value is not notset): setattr(obj, name, value) else: delattr(obj, name) self._setattr[:] = [] for (dictionary, name, value) in reversed(self._setitem): if (value is notset): try: del dictionary[name] except KeyError: pass else: dictionary[name] = value self._setitem[:] = [] if (self._savesyspath is not None): sys.path[:] = self._savesyspath self._savesyspath = None if (self._cwd is not None): os.chdir(self._cwd) self._cwd = None
'Return a Junit node containing custom properties, if any.'
def make_properties_node(self):
if self.properties: return Junit.properties([Junit.property(name=name, value=value) for (name, value) in self.properties]) return ''
'handle a setup/call/teardown report, generating the appropriate xml tags as necessary. note: due to plugins like xdist, this hook may be called in interlaced order with reports from other nodes. for example: usual call order: -> setup node1 -> call node1 -> teardown node1 -> setup node2 -> call node2 -> teardown node2 possible call order in xdist: -> setup node1 -> call node1 -> setup node2 -> call node2 -> teardown node2 -> teardown node1'
def pytest_runtest_logreport(self, report):
if report.passed: if (report.when == 'call'): reporter = self._opentestcase(report) reporter.append_pass(report) elif report.failed: reporter = self._opentestcase(report) if (report.when == 'call'): reporter.append_failure(report) else: reporter.append_error(report) elif report.skipped: reporter = self._opentestcase(report) reporter.append_skipped(report) self.update_testcase_duration(report) if (report.when == 'teardown'): self.finalize(report)
'accumulates total duration for nodeid from given report and updates the Junit.testcase with the new total if already created.'
def update_testcase_duration(self, report):
reporter = self.node_reporter(report) reporter.duration += getattr(report, 'duration', 0.0)
'Return a Junit node containing custom properties, if any.'
def _get_global_properties_node(self):
if self.global_properties: return Junit.properties([Junit.property(name=name, value=value) for (name, value) in self.global_properties]) return ''
'pop current snapshot out/err capture and flush to orig streams.'
def pop_outerr_to_orig(self):
(out, err) = self.readouterr() if out: self.out.writeorg(out) if err: self.err.writeorg(err) return (out, err)
'stop capturing and reset capturing streams'
def stop_capturing(self):
if hasattr(self, '_reset'): raise ValueError('was already stopped') self._reset = True if self.out: self.out.done() if self.err: self.err.done() if self.in_: self.in_.done()
'return snapshot unicode value of stdout/stderr capturings.'
def readouterr(self):
return ((self.out.snap() if (self.out is not None) else ''), (self.err.snap() if (self.err is not None) else ''))
'Start capturing on targetfd using memorized tmpfile.'
def start(self):
try: os.fstat(self.targetfd_save) except (AttributeError, OSError): raise ValueError('saved filedescriptor not valid anymore') os.dup2(self.tmpfile_fd, self.targetfd) self.syscapture.start()
'stop capturing, restore streams, return original capture file, seeked to position zero.'
def done(self):
targetfd_save = self.__dict__.pop('targetfd_save') os.dup2(targetfd_save, self.targetfd) os.close(targetfd_save) self.syscapture.done() self.tmpfile.close()
'write to original file descriptor.'
def writeorg(self, data):
if py.builtin._istext(data): data = data.encode('utf8') os.write(self.targetfd_save, data)
'.. deprecated:: 2.8 Use :py:meth:`pluggy.PluginManager.add_hookspecs` instead.'
def addhooks(self, module_or_class):
warning = dict(code='I2', fslocation=_pytest._code.getfslineno(sys._getframe(1)), nodeid=None, message='use pluginmanager.add_hookspecs instead of deprecated addhooks() method.') self._warn(warning) return self.add_hookspecs(module_or_class)
'Return True if the plugin with the given name is registered.'
def hasplugin(self, name):
return bool(self.get_plugin(name))
'load initial conftest files given a preparsed "namespace". As conftest files may add their own command line options which have arguments (\'--my-opt somepath\') we might get some false positives. All builtin and 3rd party plugins will have been loaded, however, so common options will not confuse our logic here.'
def _set_initial_conftests(self, namespace):
current = py.path.local() self._confcutdir = (current.join(namespace.confcutdir, abs=True) if namespace.confcutdir else None) self._noconftest = namespace.noconftest testpaths = namespace.file_or_dir foundanchor = False for path in testpaths: path = str(path) i = path.find('::') if (i != (-1)): path = path[:i] anchor = current.join(path, abs=1) if exists(anchor): self._try_load_conftest(anchor) foundanchor = True if (not foundanchor): self._try_load_conftest(current)
'get (or create) a named option Group. :name: name of the option group. :description: long description for --help output. :after: name of other group, used for ordering --help output. The returned group object has an ``addoption`` method with the same signature as :py:func:`parser.addoption <_pytest.config.Parser.addoption>` but will be shown in the respective group in the output of ``pytest. --help``.'
def getgroup(self, name, description='', after=None):
for group in self._groups: if (group.name == name): return group group = OptionGroup(name, description, parser=self) i = 0 for (i, grp) in enumerate(self._groups): if (grp.name == after): break self._groups.insert((i + 1), group) return group
'register a command line option. :opts: option names, can be short or long options. :attrs: same attributes which the ``add_option()`` function of the `argparse library <http://docs.python.org/2/library/argparse.html>`_ accepts. After command line parsing options are available on the pytest config object via ``config.option.NAME`` where ``NAME`` is usually set by passing a ``dest`` attribute, for example ``addoption("--long", dest="NAME", ...)``.'
def addoption(self, *opts, **attrs):
self._anonymous.addoption(*opts, **attrs)
'parses and returns a namespace object with known arguments at this point.'
def parse_known_args(self, args, namespace=None):
return self.parse_known_and_unknown_args(args, namespace=namespace)[0]
'parses and returns a namespace object with known arguments, and the remaining arguments unknown at this point.'
def parse_known_and_unknown_args(self, args, namespace=None):
optparser = self._getparser() args = [str(x) for x in args] return optparser.parse_known_args(args, namespace=namespace)
'register an ini-file option. :name: name of the ini-variable :type: type of the variable, can be ``pathlist``, ``args``, ``linelist`` or ``bool``. :default: default value if no ini-file option exists but is queried. The value of ini-variables can be retrieved via a call to :py:func:`config.getini(name) <_pytest.config.Config.getini>`.'
def addini(self, name, help, type=None, default=None):
assert (type in (None, 'pathlist', 'args', 'linelist', 'bool')) self._inidict[name] = (help, type, default) self._ininames.append(name)
'store parms in private vars for use in add_argument'
def __init__(self, *names, **attrs):
self._attrs = attrs self._short_opts = [] self._long_opts = [] self.dest = attrs.get('dest') if ('%default' in (attrs.get('help') or '')): warnings.warn('pytest now uses argparse. "%default" should be changed to "%(default)s" ', DeprecationWarning, stacklevel=3) try: typ = attrs['type'] except KeyError: pass else: if isinstance(typ, py.builtin._basestring): if (typ == 'choice'): warnings.warn(('type argument to addoption() is a string %r. For parsearg this is optional and when supplied should be a type. (options: %s)' % (typ, names)), DeprecationWarning, stacklevel=3) attrs['type'] = type(attrs['choices'][0]) else: warnings.warn(('type argument to addoption() is a string %r. For parsearg this should be a type. (options: %s)' % (typ, names)), DeprecationWarning, stacklevel=3) attrs['type'] = Argument._typ_map[typ] self.type = attrs['type'] else: self.type = typ try: self.default = attrs['default'] except KeyError: pass self._set_opt_strings(names) if (not self.dest): if self._long_opts: self.dest = self._long_opts[0][2:].replace('-', '_') else: try: self.dest = self._short_opts[0][1:] except IndexError: raise ArgumentError('need a long or short option', self)
'directly from optparse might not be necessary as this is passed to argparse later on'
def _set_opt_strings(self, opts):
for opt in opts: if (len(opt) < 2): raise ArgumentError(('invalid option string %r: must be at least two characters long' % opt), self) elif (len(opt) == 2): if (not ((opt[0] == '-') and (opt[1] != '-'))): raise ArgumentError(('invalid short option string %r: must be of the form -x, (x any non-dash char)' % opt), self) self._short_opts.append(opt) else: if (not ((opt[0:2] == '--') and (opt[2] != '-'))): raise ArgumentError(('invalid long option string %r: must start with --, followed by non-dash' % opt), self) self._long_opts.append(opt)
'add an option to this group. if a shortened version of a long option is specified it will be suppressed in the help. addoption(\'--twowords\', \'--two-words\') results in help showing \'--two-words\' only, but --twowords gets accepted **and** the automatic destination is in args.twowords'
def addoption(self, *optnames, **attrs):
conflict = set(optnames).intersection((name for opt in self.options for name in opt.names())) if conflict: raise ValueError(('option names %s already added' % conflict)) option = Argument(*optnames, **attrs) self._addoption_instance(option, shortupper=False)
'allow splitting of positional arguments'
def parse_args(self, args=None, namespace=None):
(args, argv) = self.parse_known_args(args, namespace) if argv: for arg in argv: if (arg and (arg[0] == '-')): lines = [('unrecognized arguments: %s' % ' '.join(argv))] for (k, v) in sorted(self.extra_info.items()): lines.append((' %s: %s' % (k, v))) self.error('\n'.join(lines)) getattr(args, FILE_OR_DIR).extend(argv) return args
'Add a function to be called when the config object gets out of use (usually coninciding with pytest_unconfigure).'
def add_cleanup(self, func):
self._cleanup.append(func)
'generate a warning for this test session.'
def warn(self, code, message, fslocation=None):
self.hook.pytest_logwarning.call_historic(kwargs=dict(code=code, message=message, fslocation=fslocation, nodeid=None))
'constructor useable for subprocesses.'
@classmethod def fromdictargs(cls, option_dict, args):
config = get_config() config.option.__dict__.update(option_dict) config.parse(args, addopts=False) for x in config.option.plugins: config.pluginmanager.consider_pluginarg(x) return config
'Install the PEP 302 import hook if using assertion re-writing. Needs to parse the --assert=<mode> option from the commandline and find all the installed plugins to mark them for re-writing by the importhook.'
def _consider_importhook(self, args, entrypoint_name):
(ns, unknown_args) = self._parser.parse_known_and_unknown_args(args) mode = ns.assertmode if (mode == 'rewrite'): try: hook = _pytest.assertion.install_importhook(self) except SystemError: mode = 'plain' else: import pkg_resources self.pluginmanager.rewrite_hook = hook for entrypoint in pkg_resources.iter_entry_points('pytest11'): for metadata in ('RECORD', 'SOURCES.txt'): for entry in entrypoint.dist._get_metadata(metadata): fn = entry.split(',')[0] is_simple_module = ((os.sep not in fn) and fn.endswith('.py')) is_package = ((fn.count(os.sep) == 1) and fn.endswith('__init__.py')) if is_simple_module: (module_name, ext) = os.path.splitext(fn) hook.mark_rewrite(module_name) elif is_package: package_name = os.path.dirname(fn) hook.mark_rewrite(package_name) self._warn_about_missing_assertion(mode)
'add a line to an ini-file option. The option must have been declared but might not yet be set in which case the line becomes the the first line in its value.'
def addinivalue_line(self, name, line):
x = self.getini(name) assert isinstance(x, list) x.append(line)
'return configuration value from an :ref:`ini file <inifiles>`. If the specified name hasn\'t been registered through a prior :py:func:`parser.addini <pytest.config.Parser.addini>` call (usually from a plugin), a ValueError is raised.'
def getini(self, name):
try: return self._inicache[name] except KeyError: self._inicache[name] = val = self._getini(name) return val
'return command line option value. :arg name: name of the option. You may also specify the literal ``--OPT`` option instead of the "dest" option name. :arg default: default value if no option of that name exists. :arg skip: if True raise pytest.skip if option does not exists or has a None value.'
def getoption(self, name, default=notset, skip=False):
name = self._opt2dest.get(name, name) try: val = getattr(self.option, name) if ((val is None) and skip): raise AttributeError(name) return val except AttributeError: if (default is not notset): return default if skip: import pytest pytest.skip(('no %r option found' % (name,))) raise ValueError(('no option named %r' % (name,)))
'(deprecated, use getoption())'
def getvalue(self, name, path=None):
return self.getoption(name)
'(deprecated, use getoption(skip=True))'
def getvalueorskip(self, name, path=None):
return self.getoption(name, skip=True)
'Read-only property that returns the full string representation of ``longrepr``. .. versionadded:: 3.0'
@property def longreprtext(self):
tw = py.io.TerminalWriter(stringio=True) tw.hasmarkup = False self.toterminal(tw) exc = tw.stringio.getvalue() return exc.strip()
'Return captured text from stdout, if capturing is enabled .. versionadded:: 3.0'
@property def capstdout(self):
return ''.join((content for (prefix, content) in self.get_sections('Captured stdout')))
'Return captured text from stderr, if capturing is enabled .. versionadded:: 3.0'
@property def capstderr(self):
return ''.join((content for (prefix, content) in self.get_sections('Captured stderr')))
'attach a finalizer to the given colitem. if colitem is None, this will add a finalizer that is called at the end of teardown_all().'
def addfinalizer(self, finalizer, colitem):
assert (colitem and (not isinstance(colitem, tuple))) assert py.builtin.callable(finalizer) self._finalizers.setdefault(colitem, []).append(finalizer)
'setup objects along the collector chain to the test-method and teardown previously setup objects.'
def prepare(self, colitem):
needed_collectors = colitem.listchain() self._teardown_towards(needed_collectors) for col in self.stack: if hasattr(col, '_prepare_exc'): py.builtin._reraise(*col._prepare_exc) for col in needed_collectors[len(self.stack):]: self.stack.append(col) try: col.setup() except Exception: col._prepare_exc = sys.exc_info() raise
'only called on non option completions'
def __call__(self, prefix, **kwargs):
if (os.path.sep in prefix[1:]): prefix_dir = len((os.path.dirname(prefix) + os.path.sep)) else: prefix_dir = 0 completion = [] globbed = [] if (('*' not in prefix) and ('?' not in prefix)): if (prefix[(-1)] == os.path.sep): globbed.extend(glob((prefix + '.*'))) prefix += '*' globbed.extend(glob(prefix)) for x in sorted(globbed): if os.path.isdir(x): x += '/' completion.append(x[prefix_dir:]) return completion
'alias attribute for ``fixturenames`` for pre-2.3 compatibility'
@property def funcargnames(self):
return self.fixturenames
'underlying collection node (depends on current request scope)'
@property def node(self):
return self._getscopeitem(self.scope)