Merge branch 'features' into conftest-exception-printing
This commit is contained in:
@@ -762,3 +762,52 @@ class TestDurationWithFixture:
|
||||
* setup *test_1*
|
||||
* call *test_1*
|
||||
""")
|
||||
|
||||
|
||||
def test_yield_tests_deprecation(testdir):
|
||||
testdir.makepyfile("""
|
||||
def func1(arg, arg2):
|
||||
assert arg == arg2
|
||||
def test_gen():
|
||||
yield "m1", func1, 15, 3*5
|
||||
yield "m2", func1, 42, 6*7
|
||||
""")
|
||||
result = testdir.runpytest('-ra')
|
||||
result.stdout.fnmatch_lines([
|
||||
'*yield tests are deprecated, and scheduled to be removed in pytest 4.0*',
|
||||
'*2 passed*',
|
||||
])
|
||||
|
||||
|
||||
def test_funcarg_prefix_deprecation(testdir):
|
||||
testdir.makepyfile("""
|
||||
def pytest_funcarg__value():
|
||||
return 10
|
||||
|
||||
def test_funcarg_prefix(value):
|
||||
assert value == 10
|
||||
""")
|
||||
result = testdir.runpytest('-ra')
|
||||
result.stdout.fnmatch_lines([
|
||||
('WC1 None pytest_funcarg__value: '
|
||||
'declaring fixtures using "pytest_funcarg__" prefix is deprecated '
|
||||
'and scheduled to be removed in pytest 4.0. '
|
||||
'Please remove the prefix and use the @pytest.fixture decorator instead.'),
|
||||
'*1 passed*',
|
||||
])
|
||||
|
||||
|
||||
def test_str_args_deprecated(tmpdir, testdir):
|
||||
"""Deprecate passing strings to pytest.main(). Scheduled for removal in pytest-4.0."""
|
||||
warnings = []
|
||||
|
||||
class Collect:
|
||||
def pytest_logwarning(self, message):
|
||||
warnings.append(message)
|
||||
|
||||
ret = pytest.main("%s -x" % tmpdir, plugins=[Collect()])
|
||||
testdir.delete_loaded_modules()
|
||||
msg = ('passing a string to pytest.main() is deprecated, '
|
||||
'pass a list of arguments instead.')
|
||||
assert msg in warnings
|
||||
assert ret == EXIT_NOTESTSCOLLECTED
|
||||
|
||||
@@ -66,24 +66,6 @@ def test_code_from_func():
|
||||
assert co.path
|
||||
|
||||
|
||||
|
||||
def test_builtin_patch_unpatch(monkeypatch):
|
||||
cpy_builtin = py.builtin.builtins
|
||||
comp = cpy_builtin.compile
|
||||
def mycompile(*args, **kwargs):
|
||||
return comp(*args, **kwargs)
|
||||
class Sub(AssertionError):
|
||||
pass
|
||||
monkeypatch.setattr(cpy_builtin, 'AssertionError', Sub)
|
||||
monkeypatch.setattr(cpy_builtin, 'compile', mycompile)
|
||||
_pytest._code.patch_builtins()
|
||||
assert cpy_builtin.AssertionError != Sub
|
||||
assert cpy_builtin.compile != mycompile
|
||||
_pytest._code.unpatch_builtins()
|
||||
assert cpy_builtin.AssertionError is Sub
|
||||
assert cpy_builtin.compile == mycompile
|
||||
|
||||
|
||||
def test_unicode_handling():
|
||||
value = py.builtin._totext('\xc4\x85\xc4\x87\n', 'utf-8').encode('utf8')
|
||||
def f():
|
||||
|
||||
@@ -274,18 +274,6 @@ class TestTraceback_f_g_h:
|
||||
assert entry.lineno == co.firstlineno + 2
|
||||
assert entry.frame.code.name == 'g'
|
||||
|
||||
def hello(x):
|
||||
x + 5
|
||||
|
||||
def test_tbentry_reinterpret():
|
||||
try:
|
||||
hello("hello")
|
||||
except TypeError:
|
||||
excinfo = _pytest._code.ExceptionInfo()
|
||||
tbentry = excinfo.traceback[-1]
|
||||
msg = tbentry.reinterpret()
|
||||
assert msg.startswith("TypeError: ('hello' + 5)")
|
||||
|
||||
def test_excinfo_exconly():
|
||||
excinfo = pytest.raises(ValueError, h)
|
||||
assert excinfo.exconly().startswith('ValueError')
|
||||
@@ -381,10 +369,12 @@ def test_match_raises_error(testdir):
|
||||
])
|
||||
|
||||
class TestFormattedExcinfo:
|
||||
def pytest_funcarg__importasmod(self, request):
|
||||
|
||||
@pytest.fixture
|
||||
def importasmod(self, request):
|
||||
def importasmod(source):
|
||||
source = _pytest._code.Source(source)
|
||||
tmpdir = request.getfuncargvalue("tmpdir")
|
||||
tmpdir = request.getfixturevalue("tmpdir")
|
||||
modpath = tmpdir.join("mod.py")
|
||||
tmpdir.ensure("__init__.py")
|
||||
modpath.write(source)
|
||||
@@ -429,7 +419,7 @@ class TestFormattedExcinfo:
|
||||
assert lines == [
|
||||
' def f():',
|
||||
'> assert 0',
|
||||
'E assert 0'
|
||||
'E AssertionError'
|
||||
]
|
||||
|
||||
|
||||
@@ -768,23 +758,6 @@ raise ValueError()
|
||||
assert reprtb.extraline == "!!! Recursion detected (same locals & position)"
|
||||
assert str(reprtb)
|
||||
|
||||
def test_tb_entry_AssertionError(self, importasmod):
|
||||
# probably this test is a bit redundant
|
||||
# as py/magic/testing/test_assertion.py
|
||||
# already tests correctness of
|
||||
# assertion-reinterpretation logic
|
||||
mod = importasmod("""
|
||||
def somefunc():
|
||||
x = 1
|
||||
assert x == 2
|
||||
""")
|
||||
excinfo = pytest.raises(AssertionError, mod.somefunc)
|
||||
|
||||
p = FormattedExcinfo()
|
||||
reprentry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)
|
||||
lines = reprentry.lines
|
||||
assert lines[-1] == "E assert 1 == 2"
|
||||
|
||||
def test_reprexcinfo_getrepr(self, importasmod):
|
||||
mod = importasmod("""
|
||||
def f(x):
|
||||
@@ -933,21 +906,6 @@ raise ValueError()
|
||||
repr.toterminal(tw)
|
||||
assert tw.stringio.getvalue()
|
||||
|
||||
|
||||
def test_native_style(self):
|
||||
excinfo = self.excinfo_from_exec("""
|
||||
assert 0
|
||||
""")
|
||||
repr = excinfo.getrepr(style='native')
|
||||
assert "assert 0" in str(repr.reprcrash)
|
||||
s = str(repr)
|
||||
assert s.startswith('Traceback (most recent call last):\n File')
|
||||
assert s.endswith('\nAssertionError: assert 0')
|
||||
assert 'exec (source.compile())' in s
|
||||
# python 2.4 fails to get the source line for the assert
|
||||
if py.std.sys.version_info >= (2, 5):
|
||||
assert s.count('assert 0') == 2
|
||||
|
||||
def test_traceback_repr_style(self, importasmod):
|
||||
mod = importasmod("""
|
||||
def f():
|
||||
@@ -1077,4 +1035,4 @@ def test_cwd_deleted(testdir):
|
||||
""")
|
||||
result = testdir.runpytest()
|
||||
result.stdout.fnmatch_lines(['* 1 failed in *'])
|
||||
assert 'INTERNALERROR' not in result.stdout.str() + result.stderr.str()
|
||||
assert 'INTERNALERROR' not in result.stdout.str() + result.stderr.str()
|
||||
|
||||
@@ -285,13 +285,14 @@ class TestSourceParsingAndCompiling:
|
||||
#print "block", str(block)
|
||||
assert str(stmt).strip().startswith('assert')
|
||||
|
||||
def test_compilefuncs_and_path_sanity(self):
|
||||
@pytest.mark.parametrize('name', ['', None, 'my'])
|
||||
def test_compilefuncs_and_path_sanity(self, name):
|
||||
def check(comp, name):
|
||||
co = comp(self.source, name)
|
||||
if not name:
|
||||
expected = "codegen %s:%d>" %(mypath, mylineno+2+1)
|
||||
expected = "codegen %s:%d>" %(mypath, mylineno+2+2)
|
||||
else:
|
||||
expected = "codegen %r %s:%d>" % (name, mypath, mylineno+2+1)
|
||||
expected = "codegen %r %s:%d>" % (name, mypath, mylineno+2+2)
|
||||
fn = co.co_filename
|
||||
assert fn.endswith(expected)
|
||||
|
||||
@@ -300,8 +301,7 @@ class TestSourceParsingAndCompiling:
|
||||
mypath = mycode.path
|
||||
|
||||
for comp in _pytest._code.compile, _pytest._code.Source.compile:
|
||||
for name in '', None, 'my':
|
||||
yield check, comp, name
|
||||
check(comp, name)
|
||||
|
||||
def test_offsetless_synerr(self):
|
||||
pytest.raises(SyntaxError, _pytest._code.compile, "lambda a,a: 0", mode='eval')
|
||||
|
||||
@@ -8,7 +8,7 @@ if __name__ == '__main__':
|
||||
setup(
|
||||
name="runtests",
|
||||
version="0.1",
|
||||
description="exemple of how embedding pytest into an executable using cx_freeze",
|
||||
description="example of how embedding pytest into an executable using cx_freeze",
|
||||
executables=[Executable("runtests_script.py")],
|
||||
options={"build_exe": {'includes': pytest.freeze_includes()}},
|
||||
)
|
||||
|
||||
@@ -334,7 +334,7 @@ class TestFunction:
|
||||
reprec.assertoutcome()
|
||||
|
||||
def test_function_equality(self, testdir, tmpdir):
|
||||
from _pytest.python import FixtureManager
|
||||
from _pytest.fixtures import FixtureManager
|
||||
config = testdir.parseconfigure()
|
||||
session = testdir.Session(config)
|
||||
session._fixturemanager = FixtureManager(session)
|
||||
@@ -795,21 +795,24 @@ class TestTracebackCutting:
|
||||
|
||||
def test_traceback_argsetup(self, testdir):
|
||||
testdir.makeconftest("""
|
||||
def pytest_funcarg__hello(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def hello(request):
|
||||
raise ValueError("xyz")
|
||||
""")
|
||||
p = testdir.makepyfile("def test(hello): pass")
|
||||
result = testdir.runpytest(p)
|
||||
assert result.ret != 0
|
||||
out = result.stdout.str()
|
||||
assert out.find("xyz") != -1
|
||||
assert out.find("conftest.py:2: ValueError") != -1
|
||||
assert "xyz" in out
|
||||
assert "conftest.py:5: ValueError" in out
|
||||
numentries = out.count("_ _ _") # separator for traceback entries
|
||||
assert numentries == 0
|
||||
|
||||
result = testdir.runpytest("--fulltrace", p)
|
||||
out = result.stdout.str()
|
||||
assert out.find("conftest.py:2: ValueError") != -1
|
||||
assert "conftest.py:5: ValueError" in out
|
||||
numentries = out.count("_ _ _ _") # separator for traceback entries
|
||||
assert numentries > 3
|
||||
|
||||
|
||||
@@ -3,35 +3,37 @@ from textwrap import dedent
|
||||
import _pytest._code
|
||||
import pytest
|
||||
import sys
|
||||
from _pytest import python as funcargs
|
||||
from _pytest.pytester import get_public_names
|
||||
from _pytest.python import FixtureLookupError
|
||||
|
||||
from _pytest.fixtures import FixtureLookupError
|
||||
from _pytest import fixtures
|
||||
|
||||
def test_getfuncargnames():
|
||||
def f(): pass
|
||||
assert not funcargs.getfuncargnames(f)
|
||||
assert not fixtures.getfuncargnames(f)
|
||||
def g(arg): pass
|
||||
assert funcargs.getfuncargnames(g) == ('arg',)
|
||||
assert fixtures.getfuncargnames(g) == ('arg',)
|
||||
def h(arg1, arg2="hello"): pass
|
||||
assert funcargs.getfuncargnames(h) == ('arg1',)
|
||||
assert fixtures.getfuncargnames(h) == ('arg1',)
|
||||
def h(arg1, arg2, arg3="hello"): pass
|
||||
assert funcargs.getfuncargnames(h) == ('arg1', 'arg2')
|
||||
assert fixtures.getfuncargnames(h) == ('arg1', 'arg2')
|
||||
class A:
|
||||
def f(self, arg1, arg2="hello"):
|
||||
pass
|
||||
assert funcargs.getfuncargnames(A().f) == ('arg1',)
|
||||
assert fixtures.getfuncargnames(A().f) == ('arg1',)
|
||||
if sys.version_info < (3,0):
|
||||
assert funcargs.getfuncargnames(A.f) == ('arg1',)
|
||||
assert fixtures.getfuncargnames(A.f) == ('arg1',)
|
||||
|
||||
class TestFillFixtures:
|
||||
def test_fillfuncargs_exposed(self):
|
||||
# used by oejskit, kept for compatibility
|
||||
assert pytest._fillfuncargs == funcargs.fillfixtures
|
||||
assert pytest._fillfuncargs == fixtures.fillfixtures
|
||||
|
||||
def test_funcarg_lookupfails(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
def pytest_funcarg__xyzsomething(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def xyzsomething(request):
|
||||
return 42
|
||||
|
||||
def test_func(some):
|
||||
@@ -47,14 +49,18 @@ class TestFillFixtures:
|
||||
|
||||
def test_funcarg_basic(self, testdir):
|
||||
item = testdir.getitem("""
|
||||
def pytest_funcarg__some(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def some(request):
|
||||
return request.function.__name__
|
||||
def pytest_funcarg__other(request):
|
||||
@pytest.fixture
|
||||
def other(request):
|
||||
return 42
|
||||
def test_func(some, other):
|
||||
pass
|
||||
""")
|
||||
funcargs.fillfixtures(item)
|
||||
fixtures.fillfixtures(item)
|
||||
del item.funcargs["request"]
|
||||
assert len(get_public_names(item.funcargs)) == 2
|
||||
assert item.funcargs['some'] == "test_func"
|
||||
@@ -62,7 +68,10 @@ class TestFillFixtures:
|
||||
|
||||
def test_funcarg_lookup_modulelevel(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
def pytest_funcarg__something(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def something(request):
|
||||
return request.function.__name__
|
||||
|
||||
class TestClass:
|
||||
@@ -76,9 +85,13 @@ class TestFillFixtures:
|
||||
|
||||
def test_funcarg_lookup_classlevel(self, testdir):
|
||||
p = testdir.makepyfile("""
|
||||
import pytest
|
||||
class TestClass:
|
||||
def pytest_funcarg__something(self, request):
|
||||
|
||||
@pytest.fixture
|
||||
def something(self, request):
|
||||
return request.instance
|
||||
|
||||
def test_method(self, something):
|
||||
assert something is self
|
||||
""")
|
||||
@@ -92,13 +105,15 @@ class TestFillFixtures:
|
||||
sub2 = testdir.mkpydir("sub2")
|
||||
sub1.join("conftest.py").write(_pytest._code.Source("""
|
||||
import pytest
|
||||
def pytest_funcarg__arg1(request):
|
||||
pytest.raises(Exception, "request.getfuncargvalue('arg2')")
|
||||
@pytest.fixture
|
||||
def arg1(request):
|
||||
pytest.raises(Exception, "request.getfixturevalue('arg2')")
|
||||
"""))
|
||||
sub2.join("conftest.py").write(_pytest._code.Source("""
|
||||
import pytest
|
||||
def pytest_funcarg__arg2(request):
|
||||
pytest.raises(Exception, "request.getfuncargvalue('arg1')")
|
||||
@pytest.fixture
|
||||
def arg2(request):
|
||||
pytest.raises(Exception, "request.getfixturevalue('arg1')")
|
||||
"""))
|
||||
|
||||
sub1.join("test_in_sub1.py").write("def test_1(arg1): pass")
|
||||
@@ -397,10 +412,13 @@ class TestFillFixtures:
|
||||
class TestRequestBasic:
|
||||
def test_request_attributes(self, testdir):
|
||||
item = testdir.getitem("""
|
||||
def pytest_funcarg__something(request): pass
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def something(request): pass
|
||||
def test_func(something): pass
|
||||
""")
|
||||
req = funcargs.FixtureRequest(item)
|
||||
req = fixtures.FixtureRequest(item)
|
||||
assert req.function == item.obj
|
||||
assert req.keywords == item.keywords
|
||||
assert hasattr(req.module, 'test_func')
|
||||
@@ -411,8 +429,11 @@ class TestRequestBasic:
|
||||
|
||||
def test_request_attributes_method(self, testdir):
|
||||
item, = testdir.getitems("""
|
||||
import pytest
|
||||
class TestB:
|
||||
def pytest_funcarg__something(self, request):
|
||||
|
||||
@pytest.fixture
|
||||
def something(self, request):
|
||||
return 1
|
||||
def test_func(self, something):
|
||||
pass
|
||||
@@ -421,9 +442,11 @@ class TestRequestBasic:
|
||||
assert req.cls.__name__ == "TestB"
|
||||
assert req.instance.__class__ == req.cls
|
||||
|
||||
def XXXtest_request_contains_funcarg_arg2fixturedefs(self, testdir):
|
||||
def test_request_contains_funcarg_arg2fixturedefs(self, testdir):
|
||||
modcol = testdir.getmodulecol("""
|
||||
def pytest_funcarg__something(request):
|
||||
import pytest
|
||||
@pytest.fixture
|
||||
def something(request):
|
||||
pass
|
||||
class TestClass:
|
||||
def test_method(self, something):
|
||||
@@ -431,41 +454,53 @@ class TestRequestBasic:
|
||||
""")
|
||||
item1, = testdir.genitems([modcol])
|
||||
assert item1.name == "test_method"
|
||||
arg2fixturedefs = funcargs.FixtureRequest(item1)._arg2fixturedefs
|
||||
arg2fixturedefs = fixtures.FixtureRequest(item1)._arg2fixturedefs
|
||||
assert len(arg2fixturedefs) == 1
|
||||
assert arg2fixturedefs[0].__name__ == "pytest_funcarg__something"
|
||||
assert arg2fixturedefs['something'][0].argname == "something"
|
||||
|
||||
def test_getfuncargvalue_recursive(self, testdir):
|
||||
def test_getfixturevalue_recursive(self, testdir):
|
||||
testdir.makeconftest("""
|
||||
def pytest_funcarg__something(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def something(request):
|
||||
return 1
|
||||
""")
|
||||
testdir.makepyfile("""
|
||||
def pytest_funcarg__something(request):
|
||||
return request.getfuncargvalue("something") + 1
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def something(request):
|
||||
return request.getfixturevalue("something") + 1
|
||||
def test_func(something):
|
||||
assert something == 2
|
||||
""")
|
||||
reprec = testdir.inline_run()
|
||||
reprec.assertoutcome(passed=1)
|
||||
|
||||
def test_getfuncargvalue(self, testdir):
|
||||
@pytest.mark.parametrize(
|
||||
'getfixmethod', ('getfixturevalue', 'getfuncargvalue'))
|
||||
def test_getfixturevalue(self, testdir, getfixmethod):
|
||||
item = testdir.getitem("""
|
||||
import pytest
|
||||
l = [2]
|
||||
def pytest_funcarg__something(request): return 1
|
||||
def pytest_funcarg__other(request):
|
||||
@pytest.fixture
|
||||
def something(request): return 1
|
||||
@pytest.fixture
|
||||
def other(request):
|
||||
return l.pop()
|
||||
def test_func(something): pass
|
||||
""")
|
||||
req = item._request
|
||||
pytest.raises(FixtureLookupError, req.getfuncargvalue, "notexists")
|
||||
val = req.getfuncargvalue("something")
|
||||
fixture_fetcher = getattr(req, getfixmethod)
|
||||
pytest.raises(FixtureLookupError, fixture_fetcher, "notexists")
|
||||
val = fixture_fetcher("something")
|
||||
assert val == 1
|
||||
val = req.getfuncargvalue("something")
|
||||
val = fixture_fetcher("something")
|
||||
assert val == 1
|
||||
val2 = req.getfuncargvalue("other")
|
||||
val2 = fixture_fetcher("other")
|
||||
assert val2 == 2
|
||||
val2 = req.getfuncargvalue("other") # see about caching
|
||||
val2 = fixture_fetcher("other") # see about caching
|
||||
assert val2 == 2
|
||||
pytest._fillfuncargs(item)
|
||||
assert item.funcargs["something"] == 1
|
||||
@@ -475,8 +510,10 @@ class TestRequestBasic:
|
||||
|
||||
def test_request_addfinalizer(self, testdir):
|
||||
item = testdir.getitem("""
|
||||
import pytest
|
||||
teardownlist = []
|
||||
def pytest_funcarg__something(request):
|
||||
@pytest.fixture
|
||||
def something(request):
|
||||
request.addfinalizer(lambda: teardownlist.append(1))
|
||||
def test_func(something): pass
|
||||
""")
|
||||
@@ -501,7 +538,8 @@ class TestRequestBasic:
|
||||
result = testdir.runpytest_subprocess()
|
||||
assert result.ret != 0
|
||||
result.stdout.fnmatch_lines([
|
||||
"*AssertionError:*pytest_funcarg__marked_with_prefix_and_decorator*"
|
||||
"*AssertionError: fixtures cannot have*@pytest.fixture*",
|
||||
"*pytest_funcarg__marked_with_prefix_and_decorator*"
|
||||
])
|
||||
|
||||
def test_request_addfinalizer_failing_setup(self, testdir):
|
||||
@@ -539,8 +577,10 @@ class TestRequestBasic:
|
||||
|
||||
def test_request_addfinalizer_partial_setup_failure(self, testdir):
|
||||
p = testdir.makepyfile("""
|
||||
import pytest
|
||||
l = []
|
||||
def pytest_funcarg__something(request):
|
||||
@pytest.fixture
|
||||
def something(request):
|
||||
request.addfinalizer(lambda: l.append(None))
|
||||
def test_func(something, missingarg):
|
||||
pass
|
||||
@@ -555,7 +595,7 @@ class TestRequestBasic:
|
||||
def test_request_getmodulepath(self, testdir):
|
||||
modcol = testdir.getmodulecol("def test_somefunc(): pass")
|
||||
item, = testdir.genitems([modcol])
|
||||
req = funcargs.FixtureRequest(item)
|
||||
req = fixtures.FixtureRequest(item)
|
||||
assert req.fspath == modcol.fspath
|
||||
|
||||
def test_request_fixturenames(self, testdir):
|
||||
@@ -581,9 +621,11 @@ class TestRequestBasic:
|
||||
|
||||
def test_funcargnames_compatattr(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
import pytest
|
||||
def pytest_generate_tests(metafunc):
|
||||
assert metafunc.funcargnames == metafunc.fixturenames
|
||||
def pytest_funcarg__fn(request):
|
||||
@pytest.fixture
|
||||
def fn(request):
|
||||
assert request._pyfuncitem.funcargnames == \
|
||||
request._pyfuncitem.fixturenames
|
||||
return request.funcargnames, request.fixturenames
|
||||
@@ -628,7 +670,9 @@ class TestRequestBasic:
|
||||
# this tests that normalization of nodeids takes place
|
||||
b = testdir.mkdir("tests").mkdir("unit")
|
||||
b.join("conftest.py").write(_pytest._code.Source("""
|
||||
def pytest_funcarg__arg1():
|
||||
import pytest
|
||||
@pytest.fixture
|
||||
def arg1():
|
||||
pass
|
||||
"""))
|
||||
p = b.join("test_module.py")
|
||||
@@ -676,7 +720,10 @@ class TestRequestBasic:
|
||||
class TestRequestMarking:
|
||||
def test_applymarker(self, testdir):
|
||||
item1,item2 = testdir.getitems("""
|
||||
def pytest_funcarg__something(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def something(request):
|
||||
pass
|
||||
class TestClass:
|
||||
def test_func1(self, something):
|
||||
@@ -684,7 +731,7 @@ class TestRequestMarking:
|
||||
def test_func2(self, something):
|
||||
pass
|
||||
""")
|
||||
req1 = funcargs.FixtureRequest(item1)
|
||||
req1 = fixtures.FixtureRequest(item1)
|
||||
assert 'xfail' not in item1.keywords
|
||||
req1.applymarker(pytest.mark.xfail)
|
||||
assert 'xfail' in item1.keywords
|
||||
@@ -735,7 +782,10 @@ class TestRequestCachedSetup:
|
||||
reprec = testdir.inline_runsource("""
|
||||
mysetup = ["hello",].pop
|
||||
|
||||
def pytest_funcarg__something(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def something(request):
|
||||
return request.cached_setup(mysetup, scope="module")
|
||||
|
||||
def test_func1(something):
|
||||
@@ -750,7 +800,9 @@ class TestRequestCachedSetup:
|
||||
reprec = testdir.inline_runsource("""
|
||||
mysetup = ["hello", "hello2", "hello3"].pop
|
||||
|
||||
def pytest_funcarg__something(request):
|
||||
import pytest
|
||||
@pytest.fixture
|
||||
def something(request):
|
||||
return request.cached_setup(mysetup, scope="class")
|
||||
def test_func1(something):
|
||||
assert something == "hello3"
|
||||
@@ -766,7 +818,7 @@ class TestRequestCachedSetup:
|
||||
|
||||
def test_request_cachedsetup_extrakey(self, testdir):
|
||||
item1 = testdir.getitem("def test_func(): pass")
|
||||
req1 = funcargs.FixtureRequest(item1)
|
||||
req1 = fixtures.FixtureRequest(item1)
|
||||
l = ["hello", "world"]
|
||||
def setup():
|
||||
return l.pop()
|
||||
@@ -781,7 +833,7 @@ class TestRequestCachedSetup:
|
||||
|
||||
def test_request_cachedsetup_cache_deletion(self, testdir):
|
||||
item1 = testdir.getitem("def test_func(): pass")
|
||||
req1 = funcargs.FixtureRequest(item1)
|
||||
req1 = fixtures.FixtureRequest(item1)
|
||||
l = []
|
||||
def setup():
|
||||
l.append("setup")
|
||||
@@ -800,9 +852,13 @@ class TestRequestCachedSetup:
|
||||
|
||||
def test_request_cached_setup_two_args(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
def pytest_funcarg__arg1(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def arg1(request):
|
||||
return request.cached_setup(lambda: 42)
|
||||
def pytest_funcarg__arg2(request):
|
||||
@pytest.fixture
|
||||
def arg2(request):
|
||||
return request.cached_setup(lambda: 17)
|
||||
def test_two_different_setups(arg1, arg2):
|
||||
assert arg1 != arg2
|
||||
@@ -812,12 +868,16 @@ class TestRequestCachedSetup:
|
||||
"*1 passed*"
|
||||
])
|
||||
|
||||
def test_request_cached_setup_getfuncargvalue(self, testdir):
|
||||
def test_request_cached_setup_getfixturevalue(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
def pytest_funcarg__arg1(request):
|
||||
arg1 = request.getfuncargvalue("arg2")
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def arg1(request):
|
||||
arg1 = request.getfixturevalue("arg2")
|
||||
return request.cached_setup(lambda: arg1 + 1)
|
||||
def pytest_funcarg__arg2(request):
|
||||
@pytest.fixture
|
||||
def arg2(request):
|
||||
return request.cached_setup(lambda: 10)
|
||||
def test_two_funcarg(arg1):
|
||||
assert arg1 == 11
|
||||
@@ -829,8 +889,10 @@ class TestRequestCachedSetup:
|
||||
|
||||
def test_request_cached_setup_functional(self, testdir):
|
||||
testdir.makepyfile(test_0="""
|
||||
import pytest
|
||||
l = []
|
||||
def pytest_funcarg__something(request):
|
||||
@pytest.fixture
|
||||
def something(request):
|
||||
val = request.cached_setup(fsetup, fteardown)
|
||||
return val
|
||||
def fsetup(mycache=[1]):
|
||||
@@ -856,7 +918,10 @@ class TestRequestCachedSetup:
|
||||
|
||||
def test_issue117_sessionscopeteardown(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
def pytest_funcarg__app(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def app(request):
|
||||
app = request.cached_setup(
|
||||
scope='session',
|
||||
setup=lambda: 0,
|
||||
@@ -1117,16 +1182,23 @@ class TestFixtureUsages:
|
||||
|
||||
|
||||
class TestFixtureManagerParseFactories:
|
||||
def pytest_funcarg__testdir(self, request):
|
||||
testdir = request.getfuncargvalue("testdir")
|
||||
|
||||
@pytest.fixture
|
||||
def testdir(self, request):
|
||||
testdir = request.getfixturevalue("testdir")
|
||||
testdir.makeconftest("""
|
||||
def pytest_funcarg__hello(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def hello(request):
|
||||
return "conftest"
|
||||
|
||||
def pytest_funcarg__fm(request):
|
||||
@pytest.fixture
|
||||
def fm(request):
|
||||
return request._fixturemanager
|
||||
|
||||
def pytest_funcarg__item(request):
|
||||
@pytest.fixture
|
||||
def item(request):
|
||||
return request._pyfuncitem
|
||||
""")
|
||||
return testdir
|
||||
@@ -1152,17 +1224,21 @@ class TestFixtureManagerParseFactories:
|
||||
faclist = fm.getfixturedefs(name, item.nodeid)
|
||||
assert len(faclist) == 1
|
||||
fac = faclist[0]
|
||||
assert fac.func.__name__ == "pytest_funcarg__" + name
|
||||
assert fac.func.__name__ == name
|
||||
""")
|
||||
reprec = testdir.inline_run("-s")
|
||||
reprec.assertoutcome(passed=1)
|
||||
|
||||
def test_parsefactories_conftest_and_module_and_class(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
def pytest_funcarg__hello(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def hello(request):
|
||||
return "module"
|
||||
class TestClass:
|
||||
def pytest_funcarg__hello(self, request):
|
||||
@pytest.fixture
|
||||
def hello(self, request):
|
||||
return "class"
|
||||
def test_hello(self, item, fm):
|
||||
faclist = fm.getfixturedefs("hello", item.nodeid)
|
||||
@@ -1210,7 +1286,9 @@ class TestFixtureManagerParseFactories:
|
||||
|
||||
|
||||
class TestAutouseDiscovery:
|
||||
def pytest_funcarg__testdir(self, testdir):
|
||||
|
||||
@pytest.fixture
|
||||
def testdir(self, testdir):
|
||||
testdir.makeconftest("""
|
||||
import pytest
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -1224,10 +1302,12 @@ class TestAutouseDiscovery:
|
||||
def perfunction2(arg1):
|
||||
pass
|
||||
|
||||
def pytest_funcarg__fm(request):
|
||||
@pytest.fixture
|
||||
def fm(request):
|
||||
return request._fixturemanager
|
||||
|
||||
def pytest_funcarg__item(request):
|
||||
@pytest.fixture
|
||||
def item(request):
|
||||
return request._pyfuncitem
|
||||
""")
|
||||
return testdir
|
||||
@@ -1506,7 +1586,8 @@ class TestAutouseManagement:
|
||||
def test_2(self):
|
||||
pass
|
||||
""")
|
||||
reprec = testdir.inline_run("-v","-s")
|
||||
confcut = "--confcutdir={0}".format(testdir.tmpdir)
|
||||
reprec = testdir.inline_run("-v","-s", confcut)
|
||||
reprec.assertoutcome(passed=8)
|
||||
config = reprec.getcalls("pytest_unconfigure")[0].config
|
||||
l = config.pluginmanager._getconftestmodules(p)[0].l
|
||||
@@ -1771,17 +1852,19 @@ class TestFixtureMarker:
|
||||
def test_scope_module_and_finalizer(self, testdir):
|
||||
testdir.makeconftest("""
|
||||
import pytest
|
||||
finalized = []
|
||||
created = []
|
||||
finalized_list = []
|
||||
created_list = []
|
||||
@pytest.fixture(scope="module")
|
||||
def arg(request):
|
||||
created.append(1)
|
||||
created_list.append(1)
|
||||
assert request.scope == "module"
|
||||
request.addfinalizer(lambda: finalized.append(1))
|
||||
def pytest_funcarg__created(request):
|
||||
return len(created)
|
||||
def pytest_funcarg__finalized(request):
|
||||
return len(finalized)
|
||||
request.addfinalizer(lambda: finalized_list.append(1))
|
||||
@pytest.fixture
|
||||
def created(request):
|
||||
return len(created_list)
|
||||
@pytest.fixture
|
||||
def finalized(request):
|
||||
return len(finalized_list)
|
||||
""")
|
||||
testdir.makepyfile(
|
||||
test_mod1="""
|
||||
@@ -1804,9 +1887,9 @@ class TestFixtureMarker:
|
||||
reprec.assertoutcome(passed=4)
|
||||
|
||||
@pytest.mark.parametrize("method", [
|
||||
'request.getfuncargvalue("arg")',
|
||||
'request.getfixturevalue("arg")',
|
||||
'request.cached_setup(lambda: None, scope="function")',
|
||||
], ids=["getfuncargvalue", "cached_setup"])
|
||||
], ids=["getfixturevalue", "cached_setup"])
|
||||
def test_scope_mismatch_various(self, testdir, method):
|
||||
testdir.makeconftest("""
|
||||
import pytest
|
||||
@@ -2718,6 +2801,7 @@ class TestContextManagerFixtureFuncs:
|
||||
""".format(flavor=flavor))
|
||||
result = testdir.runpytest("-s")
|
||||
result.stdout.fnmatch_lines("*mew*")
|
||||
|
||||
class TestParameterizedSubRequest:
|
||||
def test_call_from_fixture(self, testdir):
|
||||
testfile = testdir.makepyfile("""
|
||||
@@ -2729,7 +2813,7 @@ class TestParameterizedSubRequest:
|
||||
|
||||
@pytest.fixture
|
||||
def get_named_fixture(request):
|
||||
return request.getfuncargvalue('fix_with_param')
|
||||
return request.getfixturevalue('fix_with_param')
|
||||
|
||||
def test_foo(request, get_named_fixture):
|
||||
pass
|
||||
@@ -2754,7 +2838,7 @@ class TestParameterizedSubRequest:
|
||||
return request.param
|
||||
|
||||
def test_foo(request):
|
||||
request.getfuncargvalue('fix_with_param')
|
||||
request.getfixturevalue('fix_with_param')
|
||||
""")
|
||||
result = testdir.runpytest()
|
||||
result.stdout.fnmatch_lines("""
|
||||
@@ -2778,7 +2862,7 @@ class TestParameterizedSubRequest:
|
||||
|
||||
testfile = testdir.makepyfile("""
|
||||
def test_foo(request):
|
||||
request.getfuncargvalue('fix_with_param')
|
||||
request.getfixturevalue('fix_with_param')
|
||||
""")
|
||||
result = testdir.runpytest()
|
||||
result.stdout.fnmatch_lines("""
|
||||
@@ -2808,7 +2892,7 @@ class TestParameterizedSubRequest:
|
||||
from fix import fix_with_param
|
||||
|
||||
def test_foo(request):
|
||||
request.getfuncargvalue('fix_with_param')
|
||||
request.getfixturevalue('fix_with_param')
|
||||
"""))
|
||||
|
||||
tests_dir.chdir()
|
||||
@@ -2823,3 +2907,7 @@ class TestParameterizedSubRequest:
|
||||
E*{1}:5
|
||||
*1 failed*
|
||||
""".format(fixfile.strpath, testfile.basename))
|
||||
|
||||
|
||||
def test_getfuncargvalue_is_deprecated(request):
|
||||
pytest.deprecated_call(request.getfuncargvalue, 'tmpdir')
|
||||
|
||||
@@ -15,7 +15,9 @@ class TestOEJSKITSpecials:
|
||||
return self.fspath, 3, "xyz"
|
||||
""")
|
||||
modcol = testdir.getmodulecol("""
|
||||
def pytest_funcarg__arg1(request):
|
||||
import pytest
|
||||
@pytest.fixture
|
||||
def arg1(request):
|
||||
return 42
|
||||
class MyClass:
|
||||
pass
|
||||
@@ -43,7 +45,8 @@ class TestOEJSKITSpecials:
|
||||
@pytest.fixture(autouse=True)
|
||||
def hello():
|
||||
pass
|
||||
def pytest_funcarg__arg1(request):
|
||||
@pytest.fixture
|
||||
def arg1(request):
|
||||
return 42
|
||||
class MyClass:
|
||||
pass
|
||||
@@ -73,7 +76,7 @@ def test_wrapped_getfslineno():
|
||||
|
||||
class TestMockDecoration:
|
||||
def test_wrapped_getfuncargnames(self):
|
||||
from _pytest.python import getfuncargnames
|
||||
from _pytest.compat import getfuncargnames
|
||||
def wrap(f):
|
||||
def func():
|
||||
pass
|
||||
@@ -86,7 +89,7 @@ class TestMockDecoration:
|
||||
assert l == ("x",)
|
||||
|
||||
def test_wrapped_getfuncargnames_patching(self):
|
||||
from _pytest.python import getfuncargnames
|
||||
from _pytest.compat import getfuncargnames
|
||||
def wrap(f):
|
||||
def func():
|
||||
pass
|
||||
@@ -234,7 +237,7 @@ class TestReRunTests:
|
||||
""")
|
||||
|
||||
def test_pytestconfig_is_session_scoped():
|
||||
from _pytest.python import pytestconfig
|
||||
from _pytest.fixtures import pytestconfig
|
||||
assert pytestconfig._pytestfixturefunction.scope == "session"
|
||||
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import sys
|
||||
import _pytest._code
|
||||
import py
|
||||
import pytest
|
||||
from _pytest import python as funcargs
|
||||
from _pytest import python, fixtures
|
||||
|
||||
import hypothesis
|
||||
from hypothesis import strategies
|
||||
@@ -22,9 +22,9 @@ class TestMetafunc:
|
||||
name2fixturedefs = None
|
||||
def __init__(self, names):
|
||||
self.names_closure = names
|
||||
names = funcargs.getfuncargnames(func)
|
||||
names = fixtures.getfuncargnames(func)
|
||||
fixtureinfo = FixtureInfo(names)
|
||||
return funcargs.Metafunc(func, fixtureinfo, None)
|
||||
return python.Metafunc(func, fixtureinfo, None)
|
||||
|
||||
def test_no_funcargs(self, testdir):
|
||||
def function(): pass
|
||||
@@ -448,13 +448,13 @@ class TestMetafunc:
|
||||
|
||||
def test_parametrize_functional(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
import pytest
|
||||
def pytest_generate_tests(metafunc):
|
||||
metafunc.parametrize('x', [1,2], indirect=True)
|
||||
metafunc.parametrize('y', [2])
|
||||
def pytest_funcarg__x(request):
|
||||
@pytest.fixture
|
||||
def x(request):
|
||||
return request.param * 10
|
||||
#def pytest_funcarg__y(request):
|
||||
# return request.param
|
||||
|
||||
def test_simple(x,y):
|
||||
assert x in (10,20)
|
||||
@@ -558,16 +558,16 @@ class TestMetafunc:
|
||||
|
||||
def test_format_args(self):
|
||||
def function1(): pass
|
||||
assert funcargs._format_args(function1) == '()'
|
||||
assert fixtures._format_args(function1) == '()'
|
||||
|
||||
def function2(arg1): pass
|
||||
assert funcargs._format_args(function2) == "(arg1)"
|
||||
assert fixtures._format_args(function2) == "(arg1)"
|
||||
|
||||
def function3(arg1, arg2="qwe"): pass
|
||||
assert funcargs._format_args(function3) == "(arg1, arg2='qwe')"
|
||||
assert fixtures._format_args(function3) == "(arg1, arg2='qwe')"
|
||||
|
||||
def function4(arg1, *args, **kwargs): pass
|
||||
assert funcargs._format_args(function4) == "(arg1, *args, **kwargs)"
|
||||
assert fixtures._format_args(function4) == "(arg1, *args, **kwargs)"
|
||||
|
||||
|
||||
class TestMetafuncFunctional:
|
||||
@@ -578,7 +578,8 @@ class TestMetafuncFunctional:
|
||||
def pytest_generate_tests(metafunc):
|
||||
metafunc.addcall(param=metafunc)
|
||||
|
||||
def pytest_funcarg__metafunc(request):
|
||||
@pytest.fixture
|
||||
def metafunc(request):
|
||||
assert request._pyfuncitem._genid == "0"
|
||||
return request.param
|
||||
|
||||
@@ -630,7 +631,9 @@ class TestMetafuncFunctional:
|
||||
metafunc.addcall(param=10)
|
||||
metafunc.addcall(param=20)
|
||||
|
||||
def pytest_funcarg__arg1(request):
|
||||
import pytest
|
||||
@pytest.fixture
|
||||
def arg1(request):
|
||||
return request.param
|
||||
|
||||
def test_func1(arg1):
|
||||
@@ -669,9 +672,12 @@ class TestMetafuncFunctional:
|
||||
def pytest_generate_tests(metafunc):
|
||||
metafunc.addcall(param=(1,1), id="hello")
|
||||
|
||||
def pytest_funcarg__arg1(request):
|
||||
import pytest
|
||||
@pytest.fixture
|
||||
def arg1(request):
|
||||
return request.param[0]
|
||||
def pytest_funcarg__arg2(request):
|
||||
@pytest.fixture
|
||||
def arg2(request):
|
||||
return request.param[1]
|
||||
|
||||
class TestClass:
|
||||
@@ -749,17 +755,20 @@ class TestMetafuncFunctional:
|
||||
"*4 failed*",
|
||||
])
|
||||
|
||||
def test_parametrize_and_inner_getfuncargvalue(self, testdir):
|
||||
def test_parametrize_and_inner_getfixturevalue(self, testdir):
|
||||
p = testdir.makepyfile("""
|
||||
def pytest_generate_tests(metafunc):
|
||||
metafunc.parametrize("arg1", [1], indirect=True)
|
||||
metafunc.parametrize("arg2", [10], indirect=True)
|
||||
|
||||
def pytest_funcarg__arg1(request):
|
||||
x = request.getfuncargvalue("arg2")
|
||||
import pytest
|
||||
@pytest.fixture
|
||||
def arg1(request):
|
||||
x = request.getfixturevalue("arg2")
|
||||
return x + request.param
|
||||
|
||||
def pytest_funcarg__arg2(request):
|
||||
@pytest.fixture
|
||||
def arg2(request):
|
||||
return request.param
|
||||
|
||||
def test_func1(arg1, arg2):
|
||||
@@ -777,10 +786,13 @@ class TestMetafuncFunctional:
|
||||
assert "arg1" in metafunc.fixturenames
|
||||
metafunc.parametrize("arg1", [1], indirect=True)
|
||||
|
||||
def pytest_funcarg__arg1(request):
|
||||
import pytest
|
||||
@pytest.fixture
|
||||
def arg1(request):
|
||||
return request.param
|
||||
|
||||
def pytest_funcarg__arg2(request, arg1):
|
||||
@pytest.fixture
|
||||
def arg2(request, arg1):
|
||||
return 10 * arg1
|
||||
|
||||
def test_func(arg2):
|
||||
@@ -870,7 +882,8 @@ class TestMetafuncFunctional:
|
||||
if "arg" in metafunc.funcargnames:
|
||||
metafunc.parametrize("arg", [1,2], indirect=True,
|
||||
scope=%r)
|
||||
def pytest_funcarg__arg(request):
|
||||
@pytest.fixture
|
||||
def arg(request):
|
||||
l.append(request.param)
|
||||
return request.param
|
||||
def test_hello(arg):
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(params=['--setup-only', '--setup-plan'], scope='module')
|
||||
@pytest.fixture(params=['--setup-only', '--setup-plan', '--setup-show'],
|
||||
scope='module')
|
||||
def mode(request):
|
||||
return request.param
|
||||
|
||||
@@ -24,7 +25,7 @@ def test_show_only_active_fixtures(testdir, mode):
|
||||
|
||||
result.stdout.fnmatch_lines([
|
||||
'*SETUP F arg1*',
|
||||
'*test_arg1 (fixtures used: arg1)',
|
||||
'*test_arg1 (fixtures used: arg1)*',
|
||||
'*TEARDOWN F arg1*',
|
||||
])
|
||||
assert "_arg0" not in result.stdout.str()
|
||||
@@ -49,7 +50,7 @@ def test_show_different_scopes(testdir, mode):
|
||||
result.stdout.fnmatch_lines([
|
||||
'SETUP S arg_session*',
|
||||
'*SETUP F arg_function*',
|
||||
'*test_arg1 (fixtures used: arg_function, arg_session)',
|
||||
'*test_arg1 (fixtures used: arg_function, arg_session)*',
|
||||
'*TEARDOWN F arg_function*',
|
||||
'TEARDOWN S arg_session*',
|
||||
])
|
||||
@@ -77,7 +78,7 @@ def test_show_nested_fixtures(testdir, mode):
|
||||
result.stdout.fnmatch_lines([
|
||||
'SETUP S arg_same*',
|
||||
'*SETUP F arg_same (fixtures used: arg_same)*',
|
||||
'*test_arg1 (fixtures used: arg_same)',
|
||||
'*test_arg1 (fixtures used: arg_same)*',
|
||||
'*TEARDOWN F arg_same*',
|
||||
'TEARDOWN S arg_same*',
|
||||
])
|
||||
@@ -102,7 +103,7 @@ def test_show_fixtures_with_autouse(testdir, mode):
|
||||
result.stdout.fnmatch_lines([
|
||||
'SETUP S arg_session*',
|
||||
'*SETUP F arg_function*',
|
||||
'*test_arg1 (fixtures used: arg_function, arg_session)',
|
||||
'*test_arg1 (fixtures used: arg_function, arg_session)*',
|
||||
])
|
||||
|
||||
|
||||
@@ -219,3 +220,24 @@ def test_capturing(testdir):
|
||||
'this should be captured',
|
||||
'this should also be captured'
|
||||
])
|
||||
|
||||
|
||||
def test_show_fixtures_and_execute_test(testdir):
|
||||
""" Verifies that setups are shown and tests are executed. """
|
||||
p = testdir.makepyfile('''
|
||||
import pytest
|
||||
@pytest.fixture
|
||||
def arg():
|
||||
assert True
|
||||
def test_arg(arg):
|
||||
assert False
|
||||
''')
|
||||
|
||||
result = testdir.runpytest("--setup-show", p)
|
||||
assert result.ret == 1
|
||||
|
||||
result.stdout.fnmatch_lines([
|
||||
'*SETUP F arg*',
|
||||
'*test_arg (fixtures used: arg)F',
|
||||
'*TEARDOWN F arg*',
|
||||
])
|
||||
|
||||
@@ -1,274 +0,0 @@
|
||||
"PYTEST_DONT_REWRITE"
|
||||
import py
|
||||
import pytest
|
||||
from _pytest.assertion import util
|
||||
|
||||
|
||||
def exvalue():
|
||||
return py.std.sys.exc_info()[1]
|
||||
|
||||
def f():
|
||||
return 2
|
||||
|
||||
def test_not_being_rewritten():
|
||||
assert "@py_builtins" not in globals()
|
||||
|
||||
def test_assert():
|
||||
try:
|
||||
assert f() == 3
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
s = str(e)
|
||||
assert s.startswith('assert 2 == 3\n')
|
||||
|
||||
def test_assert_with_explicit_message():
|
||||
try:
|
||||
assert f() == 3, "hello"
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
assert e.msg == 'hello'
|
||||
|
||||
def test_assert_within_finally():
|
||||
excinfo = pytest.raises(ZeroDivisionError, """
|
||||
try:
|
||||
1/0
|
||||
finally:
|
||||
i = 42
|
||||
""")
|
||||
s = excinfo.exconly()
|
||||
assert py.std.re.search("division.+by zero", s) is not None
|
||||
|
||||
#def g():
|
||||
# A.f()
|
||||
#excinfo = getexcinfo(TypeError, g)
|
||||
#msg = getmsg(excinfo)
|
||||
#assert msg.find("must be called with A") != -1
|
||||
|
||||
|
||||
def test_assert_multiline_1():
|
||||
try:
|
||||
assert (f() ==
|
||||
3)
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
s = str(e)
|
||||
assert s.startswith('assert 2 == 3\n')
|
||||
|
||||
def test_assert_multiline_2():
|
||||
try:
|
||||
assert (f() == (4,
|
||||
3)[-1])
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
s = str(e)
|
||||
assert s.startswith('assert 2 ==')
|
||||
|
||||
def test_in():
|
||||
try:
|
||||
assert "hi" in [1, 2]
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
s = str(e)
|
||||
assert s.startswith("assert 'hi' in")
|
||||
|
||||
def test_is():
|
||||
try:
|
||||
assert 1 is 2
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
s = str(e)
|
||||
assert s.startswith("assert 1 is 2")
|
||||
|
||||
|
||||
def test_attrib():
|
||||
class Foo(object):
|
||||
b = 1
|
||||
i = Foo()
|
||||
try:
|
||||
assert i.b == 2
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
s = str(e)
|
||||
assert s.startswith("assert 1 == 2")
|
||||
|
||||
def test_attrib_inst():
|
||||
class Foo(object):
|
||||
b = 1
|
||||
try:
|
||||
assert Foo().b == 2
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
s = str(e)
|
||||
assert s.startswith("assert 1 == 2")
|
||||
|
||||
def test_len():
|
||||
l = list(range(42))
|
||||
try:
|
||||
assert len(l) == 100
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
s = str(e)
|
||||
assert s.startswith("assert 42 == 100")
|
||||
assert "where 42 = len([" in s
|
||||
|
||||
def test_assert_non_string_message():
|
||||
class A:
|
||||
def __str__(self):
|
||||
return "hello"
|
||||
try:
|
||||
assert 0 == 1, A()
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
assert e.msg == "hello"
|
||||
|
||||
def test_assert_keyword_arg():
|
||||
def f(x=3):
|
||||
return False
|
||||
try:
|
||||
assert f(x=5)
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
assert "x=5" in e.msg
|
||||
|
||||
def test_private_class_variable():
|
||||
class X:
|
||||
def __init__(self):
|
||||
self.__v = 41
|
||||
def m(self):
|
||||
assert self.__v == 42
|
||||
try:
|
||||
X().m()
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
assert "== 42" in e.msg
|
||||
|
||||
# These tests should both fail, but should fail nicely...
|
||||
class WeirdRepr:
|
||||
def __repr__(self):
|
||||
return '<WeirdRepr\nsecond line>'
|
||||
|
||||
def bug_test_assert_repr():
|
||||
v = WeirdRepr()
|
||||
try:
|
||||
assert v == 1
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
assert e.msg.find('WeirdRepr') != -1
|
||||
assert e.msg.find('second line') != -1
|
||||
assert 0
|
||||
|
||||
def test_assert_non_string():
|
||||
try:
|
||||
assert 0, ['list']
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
assert e.msg.find("list") != -1
|
||||
|
||||
def test_assert_implicit_multiline():
|
||||
try:
|
||||
x = [1,2,3]
|
||||
assert x != [1,
|
||||
2, 3]
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
assert e.msg.find('assert [1, 2, 3] !=') != -1
|
||||
|
||||
|
||||
def test_assert_with_brokenrepr_arg():
|
||||
class BrokenRepr:
|
||||
def __repr__(self): 0 / 0
|
||||
e = AssertionError(BrokenRepr())
|
||||
if e.msg.find("broken __repr__") == -1:
|
||||
pytest.fail("broken __repr__ not handle correctly")
|
||||
|
||||
def test_multiple_statements_per_line():
|
||||
try:
|
||||
a = 1; assert a == 2
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
assert "assert 1 == 2" in e.msg
|
||||
|
||||
def test_power():
|
||||
try:
|
||||
assert 2**3 == 7
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
assert "assert (2 ** 3) == 7" in e.msg
|
||||
|
||||
|
||||
def test_assert_customizable_reprcompare(monkeypatch):
|
||||
monkeypatch.setattr(util, '_reprcompare', lambda *args: 'hello')
|
||||
try:
|
||||
assert 3 == 4
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
s = str(e)
|
||||
assert "hello" in s
|
||||
|
||||
def test_assert_long_source_1():
|
||||
try:
|
||||
assert len == [
|
||||
(None, ['somet text', 'more text']),
|
||||
]
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
s = str(e)
|
||||
assert 're-run' not in s
|
||||
assert 'somet text' in s
|
||||
|
||||
def test_assert_long_source_2():
|
||||
try:
|
||||
assert(len == [
|
||||
(None, ['somet text', 'more text']),
|
||||
])
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
s = str(e)
|
||||
assert 're-run' not in s
|
||||
assert 'somet text' in s
|
||||
|
||||
def test_assert_raise_alias(testdir):
|
||||
testdir.makepyfile("""
|
||||
"PYTEST_DONT_REWRITE"
|
||||
import sys
|
||||
EX = AssertionError
|
||||
def test_hello():
|
||||
raise EX("hello"
|
||||
"multi"
|
||||
"line")
|
||||
""")
|
||||
result = testdir.runpytest()
|
||||
result.stdout.fnmatch_lines([
|
||||
"*def test_hello*",
|
||||
"*raise EX*",
|
||||
"*1 failed*",
|
||||
])
|
||||
|
||||
|
||||
def test_assert_raise_subclass():
|
||||
class SomeEx(AssertionError):
|
||||
def __init__(self, *args):
|
||||
super(SomeEx, self).__init__()
|
||||
try:
|
||||
raise SomeEx("hello")
|
||||
except AssertionError:
|
||||
s = str(exvalue())
|
||||
assert 're-run' not in s
|
||||
assert 'could not determine' in s
|
||||
|
||||
def test_assert_raises_in_nonzero_of_object_pytest_issue10():
|
||||
class A(object):
|
||||
def __nonzero__(self):
|
||||
raise ValueError(42)
|
||||
def __lt__(self, other):
|
||||
return A()
|
||||
def __repr__(self):
|
||||
return "<MY42 object>"
|
||||
def myany(x):
|
||||
return True
|
||||
try:
|
||||
assert not(myany(A() < 0))
|
||||
except AssertionError:
|
||||
e = exvalue()
|
||||
s = str(e)
|
||||
assert "<MY42 object> < 0" in s
|
||||
@@ -3,10 +3,8 @@ import sys
|
||||
import textwrap
|
||||
|
||||
import _pytest.assertion as plugin
|
||||
import _pytest._code
|
||||
import py
|
||||
import pytest
|
||||
from _pytest.assertion import reinterpret
|
||||
from _pytest.assertion import util
|
||||
|
||||
PY3 = sys.version_info >= (3, 0)
|
||||
@@ -23,24 +21,200 @@ def mock_config():
|
||||
return Config()
|
||||
|
||||
|
||||
def interpret(expr):
|
||||
return reinterpret.reinterpret(expr, _pytest._code.Frame(sys._getframe(1)))
|
||||
class TestImportHookInstallation:
|
||||
|
||||
@pytest.mark.parametrize('initial_conftest', [True, False])
|
||||
@pytest.mark.parametrize('mode', ['plain', 'rewrite'])
|
||||
def test_conftest_assertion_rewrite(self, testdir, initial_conftest, mode):
|
||||
"""Test that conftest files are using assertion rewrite on import.
|
||||
(#1619)
|
||||
"""
|
||||
testdir.tmpdir.join('foo/tests').ensure(dir=1)
|
||||
conftest_path = 'conftest.py' if initial_conftest else 'foo/conftest.py'
|
||||
contents = {
|
||||
conftest_path: """
|
||||
import pytest
|
||||
@pytest.fixture
|
||||
def check_first():
|
||||
def check(values, value):
|
||||
assert values.pop(0) == value
|
||||
return check
|
||||
""",
|
||||
'foo/tests/test_foo.py': """
|
||||
def test(check_first):
|
||||
check_first([10, 30], 30)
|
||||
"""
|
||||
}
|
||||
testdir.makepyfile(**contents)
|
||||
result = testdir.runpytest_subprocess('--assert=%s' % mode)
|
||||
if mode == 'plain':
|
||||
expected = 'E AssertionError'
|
||||
elif mode == 'rewrite':
|
||||
expected = '*assert 10 == 30*'
|
||||
else:
|
||||
assert 0
|
||||
result.stdout.fnmatch_lines([expected])
|
||||
|
||||
@pytest.mark.parametrize('mode', ['plain', 'rewrite'])
|
||||
def test_pytest_plugins_rewrite(self, testdir, mode):
|
||||
contents = {
|
||||
'conftest.py': """
|
||||
pytest_plugins = ['ham']
|
||||
""",
|
||||
'ham.py': """
|
||||
import pytest
|
||||
@pytest.fixture
|
||||
def check_first():
|
||||
def check(values, value):
|
||||
assert values.pop(0) == value
|
||||
return check
|
||||
""",
|
||||
'test_foo.py': """
|
||||
def test_foo(check_first):
|
||||
check_first([10, 30], 30)
|
||||
""",
|
||||
}
|
||||
testdir.makepyfile(**contents)
|
||||
result = testdir.runpytest_subprocess('--assert=%s' % mode)
|
||||
if mode == 'plain':
|
||||
expected = 'E AssertionError'
|
||||
elif mode == 'rewrite':
|
||||
expected = '*assert 10 == 30*'
|
||||
else:
|
||||
assert 0
|
||||
result.stdout.fnmatch_lines([expected])
|
||||
|
||||
@pytest.mark.parametrize('mode', ['plain', 'rewrite'])
|
||||
def test_installed_plugin_rewrite(self, testdir, mode):
|
||||
# Make sure the hook is installed early enough so that plugins
|
||||
# installed via setuptools are re-written.
|
||||
testdir.tmpdir.join('hampkg').ensure(dir=1)
|
||||
contents = {
|
||||
'hampkg/__init__.py': """
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def check_first2():
|
||||
def check(values, value):
|
||||
assert values.pop(0) == value
|
||||
return check
|
||||
""",
|
||||
'spamplugin.py': """
|
||||
import pytest
|
||||
from hampkg import check_first2
|
||||
|
||||
@pytest.fixture
|
||||
def check_first():
|
||||
def check(values, value):
|
||||
assert values.pop(0) == value
|
||||
return check
|
||||
""",
|
||||
'mainwrapper.py': """
|
||||
import pytest, pkg_resources
|
||||
|
||||
class DummyDistInfo:
|
||||
project_name = 'spam'
|
||||
version = '1.0'
|
||||
|
||||
def _get_metadata(self, name):
|
||||
return ['spamplugin.py,sha256=abc,123',
|
||||
'hampkg/__init__.py,sha256=abc,123']
|
||||
|
||||
class DummyEntryPoint:
|
||||
name = 'spam'
|
||||
module_name = 'spam.py'
|
||||
attrs = ()
|
||||
extras = None
|
||||
dist = DummyDistInfo()
|
||||
|
||||
def load(self, require=True, *args, **kwargs):
|
||||
import spamplugin
|
||||
return spamplugin
|
||||
|
||||
def iter_entry_points(name):
|
||||
yield DummyEntryPoint()
|
||||
|
||||
pkg_resources.iter_entry_points = iter_entry_points
|
||||
pytest.main()
|
||||
""",
|
||||
'test_foo.py': """
|
||||
def test(check_first):
|
||||
check_first([10, 30], 30)
|
||||
|
||||
def test2(check_first2):
|
||||
check_first([10, 30], 30)
|
||||
""",
|
||||
}
|
||||
testdir.makepyfile(**contents)
|
||||
result = testdir.run(sys.executable, 'mainwrapper.py', '-s', '--assert=%s' % mode)
|
||||
if mode == 'plain':
|
||||
expected = 'E AssertionError'
|
||||
elif mode == 'rewrite':
|
||||
expected = '*assert 10 == 30*'
|
||||
else:
|
||||
assert 0
|
||||
result.stdout.fnmatch_lines([expected])
|
||||
|
||||
def test_rewrite_ast(self, testdir):
|
||||
testdir.tmpdir.join('pkg').ensure(dir=1)
|
||||
contents = {
|
||||
'pkg/__init__.py': """
|
||||
import pytest
|
||||
pytest.register_assert_rewrite('pkg.helper')
|
||||
""",
|
||||
'pkg/helper.py': """
|
||||
def tool():
|
||||
a, b = 2, 3
|
||||
assert a == b
|
||||
""",
|
||||
'pkg/plugin.py': """
|
||||
import pytest, pkg.helper
|
||||
@pytest.fixture
|
||||
def tool():
|
||||
return pkg.helper.tool
|
||||
""",
|
||||
'pkg/other.py': """
|
||||
l = [3, 2]
|
||||
def tool():
|
||||
assert l.pop() == 3
|
||||
""",
|
||||
'conftest.py': """
|
||||
pytest_plugins = ['pkg.plugin']
|
||||
""",
|
||||
'test_pkg.py': """
|
||||
import pkg.other
|
||||
def test_tool(tool):
|
||||
tool()
|
||||
def test_other():
|
||||
pkg.other.tool()
|
||||
""",
|
||||
}
|
||||
testdir.makepyfile(**contents)
|
||||
result = testdir.runpytest_subprocess('--assert=rewrite')
|
||||
result.stdout.fnmatch_lines(['>*assert a == b*',
|
||||
'E*assert 2 == 3*',
|
||||
'>*assert l.pop() == 3*',
|
||||
'E*AssertionError'])
|
||||
|
||||
|
||||
class TestBinReprIntegration:
|
||||
|
||||
def test_pytest_assertrepr_compare_called(self, testdir):
|
||||
testdir.makeconftest("""
|
||||
import pytest
|
||||
l = []
|
||||
def pytest_assertrepr_compare(op, left, right):
|
||||
l.append((op, left, right))
|
||||
def pytest_funcarg__l(request):
|
||||
|
||||
@pytest.fixture
|
||||
def list(request):
|
||||
return l
|
||||
""")
|
||||
testdir.makepyfile("""
|
||||
def test_hello():
|
||||
assert 0 == 1
|
||||
def test_check(l):
|
||||
assert l == [("==", 0, 1)]
|
||||
def test_check(list):
|
||||
assert list == [("==", 0, 1)]
|
||||
""")
|
||||
result = testdir.runpytest("-v")
|
||||
result.stdout.fnmatch_lines([
|
||||
@@ -477,14 +651,6 @@ def test_assertion_options(testdir):
|
||||
result = testdir.runpytest_subprocess("--assert=plain")
|
||||
assert "3 == 4" not in result.stdout.str()
|
||||
|
||||
def test_old_assert_mode(testdir):
|
||||
testdir.makepyfile("""
|
||||
def test_in_old_mode():
|
||||
assert "@py_builtins" not in globals()
|
||||
""")
|
||||
result = testdir.runpytest_subprocess("--assert=reinterp")
|
||||
assert result.ret == 0
|
||||
|
||||
def test_triple_quoted_string_issue113(testdir):
|
||||
testdir.makepyfile("""
|
||||
def test_hello():
|
||||
|
||||
@@ -12,7 +12,7 @@ if sys.platform.startswith("java"):
|
||||
|
||||
import _pytest._code
|
||||
from _pytest.assertion import util
|
||||
from _pytest.assertion.rewrite import rewrite_asserts, PYTEST_TAG
|
||||
from _pytest.assertion.rewrite import rewrite_asserts, PYTEST_TAG, AssertionRewritingHook
|
||||
from _pytest.main import EXIT_NOTESTSCOLLECTED
|
||||
|
||||
|
||||
@@ -213,10 +213,12 @@ class TestAssertionRewrite:
|
||||
return False
|
||||
def f():
|
||||
assert x() and x()
|
||||
assert getmsg(f, {"x" : x}) == "assert (x())"
|
||||
assert getmsg(f, {"x" : x}) == """assert (False)
|
||||
+ where False = x()"""
|
||||
def f():
|
||||
assert False or x()
|
||||
assert getmsg(f, {"x" : x}) == "assert (False or x())"
|
||||
assert getmsg(f, {"x" : x}) == """assert (False or False)
|
||||
+ where False = x()"""
|
||||
def f():
|
||||
assert 1 in {} and 2 in {}
|
||||
assert getmsg(f) == "assert (1 in {})"
|
||||
@@ -299,27 +301,34 @@ class TestAssertionRewrite:
|
||||
ns = {"g" : g}
|
||||
def f():
|
||||
assert g()
|
||||
assert getmsg(f, ns) == """assert g()"""
|
||||
assert getmsg(f, ns) == """assert False
|
||||
+ where False = g()"""
|
||||
def f():
|
||||
assert g(1)
|
||||
assert getmsg(f, ns) == """assert g(1)"""
|
||||
assert getmsg(f, ns) == """assert False
|
||||
+ where False = g(1)"""
|
||||
def f():
|
||||
assert g(1, 2)
|
||||
assert getmsg(f, ns) == """assert g(1, 2)"""
|
||||
assert getmsg(f, ns) == """assert False
|
||||
+ where False = g(1, 2)"""
|
||||
def f():
|
||||
assert g(1, g=42)
|
||||
assert getmsg(f, ns) == """assert g(1, g=42)"""
|
||||
assert getmsg(f, ns) == """assert False
|
||||
+ where False = g(1, g=42)"""
|
||||
def f():
|
||||
assert g(1, 3, g=23)
|
||||
assert getmsg(f, ns) == """assert g(1, 3, g=23)"""
|
||||
assert getmsg(f, ns) == """assert False
|
||||
+ where False = g(1, 3, g=23)"""
|
||||
def f():
|
||||
seq = [1, 2, 3]
|
||||
assert g(*seq)
|
||||
assert getmsg(f, ns) == """assert g(*[1, 2, 3])"""
|
||||
assert getmsg(f, ns) == """assert False
|
||||
+ where False = g(*[1, 2, 3])"""
|
||||
def f():
|
||||
x = "a"
|
||||
assert g(**{x : 2})
|
||||
assert getmsg(f, ns) == """assert g(**{'a': 2})"""
|
||||
assert getmsg(f, ns) == """assert False
|
||||
+ where False = g(**{'a': 2})"""
|
||||
|
||||
def test_attribute(self):
|
||||
class X(object):
|
||||
@@ -332,7 +341,8 @@ class TestAssertionRewrite:
|
||||
def f():
|
||||
x.a = False # noqa
|
||||
assert x.a # noqa
|
||||
assert getmsg(f, ns) == """assert x.a"""
|
||||
assert getmsg(f, ns) == """assert False
|
||||
+ where False = x.a"""
|
||||
|
||||
def test_comparisons(self):
|
||||
def f():
|
||||
@@ -514,6 +524,16 @@ def test_rewritten():
|
||||
testdir.makepyfile("import a_package_without_init_py.module")
|
||||
assert testdir.runpytest().ret == EXIT_NOTESTSCOLLECTED
|
||||
|
||||
def test_rewrite_warning(self, pytestconfig, monkeypatch):
|
||||
hook = AssertionRewritingHook(pytestconfig)
|
||||
warnings = []
|
||||
def mywarn(code, msg):
|
||||
warnings.append((code, msg))
|
||||
monkeypatch.setattr(hook.config, 'warn', mywarn)
|
||||
hook.mark_rewrite('_pytest')
|
||||
assert '_pytest' in warnings[0][1]
|
||||
|
||||
|
||||
class TestAssertionRewriteHookDetails(object):
|
||||
def test_loader_is_package_false_for_module(self, testdir):
|
||||
testdir.makepyfile(test_fun="""
|
||||
@@ -694,40 +714,6 @@ class TestAssertionRewriteHookDetails(object):
|
||||
result = testdir.runpytest()
|
||||
result.stdout.fnmatch_lines('*1 passed*')
|
||||
|
||||
@pytest.mark.parametrize('initial_conftest', [True, False])
|
||||
@pytest.mark.parametrize('mode', ['plain', 'rewrite', 'reinterp'])
|
||||
def test_conftest_assertion_rewrite(self, testdir, initial_conftest, mode):
|
||||
"""Test that conftest files are using assertion rewrite on import.
|
||||
(#1619)
|
||||
"""
|
||||
testdir.tmpdir.join('foo/tests').ensure(dir=1)
|
||||
conftest_path = 'conftest.py' if initial_conftest else 'foo/conftest.py'
|
||||
contents = {
|
||||
conftest_path: """
|
||||
import pytest
|
||||
@pytest.fixture
|
||||
def check_first():
|
||||
def check(values, value):
|
||||
assert values.pop(0) == value
|
||||
return check
|
||||
""",
|
||||
'foo/tests/test_foo.py': """
|
||||
def test(check_first):
|
||||
check_first([10, 30], 30)
|
||||
"""
|
||||
}
|
||||
testdir.makepyfile(**contents)
|
||||
result = testdir.runpytest_subprocess('--assert=%s' % mode)
|
||||
if mode == 'plain':
|
||||
expected = 'E AssertionError'
|
||||
elif mode == 'rewrite':
|
||||
expected = '*assert 10 == 30*'
|
||||
elif mode == 'reinterp':
|
||||
expected = '*AssertionError:*was re-run*'
|
||||
else:
|
||||
assert 0
|
||||
result.stdout.fnmatch_lines([expected])
|
||||
|
||||
|
||||
def test_issue731(testdir):
|
||||
testdir.makepyfile("""
|
||||
@@ -746,5 +732,28 @@ def test_issue731(testdir):
|
||||
assert 'unbalanced braces' not in result.stdout.str()
|
||||
|
||||
|
||||
def test_collapse_false_unbalanced_braces():
|
||||
util._collapse_false('some text{ False\n{False = some more text\n}')
|
||||
class TestIssue925():
|
||||
def test_simple_case(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
def test_ternary_display():
|
||||
assert (False == False) == False
|
||||
""")
|
||||
result = testdir.runpytest()
|
||||
result.stdout.fnmatch_lines('*E*assert (False == False) == False')
|
||||
|
||||
def test_long_case(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
def test_ternary_display():
|
||||
assert False == (False == True) == True
|
||||
""")
|
||||
result = testdir.runpytest()
|
||||
result.stdout.fnmatch_lines('*E*assert (False == True) == True')
|
||||
|
||||
def test_many_brackets(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
def test_ternary_display():
|
||||
assert True == ((False == True) == True)
|
||||
""")
|
||||
result = testdir.runpytest()
|
||||
result.stdout.fnmatch_lines('*E*assert True == ((False == True) == True)')
|
||||
|
||||
|
||||
@@ -373,10 +373,14 @@ def test_preparse_ordering_with_setuptools(testdir, monkeypatch):
|
||||
pkg_resources = pytest.importorskip("pkg_resources")
|
||||
def my_iter(name):
|
||||
assert name == "pytest11"
|
||||
class Dist:
|
||||
project_name = 'spam'
|
||||
version = '1.0'
|
||||
def _get_metadata(self, name):
|
||||
return ['foo.txt,sha256=abc,123']
|
||||
class EntryPoint:
|
||||
name = "mytestplugin"
|
||||
class dist:
|
||||
pass
|
||||
dist = Dist()
|
||||
def load(self):
|
||||
class PseudoPlugin:
|
||||
x = 42
|
||||
@@ -391,12 +395,40 @@ def test_preparse_ordering_with_setuptools(testdir, monkeypatch):
|
||||
plugin = config.pluginmanager.getplugin("mytestplugin")
|
||||
assert plugin.x == 42
|
||||
|
||||
|
||||
def test_setuptools_importerror_issue1479(testdir, monkeypatch):
|
||||
pkg_resources = pytest.importorskip("pkg_resources")
|
||||
def my_iter(name):
|
||||
assert name == "pytest11"
|
||||
class Dist:
|
||||
project_name = 'spam'
|
||||
version = '1.0'
|
||||
def _get_metadata(self, name):
|
||||
return ['foo.txt,sha256=abc,123']
|
||||
class EntryPoint:
|
||||
name = "mytestplugin"
|
||||
dist = Dist()
|
||||
def load(self):
|
||||
raise ImportError("Don't hide me!")
|
||||
return iter([EntryPoint()])
|
||||
|
||||
monkeypatch.setattr(pkg_resources, 'iter_entry_points', my_iter)
|
||||
with pytest.raises(ImportError):
|
||||
testdir.parseconfig()
|
||||
|
||||
|
||||
def test_plugin_preparse_prevents_setuptools_loading(testdir, monkeypatch):
|
||||
pkg_resources = pytest.importorskip("pkg_resources")
|
||||
def my_iter(name):
|
||||
assert name == "pytest11"
|
||||
class Dist:
|
||||
project_name = 'spam'
|
||||
version = '1.0'
|
||||
def _get_metadata(self, name):
|
||||
return ['foo.txt,sha256=abc,123']
|
||||
class EntryPoint:
|
||||
name = "mytestplugin"
|
||||
dist = Dist()
|
||||
def load(self):
|
||||
assert 0, "should not arrive here"
|
||||
return iter([EntryPoint()])
|
||||
@@ -488,7 +520,6 @@ def test_load_initial_conftest_last_ordering(testdir):
|
||||
expected = [
|
||||
"_pytest.config",
|
||||
'test_config',
|
||||
'_pytest.assertion',
|
||||
'_pytest.capture',
|
||||
]
|
||||
assert [x.function.__module__ for x in l] == expected
|
||||
@@ -522,11 +553,11 @@ class TestWarning:
|
||||
def test_hello(fix):
|
||||
pass
|
||||
""")
|
||||
result = testdir.runpytest()
|
||||
result = testdir.runpytest("--disable-pytest-warnings")
|
||||
assert result.parseoutcomes()["pytest-warnings"] > 0
|
||||
assert "hello" not in result.stdout.str()
|
||||
|
||||
result = testdir.runpytest("-rw")
|
||||
result = testdir.runpytest()
|
||||
result.stdout.fnmatch_lines("""
|
||||
===*pytest-warning summary*===
|
||||
*WT1*test_warn_on_test_item*:5*hello*
|
||||
@@ -671,4 +702,4 @@ class TestOverrideIniArgs:
|
||||
"ini2:url=/tmp/user2?a=b&d=e",
|
||||
"ini3:True",
|
||||
"ini4:False"
|
||||
])
|
||||
])
|
||||
|
||||
@@ -203,6 +203,7 @@ def test_conftest_import_order(testdir, monkeypatch):
|
||||
def impct(p):
|
||||
return p
|
||||
conftest = PytestPluginManager()
|
||||
conftest._confcutdir = testdir.tmpdir
|
||||
monkeypatch.setattr(conftest, '_importconftest', impct)
|
||||
assert conftest._getconftestmodules(sub) == [ct1, ct2]
|
||||
|
||||
|
||||
@@ -119,7 +119,10 @@ class TestPython:
|
||||
|
||||
def test_setup_error(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
def pytest_funcarg__arg(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def arg(request):
|
||||
raise ValueError()
|
||||
def test_function(arg):
|
||||
pass
|
||||
@@ -131,7 +134,7 @@ class TestPython:
|
||||
tnode = node.find_first_by_tag("testcase")
|
||||
tnode.assert_attr(
|
||||
file="test_setup_error.py",
|
||||
line="2",
|
||||
line="5",
|
||||
classname="test_setup_error",
|
||||
name="test_function")
|
||||
fnode = tnode.find_first_by_tag("error")
|
||||
@@ -444,7 +447,10 @@ class TestPython:
|
||||
|
||||
def test_setup_error_captures_stdout(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
def pytest_funcarg__arg(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def arg(request):
|
||||
print('hello-stdout')
|
||||
raise ValueError()
|
||||
def test_function(arg):
|
||||
@@ -459,7 +465,10 @@ class TestPython:
|
||||
def test_setup_error_captures_stderr(self, testdir):
|
||||
testdir.makepyfile("""
|
||||
import sys
|
||||
def pytest_funcarg__arg(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def arg(request):
|
||||
sys.stderr.write('hello-stderr')
|
||||
raise ValueError()
|
||||
def test_function(arg):
|
||||
|
||||
@@ -481,7 +481,8 @@ class TestFunctional:
|
||||
def test_mark_dynamically_in_funcarg(self, testdir):
|
||||
testdir.makeconftest("""
|
||||
import pytest
|
||||
def pytest_funcarg__arg(request):
|
||||
@pytest.fixture
|
||||
def arg(request):
|
||||
request.applymarker(pytest.mark.hello)
|
||||
def pytest_terminal_summary(terminalreporter):
|
||||
l = terminalreporter.stats['passed']
|
||||
|
||||
@@ -3,10 +3,11 @@ import sys
|
||||
import textwrap
|
||||
|
||||
import pytest
|
||||
from _pytest.monkeypatch import monkeypatch as MonkeyPatch
|
||||
from _pytest.monkeypatch import MonkeyPatch
|
||||
|
||||
|
||||
def pytest_funcarg__mp(request):
|
||||
@pytest.fixture
|
||||
def mp(request):
|
||||
cwd = os.getcwd()
|
||||
sys_path = list(sys.path)
|
||||
|
||||
@@ -205,7 +206,7 @@ def test_setenv_prepend():
|
||||
def test_monkeypatch_plugin(testdir):
|
||||
reprec = testdir.inline_runsource("""
|
||||
def test_method(monkeypatch):
|
||||
assert monkeypatch.__class__.__name__ == "monkeypatch"
|
||||
assert monkeypatch.__class__.__name__ == "MonkeyPatch"
|
||||
""")
|
||||
res = reprec.countoutcomes()
|
||||
assert tuple(res) == (1, 0, 0), res
|
||||
|
||||
@@ -29,6 +29,9 @@ class TestParser:
|
||||
assert argument.dest == 'test'
|
||||
argument = parseopt.Argument('-t', '--test', dest='abc')
|
||||
assert argument.dest == 'abc'
|
||||
assert str(argument) == (
|
||||
"Argument(_short_opts: ['-t'], _long_opts: ['--test'], dest: 'abc')"
|
||||
)
|
||||
|
||||
def test_argument_type(self):
|
||||
argument = parseopt.Argument('-t', dest='abc', type='int')
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import sys
|
||||
|
||||
import _pytest._code
|
||||
import pytest
|
||||
|
||||
|
||||
def runpdb_and_get_report(testdir, source):
|
||||
@@ -12,12 +13,14 @@ def runpdb_and_get_report(testdir, source):
|
||||
|
||||
|
||||
class TestPDB:
|
||||
def pytest_funcarg__pdblist(self, request):
|
||||
monkeypatch = request.getfuncargvalue("monkeypatch")
|
||||
|
||||
@pytest.fixture
|
||||
def pdblist(self, request):
|
||||
monkeypatch = request.getfixturevalue("monkeypatch")
|
||||
pdblist = []
|
||||
def mypdb(*args):
|
||||
pdblist.append(args)
|
||||
plugin = request.config.pluginmanager.getplugin('pdb')
|
||||
plugin = request.config.pluginmanager.getplugin('debugging')
|
||||
monkeypatch.setattr(plugin, 'post_mortem', mypdb)
|
||||
return pdblist
|
||||
|
||||
@@ -311,3 +314,28 @@ class TestPDB:
|
||||
child.sendeof()
|
||||
if child.isalive():
|
||||
child.wait()
|
||||
|
||||
def test_pdb_custom_cls(self, testdir):
|
||||
called = []
|
||||
|
||||
# install dummy debugger class and track which methods were called on it
|
||||
class _CustomPdb:
|
||||
def __init__(self, *args, **kwargs):
|
||||
called.append("init")
|
||||
|
||||
def reset(self):
|
||||
called.append("reset")
|
||||
|
||||
def interaction(self, *args):
|
||||
called.append("interaction")
|
||||
|
||||
_pytest._CustomPdb = _CustomPdb
|
||||
|
||||
p1 = testdir.makepyfile("""xxx """)
|
||||
result = testdir.runpytest_inprocess(
|
||||
"--pdbcls=_pytest:_CustomPdb", p1)
|
||||
result.stdout.fnmatch_lines([
|
||||
"*NameError*xxx*",
|
||||
"*1 error*",
|
||||
])
|
||||
assert called == ["init", "reset", "interaction"]
|
||||
|
||||
@@ -229,11 +229,12 @@ class BaseFunctionalTests:
|
||||
assert reps[5].failed
|
||||
|
||||
def test_exact_teardown_issue1206(self, testdir):
|
||||
"""issue shadowing error with wrong number of arguments on teardown_method."""
|
||||
rec = testdir.inline_runsource("""
|
||||
import pytest
|
||||
|
||||
class TestClass:
|
||||
def teardown_method(self):
|
||||
def teardown_method(self, x, y, z):
|
||||
pass
|
||||
|
||||
def test_method(self):
|
||||
@@ -256,9 +257,9 @@ class BaseFunctionalTests:
|
||||
assert reps[2].when == "teardown"
|
||||
assert reps[2].longrepr.reprcrash.message in (
|
||||
# python3 error
|
||||
'TypeError: teardown_method() takes 1 positional argument but 2 were given',
|
||||
"TypeError: teardown_method() missing 2 required positional arguments: 'y' and 'z'",
|
||||
# python2 error
|
||||
'TypeError: teardown_method() takes exactly 1 argument (2 given)'
|
||||
'TypeError: teardown_method() takes exactly 4 arguments (2 given)'
|
||||
)
|
||||
|
||||
def test_failure_in_setup_function_ignores_custom_repr(self, testdir):
|
||||
@@ -399,13 +400,15 @@ def test_callinfo():
|
||||
@pytest.mark.xfail
|
||||
def test_runtest_in_module_ordering(testdir):
|
||||
p1 = testdir.makepyfile("""
|
||||
import pytest
|
||||
def pytest_runtest_setup(item): # runs after class-level!
|
||||
item.function.mylist.append("module")
|
||||
class TestClass:
|
||||
def pytest_runtest_setup(self, item):
|
||||
assert not hasattr(item.function, 'mylist')
|
||||
item.function.mylist = ['class']
|
||||
def pytest_funcarg__mylist(self, request):
|
||||
@pytest.fixture
|
||||
def mylist(self, request):
|
||||
return request.function.mylist
|
||||
def pytest_runtest_call(self, item, __multicall__):
|
||||
try:
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#
|
||||
# test correct setup/teardowns at
|
||||
# module, class, and instance level
|
||||
import pytest
|
||||
|
||||
|
||||
def test_module_and_function_setup(testdir):
|
||||
reprec = testdir.inline_runsource("""
|
||||
@@ -234,7 +236,8 @@ def test_setup_funcarg_setup_when_outer_scope_fails(testdir):
|
||||
import pytest
|
||||
def setup_module(mod):
|
||||
raise ValueError(42)
|
||||
def pytest_funcarg__hello(request):
|
||||
@pytest.fixture
|
||||
def hello(request):
|
||||
raise ValueError("xyz43")
|
||||
def test_function1(hello):
|
||||
pass
|
||||
@@ -250,3 +253,53 @@ def test_setup_funcarg_setup_when_outer_scope_fails(testdir):
|
||||
"*2 error*"
|
||||
])
|
||||
assert "xyz43" not in result.stdout.str()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('arg', ['', 'arg'])
|
||||
def test_setup_teardown_function_level_with_optional_argument(testdir, monkeypatch, arg):
|
||||
"""parameter to setup/teardown xunit-style functions parameter is now optional (#1728)."""
|
||||
import sys
|
||||
trace_setups_teardowns = []
|
||||
monkeypatch.setattr(sys, 'trace_setups_teardowns', trace_setups_teardowns, raising=False)
|
||||
p = testdir.makepyfile("""
|
||||
import pytest
|
||||
import sys
|
||||
|
||||
trace = sys.trace_setups_teardowns.append
|
||||
|
||||
def setup_module({arg}): trace('setup_module')
|
||||
def teardown_module({arg}): trace('teardown_module')
|
||||
|
||||
def setup_function({arg}): trace('setup_function')
|
||||
def teardown_function({arg}): trace('teardown_function')
|
||||
|
||||
def test_function_1(): pass
|
||||
def test_function_2(): pass
|
||||
|
||||
class Test:
|
||||
def setup_method(self, {arg}): trace('setup_method')
|
||||
def teardown_method(self, {arg}): trace('teardown_method')
|
||||
|
||||
def test_method_1(self): pass
|
||||
def test_method_2(self): pass
|
||||
""".format(arg=arg))
|
||||
result = testdir.inline_run(p)
|
||||
result.assertoutcome(passed=4)
|
||||
|
||||
expected = [
|
||||
'setup_module',
|
||||
|
||||
'setup_function',
|
||||
'teardown_function',
|
||||
'setup_function',
|
||||
'teardown_function',
|
||||
|
||||
'setup_method',
|
||||
'teardown_method',
|
||||
|
||||
'setup_method',
|
||||
'teardown_method',
|
||||
|
||||
'teardown_module',
|
||||
]
|
||||
assert trace_setups_teardowns == expected
|
||||
|
||||
@@ -197,6 +197,14 @@ class TestNewSession(SessionTests):
|
||||
colfail = [x for x in finished if x.failed]
|
||||
assert len(colfail) == 1
|
||||
|
||||
def test_minus_x_overriden_by_maxfail(self, testdir):
|
||||
testdir.makepyfile(__init__="")
|
||||
testdir.makepyfile(test_one="xxxx", test_two="yyyy", test_third="zzz")
|
||||
reprec = testdir.inline_run("-x", "--maxfail=2", testdir.tmpdir)
|
||||
finished = reprec.getreports("pytest_collectreport")
|
||||
colfail = [x for x in finished if x.failed]
|
||||
assert len(colfail) == 2
|
||||
|
||||
|
||||
def test_plugin_specify(testdir):
|
||||
pytest.raises(ImportError, """
|
||||
|
||||
@@ -309,7 +309,8 @@ class TestXFail:
|
||||
def test_dynamic_xfail_no_run(self, testdir):
|
||||
p = testdir.makepyfile("""
|
||||
import pytest
|
||||
def pytest_funcarg__arg(request):
|
||||
@pytest.fixture
|
||||
def arg(request):
|
||||
request.applymarker(pytest.mark.xfail(run=False))
|
||||
def test_this(arg):
|
||||
assert 0
|
||||
@@ -323,7 +324,8 @@ class TestXFail:
|
||||
def test_dynamic_xfail_set_during_funcarg_setup(self, testdir):
|
||||
p = testdir.makepyfile("""
|
||||
import pytest
|
||||
def pytest_funcarg__arg(request):
|
||||
@pytest.fixture
|
||||
def arg(request):
|
||||
request.applymarker(pytest.mark.xfail)
|
||||
def test_this2(arg):
|
||||
assert 0
|
||||
|
||||
@@ -590,17 +590,30 @@ def test_getreportopt():
|
||||
class config:
|
||||
class option:
|
||||
reportchars = ""
|
||||
disablepytestwarnings = True
|
||||
|
||||
config.option.reportchars = "sf"
|
||||
assert getreportopt(config) == "sf"
|
||||
|
||||
config.option.reportchars = "sfx"
|
||||
config.option.reportchars = "sfxw"
|
||||
assert getreportopt(config) == "sfx"
|
||||
|
||||
config.option.reportchars = "sfx"
|
||||
config.option.disablepytestwarnings = False
|
||||
assert getreportopt(config) == "sfxw"
|
||||
|
||||
config.option.reportchars = "sfxw"
|
||||
config.option.disablepytestwarnings = False
|
||||
assert getreportopt(config) == "sfxw"
|
||||
|
||||
|
||||
def test_terminalreporter_reportopt_addopts(testdir):
|
||||
testdir.makeini("[pytest]\naddopts=-rs")
|
||||
testdir.makepyfile("""
|
||||
def pytest_funcarg__tr(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def tr(request):
|
||||
tr = request.config.pluginmanager.getplugin("terminalreporter")
|
||||
return tr
|
||||
def test_opt(tr):
|
||||
@@ -614,7 +627,10 @@ def test_terminalreporter_reportopt_addopts(testdir):
|
||||
|
||||
def test_tbstyle_short(testdir):
|
||||
p = testdir.makepyfile("""
|
||||
def pytest_funcarg__arg(request):
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def arg(request):
|
||||
return 42
|
||||
def test_opt(arg):
|
||||
x = 0
|
||||
@@ -625,7 +641,7 @@ def test_tbstyle_short(testdir):
|
||||
assert 'arg = 42' not in s
|
||||
assert 'x = 0' not in s
|
||||
result.stdout.fnmatch_lines([
|
||||
"*%s:5*" % p.basename,
|
||||
"*%s:8*" % p.basename,
|
||||
" assert x",
|
||||
"E assert*",
|
||||
])
|
||||
|
||||
@@ -265,8 +265,8 @@ def test_testcase_custom_exception_info(testdir, type):
|
||||
def run(self, result):
|
||||
excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)
|
||||
# we fake an incompatible exception info
|
||||
from _pytest.monkeypatch import monkeypatch
|
||||
mp = monkeypatch()
|
||||
from _pytest.monkeypatch import MonkeyPatch
|
||||
mp = MonkeyPatch()
|
||||
def t(*args):
|
||||
mp.undo()
|
||||
raise TypeError()
|
||||
|
||||
Reference in New Issue
Block a user