Skip to content

Instantly share code, notes, and snippets.

@nicoddemus
Created May 24, 2018 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicoddemus/c5862b61c3e1a9e038ad4fdb903d2395 to your computer and use it in GitHub Desktop.
Save nicoddemus/c5862b61c3e1a9e038ad4fdb903d2395 to your computer and use it in GitHub Desktop.
black on pytest/testing
diff --git a/testing/acceptance_test.py b/testing/acceptance_test.py
index c2eed419..ad709c9b 100644
--- a/testing/acceptance_test.py
+++ b/testing/acceptance_test.py
@@ -595,6 +595,7 @@ class TestInvocationVariants(object):
cur = os.environ.get("PYTHONPATH")
if cur:
return str(what) + os.pathsep + cur
+
return what
empty_package = testdir.mkpydir("empty_package")
@@ -791,6 +792,7 @@ class TestInvocationVariants(object):
if line.startswith("FAIL "):
testid = line[5:].strip()
break
+
result = testdir.runpytest(testid, "-rf")
result.stdout.fnmatch_lines([line, "*1 failed*"])
@@ -845,6 +847,7 @@ class TestDurations(object):
for line in result.stdout.lines:
if ("test_%s" % x) in line and y in line:
break
+
else:
raise AssertionError("not found %s %s" % (x, y))
diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py
index 463b2e38..f1d9a15b 100644
--- a/testing/code/test_excinfo.py
+++ b/testing/code/test_excinfo.py
@@ -8,10 +8,7 @@ import _pytest
import py
import pytest
from _pytest._code.code import (
- ExceptionInfo,
- FormattedExcinfo,
- ReprExceptionInfo,
- ExceptionChainRepr,
+ ExceptionInfo, FormattedExcinfo, ReprExceptionInfo, ExceptionChainRepr
)
from test_source import astonly
@@ -60,6 +57,7 @@ class TWMock(object):
def test_excinfo_simple():
try:
raise ValueError
+
except ValueError:
info = _pytest._code.ExceptionInfo()
assert info.type == ValueError
@@ -85,9 +83,11 @@ def test_excinfo_getstatement():
values = list(excinfo.traceback)
foundlinenumbers = [x.lineno for x in values]
assert foundlinenumbers == linenumbers
- # for x in info:
- # print "%s:%d %s" %(x.path.relto(root), x.lineno, x.statement)
- # xxx
+
+
+# for x in info:
+# print "%s:%d %s" %(x.path.relto(root), x.lineno, x.statement)
+# xxx
# testchain for getentries test below
@@ -96,20 +96,26 @@ def test_excinfo_getstatement():
def f():
#
raise ValueError
- #
+
+
+#
def g():
#
__tracebackhide__ = True
f()
- #
+
+
+#
def h():
#
g()
- #
+
+
+#
class TestTraceback_f_g_h(object):
@@ -199,18 +205,21 @@ class TestTraceback_f_g_h(object):
def f():
#
raise ValueError
- #
+
+ #
def g():
#
__tracebackhide__ = tracebackhide
f()
- #
+
+ #
def h():
#
g()
- #
+
+ #
excinfo = pytest.raises(ValueError, h)
traceback = excinfo.traceback
@@ -241,6 +250,7 @@ class TestTraceback_f_g_h(object):
def f(n):
if n == 0:
raise RuntimeError("hello")
+
f(n - 1)
excinfo = pytest.raises(RuntimeError, f, 100)
@@ -452,8 +462,10 @@ class TestFormattedExcinfo(object):
exec(source.compile())
except KeyboardInterrupt:
raise
+
except: # noqa
return _pytest._code.ExceptionInfo()
+
assert 0, "did not raise"
def test_repr_source(self):
@@ -623,7 +635,8 @@ raise ValueError()
loc = repr_entry.reprfileloc
assert loc.path == mod.__file__
assert loc.lineno == 3
- # assert loc.message == "ValueError: hello"
+
+ # assert loc.message == "ValueError: hello"
def test_repr_tracebackentry_lines2(self, importasmod):
mod = importasmod(
@@ -1276,6 +1289,7 @@ def test_repr_traceback_with_unicode(style, encoding):
msg = msg.encode(encoding)
try:
raise RuntimeError(msg)
+
except RuntimeError:
e_info = ExceptionInfo()
formatter = FormattedExcinfo(style=style)
diff --git a/testing/code/test_source.py b/testing/code/test_source.py
index 56dad756..ec0173df 100644
--- a/testing/code/test_source.py
+++ b/testing/code/test_source.py
@@ -45,6 +45,7 @@ def test_unicode():
unicode
except NameError:
return
+
x = Source(unicode("4"))
assert str(x) == "4"
co = _pytest._code.compile(unicode('u"\xc3\xa5"', "utf8"), mode="eval")
diff --git a/testing/code/test_source_multiline_block.py b/testing/code/test_source_multiline_block.py
index 8c41c9ef..92f7412e 100644
--- a/testing/code/test_source_multiline_block.py
+++ b/testing/code/test_source_multiline_block.py
@@ -12,10 +12,13 @@ def test_getstartingblock_multiline():
see hhatto/autopep8#307). It was considered better to just move this single test to its own
file and exclude it from autopep8 than try to complicate things.
"""
+
class A(object):
+
def __init__(self, *args):
frame = sys._getframe(1)
self.source = _pytest._code.Frame(frame).statement
+
# fmt: off
x = A('x',
'y'
diff --git a/testing/logging/test_fixture.py b/testing/logging/test_fixture.py
index 8d9ae6b5..a4f594b4 100644
--- a/testing/logging/test_fixture.py
+++ b/testing/logging/test_fixture.py
@@ -103,6 +103,7 @@ def logging_during_setup_and_teardown(caplog):
caplog.set_level("INFO")
logger.info("a_setup_log")
yield
+
logger.info("a_teardown_log")
assert [x.message for x in caplog.get_records("teardown")] == ["a_teardown_log"]
diff --git a/testing/python/fixture.py b/testing/python/fixture.py
index 023a40d8..f42d516c 100644
--- a/testing/python/fixture.py
+++ b/testing/python/fixture.py
@@ -707,6 +707,7 @@ class TestRequestBasic(object):
warning_expectation = pytest.warns(DeprecationWarning)
else:
# see #1830 for a cleaner way to accomplish this
+
@contextlib.contextmanager
def expecting_no_warning():
yield
diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py
index e181d313..b5c981c3 100644
--- a/testing/python/metafunc.py
+++ b/testing/python/metafunc.py
@@ -19,6 +19,7 @@ class TestMetafunc(object):
# the unit tests of this class check if things work correctly
# on the funcarg level, so we don't need a full blown
# initiliazation
+
class FixtureInfo(object):
name2fixturedefs = None
diff --git a/testing/test_argcomplete.py b/testing/test_argcomplete.py
index b042de5c..026b550d 100644
--- a/testing/test_argcomplete.py
+++ b/testing/test_argcomplete.py
@@ -27,8 +27,10 @@ def _wrapcall(*args, **kargs):
try:
if sys.version_info > (2, 7):
return subprocess.check_output(*args, **kargs).decode().splitlines()
+
if "stdout" in kargs:
raise ValueError("stdout argument not allowed, it will be overridden.")
+
process = subprocess.Popen(stdout=subprocess.PIPE, *args, **kargs)
output, unused_err = process.communicate()
retcode = process.poll()
@@ -37,7 +39,9 @@ def _wrapcall(*args, **kargs):
if cmd is None:
cmd = args[0]
raise subprocess.CalledProcessError(retcode, cmd)
+
return output.decode().splitlines()
+
except subprocess.CalledProcessError:
return []
diff --git a/testing/test_assertion.py b/testing/test_assertion.py
index 6cf5b531..099efb7c 100644
--- a/testing/test_assertion.py
+++ b/testing/test_assertion.py
@@ -21,6 +21,7 @@ def mock_config():
def getoption(self, name):
if name == "verbose":
return self.verbose
+
raise KeyError("Not mocked out: %s" % name)
return Config()
@@ -390,9 +391,7 @@ class TestAssert_reprcompare(object):
? ^
+ set([0, 2])
? ^
- """
- if not PY3
- else """
+ """ if not PY3 else """
Full diff:
- {0, 1}
? ^
@@ -1035,6 +1034,7 @@ def test_AssertionError_message(testdir):
@pytest.mark.skipif(PY3, reason="This bug does not exist on PY3")
def test_set_with_unsortable_elements():
# issue #718
+
class UnsortableKey(object):
def __init__(self, name):
diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py
index aa752dab..6a7d85a4 100644
--- a/testing/test_assertrewrite.py
+++ b/testing/test_assertrewrite.py
@@ -13,9 +13,7 @@ import pytest
import _pytest._code
from _pytest.assertion import util
from _pytest.assertion.rewrite import (
- rewrite_asserts,
- PYTEST_TAG,
- AssertionRewritingHook,
+ rewrite_asserts, PYTEST_TAG, AssertionRewritingHook
)
from _pytest.main import EXIT_NOTESTSCOLLECTED
@@ -59,7 +57,9 @@ def getmsg(f, extra_ns=None, must_pass=False):
s = str(sys.exc_info()[1])
if not s.startswith("assert"):
return "AssertionError: " + s
+
return s
+
else:
if not must_pass:
pytest.fail("function didn't raise at all")
@@ -959,6 +959,7 @@ class TestAssertionRewriteHookDetails(object):
e = IOError()
e.errno = 10
raise e
+
yield # noqa
monkeypatch.setattr(atomicwrites, "atomic_write", atomic_write_failed)
diff --git a/testing/test_capture.py b/testing/test_capture.py
index 5cedc99b..ab73a55a 100644
--- a/testing/test_capture.py
+++ b/testing/test_capture.py
@@ -851,6 +851,7 @@ def test_dontreadfrominput_buffer_python2():
def tmpfile(testdir):
f = testdir.makepyfile("").open("wb+")
yield f
+
if not f.closed:
f.close()
@@ -907,6 +908,7 @@ def lsof_check():
# about UnicodeDecodeError, see note on pytester
pytest.skip("could not run 'lsof'")
yield
+
out2 = py.process.cmdexec("lsof -p %d" % pid)
len1 = len([x for x in out.split("\n") if "REG" in x])
len2 = len([x for x in out2.split("\n") if "REG" in x])
@@ -1003,6 +1005,7 @@ def saved_fd(fd):
new_fd = os.dup(fd)
try:
yield
+
finally:
os.dup2(new_fd, fd)
os.close(new_fd)
@@ -1017,6 +1020,7 @@ class TestStdCapture(object):
cap.start_capturing()
try:
yield cap
+
finally:
cap.stop_capturing()
diff --git a/testing/test_compat.py b/testing/test_compat.py
index 550a8f1b..2a7dc21d 100644
--- a/testing/test_compat.py
+++ b/testing/test_compat.py
@@ -31,6 +31,7 @@ def test_real_func_loop_limit():
def __getattr__(self, attr):
if not self.left:
raise RuntimeError("its over")
+
self.left -= 1
return self
diff --git a/testing/test_config.py b/testing/test_config.py
index 56a51514..77c027a3 100644
--- a/testing/test_config.py
+++ b/testing/test_config.py
@@ -5,10 +5,7 @@ import pytest
import _pytest._code
from _pytest.config import (
- getcfg,
- get_common_ancestor,
- determine_setup,
- _iter_rewritable_modules,
+ getcfg, get_common_ancestor, determine_setup, _iter_rewritable_modules
)
from _pytest.main import EXIT_NOTESTSCOLLECTED
diff --git a/testing/test_conftest.py b/testing/test_conftest.py
index 61b64097..c253250b 100644
--- a/testing/test_conftest.py
+++ b/testing/test_conftest.py
@@ -379,6 +379,7 @@ class TestConftestVisibility(object):
# N.B.: "swc" stands for "subdir with conftest.py"
# "snc" stands for "subdir no [i.e. without] conftest.py"
+
@pytest.mark.parametrize(
"chdir,testarg,expect_ntests_passed",
[
diff --git a/testing/test_junitxml.py b/testing/test_junitxml.py
index a1a6ccc0..4fc877e8 100644
--- a/testing/test_junitxml.py
+++ b/testing/test_junitxml.py
@@ -501,7 +501,8 @@ class TestPython(object):
)
fnode = tnode.find_first_by_tag("skipped")
fnode.assert_attr(message="expected test failure")
- # assert "ValueError" in fnode.toxml()
+
+ # assert "ValueError" in fnode.toxml()
def test_xfailure_xpass(self, testdir):
testdir.makepyfile(
diff --git a/testing/test_mark.py b/testing/test_mark.py
index e96af888..cc05c216 100644
--- a/testing/test_mark.py
+++ b/testing/test_mark.py
@@ -4,10 +4,7 @@ import sys
import pytest
from _pytest.mark import (
- MarkGenerator as Mark,
- ParameterSet,
- transfer_markers,
- EMPTY_PARAMETERSET_OPTION,
+ MarkGenerator as Mark, ParameterSet, transfer_markers, EMPTY_PARAMETERSET_OPTION
)
ignore_markinfo = pytest.mark.filterwarnings(
diff --git a/testing/test_monkeypatch.py b/testing/test_monkeypatch.py
index c298ce0d..e1d18814 100644
--- a/testing/test_monkeypatch.py
+++ b/testing/test_monkeypatch.py
@@ -12,6 +12,7 @@ def mp():
cwd = os.getcwd()
sys_path = list(sys.path)
yield MonkeyPatch()
+
sys.path[:] = sys_path
os.chdir(cwd)
@@ -323,6 +324,7 @@ class SampleNewInherit(SampleNew):
class SampleOld(object):
# oldstyle on python2
+
@staticmethod
def hello():
return True
diff --git a/testing/test_parseopt.py b/testing/test_parseopt.py
index a8fc6d72..abc1d629 100644
--- a/testing/test_parseopt.py
+++ b/testing/test_parseopt.py
@@ -184,6 +184,7 @@ class TestParser(object):
def defaultget(option):
if not hasattr(option, "type"):
return
+
if option.type is int:
option.default = 42
elif option.type is str:
@@ -268,6 +269,7 @@ class TestParser(object):
assert "--func-args, --doit foo" in help
# testing would be more helpful with all help generated
+
def test_drop_short_help1(self, parser, capsys):
group = parser.getgroup("general")
group.addoption("--doit", "--func-args", action="store_true", help="foo")
diff --git a/testing/test_pdb.py b/testing/test_pdb.py
index 615d52e8..230097ee 100644
--- a/testing/test_pdb.py
+++ b/testing/test_pdb.py
@@ -24,6 +24,7 @@ def custom_pdb_calls():
called = []
# install dummy debugger class and track which methods were called on it
+
class _CustomPdb(object):
def __init__(self, *args, **kwargs):
@@ -44,6 +45,7 @@ def custom_debugger_hook():
called = []
# install dummy debugger class and track which methods were called on it
+
class _CustomDebugger(object):
def __init__(self, *args, **kwargs):
@@ -61,6 +63,7 @@ def custom_debugger_hook():
_pytest._CustomDebugger = _CustomDebugger
yield called
+
del _pytest._CustomDebugger
@@ -161,6 +164,7 @@ class TestPDB(object):
def flush(child):
if platform.system() == "Darwin":
return
+
if child.isalive():
child.wait()
diff --git a/testing/test_resultlog.py b/testing/test_resultlog.py
index 173384ff..009b4b3d 100644
--- a/testing/test_resultlog.py
+++ b/testing/test_resultlog.py
@@ -6,10 +6,7 @@ import py
import pytest
from _pytest.nodes import Node, Item, FSCollector
from _pytest.resultlog import (
- generic_path,
- ResultLog,
- pytest_configure,
- pytest_unconfigure,
+ generic_path, ResultLog, pytest_configure, pytest_unconfigure
)
@@ -81,6 +78,7 @@ class TestWithFunctionIntegration(object):
# XXX (hpk) i think that the resultlog plugin should
# provide a Parser object so that one can remain
# ignorant regarding formatting details.
+
def getresultlog(self, testdir, arg):
resultlog = testdir.tmpdir.join("resultlog")
testdir.plugins.append("resultlog")
@@ -143,6 +141,7 @@ class TestWithFunctionIntegration(object):
# at the end of the run or a failing hook invocation
try:
raise ValueError
+
except ValueError:
excinfo = _pytest._code.ExceptionInfo()
reslog = ResultLog(None, py.io.TextIO())
diff --git a/testing/test_runner.py b/testing/test_runner.py
index 26493de6..ee42fa56 100644
--- a/testing/test_runner.py
+++ b/testing/test_runner.py
@@ -67,6 +67,7 @@ class TestSetupState(object):
def test_teardown_multiple_fail(self, testdir):
# Ensure the first exception is the one which is re-raised.
# Ideally both would be reported however.
+
def fin1():
raise Exception("oops1")
@@ -110,7 +111,8 @@ class BaseFunctionalTests(object):
assert rep.failed
assert rep.when == "call"
assert rep.outcome == "failed"
- # assert isinstance(rep.longrepr, ReprExceptionInfo)
+
+ # assert isinstance(rep.longrepr, ReprExceptionInfo)
def test_skipfunction(self, testdir):
reports = testdir.runitem(
@@ -125,12 +127,13 @@ class BaseFunctionalTests(object):
assert not rep.passed
assert rep.skipped
assert rep.outcome == "skipped"
- # assert rep.skipped.when == "call"
- # assert rep.skipped.when == "call"
- # assert rep.skipped == "%sreason == "hello"
- # assert rep.skipped.location.lineno == 3
- # assert rep.skipped.location.path
- # assert not rep.skipped.failurerepr
+
+ # assert rep.skipped.when == "call"
+ # assert rep.skipped.when == "call"
+ # assert rep.skipped == "%sreason == "hello"
+ # assert rep.skipped.location.lineno == 3
+ # assert rep.skipped.location.path
+ # assert not rep.skipped.failurerepr
def test_skip_in_setup_function(self, testdir):
reports = testdir.runitem(
@@ -187,8 +190,9 @@ class BaseFunctionalTests(object):
assert not rep.passed
assert rep.failed
assert rep.when == "teardown"
- # assert rep.longrepr.reprcrash.lineno == 3
- # assert rep.longrepr.reprtraceback.reprentries
+
+ # assert rep.longrepr.reprcrash.lineno == 3
+ # assert rep.longrepr.reprtraceback.reprentries
def test_custom_failure_repr(self, testdir):
testdir.makepyfile(
@@ -210,10 +214,11 @@ class BaseFunctionalTests(object):
assert not rep.skipped
assert not rep.passed
assert rep.failed
- # assert rep.outcome.when == "call"
- # assert rep.failed.where.lineno == 3
- # assert rep.failed.where.path.basename == "test_func.py"
- # assert rep.failed.failurerepr == "hello"
+
+ # assert rep.outcome.when == "call"
+ # assert rep.failed.where.lineno == 3
+ # assert rep.failed.where.path.basename == "test_func.py"
+ # assert rep.failed.failurerepr == "hello"
def test_teardown_final_returncode(self, testdir):
rec = testdir.inline_runsource(
@@ -342,10 +347,11 @@ class BaseFunctionalTests(object):
assert not rep.skipped
assert not rep.passed
assert rep.failed
- # assert rep.outcome.when == "setup"
- # assert rep.outcome.where.lineno == 3
- # assert rep.outcome.where.path.basename == "test_func.py"
- # assert instanace(rep.failed.failurerepr, PythonFailureRepr)
+
+ # assert rep.outcome.when == "setup"
+ # assert rep.outcome.where.lineno == 3
+ # assert rep.outcome.where.path.basename == "test_func.py"
+ # assert instanace(rep.failed.failurerepr, PythonFailureRepr)
def test_systemexit_does_not_bail_out(self, testdir):
try:
@@ -523,6 +529,7 @@ def test_outcomeexception_passes_except_Exception():
with pytest.raises(outcomes.OutcomeException):
try:
raise outcomes.OutcomeException("test")
+
except Exception:
pass
@@ -776,6 +783,7 @@ def test_makereport_getsource_dynamic_code(testdir, monkeypatch):
# Can be triggered by dynamically created functions
if obj.__name__ == "foo":
raise IndexError()
+
return original_findsource(obj, *args, **kwargs)
monkeypatch.setattr(inspect, "findsource", findsource)
@@ -802,6 +810,7 @@ def test_store_except_info_on_error():
sys.last_traceback and friends.
"""
# Simulate item that might raise a specific exception, depending on `raise_error` class var
+
class ItemMightRaise(object):
nodeid = "item_that_raises"
raise_error = True
diff --git a/testing/test_session.py b/testing/test_session.py
index 4a594009..51748a3e 100644
--- a/testing/test_session.py
+++ b/testing/test_session.py
@@ -34,10 +34,11 @@ class SessionTests(object):
assert end(failed[1]) == "test_other"
itemstarted = reprec.getcalls("pytest_itemcollected")
assert len(itemstarted) == 4
- # XXX check for failing funcarg setup
- # colreports = reprec.getcalls("pytest_collectreport")
- # assert len(colreports) == 4
- # assert colreports[1].report.failed
+
+ # XXX check for failing funcarg setup
+ # colreports = reprec.getcalls("pytest_collectreport")
+ # assert len(colreports) == 4
+ # assert colreports[1].report.failed
def test_nested_import_error(self, testdir):
tfile = testdir.makepyfile(
@@ -194,7 +195,8 @@ class TestNewSession(SessionTests):
passed, skipped, failed = reprec.countoutcomes()
assert failed == skipped == 0
assert passed == 7
- # also test listnames() here ...
+
+ # also test listnames() here ...
def test_collect_only_with_various_situations(self, testdir):
p = testdir.makepyfile(
@@ -248,9 +250,11 @@ def test_plugin_specify(testdir):
testdir.parseconfig("-p", "nqweotexistent")
""",
)
- # pytest.raises(ImportError,
- # "config.do_configure(config)"
- # )
+
+
+# pytest.raises(ImportError,
+# "config.do_configure(config)"
+# )
def test_plugin_already_exists(testdir):
diff --git a/testing/test_skipping.py b/testing/test_skipping.py
index 5d970e2f..9c6571b5 100644
--- a/testing/test_skipping.py
+++ b/testing/test_skipping.py
@@ -253,9 +253,10 @@ class TestXFail(object):
"""
)
testdir.runpytest(p, "-v")
- # result.stdout.fnmatch_lines([
- # "*HINT*use*-r*"
- # ])
+
+ # result.stdout.fnmatch_lines([
+ # "*HINT*use*-r*"
+ # ])
def test_xfail_not_run_xfail_reporting(self, testdir):
p = testdir.makepyfile(
diff --git a/testing/test_unittest.py b/testing/test_unittest.py
index ab8ec927..acb5dad0 100644
--- a/testing/test_unittest.py
+++ b/testing/test_unittest.py
@@ -468,9 +468,7 @@ class TestTrialUnittest(object):
"*i2wanto*",
"*sys.version_info*",
"*skip_in_method*",
- "*1 failed*4 skipped*3 xfailed*"
- if should_fail
- else "*4 skipped*3 xfail*1 xpass*",
+ "*1 failed*4 skipped*3 xfailed*" if should_fail else "*4 skipped*3 xfail*1 xpass*",
]
)
assert result.ret == (1 if should_fail else 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment