desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'the pytest config object associated with this request.'
| @property
def config(self):
| return self._pyfuncitem.config
|
'test function object if the request has a per-function scope.'
| @scopeproperty()
def function(self):
| return self._pyfuncitem.obj
|
'class (can be None) where the test function was collected.'
| @scopeproperty('class')
def cls(self):
| clscol = self._pyfuncitem.getparent(pytest.Class)
if clscol:
return clscol.obj
|
'instance (can be None) on which test function was collected.'
| @property
def instance(self):
| try:
return self._pyfuncitem._testcase
except AttributeError:
function = getattr(self, 'function', None)
if (function is not None):
return py.builtin._getimself(function)
|
'python module object where the test function was collected.'
| @scopeproperty()
def module(self):
| return self._pyfuncitem.getparent(pytest.Module).obj
|
'the file system path of the test module which collected this test.'
| @scopeproperty()
def fspath(self):
| return self._pyfuncitem.fspath
|
'keywords/markers dictionary for the underlying node.'
| @property
def keywords(self):
| return self.node.keywords
|
'pytest session object.'
| @property
def session(self):
| return self._pyfuncitem.session
|
'add finalizer/teardown function to be called after the
last test within the requesting test context finished
execution.'
| def addfinalizer(self, finalizer):
| self._addfinalizer(finalizer, scope=self.scope)
|
'Apply a marker to a single test function invocation.
This method is useful if you don\'t want to have a keyword/marker
on all function invocations.
:arg marker: a :py:class:`_pytest.mark.MarkDecorator` object
created by a call to ``pytest.mark.NAME(...)``.'
| def applymarker(self, marker):
| try:
self.node.keywords[marker.markname] = marker
except AttributeError:
raise ValueError(marker)
|
'raise a FixtureLookupError with the given message.'
| def raiseerror(self, msg):
| raise self._fixturemanager.FixtureLookupError(None, self, msg)
|
'(deprecated) Return a testing resource managed by ``setup`` &
``teardown`` calls. ``scope`` and ``extrakey`` determine when the
``teardown`` function will be called so that subsequent calls to
``setup`` would recreate the resource. With pytest-2.3 you often
do not need ``cached_setup()`` as you can directly declare a scope
on a fixture function and register a finalizer through
``request.addfinalizer()``.
:arg teardown: function receiving a previously setup resource.
:arg setup: a no-argument function creating a resource.
:arg scope: a string value out of ``function``, ``class``, ``module``
or ``session`` indicating the caching lifecycle of the resource.
:arg extrakey: added to internal caching key of (funcargname, scope).'
| def cached_setup(self, setup, teardown=None, scope='module', extrakey=None):
| if (not hasattr(self.config, '_setupcache')):
self.config._setupcache = {}
cachekey = (self.fixturename, self._getscopeitem(scope), extrakey)
cache = self.config._setupcache
try:
val = cache[cachekey]
except KeyError:
self._check_scope(self.fixturename, self.scope, scope)
val = setup()
cache[cachekey] = val
if (teardown is not None):
def finalizer():
del cache[cachekey]
teardown(val)
self._addfinalizer(finalizer, scope=scope)
return val
|
'Dynamically run a named fixture function.
Declaring fixtures via function argument is recommended where possible.
But if you can only decide whether to use another fixture at test
setup time, you may use this function to retrieve it inside a fixture
or test function body.'
| def getfixturevalue(self, argname):
| return self._get_active_fixturedef(argname).cached_result[0]
|
'Deprecated, use getfixturevalue.'
| def getfuncargvalue(self, argname):
| from _pytest import deprecated
warnings.warn(deprecated.GETFUNCARGVALUE, DeprecationWarning)
return self.getfixturevalue(argname)
|
'return a tuple of fixture names to be used.'
| def _getautousenames(self, nodeid):
| autousenames = []
for (baseid, basenames) in self._nodeid_and_autousenames:
if nodeid.startswith(baseid):
if baseid:
i = len(baseid)
nextchar = nodeid[i:(i + 1)]
if (nextchar and (nextchar not in ':/')):
continue
autousenames.extend(basenames)
autousenames.sort(key=(lambda x: self._arg2fixturedefs[x][(-1)].scopenum))
return autousenames
|
'Gets a list of fixtures which are applicable to the given node id.
:param str argname: name of the fixture to search for
:param str nodeid: full node id of the requesting test.
:return: list[FixtureDef]'
| def getfixturedefs(self, argname, nodeid):
| try:
fixturedefs = self._arg2fixturedefs[argname]
except KeyError:
return None
else:
return tuple(self._matchfactories(fixturedefs, nodeid))
|
'fspath sensitive hook proxy used to call pytest hooks'
| @property
def ihook(self):
| return self.session.gethookproxy(self.fspath)
|
'generate a warning with the given code and message for this
item.'
| def warn(self, code, message):
| assert isinstance(code, str)
fslocation = getattr(self, 'location', None)
if (fslocation is None):
fslocation = getattr(self, 'fspath', None)
else:
fslocation = ('%s:%s' % (fslocation[0], (fslocation[1] + 1)))
self.ihook.pytest_logwarning.call_historic(kwargs=dict(code=code, message=message, nodeid=self.nodeid, fslocation=fslocation))
|
'a ::-separated string denoting its collection tree address.'
| @property
def nodeid(self):
| try:
return self._nodeid
except AttributeError:
self._nodeid = x = self._makeid()
return x
|
'return list of all parent collectors up to self,
starting from root of collection tree.'
| def listchain(self):
| chain = []
item = self
while (item is not None):
chain.append(item)
item = item.parent
chain.reverse()
return chain
|
'dynamically add a marker object to the node.
``marker`` can be a string or pytest.mark.* instance.'
| def add_marker(self, marker):
| from _pytest.mark import MarkDecorator
if isinstance(marker, py.builtin._basestring):
marker = MarkDecorator(marker)
elif (not isinstance(marker, MarkDecorator)):
raise ValueError('is not a string or pytest.mark.* Marker')
self.keywords[marker.name] = marker
|
'get a marker object from this node or None if
the node doesn\'t have a marker with that name.'
| def get_marker(self, name):
| val = self.keywords.get(name, None)
if (val is not None):
from _pytest.mark import MarkInfo, MarkDecorator
if isinstance(val, (MarkDecorator, MarkInfo)):
return val
|
'Return a set of all extra keywords in self and any parents.'
| def listextrakeywords(self):
| extra_keywords = set()
item = self
for item in self.listchain():
extra_keywords.update(item.extra_keyword_matches)
return extra_keywords
|
'register a function to be called when this node is finalized.
This method can only be called when this node is active
in a setup chain, for example during self.setup().'
| def addfinalizer(self, fin):
| self.session._setupstate.addfinalizer(fin, self)
|
'get the next parent node (including ourself)
which is an instance of the given class'
| def getparent(self, cls):
| current = self
while (current and (not isinstance(current, cls))):
current = current.parent
return current
|
'returns a list of children (items and collectors)
for this collection node.'
| def collect(self):
| raise NotImplementedError('abstract')
|
'represent a collection failure.'
| def repr_failure(self, excinfo):
| if excinfo.errisinstance(self.CollectError):
exc = excinfo.value
return str(exc.args[0])
return self._repr_failure_py(excinfo, style='short')
|
'internal helper method to cache results of calling collect().'
| def _memocollect(self):
| return self._memoizedcall('_collected', (lambda : list(self.collect())))
|
'Convert a dotted module name to path.'
| def _tryconvertpyarg(self, x):
| import pkgutil
try:
loader = pkgutil.find_loader(x)
except ImportError:
return x
if (loader is None):
return x
try:
path = loader.get_filename(x)
except AttributeError:
path = loader.modules[x][0].co_filename
if loader.is_package(x):
path = os.path.dirname(path)
return path
|
'return (fspath, names) tuple after checking the file exists.'
| def _parsearg(self, arg):
| parts = str(arg).split('::')
if self.config.option.pyargs:
parts[0] = self._tryconvertpyarg(parts[0])
relpath = parts[0].replace('/', os.sep)
path = self.config.invocation_dir.join(relpath, abs=True)
if (not path.check()):
if self.config.option.pyargs:
raise pytest.UsageError((('file or package not found: ' + arg) + ' (missing __init__.py?)'))
else:
raise pytest.UsageError(('file not found: ' + arg))
parts[0] = path
return parts
|
'return a directory path object with the given name. If the
directory does not yet exist, it will be created. You can use it
to manage files likes e. g. store/retrieve database
dumps across test sessions.
:param name: must be a string not containing a ``/`` separator.
Make sure the name contains your plugin or application
identifiers to prevent clashes with other cache users.'
| def makedir(self, name):
| if ((_sep in name) or ((_altsep is not None) and (_altsep in name))):
raise ValueError('name is not allowed to contain path separators')
return self._cachedir.ensure_dir('d', name)
|
'return cached value for the given key. If no value
was yet cached or the value cannot be read, the specified
default is returned.
:param key: must be a ``/`` separated value. Usually the first
name is the name of your plugin or your application.
:param default: must be provided in case of a cache-miss or
invalid cache values.'
| def get(self, key, default):
| path = self._getvaluepath(key)
if path.check():
try:
with path.open('r') as f:
return json.load(f)
except ValueError:
self.trace(('cache-invalid at %s' % (path,)))
return default
|
'save value for the given key.
:param key: must be a ``/`` separated value. Usually the first
name is the name of your plugin or your application.
:param value: must be of any combination of basic
python types, including nested types
like e. g. lists of dictionaries.'
| def set(self, key, value):
| path = self._getvaluepath(key)
try:
path.dirpath().ensure_dir()
except (py.error.EEXIST, py.error.EACCES):
self.config.warn(code='I9', message=('could not create cache path %s' % (path,)))
return
try:
f = path.open('w')
except py.error.ENOTDIR:
self.config.warn(code='I9', message=('cache could not write path %s' % (path,)))
else:
with f:
self.trace(('cache-write %s: %r' % (key, value)))
json.dump(value, f, indent=2, sort_keys=True)
|
'return python path relative to the containing module.'
| def getmodpath(self, stopatmodule=True, includemodule=False):
| chain = self.listchain()
chain.reverse()
parts = []
for node in chain:
if isinstance(node, Instance):
continue
name = node.name
if isinstance(node, Module):
assert name.endswith('.py')
name = name[:(-3)]
if stopatmodule:
if includemodule:
parts.append(name)
break
parts.append(name)
parts.reverse()
s = '.'.join(parts)
return s.replace('.[', '[')
|
'Look for the __test__ attribute, which is applied by the
@nose.tools.istest decorator'
| def isnosetest(self, obj):
| return (safe_getattr(obj, '__test__', False) is True)
|
'checks if the given name matches the prefix or glob-pattern defined
in ini configuration.'
| def _matches_prefix_or_glob_option(self, option_name, name):
| for option in self.config.getini(option_name):
if name.startswith(option):
return True
elif ((('*' in option) or ('?' in option) or ('[' in option)) and fnmatch.fnmatch(name, option)):
return True
return False
|
'perform setup for this test function.'
| def setup(self):
| if hasattr(self, '_preservedparent'):
obj = self._preservedparent
elif isinstance(self.parent, Instance):
obj = self.parent.newinstance()
self.obj = self._getobj()
else:
obj = self.parent.obj
if inspect.ismethod(self.obj):
setup_name = 'setup_method'
teardown_name = 'teardown_method'
else:
setup_name = 'setup_function'
teardown_name = 'teardown_function'
setup_func_or_method = _get_xunit_setup_teardown(obj, setup_name, param_obj=self.obj)
if (setup_func_or_method is not None):
setup_func_or_method()
teardown_func_or_method = _get_xunit_setup_teardown(obj, teardown_name, param_obj=self.obj)
if (teardown_func_or_method is not None):
self.addfinalizer(teardown_func_or_method)
|
'Add new invocations to the underlying test function using the list
of argvalues for the given argnames. Parametrization is performed
during the collection phase. If you need to setup expensive resources
see about setting indirect to do it rather at test setup time.
:arg argnames: a comma-separated string denoting one or more argument
names, or a list/tuple of argument strings.
:arg argvalues: The list of argvalues determines how often a
test is invoked with different argument values. If only one
argname was specified argvalues is a list of values. If N
argnames were specified, argvalues must be a list of N-tuples,
where each tuple-element specifies a value for its respective
argname.
:arg indirect: The list of argnames or boolean. A list of arguments\'
names (subset of argnames). If True the list contains all names from
the argnames. Each argvalue corresponding to an argname in this list will
be passed as request.param to its respective argname fixture
function so that it can perform more expensive setups during the
setup phase of a test rather than at collection time.
:arg ids: list of string ids, or a callable.
If strings, each is corresponding to the argvalues so that they are
part of the test id. If None is given as id of specific test, the
automatically generated id for that argument will be used.
If callable, it should take one argument (a single argvalue) and return
a string or return None. If None, the automatically generated id for that
argument will be used.
If no ids are provided they will be generated automatically from
the argvalues.
:arg scope: if specified it denotes the scope of the parameters.
The scope is used for grouping tests by parameter instances.
It will also override any fixture-function defined scope, allowing
to set a dynamic scope using test context or configuration.'
| def parametrize(self, argnames, argvalues, indirect=False, ids=None, scope=None):
| from _pytest.fixtures import scope2index
from _pytest.mark import extract_argvalue
from py.io import saferepr
unwrapped_argvalues = []
newkeywords = []
for maybe_marked_args in argvalues:
(argval, newmarks) = extract_argvalue(maybe_marked_args)
unwrapped_argvalues.append(argval)
newkeywords.append(newmarks)
argvalues = unwrapped_argvalues
if (not isinstance(argnames, (tuple, list))):
argnames = [x.strip() for x in argnames.split(',') if x.strip()]
if (len(argnames) == 1):
argvalues = [(val,) for val in argvalues]
if (not argvalues):
argvalues = [((NOTSET,) * len(argnames))]
(fs, lineno) = getfslineno(self.function)
newmark = pytest.mark.skip(reason=('got empty parameter set %r, function %s at %s:%d' % (argnames, self.function.__name__, fs, lineno)))
newkeywords = [{newmark.markname: newmark}]
if (scope is None):
scope = _find_parametrized_scope(argnames, self._arg2fixturedefs, indirect)
scopenum = scope2index(scope, descr='call to {0}'.format(self.parametrize))
valtypes = {}
for arg in argnames:
if (arg not in self.fixturenames):
if isinstance(indirect, (tuple, list)):
name = ('fixture' if (arg in indirect) else 'argument')
else:
name = ('fixture' if indirect else 'argument')
raise ValueError(('%r uses no %s %r' % (self.function, name, arg)))
if (indirect is True):
valtypes = dict.fromkeys(argnames, 'params')
elif (indirect is False):
valtypes = dict.fromkeys(argnames, 'funcargs')
elif isinstance(indirect, (tuple, list)):
valtypes = dict.fromkeys(argnames, 'funcargs')
for arg in indirect:
if (arg not in argnames):
raise ValueError(("indirect given to %r: fixture %r doesn't exist" % (self.function, arg)))
valtypes[arg] = 'params'
idfn = None
if callable(ids):
idfn = ids
ids = None
if ids:
if (len(ids) != len(argvalues)):
raise ValueError(('%d tests specified with %d ids' % (len(argvalues), len(ids))))
for id_value in ids:
if ((id_value is not None) and (not isinstance(id_value, py.builtin._basestring))):
msg = 'ids must be list of strings, found: %s (type: %s)'
raise ValueError((msg % (saferepr(id_value), type(id_value).__name__)))
ids = idmaker(argnames, argvalues, idfn, ids, self.config)
newcalls = []
for callspec in (self._calls or [CallSpec2(self)]):
elements = zip(ids, argvalues, newkeywords, count())
for (a_id, valset, keywords, param_index) in elements:
assert (len(valset) == len(argnames))
newcallspec = callspec.copy(self)
newcallspec.setmulti(valtypes, argnames, valset, a_id, keywords, scopenum, param_index)
newcalls.append(newcallspec)
self._calls = newcalls
|
'(deprecated, use parametrize) Add a new call to the underlying
test function during the collection phase of a test run. Note that
request.addcall() is called during the test collection phase prior and
independently to actual test execution. You should only use addcall()
if you need to specify multiple arguments of a test function.
:arg funcargs: argument keyword dictionary used when invoking
the test function.
:arg id: used for reporting and identification purposes. If you
don\'t supply an `id` an automatic unique id will be generated.
:arg param: a parameter which will be exposed to a later fixture function
invocation through the ``request.param`` attribute.'
| def addcall(self, funcargs=None, id=NOTSET, param=NOTSET):
| assert ((funcargs is None) or isinstance(funcargs, dict))
if (funcargs is not None):
for name in funcargs:
if (name not in self.fixturenames):
pytest.fail(('funcarg %r not used in this function.' % name))
else:
funcargs = {}
if (id is None):
raise ValueError('id=None not allowed')
if (id is NOTSET):
id = len(self._calls)
id = str(id)
if (id in self._ids):
raise ValueError(('duplicate id %r' % id))
self._ids.add(id)
cs = CallSpec2(self)
cs.setall(funcargs, id, param)
self._calls.append(cs)
|
'underlying python \'function\' object'
| @property
def function(self):
| return getattr(self.obj, 'im_func', self.obj)
|
'(compatonly) for code expecting pytest-2.2 style request objects'
| @property
def _pyfuncitem(self):
| return self
|
'execute the underlying test function.'
| def runtest(self):
| self.ihook.pytest_pyfunc_call(pyfuncitem=self)
|
'return a path object pointing to source code (note that it
might not point to an actually existing file).'
| @property
def path(self):
| try:
p = py.path.local(self.raw.co_filename)
if (not p.check()):
raise OSError('py.path check failed.')
except OSError:
p = self.raw.co_filename
return p
|
'return a _pytest._code.Source object for the full source file of the code'
| @property
def fullsource(self):
| from _pytest._code import source
(full, _) = source.findsource(self.raw)
return full
|
'return a _pytest._code.Source object for the code object\'s source only'
| def source(self):
| import _pytest._code
return _pytest._code.Source(self.raw)
|
'return a tuple with the argument names for the code object
if \'var\' is set True also return the names of the variable and
keyword arguments when present'
| def getargs(self, var=False):
| raw = self.raw
argcount = raw.co_argcount
if var:
argcount += (raw.co_flags & CO_VARARGS)
argcount += (raw.co_flags & CO_VARKEYWORDS)
return raw.co_varnames[:argcount]
|
'statement this frame is at'
| @property
def statement(self):
| import _pytest._code
if (self.code.fullsource is None):
return _pytest._code.Source('')
return self.code.fullsource.getstatement(self.lineno)
|
'evaluate \'code\' in the frame
\'vars\' are optional additional local variables
returns the result of the evaluation'
| def eval(self, code, **vars):
| f_locals = self.f_locals.copy()
f_locals.update(vars)
return eval(code, self.f_globals, f_locals)
|
'exec \'code\' in the frame
\'vars\' are optiona; additional local variables'
| def exec_(self, code, **vars):
| f_locals = self.f_locals.copy()
f_locals.update(vars)
py.builtin.exec_(code, self.f_globals, f_locals)
|
'return a \'safe\' (non-recursive, one-line) string repr for \'object\''
| def repr(self, object):
| return py.io.saferepr(object)
|
'return a list of tuples (name, value) for all arguments
if \'var\' is set True also include the variable and keyword
arguments when present'
| def getargs(self, var=False):
| retval = []
for arg in self.code.getargs(var):
try:
retval.append((arg, self.f_locals[arg]))
except KeyError:
pass
return retval
|
'_pytest._code.Source object for the current statement'
| @property
def statement(self):
| source = self.frame.code.fullsource
return source.getstatement(self.lineno)
|
'path to the source code'
| @property
def path(self):
| return self.frame.code.path
|
'return failing source code.'
| def getsource(self, astcache=None):
| from _pytest._code.source import getstatementrange_ast
source = self.frame.code.fullsource
if (source is None):
return None
key = astnode = None
if (astcache is not None):
key = self.frame.code.path
if (key is not None):
astnode = astcache.get(key, None)
start = self.getfirstlinesource()
try:
(astnode, _, end) = getstatementrange_ast(self.lineno, source, astnode=astnode)
except SyntaxError:
end = (self.lineno + 1)
else:
if (key is not None):
astcache[key] = astnode
return source[start:end]
|
'return True if the current frame has a var __tracebackhide__
resolving to True
If __tracebackhide__ is a callable, it gets called with the
ExceptionInfo instance and can decide whether to hide the traceback.
mostly for internal use'
| def ishidden(self):
| try:
tbh = self.frame.f_locals['__tracebackhide__']
except KeyError:
try:
tbh = self.frame.f_globals['__tracebackhide__']
except KeyError:
return False
if py.builtin.callable(tbh):
return tbh((None if (self._excinfo is None) else self._excinfo()))
else:
return tbh
|
'initialize from given python traceback object and ExceptionInfo'
| def __init__(self, tb, excinfo=None):
| self._excinfo = excinfo
if hasattr(tb, 'tb_next'):
def f(cur):
while (cur is not None):
(yield self.Entry(cur, excinfo=excinfo))
cur = cur.tb_next
list.__init__(self, f(tb))
else:
list.__init__(self, tb)
|
'return a Traceback instance wrapping part of this Traceback
by provding any combination of path, lineno and firstlineno, the
first frame to start the to-be-returned traceback is determined
this allows cutting the first part of a Traceback instance e.g.
for formatting reasons (removing some uninteresting bits that deal
with handling of the exception/traceback)'
| def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None):
| for x in self:
code = x.frame.code
codepath = code.path
if (((path is None) or (codepath == path)) and ((excludepath is None) or (not hasattr(codepath, 'relto')) or (not codepath.relto(excludepath))) and ((lineno is None) or (x.lineno == lineno)) and ((firstlineno is None) or (x.frame.code.firstlineno == firstlineno))):
return Traceback(x._rawentry, self._excinfo)
return self
|
'return a Traceback instance with certain items removed
fn is a function that gets a single argument, a TracebackEntry
instance, and should return True when the item should be added
to the Traceback, False when not
by default this removes all the TracebackEntries which are hidden
(see ishidden() above)'
| def filter(self, fn=(lambda x: (not x.ishidden()))):
| return Traceback(filter(fn, self), self._excinfo)
|
'return last non-hidden traceback entry that lead
to the exception of a traceback.'
| def getcrashentry(self):
| for i in range((-1), ((- len(self)) - 1), (-1)):
entry = self[i]
if (not entry.ishidden()):
return entry
return self[(-1)]
|
'return the index of the frame/TracebackEntry where recursion
originates if appropriate, None if no recursion occurred'
| def recursionindex(self):
| cache = {}
for (i, entry) in enumerate(self):
key = (entry.frame.code.path, id(entry.frame.code.raw), entry.lineno)
l = cache.setdefault(key, [])
if l:
f = entry.frame
loc = f.f_locals
for otherloc in l:
if f.is_true(f.eval(co_equal, __recursioncache_locals_1=loc, __recursioncache_locals_2=otherloc)):
return i
l.append(entry.frame.f_locals)
return None
|
'return the exception as a string
when \'tryshort\' resolves to True, and the exception is a
_pytest._code._AssertionError, only the actual exception part of
the exception representation is returned (so \'AssertionError: \' is
removed from the beginning)'
| def exconly(self, tryshort=False):
| lines = format_exception_only(self.type, self.value)
text = ''.join(lines)
text = text.rstrip()
if tryshort:
if text.startswith(self._striptext):
text = text[len(self._striptext):]
return text
|
'return True if the exception is an instance of exc'
| def errisinstance(self, exc):
| return isinstance(self.value, exc)
|
'return str()able representation of this exception info.
showlocals: show locals per traceback entry
style: long|short|no|native traceback style
tbfilter: hide entries (where __tracebackhide__ is true)
in case of style==native, tbfilter and showlocals is ignored.'
| def getrepr(self, showlocals=False, style='long', abspath=False, tbfilter=True, funcargs=False):
| if (style == 'native'):
return ReprExceptionInfo(ReprTracebackNative(py.std.traceback.format_exception(self.type, self.value, self.traceback[0]._rawentry)), self._getreprcrash())
fmt = FormattedExcinfo(showlocals=showlocals, style=style, abspath=abspath, tbfilter=tbfilter, funcargs=funcargs)
return fmt.repr_excinfo(self)
|
'Match the regular expression \'regexp\' on the string representation of
the exception. If it matches then True is returned (so that it is
possible to write \'assert excinfo.match()\'). If it doesn\'t match an
AssertionError is raised.'
| def match(self, regexp):
| __tracebackhide__ = True
if (not re.search(regexp, str(self.value))):
assert 0, "Pattern '{0!s}' not found in '{1!s}'".format(regexp, self.value)
return True
|
'return formatted and marked up source lines.'
| def get_source(self, source, line_index=(-1), excinfo=None, short=False):
| import _pytest._code
lines = []
if ((source is None) or (line_index >= len(source.lines))):
source = _pytest._code.Source('???')
line_index = 0
if (line_index < 0):
line_index += len(source)
space_prefix = ' '
if short:
lines.append((space_prefix + source.lines[line_index].strip()))
else:
for line in source.lines[:line_index]:
lines.append((space_prefix + line))
lines.append(((self.flow_marker + ' ') + source.lines[line_index]))
for line in source.lines[(line_index + 1):]:
lines.append((space_prefix + line))
if (excinfo is not None):
indent = (4 if short else self._getindent(source))
lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))
return lines
|
'return new source object with trailing
and leading blank lines removed.'
| def strip(self):
| (start, end) = (0, len(self))
while ((start < end) and (not self.lines[start].strip())):
start += 1
while ((end > start) and (not self.lines[(end - 1)].strip())):
end -= 1
source = Source()
source.lines[:] = self.lines[start:end]
return source
|
'return a copy of the source object with
\'before\' and \'after\' wrapped around it.'
| def putaround(self, before='', after='', indent=(' ' * 4)):
| before = Source(before)
after = Source(after)
newsource = Source()
lines = [(indent + line) for line in self.lines]
newsource.lines = ((before.lines + lines) + after.lines)
return newsource
|
'return a copy of the source object with
all lines indented by the given indent-string.'
| def indent(self, indent=(' ' * 4)):
| newsource = Source()
newsource.lines = [(indent + line) for line in self.lines]
return newsource
|
'return Source statement which contains the
given linenumber (counted from 0).'
| def getstatement(self, lineno, assertion=False):
| (start, end) = self.getstatementrange(lineno, assertion)
return self[start:end]
|
'return (start, end) tuple which spans the minimal
statement region which containing the given lineno.'
| def getstatementrange(self, lineno, assertion=False):
| if (not (0 <= lineno < len(self))):
raise IndexError('lineno out of range')
(ast, start, end) = getstatementrange_ast(lineno, self)
return (start, end)
|
'return a new source object deindented by offset.
If offset is None then guess an indentation offset from
the first non-blank line. Subsequent lines which have a
lower indentation offset will be copied verbatim as
they are assumed to be part of multilines.'
| def deindent(self, offset=None):
| newsource = Source()
newsource.lines[:] = deindent(self.lines, offset)
return newsource
|
'return True if source is parseable, heuristically
deindenting it by default.'
| def isparseable(self, deindent=True):
| try:
import parser
except ImportError:
syntax_checker = (lambda x: compile(x, 'asd', 'exec'))
else:
syntax_checker = parser.suite
if deindent:
source = str(self.deindent())
else:
source = str(self)
try:
syntax_checker((source + '\n'))
except KeyboardInterrupt:
raise
except Exception:
return False
else:
return True
|
'return compiled code object. if filename is None
invent an artificial filename which displays
the source/line position of the caller frame.'
| def compile(self, filename=None, mode='exec', flag=generators.compiler_flag, dont_inherit=0, _genframe=None):
| if ((not filename) or py.path.local(filename).check(file=0)):
if (_genframe is None):
_genframe = sys._getframe(1)
(fn, lineno) = (_genframe.f_code.co_filename, _genframe.f_lineno)
base = ('<%d-codegen ' % self._compilecounter)
self.__class__._compilecounter += 1
if (not filename):
filename = (base + ('%s:%d>' % (fn, lineno)))
else:
filename = (base + ('%r %s:%d>' % (filename, fn, lineno)))
source = ('\n'.join(self.lines) + '\n')
try:
co = cpy_compile(source, filename, mode, flag)
except SyntaxError:
ex = sys.exc_info()[1]
msglines = self.lines[:ex.lineno]
if ex.offset:
msglines.append(((' ' * ex.offset) + '^'))
msglines.append(('(code was compiled probably from here: %s)' % filename))
newex = SyntaxError('\n'.join(msglines))
newex.offset = ex.offset
newex.lineno = ex.lineno
newex.text = ex.text
raise newex
else:
if (flag & _AST_FLAG):
return co
lines = [(x + '\n') for x in self.lines]
py.std.linecache.cache[filename] = (1, None, lines, filename)
return co
|
'The @unittest.skip decorator calls functools.wraps(self._testcase)
The call to functools.wraps() fails unless self._testcase
has a __name__ attribute. This is usually automatically supplied
if the test is a function or method, but we need to add manually
here.
See issue #1169'
| def _fix_unittest_skip_decorator(self):
| if (sys.version_info[0] == 2):
setattr(self._testcase, '__name__', self.name)
|
'Mark import names as needing to be re-written.
The named module or package as well as any nested modules will
be re-written on import.'
| def mark_rewrite(self, *names):
| already_imported = set(names).intersection(set(sys.modules))
if already_imported:
for name in already_imported:
if (name not in self._rewritten_names):
self._warn_already_imported(name)
self._must_rewrite.update(names)
|
'Ensure package resources can be loaded from this loader. May be called
multiple times, as the operation is idempotent.'
| @classmethod
def _register_with_pkg_resources(cls):
| try:
import pkg_resources
pkg_resources.__name__
except ImportError:
return
pkg_resources.register_loader_type(cls, pkg_resources.DefaultProvider)
|
'Optional PEP302 get_data API.'
| def get_data(self, pathname):
| with open(pathname, 'rb') as f:
return f.read()
|
'Find all assert statements in *mod* and rewrite them.'
| def run(self, mod):
| if (not mod.body):
return
aliases = [ast.alias(py.builtin.builtins.__name__, '@py_builtins'), ast.alias('_pytest.assertion.rewrite', '@pytest_ar')]
expect_docstring = True
pos = 0
lineno = 0
for item in mod.body:
if (expect_docstring and isinstance(item, ast.Expr) and isinstance(item.value, ast.Str)):
doc = item.value.s
if ('PYTEST_DONT_REWRITE' in doc):
return
lineno += (len(doc) - 1)
expect_docstring = False
elif ((not isinstance(item, ast.ImportFrom)) or (item.level > 0) or (item.module != '__future__')):
lineno = item.lineno
break
pos += 1
imports = [ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases]
mod.body[pos:pos] = imports
nodes = [mod]
while nodes:
node = nodes.pop()
for (name, field) in ast.iter_fields(node):
if isinstance(field, list):
new = []
for (i, child) in enumerate(field):
if isinstance(child, ast.Assert):
new.extend(self.visit(child))
else:
new.append(child)
if isinstance(child, ast.AST):
nodes.append(child)
setattr(node, name, new)
elif (isinstance(field, ast.AST) and (not isinstance(field, ast.expr))):
nodes.append(field)
|
'Get a new variable.'
| def variable(self):
| name = ('@py_assert' + str(next(self.variable_counter)))
self.variables.append(name)
return name
|
'Give *expr* a name.'
| def assign(self, expr):
| name = self.variable()
self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))
return ast.Name(name, ast.Load())
|
'Call py.io.saferepr on the expression.'
| def display(self, expr):
| return self.helper('saferepr', expr)
|
'Call a helper in this module.'
| def helper(self, name, *args):
| py_name = ast.Name('@pytest_ar', ast.Load())
attr = ast.Attribute(py_name, ('_' + name), ast.Load())
return ast_Call(attr, list(args), [])
|
'Return the builtin called *name*.'
| def builtin(self, name):
| builtin_name = ast.Name('@py_builtins', ast.Load())
return ast.Attribute(builtin_name, name, ast.Load())
|
'Return a new named %-formatting placeholder for expr.
This creates a %-formatting placeholder for expr in the
current formatting context, e.g. ``%(py0)s``. The placeholder
and expr are placed in the current format context so that it
can be used on the next call to .pop_format_context().'
| def explanation_param(self, expr):
| specifier = ('py' + str(next(self.variable_counter)))
self.explanation_specifiers[specifier] = expr
return (('%(' + specifier) + ')s')
|
'Create a new formatting context.
The format context is used for when an explanation wants to
have a variable value formatted in the assertion message. In
this case the value required can be added using
.explanation_param(). Finally .pop_format_context() is used
to format a string of %-formatted values as added by
.explanation_param().'
| def push_format_context(self):
| self.explanation_specifiers = {}
self.stack.append(self.explanation_specifiers)
|
'Format the %-formatted string with current format context.
The expl_expr should be an ast.Str instance constructed from
the %-placeholders created by .explanation_param(). This will
add the required code to format said string to .on_failure and
return the ast.Name instance of the formatted string.'
| def pop_format_context(self, expl_expr):
| current = self.stack.pop()
if self.stack:
self.explanation_specifiers = self.stack[(-1)]
keys = [ast.Str(key) for key in current.keys()]
format_dict = ast.Dict(keys, list(current.values()))
form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
name = ('@py_format' + str(next(self.variable_counter)))
self.on_failure.append(ast.Assign([ast.Name(name, ast.Store())], form))
return ast.Name(name, ast.Load())
|
'Handle expressions we don\'t have custom code for.'
| def generic_visit(self, node):
| assert isinstance(node, ast.expr)
res = self.assign(node)
return (res, self.explanation_param(self.display(res)))
|
'Return the AST statements to replace the ast.Assert instance.
This re-writes the test of an assertion to provide
intermediate values and replace it with an if statement which
raises an assertion error with a detailed explanation in case
the expression is false.'
| def visit_Assert(self, assert_):
| if (isinstance(assert_.test, ast.Tuple) and (self.config is not None)):
fslocation = (self.module_path, assert_.lineno)
self.config.warn('R1', 'assertion is always true, perhaps remove parentheses?', fslocation=fslocation)
self.statements = []
self.variables = []
self.variable_counter = itertools.count()
self.stack = []
self.on_failure = []
self.push_format_context()
(top_condition, explanation) = self.visit(assert_.test)
body = self.on_failure
negation = ast.UnaryOp(ast.Not(), top_condition)
self.statements.append(ast.If(negation, body, []))
if assert_.msg:
assertmsg = self.helper('format_assertmsg', assert_.msg)
explanation = ('\n>assert ' + explanation)
else:
assertmsg = ast.Str('')
explanation = ('assert ' + explanation)
template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))
msg = self.pop_format_context(template)
fmt = self.helper('format_explanation', msg)
err_name = ast.Name('AssertionError', ast.Load())
exc = ast_Call(err_name, [fmt], [])
if (sys.version_info[0] >= 3):
raise_ = ast.Raise(exc, None)
else:
raise_ = ast.Raise(exc, None, None)
body.append(raise_)
if self.variables:
variables = [ast.Name(name, ast.Store()) for name in self.variables]
clear = ast.Assign(variables, _NameConstant(None))
self.statements.append(clear)
for stmt in self.statements:
set_location(stmt, assert_.lineno, assert_.col_offset)
return self.statements
|
'visit `ast.Call` nodes on Python3.5 and after'
| def visit_Call_35(self, call):
| (new_func, func_expl) = self.visit(call.func)
arg_expls = []
new_args = []
new_kwargs = []
for arg in call.args:
(res, expl) = self.visit(arg)
arg_expls.append(expl)
new_args.append(res)
for keyword in call.keywords:
(res, expl) = self.visit(keyword.value)
new_kwargs.append(ast.keyword(keyword.arg, res))
if keyword.arg:
arg_expls.append(((keyword.arg + '=') + expl))
else:
arg_expls.append(('**' + expl))
expl = ('%s(%s)' % (func_expl, ', '.join(arg_expls)))
new_call = ast.Call(new_func, new_args, new_kwargs)
res = self.assign(new_call)
res_expl = self.explanation_param(self.display(res))
outer_expl = ('%s\n{%s = %s\n}' % (res_expl, res_expl, expl))
return (res, outer_expl)
|
'visit `ast.Call nodes on 3.4 and below`'
| def visit_Call_legacy(self, call):
| (new_func, func_expl) = self.visit(call.func)
arg_expls = []
new_args = []
new_kwargs = []
new_star = new_kwarg = None
for arg in call.args:
(res, expl) = self.visit(arg)
new_args.append(res)
arg_expls.append(expl)
for keyword in call.keywords:
(res, expl) = self.visit(keyword.value)
new_kwargs.append(ast.keyword(keyword.arg, res))
arg_expls.append(((keyword.arg + '=') + expl))
if call.starargs:
(new_star, expl) = self.visit(call.starargs)
arg_expls.append(('*' + expl))
if call.kwargs:
(new_kwarg, expl) = self.visit(call.kwargs)
arg_expls.append(('**' + expl))
expl = ('%s(%s)' % (func_expl, ', '.join(arg_expls)))
new_call = ast.Call(new_func, new_args, new_kwargs, new_star, new_kwarg)
res = self.assign(new_call)
res_expl = self.explanation_param(self.display(res))
outer_expl = ('%s\n{%s = %s\n}' % (res_expl, res_expl, expl))
return (res, outer_expl)
|
'invoke PDB set_trace debugging, dropping any IO capturing.'
| def set_trace(self):
| import _pytest.config
frame = sys._getframe().f_back
if (self._pluginmanager is not None):
capman = self._pluginmanager.getplugin('capturemanager')
if capman:
capman.suspendcapture(in_=True)
tw = _pytest.config.create_terminal_writer(self._config)
tw.line()
tw.sep('>', 'PDB set_trace (IO-capturing turned off)')
self._pluginmanager.hook.pytest_enter_pdb(config=self._config)
self._pdb_cls().set_trace(frame)
|
'if passed a single callable argument: decorate it with mark info.
otherwise add *args/**kwargs in-place to mark information.'
| def __call__(self, *args, **kwargs):
| if (args and (not kwargs)):
func = args[0]
is_class = inspect.isclass(func)
if ((len(args) == 1) and (istestfunc(func) or is_class)):
if is_class:
if hasattr(func, 'pytestmark'):
mark_list = func.pytestmark
if (not isinstance(mark_list, list)):
mark_list = [mark_list]
mark_list = (mark_list + [self])
func.pytestmark = mark_list
else:
func.pytestmark = [self]
else:
holder = getattr(func, self.name, None)
if (holder is None):
holder = MarkInfo(self.name, self.args, self.kwargs)
setattr(func, self.name, holder)
else:
holder.add(self.args, self.kwargs)
return func
kw = self.kwargs.copy()
kw.update(kwargs)
args = (self.args + args)
return self.__class__(self.name, args=args, kwargs=kw)
|
'add a MarkInfo with the given args and kwargs.'
| def add(self, args, kwargs):
| self._arglist.append((args, kwargs))
self.args += args
self.kwargs.update(kwargs)
|
'yield MarkInfo objects each relating to a marking-call.'
| def __iter__(self):
| for (args, kwargs) in self._arglist:
(yield MarkInfo(self.name, args, kwargs))
|
'if passed a function, directly sets attributes on the function
which will make it discoverable to add_hookspecs(). If passed no
function, returns a decorator which can be applied to a function
later using the attributes supplied.
If firstresult is True the 1:N hook call (N being the number of registered
hook implementation functions) will stop at I<=N when the I\'th function
returns a non-None result.
If historic is True calls to a hook will be memorized and replayed
on later registered plugins.'
| def __call__(self, function=None, firstresult=False, historic=False):
| def setattr_hookspec_opts(func):
if (historic and firstresult):
raise ValueError('cannot have a historic firstresult hook')
setattr(func, (self.project_name + '_spec'), dict(firstresult=firstresult, historic=historic))
return func
if (function is not None):
return setattr_hookspec_opts(function)
else:
return setattr_hookspec_opts
|
'if passed a function, directly sets attributes on the function
which will make it discoverable to register(). If passed no function,
returns a decorator which can be applied to a function later using
the attributes supplied.
If optionalhook is True a missing matching hook specification will not result
in an error (by default it is an error if no matching spec is found).
If tryfirst is True this hook implementation will run as early as possible
in the chain of N hook implementations for a specfication.
If trylast is True this hook implementation will run as late as possible
in the chain of N hook implementations.
If hookwrapper is True the hook implementations needs to execute exactly
one "yield". The code before the yield is run early before any non-hookwrapper
function is run. The code after the yield is run after all non-hookwrapper
function have run. The yield receives an ``_CallOutcome`` object representing
the exception or result outcome of the inner calls (including other hookwrapper
calls).'
| def __call__(self, function=None, hookwrapper=False, optionalhook=False, tryfirst=False, trylast=False):
| def setattr_hookimpl_opts(func):
setattr(func, (self.project_name + '_impl'), dict(hookwrapper=hookwrapper, optionalhook=optionalhook, tryfirst=tryfirst, trylast=trylast))
return func
if (function is None):
return setattr_hookimpl_opts
else:
return setattr_hookimpl_opts(function)
|
'if implprefix is given implementation functions
will be recognized if their name matches the implprefix.'
| def __init__(self, project_name, implprefix=None):
| self.project_name = project_name
self._name2plugin = {}
self._plugin2hookcallers = {}
self._plugin_distinfo = []
self.trace = _TagTracer().get('pluginmanage')
self.hook = _HookRelay(self.trace.root.get('hook'))
self._implprefix = implprefix
self._inner_hookexec = (lambda hook, methods, kwargs: _MultiCall(methods, kwargs, hook.spec_opts).execute())
|
'Register a plugin and return its canonical name or None if the name
is blocked from registering. Raise a ValueError if the plugin is already
registered.'
| def register(self, plugin, name=None):
| plugin_name = (name or self.get_canonical_name(plugin))
if ((plugin_name in self._name2plugin) or (plugin in self._plugin2hookcallers)):
if (self._name2plugin.get(plugin_name, (-1)) is None):
return
raise ValueError(('Plugin already registered: %s=%s\n%s' % (plugin_name, plugin, self._name2plugin)))
self._name2plugin[plugin_name] = plugin
self._plugin2hookcallers[plugin] = hookcallers = []
for name in dir(plugin):
hookimpl_opts = self.parse_hookimpl_opts(plugin, name)
if (hookimpl_opts is not None):
normalize_hookimpl_opts(hookimpl_opts)
method = getattr(plugin, name)
hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_opts)
hook = getattr(self.hook, name, None)
if (hook is None):
hook = _HookCaller(name, self._hookexec)
setattr(self.hook, name, hook)
elif hook.has_spec():
self._verify_hook(hook, hookimpl)
hook._maybe_apply_history(hookimpl)
hook._add_hookimpl(hookimpl)
hookcallers.append(hook)
return plugin_name
|
'unregister a plugin object and all its contained hook implementations
from internal data structures.'
| def unregister(self, plugin=None, name=None):
| if (name is None):
assert (plugin is not None), 'one of name or plugin needs to be specified'
name = self.get_name(plugin)
if (plugin is None):
plugin = self.get_plugin(name)
if self._name2plugin.get(name):
del self._name2plugin[name]
for hookcaller in self._plugin2hookcallers.pop(plugin, []):
hookcaller._remove_plugin(plugin)
return plugin
|
'block registrations of the given name, unregister if already registered.'
| def set_blocked(self, name):
| self.unregister(name=name)
self._name2plugin[name] = None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.