fix flakes issues and make --flakes run part of tox runs

This commit is contained in:
holger krekel 2013-10-12 15:39:22 +02:00
parent 8550ea0728
commit 8ac5af2896
40 changed files with 143 additions and 167 deletions

View File

@ -34,7 +34,7 @@ def pytest_configure(config):
mode = "plain"
if mode == "rewrite":
try:
import ast
import ast # noqa
except ImportError:
mode = "reinterp"
else:
@ -48,10 +48,10 @@ def pytest_configure(config):
m = monkeypatch()
config._cleanup.append(m.undo)
m.setattr(py.builtin.builtins, 'AssertionError',
reinterpret.AssertionError)
reinterpret.AssertionError) # noqa
hook = None
if mode == "rewrite":
hook = rewrite.AssertionRewritingHook()
hook = rewrite.AssertionRewritingHook() # noqa
sys.meta_path.insert(0, hook)
warn_about_missing_assertion(mode)
config._assertstate = AssertionState(config, mode)
@ -101,9 +101,9 @@ def pytest_sessionfinish(session):
def _load_modules(mode):
"""Lazily import assertion related code."""
global rewrite, reinterpret
from _pytest.assertion import reinterpret
from _pytest.assertion import reinterpret # noqa
if mode == "rewrite":
from _pytest.assertion import rewrite
from _pytest.assertion import rewrite # noqa
def warn_about_missing_assertion(mode):
try:

View File

@ -319,7 +319,7 @@ def rewrite_asserts(mod):
_saferepr = py.io.saferepr
from _pytest.assertion.util import format_explanation as _format_explanation
from _pytest.assertion.util import format_explanation as _format_explanation # noqa
def _should_repr_global_name(obj):
return not hasattr(obj, "__name__") and not py.builtin.callable(obj)
@ -557,7 +557,8 @@ class AssertionRewriter(ast.NodeVisitor):
for i, v in enumerate(boolop.values):
if i:
fail_inner = []
self.on_failure.append(ast.If(cond, fail_inner, []))
# cond is set in a prior loop iteration below
self.on_failure.append(ast.If(cond, fail_inner, [])) # noqa
self.on_failure = fail_inner
self.push_format_context()
res, expl = self.visit(v)

View File

@ -41,7 +41,7 @@ def get_plugin_manager():
return _preinit.pop(0)
# subsequent calls to main will create a fresh instance
pluginmanager = PytestPluginManager()
pluginmanager.config = config = Config(pluginmanager) # XXX attr needed?
pluginmanager.config = Config(pluginmanager) # XXX attr needed?
for spec in default_plugins:
pluginmanager.import_plugin(spec)
return pluginmanager

View File

@ -120,7 +120,6 @@ def pytest_report_header(config):
if config.option.traceconfig:
lines.append("active plugins:")
plugins = []
items = config.pluginmanager._name2plugin.items()
for name, plugin in items:
if hasattr(plugin, '__file__'):

View File

@ -425,7 +425,6 @@ class Collector(Node):
def _prunetraceback(self, excinfo):
if hasattr(self, 'fspath'):
path = self.fspath
traceback = excinfo.traceback
ntraceback = traceback.cut(path=self.fspath)
if ntraceback == traceback:

View File

@ -26,7 +26,6 @@ def pytest_addoption(parser):
def pytest_configure(config):
# This might be called multiple times. Only take the first.
global _pytest_fullpath
import pytest
try:
_pytest_fullpath
except NameError:
@ -121,7 +120,6 @@ class HookRecorder:
def contains(self, entries):
__tracebackhide__ = True
from py.builtin import print_
i = 0
entries = list(entries)
backlocals = py.std.sys._getframe(1).f_locals
@ -260,9 +258,6 @@ class TmpTestdir:
def makefile(self, ext, *args, **kwargs):
return self._makefile(ext, args, kwargs)
def makeini(self, source):
return self.makefile('cfg', setup=source)
def makeconftest(self, source):
return self.makepyfile(conftest=source)
@ -475,7 +470,7 @@ class TmpTestdir:
# XXX we rely on script refering to the correct environment
# we cannot use "(py.std.sys.executable,script)"
# becaue on windows the script is e.g. a py.test.exe
return (py.std.sys.executable, _pytest_fullpath,)
return (py.std.sys.executable, _pytest_fullpath,) # noqa
else:
py.test.skip("cannot run %r with --no-tools-on-path" % scriptname)

View File

@ -4,7 +4,7 @@ import inspect
import sys
import pytest
from _pytest.main import getfslineno
from _pytest.mark import MarkDecorator, MarkInfo
from _pytest.mark import MarkDecorator
from _pytest.monkeypatch import monkeypatch
from py._code.code import TerminalRepr
@ -177,7 +177,6 @@ def pytest_pyfunc_call(__multicall__, pyfuncitem):
def pytest_collect_file(path, parent):
ext = path.ext
pb = path.purebasename
if ext == ".py":
if not parent.session.isinitpath(path):
for pat in parent.config.getini('python_files'):
@ -914,10 +913,6 @@ def raises(ExpectedException, *args, **kwargs):
func(*args[1:], **kwargs)
except ExpectedException:
return py.code.ExceptionInfo()
k = ", ".join(["%s=%r" % x for x in kwargs.items()])
if k:
k = ', ' + k
expr = '%s(%r%s)' %(getattr(func, '__name__', func), args, k)
pytest.fail("DID NOT RAISE")
class RaisesContext(object):
@ -1015,7 +1010,7 @@ class Function(FunctionMixin, pytest.Item, FuncargnamesCompatAttr):
def setup(self):
# check if parametrization happend with an empty list
try:
empty = self.callspec._emptyparamspecified
self.callspec._emptyparamspecified
except AttributeError:
pass
else:
@ -1392,10 +1387,10 @@ class FixtureLookupError(LookupError):
if msg is None:
fm = self.request._fixturemanager
nodeid = self.request._parentid
available = []
for name, fixturedef in fm._arg2fixturedefs.items():
faclist = list(fm._matchfactories(fixturedef, self.request._parentid))
faclist = list(fm._matchfactories(fixturedef,
self.request._parentid))
if faclist:
available.append(name)
msg = "fixture %r not found" % (self.argname,)

View File

@ -217,7 +217,6 @@ def pytest_terminal_summary(terminalreporter):
tr._tw.line(line)
def show_simple(terminalreporter, lines, stat, format):
tw = terminalreporter._tw
failed = terminalreporter.stats.get(stat)
if failed:
for rep in failed:

View File

@ -39,7 +39,7 @@ class DictImporter(object):
if is_pkg:
module.__path__ = [fullname]
do_exec(co, module.__dict__)
do_exec(co, module.__dict__) # noqa
return sys.modules[fullname]
def get_source(self, name):
@ -63,4 +63,4 @@ if __name__ == "__main__":
sys.meta_path.insert(0, importer)
entry = "@ENTRY@"
do_exec(entry, locals())
do_exec(entry, locals()) # noqa

View File

@ -5,7 +5,6 @@ This is a good source for looking at the various reporting hooks.
import pytest
import py
import sys
import os
def pytest_addoption(parser):
group = parser.getgroup("terminal reporting", "reporting", after="general")

View File

@ -53,7 +53,8 @@ them in turn::
$ py.test
=========================== test session starts ============================
platform linux2 -- Python 2.7.3 -- pytest-2.4.2
platform linux2 -- Python 2.7.3 -- pytest-2.4.3.dev1
plugins: xdist, cov, pep8, xprocess, capturelog, cache, flakes, instafail
collected 3 items
test_expectation.py ..F
@ -74,7 +75,7 @@ them in turn::
E + where 54 = eval('6*9')
test_expectation.py:8: AssertionError
==================== 1 failed, 2 passed in 0.01 seconds ====================
==================== 1 failed, 2 passed in 0.04 seconds ====================
As designed in this example, only one pair of input/output values fails
the simple test function. And as usual with test function arguments,
@ -100,12 +101,13 @@ Let's run this::
$ py.test
=========================== test session starts ============================
platform linux2 -- Python 2.7.3 -- pytest-2.4.2
platform linux2 -- Python 2.7.3 -- pytest-2.4.3.dev1
plugins: xdist, cov, pep8, xprocess, capturelog, cache, flakes, instafail
collected 3 items
test_expectation.py ..x
=================== 2 passed, 1 xfailed in 0.01 seconds ====================
=================== 2 passed, 1 xfailed in 0.02 seconds ====================
The one parameter set which caused a failure previously now
shows up as an "xfailed (expected to fail)" test.
@ -170,8 +172,8 @@ Let's also run with a stringinput that will lead to a failing test::
def test_valid_string(stringinput):
> assert stringinput.isalpha()
E assert <built-in method isalpha of str object at 0x2ac85b043198>()
E + where <built-in method isalpha of str object at 0x2ac85b043198> = '!'.isalpha
E assert <built-in method isalpha of str object at 0x7f36a91ea1c0>()
E + where <built-in method isalpha of str object at 0x7f36a91ea1c0> = '!'.isalpha
test_strings.py:3: AssertionError
1 failed in 0.01 seconds
@ -185,7 +187,7 @@ listlist::
$ py.test -q -rs test_strings.py
s
========================= short test summary info ==========================
SKIP [1] /home/hpk/p/pytest/.tox/regen/local/lib/python2.7/site-packages/_pytest/python.py:1024: got empty parameter set, function test_valid_string at /tmp/doc-exec-561/test_strings.py:1
SKIP [1] /home/hpk/p/pytest/_pytest/python.py:1019: got empty parameter set, function test_valid_string at /tmp/doc-exec-686/test_strings.py:1
1 skipped in 0.01 seconds
For further examples, you might want to look at :ref:`more

View File

@ -1,4 +1,4 @@
import sys, py, pytest
import py, pytest
class TestGeneralUsage:
def test_config_error(self, testdir):
@ -14,7 +14,7 @@ class TestGeneralUsage:
])
def test_root_conftest_syntax_error(self, testdir):
p = testdir.makepyfile(conftest="raise SyntaxError\n")
testdir.makepyfile(conftest="raise SyntaxError\n")
result = testdir.runpytest()
result.stderr.fnmatch_lines(["*raise SyntaxError*"])
assert result.ret != 0
@ -67,7 +67,7 @@ class TestGeneralUsage:
result = testdir.runpytest("-s", "asd")
assert result.ret == 4 # EXIT_USAGEERROR
result.stderr.fnmatch_lines(["ERROR: file not found*asd"])
s = result.stdout.fnmatch_lines([
result.stdout.fnmatch_lines([
"*---configure",
"*---unconfigure",
])
@ -539,7 +539,6 @@ class TestDurations:
assert result.ret == 0
for x in "123":
for y in 'call',: #'setup', 'call', 'teardown':
l = []
for line in result.stdout.lines:
if ("test_%s" % x) in line and y in line:
break

View File

@ -1,6 +1,4 @@
import pytest, py, sys
from _pytest import python as funcargs
from _pytest.python import FixtureLookupError
import pytest, py
class TestModule:
def test_failing_import(self, testdir):
@ -32,7 +30,7 @@ class TestModule:
def test_module_considers_pluginmanager_at_import(self, testdir):
modcol = testdir.getmodulecol("pytest_plugins='xasdlkj',")
pytest.raises(ImportError, "modcol.obj")
pytest.raises(ImportError, lambda: modcol.obj)
class TestClass:
def test_class_with_init_skip_collect(self, testdir):
@ -606,7 +604,7 @@ class TestReportInfo:
return MyFunction(name, parent=collector)
""")
item = testdir.getitem("def test_func(): pass")
runner = item.config.pluginmanager.getplugin("runner")
item.config.pluginmanager.getplugin("runner")
assert item.location == ("ABCDE", 42, "custom")
def test_func_reportinfo(self, testdir):
@ -696,7 +694,7 @@ def test_customized_python_discovery_functions(testdir):
[pytest]
python_functions=_test
""")
p = testdir.makepyfile("""
testdir.makepyfile("""
def _test_underscore():
pass
""")

View File

@ -247,7 +247,7 @@ class TestFillFixtures:
assert result.ret == 0
def test_funcarg_lookup_error(self, testdir):
p = testdir.makepyfile("""
testdir.makepyfile("""
def test_lookup_error(unknown):
pass
""")
@ -307,7 +307,7 @@ class TestRequestBasic:
def pytest_funcarg__something(request):
return 1
""")
item = testdir.makepyfile("""
testdir.makepyfile("""
def pytest_funcarg__something(request):
return request.getfuncargvalue("something") + 1
def test_func(something):
@ -634,13 +634,13 @@ class TestRequestCachedSetup:
l.append("setup")
def teardown(val):
l.append("teardown")
ret1 = req1.cached_setup(setup, teardown, scope="function")
req1.cached_setup(setup, teardown, scope="function")
assert l == ['setup']
# artificial call of finalizer
setupstate = req1._pyfuncitem.session._setupstate
setupstate._callfinalizers(item1)
assert l == ["setup", "teardown"]
ret2 = req1.cached_setup(setup, teardown, scope="function")
req1.cached_setup(setup, teardown, scope="function")
assert l == ["setup", "teardown", "setup"]
setupstate._callfinalizers(item1)
assert l == ["setup", "teardown", "setup", "teardown"]
@ -1461,7 +1461,7 @@ class TestFixtureMarker:
'request.getfuncargvalue("arg")',
'request.cached_setup(lambda: None, scope="function")',
], ids=["getfuncargvalue", "cached_setup"])
def test_scope_mismatch(self, testdir, method):
def test_scope_mismatch_various(self, testdir, method):
testdir.makeconftest("""
import pytest
finalized = []
@ -1609,7 +1609,7 @@ class TestFixtureMarker:
""")
def test_class_ordering(self, testdir):
p = testdir.makeconftest("""
testdir.makeconftest("""
import pytest
l = []

View File

@ -1,4 +1,4 @@
import pytest, py, sys
import pytest
from _pytest import runner
class TestOEJSKITSpecials:

View File

@ -1,7 +1,6 @@
import pytest, py, sys
import pytest, py
from _pytest import python as funcargs
from _pytest.python import FixtureLookupError
class TestMetafunc:
def Metafunc(self, func):

View File

@ -29,7 +29,7 @@ class TestRaises:
def test_raises_flip_builtin_AssertionError(self):
# we replace AssertionError on python level
# however c code might still raise the builtin one
from _pytest.assertion.util import BuiltinAssertionError
from _pytest.assertion.util import BuiltinAssertionError # noqa
pytest.raises(AssertionError,"""
raise BuiltinAssertionError
""")

View File

@ -2,7 +2,7 @@ import sys
import py, pytest
import _pytest.assertion as plugin
from _pytest.assertion import reinterpret, util
from _pytest.assertion import reinterpret
needsnewassert = pytest.mark.skipif("sys.version_info < (2,6)")
@ -353,7 +353,7 @@ def test_traceback_failure(testdir):
@pytest.mark.skipif("sys.version_info < (2,5) or '__pypy__' in sys.builtin_module_names or sys.platform.startswith('java')" )
def test_warn_missing(testdir):
p1 = testdir.makepyfile("")
testdir.makepyfile("")
result = testdir.run(sys.executable, "-OO", "-m", "pytest", "-h")
result.stderr.fnmatch_lines([
"*WARNING*assert statements are not executed*",

View File

@ -107,13 +107,13 @@ class TestAssertionRewrite:
assert f
assert getmsg(f) == "assert False"
def f():
assert a_global
assert a_global # noqa
assert getmsg(f, {"a_global" : False}) == "assert False"
def f():
assert sys == 42
assert getmsg(f, {"sys" : sys}) == "assert sys == 42"
def f():
assert cls == 42
assert cls == 42 # noqa
class X(object):
pass
assert getmsg(f, {"cls" : X}) == "assert cls == 42"
@ -174,7 +174,7 @@ class TestAssertionRewrite:
def test_short_circut_evaluation(self):
def f():
assert True or explode
assert True or explode # noqa
getmsg(f, must_pass=True)
def f():
x = 1
@ -206,7 +206,6 @@ class TestAssertionRewrite:
assert x + y
assert getmsg(f) == "assert (1 + -1)"
def f():
x = range(10)
assert not 5 % 4
assert getmsg(f) == "assert not (5 % 4)"
@ -243,12 +242,12 @@ class TestAssertionRewrite:
g = 3
ns = {"x" : X}
def f():
assert not x.g
assert not x.g # noqa
assert getmsg(f, ns) == """assert not 3
+ where 3 = x.g"""
def f():
x.a = False
assert x.a
x.a = False # noqa
assert x.a # noqa
assert getmsg(f, ns) == """assert x.a"""
def test_comparisons(self):
@ -435,7 +434,7 @@ class TestAssertionRewriteHookDetails(object):
def test_missing():
assert not __loader__.is_package('pytest_not_there')
""")
pkg = testdir.mkpydir('fun')
testdir.mkpydir('fun')
result = testdir.runpytest()
result.stdout.fnmatch_lines([
'* 3 passed*',

View File

@ -242,7 +242,7 @@ class TestCustomConftests:
assert "passed" in result.stdout.str()
def test_pytest_fs_collect_hooks_are_seen(self, testdir):
conf = testdir.makeconftest("""
testdir.makeconftest("""
import pytest
class MyModule(pytest.Module):
pass
@ -250,8 +250,8 @@ class TestCustomConftests:
if path.ext == ".py":
return MyModule(path, parent)
""")
sub = testdir.mkdir("sub")
p = testdir.makepyfile("def test_x(): pass")
testdir.mkdir("sub")
testdir.makepyfile("def test_x(): pass")
result = testdir.runpytest("--collect-only")
result.stdout.fnmatch_lines([
"*MyModule*",
@ -318,7 +318,7 @@ class TestSession:
topdir = testdir.tmpdir
rcol = Session(config)
assert topdir == rcol.fspath
rootid = rcol.nodeid
#rootid = rcol.nodeid
#root2 = rcol.perform_collect([rcol.nodeid], genitems=False)[0]
#assert root2 == rcol, rootid
colitems = rcol.perform_collect([rcol.nodeid], genitems=False)
@ -329,13 +329,13 @@ class TestSession:
def test_collect_protocol_single_function(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
id = "::".join([p.basename, "test_func"])
topdir = testdir.tmpdir
items, hookrec = testdir.inline_genitems(id)
item, = items
assert item.name == "test_func"
newid = item.nodeid
assert newid == id
py.std.pprint.pprint(hookrec.hookrecorder.calls)
topdir = testdir.tmpdir # noqa
hookrec.hookrecorder.contains([
("pytest_collectstart", "collector.fspath == topdir"),
("pytest_make_collect_report", "collector.fspath == topdir"),
@ -436,7 +436,7 @@ class TestSession:
])
def test_serialization_byid(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
testdir.makepyfile("def test_func(): pass")
items, hookrec = testdir.inline_genitems()
assert len(items) == 1
item, = items

View File

@ -16,7 +16,7 @@ class TestParseIni:
assert config.inicfg['name'] == 'value'
def test_getcfg_empty_path(self, tmpdir):
cfg = getcfg([''], ['setup.cfg']) #happens on py.test ""
getcfg([''], ['setup.cfg']) #happens on py.test ""
def test_append_parse_args(self, testdir, tmpdir):
tmpdir.join("setup.cfg").write(py.code.Source("""
@ -31,7 +31,7 @@ class TestParseIni:
#assert len(args) == 1
def test_tox_ini_wrong_version(self, testdir):
p = testdir.makefile('.ini', tox="""
testdir.makefile('.ini', tox="""
[pytest]
minversion=9.0
""")
@ -77,7 +77,7 @@ class TestParseIni:
class TestConfigCmdlineParsing:
def test_parsing_again_fails(self, testdir):
config = testdir.parseconfig()
pytest.raises(AssertionError, "config.parse([])")
pytest.raises(AssertionError, lambda: config.parse([]))
class TestConfigAPI:
@ -200,7 +200,7 @@ class TestConfigAPI:
parser.addini("args", "new args", type="args")
parser.addini("a2", "", "args", default="1 2 3".split())
""")
p = testdir.makeini("""
testdir.makeini("""
[pytest]
args=123 "123 hello" "this"
""")
@ -217,7 +217,7 @@ class TestConfigAPI:
parser.addini("xy", "", type="linelist")
parser.addini("a2", "", "linelist")
""")
p = testdir.makeini("""
testdir.makeini("""
[pytest]
xy= 123 345
second line
@ -234,7 +234,7 @@ class TestConfigAPI:
def pytest_addoption(parser):
parser.addini("xy", "", type="linelist")
""")
p = testdir.makeini("""
testdir.makeini("""
[pytest]
xy= 123
""")

View File

@ -8,7 +8,7 @@ def pytest_generate_tests(metafunc):
def pytest_funcarg__basedir(request):
def basedirmaker(request):
basedir = d = request.getfuncargvalue("tmpdir")
d = request.getfuncargvalue("tmpdir")
d.ensure("adir/conftest.py").write("a=1 ; Directory = 3")
d.ensure("adir/b/conftest.py").write("b=2 ; a = 1.5")
if request.param == "inpackage":
@ -41,7 +41,7 @@ class TestConftestValueAccessGlobal:
def test_immediate_initialiation_and_incremental_are_the_same(self, basedir):
conftest = Conftest()
snap0 = len(conftest._path2confmods)
len(conftest._path2confmods)
conftest.getconftestmodules(basedir)
snap1 = len(conftest._path2confmods)
#assert len(conftest._path2confmods) == snap1 + 1
@ -57,7 +57,7 @@ class TestConftestValueAccessGlobal:
def test_value_access_not_existing(self, basedir):
conftest = ConftestWithSetinitial(basedir)
pytest.raises(KeyError, "conftest.rget('a')")
pytest.raises(KeyError, lambda: conftest.rget('a'))
#pytest.raises(KeyError, "conftest.lget('a')")
def test_value_access_by_path(self, basedir):
@ -97,7 +97,7 @@ def test_conftest_in_nonpkg_with_init(tmpdir):
tmpdir.ensure("adir-1.0/b/conftest.py").write("b=2 ; a = 1.5")
tmpdir.ensure("adir-1.0/b/__init__.py")
tmpdir.ensure("adir-1.0/__init__.py")
conftest = ConftestWithSetinitial(tmpdir.join("adir-1.0", "b"))
ConftestWithSetinitial(tmpdir.join("adir-1.0", "b"))
def test_doubledash_not_considered(testdir):
conf = testdir.mkdir("--option")

View File

@ -8,13 +8,12 @@ class TestBootstrapping:
def test_consider_env_fails_to_import(self, monkeypatch):
pluginmanager = PluginManager()
monkeypatch.setenv('PYTEST_PLUGINS', 'nonexisting', prepend=",")
pytest.raises(ImportError, "pluginmanager.consider_env()")
pytest.raises(ImportError, lambda: pluginmanager.consider_env())
def test_preparse_args(self):
pluginmanager = PluginManager()
pytest.raises(ImportError, """
pluginmanager.consider_preparse(["xyz", "-p", "hello123"])
""")
pytest.raises(ImportError, lambda:
pluginmanager.consider_preparse(["xyz", "-p", "hello123"]))
def test_plugin_prevent_register(self):
pluginmanager = PluginManager()
@ -93,7 +92,7 @@ class TestBootstrapping:
# ok, we did not explode
def test_pluginmanager_ENV_startup(self, testdir, monkeypatch):
x500 = testdir.makepyfile(pytest_x500="#")
testdir.makepyfile(pytest_x500="#")
p = testdir.makepyfile("""
import pytest
def test_hello(pytestconfig):
@ -110,7 +109,7 @@ class TestBootstrapping:
pytest.raises(ImportError, 'pluginmanager.import_plugin("qweqwex.y")')
pytest.raises(ImportError, 'pluginmanager.import_plugin("pytest_qweqwx.y")')
reset = testdir.syspathinsert()
testdir.syspathinsert()
pluginname = "pytest_hello"
testdir.makepyfile(**{pluginname: ""})
pluginmanager.import_plugin("pytest_hello")
@ -128,7 +127,7 @@ class TestBootstrapping:
pytest.raises(ImportError, 'pluginmanager.import_plugin("qweqwex.y")')
pytest.raises(ImportError, 'pluginmanager.import_plugin("pytest_qweqwex.y")')
reset = testdir.syspathinsert()
testdir.syspathinsert()
testdir.mkpydir("pkg").join("plug.py").write("x=3")
pluginname = "pkg.plug"
pluginmanager.import_plugin(pluginname)
@ -170,7 +169,7 @@ class TestBootstrapping:
def test_consider_conftest_deps(self, testdir):
mod = testdir.makepyfile("pytest_plugins='xyz'").pyimport()
pp = PluginManager()
pytest.raises(ImportError, "pp.consider_conftest(mod)")
pytest.raises(ImportError, lambda: pp.consider_conftest(mod))
def test_pm(self):
pp = PluginManager()
@ -210,9 +209,7 @@ class TestBootstrapping:
l = pp.getplugins()
assert mod in l
pytest.raises(ValueError, "pp.register(mod)")
mod2 = py.std.types.ModuleType("pytest_hello")
#pp.register(mod2) # double pm
pytest.raises(ValueError, "pp.register(mod)")
pytest.raises(ValueError, lambda: pp.register(mod))
#assert not pp.isregistered(mod2)
assert pp.getplugins() == l
@ -229,14 +226,14 @@ class TestBootstrapping:
class hello:
def pytest_gurgel(self):
pass
pytest.raises(Exception, "pp.register(hello())")
pytest.raises(Exception, lambda: pp.register(hello()))
def test_register_mismatch_arg(self):
pp = get_plugin_manager()
class hello:
def pytest_configure(self, asd):
pass
excinfo = pytest.raises(Exception, "pp.register(hello())")
pytest.raises(Exception, lambda: pp.register(hello()))
def test_register(self):
pm = get_plugin_manager()
@ -293,7 +290,7 @@ class TestBootstrapping:
class TestPytestPluginInteractions:
def test_addhooks_conftestplugin(self, testdir):
newhooks = testdir.makepyfile(newhooks="""
testdir.makepyfile(newhooks="""
def pytest_myhook(xyz):
"new hook"
""")
@ -312,7 +309,7 @@ class TestPytestPluginInteractions:
assert res == [11]
def test_addhooks_nohooks(self, testdir):
conf = testdir.makeconftest("""
testdir.makeconftest("""
import sys
def pytest_addhooks(pluginmanager):
pluginmanager.addhooks(sys)
@ -431,7 +428,7 @@ def test_namespace_has_default_and_env_plugins(testdir):
def test_varnames():
def f(x):
i = 3
i = 3 # noqa
class A:
def f(self, y):
pass
@ -496,7 +493,7 @@ class TestMultiCall:
def test_tags_call_error(self):
multicall = MultiCall([lambda x: x], {})
pytest.raises(TypeError, "multicall.execute()")
pytest.raises(TypeError, multicall.execute)
def test_call_subexecute(self):
def m(__multicall__):
@ -544,7 +541,7 @@ class TestHookRelay:
def hello(self, arg):
"api hook 1"
mcm = HookRelay(hookspecs=Api, pm=pm, prefix="he")
pytest.raises(TypeError, "mcm.hello(3)")
pytest.raises(TypeError, lambda: mcm.hello(3))
def test_firstresult_definition(self):
pm = PluginManager()

View File

@ -99,7 +99,7 @@ class TestDoctests:
reprec.assertoutcome(failed=1)
def test_doctest_unexpected_exception(self, testdir):
p = testdir.maketxtfile("""
testdir.maketxtfile("""
>>> i = 0
>>> 0 / i
2
@ -136,7 +136,7 @@ class TestDoctests:
testdir.tmpdir.join("hello.py").write(py.code.Source("""
import asdalsdkjaslkdjasd
"""))
p = testdir.maketxtfile("""
testdir.maketxtfile("""
>>> import hello
>>>
""")

View File

@ -1,6 +1,5 @@
import pytest
import py, os, sys
import subprocess
import sys
@pytest.fixture(scope="module")

View File

@ -1,4 +1,4 @@
import py, pytest,os
import py, pytest
from _pytest.helpconfig import collectattr
def test_version(testdir, pytestconfig):

View File

@ -1,4 +1,3 @@
import pytest
from xml.dom import minidom
import py, sys, os
@ -370,7 +369,7 @@ def test_nullbyte(testdir):
assert False
""")
xmlf = testdir.tmpdir.join('junit.xml')
result = testdir.runpytest('--junitxml=%s' % xmlf)
testdir.runpytest('--junitxml=%s' % xmlf)
text = xmlf.read()
assert '\x00' not in text
assert '#x00' in text
@ -386,7 +385,7 @@ def test_nullbyte_replace(testdir):
assert False
""")
xmlf = testdir.tmpdir.join('junit.xml')
result = testdir.runpytest('--junitxml=%s' % xmlf)
testdir.runpytest('--junitxml=%s' % xmlf)
text = xmlf.read()
assert '#x0' in text
@ -405,7 +404,6 @@ def test_invalid_xml_escape():
unichr(65)
except NameError:
unichr = chr
u = py.builtin._totext
invalid = (0x00, 0x1, 0xB, 0xC, 0xE, 0x19,
27, # issue #126
0xD800, 0xDFFF, 0xFFFE, 0x0FFFF) #, 0x110000)

View File

@ -13,7 +13,7 @@ class TestMark:
def test_pytest_mark_notcallable(self):
mark = Mark()
pytest.raises((AttributeError, TypeError), "mark()")
pytest.raises((AttributeError, TypeError), mark)
def test_pytest_mark_bare(self):
mark = Mark()
@ -35,7 +35,7 @@ class TestMark:
mark = Mark()
def f():
pass
marker = mark.world
mark.world
mark.world(x=3)(f)
assert f.world.kwargs['x'] == 3
mark.world(y=4)(f)
@ -374,7 +374,7 @@ class TestFunctional:
assert len(deselected_tests) == 2
def test_keywords_at_node_level(self, testdir):
p = testdir.makepyfile("""
testdir.makepyfile("""
import pytest
@pytest.fixture(scope="session", autouse=True)
def some(request):

View File

@ -96,7 +96,7 @@ def test_nose_setup_func_failure(testdir):
def test_nose_setup_func_failure_2(testdir):
p = testdir.makepyfile("""
testdir.makepyfile("""
l = []
my_setup = 1

View File

@ -3,7 +3,6 @@ import sys
import os
import py, pytest
from _pytest import config as parseopt
from textwrap import dedent
@pytest.fixture
def parser():
@ -12,7 +11,7 @@ def parser():
class TestParser:
def test_no_help_by_default(self, capsys):
parser = parseopt.Parser(usage="xyz")
pytest.raises(SystemExit, 'parser.parse(["-h"])')
pytest.raises(SystemExit, lambda: parser.parse(["-h"]))
out, err = capsys.readouterr()
assert err.find("error: unrecognized arguments") != -1
@ -65,9 +64,9 @@ class TestParser:
assert group2 is group
def test_group_ordering(self, parser):
group0 = parser.getgroup("1")
group1 = parser.getgroup("2")
group1 = parser.getgroup("3", after="1")
parser.getgroup("1")
parser.getgroup("2")
parser.getgroup("3", after="1")
groups = parser._groups
groups_names = [x.name for x in groups]
assert groups_names == list("132")
@ -104,7 +103,7 @@ class TestParser:
assert getattr(args, parseopt.FILE_OR_DIR)[0] == py.path.local()
def test_parse_known_args(self, parser):
args = parser.parse_known_args([py.path.local()])
parser.parse_known_args([py.path.local()])
parser.addoption("--hello", action="store_true")
ns = parser.parse_known_args(["x", "--y", "--hello", "this"])
assert ns.hello
@ -114,7 +113,7 @@ class TestParser:
option = parser.parse([])
assert option.hello == "x"
del option.hello
args = parser.parse_setoption([], option)
parser.parse_setoption([], option)
assert option.hello == "x"
def test_parse_setoption(self, parser):
@ -128,7 +127,7 @@ class TestParser:
assert not args
def test_parse_special_destination(self, parser):
x = parser.addoption("--ultimate-answer", type=int)
parser.addoption("--ultimate-answer", type=int)
args = parser.parse(['--ultimate-answer', '42'])
assert args.ultimate_answer == 42

View File

@ -1,4 +1,3 @@
import pytest
class TestPasting:
def pytest_funcarg__pastebinlist(self, request):
@ -56,4 +55,4 @@ class TestRPCClient:
assert proxy is not None
assert proxy.__class__.__module__.startswith('xmlrpc')

View File

@ -1,4 +1,4 @@
import py, pytest
import py
import sys
from test_doctest import xfail_if_pdbpp_installed
@ -162,7 +162,7 @@ class TestPDB:
child.send("capsys.readouterr()\n")
child.expect("hello1")
child.sendeof()
rest = child.read()
child.read()
if child.isalive():
child.wait()

View File

@ -1,7 +1,7 @@
import py
import pytest
import os, sys
from _pytest.pytester import LineMatcher, LineComp, HookRecorder
import os
from _pytest.pytester import HookRecorder
from _pytest.core import PluginManager
def test_reportrecorder(testdir):
@ -56,7 +56,6 @@ def test_reportrecorder(testdir):
def test_parseconfig(testdir):
import py
config1 = testdir.parseconfig()
config2 = testdir.parseconfig()
assert config2 != config1

View File

@ -1,6 +1,5 @@
import pytest, py, sys, os
from _pytest import runner, main
from py._code.code import ReprExceptionInfo
class TestSetupState:
def test_setup(self, testdir):
@ -39,10 +38,11 @@ class TestSetupState:
def setup_module(mod):
raise ValueError(42)
def test_func(): pass
""")
""") # noqa
ss = runner.SetupState()
pytest.raises(ValueError, "ss.prepare(item)")
pytest.raises(ValueError, "ss.prepare(item)")
pytest.raises(ValueError, lambda: ss.prepare(item))
pytest.raises(ValueError, lambda: ss.prepare(item))
class BaseFunctionalTests:
def test_passfunction(self, testdir):
@ -428,7 +428,7 @@ def test_importorskip():
def f():
importorskip("asdlkj")
try:
sys = importorskip("sys")
sys = importorskip("sys") # noqa
assert sys == py.std.sys
#path = py.test.importorskip("os.path")
#assert path == py.std.os.path
@ -464,7 +464,7 @@ def test_pytest_cmdline_main(testdir):
""")
import subprocess
popen = subprocess.Popen([sys.executable, str(p)], stdout=subprocess.PIPE)
s = popen.stdout.read()
popen.communicate()
ret = popen.wait()
assert ret == 0

View File

@ -204,7 +204,7 @@ class TestNewSession(SessionTests):
def test_plugin_specify(testdir):
testdir.chdir()
config = pytest.raises(ImportError, """
pytest.raises(ImportError, """
testdir.parseconfig("-p", "nqweotexistent")
""")
#pytest.raises(ImportError,

View File

@ -1,8 +1,7 @@
import pytest
import sys
from _pytest.skipping import MarkEvaluator, folded_skips
from _pytest.skipping import pytest_runtest_setup
from _pytest.skipping import MarkEvaluator, folded_skips, pytest_runtest_setup
from _pytest.runner import runtestprotocol
class TestEvaluator:
@ -108,7 +107,7 @@ class TestEvaluator:
pass
""")
ev = MarkEvaluator(item, 'skipif')
exc = pytest.raises(pytest.fail.Exception, "ev.istrue()")
exc = pytest.raises(pytest.fail.Exception, ev.istrue)
assert """Failed: you need to specify reason=STRING when using booleans as conditions.""" in exc.value.msg
def test_skipif_class(self, testdir):
@ -189,7 +188,7 @@ class TestXFail:
def test_this():
assert 0
""")
result = testdir.runpytest(p, '-v')
testdir.runpytest(p, '-v')
#result.stdout.fnmatch_lines([
# "*HINT*use*-r*"
#])
@ -370,8 +369,9 @@ class TestSkipif:
@pytest.mark.skipif("hasattr(os, 'sep')")
def test_func():
pass
""")
x = pytest.raises(pytest.skip.Exception, "pytest_runtest_setup(item)")
""") # noqa
x = pytest.raises(pytest.skip.Exception, lambda:
pytest_runtest_setup(item))
assert x.value.msg == "condition: hasattr(os, 'sep')"

View File

@ -39,7 +39,7 @@ def pytest_generate_tests(metafunc):
class TestTerminal:
def test_pass_skip_fail(self, testdir, option):
p = testdir.makepyfile("""
testdir.makepyfile("""
import pytest
def test_ok():
pass
@ -76,7 +76,6 @@ class TestTerminal:
def test_writeline(self, testdir, linecomp):
modcol = testdir.getmodulecol("def test_one(): pass")
stringio = py.io.TextIO()
rep = TerminalReporter(modcol.config, file=linecomp.stringio)
rep.write_fspath_result(py.path.local("xy.py"), '.')
rep.write_line("hello world")
@ -97,7 +96,7 @@ class TestTerminal:
])
def test_runtest_location_shown_before_test_starts(self, testdir):
p1 = testdir.makepyfile("""
testdir.makepyfile("""
def test_1():
import time
time.sleep(20)
@ -108,7 +107,7 @@ class TestTerminal:
child.kill(15)
def test_itemreport_subclasses_show_subclassed_file(self, testdir):
p1 = testdir.makepyfile(test_p1="""
testdir.makepyfile(test_p1="""
class BaseTests:
def test_p1(self):
pass
@ -145,7 +144,7 @@ class TestTerminal:
assert " <- " not in result.stdout.str()
def test_keyboard_interrupt(self, testdir, option):
p = testdir.makepyfile("""
testdir.makepyfile("""
def test_foobar():
assert 0
def test_spamegg():
@ -172,7 +171,7 @@ class TestTerminal:
def pytest_sessionstart():
raise KeyboardInterrupt
""")
p = testdir.makepyfile("""
testdir.makepyfile("""
def test_foobar():
pass
""")
@ -214,7 +213,7 @@ class TestCollectonly:
])
def test_collectonly_fatal(self, testdir):
p1 = testdir.makeconftest("""
testdir.makeconftest("""
def pytest_collectstart(collector):
assert 0, "urgs"
""")
@ -233,7 +232,6 @@ class TestCollectonly:
pass
""")
result = testdir.runpytest("--collect-only", p)
stderr = result.stderr.str().strip()
#assert stderr.startswith("inserting into sys.path")
assert result.ret == 0
result.stdout.fnmatch_lines([
@ -247,7 +245,6 @@ class TestCollectonly:
def test_collectonly_error(self, testdir):
p = testdir.makepyfile("import Errlkjqweqwe")
result = testdir.runpytest("--collect-only", p)
stderr = result.stderr.str().strip()
assert result.ret == 1
result.stdout.fnmatch_lines(py.code.Source("""
*ERROR*
@ -293,7 +290,7 @@ def test_repr_python_version(monkeypatch):
class TestFixtureReporting:
def test_setup_fixture_error(self, testdir):
p = testdir.makepyfile("""
testdir.makepyfile("""
def setup_function(function):
print ("setup func")
assert 0
@ -311,7 +308,7 @@ class TestFixtureReporting:
assert result.ret != 0
def test_teardown_fixture_error(self, testdir):
p = testdir.makepyfile("""
testdir.makepyfile("""
def test_nada():
pass
def teardown_function(function):
@ -329,7 +326,7 @@ class TestFixtureReporting:
])
def test_teardown_fixture_error_and_test_failure(self, testdir):
p = testdir.makepyfile("""
testdir.makepyfile("""
def test_fail():
assert 0, "failingfunc"
@ -403,7 +400,7 @@ class TestTerminalFunctional:
assert result.ret == 0
def test_header_trailer_info(self, testdir):
p1 = testdir.makepyfile("""
testdir.makepyfile("""
def test_passes():
pass
""")
@ -486,18 +483,18 @@ class TestTerminalFunctional:
def test_fail_extra_reporting(testdir):
p = testdir.makepyfile("def test_this(): assert 0")
result = testdir.runpytest(p)
testdir.makepyfile("def test_this(): assert 0")
result = testdir.runpytest()
assert 'short test summary' not in result.stdout.str()
result = testdir.runpytest(p, '-rf')
result = testdir.runpytest('-rf')
result.stdout.fnmatch_lines([
"*test summary*",
"FAIL*test_fail_extra_reporting*",
])
def test_fail_reporting_on_pass(testdir):
p = testdir.makepyfile("def test_this(): assert 1")
result = testdir.runpytest(p, '-rf')
testdir.makepyfile("def test_this(): assert 1")
result = testdir.runpytest('-rf')
assert 'short test summary' not in result.stdout.str()
def test_getreportopt():
@ -522,7 +519,7 @@ def test_getreportopt():
def test_terminalreporter_reportopt_addopts(testdir):
testdir.makeini("[pytest]\naddopts=-rs")
p = testdir.makepyfile("""
testdir.makepyfile("""
def pytest_funcarg__tr(request):
tr = request.config.pluginmanager.getplugin("terminalreporter")
return tr
@ -570,7 +567,7 @@ class TestGenericReporting:
provider to run e.g. distributed tests.
"""
def test_collect_fail(self, testdir, option):
p = testdir.makepyfile("import xyz\n")
testdir.makepyfile("import xyz\n")
result = testdir.runpytest(*option.args)
result.stdout.fnmatch_lines([
"> import xyz",
@ -579,7 +576,7 @@ class TestGenericReporting:
])
def test_maxfailures(self, testdir, option):
p = testdir.makepyfile("""
testdir.makepyfile("""
def test_1():
assert 0
def test_2():
@ -597,7 +594,7 @@ class TestGenericReporting:
def test_tb_option(self, testdir, option):
p = testdir.makepyfile("""
testdir.makepyfile("""
import pytest
def g():
raise IndexError
@ -678,7 +675,7 @@ def test_fdopen_kept_alive_issue124(testdir):
])
def test_tbstyle_native_setup_error(testdir):
p = testdir.makepyfile("""
testdir.makepyfile("""
import pytest
@pytest.fixture
def setup_error_fixture():

View File

@ -1,5 +1,4 @@
import py, pytest
import os
from _pytest.tmpdir import tmpdir, TempdirHandler

View File

@ -15,7 +15,7 @@ def test_simple_unittest(testdir):
assert reprec.matchreport("test_failing").failed
def test_runTest_method(testdir):
testpath=testdir.makepyfile("""
testdir.makepyfile("""
import unittest
pytest_plugins = "pytest_unittest"
class MyTestCaseWithRunTest(unittest.TestCase):

View File

@ -1,6 +1,6 @@
[tox]
distshare={homedir}/.tox/distshare
envlist=py25,py26,py27,py27-nobyte,py32,py33,py27-xdist,trial
envlist=flakes,py25,py26,py27,py27-nobyte,py32,py33,py27-xdist,trial
[testenv]
changedir=testing
@ -17,6 +17,11 @@ commands= py.test --genscript=pytest1
setenv =
PIP_INSECURE=1
[testenv:flakes]
changedir=
deps = pytest-flakes>=0.2
commands = py.test --flakes -m flakes _pytest testing
[testenv:py27-xdist]
changedir=.
basepython=python2.7