Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_lastfailed_usecase(self, testdir, monkeypatch):
monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", 1)
p = testdir.makepyfile("""
def test_1():
assert 0
def test_2():
assert 0
def test_3():
assert 1
""")
result = testdir.runpytest()
result.stdout.fnmatch_lines([
"*2 failed*",
])
p.write(py.code.Source("""
def test_1():
assert 1
def test_2():
assert 1
def test_3():
assert 0
"""))
result = testdir.runpytest("--lf")
result.stdout.fnmatch_lines([
"*2 passed*1 desel*",
])
result = testdir.runpytest("--lf")
result.stdout.fnmatch_lines([
"*1 failed*2 passed*",
('x,y', 'x==y', 'failIfEqual,assertNotEqual, assertNotEquals'),
]
items = []
for sig, expr, names in aliasmap:
names = map(str.strip, names.split(','))
sigsubst = expr.replace('y', '%s').replace('x', '%s')
for name in names:
items.append("""
def %(name)s(self, %(sig)s, msg=""):
__tracebackhide__ = True
if %(expr)s:
raise Failed(msg=msg + (%(sigsubst)r %% (%(sig)s)))
""" % locals() )
source = "".join(items)
exec py.code.Source(source).compile()
__all__ = ['TestCase']
class MyDirectory(py.test.collect.Directory):
Module = MyModule
def run(self):
return ['somefile.py']
def join(self, name):
if name == "somefile.py":
return self.Module(self.fspath.join(name), parent=self)
def pytest_collect_directory(path, parent):
if path.basename == "subconf":
return MyDirectory(path, parent)
""")
subconf = testdir.mkpydir("subconf")
somefile = subconf.join("somefile.py")
somefile.write(py.code.Source("""
def check(): pass
class Cls:
def check2(self): pass
"""))
config = testdir.parseconfig(somefile)
dirnode = config.getnode(somefile.dirpath())
colitems = dirnode.collect()
w = recwarn.pop(DeprecationWarning)
assert w.filename.find("conftest.py") != -1
#recwarn.resetregistry()
#assert 0, (w.message, w.filename, w.lineno)
assert len(colitems) == 1
modcol = colitems[0]
assert modcol.name == "somefile.py"
colitems = modcol.collect()
recwarn.pop(DeprecationWarning)
def __init__(self, rawcode):
rawcode = py.code.getrawcode(rawcode)
self.raw = rawcode
try:
self.filename = rawcode.co_filename
self.firstlineno = rawcode.co_firstlineno - 1
self.name = rawcode.co_name
except AttributeError:
raise TypeError("not a code object: %r" %(rawcode,))
def repr_traceback_entry(self, entry, excinfo=None):
# excinfo is not None if this is the last tb entry
source = self._getentrysource(entry)
if source is None:
source = py.code.Source("???")
line_index = 0
else:
# entry.getfirstlinesource() can be -1, should be 0 on jython
line_index = entry.lineno - max(entry.getfirstlinesource(), 0)
lines = []
if self.style in ("short", "long"):
short = self.style == "short"
reprargs = None
if not short:
reprargs = self.repr_args(entry)
s = self.get_source(source, line_index, excinfo, short=short)
lines.extend(s)
if short:
message = "in %s" %(entry.name)
else:
def cut_stack(stack, frame, upward_frame=None):
if hasattr(frame, 'raw'):
frame = frame.raw
if upward_frame:
if hasattr(upward_frame, 'raw'):
upward_frame = upward_frame.raw
lst = [py.code.Frame(i) for i in stack[stack.index(frame):\
stack.index(upward_frame)+1]]
if len(lst) > 1:
return CallStack(lst[:-1])
return CallStack(lst)
return CallStack([py.code.Frame(i) for i in stack[stack.index(frame):]])
def setup_pkg(testname):
temp = py.test.ensuretemp(testname)
pkgpath = temp.ensure('pkg', dir=True)
pyfile = pkgpath.ensure('mod.py').write(py.code.Source("""
def foo(x):
return x + 1
"""))
testfile = pkgpath.ensure('test/test_mod.py').write(py.code.Source("""
from pkg.sub import foo
def test_foo():
assert foo(1) == 2
"""))
initfile = pkgpath.ensure('__init__.py').write(py.code.Source("""
import py
from py.__.initpkg import initpkg
initpkg(__name__, exportdefs={
'sub.foo': ('./mod.py', 'foo'),
})
"""))
initfile = pkgpath.ensure('apigen/apigen.py').write(py.code.Source("""
from py.__.apigen.apigen import build, \
get_documentable_items_pkgdir as get_documentable_items
"""))
return pkgpath
def patch_builtins(assertion=True, compile=True):
""" put compile and AssertionError builtins to Python's builtins. """
if assertion:
from py._code import assertion
l = oldbuiltins.setdefault('AssertionError', [])
l.append(py.builtin.builtins.AssertionError)
py.builtin.builtins.AssertionError = assertion.AssertionError
if compile:
l = oldbuiltins.setdefault('compile', [])
l.append(py.builtin.builtins.compile)
py.builtin.builtins.compile = py.code.compile
def getsource(obj, **kwargs):
obj = py.code.getrawcode(obj)
try:
strsrc = inspect.getsource(obj)
except IndentationError:
strsrc = "\"Buggy python version consider upgrading, cannot get source\""
assert isinstance(strsrc, str)
return Source(strsrc, **kwargs)
def __init__(self, frame):
self.lineno = frame.f_lineno - 1
self.f_globals = frame.f_globals
self.f_locals = frame.f_locals
self.raw = frame
self.code = py.code.Code(frame.f_code)