Merge pull request #7472 from bluetech/cleanups-4

Some minor fixes & type annotations
This commit is contained in:
Ran Benita
2020-07-11 19:05:07 +03:00
committed by GitHub
44 changed files with 360 additions and 349 deletions

View File

@@ -752,7 +752,7 @@ raise ValueError()
from _pytest._code.code import Code
monkeypatch.setattr(Code, "path", "bogus")
excinfo.traceback[0].frame.code.path = "bogus" # type: ignore[misc] # noqa: F821
excinfo.traceback[0].frame.code.path = "bogus" # type: ignore[misc]
p = FormattedExcinfo(style="short")
reprtb = p.repr_traceback_entry(excinfo.traceback[-2])
lines = reprtb.lines

View File

@@ -16,4 +16,4 @@ def test_comparing_two_different_data_classes() -> None:
left = SimpleDataObjectOne(1, "b")
right = SimpleDataObjectTwo(1, "c")
assert left != right # type: ignore[comparison-overlap] # noqa: F821
assert left != right # type: ignore[comparison-overlap]

View File

@@ -34,8 +34,8 @@ def test_exceptions() -> None:
raise self.ex
class BrokenReprException(Exception):
__str__ = None # type: ignore[assignment] # noqa: F821
__repr__ = None # type: ignore[assignment] # noqa: F821
__str__ = None # type: ignore[assignment]
__repr__ = None # type: ignore[assignment]
assert "Exception" in saferepr(BrokenRepr(Exception("broken")))
s = saferepr(BrokenReprException("really broken"))
@@ -44,7 +44,7 @@ def test_exceptions() -> None:
none = None
try:
none() # type: ignore[misc] # noqa: F821
none() # type: ignore[misc]
except BaseException as exc:
exp_exc = repr(exc)
obj = BrokenRepr(BrokenReprException("omg even worse"))
@@ -139,7 +139,7 @@ def test_big_repr():
def test_repr_on_newstyle() -> None:
class Function:
def __repr__(self):
return "<%s>" % (self.name) # type: ignore[attr-defined] # noqa: F821
return "<%s>" % (self.name) # type: ignore[attr-defined]
assert saferepr(Function())

View File

@@ -675,7 +675,11 @@ class TestFunction:
pass
"""
)
assert [x.originalname for x in items] == [
originalnames = []
for x in items:
assert isinstance(x, pytest.Function)
originalnames.append(x.originalname)
assert originalnames == [
"test_func",
"test_func",
"test_no_param",
@@ -720,10 +724,10 @@ class TestSorting:
assert fn1 != fn3
for fn in fn1, fn2, fn3:
assert fn != 3 # type: ignore[comparison-overlap] # noqa: F821
assert fn != 3 # type: ignore[comparison-overlap]
assert fn != modcol
assert fn != [1, 2, 3] # type: ignore[comparison-overlap] # noqa: F821
assert [1, 2, 3] != fn # type: ignore[comparison-overlap] # noqa: F821
assert fn != [1, 2, 3] # type: ignore[comparison-overlap]
assert [1, 2, 3] != fn # type: ignore[comparison-overlap]
assert modcol != fn
def test_allow_sane_sorting_for_decorators(self, testdir):

View File

@@ -3850,7 +3850,7 @@ class TestScopeOrdering:
)
testdir.runpytest()
# actual fixture execution differs: dependent fixtures must be created first ("my_tmpdir")
FIXTURE_ORDER = pytest.FIXTURE_ORDER # type: ignore[attr-defined] # noqa: F821
FIXTURE_ORDER = pytest.FIXTURE_ORDER # type: ignore[attr-defined]
assert FIXTURE_ORDER == "s1 my_tmpdir_factory p1 m1 my_tmpdir f1 f2".split()
def test_func_closure_module(self, testdir):
@@ -4159,7 +4159,7 @@ def test_fixture_duplicated_arguments() -> None:
"""Raise error if there are positional and keyword arguments for the same parameter (#1682)."""
with pytest.raises(TypeError) as excinfo:
@pytest.fixture("session", scope="session") # type: ignore[call-overload] # noqa: F821
@pytest.fixture("session", scope="session") # type: ignore[call-overload]
def arg(arg):
pass
@@ -4171,7 +4171,7 @@ def test_fixture_duplicated_arguments() -> None:
with pytest.raises(TypeError) as excinfo:
@pytest.fixture( # type: ignore[call-overload] # noqa: F821
@pytest.fixture( # type: ignore[call-overload]
"function",
["p1"],
True,
@@ -4199,7 +4199,7 @@ def test_fixture_with_positionals() -> None:
with pytest.warns(pytest.PytestDeprecationWarning) as warnings:
@pytest.fixture("function", [0], True) # type: ignore[call-overload] # noqa: F821
@pytest.fixture("function", [0], True) # type: ignore[call-overload]
def fixture_with_positionals():
pass
@@ -4213,7 +4213,7 @@ def test_fixture_with_positionals() -> None:
def test_fixture_with_too_many_positionals() -> None:
with pytest.raises(TypeError) as excinfo:
@pytest.fixture("function", [0], True, ["id"], "name", "extra") # type: ignore[call-overload] # noqa: F821
@pytest.fixture("function", [0], True, ["id"], "name", "extra") # type: ignore[call-overload]
def fixture_with_positionals():
pass

View File

@@ -3,9 +3,12 @@ import re
import sys
import textwrap
from typing import Any
from typing import cast
from typing import Dict
from typing import Iterator
from typing import List
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Union
@@ -74,7 +77,7 @@ class TestMetafunc:
pytest.raises(ValueError, lambda: metafunc.parametrize("y", [5, 6]))
with pytest.raises(TypeError, match="^ids must be a callable or an iterable$"):
metafunc.parametrize("y", [5, 6], ids=42) # type: ignore[arg-type] # noqa: F821
metafunc.parametrize("y", [5, 6], ids=42) # type: ignore[arg-type]
def test_parametrize_error_iterator(self) -> None:
def func(x):
@@ -92,7 +95,7 @@ class TestMetafunc:
metafunc = self.Metafunc(func)
# When the input is an iterator, only len(args) are taken,
# so the bad Exc isn't reached.
metafunc.parametrize("x", [1, 2], ids=gen()) # type: ignore[arg-type] # noqa: F821
metafunc.parametrize("x", [1, 2], ids=gen()) # type: ignore[arg-type]
assert [(x.funcargs, x.id) for x in metafunc._calls] == [
({"x": 1}, "0"),
({"x": 2}, "2"),
@@ -104,7 +107,7 @@ class TestMetafunc:
r" Exc\(from_gen\) \(type: <class .*Exc'>\) at index 2"
),
):
metafunc.parametrize("x", [1, 2, 3], ids=gen()) # type: ignore[arg-type] # noqa: F821
metafunc.parametrize("x", [1, 2, 3], ids=gen()) # type: ignore[arg-type]
def test_parametrize_bad_scope(self) -> None:
def func(x):
@@ -115,7 +118,7 @@ class TestMetafunc:
fail.Exception,
match=r"parametrize\(\) call in func got an unexpected scope value 'doggy'",
):
metafunc.parametrize("x", [1], scope="doggy") # type: ignore[arg-type] # noqa: F821
metafunc.parametrize("x", [1], scope="doggy") # type: ignore[arg-type]
def test_parametrize_request_name(self, testdir: Testdir) -> None:
"""Show proper error when 'request' is used as a parameter name in parametrize (#6183)"""
@@ -138,12 +141,15 @@ class TestMetafunc:
class DummyFixtureDef:
scope = attr.ib()
fixtures_defs = dict(
session_fix=[DummyFixtureDef("session")],
package_fix=[DummyFixtureDef("package")],
module_fix=[DummyFixtureDef("module")],
class_fix=[DummyFixtureDef("class")],
func_fix=[DummyFixtureDef("function")],
fixtures_defs = cast(
Dict[str, Sequence[fixtures.FixtureDef]],
dict(
session_fix=[DummyFixtureDef("session")],
package_fix=[DummyFixtureDef("package")],
module_fix=[DummyFixtureDef("module")],
class_fix=[DummyFixtureDef("class")],
func_fix=[DummyFixtureDef("function")],
),
)
# use arguments to determine narrow scope; the cause of the bug is that it would look on all
@@ -669,7 +675,7 @@ class TestMetafunc:
fail.Exception,
match="In func: expected Sequence or boolean for indirect, got dict",
):
metafunc.parametrize("x, y", [("a", "b")], indirect={}) # type: ignore[arg-type] # noqa: F821
metafunc.parametrize("x, y", [("a", "b")], indirect={}) # type: ignore[arg-type]
def test_parametrize_indirect_list_functional(self, testdir: Testdir) -> None:
"""

View File

@@ -8,7 +8,7 @@ from _pytest.outcomes import Failed
class TestRaises:
def test_check_callable(self) -> None:
with pytest.raises(TypeError, match=r".* must be callable"):
pytest.raises(RuntimeError, "int('qwe')") # type: ignore[call-overload] # noqa: F821
pytest.raises(RuntimeError, "int('qwe')") # type: ignore[call-overload]
def test_raises(self):
excinfo = pytest.raises(ValueError, int, "qwe")
@@ -30,7 +30,7 @@ class TestRaises:
def test_raises_falsey_type_error(self) -> None:
with pytest.raises(TypeError):
with pytest.raises(AssertionError, match=0): # type: ignore[call-overload] # noqa: F821
with pytest.raises(AssertionError, match=0): # type: ignore[call-overload]
raise AssertionError("ohai")
def test_raises_repr_inflight(self):
@@ -128,11 +128,11 @@ class TestRaises:
def test_noclass(self) -> None:
with pytest.raises(TypeError):
pytest.raises("wrong", lambda: None) # type: ignore[call-overload] # noqa: F821
pytest.raises("wrong", lambda: None) # type: ignore[call-overload]
def test_invalid_arguments_to_raises(self) -> None:
with pytest.raises(TypeError, match="unknown"):
with pytest.raises(TypeError, unknown="bogus"): # type: ignore[call-overload] # noqa: F821
with pytest.raises(TypeError, unknown="bogus"): # type: ignore[call-overload]
raise ValueError()
def test_tuple(self):
@@ -262,12 +262,12 @@ class TestRaises:
assert False, "via __class__"
with pytest.raises(AssertionError) as excinfo:
with pytest.raises(CrappyClass()): # type: ignore[call-overload] # noqa: F821
with pytest.raises(CrappyClass()): # type: ignore[call-overload]
pass
assert "via __class__" in excinfo.value.args[0]
def test_raises_context_manager_with_kwargs(self):
with pytest.raises(TypeError) as excinfo:
with pytest.raises(Exception, foo="bar"): # type: ignore[call-overload] # noqa: F821
with pytest.raises(Exception, foo="bar"): # type: ignore[call-overload]
pass
assert "Unexpected keyword arguments" in str(excinfo.value)

View File

@@ -51,7 +51,7 @@ def getmsg(
exec(code, ns)
func = ns[f.__name__]
try:
func() # type: ignore[operator] # noqa: F821
func() # type: ignore[operator]
except AssertionError:
if must_pass:
pytest.fail("shouldn't have raised")
@@ -174,7 +174,7 @@ class TestAssertionRewrite:
assert getmsg(f3, {"a_global": False}) == "assert False"
def f4() -> None:
assert sys == 42 # type: ignore[comparison-overlap] # noqa: F821
assert sys == 42 # type: ignore[comparison-overlap]
verbose = request.config.getoption("verbose")
msg = getmsg(f4, {"sys": sys})
@@ -188,7 +188,7 @@ class TestAssertionRewrite:
assert msg == "assert sys == 42"
def f5() -> None:
assert cls == 42 # type: ignore[name-defined] # noqa: F821
assert cls == 42 # type: ignore[name-defined] # noqa: F821
class X:
pass
@@ -684,7 +684,7 @@ class TestAssertionRewrite:
def test_formatchar(self) -> None:
def f() -> None:
assert "%test" == "test" # type: ignore[comparison-overlap] # noqa: F821
assert "%test" == "test" # type: ignore[comparison-overlap]
msg = getmsg(f)
assert msg is not None
@@ -1264,7 +1264,7 @@ class TestEarlyRewriteBailout:
# use default patterns, otherwise we inherit pytest's testing config
hook.fnpats[:] = ["test_*.py", "*_test.py"]
monkeypatch.setattr(hook, "_find_spec", spy_find_spec)
hook.set_session(StubSession()) # type: ignore[arg-type] # noqa: F821
hook.set_session(StubSession()) # type: ignore[arg-type]
testdir.syspathinsert()
return hook

View File

@@ -1537,7 +1537,7 @@ def test_encodedfile_writelines(tmpfile: BinaryIO) -> None:
ef = capture.EncodedFile(tmpfile, encoding="utf-8")
with pytest.raises(TypeError):
ef.writelines([b"line1", b"line2"])
assert ef.writelines(["line3", "line4"]) is None # type: ignore[func-returns-value] # noqa: F821
assert ef.writelines(["line3", "line4"]) is None # type: ignore[func-returns-value]
ef.flush()
tmpfile.seek(0)
assert tmpfile.read() == b"line3line4"

View File

@@ -41,10 +41,10 @@ class TestCollector:
for fn in fn1, fn2, fn3:
assert isinstance(fn, pytest.Function)
assert fn != 3 # type: ignore[comparison-overlap] # noqa: F821
assert fn != 3 # type: ignore[comparison-overlap]
assert fn != modcol
assert fn != [1, 2, 3] # type: ignore[comparison-overlap] # noqa: F821
assert [1, 2, 3] != fn # type: ignore[comparison-overlap] # noqa: F821
assert fn != [1, 2, 3] # type: ignore[comparison-overlap]
assert [1, 2, 3] != fn # type: ignore[comparison-overlap]
assert modcol != fn
assert testdir.collect_by_name(modcol, "doesnotexist") is None

View File

@@ -1602,7 +1602,7 @@ def test_invocation_args(testdir):
# args cannot be None
with pytest.raises(TypeError):
Config.InvocationParams(args=None, plugins=None, dir=Path()) # type: ignore[arg-type] # noqa: F821
Config.InvocationParams(args=None, plugins=None, dir=Path()) # type: ignore[arg-type]
@pytest.mark.parametrize(

View File

@@ -1490,7 +1490,7 @@ def test_warning_on_unwrap_of_broken_object(
pytest.PytestWarning, match="^Got KeyError.* when unwrapping"
):
with pytest.raises(KeyError):
inspect.unwrap(bad_instance, stop=stop) # type: ignore[arg-type] # noqa: F821
inspect.unwrap(bad_instance, stop=stop) # type: ignore[arg-type]
assert inspect.unwrap.__module__ == "inspect"

View File

@@ -1124,7 +1124,7 @@ def test_unicode_issue368(testdir) -> None:
node_reporter.append_skipped(test_report)
test_report.longrepr = "filename", 1, "Skipped: 卡嘣嘣"
node_reporter.append_skipped(test_report)
test_report.wasxfail = ustr # type: ignore[attr-defined] # noqa: F821
test_report.wasxfail = ustr # type: ignore[attr-defined]
node_reporter.append_skipped(test_report)
log.pytest_sessionfinish()

View File

@@ -20,7 +20,7 @@ class TestMark:
def test_pytest_mark_notcallable(self) -> None:
mark = Mark()
with pytest.raises(TypeError):
mark() # type: ignore[operator] # noqa: F821
mark() # type: ignore[operator]
def test_mark_with_param(self):
def some_function(abc):
@@ -31,10 +31,10 @@ class TestMark:
assert pytest.mark.foo(some_function) is some_function
marked_with_args = pytest.mark.foo.with_args(some_function)
assert marked_with_args is not some_function # type: ignore[comparison-overlap] # noqa: F821
assert marked_with_args is not some_function # type: ignore[comparison-overlap]
assert pytest.mark.foo(SomeClass) is SomeClass
assert pytest.mark.foo.with_args(SomeClass) is not SomeClass # type: ignore[comparison-overlap] # noqa: F821
assert pytest.mark.foo.with_args(SomeClass) is not SomeClass # type: ignore[comparison-overlap]
def test_pytest_mark_name_starts_with_underscore(self):
mark = Mark()
@@ -1077,7 +1077,7 @@ def test_markers_from_parametrize(testdir):
def test_pytest_param_id_requires_string() -> None:
with pytest.raises(TypeError) as excinfo:
pytest.param(id=True) # type: ignore[arg-type] # noqa: F821
pytest.param(id=True) # type: ignore[arg-type]
(msg,) = excinfo.value.args
assert msg == "Expected id to be a string, got <class 'bool'>: True"

View File

@@ -25,9 +25,9 @@ def test_ischildnode(baseid: str, nodeid: str, expected: bool) -> None:
def test_node_from_parent_disallowed_arguments() -> None:
with pytest.raises(TypeError, match="session is"):
nodes.Node.from_parent(None, session=None) # type: ignore[arg-type] # noqa: F821
nodes.Node.from_parent(None, session=None) # type: ignore[arg-type]
with pytest.raises(TypeError, match="config is"):
nodes.Node.from_parent(None, config=None) # type: ignore[arg-type] # noqa: F821
nodes.Node.from_parent(None, config=None) # type: ignore[arg-type]
def test_std_warn_not_pytestwarning(testdir: Testdir) -> None:
@@ -38,7 +38,7 @@ def test_std_warn_not_pytestwarning(testdir: Testdir) -> None:
"""
)
with pytest.raises(ValueError, match=".*instance of PytestWarning.*"):
items[0].warn(UserWarning("some warning"))
items[0].warn(UserWarning("some warning")) # type: ignore[arg-type]
def test__check_initialpaths_for_relpath() -> None:

View File

@@ -484,20 +484,20 @@ def test_linematcher_with_nonlist() -> None:
lm = LineMatcher([])
with pytest.raises(TypeError, match="invalid type for lines2: set"):
lm.fnmatch_lines(set()) # type: ignore[arg-type] # noqa: F821
lm.fnmatch_lines(set()) # type: ignore[arg-type]
with pytest.raises(TypeError, match="invalid type for lines2: dict"):
lm.fnmatch_lines({}) # type: ignore[arg-type] # noqa: F821
lm.fnmatch_lines({}) # type: ignore[arg-type]
with pytest.raises(TypeError, match="invalid type for lines2: set"):
lm.re_match_lines(set()) # type: ignore[arg-type] # noqa: F821
lm.re_match_lines(set()) # type: ignore[arg-type]
with pytest.raises(TypeError, match="invalid type for lines2: dict"):
lm.re_match_lines({}) # type: ignore[arg-type] # noqa: F821
lm.re_match_lines({}) # type: ignore[arg-type]
with pytest.raises(TypeError, match="invalid type for lines2: Source"):
lm.fnmatch_lines(Source()) # type: ignore[arg-type] # noqa: F821
lm.fnmatch_lines(Source()) # type: ignore[arg-type]
lm.fnmatch_lines([])
lm.fnmatch_lines(())
lm.fnmatch_lines("")
assert lm._getlines({}) == {} # type: ignore[arg-type,comparison-overlap] # noqa: F821
assert lm._getlines(set()) == set() # type: ignore[arg-type,comparison-overlap] # noqa: F821
assert lm._getlines({}) == {} # type: ignore[arg-type,comparison-overlap]
assert lm._getlines(set()) == set() # type: ignore[arg-type,comparison-overlap]
assert lm._getlines(Source()) == []
assert lm._getlines(Source("pass\npass")) == ["pass", "pass"]

View File

@@ -884,7 +884,7 @@ def test_store_except_info_on_error() -> None:
raise IndexError("TEST")
try:
runner.pytest_runtest_call(ItemMightRaise()) # type: ignore[arg-type] # noqa: F821
runner.pytest_runtest_call(ItemMightRaise()) # type: ignore[arg-type]
except IndexError:
pass
# Check that exception info is stored on sys
@@ -895,7 +895,7 @@ def test_store_except_info_on_error() -> None:
# The next run should clear the exception info stored by the previous run
ItemMightRaise.raise_error = False
runner.pytest_runtest_call(ItemMightRaise()) # type: ignore[arg-type] # noqa: F821
runner.pytest_runtest_call(ItemMightRaise()) # type: ignore[arg-type]
assert not hasattr(sys, "last_type")
assert not hasattr(sys, "last_value")
assert not hasattr(sys, "last_traceback")

View File

@@ -47,7 +47,7 @@ def test_store() -> None:
# Can't accidentally add attributes to store object itself.
with pytest.raises(AttributeError):
store.foo = "nope" # type: ignore[attr-defined] # noqa: F821
store.foo = "nope" # type: ignore[attr-defined]
# No interaction with anoter store.
store2 = Store()

View File

@@ -1699,7 +1699,7 @@ def test_summary_stats(
class fake_session:
testscollected = 0
tr._session = fake_session # type: ignore[assignment] # noqa: F821
tr._session = fake_session # type: ignore[assignment]
assert tr._is_last_item
# Reset cache.