pre-commit run pyupgrade --all-files

This commit is contained in:
Anthony Sottile 2019-06-02 15:32:00 -07:00 committed by Bruno Oliveira
parent 3f1ec520fc
commit a91fe1fedd
100 changed files with 739 additions and 801 deletions

View File

@ -62,9 +62,9 @@ source_suffix = ".rst"
master_doc = "contents" master_doc = "contents"
# General information about the project. # General information about the project.
project = u"pytest" project = "pytest"
year = datetime.datetime.utcnow().year year = datetime.datetime.utcnow().year
copyright = u"20152019 , holger krekel and pytest-dev team" copyright = "20152019 , holger krekel and pytest-dev team"
# The language for content autogenerated by Sphinx. Refer to documentation # The language for content autogenerated by Sphinx. Refer to documentation
@ -232,8 +232,8 @@ latex_documents = [
( (
"contents", "contents",
"pytest.tex", "pytest.tex",
u"pytest Documentation", "pytest Documentation",
u"holger krekel, trainer and consultant, http://merlinux.eu", "holger krekel, trainer and consultant, http://merlinux.eu",
"manual", "manual",
) )
] ]
@ -265,16 +265,16 @@ latex_domain_indices = False
# One entry per manual page. List of tuples # One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section). # (source start file, name, description, authors, manual section).
man_pages = [("usage", "pytest", u"pytest usage", [u"holger krekel at merlinux eu"], 1)] man_pages = [("usage", "pytest", "pytest usage", ["holger krekel at merlinux eu"], 1)]
# -- Options for Epub output --------------------------------------------------- # -- Options for Epub output ---------------------------------------------------
# Bibliographic Dublin Core info. # Bibliographic Dublin Core info.
epub_title = u"pytest" epub_title = "pytest"
epub_author = u"holger krekel at merlinux eu" epub_author = "holger krekel at merlinux eu"
epub_publisher = u"holger krekel at merlinux eu" epub_publisher = "holger krekel at merlinux eu"
epub_copyright = u"2013, holger krekel et alii" epub_copyright = "2013, holger krekel et alii"
# The language of the text. It defaults to the language option # The language of the text. It defaults to the language option
# or en if the language is not set. # or en if the language is not set.

View File

@ -20,7 +20,7 @@ def test_generative(param1, param2):
assert param1 * 2 < param2 assert param1 * 2 < param2
class TestFailing(object): class TestFailing:
def test_simple(self): def test_simple(self):
def f(): def f():
return 42 return 42
@ -40,7 +40,7 @@ class TestFailing(object):
assert not f() assert not f()
class TestSpecialisedExplanations(object): class TestSpecialisedExplanations:
def test_eq_text(self): def test_eq_text(self):
assert "spam" == "eggs" assert "spam" == "eggs"
@ -100,7 +100,7 @@ class TestSpecialisedExplanations(object):
from dataclasses import dataclass from dataclasses import dataclass
@dataclass @dataclass
class Foo(object): class Foo:
a: int a: int
b: str b: str
@ -112,7 +112,7 @@ class TestSpecialisedExplanations(object):
import attr import attr
@attr.s @attr.s
class Foo(object): class Foo:
a = attr.ib() a = attr.ib()
b = attr.ib() b = attr.ib()
@ -122,7 +122,7 @@ class TestSpecialisedExplanations(object):
def test_attribute(): def test_attribute():
class Foo(object): class Foo:
b = 1 b = 1
i = Foo() i = Foo()
@ -130,14 +130,14 @@ def test_attribute():
def test_attribute_instance(): def test_attribute_instance():
class Foo(object): class Foo:
b = 1 b = 1
assert Foo().b == 2 assert Foo().b == 2
def test_attribute_failure(): def test_attribute_failure():
class Foo(object): class Foo:
def _get_b(self): def _get_b(self):
raise Exception("Failed to get attrib") raise Exception("Failed to get attrib")
@ -148,10 +148,10 @@ def test_attribute_failure():
def test_attribute_multiple(): def test_attribute_multiple():
class Foo(object): class Foo:
b = 1 b = 1
class Bar(object): class Bar:
b = 2 b = 2
assert Foo().b == Bar().b assert Foo().b == Bar().b
@ -161,7 +161,7 @@ def globf(x):
return x + 1 return x + 1
class TestRaises(object): class TestRaises:
def test_raises(self): def test_raises(self):
s = "qwe" s = "qwe"
raises(TypeError, int, s) raises(TypeError, int, s)
@ -202,7 +202,7 @@ def test_dynamic_compile_shows_nicely():
module.foo() module.foo()
class TestMoreErrors(object): class TestMoreErrors:
def test_complex_error(self): def test_complex_error(self):
def f(): def f():
return 44 return 44
@ -252,16 +252,16 @@ class TestMoreErrors(object):
x = 0 x = 0
class TestCustomAssertMsg(object): class TestCustomAssertMsg:
def test_single_line(self): def test_single_line(self):
class A(object): class A:
a = 1 a = 1
b = 2 b = 2
assert A.a == b, "A.a appears not to be b" assert A.a == b, "A.a appears not to be b"
def test_multiline(self): def test_multiline(self):
class A(object): class A:
a = 1 a = 1
b = 2 b = 2
@ -270,7 +270,7 @@ class TestCustomAssertMsg(object):
), "A.a appears not to be b\nor does not appear to be b\none of those" ), "A.a appears not to be b\nor does not appear to be b\none of those"
def test_custom_repr(self): def test_custom_repr(self):
class JSON(object): class JSON:
a = 1 a = 1
def __repr__(self): def __repr__(self):

View File

@ -2,7 +2,7 @@ def setup_module(module):
module.TestStateFullThing.classcount = 0 module.TestStateFullThing.classcount = 0
class TestStateFullThing(object): class TestStateFullThing:
def setup_class(cls): def setup_class(cls):
cls.classcount += 1 cls.classcount += 1

View File

@ -8,7 +8,7 @@ def setup(request):
setup.finalize() setup.finalize()
class CostlySetup(object): class CostlySetup:
def __init__(self): def __init__(self):
import time import time

View File

@ -22,7 +22,7 @@ def python2(request, python1):
return Python(request.param, python1.picklefile) return Python(request.param, python1.picklefile)
class Python(object): class Python:
def __init__(self, version, picklefile): def __init__(self, version, picklefile):
self.pythonpath = distutils.spawn.find_executable(version) self.pythonpath = distutils.spawn.find_executable(version)
if not self.pythonpath: if not self.pythonpath:

View File

@ -18,7 +18,7 @@ class YamlFile(pytest.File):
class YamlItem(pytest.Item): class YamlItem(pytest.Item):
def __init__(self, name, parent, spec): def __init__(self, name, parent, spec):
super(YamlItem, self).__init__(name, parent) super().__init__(name, parent)
self.spec = spec self.spec = spec
def runtest(self): def runtest(self):

View File

@ -6,7 +6,7 @@ def test_function():
pass pass
class TestClass(object): class TestClass:
def test_method(self): def test_method(self):
pass pass

View File

@ -58,7 +58,7 @@ import sys
from glob import glob from glob import glob
class FastFilesCompleter(object): class FastFilesCompleter:
"Fast file completer class" "Fast file completer class"
def __init__(self, directories=True): def __init__(self, directories=True):

View File

@ -4,8 +4,6 @@
# #
import types import types
from six import text_type
def format_exception_only(etype, value): def format_exception_only(etype, value):
"""Format the exception part of a traceback. """Format the exception part of a traceback.
@ -80,7 +78,7 @@ def _format_final_exc_line(etype, value):
def _some_str(value): def _some_str(value):
try: try:
return text_type(value) return str(value)
except Exception: except Exception:
try: try:
return bytes(value).decode("UTF-8", "replace") return bytes(value).decode("UTF-8", "replace")

View File

@ -16,7 +16,7 @@ from _pytest._io.saferepr import safeformat
from _pytest._io.saferepr import saferepr from _pytest._io.saferepr import saferepr
class Code(object): class Code:
""" wrapper around Python code objects """ """ wrapper around Python code objects """
def __init__(self, rawcode): def __init__(self, rawcode):
@ -27,7 +27,7 @@ class Code(object):
self.firstlineno = rawcode.co_firstlineno - 1 self.firstlineno = rawcode.co_firstlineno - 1
self.name = rawcode.co_name self.name = rawcode.co_name
except AttributeError: except AttributeError:
raise TypeError("not a code object: %r" % (rawcode,)) raise TypeError("not a code object: {!r}".format(rawcode))
self.raw = rawcode self.raw = rawcode
def __eq__(self, other): def __eq__(self, other):
@ -86,7 +86,7 @@ class Code(object):
return raw.co_varnames[:argcount] return raw.co_varnames[:argcount]
class Frame(object): class Frame:
"""Wrapper around a Python frame holding f_locals and f_globals """Wrapper around a Python frame holding f_locals and f_globals
in which expressions can be evaluated.""" in which expressions can be evaluated."""
@ -149,7 +149,7 @@ class Frame(object):
return retval return retval
class TracebackEntry(object): class TracebackEntry:
""" a single entry in a traceback """ """ a single entry in a traceback """
_repr_style = None _repr_style = None
@ -309,7 +309,7 @@ class Traceback(list):
return self return self
def __getitem__(self, key): def __getitem__(self, key):
val = super(Traceback, self).__getitem__(key) val = super().__getitem__(key)
if isinstance(key, type(slice(0))): if isinstance(key, type(slice(0))):
val = self.__class__(val) val = self.__class__(val)
return val return val
@ -371,7 +371,7 @@ co_equal = compile(
@attr.s(repr=False) @attr.s(repr=False)
class ExceptionInfo(object): class ExceptionInfo:
""" wraps sys.exc_info() objects and offers """ wraps sys.exc_info() objects and offers
help for navigating the traceback. help for navigating the traceback.
""" """
@ -556,7 +556,7 @@ class ExceptionInfo(object):
@attr.s @attr.s
class FormattedExcinfo(object): class FormattedExcinfo:
""" presenting information about failing Functions and Generators. """ """ presenting information about failing Functions and Generators. """
# for traceback entries # for traceback entries
@ -655,7 +655,7 @@ class FormattedExcinfo(object):
str_repr = safeformat(value) str_repr = safeformat(value)
# if len(str_repr) < 70 or not isinstance(value, # if len(str_repr) < 70 or not isinstance(value,
# (list, tuple, dict)): # (list, tuple, dict)):
lines.append("%-10s = %s" % (name, str_repr)) lines.append("{:<10} = {}".format(name, str_repr))
# else: # else:
# self._line("%-10s =\\" % (name,)) # self._line("%-10s =\\" % (name,))
# # XXX # # XXX
@ -804,7 +804,7 @@ class FormattedExcinfo(object):
return ExceptionChainRepr(repr_chain) return ExceptionChainRepr(repr_chain)
class TerminalRepr(object): class TerminalRepr:
def __str__(self): def __str__(self):
# FYI this is called from pytest-xdist's serialization of exception # FYI this is called from pytest-xdist's serialization of exception
# information. # information.
@ -814,7 +814,7 @@ class TerminalRepr(object):
return io.getvalue().strip() return io.getvalue().strip()
def __repr__(self): def __repr__(self):
return "<%s instance at %0x>" % (self.__class__, id(self)) return "<{} instance at {:0x}>".format(self.__class__, id(self))
class ExceptionRepr(TerminalRepr): class ExceptionRepr(TerminalRepr):
@ -832,7 +832,7 @@ class ExceptionRepr(TerminalRepr):
class ExceptionChainRepr(ExceptionRepr): class ExceptionChainRepr(ExceptionRepr):
def __init__(self, chain): def __init__(self, chain):
super(ExceptionChainRepr, self).__init__() super().__init__()
self.chain = chain self.chain = chain
# reprcrash and reprtraceback of the outermost (the newest) exception # reprcrash and reprtraceback of the outermost (the newest) exception
# in the chain # in the chain
@ -845,18 +845,18 @@ class ExceptionChainRepr(ExceptionRepr):
if element[2] is not None: if element[2] is not None:
tw.line("") tw.line("")
tw.line(element[2], yellow=True) tw.line(element[2], yellow=True)
super(ExceptionChainRepr, self).toterminal(tw) super().toterminal(tw)
class ReprExceptionInfo(ExceptionRepr): class ReprExceptionInfo(ExceptionRepr):
def __init__(self, reprtraceback, reprcrash): def __init__(self, reprtraceback, reprcrash):
super(ReprExceptionInfo, self).__init__() super().__init__()
self.reprtraceback = reprtraceback self.reprtraceback = reprtraceback
self.reprcrash = reprcrash self.reprcrash = reprcrash
def toterminal(self, tw): def toterminal(self, tw):
self.reprtraceback.toterminal(tw) self.reprtraceback.toterminal(tw)
super(ReprExceptionInfo, self).toterminal(tw) super().toterminal(tw)
class ReprTraceback(TerminalRepr): class ReprTraceback(TerminalRepr):
@ -933,7 +933,9 @@ class ReprEntry(TerminalRepr):
self.reprfileloc.toterminal(tw) self.reprfileloc.toterminal(tw)
def __str__(self): def __str__(self):
return "%s\n%s\n%s" % ("\n".join(self.lines), self.reprlocals, self.reprfileloc) return "{}\n{}\n{}".format(
"\n".join(self.lines), self.reprlocals, self.reprfileloc
)
class ReprFileLocation(TerminalRepr): class ReprFileLocation(TerminalRepr):
@ -950,7 +952,7 @@ class ReprFileLocation(TerminalRepr):
if i != -1: if i != -1:
msg = msg[:i] msg = msg[:i]
tw.write(self.path, bold=True, red=True) tw.write(self.path, bold=True, red=True)
tw.line(":%s: %s" % (self.lineno, msg)) tw.line(":{}: {}".format(self.lineno, msg))
class ReprLocals(TerminalRepr): class ReprLocals(TerminalRepr):
@ -970,7 +972,7 @@ class ReprFuncArgs(TerminalRepr):
if self.args: if self.args:
linesofar = "" linesofar = ""
for name, value in self.args: for name, value in self.args:
ns = "%s = %s" % (name, value) ns = "{} = {}".format(name, value)
if len(ns) + len(linesofar) + 2 > tw.fullwidth: if len(ns) + len(linesofar) + 2 > tw.fullwidth:
if linesofar: if linesofar:
tw.line(linesofar) tw.line(linesofar)

View File

@ -9,10 +9,9 @@ from ast import PyCF_ONLY_AST as _AST_FLAG
from bisect import bisect_right from bisect import bisect_right
import py import py
import six
class Source(object): class Source:
""" an immutable object holding a source code fragment, """ an immutable object holding a source code fragment,
possibly deindenting it. possibly deindenting it.
""" """
@ -29,7 +28,7 @@ class Source(object):
partlines = part.lines partlines = part.lines
elif isinstance(part, (tuple, list)): elif isinstance(part, (tuple, list)):
partlines = [x.rstrip("\n") for x in part] partlines = [x.rstrip("\n") for x in part]
elif isinstance(part, six.string_types): elif isinstance(part, str):
partlines = part.split("\n") partlines = part.split("\n")
else: else:
partlines = getsource(part, deindent=de).lines partlines = getsource(part, deindent=de).lines

View File

@ -12,11 +12,8 @@ def _call_and_format_exception(call, x, *args):
exc_info = str(exc) exc_info = str(exc)
except Exception: except Exception:
exc_info = "unknown" exc_info = "unknown"
return '<[%s("%s") raised in repr()] %s object at 0x%x>' % ( return '<[{}("{}") raised in repr()] {} object at 0x{:x}>'.format(
exc_name, exc_name, exc_info, x.__class__.__name__, id(x)
exc_info,
x.__class__.__name__,
id(x),
) )
@ -32,11 +29,11 @@ class SafeRepr(reprlib.Repr):
# Strictly speaking wrong on narrow builds # Strictly speaking wrong on narrow builds
def repr(u): def repr(u):
if "'" not in u: if "'" not in u:
return u"'%s'" % u return "'%s'" % u
elif '"' not in u: elif '"' not in u:
return u'"%s"' % u return '"%s"' % u
else: else:
return u"'%s'" % u.replace("'", r"\'") return "'%s'" % u.replace("'", r"\'")
s = repr(x[: self.maxstring]) s = repr(x[: self.maxstring])
if len(s) > self.maxstring: if len(s) > self.maxstring:

View File

@ -3,8 +3,6 @@ support for presenting detailed information in failing assertions.
""" """
import sys import sys
import six
from _pytest.assertion import rewrite from _pytest.assertion import rewrite
from _pytest.assertion import truncate from _pytest.assertion import truncate
from _pytest.assertion import util from _pytest.assertion import util
@ -51,14 +49,14 @@ def register_assert_rewrite(*names):
importhook.mark_rewrite(*names) importhook.mark_rewrite(*names)
class DummyRewriteHook(object): class DummyRewriteHook:
"""A no-op import hook for when rewriting is disabled.""" """A no-op import hook for when rewriting is disabled."""
def mark_rewrite(self, *names): def mark_rewrite(self, *names):
pass pass
class AssertionState(object): class AssertionState:
"""State for the assertion plugin.""" """State for the assertion plugin."""
def __init__(self, config, mode): def __init__(self, config, mode):
@ -124,7 +122,7 @@ def pytest_runtest_setup(item):
if new_expl: if new_expl:
new_expl = truncate.truncate_if_required(new_expl, item) new_expl = truncate.truncate_if_required(new_expl, item)
new_expl = [line.replace("\n", "\\n") for line in new_expl] new_expl = [line.replace("\n", "\\n") for line in new_expl]
res = six.text_type("\n~").join(new_expl) res = "\n~".join(new_expl)
if item.config.getvalue("assertmode") == "rewrite": if item.config.getvalue("assertmode") == "rewrite":
res = res.replace("%", "%%") res = res.replace("%", "%%")
return res return res

View File

@ -33,14 +33,14 @@ else:
else: else:
impl = "cpython" impl = "cpython"
ver = sys.version_info ver = sys.version_info
PYTEST_TAG = "%s-%s%s-PYTEST" % (impl, ver[0], ver[1]) PYTEST_TAG = "{}-{}{}-PYTEST".format(impl, ver[0], ver[1])
del ver, impl del ver, impl
PYC_EXT = ".py" + (__debug__ and "c" or "o") PYC_EXT = ".py" + (__debug__ and "c" or "o")
PYC_TAIL = "." + PYTEST_TAG + PYC_EXT PYC_TAIL = "." + PYTEST_TAG + PYC_EXT
class AssertionRewritingHook(object): class AssertionRewritingHook:
"""PEP302 Import hook which rewrites asserts.""" """PEP302 Import hook which rewrites asserts."""
def __init__(self, config): def __init__(self, config):
@ -149,7 +149,7 @@ class AssertionRewritingHook(object):
# to check for a cached pyc. This may not be optimal... # to check for a cached pyc. This may not be optimal...
co = _read_pyc(fn_pypath, pyc, state.trace) co = _read_pyc(fn_pypath, pyc, state.trace)
if co is None: if co is None:
state.trace("rewriting %r" % (fn,)) state.trace("rewriting {!r}".format(fn))
source_stat, co = _rewrite_test(self.config, fn_pypath) source_stat, co = _rewrite_test(self.config, fn_pypath)
if co is None: if co is None:
# Probably a SyntaxError in the test. # Probably a SyntaxError in the test.
@ -161,7 +161,7 @@ class AssertionRewritingHook(object):
finally: finally:
self._writing_pyc = False self._writing_pyc = False
else: else:
state.trace("found cached rewritten pyc for %r" % (fn,)) state.trace("found cached rewritten pyc for {!r}".format(fn))
self.modules[name] = co, pyc self.modules[name] = co, pyc
return self return self
@ -200,26 +200,28 @@ class AssertionRewritingHook(object):
if self._is_marked_for_rewrite(name, state): if self._is_marked_for_rewrite(name, state):
return False return False
state.trace("early skip of rewriting module: %s" % (name,)) state.trace("early skip of rewriting module: {}".format(name))
return True return True
def _should_rewrite(self, name, fn_pypath, state): def _should_rewrite(self, name, fn_pypath, state):
# always rewrite conftest files # always rewrite conftest files
fn = str(fn_pypath) fn = str(fn_pypath)
if fn_pypath.basename == "conftest.py": if fn_pypath.basename == "conftest.py":
state.trace("rewriting conftest file: %r" % (fn,)) state.trace("rewriting conftest file: {!r}".format(fn))
return True return True
if self.session is not None: if self.session is not None:
if self.session.isinitpath(fn): if self.session.isinitpath(fn):
state.trace("matched test file (was specified on cmdline): %r" % (fn,)) state.trace(
"matched test file (was specified on cmdline): {!r}".format(fn)
)
return True return True
# modules not passed explicitly on the command line are only # modules not passed explicitly on the command line are only
# rewritten if they match the naming convention for test files # rewritten if they match the naming convention for test files
for pat in self.fnpats: for pat in self.fnpats:
if fn_pypath.fnmatch(pat): if fn_pypath.fnmatch(pat):
state.trace("matched test file %r" % (fn,)) state.trace("matched test file {!r}".format(fn))
return True return True
return self._is_marked_for_rewrite(name, state) return self._is_marked_for_rewrite(name, state)
@ -230,7 +232,9 @@ class AssertionRewritingHook(object):
except KeyError: except KeyError:
for marked in self._must_rewrite: for marked in self._must_rewrite:
if name == marked or name.startswith(marked + "."): if name == marked or name.startswith(marked + "."):
state.trace("matched marked file %r (from %r)" % (name, marked)) state.trace(
"matched marked file {!r} (from {!r})".format(name, marked)
)
self._marked_for_rewrite_cache[name] = True self._marked_for_rewrite_cache[name] = True
return True return True
@ -325,7 +329,7 @@ def _write_pyc(state, co, source_stat, pyc):
fp.write(struct.pack("<LL", mtime, size)) fp.write(struct.pack("<LL", mtime, size))
fp.write(marshal.dumps(co)) fp.write(marshal.dumps(co))
except EnvironmentError as e: except EnvironmentError as e:
state.trace("error writing pyc file at %s: errno=%s" % (pyc, e.errno)) state.trace("error writing pyc file at {}: errno={}".format(pyc, e.errno))
# we ignore any failure to write the cache file # we ignore any failure to write the cache file
# there are many reasons, permission-denied, __pycache__ being a # there are many reasons, permission-denied, __pycache__ being a
# file etc. # file etc.
@ -333,8 +337,8 @@ def _write_pyc(state, co, source_stat, pyc):
return True return True
RN = "\r\n".encode("utf-8") RN = "\r\n".encode()
N = "\n".encode("utf-8") N = "\n".encode()
cookie_re = re.compile(r"^[ \t\f]*#.*coding[:=][ \t]*[-\w.]+") cookie_re = re.compile(r"^[ \t\f]*#.*coding[:=][ \t]*[-\w.]+")
BOM_UTF8 = "\xef\xbb\xbf" BOM_UTF8 = "\xef\xbb\xbf"
@ -352,7 +356,7 @@ def _rewrite_test(config, fn):
tree = ast.parse(source, filename=fn.strpath) tree = ast.parse(source, filename=fn.strpath)
except SyntaxError: except SyntaxError:
# Let this pop up again in the real import. # Let this pop up again in the real import.
state.trace("failed to parse: %r" % (fn,)) state.trace("failed to parse: {!r}".format(fn))
return None, None return None, None
rewrite_asserts(tree, fn, config) rewrite_asserts(tree, fn, config)
try: try:
@ -360,7 +364,7 @@ def _rewrite_test(config, fn):
except SyntaxError: except SyntaxError:
# It's possible that this error is from some bug in the # It's possible that this error is from some bug in the
# assertion rewriting, but I don't know of a fast way to tell. # assertion rewriting, but I don't know of a fast way to tell.
state.trace("failed to compile: %r" % (fn,)) state.trace("failed to compile: {!r}".format(fn))
return None, None return None, None
return stat, co return stat, co
@ -380,7 +384,7 @@ def _read_pyc(source, pyc, trace=lambda x: None):
size = source.size() size = source.size()
data = fp.read(12) data = fp.read(12)
except EnvironmentError as e: except EnvironmentError as e:
trace("_read_pyc(%s): EnvironmentError %s" % (source, e)) trace("_read_pyc({}): EnvironmentError {}".format(source, e))
return None return None
# Check for invalid or out of date pyc file. # Check for invalid or out of date pyc file.
if ( if (
@ -393,7 +397,7 @@ def _read_pyc(source, pyc, trace=lambda x: None):
try: try:
co = marshal.load(fp) co = marshal.load(fp)
except Exception as e: except Exception as e:
trace("_read_pyc(%s): marshal.load error %s" % (source, e)) trace("_read_pyc({}): marshal.load error {}".format(source, e))
return None return None
if not isinstance(co, types.CodeType): if not isinstance(co, types.CodeType):
trace("_read_pyc(%s): not a code object" % source) trace("_read_pyc(%s): not a code object" % source)
@ -421,11 +425,11 @@ def _saferepr(obj):
# only occurs in python2.x, repr must return text in python3+ # only occurs in python2.x, repr must return text in python3+
if isinstance(r, bytes): if isinstance(r, bytes):
# Represent unprintable bytes as `\x##` # Represent unprintable bytes as `\x##`
r = u"".join( r = "".join(
u"\\x{:x}".format(ord(c)) if c not in string.printable else c.decode() "\\x{:x}".format(ord(c)) if c not in string.printable else c.decode()
for c in r for c in r
) )
return r.replace(u"\n", u"\\n") return r.replace("\n", "\\n")
def _format_assertmsg(obj): def _format_assertmsg(obj):
@ -440,10 +444,10 @@ def _format_assertmsg(obj):
# contains a newline it gets escaped, however if an object has a # contains a newline it gets escaped, however if an object has a
# .__repr__() which contains newlines it does not get escaped. # .__repr__() which contains newlines it does not get escaped.
# However in either case we want to preserve the newline. # However in either case we want to preserve the newline.
replaces = [(u"\n", u"\n~"), (u"%", u"%%")] replaces = [("\n", "\n~"), ("%", "%%")]
if not isinstance(obj, six.string_types): if not isinstance(obj, str):
obj = saferepr(obj) obj = saferepr(obj)
replaces.append((u"\\n", u"\n~")) replaces.append(("\\n", "\n~"))
if isinstance(obj, bytes): if isinstance(obj, bytes):
replaces = [(r1.encode(), r2.encode()) for r1, r2 in replaces] replaces = [(r1.encode(), r2.encode()) for r1, r2 in replaces]
@ -466,8 +470,8 @@ def _should_repr_global_name(obj):
def _format_boolop(explanations, is_or): def _format_boolop(explanations, is_or):
explanation = "(" + (is_or and " or " or " and ").join(explanations) + ")" explanation = "(" + (is_or and " or " or " and ").join(explanations) + ")"
if isinstance(explanation, six.text_type): if isinstance(explanation, str):
return explanation.replace(u"%", u"%%") return explanation.replace("%", "%%")
else: else:
return explanation.replace(b"%", b"%%") return explanation.replace(b"%", b"%%")
@ -596,7 +600,7 @@ class AssertionRewriter(ast.NodeVisitor):
""" """
def __init__(self, module_path, config): def __init__(self, module_path, config):
super(AssertionRewriter, self).__init__() super().__init__()
self.module_path = module_path self.module_path = module_path
self.config = config self.config = config
@ -896,7 +900,7 @@ warn_explicit(
symbol = binop_map[binop.op.__class__] symbol = binop_map[binop.op.__class__]
left_expr, left_expl = self.visit(binop.left) left_expr, left_expl = self.visit(binop.left)
right_expr, right_expl = self.visit(binop.right) right_expr, right_expl = self.visit(binop.right)
explanation = "(%s %s %s)" % (left_expl, symbol, right_expl) explanation = "({} {} {})".format(left_expl, symbol, right_expl)
res = self.assign(ast.BinOp(left_expr, binop.op, right_expr)) res = self.assign(ast.BinOp(left_expr, binop.op, right_expr))
return res, explanation return res, explanation
@ -932,11 +936,11 @@ warn_explicit(
else: # **args have `arg` keywords with an .arg of None else: # **args have `arg` keywords with an .arg of None
arg_expls.append("**" + expl) arg_expls.append("**" + expl)
expl = "%s(%s)" % (func_expl, ", ".join(arg_expls)) expl = "{}({})".format(func_expl, ", ".join(arg_expls))
new_call = ast.Call(new_func, new_args, new_kwargs) new_call = ast.Call(new_func, new_args, new_kwargs)
res = self.assign(new_call) res = self.assign(new_call)
res_expl = self.explanation_param(self.display(res)) res_expl = self.explanation_param(self.display(res))
outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl) outer_expl = "{}\n{{{} = {}\n}}".format(res_expl, res_expl, expl)
return res, outer_expl return res, outer_expl
def _visit_all(self, call): def _visit_all(self, call):
@ -993,7 +997,7 @@ warn_explicit(
results.append(next_res) results.append(next_res)
sym = binop_map[op.__class__] sym = binop_map[op.__class__]
syms.append(ast.Str(sym)) syms.append(ast.Str(sym))
expl = "%s %s %s" % (left_expl, sym, next_expl) expl = "{} {} {}".format(left_expl, sym, next_expl)
expls.append(ast.Str(expl)) expls.append(ast.Str(expl))
res_expr = ast.Compare(left_res, [op], [next_res]) res_expr = ast.Compare(left_res, [op], [next_res])
self.statements.append(ast.Assign([store_names[i]], res_expr)) self.statements.append(ast.Assign([store_names[i]], res_expr))

View File

@ -6,8 +6,6 @@ Current default behaviour is to truncate assertion explanations at
""" """
import os import os
import six
DEFAULT_MAX_LINES = 8 DEFAULT_MAX_LINES = 8
DEFAULT_MAX_CHARS = 8 * 80 DEFAULT_MAX_CHARS = 8 * 80
USAGE_MSG = "use '-vv' to show" USAGE_MSG = "use '-vv' to show"
@ -71,7 +69,7 @@ def _truncate_explanation(input_lines, max_lines=None, max_chars=None):
else: else:
msg += " ({} lines hidden)".format(truncated_line_count) msg += " ({} lines hidden)".format(truncated_line_count)
msg += ", {}".format(USAGE_MSG) msg += ", {}".format(USAGE_MSG)
truncated_explanation.extend([six.text_type(""), six.text_type(msg)]) truncated_explanation.extend(["", str(msg)])
return truncated_explanation return truncated_explanation

View File

@ -2,8 +2,6 @@
import pprint import pprint
from collections.abc import Sequence from collections.abc import Sequence
import six
import _pytest._code import _pytest._code
from _pytest import outcomes from _pytest import outcomes
from _pytest._io.saferepr import saferepr from _pytest._io.saferepr import saferepr
@ -37,7 +35,7 @@ def format_explanation(explanation):
explanation = ecu(explanation) explanation = ecu(explanation)
lines = _split_explanation(explanation) lines = _split_explanation(explanation)
result = _format_lines(lines) result = _format_lines(lines)
return u"\n".join(result) return "\n".join(result)
def _split_explanation(explanation): def _split_explanation(explanation):
@ -47,7 +45,7 @@ def _split_explanation(explanation):
Any other newlines will be escaped and appear in the line as the Any other newlines will be escaped and appear in the line as the
literal '\n' characters. literal '\n' characters.
""" """
raw_lines = (explanation or u"").split("\n") raw_lines = (explanation or "").split("\n")
lines = [raw_lines[0]] lines = [raw_lines[0]]
for values in raw_lines[1:]: for values in raw_lines[1:]:
if values and values[0] in ["{", "}", "~", ">"]: if values and values[0] in ["{", "}", "~", ">"]:
@ -72,13 +70,13 @@ def _format_lines(lines):
for line in lines[1:]: for line in lines[1:]:
if line.startswith("{"): if line.startswith("{"):
if stackcnt[-1]: if stackcnt[-1]:
s = u"and " s = "and "
else: else:
s = u"where " s = "where "
stack.append(len(result)) stack.append(len(result))
stackcnt[-1] += 1 stackcnt[-1] += 1
stackcnt.append(0) stackcnt.append(0)
result.append(u" +" + u" " * (len(stack) - 1) + s + line[1:]) result.append(" +" + " " * (len(stack) - 1) + s + line[1:])
elif line.startswith("}"): elif line.startswith("}"):
stack.pop() stack.pop()
stackcnt.pop() stackcnt.pop()
@ -87,7 +85,7 @@ def _format_lines(lines):
assert line[0] in ["~", ">"] assert line[0] in ["~", ">"]
stack[-1] += 1 stack[-1] += 1
indent = len(stack) if line.startswith("~") else len(stack) - 1 indent = len(stack) if line.startswith("~") else len(stack) - 1
result.append(u" " * indent + line[1:]) result.append(" " * indent + line[1:])
assert len(stack) == 1 assert len(stack) == 1
return result return result
@ -137,7 +135,7 @@ def assertrepr_compare(config, op, left, right):
left_repr = saferepr(left, maxsize=int(width // 2)) left_repr = saferepr(left, maxsize=int(width // 2))
right_repr = saferepr(right, maxsize=width - len(left_repr)) right_repr = saferepr(right, maxsize=width - len(left_repr))
summary = u"%s %s %s" % (ecu(left_repr), op, ecu(right_repr)) summary = "{} {} {}".format(ecu(left_repr), op, ecu(right_repr))
verbose = config.getoption("verbose") verbose = config.getoption("verbose")
explanation = None explanation = None
@ -170,9 +168,9 @@ def assertrepr_compare(config, op, left, right):
raise raise
except Exception: except Exception:
explanation = [ explanation = [
u"(pytest_assertion plugin: representation of details failed. " "(pytest_assertion plugin: representation of details failed. "
u"Probably an object has a faulty __repr__.)", "Probably an object has a faulty __repr__.)",
six.text_type(_pytest._code.ExceptionInfo.from_current()), str(_pytest._code.ExceptionInfo.from_current()),
] ]
if not explanation: if not explanation:
@ -199,7 +197,7 @@ def _diff_text(left, right, verbose=0):
This is done using repr() which then needs post-processing to fix the encompassing quotes and un-escape This is done using repr() which then needs post-processing to fix the encompassing quotes and un-escape
newlines and carriage returns (#429). newlines and carriage returns (#429).
""" """
r = six.text_type(repr(binary_text)[1:-1]) r = str(repr(binary_text)[1:-1])
r = r.replace(r"\n", "\n") r = r.replace(r"\n", "\n")
r = r.replace(r"\r", "\r") r = r.replace(r"\r", "\r")
return r return r
@ -216,7 +214,7 @@ def _diff_text(left, right, verbose=0):
if i > 42: if i > 42:
i -= 10 # Provide some context i -= 10 # Provide some context
explanation = [ explanation = [
u"Skipping %s identical leading characters in diff, use -v to show" % i "Skipping %s identical leading characters in diff, use -v to show" % i
] ]
left = left[i:] left = left[i:]
right = right[i:] right = right[i:]
@ -227,8 +225,8 @@ def _diff_text(left, right, verbose=0):
if i > 42: if i > 42:
i -= 10 # Provide some context i -= 10 # Provide some context
explanation += [ explanation += [
u"Skipping {} identical trailing " "Skipping {} identical trailing "
u"characters in diff, use -v to show".format(i) "characters in diff, use -v to show".format(i)
] ]
left = left[:-i] left = left[:-i]
right = right[:-i] right = right[:-i]
@ -236,7 +234,7 @@ def _diff_text(left, right, verbose=0):
if left.isspace() or right.isspace(): if left.isspace() or right.isspace():
left = repr(str(left)) left = repr(str(left))
right = repr(str(right)) right = repr(str(right))
explanation += [u"Strings contain only whitespace, escaping them using repr()"] explanation += ["Strings contain only whitespace, escaping them using repr()"]
explanation += [ explanation += [
line.strip("\n") line.strip("\n")
for line in ndiff(left.splitlines(keepends), right.splitlines(keepends)) for line in ndiff(left.splitlines(keepends), right.splitlines(keepends))
@ -250,29 +248,29 @@ def _compare_eq_verbose(left, right):
right_lines = repr(right).splitlines(keepends) right_lines = repr(right).splitlines(keepends)
explanation = [] explanation = []
explanation += [u"-" + line for line in left_lines] explanation += ["-" + line for line in left_lines]
explanation += [u"+" + line for line in right_lines] explanation += ["+" + line for line in right_lines]
return explanation return explanation
def _compare_eq_iterable(left, right, verbose=0): def _compare_eq_iterable(left, right, verbose=0):
if not verbose: if not verbose:
return [u"Use -v to get the full diff"] return ["Use -v to get the full diff"]
# dynamic import to speedup pytest # dynamic import to speedup pytest
import difflib import difflib
try: try:
left_formatting = pprint.pformat(left).splitlines() left_formatting = pprint.pformat(left).splitlines()
right_formatting = pprint.pformat(right).splitlines() right_formatting = pprint.pformat(right).splitlines()
explanation = [u"Full diff:"] explanation = ["Full diff:"]
except Exception: except Exception:
# hack: PrettyPrinter.pformat() in python 2 fails when formatting items that can't be sorted(), ie, calling # hack: PrettyPrinter.pformat() in python 2 fails when formatting items that can't be sorted(), ie, calling
# sorted() on a list would raise. See issue #718. # sorted() on a list would raise. See issue #718.
# As a workaround, the full diff is generated by using the repr() string of each item of each container. # As a workaround, the full diff is generated by using the repr() string of each item of each container.
left_formatting = sorted(repr(x) for x in left) left_formatting = sorted(repr(x) for x in left)
right_formatting = sorted(repr(x) for x in right) right_formatting = sorted(repr(x) for x in right)
explanation = [u"Full diff (fallback to calling repr on each item):"] explanation = ["Full diff (fallback to calling repr on each item):"]
explanation.extend( explanation.extend(
line.strip() for line in difflib.ndiff(left_formatting, right_formatting) line.strip() for line in difflib.ndiff(left_formatting, right_formatting)
) )
@ -285,7 +283,9 @@ def _compare_eq_sequence(left, right, verbose=0):
len_right = len(right) len_right = len(right)
for i in range(min(len_left, len_right)): for i in range(min(len_left, len_right)):
if left[i] != right[i]: if left[i] != right[i]:
explanation += [u"At index %s diff: %r != %r" % (i, left[i], right[i])] explanation += [
"At index {} diff: {!r} != {!r}".format(i, left[i], right[i])
]
break break
len_diff = len_left - len_right len_diff = len_left - len_right
@ -299,10 +299,12 @@ def _compare_eq_sequence(left, right, verbose=0):
extra = saferepr(right[len_left]) extra = saferepr(right[len_left])
if len_diff == 1: if len_diff == 1:
explanation += [u"%s contains one more item: %s" % (dir_with_more, extra)] explanation += [
"{} contains one more item: {}".format(dir_with_more, extra)
]
else: else:
explanation += [ explanation += [
u"%s contains %d more items, first extra item: %s" "%s contains %d more items, first extra item: %s"
% (dir_with_more, len_diff, extra) % (dir_with_more, len_diff, extra)
] ]
return explanation return explanation
@ -313,11 +315,11 @@ def _compare_eq_set(left, right, verbose=0):
diff_left = left - right diff_left = left - right
diff_right = right - left diff_right = right - left
if diff_left: if diff_left:
explanation.append(u"Extra items in the left set:") explanation.append("Extra items in the left set:")
for item in diff_left: for item in diff_left:
explanation.append(saferepr(item)) explanation.append(saferepr(item))
if diff_right: if diff_right:
explanation.append(u"Extra items in the right set:") explanation.append("Extra items in the right set:")
for item in diff_right: for item in diff_right:
explanation.append(saferepr(item)) explanation.append(saferepr(item))
return explanation return explanation
@ -330,20 +332,20 @@ def _compare_eq_dict(left, right, verbose=0):
common = set_left.intersection(set_right) common = set_left.intersection(set_right)
same = {k: left[k] for k in common if left[k] == right[k]} same = {k: left[k] for k in common if left[k] == right[k]}
if same and verbose < 2: if same and verbose < 2:
explanation += [u"Omitting %s identical items, use -vv to show" % len(same)] explanation += ["Omitting %s identical items, use -vv to show" % len(same)]
elif same: elif same:
explanation += [u"Common items:"] explanation += ["Common items:"]
explanation += pprint.pformat(same).splitlines() explanation += pprint.pformat(same).splitlines()
diff = {k for k in common if left[k] != right[k]} diff = {k for k in common if left[k] != right[k]}
if diff: if diff:
explanation += [u"Differing items:"] explanation += ["Differing items:"]
for k in diff: for k in diff:
explanation += [saferepr({k: left[k]}) + " != " + saferepr({k: right[k]})] explanation += [saferepr({k: left[k]}) + " != " + saferepr({k: right[k]})]
extra_left = set_left - set_right extra_left = set_left - set_right
len_extra_left = len(extra_left) len_extra_left = len(extra_left)
if len_extra_left: if len_extra_left:
explanation.append( explanation.append(
u"Left contains %d more item%s:" "Left contains %d more item%s:"
% (len_extra_left, "" if len_extra_left == 1 else "s") % (len_extra_left, "" if len_extra_left == 1 else "s")
) )
explanation.extend( explanation.extend(
@ -353,7 +355,7 @@ def _compare_eq_dict(left, right, verbose=0):
len_extra_right = len(extra_right) len_extra_right = len(extra_right)
if len_extra_right: if len_extra_right:
explanation.append( explanation.append(
u"Right contains %d more item%s:" "Right contains %d more item%s:"
% (len_extra_right, "" if len_extra_right == 1 else "s") % (len_extra_right, "" if len_extra_right == 1 else "s")
) )
explanation.extend( explanation.extend(
@ -381,15 +383,15 @@ def _compare_eq_cls(left, right, verbose, type_fns):
explanation = [] explanation = []
if same and verbose < 2: if same and verbose < 2:
explanation.append(u"Omitting %s identical items, use -vv to show" % len(same)) explanation.append("Omitting %s identical items, use -vv to show" % len(same))
elif same: elif same:
explanation += [u"Matching attributes:"] explanation += ["Matching attributes:"]
explanation += pprint.pformat(same).splitlines() explanation += pprint.pformat(same).splitlines()
if diff: if diff:
explanation += [u"Differing attributes:"] explanation += ["Differing attributes:"]
for field in diff: for field in diff:
explanation += [ explanation += [
(u"%s: %r != %r") % (field, getattr(left, field), getattr(right, field)) ("%s: %r != %r") % (field, getattr(left, field), getattr(right, field))
] ]
return explanation return explanation
@ -400,14 +402,14 @@ def _notin_text(term, text, verbose=0):
tail = text[index + len(term) :] tail = text[index + len(term) :]
correct_text = head + tail correct_text = head + tail
diff = _diff_text(correct_text, text, verbose) diff = _diff_text(correct_text, text, verbose)
newdiff = [u"%s is contained here:" % saferepr(term, maxsize=42)] newdiff = ["%s is contained here:" % saferepr(term, maxsize=42)]
for line in diff: for line in diff:
if line.startswith(u"Skipping"): if line.startswith("Skipping"):
continue continue
if line.startswith(u"- "): if line.startswith("- "):
continue continue
if line.startswith(u"+ "): if line.startswith("+ "):
newdiff.append(u" " + line[2:]) newdiff.append(" " + line[2:])
else: else:
newdiff.append(line) newdiff.append(line)
return newdiff return newdiff

View File

@ -10,14 +10,13 @@ from collections import OrderedDict
import attr import attr
import py import py
import six
import pytest import pytest
from .pathlib import Path from .pathlib import Path
from .pathlib import resolve_from_str from .pathlib import resolve_from_str
from .pathlib import rmtree from .pathlib import rmtree
README_CONTENT = u"""\ README_CONTENT = """\
# pytest cache directory # # pytest cache directory #
This directory contains data from the pytest's cache plugin, This directory contains data from the pytest's cache plugin,
@ -37,7 +36,7 @@ Signature: 8a477f597d28d172789f06886806bc55
@attr.s @attr.s
class Cache(object): class Cache:
_cachedir = attr.ib(repr=False) _cachedir = attr.ib(repr=False)
_config = attr.ib(repr=False) _config = attr.ib(repr=False)
@ -136,14 +135,14 @@ class Cache(object):
readme_path.write_text(README_CONTENT) readme_path.write_text(README_CONTENT)
gitignore_path = self._cachedir.joinpath(".gitignore") gitignore_path = self._cachedir.joinpath(".gitignore")
msg = u"# Created by pytest automatically.\n*" msg = "# Created by pytest automatically.\n*"
gitignore_path.write_text(msg, encoding="UTF-8") gitignore_path.write_text(msg, encoding="UTF-8")
cachedir_tag_path = self._cachedir.joinpath("CACHEDIR.TAG") cachedir_tag_path = self._cachedir.joinpath("CACHEDIR.TAG")
cachedir_tag_path.write_bytes(CACHEDIR_TAG_CONTENT) cachedir_tag_path.write_bytes(CACHEDIR_TAG_CONTENT)
class LFPlugin(object): class LFPlugin:
""" Plugin which implements the --lf (run last-failing) option """ """ Plugin which implements the --lf (run last-failing) option """
def __init__(self, config): def __init__(self, config):
@ -256,7 +255,7 @@ class LFPlugin(object):
config.cache.set("cache/lastfailed", self.lastfailed) config.cache.set("cache/lastfailed", self.lastfailed)
class NFPlugin(object): class NFPlugin:
""" Plugin which implements the --nf (run new-first) option """ """ Plugin which implements the --nf (run new-first) option """
def __init__(self, config): def __init__(self, config):
@ -275,8 +274,8 @@ class NFPlugin(object):
other_items[item.nodeid] = item other_items[item.nodeid] = item
items[:] = self._get_increasing_order( items[:] = self._get_increasing_order(
six.itervalues(new_items) new_items.values()
) + self._get_increasing_order(six.itervalues(other_items)) ) + self._get_increasing_order(other_items.values())
self.cached_nodeids = [x.nodeid for x in items if isinstance(x, pytest.Item)] self.cached_nodeids = [x.nodeid for x in items if isinstance(x, pytest.Item)]
def _get_increasing_order(self, items): def _get_increasing_order(self, items):

View File

@ -10,8 +10,6 @@ import sys
from io import UnsupportedOperation from io import UnsupportedOperation
from tempfile import TemporaryFile from tempfile import TemporaryFile
import six
import pytest import pytest
from _pytest.compat import CaptureIO from _pytest.compat import CaptureIO
@ -61,7 +59,7 @@ def pytest_load_initial_conftests(early_config, parser, args):
sys.stderr.write(err) sys.stderr.write(err)
class CaptureManager(object): class CaptureManager:
""" """
Capture plugin, manages that the appropriate capture method is enabled/disabled during collection and each Capture plugin, manages that the appropriate capture method is enabled/disabled during collection and each
test phase (setup, call, teardown). After each of those points, the captured output is obtained and test phase (setup, call, teardown). After each of those points, the captured output is obtained and
@ -80,10 +78,8 @@ class CaptureManager(object):
self._current_item = None self._current_item = None
def __repr__(self): def __repr__(self):
return "<CaptureManager _method=%r _global_capturing=%r _current_item=%r>" % ( return "<CaptureManager _method={!r} _global_capturing={!r} _current_item={!r}>".format(
self._method, self._method, self._global_capturing, self._current_item
self._global_capturing,
self._current_item,
) )
def _getcapture(self, method): def _getcapture(self, method):
@ -335,7 +331,7 @@ def _install_capture_fixture_on_item(request, capture_class):
del request.node._capture_fixture del request.node._capture_fixture
class CaptureFixture(object): class CaptureFixture:
""" """
Object returned by :py:func:`capsys`, :py:func:`capsysbinary`, :py:func:`capfd` and :py:func:`capfdbinary` Object returned by :py:func:`capsys`, :py:func:`capsysbinary`, :py:func:`capfd` and :py:func:`capfdbinary`
fixtures. fixtures.
@ -414,7 +410,7 @@ def safe_text_dupfile(f, mode, default_encoding="UTF8"):
return EncodedFile(f, encoding or default_encoding) return EncodedFile(f, encoding or default_encoding)
class EncodedFile(object): class EncodedFile:
errors = "strict" # possibly needed by py3 code (issue555) errors = "strict" # possibly needed by py3 code (issue555)
def __init__(self, buffer, encoding): def __init__(self, buffer, encoding):
@ -422,7 +418,7 @@ class EncodedFile(object):
self.encoding = encoding self.encoding = encoding
def write(self, obj): def write(self, obj):
if isinstance(obj, six.text_type): if isinstance(obj, str):
obj = obj.encode(self.encoding, "replace") obj = obj.encode(self.encoding, "replace")
else: else:
raise TypeError( raise TypeError(
@ -450,7 +446,7 @@ class EncodedFile(object):
CaptureResult = collections.namedtuple("CaptureResult", ["out", "err"]) CaptureResult = collections.namedtuple("CaptureResult", ["out", "err"])
class MultiCapture(object): class MultiCapture:
out = err = in_ = None out = err = in_ = None
_state = None _state = None
@ -463,7 +459,7 @@ class MultiCapture(object):
self.err = Capture(2) self.err = Capture(2)
def __repr__(self): def __repr__(self):
return "<MultiCapture out=%r err=%r in_=%r _state=%r _in_suspended=%r>" % ( return "<MultiCapture out={!r} err={!r} in_={!r} _state={!r} _in_suspended={!r}>".format(
self.out, self.out,
self.err, self.err,
self.in_, self.in_,
@ -529,12 +525,12 @@ class MultiCapture(object):
) )
class NoCapture(object): class NoCapture:
EMPTY_BUFFER = None EMPTY_BUFFER = None
__init__ = start = done = suspend = resume = lambda *args: None __init__ = start = done = suspend = resume = lambda *args: None
class FDCaptureBinary(object): class FDCaptureBinary:
"""Capture IO to/from a given os-level filedescriptor. """Capture IO to/from a given os-level filedescriptor.
snap() produces `bytes` snap() produces `bytes`
@ -568,10 +564,8 @@ class FDCaptureBinary(object):
self.tmpfile_fd = tmpfile.fileno() self.tmpfile_fd = tmpfile.fileno()
def __repr__(self): def __repr__(self):
return "<FDCapture %s oldfd=%s _state=%r>" % ( return "<FDCapture {} oldfd={} _state={!r}>".format(
self.targetfd, self.targetfd, getattr(self, "targetfd_save", None), self._state
getattr(self, "targetfd_save", None),
self._state,
) )
def start(self): def start(self):
@ -613,7 +607,7 @@ class FDCaptureBinary(object):
def writeorg(self, data): def writeorg(self, data):
""" write to original file descriptor. """ """ write to original file descriptor. """
if isinstance(data, six.text_type): if isinstance(data, str):
data = data.encode("utf8") # XXX use encoding of original stream data = data.encode("utf8") # XXX use encoding of original stream
os.write(self.targetfd_save, data) os.write(self.targetfd_save, data)
@ -627,14 +621,14 @@ class FDCapture(FDCaptureBinary):
EMPTY_BUFFER = str() EMPTY_BUFFER = str()
def snap(self): def snap(self):
res = super(FDCapture, self).snap() res = super().snap()
enc = getattr(self.tmpfile, "encoding", None) enc = getattr(self.tmpfile, "encoding", None)
if enc and isinstance(res, bytes): if enc and isinstance(res, bytes):
res = six.text_type(res, enc, "replace") res = str(res, enc, "replace")
return res return res
class SysCapture(object): class SysCapture:
EMPTY_BUFFER = str() EMPTY_BUFFER = str()
_state = None _state = None
@ -651,11 +645,8 @@ class SysCapture(object):
self.tmpfile = tmpfile self.tmpfile = tmpfile
def __repr__(self): def __repr__(self):
return "<SysCapture %s _old=%r, tmpfile=%r _state=%r>" % ( return "<SysCapture {} _old={!r}, tmpfile={!r} _state={!r}>".format(
self.name, self.name, self._old, self.tmpfile, self._state
self._old,
self.tmpfile,
self._state,
) )
def start(self): def start(self):
@ -697,7 +688,7 @@ class SysCaptureBinary(SysCapture):
return res return res
class DontReadFromInput(six.Iterator): class DontReadFromInput:
"""Temporary stub class. Ideally when stdin is accessed, the """Temporary stub class. Ideally when stdin is accessed, the
capturing should be turned off, with possibly all data captured capturing should be turned off, with possibly all data captured
so far sent to the screen. This should be configurable, though, so far sent to the screen. This should be configurable, though,

View File

@ -148,10 +148,10 @@ def get_default_arg_names(function):
_non_printable_ascii_translate_table = { _non_printable_ascii_translate_table = {
i: u"\\x{:02x}".format(i) for i in range(128) if i not in range(32, 127) i: "\\x{:02x}".format(i) for i in range(128) if i not in range(32, 127)
} }
_non_printable_ascii_translate_table.update( _non_printable_ascii_translate_table.update(
{ord("\t"): u"\\t", ord("\r"): u"\\r", ord("\n"): u"\\n"} {ord("\t"): "\\t", ord("\r"): "\\r", ord("\n"): "\\n"}
) )
@ -191,7 +191,7 @@ def ascii_escaped(val):
return _translate_non_printable(ret) return _translate_non_printable(ret)
class _PytestWrapper(object): class _PytestWrapper:
"""Dummy wrapper around a function object for internal use only. """Dummy wrapper around a function object for internal use only.
Used to correctly unwrap the underlying function object Used to correctly unwrap the underlying function object
@ -310,15 +310,13 @@ def _setup_collect_fakemodule():
class CaptureIO(io.TextIOWrapper): class CaptureIO(io.TextIOWrapper):
def __init__(self): def __init__(self):
super(CaptureIO, self).__init__( super().__init__(io.BytesIO(), encoding="UTF-8", newline="", write_through=True)
io.BytesIO(), encoding="UTF-8", newline="", write_through=True
)
def getvalue(self): def getvalue(self):
return self.buffer.getvalue().decode("UTF-8") return self.buffer.getvalue().decode("UTF-8")
class FuncargnamesCompatAttr(object): class FuncargnamesCompatAttr:
""" helper class so that Metafunc, Function and FixtureRequest """ helper class so that Metafunc, Function and FixtureRequest
don't need to each define the "funcargnames" compatibility attribute. don't need to each define the "funcargnames" compatibility attribute.
""" """

View File

@ -11,7 +11,6 @@ from functools import lru_cache
import importlib_metadata import importlib_metadata
import py import py
import six
from packaging.version import Version from packaging.version import Version
from pluggy import HookimplMarker from pluggy import HookimplMarker
from pluggy import HookspecMarker from pluggy import HookspecMarker
@ -83,7 +82,7 @@ def main(args=None, plugins=None):
return EXIT_USAGEERROR return EXIT_USAGEERROR
class cmdline(object): # compatibility namespace class cmdline: # compatibility namespace
main = staticmethod(main) main = staticmethod(main)
@ -189,7 +188,7 @@ def _prepareconfig(args=None, plugins=None):
try: try:
if plugins: if plugins:
for plugin in plugins: for plugin in plugins:
if isinstance(plugin, six.string_types): if isinstance(plugin, str):
pluginmanager.consider_pluginarg(plugin) pluginmanager.consider_pluginarg(plugin)
else: else:
pluginmanager.register(plugin) pluginmanager.register(plugin)
@ -216,7 +215,7 @@ class PytestPluginManager(PluginManager):
""" """
def __init__(self): def __init__(self):
super(PytestPluginManager, self).__init__("pytest") super().__init__("pytest")
self._conftest_plugins = set() self._conftest_plugins = set()
# state related to local conftest plugins # state related to local conftest plugins
@ -264,7 +263,7 @@ class PytestPluginManager(PluginManager):
return return
method = getattr(plugin, name) method = getattr(plugin, name)
opts = super(PytestPluginManager, self).parse_hookimpl_opts(plugin, name) opts = super().parse_hookimpl_opts(plugin, name)
# consider only actual functions for hooks (#3775) # consider only actual functions for hooks (#3775)
if not inspect.isroutine(method): if not inspect.isroutine(method):
@ -283,9 +282,7 @@ class PytestPluginManager(PluginManager):
return opts return opts
def parse_hookspec_opts(self, module_or_class, name): def parse_hookspec_opts(self, module_or_class, name):
opts = super(PytestPluginManager, self).parse_hookspec_opts( opts = super().parse_hookspec_opts(module_or_class, name)
module_or_class, name
)
if opts is None: if opts is None:
method = getattr(module_or_class, name) method = getattr(module_or_class, name)
@ -312,7 +309,7 @@ class PytestPluginManager(PluginManager):
) )
) )
return return
ret = super(PytestPluginManager, self).register(plugin, name) ret = super().register(plugin, name)
if ret: if ret:
self.hook.pytest_plugin_registered.call_historic( self.hook.pytest_plugin_registered.call_historic(
kwargs=dict(plugin=plugin, manager=self) kwargs=dict(plugin=plugin, manager=self)
@ -473,7 +470,7 @@ class PytestPluginManager(PluginManager):
while i < n: while i < n:
opt = args[i] opt = args[i]
i += 1 i += 1
if isinstance(opt, six.string_types): if isinstance(opt, str):
if opt == "-p": if opt == "-p":
try: try:
parg = args[i] parg = args[i]
@ -534,7 +531,7 @@ class PytestPluginManager(PluginManager):
# "terminal" or "capture". Those plugins are registered under their # "terminal" or "capture". Those plugins are registered under their
# basename for historic purposes but must be imported with the # basename for historic purposes but must be imported with the
# _pytest prefix. # _pytest prefix.
assert isinstance(modname, six.string_types), ( assert isinstance(modname, str), (
"module name as text required, got %r" % modname "module name as text required, got %r" % modname
) )
modname = str(modname) modname = str(modname)
@ -552,20 +549,19 @@ class PytestPluginManager(PluginManager):
try: try:
__import__(importspec) __import__(importspec)
except ImportError as e: except ImportError as e:
new_exc_message = 'Error importing plugin "%s": %s' % ( new_exc_message = 'Error importing plugin "{}": {}'.format(
modname, modname, str(e.args[0])
str(e.args[0]),
) )
new_exc = ImportError(new_exc_message) new_exc = ImportError(new_exc_message)
tb = sys.exc_info()[2] tb = sys.exc_info()[2]
six.reraise(ImportError, new_exc, tb) raise new_exc.with_traceback(tb)
except Skipped as e: except Skipped as e:
from _pytest.warnings import _issue_warning_captured from _pytest.warnings import _issue_warning_captured
_issue_warning_captured( _issue_warning_captured(
PytestConfigWarning("skipped plugin %r: %s" % (modname, e.msg)), PytestConfigWarning("skipped plugin {!r}: {}".format(modname, e.msg)),
self.hook, self.hook,
stacklevel=1, stacklevel=1,
) )
@ -583,7 +579,7 @@ def _get_plugin_specs_as_list(specs):
empty list is returned. empty list is returned.
""" """
if specs is not None and not isinstance(specs, types.ModuleType): if specs is not None and not isinstance(specs, types.ModuleType):
if isinstance(specs, six.string_types): if isinstance(specs, str):
specs = specs.split(",") if specs else [] specs = specs.split(",") if specs else []
if not isinstance(specs, (list, tuple)): if not isinstance(specs, (list, tuple)):
raise UsageError( raise UsageError(
@ -601,7 +597,7 @@ def _ensure_removed_sysmodule(modname):
pass pass
class Notset(object): class Notset:
def __repr__(self): def __repr__(self):
return "<NOTSET>" return "<NOTSET>"
@ -621,7 +617,7 @@ def _iter_rewritable_modules(package_files):
yield package_name yield package_name
class Config(object): class Config:
""" access to configuration values, pluginmanager and plugin hooks. """ """ access to configuration values, pluginmanager and plugin hooks. """
def __init__(self, pluginmanager): def __init__(self, pluginmanager):
@ -632,7 +628,7 @@ class Config(object):
_a = FILE_OR_DIR _a = FILE_OR_DIR
self._parser = Parser( self._parser = Parser(
usage="%%(prog)s [options] [%s] [%s] [...]" % (_a, _a), usage="%(prog)s [options] [{}] [{}] [...]".format(_a, _a),
processopt=self._processopt, processopt=self._processopt,
) )
#: a pluginmanager instance #: a pluginmanager instance
@ -920,7 +916,7 @@ class Config(object):
try: try:
description, type, default = self._parser._inidict[name] description, type, default = self._parser._inidict[name]
except KeyError: except KeyError:
raise ValueError("unknown configuration value: %r" % (name,)) raise ValueError("unknown configuration value: {!r}".format(name))
value = self._get_override_ini_value(name) value = self._get_override_ini_value(name)
if value is None: if value is None:
try: try:
@ -997,8 +993,8 @@ class Config(object):
if skip: if skip:
import pytest import pytest
pytest.skip("no %r option found" % (name,)) pytest.skip("no {!r} option found".format(name))
raise ValueError("no option named %r" % (name,)) raise ValueError("no option named {!r}".format(name))
def getvalue(self, name, path=None): def getvalue(self, name, path=None):
""" (deprecated, use getoption()) """ """ (deprecated, use getoption()) """
@ -1086,4 +1082,4 @@ def _strtobool(val):
elif val in ("n", "no", "f", "false", "off", "0"): elif val in ("n", "no", "f", "false", "off", "0"):
return 0 return 0
else: else:
raise ValueError("invalid truth value %r" % (val,)) raise ValueError("invalid truth value {!r}".format(val))

View File

@ -2,14 +2,13 @@ import argparse
import warnings import warnings
import py import py
import six
from _pytest.config.exceptions import UsageError from _pytest.config.exceptions import UsageError
FILE_OR_DIR = "file_or_dir" FILE_OR_DIR = "file_or_dir"
class Parser(object): class Parser:
""" Parser for command line arguments and ini-file values. """ Parser for command line arguments and ini-file values.
:ivar extra_info: dict of generic param -> value to display in case :ivar extra_info: dict of generic param -> value to display in case
@ -144,12 +143,12 @@ class ArgumentError(Exception):
def __str__(self): def __str__(self):
if self.option_id: if self.option_id:
return "option %s: %s" % (self.option_id, self.msg) return "option {}: {}".format(self.option_id, self.msg)
else: else:
return self.msg return self.msg
class Argument(object): class Argument:
"""class that mimics the necessary behaviour of optparse.Option """class that mimics the necessary behaviour of optparse.Option
it's currently a least effort implementation it's currently a least effort implementation
@ -178,7 +177,7 @@ class Argument(object):
pass pass
else: else:
# this might raise a keyerror as well, don't want to catch that # this might raise a keyerror as well, don't want to catch that
if isinstance(typ, six.string_types): if isinstance(typ, str):
if typ == "choice": if typ == "choice":
warnings.warn( warnings.warn(
"`type` argument to addoption() is the string %r." "`type` argument to addoption() is the string %r."
@ -281,7 +280,7 @@ class Argument(object):
return "Argument({})".format(", ".join(args)) return "Argument({})".format(", ".join(args))
class OptionGroup(object): class OptionGroup:
def __init__(self, name, description="", parser=None): def __init__(self, name, description="", parser=None):
self.name = name self.name = name
self.description = description self.description = description
@ -336,10 +335,10 @@ class MyOptionParser(argparse.ArgumentParser):
def error(self, message): def error(self, message):
"""Transform argparse error message into UsageError.""" """Transform argparse error message into UsageError."""
msg = "%s: error: %s" % (self.prog, message) msg = "{}: error: {}".format(self.prog, message)
if hasattr(self._parser, "_config_source_hint"): if hasattr(self._parser, "_config_source_hint"):
msg = "%s (%s)" % (msg, self._parser._config_source_hint) msg = "{} ({})".format(msg, self._parser._config_source_hint)
raise UsageError(self.format_usage() + msg) raise UsageError(self.format_usage() + msg)
@ -351,7 +350,7 @@ class MyOptionParser(argparse.ArgumentParser):
if arg and arg[0] == "-": if arg and arg[0] == "-":
lines = ["unrecognized arguments: %s" % (" ".join(argv))] lines = ["unrecognized arguments: %s" % (" ".join(argv))]
for k, v in sorted(self.extra_info.items()): for k, v in sorted(self.extra_info.items()):
lines.append(" %s: %s" % (k, v)) lines.append(" {}: {}".format(k, v))
self.error("\n".join(lines)) self.error("\n".join(lines))
getattr(args, FILE_OR_DIR).extend(argv) getattr(args, FILE_OR_DIR).extend(argv)
return args return args

View File

@ -69,7 +69,7 @@ def pytest_configure(config):
config._cleanup.append(fin) config._cleanup.append(fin)
class pytestPDB(object): class pytestPDB:
""" Pseudo PDB that defers to the real pdb. """ """ Pseudo PDB that defers to the real pdb. """
_pluginmanager = None _pluginmanager = None
@ -123,18 +123,18 @@ class pytestPDB(object):
def _get_pdb_wrapper_class(cls, pdb_cls, capman): def _get_pdb_wrapper_class(cls, pdb_cls, capman):
import _pytest.config import _pytest.config
class PytestPdbWrapper(pdb_cls, object): class PytestPdbWrapper(pdb_cls):
_pytest_capman = capman _pytest_capman = capman
_continued = False _continued = False
def do_debug(self, arg): def do_debug(self, arg):
cls._recursive_debug += 1 cls._recursive_debug += 1
ret = super(PytestPdbWrapper, self).do_debug(arg) ret = super().do_debug(arg)
cls._recursive_debug -= 1 cls._recursive_debug -= 1
return ret return ret
def do_continue(self, arg): def do_continue(self, arg):
ret = super(PytestPdbWrapper, self).do_continue(arg) ret = super().do_continue(arg)
if cls._recursive_debug == 0: if cls._recursive_debug == 0:
tw = _pytest.config.create_terminal_writer(cls._config) tw = _pytest.config.create_terminal_writer(cls._config)
tw.line() tw.line()
@ -166,7 +166,7 @@ class pytestPDB(object):
could be handled, but this would require to wrap the could be handled, but this would require to wrap the
whole pytest run, and adjust the report etc. whole pytest run, and adjust the report etc.
""" """
ret = super(PytestPdbWrapper, self).do_quit(arg) ret = super().do_quit(arg)
if cls._recursive_debug == 0: if cls._recursive_debug == 0:
outcomes.exit("Quitting debugger") outcomes.exit("Quitting debugger")
@ -182,7 +182,7 @@ class pytestPDB(object):
Needed after do_continue resumed, and entering another Needed after do_continue resumed, and entering another
breakpoint again. breakpoint again.
""" """
ret = super(PytestPdbWrapper, self).setup(f, tb) ret = super().setup(f, tb)
if not ret and self._continued: if not ret and self._continued:
# pdb.setup() returns True if the command wants to exit # pdb.setup() returns True if the command wants to exit
# from the interaction: do not suspend capturing then. # from the interaction: do not suspend capturing then.
@ -191,7 +191,7 @@ class pytestPDB(object):
return ret return ret
def get_stack(self, f, t): def get_stack(self, f, t):
stack, i = super(PytestPdbWrapper, self).get_stack(f, t) stack, i = super().get_stack(f, t)
if f is None: if f is None:
# Find last non-hidden frame. # Find last non-hidden frame.
i = max(0, len(stack) - 1) i = max(0, len(stack) - 1)
@ -225,7 +225,7 @@ class pytestPDB(object):
else: else:
capturing = cls._is_capturing(capman) capturing = cls._is_capturing(capman)
if capturing == "global": if capturing == "global":
tw.sep(">", "PDB %s (IO-capturing turned off)" % (method,)) tw.sep(">", "PDB {} (IO-capturing turned off)".format(method))
elif capturing: elif capturing:
tw.sep( tw.sep(
">", ">",
@ -233,7 +233,7 @@ class pytestPDB(object):
% (method, capturing), % (method, capturing),
) )
else: else:
tw.sep(">", "PDB %s" % (method,)) tw.sep(">", "PDB {}".format(method))
_pdb = cls._import_pdb_cls(capman)(**kwargs) _pdb = cls._import_pdb_cls(capman)(**kwargs)
@ -249,7 +249,7 @@ class pytestPDB(object):
_pdb.set_trace(frame) _pdb.set_trace(frame)
class PdbInvoke(object): class PdbInvoke:
def pytest_exception_interact(self, node, call, report): def pytest_exception_interact(self, node, call, report):
capman = node.config.pluginmanager.getplugin("capturemanager") capman = node.config.pluginmanager.getplugin("capturemanager")
if capman: if capman:
@ -264,7 +264,7 @@ class PdbInvoke(object):
post_mortem(tb) post_mortem(tb)
class PdbTrace(object): class PdbTrace:
@hookimpl(hookwrapper=True) @hookimpl(hookwrapper=True)
def pytest_pyfunc_call(self, pyfuncitem): def pytest_pyfunc_call(self, pyfuncitem):
_test_pytest_function(pyfuncitem) _test_pytest_function(pyfuncitem)

View File

@ -121,7 +121,7 @@ class ReprFailDoctest(TerminalRepr):
class MultipleDoctestFailures(Exception): class MultipleDoctestFailures(Exception):
def __init__(self, failures): def __init__(self, failures):
super(MultipleDoctestFailures, self).__init__() super().__init__()
self.failures = failures self.failures = failures
@ -176,7 +176,7 @@ def _get_runner(checker=None, verbose=None, optionflags=0, continue_on_failure=T
class DoctestItem(pytest.Item): class DoctestItem(pytest.Item):
def __init__(self, name, parent, runner=None, dtest=None): def __init__(self, name, parent, runner=None, dtest=None):
super(DoctestItem, self).__init__(name, parent) super().__init__(name, parent)
self.runner = runner self.runner = runner
self.dtest = dtest self.dtest = dtest
self.obj = None self.obj = None
@ -253,7 +253,7 @@ class DoctestItem(pytest.Item):
] ]
indent = ">>>" indent = ">>>"
for line in example.source.splitlines(): for line in example.source.splitlines():
lines.append("??? %s %s" % (indent, line)) lines.append("??? {} {}".format(indent, line))
indent = "..." indent = "..."
if isinstance(failure, doctest.DocTestFailure): if isinstance(failure, doctest.DocTestFailure):
lines += checker.output_difference( lines += checker.output_difference(
@ -266,7 +266,7 @@ class DoctestItem(pytest.Item):
reprlocation_lines.append((reprlocation, lines)) reprlocation_lines.append((reprlocation, lines))
return ReprFailDoctest(reprlocation_lines) return ReprFailDoctest(reprlocation_lines)
else: else:
return super(DoctestItem, self).repr_failure(excinfo) return super().repr_failure(excinfo)
def reportinfo(self): def reportinfo(self):
return self.fspath, self.dtest.lineno, "[doctest] %s" % self.name return self.fspath, self.dtest.lineno, "[doctest] %s" % self.name

View File

@ -36,7 +36,7 @@ from _pytest.outcomes import TEST_OUTCOME
@attr.s(frozen=True) @attr.s(frozen=True)
class PseudoFixtureDef(object): class PseudoFixtureDef:
cached_result = attr.ib() cached_result = attr.ib()
scope = attr.ib() scope = attr.ib()
@ -76,7 +76,7 @@ def scopeproperty(name=None, doc=None):
if func.__name__ in scope2props[self.scope]: if func.__name__ in scope2props[self.scope]:
return func(self) return func(self)
raise AttributeError( raise AttributeError(
"%s not available in %s-scoped context" % (scopename, self.scope) "{} not available in {}-scoped context".format(scopename, self.scope)
) )
return property(provide, None, None, func.__doc__) return property(provide, None, None, func.__doc__)
@ -89,7 +89,7 @@ def get_scope_package(node, fixturedef):
cls = pytest.Package cls = pytest.Package
current = node current = node
fixture_package_name = "%s/%s" % (fixturedef.baseid, "__init__.py") fixture_package_name = "{}/{}".format(fixturedef.baseid, "__init__.py")
while current and ( while current and (
type(current) is not cls or fixture_package_name != current.nodeid type(current) is not cls or fixture_package_name != current.nodeid
): ):
@ -296,7 +296,7 @@ def get_direct_param_fixture_func(request):
@attr.s(slots=True) @attr.s(slots=True)
class FuncFixtureInfo(object): class FuncFixtureInfo:
# original function argument names # original function argument names
argnames = attr.ib(type=tuple) argnames = attr.ib(type=tuple)
# argnames that function immediately requires. These include argnames + # argnames that function immediately requires. These include argnames +
@ -652,7 +652,7 @@ class SubRequest(FixtureRequest):
self._fixturemanager = request._fixturemanager self._fixturemanager = request._fixturemanager
def __repr__(self): def __repr__(self):
return "<SubRequest %r for %r>" % (self.fixturename, self._pyfuncitem) return "<SubRequest {!r} for {!r}>".format(self.fixturename, self._pyfuncitem)
def addfinalizer(self, finalizer): def addfinalizer(self, finalizer):
self._fixturedef.addfinalizer(finalizer) self._fixturedef.addfinalizer(finalizer)
@ -665,7 +665,7 @@ class SubRequest(FixtureRequest):
fixturedef.addfinalizer( fixturedef.addfinalizer(
functools.partial(self._fixturedef.finish, request=self) functools.partial(self._fixturedef.finish, request=self)
) )
super(SubRequest, self)._schedule_finalizers(fixturedef, subrequest) super()._schedule_finalizers(fixturedef, subrequest)
scopes = "session package module class function".split() scopes = "session package module class function".split()
@ -718,7 +718,7 @@ class FixtureLookupError(LookupError):
error_msg = "file %s, line %s: source code not available" error_msg = "file %s, line %s: source code not available"
addline(error_msg % (fspath, lineno + 1)) addline(error_msg % (fspath, lineno + 1))
else: else:
addline("file %s, line %s" % (fspath, lineno + 1)) addline("file {}, line {}".format(fspath, lineno + 1))
for i, line in enumerate(lines): for i, line in enumerate(lines):
line = line.rstrip() line = line.rstrip()
addline(" " + line) addline(" " + line)
@ -774,7 +774,7 @@ class FixtureLookupErrorRepr(TerminalRepr):
def fail_fixturefunc(fixturefunc, msg): def fail_fixturefunc(fixturefunc, msg):
fs, lineno = getfslineno(fixturefunc) fs, lineno = getfslineno(fixturefunc)
location = "%s:%s" % (fs, lineno + 1) location = "{}:{}".format(fs, lineno + 1)
source = _pytest._code.Source(fixturefunc) source = _pytest._code.Source(fixturefunc)
fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False) fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False)
@ -804,7 +804,7 @@ def _teardown_yield_fixture(fixturefunc, it):
) )
class FixtureDef(object): class FixtureDef:
""" A container for a factory definition. """ """ A container for a factory definition. """
def __init__( def __init__(
@ -889,10 +889,8 @@ class FixtureDef(object):
return hook.pytest_fixture_setup(fixturedef=self, request=request) return hook.pytest_fixture_setup(fixturedef=self, request=request)
def __repr__(self): def __repr__(self):
return "<FixtureDef argname=%r scope=%r baseid=%r>" % ( return "<FixtureDef argname={!r} scope={!r} baseid={!r}>".format(
self.argname, self.argname, self.scope, self.baseid
self.scope,
self.baseid,
) )
@ -964,7 +962,7 @@ def wrap_function_to_error_out_if_called_directly(function, fixture_marker):
@attr.s(frozen=True) @attr.s(frozen=True)
class FixtureFunctionMarker(object): class FixtureFunctionMarker:
scope = attr.ib() scope = attr.ib()
params = attr.ib(converter=attr.converters.optional(tuple)) params = attr.ib(converter=attr.converters.optional(tuple))
autouse = attr.ib(default=False) autouse = attr.ib(default=False)
@ -1078,7 +1076,7 @@ def pytest_addoption(parser):
) )
class FixtureManager(object): class FixtureManager:
""" """
pytest fixtures definitions and information is stored and managed pytest fixtures definitions and information is stored and managed
from this class. from this class.

View File

@ -19,7 +19,7 @@ class HelpAction(Action):
""" """
def __init__(self, option_strings, dest=None, default=False, help=None): def __init__(self, option_strings, dest=None, default=False, help=None):
super(HelpAction, self).__init__( super().__init__(
option_strings=option_strings, option_strings=option_strings,
dest=dest, dest=dest,
const=True, const=True,
@ -117,7 +117,7 @@ def pytest_cmdline_parse():
def showversion(config): def showversion(config):
p = py.path.local(pytest.__file__) p = py.path.local(pytest.__file__)
sys.stderr.write( sys.stderr.write(
"This is pytest version %s, imported from %s\n" % (pytest.__version__, p) "This is pytest version {}, imported from {}\n".format(pytest.__version__, p)
) )
plugininfo = getpluginversioninfo(config) plugininfo = getpluginversioninfo(config)
if plugininfo: if plugininfo:
@ -155,7 +155,7 @@ def showhelp(config):
help, type, default = config._parser._inidict[name] help, type, default = config._parser._inidict[name]
if type is None: if type is None:
type = "string" type = "string"
spec = "%s (%s):" % (name, type) spec = "{} ({}):".format(name, type)
tw.write(" %s" % spec) tw.write(" %s" % spec)
spec_len = len(spec) spec_len = len(spec)
if spec_len > (indent_len - 3): if spec_len > (indent_len - 3):
@ -189,7 +189,7 @@ def showhelp(config):
("PYTEST_DEBUG", "set to enable debug tracing of pytest's internals"), ("PYTEST_DEBUG", "set to enable debug tracing of pytest's internals"),
] ]
for name, help in vars: for name, help in vars:
tw.line(" %-24s %s" % (name, help)) tw.line(" {:<24} {}".format(name, help))
tw.line() tw.line()
tw.line() tw.line()
@ -216,7 +216,7 @@ def getpluginversioninfo(config):
lines.append("setuptools registered plugins:") lines.append("setuptools registered plugins:")
for plugin, dist in plugininfo: for plugin, dist in plugininfo:
loc = getattr(plugin, "__file__", repr(plugin)) loc = getattr(plugin, "__file__", repr(plugin))
content = "%s-%s at %s" % (dist.project_name, dist.version, loc) content = "{}-{} at {}".format(dist.project_name, dist.version, loc)
lines.append(" " + content) lines.append(" " + content)
return lines return lines
@ -224,7 +224,9 @@ def getpluginversioninfo(config):
def pytest_report_header(config): def pytest_report_header(config):
lines = [] lines = []
if config.option.debug or config.option.traceconfig: if config.option.debug or config.option.traceconfig:
lines.append("using: pytest-%s pylib-%s" % (pytest.__version__, py.__version__)) lines.append(
"using: pytest-{} pylib-{}".format(pytest.__version__, py.__version__)
)
verinfo = getpluginversioninfo(config) verinfo = getpluginversioninfo(config)
if verinfo: if verinfo:
@ -238,5 +240,5 @@ def pytest_report_header(config):
r = plugin.__file__ r = plugin.__file__
else: else:
r = repr(plugin) r = repr(plugin)
lines.append(" %-20s: %s" % (name, r)) lines.append(" {:<20}: {}".format(name, r))
return lines return lines

View File

@ -15,7 +15,6 @@ import sys
import time import time
import py import py
import six
import pytest import pytest
from _pytest import nodes from _pytest import nodes
@ -34,12 +33,12 @@ class Junit(py.xml.Namespace):
_legal_chars = (0x09, 0x0A, 0x0D) _legal_chars = (0x09, 0x0A, 0x0D)
_legal_ranges = ((0x20, 0x7E), (0x80, 0xD7FF), (0xE000, 0xFFFD), (0x10000, 0x10FFFF)) _legal_ranges = ((0x20, 0x7E), (0x80, 0xD7FF), (0xE000, 0xFFFD), (0x10000, 0x10FFFF))
_legal_xml_re = [ _legal_xml_re = [
u"%s-%s" % (six.unichr(low), six.unichr(high)) "{}-{}".format(chr(low), chr(high))
for (low, high) in _legal_ranges for (low, high) in _legal_ranges
if low < sys.maxunicode if low < sys.maxunicode
] ]
_legal_xml_re = [six.unichr(x) for x in _legal_chars] + _legal_xml_re _legal_xml_re = [chr(x) for x in _legal_chars] + _legal_xml_re
illegal_xml_re = re.compile(u"[^%s]" % u"".join(_legal_xml_re)) illegal_xml_re = re.compile("[^%s]" % "".join(_legal_xml_re))
del _legal_chars del _legal_chars
del _legal_ranges del _legal_ranges
del _legal_xml_re del _legal_xml_re
@ -51,9 +50,9 @@ def bin_xml_escape(arg):
def repl(matchobj): def repl(matchobj):
i = ord(matchobj.group()) i = ord(matchobj.group())
if i <= 0xFF: if i <= 0xFF:
return u"#x%02X" % i return "#x%02X" % i
else: else:
return u"#x%04X" % i return "#x%04X" % i
return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg))) return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg)))
@ -80,7 +79,7 @@ merge_family(families["xunit1"], families["_base_legacy"])
families["xunit2"] = families["_base"] families["xunit2"] = families["_base"]
class _NodeReporter(object): class _NodeReporter:
def __init__(self, nodeid, xml): def __init__(self, nodeid, xml):
self.id = nodeid self.id = nodeid
self.xml = xml self.xml = xml
@ -220,7 +219,7 @@ class _NodeReporter(object):
else: else:
if hasattr(report.longrepr, "reprcrash"): if hasattr(report.longrepr, "reprcrash"):
message = report.longrepr.reprcrash.message message = report.longrepr.reprcrash.message
elif isinstance(report.longrepr, six.string_types): elif isinstance(report.longrepr, str):
message = report.longrepr message = report.longrepr
else: else:
message = str(report.longrepr) message = str(report.longrepr)
@ -259,7 +258,7 @@ class _NodeReporter(object):
filename, lineno, skipreason = report.longrepr filename, lineno, skipreason = report.longrepr
if skipreason.startswith("Skipped: "): if skipreason.startswith("Skipped: "):
skipreason = skipreason[9:] skipreason = skipreason[9:]
details = "%s:%s: %s" % (filename, lineno, skipreason) details = "{}:{}: {}".format(filename, lineno, skipreason)
self.append( self.append(
Junit.skipped( Junit.skipped(
@ -344,7 +343,7 @@ def _check_record_param_type(param, v):
"""Used by record_testsuite_property to check that the given parameter name is of the proper """Used by record_testsuite_property to check that the given parameter name is of the proper
type""" type"""
__tracebackhide__ = True __tracebackhide__ = True
if not isinstance(v, six.string_types): if not isinstance(v, str):
msg = "{param} parameter needs to be a string, but {g} given" msg = "{param} parameter needs to be a string, but {g} given"
raise TypeError(msg.format(param=param, g=type(v).__name__)) raise TypeError(msg.format(param=param, g=type(v).__name__))
@ -464,7 +463,7 @@ def mangle_test_address(address):
return names return names
class LogXML(object): class LogXML:
def __init__( def __init__(
self, self,
logfile, logfile,

View File

@ -37,7 +37,7 @@ class ColoredLevelFormatter(logging.Formatter):
LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*s)") LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*s)")
def __init__(self, terminalwriter, *args, **kwargs): def __init__(self, terminalwriter, *args, **kwargs):
super(ColoredLevelFormatter, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self._original_fmt = self._style._fmt self._original_fmt = self._style._fmt
self._level_to_fmt_mapping = {} self._level_to_fmt_mapping = {}
@ -63,7 +63,7 @@ class ColoredLevelFormatter(logging.Formatter):
def format(self, record): def format(self, record):
fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt) fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt)
self._style._fmt = fmt self._style._fmt = fmt
return super(ColoredLevelFormatter, self).format(record) return super().format(record)
if not six.PY2: if not six.PY2:
@ -235,7 +235,7 @@ class LogCaptureHandler(logging.StreamHandler):
self.stream = py.io.TextIO() self.stream = py.io.TextIO()
class LogCaptureFixture(object): class LogCaptureFixture:
"""Provides access and control of log capturing.""" """Provides access and control of log capturing."""
def __init__(self, item): def __init__(self, item):
@ -382,7 +382,7 @@ def get_actual_log_level(config, *setting_names):
else: else:
return return
if isinstance(log_level, six.string_types): if isinstance(log_level, str):
log_level = log_level.upper() log_level = log_level.upper()
try: try:
return int(getattr(logging, log_level, log_level)) return int(getattr(logging, log_level, log_level))
@ -401,7 +401,7 @@ def pytest_configure(config):
config.pluginmanager.register(LoggingPlugin(config), "logging-plugin") config.pluginmanager.register(LoggingPlugin(config), "logging-plugin")
class LoggingPlugin(object): class LoggingPlugin:
"""Attaches to the logging module and captures log messages for each test. """Attaches to the logging module and captures log messages for each test.
""" """

View File

@ -8,7 +8,6 @@ import warnings
import attr import attr
import py import py
import six
import _pytest._code import _pytest._code
from _pytest import nodes from _pytest import nodes
@ -166,7 +165,7 @@ def pytest_addoption(parser):
) )
class _ConfigDeprecated(object): class _ConfigDeprecated:
def __init__(self, config): def __init__(self, config):
self.__dict__["_config"] = config self.__dict__["_config"] = config
@ -305,10 +304,7 @@ def pytest_ignore_collect(path, config):
if excludeglobopt: if excludeglobopt:
ignore_globs.extend([py.path.local(x) for x in excludeglobopt]) ignore_globs.extend([py.path.local(x) for x in excludeglobopt])
if any( if any(fnmatch.fnmatch(str(path), str(glob)) for glob in ignore_globs):
fnmatch.fnmatch(six.text_type(path), six.text_type(glob))
for glob in ignore_globs
):
return True return True
allow_in_venv = config.getoption("collect_in_virtualenv") allow_in_venv = config.getoption("collect_in_virtualenv")
@ -336,7 +332,7 @@ def pytest_collection_modifyitems(items, config):
items[:] = remaining items[:] = remaining
class FSHookProxy(object): class FSHookProxy:
def __init__(self, fspath, pm, remove_mods): def __init__(self, fspath, pm, remove_mods):
self.fspath = fspath self.fspath = fspath
self.pm = pm self.pm = pm
@ -476,8 +472,8 @@ class Session(nodes.FSCollector):
if self._notfound: if self._notfound:
errors = [] errors = []
for arg, exc in self._notfound: for arg, exc in self._notfound:
line = "(no name %r in any of %r)" % (arg, exc.args[0]) line = "(no name {!r} in any of {!r})".format(arg, exc.args[0])
errors.append("not found: %s\n%s" % (arg, line)) errors.append("not found: {}\n{}".format(arg, line))
# XXX: test this # XXX: test this
raise UsageError(*errors) raise UsageError(*errors)
if not genitems: if not genitems:
@ -494,8 +490,7 @@ class Session(nodes.FSCollector):
self.trace("processing argument", arg) self.trace("processing argument", arg)
self.trace.root.indent += 1 self.trace.root.indent += 1
try: try:
for x in self._collect(arg): yield from self._collect(arg)
yield x
except NoMatch: except NoMatch:
# we are inside a make_report hook so # we are inside a make_report hook so
# we cannot directly pass through the exception # we cannot directly pass through the exception
@ -532,7 +527,7 @@ class Session(nodes.FSCollector):
# If it's a directory argument, recurse and look for any Subpackages. # If it's a directory argument, recurse and look for any Subpackages.
# Let the Package collector deal with subnodes, don't collect here. # Let the Package collector deal with subnodes, don't collect here.
if argpath.check(dir=1): if argpath.check(dir=1):
assert not names, "invalid arg %r" % (arg,) assert not names, "invalid arg {!r}".format(arg)
seen_dirs = set() seen_dirs = set()
for path in argpath.visit( for path in argpath.visit(
@ -577,15 +572,13 @@ class Session(nodes.FSCollector):
if argpath.basename == "__init__.py": if argpath.basename == "__init__.py":
yield next(m[0].collect()) yield next(m[0].collect())
return return
for y in m: yield from m
yield y
def _collectfile(self, path, handle_dupes=True): def _collectfile(self, path, handle_dupes=True):
assert path.isfile(), "%r is not a file (isdir=%r, exists=%r, islink=%r)" % ( assert (
path, path.isfile()
path.isdir(), ), "{!r} is not a file (isdir={!r}, exists={!r}, islink={!r})".format(
path.exists(), path, path.isdir(), path.exists(), path.islink()
path.islink(),
) )
ihook = self.gethookproxy(path) ihook = self.gethookproxy(path)
if not self.isinitpath(path): if not self.isinitpath(path):
@ -713,6 +706,5 @@ class Session(nodes.FSCollector):
rep = collect_one_node(node) rep = collect_one_node(node)
if rep.passed: if rep.passed:
for subnode in rep.result: for subnode in rep.result:
for x in self.genitems(subnode): yield from self.genitems(subnode)
yield x
node.ihook.pytest_collectreport(report=rep) node.ihook.pytest_collectreport(report=rep)

View File

@ -3,8 +3,6 @@ import platform
import sys import sys
import traceback import traceback
import six
from ..outcomes import fail from ..outcomes import fail
from ..outcomes import TEST_OUTCOME from ..outcomes import TEST_OUTCOME
@ -22,7 +20,7 @@ def cached_eval(config, expr, d):
return x return x
class MarkEvaluator(object): class MarkEvaluator:
def __init__(self, item, name): def __init__(self, item, name):
self.item = item self.item = item
self._marks = None self._marks = None
@ -86,7 +84,7 @@ class MarkEvaluator(object):
for expr in args: for expr in args:
self.expr = expr self.expr = expr
if isinstance(expr, six.string_types): if isinstance(expr, str):
d = self._getglobals() d = self._getglobals()
result = cached_eval(self.item.config, expr, d) result = cached_eval(self.item.config, expr, d)
else: else:

View File

@ -10,7 +10,7 @@ from _pytest.config import UsageError
@attr.s @attr.s
class MarkMapping(object): class MarkMapping:
"""Provides a local mapping for markers where item access """Provides a local mapping for markers where item access
resolves to True if the marker is present. """ resolves to True if the marker is present. """
@ -25,7 +25,7 @@ class MarkMapping(object):
return name in self.own_mark_names return name in self.own_mark_names
class KeywordMapping(object): class KeywordMapping:
"""Provides a local mapping for keywords. """Provides a local mapping for keywords.
Given a list of names, map any substring of one of these names to True. Given a list of names, map any substring of one of these names to True.
""" """

View File

@ -5,7 +5,6 @@ from collections.abc import MutableMapping
from operator import attrgetter from operator import attrgetter
import attr import attr
import six
from ..compat import ascii_escaped from ..compat import ascii_escaped
from ..compat import getfslineno from ..compat import getfslineno
@ -71,7 +70,7 @@ class ParameterSet(namedtuple("ParameterSet", "values, marks, id")):
id_ = kwargs.pop("id", None) id_ = kwargs.pop("id", None)
if id_ is not None: if id_ is not None:
if not isinstance(id_, six.string_types): if not isinstance(id_, str):
raise TypeError( raise TypeError(
"Expected id to be a string, got {}: {!r}".format(type(id_), id_) "Expected id to be a string, got {}: {!r}".format(type(id_), id_)
) )
@ -157,7 +156,7 @@ class ParameterSet(namedtuple("ParameterSet", "values, marks, id")):
@attr.s(frozen=True) @attr.s(frozen=True)
class Mark(object): class Mark:
#: name of the mark #: name of the mark
name = attr.ib(type=str) name = attr.ib(type=str)
#: positional arguments of the mark decorator #: positional arguments of the mark decorator
@ -180,7 +179,7 @@ class Mark(object):
@attr.s @attr.s
class MarkDecorator(object): class MarkDecorator:
""" A decorator for test functions and test classes. When applied """ A decorator for test functions and test classes. When applied
it will create :class:`MarkInfo` objects which may be it will create :class:`MarkInfo` objects which may be
:ref:`retrieved by hooks as item keywords <excontrolskip>`. :ref:`retrieved by hooks as item keywords <excontrolskip>`.
@ -228,7 +227,7 @@ class MarkDecorator(object):
return self.mark == other.mark if isinstance(other, MarkDecorator) else False return self.mark == other.mark if isinstance(other, MarkDecorator) else False
def __repr__(self): def __repr__(self):
return "<MarkDecorator %r>" % (self.mark,) return "<MarkDecorator {!r}>".format(self.mark)
def with_args(self, *args, **kwargs): def with_args(self, *args, **kwargs):
""" return a MarkDecorator with extra arguments added """ return a MarkDecorator with extra arguments added
@ -289,7 +288,7 @@ def store_mark(obj, mark):
obj.pytestmark = get_unpacked_marks(obj) + [mark] obj.pytestmark = get_unpacked_marks(obj) + [mark]
class MarkGenerator(object): class MarkGenerator:
""" Factory for :class:`MarkDecorator` objects - exposed as """ Factory for :class:`MarkDecorator` objects - exposed as
a ``pytest.mark`` singleton instance. Example:: a ``pytest.mark`` singleton instance. Example::
@ -376,11 +375,11 @@ class NodeKeywords(MutableMapping):
return len(self._seen()) return len(self._seen())
def __repr__(self): def __repr__(self):
return "<NodeKeywords for node %s>" % (self.node,) return "<NodeKeywords for node {}>".format(self.node)
@attr.s(cmp=False, hash=False) @attr.s(cmp=False, hash=False)
class NodeMarkers(object): class NodeMarkers:
""" """
internal structure for storing marks belonging to a node internal structure for storing marks belonging to a node

View File

@ -5,8 +5,6 @@ import sys
import warnings import warnings
from contextlib import contextmanager from contextlib import contextmanager
import six
import pytest import pytest
from _pytest.fixtures import fixture from _pytest.fixtures import fixture
from _pytest.pathlib import Path from _pytest.pathlib import Path
@ -62,7 +60,7 @@ def resolve(name):
if expected == used: if expected == used:
raise raise
else: else:
raise ImportError("import error in %s: %s" % (used, ex)) raise ImportError("import error in {}: {}".format(used, ex))
found = annotated_getattr(found, part, used) found = annotated_getattr(found, part, used)
return found return found
@ -72,14 +70,18 @@ def annotated_getattr(obj, name, ann):
obj = getattr(obj, name) obj = getattr(obj, name)
except AttributeError: except AttributeError:
raise AttributeError( raise AttributeError(
"%r object at %s has no attribute %r" % (type(obj).__name__, ann, name) "{!r} object at {} has no attribute {!r}".format(
type(obj).__name__, ann, name
)
) )
return obj return obj
def derive_importpath(import_path, raising): def derive_importpath(import_path, raising):
if not isinstance(import_path, six.string_types) or "." not in import_path: if not isinstance(import_path, str) or "." not in import_path:
raise TypeError("must be absolute import path string, not %r" % (import_path,)) raise TypeError(
"must be absolute import path string, not {!r}".format(import_path)
)
module, attr = import_path.rsplit(".", 1) module, attr = import_path.rsplit(".", 1)
target = resolve(module) target = resolve(module)
if raising: if raising:
@ -87,7 +89,7 @@ def derive_importpath(import_path, raising):
return attr, target return attr, target
class Notset(object): class Notset:
def __repr__(self): def __repr__(self):
return "<notset>" return "<notset>"
@ -95,7 +97,7 @@ class Notset(object):
notset = Notset() notset = Notset()
class MonkeyPatch(object): class MonkeyPatch:
""" Object returned by the ``monkeypatch`` fixture keeping a record of setattr/item/env/syspath changes. """ Object returned by the ``monkeypatch`` fixture keeping a record of setattr/item/env/syspath changes.
""" """
@ -146,7 +148,7 @@ class MonkeyPatch(object):
import inspect import inspect
if value is notset: if value is notset:
if not isinstance(target, six.string_types): if not isinstance(target, str):
raise TypeError( raise TypeError(
"use setattr(target, name, value) or " "use setattr(target, name, value) or "
"setattr(target, value) with target being a dotted " "setattr(target, value) with target being a dotted "
@ -157,7 +159,7 @@ class MonkeyPatch(object):
oldval = getattr(target, name, notset) oldval = getattr(target, name, notset)
if raising and oldval is notset: if raising and oldval is notset:
raise AttributeError("%r has no attribute %r" % (target, name)) raise AttributeError("{!r} has no attribute {!r}".format(target, name))
# avoid class descriptors like staticmethod/classmethod # avoid class descriptors like staticmethod/classmethod
if inspect.isclass(target): if inspect.isclass(target):
@ -180,7 +182,7 @@ class MonkeyPatch(object):
import inspect import inspect
if name is notset: if name is notset:
if not isinstance(target, six.string_types): if not isinstance(target, str):
raise TypeError( raise TypeError(
"use delattr(target, name) or " "use delattr(target, name) or "
"delattr(target) with target being a dotted " "delattr(target) with target being a dotted "

View File

@ -2,7 +2,6 @@ import os
import warnings import warnings
import py import py
import six
import _pytest._code import _pytest._code
from _pytest.compat import getfslineno from _pytest.compat import getfslineno
@ -50,7 +49,7 @@ def ischildnode(baseid, nodeid):
return node_parts[: len(base_parts)] == base_parts return node_parts[: len(base_parts)] == base_parts
class Node(object): class Node:
""" base class for Collector and Item the test collection tree. """ base class for Collector and Item the test collection tree.
Collector subclasses have children, Items are terminal nodes.""" Collector subclasses have children, Items are terminal nodes."""
@ -98,7 +97,7 @@ class Node(object):
return self.session.gethookproxy(self.fspath) return self.session.gethookproxy(self.fspath)
def __repr__(self): def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, getattr(self, "name", None)) return "<{} {}>".format(self.__class__.__name__, getattr(self, "name", None))
def warn(self, warning): def warn(self, warning):
"""Issue a warning for this item. """Issue a warning for this item.
@ -168,7 +167,7 @@ class Node(object):
""" """
from _pytest.mark import MarkDecorator, MARK_GEN from _pytest.mark import MarkDecorator, MARK_GEN
if isinstance(marker, six.string_types): if isinstance(marker, str):
marker = getattr(MARK_GEN, marker) marker = getattr(MARK_GEN, marker)
elif not isinstance(marker, MarkDecorator): elif not isinstance(marker, MarkDecorator):
raise ValueError("is not a string or pytest.mark.* Marker") raise ValueError("is not a string or pytest.mark.* Marker")
@ -239,7 +238,7 @@ class Node(object):
def _repr_failure_py(self, excinfo, style=None): def _repr_failure_py(self, excinfo, style=None):
if excinfo.errisinstance(fail.Exception): if excinfo.errisinstance(fail.Exception):
if not excinfo.value.pytrace: if not excinfo.value.pytrace:
return six.text_type(excinfo.value) return str(excinfo.value)
fm = self.session._fixturemanager fm = self.session._fixturemanager
if excinfo.errisinstance(fm.FixtureLookupError): if excinfo.errisinstance(fm.FixtureLookupError):
return excinfo.value.formatrepr() return excinfo.value.formatrepr()
@ -366,9 +365,7 @@ class FSCollector(Collector):
if nodeid and os.sep != SEP: if nodeid and os.sep != SEP:
nodeid = nodeid.replace(os.sep, SEP) nodeid = nodeid.replace(os.sep, SEP)
super(FSCollector, self).__init__( super().__init__(name, parent, config, session, nodeid=nodeid, fspath=fspath)
name, parent, config, session, nodeid=nodeid, fspath=fspath
)
class File(FSCollector): class File(FSCollector):
@ -383,7 +380,7 @@ class Item(Node):
nextitem = None nextitem = None
def __init__(self, name, parent=None, config=None, session=None, nodeid=None): def __init__(self, name, parent=None, config=None, session=None, nodeid=None):
super(Item, self).__init__(name, parent, config, session, nodeid=nodeid) super().__init__(name, parent, config, session, nodeid=nodeid)
self._report_sections = [] self._report_sections = []
#: user properties is a list of tuples (name, value) that holds user #: user properties is a list of tuples (name, value) that holds user

View File

@ -1,8 +1,6 @@
""" run test suites written for nose. """ """ run test suites written for nose. """
import sys import sys
import six
import pytest import pytest
from _pytest import python from _pytest import python
from _pytest import runner from _pytest import runner
@ -23,7 +21,7 @@ def pytest_runtest_makereport(item, call):
if call.excinfo and call.excinfo.errisinstance(get_skip_exceptions()): if call.excinfo and call.excinfo.errisinstance(get_skip_exceptions()):
# let's substitute the excinfo with a pytest.skip one # let's substitute the excinfo with a pytest.skip one
call2 = runner.CallInfo.from_call( call2 = runner.CallInfo.from_call(
lambda: pytest.skip(six.text_type(call.excinfo.value)), call.when lambda: pytest.skip(str(call.excinfo.value)), call.when
) )
call.excinfo = call2.excinfo call.excinfo = call2.excinfo

View File

@ -23,7 +23,7 @@ class OutcomeException(BaseException):
if isinstance(val, bytes): if isinstance(val, bytes):
val = val.decode("UTF-8", errors="replace") val = val.decode("UTF-8", errors="replace")
return val return val
return "<%s instance>" % (self.__class__.__name__,) return "<{} instance>".format(self.__class__.__name__)
__str__ = __repr__ __str__ = __repr__
@ -53,7 +53,7 @@ class Exit(Exception):
def __init__(self, msg="unknown reason", returncode=None): def __init__(self, msg="unknown reason", returncode=None):
self.msg = msg self.msg = msg
self.returncode = returncode self.returncode = returncode
super(Exit, self).__init__(msg) super().__init__(msg)
# exposed helper methods # exposed helper methods
@ -166,7 +166,7 @@ def importorskip(modname, minversion=None, reason=None):
import_exc = exc import_exc = exc
if import_exc: if import_exc:
if reason is None: if reason is None:
reason = "could not import %r: %s" % (modname, import_exc) reason = "could not import {!r}: {}".format(modname, import_exc)
raise Skipped(reason, allow_module_level=True) raise Skipped(reason, allow_module_level=True)
mod = sys.modules[modname] mod = sys.modules[modname]
if minversion is None: if minversion is None:

View File

@ -1,8 +1,6 @@
""" submit failure or test session information to a pastebin service. """ """ submit failure or test session information to a pastebin service. """
import tempfile import tempfile
import six
import pytest import pytest
@ -33,7 +31,7 @@ def pytest_configure(config):
def tee_write(s, **kwargs): def tee_write(s, **kwargs):
oldwrite(s, **kwargs) oldwrite(s, **kwargs)
if isinstance(s, six.text_type): if isinstance(s, str):
s = s.encode("utf-8") s = s.encode("utf-8")
config._pastebinfile.write(s) config._pastebinfile.write(s)
@ -72,7 +70,7 @@ def create_new_paste(contents):
response = urlopen(url, data=urlencode(params).encode("ascii")).read() response = urlopen(url, data=urlencode(params).encode("ascii")).read()
m = re.search(r'href="/raw/(\w+)"', response.decode("utf-8")) m = re.search(r'href="/raw/(\w+)"', response.decode("utf-8"))
if m: if m:
return "%s/show/%s" % (url, m.group(1)) return "{}/show/{}".format(url, m.group(1))
else: else:
return "bad response: " + response return "bad response: " + response
@ -97,4 +95,4 @@ def pytest_terminal_summary(terminalreporter):
s = tw.stringio.getvalue() s = tw.stringio.getvalue()
assert len(s) assert len(s)
pastebinurl = create_new_paste(s) pastebinurl = create_new_paste(s)
tr.write_line("%s --> %s" % (msg, pastebinurl)) tr.write_line("{} --> {}".format(msg, pastebinurl))

View File

@ -13,8 +13,6 @@ from os.path import isabs
from os.path import sep from os.path import sep
from posixpath import sep as posix_sep from posixpath import sep as posix_sep
import six
if sys.version_info[:2] >= (3, 6): if sys.version_info[:2] >= (3, 6):
from pathlib import Path, PurePath from pathlib import Path, PurePath
@ -128,9 +126,10 @@ def create_cleanup_lock(p):
fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
except OSError as e: except OSError as e:
if e.errno == errno.EEXIST: if e.errno == errno.EEXIST:
six.raise_from( raise EnvironmentError(
EnvironmentError("cannot create lockfile in {path}".format(path=p)), e "cannot create lockfile in {path}".format(path=p)
) ) from e
else: else:
raise raise
else: else:
@ -296,7 +295,7 @@ def fnmatch_ex(pattern, path):
if sep not in pattern: if sep not in pattern:
name = path.name name = path.name
else: else:
name = six.text_type(path) name = str(path)
return fnmatch.fnmatch(name, pattern) return fnmatch.fnmatch(name, pattern)

View File

@ -13,7 +13,6 @@ from fnmatch import fnmatch
from weakref import WeakKeyDictionary from weakref import WeakKeyDictionary
import py import py
import six
import pytest import pytest
from _pytest._code import Source from _pytest._code import Source
@ -28,7 +27,7 @@ from _pytest.monkeypatch import MonkeyPatch
from _pytest.pathlib import Path from _pytest.pathlib import Path
IGNORE_PAM = [ # filenames added when obtaining details about the current user IGNORE_PAM = [ # filenames added when obtaining details about the current user
u"/var/lib/sss/mc/passwd" "/var/lib/sss/mc/passwd"
] ]
@ -78,7 +77,7 @@ def raise_on_kwargs(kwargs):
) )
class LsofFdLeakChecker(object): class LsofFdLeakChecker:
def get_open_files(self): def get_open_files(self):
out = self._exec_lsof() out = self._exec_lsof()
open_files = self._parse_lsof_output(out) open_files = self._parse_lsof_output(out)
@ -160,7 +159,7 @@ def _pytest(request):
return PytestArg(request) return PytestArg(request)
class PytestArg(object): class PytestArg:
def __init__(self, request): def __init__(self, request):
self.request = request self.request = request
@ -175,7 +174,7 @@ def get_public_names(values):
return [x for x in values if x[0] != "_"] return [x for x in values if x[0] != "_"]
class ParsedCall(object): class ParsedCall:
def __init__(self, name, kwargs): def __init__(self, name, kwargs):
self.__dict__.update(kwargs) self.__dict__.update(kwargs)
self._name = name self._name = name
@ -183,10 +182,10 @@ class ParsedCall(object):
def __repr__(self): def __repr__(self):
d = self.__dict__.copy() d = self.__dict__.copy()
del d["_name"] del d["_name"]
return "<ParsedCall %r(**%r)>" % (self._name, d) return "<ParsedCall {!r}(**{!r})>".format(self._name, d)
class HookRecorder(object): class HookRecorder:
"""Record all hooks called in a plugin manager. """Record all hooks called in a plugin manager.
This wraps all the hook calls in the plugin manager, recording each call This wraps all the hook calls in the plugin manager, recording each call
@ -233,7 +232,7 @@ class HookRecorder(object):
break break
print("NONAMEMATCH", name, "with", call) print("NONAMEMATCH", name, "with", call)
else: else:
pytest.fail("could not find %r check %r" % (name, check)) pytest.fail("could not find {!r} check {!r}".format(name, check))
def popcall(self, name): def popcall(self, name):
__tracebackhide__ = True __tracebackhide__ = True
@ -241,7 +240,7 @@ class HookRecorder(object):
if call._name == name: if call._name == name:
del self.calls[i] del self.calls[i]
return call return call
lines = ["could not find call %r, in:" % (name,)] lines = ["could not find call {!r}, in:".format(name)]
lines.extend([" %s" % x for x in self.calls]) lines.extend([" %s" % x for x in self.calls])
pytest.fail("\n".join(lines)) pytest.fail("\n".join(lines))
@ -278,7 +277,9 @@ class HookRecorder(object):
) )
if len(values) > 1: if len(values) > 1:
raise ValueError( raise ValueError(
"found 2 or more testreports matching %r: %s" % (inamepart, values) "found 2 or more testreports matching {!r}: {}".format(
inamepart, values
)
) )
return values[0] return values[0]
@ -352,7 +353,7 @@ def _config_for_test():
rex_outcome = re.compile(r"(\d+) ([\w-]+)") rex_outcome = re.compile(r"(\d+) ([\w-]+)")
class RunResult(object): class RunResult:
"""The result of running a command. """The result of running a command.
Attributes: Attributes:
@ -424,7 +425,7 @@ class RunResult(object):
assert obtained == expected assert obtained == expected
class CwdSnapshot(object): class CwdSnapshot:
def __init__(self): def __init__(self):
self.__saved = os.getcwd() self.__saved = os.getcwd()
@ -432,7 +433,7 @@ class CwdSnapshot(object):
os.chdir(self.__saved) os.chdir(self.__saved)
class SysModulesSnapshot(object): class SysModulesSnapshot:
def __init__(self, preserve=None): def __init__(self, preserve=None):
self.__preserve = preserve self.__preserve = preserve
self.__saved = dict(sys.modules) self.__saved = dict(sys.modules)
@ -446,7 +447,7 @@ class SysModulesSnapshot(object):
sys.modules.update(self.__saved) sys.modules.update(self.__saved)
class SysPathsSnapshot(object): class SysPathsSnapshot:
def __init__(self): def __init__(self):
self.__saved = list(sys.path), list(sys.meta_path) self.__saved = list(sys.path), list(sys.meta_path)
@ -454,7 +455,7 @@ class SysPathsSnapshot(object):
sys.path[:], sys.meta_path[:] = self.__saved sys.path[:], sys.meta_path[:] = self.__saved
class Testdir(object): class Testdir:
"""Temporary test directory with tools to test/run pytest itself. """Temporary test directory with tools to test/run pytest itself.
This is based on the ``tmpdir`` fixture but provides a number of methods This is based on the ``tmpdir`` fixture but provides a number of methods
@ -507,7 +508,7 @@ class Testdir(object):
self._env_run_update = {"HOME": tmphome, "USERPROFILE": tmphome} self._env_run_update = {"HOME": tmphome, "USERPROFILE": tmphome}
def __repr__(self): def __repr__(self):
return "<Testdir %r>" % (self.tmpdir,) return "<Testdir {!r}>".format(self.tmpdir)
def __str__(self): def __str__(self):
return str(self.tmpdir) return str(self.tmpdir)
@ -552,10 +553,10 @@ class Testdir(object):
items = list(kwargs.items()) items = list(kwargs.items())
def to_text(s): def to_text(s):
return s.decode(encoding) if isinstance(s, bytes) else six.text_type(s) return s.decode(encoding) if isinstance(s, bytes) else str(s)
if args: if args:
source = u"\n".join(to_text(x) for x in args) source = "\n".join(to_text(x) for x in args)
basename = self.request.function.__name__ basename = self.request.function.__name__
items.insert(0, (basename, source)) items.insert(0, (basename, source))
@ -564,7 +565,7 @@ class Testdir(object):
p = self.tmpdir.join(basename).new(ext=ext) p = self.tmpdir.join(basename).new(ext=ext)
p.dirpath().ensure_dir() p.dirpath().ensure_dir()
source = Source(value) source = Source(value)
source = u"\n".join(to_text(line) for line in source.lines) source = "\n".join(to_text(line) for line in source.lines)
p.write(source.strip().encode(encoding), "wb") p.write(source.strip().encode(encoding), "wb")
if ret is None: if ret is None:
ret = p ret = p
@ -833,7 +834,7 @@ class Testdir(object):
rec = [] rec = []
class Collect(object): class Collect:
def pytest_configure(x, config): def pytest_configure(x, config):
rec.append(self.make_hook_recorder(config.pluginmanager)) rec.append(self.make_hook_recorder(config.pluginmanager))
@ -843,7 +844,7 @@ class Testdir(object):
reprec = rec.pop() reprec = rec.pop()
else: else:
class reprec(object): class reprec:
pass pass
reprec.ret = ret reprec.ret = ret
@ -875,13 +876,13 @@ class Testdir(object):
reprec = self.inline_run(*args, **kwargs) reprec = self.inline_run(*args, **kwargs)
except SystemExit as e: except SystemExit as e:
class reprec(object): class reprec:
ret = e.args[0] ret = e.args[0]
except Exception: except Exception:
traceback.print_exc() traceback.print_exc()
class reprec(object): class reprec:
ret = 3 ret = 3
finally: finally:
@ -963,10 +964,8 @@ class Testdir(object):
for item in items: for item in items:
if item.name == funcname: if item.name == funcname:
return item return item
assert 0, "%r item not found in module:\n%s\nitems: %s" % ( assert 0, "{!r} item not found in module:\n{}\nitems: {}".format(
funcname, funcname, source, items
source,
items,
) )
def getitems(self, source): def getitems(self, source):
@ -1143,7 +1142,7 @@ class Testdir(object):
for line in lines: for line in lines:
print(line, file=fp) print(line, file=fp)
except UnicodeEncodeError: except UnicodeEncodeError:
print("couldn't print to %s because of encoding" % (fp,)) print("couldn't print to {} because of encoding".format(fp))
def _getpytestargs(self): def _getpytestargs(self):
return sys.executable, "-mpytest" return sys.executable, "-mpytest"
@ -1200,7 +1199,7 @@ class Testdir(object):
""" """
basetemp = self.tmpdir.mkdir("temp-pexpect") basetemp = self.tmpdir.mkdir("temp-pexpect")
invoke = " ".join(map(str, self._getpytestargs())) invoke = " ".join(map(str, self._getpytestargs()))
cmd = "%s --basetemp=%s %s" % (invoke, basetemp, string) cmd = "{} --basetemp={} {}".format(invoke, basetemp, string)
return self.spawn(cmd, expect_timeout=expect_timeout) return self.spawn(cmd, expect_timeout=expect_timeout)
def spawn(self, cmd, expect_timeout=10.0): def spawn(self, cmd, expect_timeout=10.0):
@ -1230,10 +1229,12 @@ def getdecoded(out):
try: try:
return out.decode("utf-8") return out.decode("utf-8")
except UnicodeDecodeError: except UnicodeDecodeError:
return "INTERNAL not-utf8-decodeable, truncated string:\n%s" % (saferepr(out),) return "INTERNAL not-utf8-decodeable, truncated string:\n{}".format(
saferepr(out)
)
class LineComp(object): class LineComp:
def __init__(self): def __init__(self):
self.stringio = py.io.TextIO() self.stringio = py.io.TextIO()
@ -1251,7 +1252,7 @@ class LineComp(object):
return LineMatcher(lines1).fnmatch_lines(lines2) return LineMatcher(lines1).fnmatch_lines(lines2)
class LineMatcher(object): class LineMatcher:
"""Flexible matching of text. """Flexible matching of text.
This is a convenience class to test large texts like the output of This is a convenience class to test large texts like the output of
@ -1389,5 +1390,5 @@ class LineMatcher(object):
self._log(" and:", repr(nextline)) self._log(" and:", repr(nextline))
extralines.append(nextline) extralines.append(nextline)
else: else:
self._log("remains unmatched: %r" % (line,)) self._log("remains unmatched: {!r}".format(line))
pytest.fail(self._log_text) pytest.fail(self._log_text)

View File

@ -10,7 +10,6 @@ from functools import partial
from textwrap import dedent from textwrap import dedent
import py import py
import six
import _pytest import _pytest
from _pytest import deprecated from _pytest import deprecated
@ -49,8 +48,8 @@ def pyobj_property(name):
if node is not None: if node is not None:
return node.obj return node.obj
doc = "python %s object this node was collected from (can be None)." % ( doc = "python {} object this node was collected from (can be None).".format(
name.lower(), name.lower()
) )
return property(get, None, None, doc) return property(get, None, None, doc)
@ -233,7 +232,7 @@ def pytest_make_parametrize_id(config, val, argname=None):
return None return None
class PyobjContext(object): class PyobjContext:
module = pyobj_property("Module") module = pyobj_property("Module")
cls = pyobj_property("Class") cls = pyobj_property("Class")
instance = pyobj_property("Instance") instance = pyobj_property("Instance")
@ -243,7 +242,7 @@ class PyobjMixin(PyobjContext):
_ALLOW_MARKERS = True _ALLOW_MARKERS = True
def __init__(self, *k, **kw): def __init__(self, *k, **kw):
super(PyobjMixin, self).__init__(*k, **kw) super().__init__(*k, **kw)
@property @property
def obj(self): def obj(self):
@ -415,7 +414,7 @@ class PyCollector(PyobjMixin, nodes.Collector):
fixtureinfo.prune_dependency_tree() fixtureinfo.prune_dependency_tree()
for callspec in metafunc._calls: for callspec in metafunc._calls:
subname = "%s[%s]" % (name, callspec.id) subname = "{}[{}]".format(name, callspec.id)
yield Function( yield Function(
name=subname, name=subname,
parent=self, parent=self,
@ -437,7 +436,7 @@ class Module(nodes.File, PyCollector):
self._inject_setup_module_fixture() self._inject_setup_module_fixture()
self._inject_setup_function_fixture() self._inject_setup_function_fixture()
self.session._fixturemanager.parsefactories(self) self.session._fixturemanager.parsefactories(self)
return super(Module, self).collect() return super().collect()
def _inject_setup_module_fixture(self): def _inject_setup_module_fixture(self):
"""Injects a hidden autouse, module scoped fixture into the collected module object """Injects a hidden autouse, module scoped fixture into the collected module object
@ -600,11 +599,10 @@ class Package(Module):
return proxy return proxy
def _collectfile(self, path, handle_dupes=True): def _collectfile(self, path, handle_dupes=True):
assert path.isfile(), "%r is not a file (isdir=%r, exists=%r, islink=%r)" % ( assert (
path, path.isfile()
path.isdir(), ), "{!r} is not a file (isdir={!r}, exists={!r}, islink={!r})".format(
path.exists(), path, path.isdir(), path.exists(), path.islink()
path.islink(),
) )
ihook = self.gethookproxy(path) ihook = self.gethookproxy(path)
if not self.isinitpath(path): if not self.isinitpath(path):
@ -651,8 +649,7 @@ class Package(Module):
continue continue
if is_file: if is_file:
for x in self._collectfile(path): yield from self._collectfile(path)
yield x
elif not path.isdir(): elif not path.isdir():
# Broken symlink or invalid/missing file. # Broken symlink or invalid/missing file.
continue continue
@ -794,7 +791,7 @@ class Instance(PyCollector):
def collect(self): def collect(self):
self.session._fixturemanager.parsefactories(self) self.session._fixturemanager.parsefactories(self)
return super(Instance, self).collect() return super().collect()
def newinstance(self): def newinstance(self):
self.obj = self._getobj() self.obj = self._getobj()
@ -852,7 +849,7 @@ def hasnew(obj):
return new != object.__new__ return new != object.__new__
class CallSpec2(object): class CallSpec2:
def __init__(self, metafunc): def __init__(self, metafunc):
self.metafunc = metafunc self.metafunc = metafunc
self.funcargs = {} self.funcargs = {}
@ -878,7 +875,7 @@ class CallSpec2(object):
def _checkargnotcontained(self, arg): def _checkargnotcontained(self, arg):
if arg in self.params or arg in self.funcargs: if arg in self.params or arg in self.funcargs:
raise ValueError("duplicate %r" % (arg,)) raise ValueError("duplicate {!r}".format(arg))
def getparam(self, name): def getparam(self, name):
try: try:
@ -1054,7 +1051,7 @@ class Metafunc(fixtures.FuncargnamesCompatAttr):
msg = "In {}: {} parameter sets specified, with different number of ids: {}" msg = "In {}: {} parameter sets specified, with different number of ids: {}"
fail(msg.format(func_name, len(parameters), len(ids)), pytrace=False) fail(msg.format(func_name, len(parameters), len(ids)), pytrace=False)
for id_value in ids: for id_value in ids:
if id_value is not None and not isinstance(id_value, six.string_types): if id_value is not None and not isinstance(id_value, str):
msg = "In {}: ids must be list of strings, found: {} (type: {!r})" msg = "In {}: ids must be list of strings, found: {} (type: {!r})"
fail( fail(
msg.format(func_name, saferepr(id_value), type(id_value)), msg.format(func_name, saferepr(id_value), type(id_value)),
@ -1177,7 +1174,7 @@ def _idval(val, argname, idx, idfn, item, config):
msg = msg.format(item.nodeid, argname, idx) msg = msg.format(item.nodeid, argname, idx)
# we only append the exception type and message because on Python 2 reraise does nothing # we only append the exception type and message because on Python 2 reraise does nothing
msg += " {}: {}\n".format(type(e).__name__, e) msg += " {}: {}\n".format(type(e).__name__, e)
six.raise_from(ValueError(msg), e) raise ValueError(msg) from e
elif config: elif config:
hook_id = config.hook.pytest_make_parametrize_id( hook_id = config.hook.pytest_make_parametrize_id(
config=config, val=val, argname=argname config=config, val=val, argname=argname
@ -1329,7 +1326,7 @@ def _showfixtures_main(config, session):
if currentmodule != module: if currentmodule != module:
if not module.startswith("_pytest."): if not module.startswith("_pytest."):
tw.line() tw.line()
tw.sep("-", "fixtures defined from %s" % (module,)) tw.sep("-", "fixtures defined from {}".format(module))
currentmodule = module currentmodule = module
if verbose <= 0 and argname[0] == "_": if verbose <= 0 and argname[0] == "_":
continue continue
@ -1344,7 +1341,7 @@ def _showfixtures_main(config, session):
if doc: if doc:
write_docstring(tw, doc) write_docstring(tw, doc)
else: else:
tw.line(" %s: no docstring available" % (loc,), red=True) tw.line(" {}: no docstring available".format(loc), red=True)
tw.line() tw.line()
@ -1384,7 +1381,7 @@ class Function(FunctionMixin, nodes.Item, fixtures.FuncargnamesCompatAttr):
fixtureinfo=None, fixtureinfo=None,
originalname=None, originalname=None,
): ):
super(Function, self).__init__(name, parent, config=config, session=session) super().__init__(name, parent, config=config, session=session)
self._args = args self._args = args
if callobj is not NOTSET: if callobj is not NOTSET:
self.obj = callobj self.obj = callobj
@ -1458,7 +1455,7 @@ class Function(FunctionMixin, nodes.Item, fixtures.FuncargnamesCompatAttr):
self.ihook.pytest_pyfunc_call(pyfuncitem=self) self.ihook.pytest_pyfunc_call(pyfuncitem=self)
def setup(self): def setup(self):
super(Function, self).setup() super().setup()
fixtures.fillfixtures(self) fixtures.fillfixtures(self)

View File

@ -46,7 +46,7 @@ def _non_numeric_type_error(value, at):
# builtin pytest.approx helper # builtin pytest.approx helper
class ApproxBase(object): class ApproxBase:
""" """
Provide shared utilities for making approximate comparisons between numbers Provide shared utilities for making approximate comparisons between numbers
or sequences of numbers. or sequences of numbers.
@ -706,7 +706,7 @@ def raises(expected_exception, *args, **kwargs):
raises.Exception = fail.Exception raises.Exception = fail.Exception
class RaisesContext(object): class RaisesContext:
def __init__(self, expected_exception, message, match_expr): def __init__(self, expected_exception, message, match_expr):
self.expected_exception = expected_exception self.expected_exception = expected_exception
self.message = message self.message = message

View File

@ -110,7 +110,7 @@ class WarningsRecorder(warnings.catch_warnings):
""" """
def __init__(self): def __init__(self):
super(WarningsRecorder, self).__init__(record=True) super().__init__(record=True)
self._entered = False self._entered = False
self._list = [] self._list = []
@ -147,7 +147,7 @@ class WarningsRecorder(warnings.catch_warnings):
if self._entered: if self._entered:
__tracebackhide__ = True __tracebackhide__ = True
raise RuntimeError("Cannot enter %r twice" % self) raise RuntimeError("Cannot enter %r twice" % self)
self._list = super(WarningsRecorder, self).__enter__() self._list = super().__enter__()
warnings.simplefilter("always") warnings.simplefilter("always")
return self return self
@ -156,7 +156,7 @@ class WarningsRecorder(warnings.catch_warnings):
__tracebackhide__ = True __tracebackhide__ = True
raise RuntimeError("Cannot exit %r without entering first" % self) raise RuntimeError("Cannot exit %r without entering first" % self)
super(WarningsRecorder, self).__exit__(*exc_info) super().__exit__(*exc_info)
# Built-in catch_warnings does not reset entered state so we do it # Built-in catch_warnings does not reset entered state so we do it
# manually here for this context manager to become reusable. # manually here for this context manager to become reusable.
@ -165,7 +165,7 @@ class WarningsRecorder(warnings.catch_warnings):
class WarningsChecker(WarningsRecorder): class WarningsChecker(WarningsRecorder):
def __init__(self, expected_warning=None, match_expr=None): def __init__(self, expected_warning=None, match_expr=None):
super(WarningsChecker, self).__init__() super().__init__()
msg = "exceptions must be old-style classes or derived from Warning, not %s" msg = "exceptions must be old-style classes or derived from Warning, not %s"
if isinstance(expected_warning, tuple): if isinstance(expected_warning, tuple):
@ -181,7 +181,7 @@ class WarningsChecker(WarningsRecorder):
self.match_expr = match_expr self.match_expr = match_expr
def __exit__(self, *exc_info): def __exit__(self, *exc_info):
super(WarningsChecker, self).__exit__(*exc_info) super().__exit__(*exc_info)
__tracebackhide__ = True __tracebackhide__ = True

View File

@ -1,7 +1,6 @@
from pprint import pprint from pprint import pprint
import py import py
import six
from _pytest._code.code import ExceptionInfo from _pytest._code.code import ExceptionInfo
from _pytest._code.code import ReprEntry from _pytest._code.code import ReprEntry
@ -22,16 +21,13 @@ def getslaveinfoline(node):
except AttributeError: except AttributeError:
d = node.slaveinfo d = node.slaveinfo
ver = "%s.%s.%s" % d["version_info"][:3] ver = "%s.%s.%s" % d["version_info"][:3]
node._slaveinfocache = s = "[%s] %s -- Python %s %s" % ( node._slaveinfocache = s = "[{}] {} -- Python {} {}".format(
d["id"], d["id"], d["sysplatform"], ver, d["executable"]
d["sysplatform"],
ver,
d["executable"],
) )
return s return s
class BaseReport(object): class BaseReport:
when = None when = None
location = None location = None
@ -194,7 +190,7 @@ class BaseReport(object):
): ):
d["longrepr"] = disassembled_report(self) d["longrepr"] = disassembled_report(self)
else: else:
d["longrepr"] = six.text_type(self.longrepr) d["longrepr"] = str(self.longrepr)
else: else:
d["longrepr"] = self.longrepr d["longrepr"] = self.longrepr
for name in d: for name in d:
@ -334,11 +330,8 @@ class TestReport(BaseReport):
self.__dict__.update(extra) self.__dict__.update(extra)
def __repr__(self): def __repr__(self):
return "<%s %r when=%r outcome=%r>" % ( return "<{} {!r} when={!r} outcome={!r}>".format(
self.__class__.__name__, self.__class__.__name__, self.nodeid, self.when, self.outcome
self.nodeid,
self.when,
self.outcome,
) )
@classmethod @classmethod
@ -371,7 +364,7 @@ class TestReport(BaseReport):
excinfo, style=item.config.getoption("tbstyle", "auto") excinfo, style=item.config.getoption("tbstyle", "auto")
) )
for rwhen, key, content in item._report_sections: for rwhen, key, content in item._report_sections:
sections.append(("Captured %s %s" % (key, rwhen), content)) sections.append(("Captured {} {}".format(key, rwhen), content))
return cls( return cls(
item.nodeid, item.nodeid,
item.location, item.location,
@ -401,10 +394,8 @@ class CollectReport(BaseReport):
return (self.fspath, None, self.fspath) return (self.fspath, None, self.fspath)
def __repr__(self): def __repr__(self):
return "<CollectReport %r lenresult=%s outcome=%r>" % ( return "<CollectReport {!r} lenresult={} outcome={!r}>".format(
self.nodeid, self.nodeid, len(self.result), self.outcome
len(self.result),
self.outcome,
) )

View File

@ -43,13 +43,13 @@ def pytest_unconfigure(config):
config.pluginmanager.unregister(resultlog) config.pluginmanager.unregister(resultlog)
class ResultLog(object): class ResultLog:
def __init__(self, config, logfile): def __init__(self, config, logfile):
self.config = config self.config = config
self.logfile = logfile # preferably line buffered self.logfile = logfile # preferably line buffered
def write_log_entry(self, testpath, lettercode, longrepr): def write_log_entry(self, testpath, lettercode, longrepr):
print("%s %s" % (lettercode, testpath), file=self.logfile) print("{} {}".format(lettercode, testpath), file=self.logfile)
for line in longrepr.splitlines(): for line in longrepr.splitlines():
print(" %s" % line, file=self.logfile) print(" %s" % line, file=self.logfile)

View File

@ -57,7 +57,7 @@ def pytest_terminal_summary(terminalreporter):
tr.write_line("") tr.write_line("")
tr.write_line("(0.00 durations hidden. Use -vv to show these durations.)") tr.write_line("(0.00 durations hidden. Use -vv to show these durations.)")
break break
tr.write_line("%02.2fs %-8s %s" % (rep.duration, rep.when, rep.nodeid)) tr.write_line("{:02.2f}s {:<8} {}".format(rep.duration, rep.when, rep.nodeid))
def pytest_sessionstart(session): def pytest_sessionstart(session):
@ -195,7 +195,7 @@ def call_runtest_hook(item, when, **kwds):
@attr.s(repr=False) @attr.s(repr=False)
class CallInfo(object): class CallInfo:
""" Result/Exception info a function invocation. """ """ Result/Exception info a function invocation. """
_result = attr.ib() _result = attr.ib()
@ -270,7 +270,7 @@ def pytest_make_collect_report(collector):
return rep return rep
class SetupState(object): class SetupState:
""" shared state for setting up/tearing down test items or collectors. """ """ shared state for setting up/tearing down test items or collectors. """
def __init__(self): def __init__(self):

View File

@ -12,7 +12,6 @@ from functools import partial
import attr import attr
import pluggy import pluggy
import py import py
import six
from more_itertools import collapse from more_itertools import collapse
import pytest import pytest
@ -35,7 +34,7 @@ class MoreQuietAction(argparse.Action):
""" """
def __init__(self, option_strings, dest, default=None, required=False, help=None): def __init__(self, option_strings, dest, default=None, required=False, help=None):
super(MoreQuietAction, self).__init__( super().__init__(
option_strings=option_strings, option_strings=option_strings,
dest=dest, dest=dest,
nargs=0, nargs=0,
@ -186,7 +185,7 @@ def pytest_report_teststatus(report):
@attr.s @attr.s
class WarningReport(object): class WarningReport:
""" """
Simple structure to hold warnings information captured by ``pytest_warning_captured``. Simple structure to hold warnings information captured by ``pytest_warning_captured``.
@ -214,13 +213,13 @@ class WarningReport(object):
relpath = py.path.local(filename).relto(config.invocation_dir) relpath = py.path.local(filename).relto(config.invocation_dir)
if not relpath: if not relpath:
relpath = str(filename) relpath = str(filename)
return "%s:%s" % (relpath, linenum) return "{}:{}".format(relpath, linenum)
else: else:
return str(self.fslocation) return str(self.fslocation)
return None return None
class TerminalReporter(object): class TerminalReporter:
def __init__(self, config, file=None): def __init__(self, config, file=None):
import _pytest.config import _pytest.config
@ -315,8 +314,8 @@ class TerminalReporter(object):
self._tw.write(content, **markup) self._tw.write(content, **markup)
def write_line(self, line, **markup): def write_line(self, line, **markup):
if not isinstance(line, six.text_type): if not isinstance(line, str):
line = six.text_type(line, errors="replace") line = str(line, errors="replace")
self.ensure_newline() self.ensure_newline()
self._tw.line(line, **markup) self._tw.line(line, **markup)
@ -349,7 +348,7 @@ class TerminalReporter(object):
self._tw.line(msg, **kw) self._tw.line(msg, **kw)
def pytest_internalerror(self, excrepr): def pytest_internalerror(self, excrepr):
for line in six.text_type(excrepr).split("\n"): for line in str(excrepr).split("\n"):
self.write_line("INTERNALERROR> " + line) self.write_line("INTERNALERROR> " + line)
return 1 return 1
@ -369,7 +368,7 @@ class TerminalReporter(object):
def pytest_plugin_registered(self, plugin): def pytest_plugin_registered(self, plugin):
if self.config.option.traceconfig: if self.config.option.traceconfig:
msg = "PLUGIN registered: %s" % (plugin,) msg = "PLUGIN registered: {}".format(plugin)
# XXX this event may happen during setup/teardown time # XXX this event may happen during setup/teardown time
# which unfortunately captures our output here # which unfortunately captures our output here
# which garbles our output if we use self.write_line # which garbles our output if we use self.write_line
@ -556,14 +555,12 @@ class TerminalReporter(object):
return return
self.write_sep("=", "test session starts", bold=True) self.write_sep("=", "test session starts", bold=True)
verinfo = platform.python_version() verinfo = platform.python_version()
msg = "platform %s -- Python %s" % (sys.platform, verinfo) msg = "platform {} -- Python {}".format(sys.platform, verinfo)
if hasattr(sys, "pypy_version_info"): if hasattr(sys, "pypy_version_info"):
verinfo = ".".join(map(str, sys.pypy_version_info[:3])) verinfo = ".".join(map(str, sys.pypy_version_info[:3]))
msg += "[pypy-%s-%s]" % (verinfo, sys.pypy_version_info[3]) msg += "[pypy-{}-{}]".format(verinfo, sys.pypy_version_info[3])
msg += ", pytest-%s, py-%s, pluggy-%s" % ( msg += ", pytest-{}, py-{}, pluggy-{}".format(
pytest.__version__, pytest.__version__, py.__version__, pluggy.__version__
py.__version__,
pluggy.__version__,
) )
if ( if (
self.verbosity > 0 self.verbosity > 0
@ -645,11 +642,11 @@ class TerminalReporter(object):
if col.name == "()": # Skip Instances. if col.name == "()": # Skip Instances.
continue continue
indent = (len(stack) - 1) * " " indent = (len(stack) - 1) * " "
self._tw.line("%s%s" % (indent, col)) self._tw.line("{}{}".format(indent, col))
if self.config.option.verbose >= 1: if self.config.option.verbose >= 1:
if hasattr(col, "_obj") and col._obj.__doc__: if hasattr(col, "_obj") and col._obj.__doc__:
for line in col._obj.__doc__.strip().splitlines(): for line in col._obj.__doc__.strip().splitlines():
self._tw.line("%s%s" % (indent + " ", line.strip())) self._tw.line("{}{}".format(indent + " ", line.strip()))
@pytest.hookimpl(hookwrapper=True) @pytest.hookimpl(hookwrapper=True)
def pytest_sessionfinish(self, exitstatus): def pytest_sessionfinish(self, exitstatus):
@ -849,7 +846,7 @@ class TerminalReporter(object):
if rep.when == "collect": if rep.when == "collect":
msg = "ERROR collecting " + msg msg = "ERROR collecting " + msg
else: else:
msg = "ERROR at %s of %s" % (rep.when, msg) msg = "ERROR at {} of {}".format(rep.when, msg)
self.write_sep("_", msg, red=True, bold=True) self.write_sep("_", msg, red=True, bold=True)
self._outrep_summary(rep) self._outrep_summary(rep)
@ -869,7 +866,7 @@ class TerminalReporter(object):
def summary_stats(self): def summary_stats(self):
session_duration = time.time() - self._sessionstarttime session_duration = time.time() - self._sessionstarttime
(line, color) = build_summary_stats_line(self.stats) (line, color) = build_summary_stats_line(self.stats)
msg = "%s in %.2f seconds" % (line, session_duration) msg = "{} in {:.2f} seconds".format(line, session_duration)
markup = {color: True, "bold": True} markup = {color: True, "bold": True}
if self.verbosity >= 0: if self.verbosity >= 0:
@ -896,7 +893,7 @@ class TerminalReporter(object):
for rep in xfailed: for rep in xfailed:
verbose_word = rep._get_verbose_word(self.config) verbose_word = rep._get_verbose_word(self.config)
pos = _get_pos(self.config, rep) pos = _get_pos(self.config, rep)
lines.append("%s %s" % (verbose_word, pos)) lines.append("{} {}".format(verbose_word, pos))
reason = rep.wasxfail reason = rep.wasxfail
if reason: if reason:
lines.append(" " + str(reason)) lines.append(" " + str(reason))
@ -907,7 +904,7 @@ class TerminalReporter(object):
verbose_word = rep._get_verbose_word(self.config) verbose_word = rep._get_verbose_word(self.config)
pos = _get_pos(self.config, rep) pos = _get_pos(self.config, rep)
reason = rep.wasxfail reason = rep.wasxfail
lines.append("%s %s %s" % (verbose_word, pos, reason)) lines.append("{} {} {}".format(verbose_word, pos, reason))
def show_skipped(lines): def show_skipped(lines):
skipped = self.stats.get("skipped", []) skipped = self.stats.get("skipped", [])
@ -961,7 +958,7 @@ def _get_line_with_reprcrash_message(config, rep, termwidth):
verbose_word = rep._get_verbose_word(config) verbose_word = rep._get_verbose_word(config)
pos = _get_pos(config, rep) pos = _get_pos(config, rep)
line = "%s %s" % (verbose_word, pos) line = "{} {}".format(verbose_word, pos)
len_line = wcswidth(line) len_line = wcswidth(line)
ellipsis, len_ellipsis = "...", 3 ellipsis, len_ellipsis = "...", 3
if len_line > termwidth - len_ellipsis: if len_line > termwidth - len_ellipsis:

View File

@ -17,7 +17,7 @@ from _pytest.monkeypatch import MonkeyPatch
@attr.s @attr.s
class TempPathFactory(object): class TempPathFactory:
"""Factory for temporary directories under the common base temp directory. """Factory for temporary directories under the common base temp directory.
The base directory can be configured using the ``--basetemp`` option.""" The base directory can be configured using the ``--basetemp`` option."""
@ -77,7 +77,7 @@ class TempPathFactory(object):
@attr.s @attr.s
class TempdirFactory(object): class TempdirFactory:
""" """
backward comptibility wrapper that implements backward comptibility wrapper that implements
:class:``py.path.local`` for :class:``TempPathFactory`` :class:``py.path.local`` for :class:``TempPathFactory``

View File

@ -94,7 +94,7 @@ class RemovedInPytest4Warning(PytestDeprecationWarning):
@attr.s @attr.s
class UnformattedWarning(object): class UnformattedWarning:
"""Used to hold warnings that need to format their message at runtime, as opposed to a direct message. """Used to hold warnings that need to format their message at runtime, as opposed to a direct message.
Using this class avoids to keep all the warning types and messages in this module, avoiding misuse. Using this class avoids to keep all the warning types and messages in this module, avoiding misuse.

View File

@ -13,7 +13,7 @@ def _setoption(wmod, arg):
""" """
parts = arg.split(":") parts = arg.split(":")
if len(parts) > 5: if len(parts) > 5:
raise wmod._OptionError("too many fields (max 5): %r" % (arg,)) raise wmod._OptionError("too many fields (max 5): {!r}".format(arg))
while len(parts) < 5: while len(parts) < 5:
parts.append("") parts.append("")
action, message, category, module, lineno = [s.strip() for s in parts] action, message, category, module, lineno = [s.strip() for s in parts]
@ -25,7 +25,7 @@ def _setoption(wmod, arg):
if lineno < 0: if lineno < 0:
raise ValueError raise ValueError
except (ValueError, OverflowError): except (ValueError, OverflowError):
raise wmod._OptionError("invalid lineno %r" % (lineno,)) raise wmod._OptionError("invalid lineno {!r}".format(lineno))
else: else:
lineno = 0 lineno = 0
wmod.filterwarnings(action, message, category, module, lineno) wmod.filterwarnings(action, message, category, module, lineno)

View File

@ -6,7 +6,6 @@ import types
import attr import attr
import importlib_metadata import importlib_metadata
import py import py
import six
import pytest import pytest
from _pytest.main import EXIT_NOTESTSCOLLECTED from _pytest.main import EXIT_NOTESTSCOLLECTED
@ -21,7 +20,7 @@ def prepend_pythonpath(*dirs):
return os.pathsep.join(str(p) for p in dirs) return os.pathsep.join(str(p) for p in dirs)
class TestGeneralUsage(object): class TestGeneralUsage:
def test_config_error(self, testdir): def test_config_error(self, testdir):
testdir.copy_example("conftest_usageerror/conftest.py") testdir.copy_example("conftest_usageerror/conftest.py")
result = testdir.runpytest(testdir.tmpdir) result = testdir.runpytest(testdir.tmpdir)
@ -115,7 +114,7 @@ class TestGeneralUsage(object):
loaded = [] loaded = []
@attr.s @attr.s
class DummyEntryPoint(object): class DummyEntryPoint:
name = attr.ib() name = attr.ib()
module = attr.ib() module = attr.ib()
group = "pytest11" group = "pytest11"
@ -132,7 +131,7 @@ class TestGeneralUsage(object):
] ]
@attr.s @attr.s
class DummyDist(object): class DummyDist:
entry_points = attr.ib() entry_points = attr.ib()
files = () files = ()
@ -508,7 +507,7 @@ class TestGeneralUsage(object):
def test_parametrized_with_null_bytes(self, testdir): def test_parametrized_with_null_bytes(self, testdir):
"""Test parametrization with values that contain null bytes and unicode characters (#2644, #2957)""" """Test parametrization with values that contain null bytes and unicode characters (#2644, #2957)"""
p = testdir.makepyfile( p = testdir.makepyfile(
u""" """
# encoding: UTF-8 # encoding: UTF-8
import pytest import pytest
@ -521,7 +520,7 @@ class TestGeneralUsage(object):
res.assert_outcomes(passed=3) res.assert_outcomes(passed=3)
class TestInvocationVariants(object): class TestInvocationVariants:
def test_earlyinit(self, testdir): def test_earlyinit(self, testdir):
p = testdir.makepyfile( p = testdir.makepyfile(
""" """
@ -618,7 +617,7 @@ class TestInvocationVariants(object):
out, err = capsys.readouterr() out, err = capsys.readouterr()
def test_invoke_plugin_api(self, testdir, capsys): def test_invoke_plugin_api(self, testdir, capsys):
class MyPlugin(object): class MyPlugin:
def pytest_addoption(self, parser): def pytest_addoption(self, parser):
parser.addoption("--myopt") parser.addoption("--myopt")
@ -756,7 +755,7 @@ class TestInvocationVariants(object):
str(testdir.tmpdir.join("tmpfile2")), str(testdir.tmpdir.join("tmpfile2")),
) )
except OSError as e: except OSError as e:
pytest.skip(six.text_type(e.args[0])) pytest.skip(str(e.args[0]))
monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False) monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
dirname = "lib" dirname = "lib"
@ -871,7 +870,7 @@ class TestInvocationVariants(object):
assert request.config.pluginmanager.hasplugin("python") assert request.config.pluginmanager.hasplugin("python")
class TestDurations(object): class TestDurations:
source = """ source = """
import time import time
frag = 0.002 frag = 0.002
@ -949,7 +948,7 @@ class TestDurations(object):
assert result.ret == 0 assert result.ret == 0
class TestDurationWithFixture(object): class TestDurationWithFixture:
source = """ source = """
import pytest import pytest
import time import time

View File

@ -1,7 +1,6 @@
import sys import sys
from unittest import mock from unittest import mock
from six import text_type
from test_excinfo import TWMock from test_excinfo import TWMock
import _pytest._code import _pytest._code
@ -25,7 +24,7 @@ def test_code_gives_back_name_for_not_existing_file():
def test_code_with_class(): def test_code_with_class():
class A(object): class A:
pass pass
pytest.raises(TypeError, _pytest._code.Code, A) pytest.raises(TypeError, _pytest._code.Code, A)
@ -76,13 +75,13 @@ def test_code_from_func():
def test_unicode_handling(): def test_unicode_handling():
value = u"ąć".encode("UTF-8") value = "ąć".encode()
def f(): def f():
raise Exception(value) raise Exception(value)
excinfo = pytest.raises(Exception, f) excinfo = pytest.raises(Exception, f)
text_type(excinfo) str(excinfo)
def test_code_getargs(): def test_code_getargs():
@ -137,7 +136,7 @@ def test_frame_getargs():
assert fr4.getargs(var=True) == [("x", "a"), ("y", ("b",)), ("z", {"c": "d"})] assert fr4.getargs(var=True) == [("x", "a"), ("y", ("b",)), ("z", {"c": "d"})]
class TestExceptionInfo(object): class TestExceptionInfo:
def test_bad_getsource(self): def test_bad_getsource(self):
try: try:
if False: if False:
@ -153,7 +152,7 @@ class TestExceptionInfo(object):
_pytest._code.ExceptionInfo.from_current() _pytest._code.ExceptionInfo.from_current()
class TestTracebackEntry(object): class TestTracebackEntry:
def test_getsource(self): def test_getsource(self):
try: try:
if False: if False:
@ -168,13 +167,13 @@ class TestTracebackEntry(object):
assert "assert False" in source[5] assert "assert False" in source[5]
class TestReprFuncArgs(object): class TestReprFuncArgs:
def test_not_raise_exception_with_mixed_encoding(self): def test_not_raise_exception_with_mixed_encoding(self):
from _pytest._code.code import ReprFuncArgs from _pytest._code.code import ReprFuncArgs
tw = TWMock() tw = TWMock()
args = [("unicode_string", u"São Paulo"), ("utf8_string", b"S\xc3\xa3o Paulo")] args = [("unicode_string", "São Paulo"), ("utf8_string", b"S\xc3\xa3o Paulo")]
r = ReprFuncArgs(args) r = ReprFuncArgs(args)
r.toterminal(tw) r.toterminal(tw)

View File

@ -5,7 +5,6 @@ import sys
import textwrap import textwrap
import py import py
import six
import _pytest import _pytest
import pytest import pytest
@ -32,7 +31,7 @@ def limited_recursion_depth():
sys.setrecursionlimit(before) sys.setrecursionlimit(before)
class TWMock(object): class TWMock:
WRITE = object() WRITE = object()
def __init__(self): def __init__(self):
@ -113,7 +112,7 @@ def h():
# #
class TestTraceback_f_g_h(object): class TestTraceback_f_g_h:
def setup_method(self, method): def setup_method(self, method):
try: try:
h() h()
@ -252,7 +251,7 @@ class TestTraceback_f_g_h(object):
import sys import sys
exc, val, tb = sys.exc_info() exc, val, tb = sys.exc_info()
six.reraise(exc, val, tb) raise val.with_traceback(tb)
def f(n): def f(n):
try: try:
@ -429,7 +428,7 @@ def test_match_raises_error(testdir):
result.stdout.fnmatch_lines(["*AssertionError*Pattern*[123]*not found*"]) result.stdout.fnmatch_lines(["*AssertionError*Pattern*[123]*not found*"])
class TestFormattedExcinfo(object): class TestFormattedExcinfo:
@pytest.fixture @pytest.fixture
def importasmod(self, request, _sys_snapshot): def importasmod(self, request, _sys_snapshot):
def importasmod(source): def importasmod(source):
@ -515,8 +514,8 @@ raise ValueError()
def test_repr_source_failing_fullsource(self): def test_repr_source_failing_fullsource(self):
pr = FormattedExcinfo() pr = FormattedExcinfo()
class FakeCode(object): class FakeCode:
class raw(object): class raw:
co_filename = "?" co_filename = "?"
path = "?" path = "?"
@ -527,7 +526,7 @@ raise ValueError()
fullsource = property(fullsource) fullsource = property(fullsource)
class FakeFrame(object): class FakeFrame:
code = FakeCode() code = FakeCode()
f_locals = {} f_locals = {}
f_globals = {} f_globals = {}
@ -558,7 +557,7 @@ raise ValueError()
excinfo = FakeExcinfo() excinfo = FakeExcinfo()
class FakeRawTB(object): class FakeRawTB:
tb_next = None tb_next = None
tb = FakeRawTB() tb = FakeRawTB()
@ -915,10 +914,10 @@ raise ValueError()
class MyRepr(TerminalRepr): class MyRepr(TerminalRepr):
def toterminal(self, tw): def toterminal(self, tw):
tw.line(u"я") tw.line("я")
x = six.text_type(MyRepr()) x = str(MyRepr())
assert x == u"я" assert x == "я"
def test_toterminal_long(self, importasmod): def test_toterminal_long(self, importasmod):
mod = importasmod( mod = importasmod(
@ -1351,7 +1350,7 @@ raise ValueError()
@pytest.mark.parametrize("style", ["short", "long"]) @pytest.mark.parametrize("style", ["short", "long"])
@pytest.mark.parametrize("encoding", [None, "utf8", "utf16"]) @pytest.mark.parametrize("encoding", [None, "utf8", "utf16"])
def test_repr_traceback_with_unicode(style, encoding): def test_repr_traceback_with_unicode(style, encoding):
msg = u"" msg = ""
if encoding is not None: if encoding is not None:
msg = msg.encode(encoding) msg = msg.encode(encoding)
try: try:
@ -1385,7 +1384,7 @@ def test_exception_repr_extraction_error_on_recursion():
""" """
from _pytest.pytester import LineMatcher from _pytest.pytester import LineMatcher
class numpy_like(object): class numpy_like:
def __eq__(self, other): def __eq__(self, other):
if type(other) is numpy_like: if type(other) is numpy_like:
raise ValueError( raise ValueError(
@ -1419,7 +1418,7 @@ def test_no_recursion_index_on_recursion_error():
during a recursion error (#2486). during a recursion error (#2486).
""" """
class RecursionDepthError(object): class RecursionDepthError:
def __getattr__(self, attr): def __getattr__(self, attr):
return getattr(self, "_" + attr) return getattr(self, "_" + attr)

View File

@ -28,11 +28,11 @@ def test_source_str_function():
def test_unicode(): def test_unicode():
x = Source(u"4") x = Source("4")
assert str(x) == "4" assert str(x) == "4"
co = _pytest._code.compile(u'u"å"', mode="eval") co = _pytest._code.compile('u"å"', mode="eval")
val = eval(co) val = eval(co)
assert isinstance(val, six.text_type) assert isinstance(val, str)
def test_source_from_function(): def test_source_from_function():
@ -41,7 +41,7 @@ def test_source_from_function():
def test_source_from_method(): def test_source_from_method():
class TestClass(object): class TestClass:
def test_method(self): def test_method(self):
pass pass
@ -128,7 +128,7 @@ def test_isparseable():
assert not Source(chr(0)).isparseable() assert not Source(chr(0)).isparseable()
class TestAccesses(object): class TestAccesses:
source = Source( source = Source(
"""\ """\
def f(x): def f(x):
@ -156,7 +156,7 @@ class TestAccesses(object):
assert len(values) == 4 assert len(values) == 4
class TestSourceParsingAndCompiling(object): class TestSourceParsingAndCompiling:
source = Source( source = Source(
"""\ """\
def f(x): def f(x):
@ -333,7 +333,7 @@ class TestSourceParsingAndCompiling(object):
def test_getstartingblock_singleline(): def test_getstartingblock_singleline():
class A(object): class A:
def __init__(self, *args): def __init__(self, *args):
frame = sys._getframe(1) frame = sys._getframe(1)
self.source = _pytest._code.Frame(frame).statement self.source = _pytest._code.Frame(frame).statement
@ -480,7 +480,7 @@ def test_getfslineno():
assert fspath.basename == "test_source.py" assert fspath.basename == "test_source.py"
assert lineno == _pytest._code.getrawcode(f).co_firstlineno - 1 # see findsource assert lineno == _pytest._code.getrawcode(f).co_firstlineno - 1 # see findsource
class A(object): class A:
pass pass
fspath, lineno = getfslineno(A) fspath, lineno = getfslineno(A)
@ -491,7 +491,7 @@ def test_getfslineno():
assert getfslineno(3) == ("", -1) assert getfslineno(3) == ("", -1)
class B(object): class B:
pass pass
B.__name__ = "B2" B.__name__ = "B2"
@ -499,19 +499,19 @@ def test_getfslineno():
def test_code_of_object_instance_with_call(): def test_code_of_object_instance_with_call():
class A(object): class A:
pass pass
pytest.raises(TypeError, lambda: _pytest._code.Source(A())) pytest.raises(TypeError, lambda: _pytest._code.Source(A()))
class WithCall(object): class WithCall:
def __call__(self): def __call__(self):
pass pass
code = _pytest._code.Code(WithCall()) code = _pytest._code.Code(WithCall())
assert "pass" in str(code.source()) assert "pass" in str(code.source())
class Hello(object): class Hello:
def __call__(self): def __call__(self):
pass pass
@ -620,7 +620,7 @@ x = 3
assert str(source) == "raise ValueError(\n 23\n)" assert str(source) == "raise ValueError(\n 23\n)"
class TestTry(object): class TestTry:
source = """\ source = """\
try: try:
raise ValueError raise ValueError
@ -647,7 +647,7 @@ else:
assert str(source) == " raise KeyError()" assert str(source) == " raise KeyError()"
class TestTryFinally(object): class TestTryFinally:
source = """\ source = """\
try: try:
raise ValueError raise ValueError
@ -664,7 +664,7 @@ finally:
assert str(source) == " raise IndexError(1)" assert str(source) == " raise IndexError(1)"
class TestIf(object): class TestIf:
source = """\ source = """\
if 1: if 1:
y = 3 y = 3
@ -720,7 +720,7 @@ something
def test_getstartingblock_multiline(): def test_getstartingblock_multiline():
class A(object): class A:
def __init__(self, *args): def __init__(self, *args):
frame = sys._getframe(1) frame = sys._getframe(1)
self.source = _pytest._code.Frame(frame).statement self.source = _pytest._code.Frame(frame).statement

View File

@ -1,2 +1,2 @@
class pytest_something(object): class pytest_something:
pass pass

View File

@ -4,7 +4,7 @@ from dataclasses import field
def test_dataclasses(): def test_dataclasses():
@dataclass @dataclass
class SimpleDataObject(object): class SimpleDataObject:
field_a: int = field() field_a: int = field()
field_b: int = field() field_b: int = field()

View File

@ -4,7 +4,7 @@ from dataclasses import field
def test_dataclasses_with_attribute_comparison_off(): def test_dataclasses_with_attribute_comparison_off():
@dataclass @dataclass
class SimpleDataObject(object): class SimpleDataObject:
field_a: int = field() field_a: int = field()
field_b: int = field(compare=False) field_b: int = field(compare=False)

View File

@ -4,7 +4,7 @@ from dataclasses import field
def test_dataclasses_verbose(): def test_dataclasses_verbose():
@dataclass @dataclass
class SimpleDataObject(object): class SimpleDataObject:
field_a: int = field() field_a: int = field()
field_b: int = field() field_b: int = field()

View File

@ -4,12 +4,12 @@ from dataclasses import field
def test_comparing_two_different_data_classes(): def test_comparing_two_different_data_classes():
@dataclass @dataclass
class SimpleDataObjectOne(object): class SimpleDataObjectOne:
field_a: int = field() field_a: int = field()
field_b: int = field() field_b: int = field()
@dataclass @dataclass
class SimpleDataObjectTwo(object): class SimpleDataObjectTwo:
field_a: int = field() field_a: int = field()
field_b: int = field() field_b: int = field()

View File

@ -6,7 +6,7 @@ def spam():
return "spam" return "spam"
class TestSpam(object): class TestSpam:
@pytest.fixture @pytest.fixture
def spam(self, spam): def spam(self, spam):
return spam * 2 return spam * 2

View File

@ -1,7 +1,7 @@
import pytest import pytest
class TestClass(object): class TestClass:
@pytest.fixture @pytest.fixture
def something(self, request): def something(self, request):
return request.instance return request.instance

View File

@ -6,7 +6,7 @@ def something(request):
return request.function.__name__ return request.function.__name__
class TestClass(object): class TestClass:
def test_method(self, something): def test_method(self, something):
assert something == "test_method" assert something == "test_method"

View File

@ -52,7 +52,7 @@ def test_big_repr():
def test_repr_on_newstyle(): def test_repr_on_newstyle():
class Function(object): class Function:
def __repr__(self): def __repr__(self):
return "<%s>" % (self.name) return "<%s>" % (self.name)
@ -60,6 +60,6 @@ def test_repr_on_newstyle():
def test_unicode(): def test_unicode():
val = u"£€" val = "£€"
reprval = u"'£€'" reprval = "'£€'"
assert saferepr(val) == reprval assert saferepr(val) == reprval

View File

@ -102,15 +102,15 @@ def test_record_tuples(caplog):
def test_unicode(caplog): def test_unicode(caplog):
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
logger.info(u"") logger.info("")
assert caplog.records[0].levelname == "INFO" assert caplog.records[0].levelname == "INFO"
assert caplog.records[0].msg == u"" assert caplog.records[0].msg == ""
assert u"" in caplog.text assert "" in caplog.text
def test_clear(caplog): def test_clear(caplog):
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
logger.info(u"") logger.info("")
assert len(caplog.records) assert len(caplog.records)
assert caplog.text assert caplog.text
caplog.clear() caplog.clear()

View File

@ -20,8 +20,8 @@ def test_coloredlogformatter():
exc_info=False, exc_info=False,
) )
class ColorConfig(object): class ColorConfig:
class option(object): class option:
pass pass
tw = py.io.TerminalWriter() tw = py.io.TerminalWriter()

View File

@ -860,7 +860,7 @@ def test_log_file_unicode(testdir):
with open(log_file, encoding="utf-8") as rfh: with open(log_file, encoding="utf-8") as rfh:
contents = rfh.read() contents = rfh.read()
assert "Normal message" in contents assert "Normal message" in contents
assert u"" in contents assert "" in contents
assert "Another normal message" in contents assert "Another normal message" in contents

View File

@ -23,10 +23,10 @@ class MyDocTestRunner(doctest.DocTestRunner):
) )
class TestApprox(object): class TestApprox:
@pytest.fixture @pytest.fixture
def plus_minus(self): def plus_minus(self):
return u"\u00b1" return "\u00b1"
def test_repr_string(self, plus_minus): def test_repr_string(self, plus_minus):
tol1, tol2, infr = "1.0e-06", "2.0e-06", "inf" tol1, tol2, infr = "1.0e-06", "2.0e-06", "inf"
@ -496,7 +496,7 @@ class TestApprox(object):
assert approx(expected, rel=5e-8, abs=0) != actual assert approx(expected, rel=5e-8, abs=0) != actual
def test_generic_sized_iterable_object(self): def test_generic_sized_iterable_object(self):
class MySizedIterable(object): class MySizedIterable:
def __iter__(self): def __iter__(self):
return iter([1, 2, 3, 4]) return iter([1, 2, 3, 4])

View File

@ -8,7 +8,7 @@ from _pytest.main import EXIT_NOTESTSCOLLECTED
from _pytest.nodes import Collector from _pytest.nodes import Collector
class TestModule(object): class TestModule:
def test_failing_import(self, testdir): def test_failing_import(self, testdir):
modcol = testdir.getmodulecol("import alksdjalskdjalkjals") modcol = testdir.getmodulecol("import alksdjalskdjalkjals")
pytest.raises(Collector.CollectError, modcol.collect) pytest.raises(Collector.CollectError, modcol.collect)
@ -117,7 +117,7 @@ class TestModule(object):
are handled properly (#2336). are handled properly (#2336).
""" """
testdir.makepyfile( testdir.makepyfile(
u""" """
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
raise ImportError(u'Something bad happened ☺') raise ImportError(u'Something bad happened ☺')
""" """
@ -133,7 +133,7 @@ class TestModule(object):
assert result.ret == 2 assert result.ret == 2
class TestClass(object): class TestClass:
def test_class_with_init_warning(self, testdir): def test_class_with_init_warning(self, testdir):
testdir.makepyfile( testdir.makepyfile(
""" """
@ -254,7 +254,7 @@ class TestClass(object):
assert result.ret == EXIT_NOTESTSCOLLECTED assert result.ret == EXIT_NOTESTSCOLLECTED
class TestFunction(object): class TestFunction:
def test_getmodulecollector(self, testdir): def test_getmodulecollector(self, testdir):
item = testdir.getitem("def test_func(): pass") item = testdir.getitem("def test_func(): pass")
modcol = item.getparent(pytest.Module) modcol = item.getparent(pytest.Module)
@ -513,11 +513,11 @@ class TestFunction(object):
item = testdir.getitem("def test_func(): raise ValueError") item = testdir.getitem("def test_func(): raise ValueError")
config = item.config config = item.config
class MyPlugin1(object): class MyPlugin1:
def pytest_pyfunc_call(self, pyfuncitem): def pytest_pyfunc_call(self, pyfuncitem):
raise ValueError raise ValueError
class MyPlugin2(object): class MyPlugin2:
def pytest_pyfunc_call(self, pyfuncitem): def pytest_pyfunc_call(self, pyfuncitem):
return True return True
@ -663,7 +663,7 @@ class TestFunction(object):
assert [x.originalname for x in items] == ["test_func", "test_func"] assert [x.originalname for x in items] == ["test_func", "test_func"]
class TestSorting(object): class TestSorting:
def test_check_equality(self, testdir): def test_check_equality(self, testdir):
modcol = testdir.getmodulecol( modcol = testdir.getmodulecol(
""" """
@ -715,7 +715,7 @@ class TestSorting(object):
assert [item.name for item in colitems] == ["test_b", "test_a"] assert [item.name for item in colitems] == ["test_b", "test_a"]
class TestConftestCustomization(object): class TestConftestCustomization:
def test_pytest_pycollect_module(self, testdir): def test_pytest_pycollect_module(self, testdir):
testdir.makeconftest( testdir.makeconftest(
""" """
@ -890,7 +890,7 @@ def test_modulecol_roundtrip(testdir):
assert modcol.name == newcol.name assert modcol.name == newcol.name
class TestTracebackCutting(object): class TestTracebackCutting:
def test_skip_simple(self): def test_skip_simple(self):
with pytest.raises(pytest.skip.Exception) as excinfo: with pytest.raises(pytest.skip.Exception) as excinfo:
pytest.skip("xxx") pytest.skip("xxx")
@ -1019,7 +1019,7 @@ class TestTracebackCutting(object):
assert filter_traceback(tb[-1]) assert filter_traceback(tb[-1])
class TestReportInfo(object): class TestReportInfo:
def test_itemreport_reportinfo(self, testdir, linecomp): def test_itemreport_reportinfo(self, testdir, linecomp):
testdir.makeconftest( testdir.makeconftest(
""" """
@ -1257,7 +1257,7 @@ def test_syntax_error_with_non_ascii_chars(testdir):
"""Fix decoding issue while formatting SyntaxErrors during collection (#578) """Fix decoding issue while formatting SyntaxErrors during collection (#578)
""" """
testdir.makepyfile( testdir.makepyfile(
u""" """
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-

View File

@ -31,7 +31,7 @@ def test_getfuncargnames():
assert fixtures.getfuncargnames(h) == ("arg1", "arg2") assert fixtures.getfuncargnames(h) == ("arg1", "arg2")
class A(object): class A:
def f(self, arg1, arg2="hello"): def f(self, arg1, arg2="hello"):
pass pass
@ -44,7 +44,7 @@ def test_getfuncargnames():
@pytest.mark.pytester_example_path("fixtures/fill_fixtures") @pytest.mark.pytester_example_path("fixtures/fill_fixtures")
class TestFillFixtures(object): class TestFillFixtures:
def test_fillfuncargs_exposed(self): def test_fillfuncargs_exposed(self):
# used by oejskit, kept for compatibility # used by oejskit, kept for compatibility
assert pytest._fillfuncargs == fixtures.fillfixtures assert pytest._fillfuncargs == fixtures.fillfixtures
@ -442,7 +442,7 @@ class TestFillFixtures(object):
assert result.ret == 0 assert result.ret == 0
class TestRequestBasic(object): class TestRequestBasic:
def test_request_attributes(self, testdir): def test_request_attributes(self, testdir):
item = testdir.getitem( item = testdir.getitem(
""" """
@ -901,7 +901,7 @@ class TestRequestBasic(object):
reprec.assertoutcome(passed=2) reprec.assertoutcome(passed=2)
class TestRequestMarking(object): class TestRequestMarking:
def test_applymarker(self, testdir): def test_applymarker(self, testdir):
item1, item2 = testdir.getitems( item1, item2 = testdir.getitems(
""" """
@ -971,7 +971,7 @@ class TestRequestMarking(object):
reprec.assertoutcome(passed=2) reprec.assertoutcome(passed=2)
class TestFixtureUsages(object): class TestFixtureUsages:
def test_noargfixturedec(self, testdir): def test_noargfixturedec(self, testdir):
testdir.makepyfile( testdir.makepyfile(
""" """
@ -1302,7 +1302,7 @@ class TestFixtureUsages(object):
result.stdout.fnmatch_lines(["* 2 passed in *"]) result.stdout.fnmatch_lines(["* 2 passed in *"])
class TestFixtureManagerParseFactories(object): class TestFixtureManagerParseFactories:
@pytest.fixture @pytest.fixture
def testdir(self, request): def testdir(self, request):
testdir = request.getfixturevalue("testdir") testdir = request.getfixturevalue("testdir")
@ -1528,7 +1528,7 @@ class TestFixtureManagerParseFactories(object):
result.stdout.fnmatch_lines(["*passed*"]) result.stdout.fnmatch_lines(["*passed*"])
class TestAutouseDiscovery(object): class TestAutouseDiscovery:
@pytest.fixture @pytest.fixture
def testdir(self, testdir): def testdir(self, testdir):
testdir.makeconftest( testdir.makeconftest(
@ -1704,7 +1704,7 @@ class TestAutouseDiscovery(object):
reprec.assertoutcome(passed=3) reprec.assertoutcome(passed=3)
class TestAutouseManagement(object): class TestAutouseManagement:
def test_autouse_conftest_mid_directory(self, testdir): def test_autouse_conftest_mid_directory(self, testdir):
pkgdir = testdir.mkpydir("xyz123") pkgdir = testdir.mkpydir("xyz123")
pkgdir.join("conftest.py").write( pkgdir.join("conftest.py").write(
@ -1952,7 +1952,7 @@ class TestAutouseManagement(object):
reprec.assertoutcome(passed=2) reprec.assertoutcome(passed=2)
class TestFixtureMarker(object): class TestFixtureMarker:
def test_parametrize(self, testdir): def test_parametrize(self, testdir):
testdir.makepyfile( testdir.makepyfile(
""" """
@ -2908,7 +2908,7 @@ class TestFixtureMarker(object):
assert out1 == out2 assert out1 == out2
class TestRequestScopeAccess(object): class TestRequestScopeAccess:
pytestmark = pytest.mark.parametrize( pytestmark = pytest.mark.parametrize(
("scope", "ok", "error"), ("scope", "ok", "error"),
[ [
@ -2962,7 +2962,7 @@ class TestRequestScopeAccess(object):
reprec.assertoutcome(passed=1) reprec.assertoutcome(passed=1)
class TestErrors(object): class TestErrors:
def test_subfactory_missing_funcarg(self, testdir): def test_subfactory_missing_funcarg(self, testdir):
testdir.makepyfile( testdir.makepyfile(
""" """
@ -3029,7 +3029,7 @@ class TestErrors(object):
) )
class TestShowFixtures(object): class TestShowFixtures:
def test_funcarg_compat(self, testdir): def test_funcarg_compat(self, testdir):
config = testdir.parseconfigure("--funcargs") config = testdir.parseconfigure("--funcargs")
assert config.option.showfixtures assert config.option.showfixtures
@ -3317,7 +3317,7 @@ class TestShowFixtures(object):
pass pass
class TestContextManagerFixtureFuncs(object): class TestContextManagerFixtureFuncs:
@pytest.fixture(params=["fixture", "yield_fixture"]) @pytest.fixture(params=["fixture", "yield_fixture"])
def flavor(self, request, testdir, monkeypatch): def flavor(self, request, testdir, monkeypatch):
monkeypatch.setenv("PYTEST_FIXTURE_FLAVOR", request.param) monkeypatch.setenv("PYTEST_FIXTURE_FLAVOR", request.param)
@ -3465,7 +3465,7 @@ class TestContextManagerFixtureFuncs(object):
result.stdout.fnmatch_lines(["*mew*"]) result.stdout.fnmatch_lines(["*mew*"])
class TestParameterizedSubRequest(object): class TestParameterizedSubRequest:
def test_call_from_fixture(self, testdir): def test_call_from_fixture(self, testdir):
testdir.makepyfile( testdir.makepyfile(
test_call_from_fixture=""" test_call_from_fixture="""
@ -3644,7 +3644,7 @@ def test_pytest_fixture_setup_and_post_finalizer_hook(testdir):
) )
class TestScopeOrdering(object): class TestScopeOrdering:
"""Class of tests that ensure fixtures are ordered based on their scopes (#2405)""" """Class of tests that ensure fixtures are ordered based on their scopes (#2405)"""
@pytest.mark.parametrize("variant", ["mark", "autouse"]) @pytest.mark.parametrize("variant", ["mark", "autouse"])

View File

@ -3,7 +3,7 @@ from _pytest import python
from _pytest import runner from _pytest import runner
class TestOEJSKITSpecials(object): class TestOEJSKITSpecials:
def test_funcarg_non_pycollectobj(self, testdir): # rough jstests usage def test_funcarg_non_pycollectobj(self, testdir): # rough jstests usage
testdir.makeconftest( testdir.makeconftest(
""" """
@ -86,7 +86,7 @@ def test_wrapped_getfslineno():
assert lineno > lineno2, "getfslineno does not unwrap correctly" assert lineno > lineno2, "getfslineno does not unwrap correctly"
class TestMockDecoration(object): class TestMockDecoration:
def test_wrapped_getfuncargnames(self): def test_wrapped_getfuncargnames(self):
from _pytest.compat import getfuncargnames from _pytest.compat import getfuncargnames
@ -263,7 +263,7 @@ class TestMockDecoration(object):
reprec.assertoutcome(passed=1) reprec.assertoutcome(passed=1)
class TestReRunTests(object): class TestReRunTests:
def test_rerun(self, testdir): def test_rerun(self, testdir):
testdir.makeconftest( testdir.makeconftest(
""" """
@ -309,7 +309,7 @@ def test_pytestconfig_is_session_scoped():
assert pytestconfig._pytestfixturefunction.scope == "session" assert pytestconfig._pytestfixturefunction.scope == "session"
class TestNoselikeTestAttribute(object): class TestNoselikeTestAttribute:
def test_module_with_global_test(self, testdir): def test_module_with_global_test(self, testdir):
testdir.makepyfile( testdir.makepyfile(
""" """
@ -393,7 +393,7 @@ class TestNoselikeTestAttribute(object):
assert not call.items assert not call.items
class TestParameterize(object): class TestParameterize:
"""#351""" """#351"""
def test_idfn_marker(self, testdir): def test_idfn_marker(self, testdir):

View File

@ -4,7 +4,6 @@ import textwrap
import attr import attr
import hypothesis import hypothesis
import six
from hypothesis import strategies from hypothesis import strategies
import pytest import pytest
@ -13,19 +12,19 @@ from _pytest import python
from _pytest.warnings import SHOW_PYTEST_WARNINGS_ARG from _pytest.warnings import SHOW_PYTEST_WARNINGS_ARG
class TestMetafunc(object): class TestMetafunc:
def Metafunc(self, func, config=None): def Metafunc(self, func, config=None):
# the unit tests of this class check if things work correctly # the unit tests of this class check if things work correctly
# on the funcarg level, so we don't need a full blown # on the funcarg level, so we don't need a full blown
# initiliazation # initiliazation
class FixtureInfo(object): class FixtureInfo:
name2fixturedefs = None name2fixturedefs = None
def __init__(self, names): def __init__(self, names):
self.names_closure = names self.names_closure = names
@attr.s @attr.s
class DefinitionMock(object): class DefinitionMock:
obj = attr.ib() obj = attr.ib()
names = fixtures.getfuncargnames(func) names = fixtures.getfuncargnames(func)
@ -79,7 +78,7 @@ class TestMetafunc(object):
from _pytest.python import _find_parametrized_scope from _pytest.python import _find_parametrized_scope
@attr.s @attr.s
class DummyFixtureDef(object): class DummyFixtureDef:
scope = attr.ib() scope = attr.ib()
fixtures_defs = dict( fixtures_defs = dict(
@ -138,9 +137,9 @@ class TestMetafunc(object):
pass pass
metafunc = self.Metafunc(func) metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1, 2], ids=[u"basic", u"advanced"]) metafunc.parametrize("x", [1, 2], ids=["basic", "advanced"])
ids = [x.id for x in metafunc._calls] ids = [x.id for x in metafunc._calls]
assert ids == [u"basic", u"advanced"] assert ids == ["basic", "advanced"]
def test_parametrize_with_wrong_number_of_ids(self, testdir): def test_parametrize_with_wrong_number_of_ids(self, testdir):
def func(x, y): def func(x, y):
@ -162,7 +161,7 @@ class TestMetafunc(object):
def func(y): def func(y):
pass pass
class MockConfig(object): class MockConfig:
def getini(self, name): def getini(self, name):
return "" return ""
@ -183,7 +182,7 @@ class TestMetafunc(object):
metafunc = self.Metafunc(func) metafunc = self.Metafunc(func)
class A(object): class A:
pass pass
metafunc.parametrize("x", [A(), A()]) metafunc.parametrize("x", [A(), A()])
@ -201,7 +200,7 @@ class TestMetafunc(object):
from _pytest.python import _idval from _pytest.python import _idval
escaped = _idval(value, "a", 6, None, item=None, config=None) escaped = _idval(value, "a", 6, None, item=None, config=None)
assert isinstance(escaped, six.text_type) assert isinstance(escaped, str)
escaped.encode("ascii") escaped.encode("ascii")
def test_unicode_idval(self): def test_unicode_idval(self):
@ -213,12 +212,12 @@ class TestMetafunc(object):
from _pytest.python import _idval from _pytest.python import _idval
values = [ values = [
(u"", ""), ("", ""),
(u"ascii", "ascii"), ("ascii", "ascii"),
(u"ação", "a\\xe7\\xe3o"), ("ação", "a\\xe7\\xe3o"),
(u"josé@blah.com", "jos\\xe9@blah.com"), ("josé@blah.com", "jos\\xe9@blah.com"),
( (
u"δοκ.ιμή@παράδειγμα.δοκιμή", "δοκ.ιμή@παράδειγμα.δοκιμή",
"\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3" "\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3"
"\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae", "\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae",
), ),
@ -233,7 +232,7 @@ class TestMetafunc(object):
""" """
from _pytest.python import _idval from _pytest.python import _idval
class MockConfig(object): class MockConfig:
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config
@ -250,8 +249,8 @@ class TestMetafunc(object):
option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support" option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
values = [ values = [
(u"ação", MockConfig({option: True}), u"ação"), ("ação", MockConfig({option: True}), "ação"),
(u"ação", MockConfig({option: False}), "a\\xe7\\xe3o"), ("ação", MockConfig({option: False}), "a\\xe7\\xe3o"),
] ]
for val, config, expected in values: for val, config, expected in values:
assert _idval(val, "a", 6, None, item=None, config=config) == expected assert _idval(val, "a", 6, None, item=None, config=config) == expected
@ -269,7 +268,7 @@ class TestMetafunc(object):
(b"", ""), (b"", ""),
(b"\xc3\xb4\xff\xe4", "\\xc3\\xb4\\xff\\xe4"), (b"\xc3\xb4\xff\xe4", "\\xc3\\xb4\\xff\\xe4"),
(b"ascii", "ascii"), (b"ascii", "ascii"),
(u"αρά".encode("utf-8"), "\\xce\\xb1\\xcf\\x81\\xce\\xac"), ("αρά".encode(), "\\xce\\xb1\\xcf\\x81\\xce\\xac"),
] ]
for val, expected in values: for val, expected in values:
assert _idval(val, "a", 6, idfn=None, item=None, config=None) == expected assert _idval(val, "a", 6, idfn=None, item=None, config=None) == expected
@ -280,7 +279,7 @@ class TestMetafunc(object):
""" """
from _pytest.python import _idval from _pytest.python import _idval
class TestClass(object): class TestClass:
pass pass
def test_function(): def test_function():
@ -304,7 +303,7 @@ class TestMetafunc(object):
) )
assert result == ["a0-1.0", "a1-b1"] assert result == ["a0-1.0", "a1-b1"]
# unicode mixing, issue250 # unicode mixing, issue250
result = idmaker((u"a", "b"), [pytest.param({}, b"\xc3\xb4")]) result = idmaker(("a", "b"), [pytest.param({}, b"\xc3\xb4")])
assert result == ["a0-\\xc3\\xb4"] assert result == ["a0-\\xc3\\xb4"]
def test_idmaker_with_bytes_regex(self): def test_idmaker_with_bytes_regex(self):
@ -330,7 +329,7 @@ class TestMetafunc(object):
pytest.param({7}, set("seven")), pytest.param({7}, set("seven")),
pytest.param(tuple("eight"), (8, -8, 8)), pytest.param(tuple("eight"), (8, -8, 8)),
pytest.param(b"\xc3\xb4", b"name"), pytest.param(b"\xc3\xb4", b"name"),
pytest.param(b"\xc3\xb4", u"other"), pytest.param(b"\xc3\xb4", "other"),
], ],
) )
assert result == [ assert result == [
@ -428,7 +427,7 @@ class TestMetafunc(object):
""" """
from _pytest.python import idmaker from _pytest.python import idmaker
class MockConfig(object): class MockConfig:
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config
@ -445,12 +444,12 @@ class TestMetafunc(object):
option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support" option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
values = [ values = [
(MockConfig({option: True}), u"ação"), (MockConfig({option: True}), "ação"),
(MockConfig({option: False}), "a\\xe7\\xe3o"), (MockConfig({option: False}), "a\\xe7\\xe3o"),
] ]
for config, expected in values: for config, expected in values:
result = idmaker( result = idmaker(
("a",), [pytest.param("string")], idfn=lambda _: u"ação", config=config ("a",), [pytest.param("string")], idfn=lambda _: "ação", config=config
) )
assert result == [expected] assert result == [expected]
@ -461,7 +460,7 @@ class TestMetafunc(object):
""" """
from _pytest.python import idmaker from _pytest.python import idmaker
class MockConfig(object): class MockConfig:
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config
@ -478,12 +477,12 @@ class TestMetafunc(object):
option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support" option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
values = [ values = [
(MockConfig({option: True}), u"ação"), (MockConfig({option: True}), "ação"),
(MockConfig({option: False}), "a\\xe7\\xe3o"), (MockConfig({option: False}), "a\\xe7\\xe3o"),
] ]
for config, expected in values: for config, expected in values:
result = idmaker( result = idmaker(
("a",), [pytest.param("string")], ids=[u"ação"], config=config ("a",), [pytest.param("string")], ids=["ação"], config=config
) )
assert result == [expected] assert result == [expected]
@ -888,7 +887,7 @@ class TestMetafunc(object):
assert fixtures._format_args(function4) == "(arg1, *args, **kwargs)" assert fixtures._format_args(function4) == "(arg1, *args, **kwargs)"
class TestMetafuncFunctional(object): class TestMetafuncFunctional:
def test_attributes(self, testdir): def test_attributes(self, testdir):
p = testdir.makepyfile( p = testdir.makepyfile(
""" """
@ -1324,7 +1323,7 @@ class TestMetafuncFunctional(object):
) )
class TestMetafuncFunctionalAuto(object): class TestMetafuncFunctionalAuto:
""" """
Tests related to automatically find out the correct scope for parametrized tests (#1832). Tests related to automatically find out the correct scope for parametrized tests (#1832).
""" """
@ -1486,7 +1485,7 @@ class TestMetafuncFunctionalAuto(object):
assert output.count("preparing foo-3") == 1 assert output.count("preparing foo-3") == 1
class TestMarkersWithParametrization(object): class TestMarkersWithParametrization:
"""#308""" """#308"""
def test_simple_mark(self, testdir): def test_simple_mark(self, testdir):

View File

@ -5,7 +5,7 @@ from _pytest.outcomes import Failed
from _pytest.warning_types import PytestDeprecationWarning from _pytest.warning_types import PytestDeprecationWarning
class TestRaises(object): class TestRaises:
def test_raises(self): def test_raises(self):
source = "int('qwe')" source = "int('qwe')"
with pytest.warns(PytestDeprecationWarning): with pytest.warns(PytestDeprecationWarning):
@ -33,7 +33,7 @@ class TestRaises(object):
pytest.raises(ValueError, int, "hello") pytest.raises(ValueError, int, "hello")
def test_raises_callable_no_exception(self): def test_raises_callable_no_exception(self):
class A(object): class A:
def __call__(self): def __call__(self):
pass pass
@ -187,7 +187,7 @@ class TestRaises(object):
""" """
import gc import gc
class T(object): class T:
def __call__(self): def __call__(self):
raise ValueError raise ValueError
@ -235,8 +235,6 @@ class TestRaises(object):
int("asdf") int("asdf")
def test_raises_exception_looks_iterable(self): def test_raises_exception_looks_iterable(self):
from six import add_metaclass
class Meta(type(object)): class Meta(type(object)):
def __getitem__(self, item): def __getitem__(self, item):
return 1 / 0 return 1 / 0
@ -244,8 +242,7 @@ class TestRaises(object):
def __len__(self): def __len__(self):
return 1 return 1
@add_metaclass(Meta) class ClassLooksIterableException(Exception, metaclass=Meta):
class ClassLooksIterableException(Exception):
pass pass
with pytest.raises( with pytest.raises(

View File

@ -1,5 +1,3 @@
def test_no_items_should_not_show_output(testdir): def test_no_items_should_not_show_output(testdir):
result = testdir.runpytest("--fixtures-per-test") result = testdir.runpytest("--fixtures-per-test")
assert "fixtures used by" not in result.stdout.str() assert "fixtures used by" not in result.stdout.str()

View File

@ -30,7 +30,7 @@ def _wrapcall(*args, **kargs):
return [] return []
class FilesCompleter(object): class FilesCompleter:
"File completer class, optionally takes a list of allowed extensions" "File completer class, optionally takes a list of allowed extensions"
def __init__(self, allowednames=(), directories=True): def __init__(self, allowednames=(), directories=True):
@ -73,7 +73,7 @@ class FilesCompleter(object):
return completion return completion
class TestArgComplete(object): class TestArgComplete:
@pytest.mark.skipif("sys.platform in ('win32', 'darwin')") @pytest.mark.skipif("sys.platform in ('win32', 'darwin')")
def test_compare_with_compgen(self, tmpdir): def test_compare_with_compgen(self, tmpdir):
from _pytest._argcomplete import FastFilesCompleter from _pytest._argcomplete import FastFilesCompleter

View File

@ -3,7 +3,6 @@ import sys
import textwrap import textwrap
import attr import attr
import six
import _pytest.assertion as plugin import _pytest.assertion as plugin
import pytest import pytest
@ -13,7 +12,7 @@ from _pytest.assertion import util
def mock_config(): def mock_config():
class Config(object): class Config:
verbose = False verbose = False
def getoption(self, name): def getoption(self, name):
@ -24,7 +23,7 @@ def mock_config():
return Config() return Config()
class TestImportHookInstallation(object): class TestImportHookInstallation:
@pytest.mark.parametrize("initial_conftest", [True, False]) @pytest.mark.parametrize("initial_conftest", [True, False])
@pytest.mark.parametrize("mode", ["plain", "rewrite"]) @pytest.mark.parametrize("mode", ["plain", "rewrite"])
def test_conftest_assertion_rewrite(self, testdir, initial_conftest, mode): def test_conftest_assertion_rewrite(self, testdir, initial_conftest, mode):
@ -269,7 +268,7 @@ class TestImportHookInstallation(object):
) )
class TestBinReprIntegration(object): class TestBinReprIntegration:
def test_pytest_assertrepr_compare_called(self, testdir): def test_pytest_assertrepr_compare_called(self, testdir):
testdir.makeconftest( testdir.makeconftest(
""" """
@ -301,7 +300,7 @@ def callequal(left, right, verbose=False):
return plugin.pytest_assertrepr_compare(config, "==", left, right) return plugin.pytest_assertrepr_compare(config, "==", left, right)
class TestAssert_reprcompare(object): class TestAssert_reprcompare:
def test_different_types(self): def test_different_types(self):
assert callequal([0, 1], "foo") is None assert callequal([0, 1], "foo") is None
@ -527,7 +526,7 @@ class TestAssert_reprcompare(object):
assert "+" + repr(nums_y) in expl assert "+" + repr(nums_y) in expl
def test_list_bad_repr(self): def test_list_bad_repr(self):
class A(object): class A:
def __repr__(self): def __repr__(self):
raise ValueError(42) raise ValueError(42)
@ -554,12 +553,12 @@ class TestAssert_reprcompare(object):
assert "raised in repr()" not in expl assert "raised in repr()" not in expl
def test_unicode(self): def test_unicode(self):
left = u"£€" left = "£€"
right = u"£" right = "£"
expl = callequal(left, right) expl = callequal(left, right)
assert expl[0] == u"'£€' == '£'" assert expl[0] == "'£€' == '£'"
assert expl[1] == u"- £€" assert expl[1] == "- £€"
assert expl[2] == u"+ £" assert expl[2] == "+ £"
def test_nonascii_text(self): def test_nonascii_text(self):
""" """
@ -583,12 +582,12 @@ class TestAssert_reprcompare(object):
right = b"\xc3\xa9" right = b"\xc3\xa9"
expl = callequal(left, right) expl = callequal(left, right)
for line in expl: for line in expl:
assert isinstance(line, six.text_type) assert isinstance(line, str)
msg = u"\n".join(expl) msg = "\n".join(expl)
assert msg assert msg
class TestAssert_reprcompare_dataclass(object): class TestAssert_reprcompare_dataclass:
@pytest.mark.skipif(sys.version_info < (3, 7), reason="Dataclasses in Python3.7+") @pytest.mark.skipif(sys.version_info < (3, 7), reason="Dataclasses in Python3.7+")
def test_dataclasses(self, testdir): def test_dataclasses(self, testdir):
p = testdir.copy_example("dataclasses/test_compare_dataclasses.py") p = testdir.copy_example("dataclasses/test_compare_dataclasses.py")
@ -633,10 +632,10 @@ class TestAssert_reprcompare_dataclass(object):
result.assert_outcomes(failed=0, passed=1) result.assert_outcomes(failed=0, passed=1)
class TestAssert_reprcompare_attrsclass(object): class TestAssert_reprcompare_attrsclass:
def test_attrs(self): def test_attrs(self):
@attr.s @attr.s
class SimpleDataObject(object): class SimpleDataObject:
field_a = attr.ib() field_a = attr.ib()
field_b = attr.ib() field_b = attr.ib()
@ -651,7 +650,7 @@ class TestAssert_reprcompare_attrsclass(object):
def test_attrs_verbose(self): def test_attrs_verbose(self):
@attr.s @attr.s
class SimpleDataObject(object): class SimpleDataObject:
field_a = attr.ib() field_a = attr.ib()
field_b = attr.ib() field_b = attr.ib()
@ -665,7 +664,7 @@ class TestAssert_reprcompare_attrsclass(object):
def test_attrs_with_attribute_comparison_off(self): def test_attrs_with_attribute_comparison_off(self):
@attr.s @attr.s
class SimpleDataObject(object): class SimpleDataObject:
field_a = attr.ib() field_a = attr.ib()
field_b = attr.ib(cmp=False) field_b = attr.ib(cmp=False)
@ -681,12 +680,12 @@ class TestAssert_reprcompare_attrsclass(object):
def test_comparing_two_different_attrs_classes(self): def test_comparing_two_different_attrs_classes(self):
@attr.s @attr.s
class SimpleDataObjectOne(object): class SimpleDataObjectOne:
field_a = attr.ib() field_a = attr.ib()
field_b = attr.ib() field_b = attr.ib()
@attr.s @attr.s
class SimpleDataObjectTwo(object): class SimpleDataObjectTwo:
field_a = attr.ib() field_a = attr.ib()
field_b = attr.ib() field_b = attr.ib()
@ -697,7 +696,7 @@ class TestAssert_reprcompare_attrsclass(object):
assert lines is None assert lines is None
class TestFormatExplanation(object): class TestFormatExplanation:
def test_special_chars_full(self, testdir): def test_special_chars_full(self, testdir):
# Issue 453, for the bug this would raise IndexError # Issue 453, for the bug this would raise IndexError
testdir.makepyfile( testdir.makepyfile(
@ -784,7 +783,7 @@ class TestFormatExplanation(object):
assert util.format_explanation(expl) == res assert util.format_explanation(expl) == res
class TestTruncateExplanation(object): class TestTruncateExplanation:
""" Confirm assertion output is truncated as expected """ """ Confirm assertion output is truncated as expected """
@ -1218,7 +1217,7 @@ def test_assert_indirect_tuple_no_warning(testdir):
def test_assert_with_unicode(monkeypatch, testdir): def test_assert_with_unicode(monkeypatch, testdir):
testdir.makepyfile( testdir.makepyfile(
u""" """
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
def test_unicode(): def test_unicode():
assert u'유니코드' == u'Unicode' assert u'유니코드' == u'Unicode'
@ -1243,7 +1242,7 @@ def test_raise_unprintable_assertion_error(testdir):
def test_raise_assertion_error_raisin_repr(testdir): def test_raise_assertion_error_raisin_repr(testdir):
testdir.makepyfile( testdir.makepyfile(
u""" """
class RaisingRepr(object): class RaisingRepr(object):
def __repr__(self): def __repr__(self):
raise Exception() raise Exception()

View File

@ -8,7 +8,6 @@ import textwrap
import zipfile import zipfile
import py import py
import six
import _pytest._code import _pytest._code
import pytest import pytest
@ -50,7 +49,7 @@ def getmsg(f, extra_ns=None, must_pass=False):
except AssertionError: except AssertionError:
if must_pass: if must_pass:
pytest.fail("shouldn't have raised") pytest.fail("shouldn't have raised")
s = six.text_type(sys.exc_info()[1]) s = str(sys.exc_info()[1])
if not s.startswith("assert"): if not s.startswith("assert"):
return "AssertionError: " + s return "AssertionError: " + s
return s return s
@ -59,7 +58,7 @@ def getmsg(f, extra_ns=None, must_pass=False):
pytest.fail("function didn't raise at all") pytest.fail("function didn't raise at all")
class TestAssertionRewrite(object): class TestAssertionRewrite:
def test_place_initial_imports(self): def test_place_initial_imports(self):
s = """'Doc string'\nother = stuff""" s = """'Doc string'\nother = stuff"""
m = rewrite(s) m = rewrite(s)
@ -152,7 +151,7 @@ class TestAssertionRewrite(object):
def f(): def f():
assert cls == 42 # noqa: F821 assert cls == 42 # noqa: F821
class X(object): class X:
pass pass
msg = getmsg(f, {"cls": X}).splitlines() msg = getmsg(f, {"cls": X}).splitlines()
@ -167,7 +166,7 @@ class TestAssertionRewrite(object):
assert msg == ["assert cls == 42"] assert msg == ["assert cls == 42"]
def test_dont_rewrite_if_hasattr_fails(self, request): def test_dont_rewrite_if_hasattr_fails(self, request):
class Y(object): class Y:
""" A class whos getattr fails, but not with `AttributeError` """ """ A class whos getattr fails, but not with `AttributeError` """
def __getattr__(self, attribute_name): def __getattr__(self, attribute_name):
@ -506,7 +505,7 @@ class TestAssertionRewrite(object):
) )
def test_attribute(self): def test_attribute(self):
class X(object): class X:
g = 3 g = 3
ns = {"x": X} ns = {"x": X}
@ -596,7 +595,7 @@ class TestAssertionRewrite(object):
def test_assert_raising_nonzero_in_comparison(self): def test_assert_raising_nonzero_in_comparison(self):
def f(): def f():
class A(object): class A:
def __nonzero__(self): def __nonzero__(self):
raise ValueError(42) raise ValueError(42)
@ -621,7 +620,7 @@ class TestAssertionRewrite(object):
def test_custom_repr(self, request): def test_custom_repr(self, request):
def f(): def f():
class Foo(object): class Foo:
a = 1 a = 1
def __repr__(self): def __repr__(self):
@ -644,8 +643,8 @@ class TestAssertionRewrite(object):
def test_custom_repr_non_ascii(self): def test_custom_repr_non_ascii(self):
def f(): def f():
class A(object): class A:
name = u"ä" name = "ä"
def __repr__(self): def __repr__(self):
return self.name.encode("UTF-8") # only legal in python2 return self.name.encode("UTF-8") # only legal in python2
@ -730,7 +729,7 @@ class TestAssertionRewrite(object):
result.stdout.fnmatch_lines(["*assert False*", "*where False = check_even(1)*"]) result.stdout.fnmatch_lines(["*assert False*", "*where False = check_even(1)*"])
class TestRewriteOnImport(object): class TestRewriteOnImport:
def test_pycache_is_a_file(self, testdir): def test_pycache_is_a_file(self, testdir):
testdir.tmpdir.join("__pycache__").write("Hello") testdir.tmpdir.join("__pycache__").write("Hello")
testdir.makepyfile( testdir.makepyfile(
@ -950,7 +949,7 @@ def test_rewritten():
assert "pytest-warning summary" not in result.stdout.str() assert "pytest-warning summary" not in result.stdout.str()
class TestAssertionRewriteHookDetails(object): class TestAssertionRewriteHookDetails:
def test_loader_is_package_false_for_module(self, testdir): def test_loader_is_package_false_for_module(self, testdir):
testdir.makepyfile( testdir.makepyfile(
test_fun=""" test_fun="""
@ -1169,7 +1168,7 @@ def test_issue731(testdir):
assert "unbalanced braces" not in result.stdout.str() assert "unbalanced braces" not in result.stdout.str()
class TestIssue925(object): class TestIssue925:
def test_simple_case(self, testdir): def test_simple_case(self, testdir):
testdir.makepyfile( testdir.makepyfile(
""" """
@ -1276,7 +1275,7 @@ def test_rewrite_infinite_recursion(testdir, pytestconfig, monkeypatch):
assert len(write_pyc_called) == 1 assert len(write_pyc_called) == 1
class TestEarlyRewriteBailout(object): class TestEarlyRewriteBailout:
@pytest.fixture @pytest.fixture
def hook(self, pytestconfig, monkeypatch, testdir): def hook(self, pytestconfig, monkeypatch, testdir):
"""Returns a patched AssertionRewritingHook instance so we can configure its initial paths and track """Returns a patched AssertionRewritingHook instance so we can configure its initial paths and track
@ -1287,7 +1286,7 @@ class TestEarlyRewriteBailout(object):
self.find_module_calls = [] self.find_module_calls = []
self.initial_paths = set() self.initial_paths = set()
class StubSession(object): class StubSession:
_initialpaths = self.initial_paths _initialpaths = self.initial_paths
def isinitpath(self, p): def isinitpath(self, p):

View File

@ -11,7 +11,7 @@ from _pytest.main import EXIT_NOTESTSCOLLECTED
pytest_plugins = ("pytester",) pytest_plugins = ("pytester",)
class TestNewAPI(object): class TestNewAPI:
def test_config_cache_makedir(self, testdir): def test_config_cache_makedir(self, testdir):
testdir.makeini("[pytest]") testdir.makeini("[pytest]")
config = testdir.parseconfigure() config = testdir.parseconfigure()
@ -236,7 +236,7 @@ def test_cache_show(testdir):
assert result.ret == 0 assert result.ret == 0
class TestLastFailed(object): class TestLastFailed:
def test_lastfailed_usecase(self, testdir, monkeypatch): def test_lastfailed_usecase(self, testdir, monkeypatch):
monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", "1") monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", "1")
p = testdir.makepyfile( p = testdir.makepyfile(
@ -870,7 +870,7 @@ class TestLastFailed(object):
) )
class TestNewFirst(object): class TestNewFirst:
def test_newfirst_usecase(self, testdir): def test_newfirst_usecase(self, testdir):
testdir.makepyfile( testdir.makepyfile(
**{ **{
@ -995,7 +995,7 @@ class TestNewFirst(object):
) )
class TestReadme(object): class TestReadme:
def check_readme(self, testdir): def check_readme(self, testdir):
config = testdir.parseconfigure() config = testdir.parseconfigure()
readme = config.cache._cachedir.joinpath("README.md") readme = config.cache._cachedir.joinpath("README.md")
@ -1034,7 +1034,7 @@ def test_gitignore(testdir):
assert gitignore_path.read_text(encoding="UTF-8") == msg assert gitignore_path.read_text(encoding="UTF-8") == msg
# Does not overwrite existing/custom one. # Does not overwrite existing/custom one.
gitignore_path.write_text(u"custom") gitignore_path.write_text("custom")
cache.set("something", "else") cache.set("something", "else")
assert gitignore_path.read_text(encoding="UTF-8") == "custom" assert gitignore_path.read_text(encoding="UTF-8") == "custom"

View File

@ -31,7 +31,7 @@ def StdCapture(out=True, err=True, in_=True):
return capture.MultiCapture(out, err, in_, Capture=capture.SysCapture) return capture.MultiCapture(out, err, in_, Capture=capture.SysCapture)
class TestCaptureManager(object): class TestCaptureManager:
def test_getmethod_default_no_fd(self, monkeypatch): def test_getmethod_default_no_fd(self, monkeypatch):
from _pytest.capture import pytest_addoption from _pytest.capture import pytest_addoption
from _pytest.config.argparsing import Parser from _pytest.config.argparsing import Parser
@ -142,7 +142,7 @@ def test_collect_capturing(testdir):
) )
class TestPerTestCapturing(object): class TestPerTestCapturing:
def test_capture_and_fixtures(self, testdir): def test_capture_and_fixtures(self, testdir):
p = testdir.makepyfile( p = testdir.makepyfile(
""" """
@ -285,7 +285,7 @@ class TestPerTestCapturing(object):
) )
class TestLoggingInteraction(object): class TestLoggingInteraction:
def test_logging_stream_ownership(self, testdir): def test_logging_stream_ownership(self, testdir):
p = testdir.makepyfile( p = testdir.makepyfile(
"""\ """\
@ -423,7 +423,7 @@ class TestLoggingInteraction(object):
) )
class TestCaptureFixture(object): class TestCaptureFixture:
@pytest.mark.parametrize("opt", [[], ["-s"]]) @pytest.mark.parametrize("opt", [[], ["-s"]])
def test_std_functional(self, testdir, opt): def test_std_functional(self, testdir, opt):
reprec = testdir.inline_runsource( reprec = testdir.inline_runsource(
@ -801,7 +801,7 @@ def test_error_during_readouterr(testdir):
) )
class TestCaptureIO(object): class TestCaptureIO:
def test_text(self): def test_text(self):
f = capture.CaptureIO() f = capture.CaptureIO()
f.write("hello") f.write("hello")
@ -916,7 +916,7 @@ def lsof_check():
assert len2 < len1 + 3, out2 assert len2 < len1 + 3, out2
class TestFDCapture(object): class TestFDCapture:
pytestmark = needsosdup pytestmark = needsosdup
def test_simple(self, tmpfile): def test_simple(self, tmpfile):
@ -1014,7 +1014,7 @@ def saved_fd(fd):
os.close(new_fd) os.close(new_fd)
class TestStdCapture(object): class TestStdCapture:
captureclass = staticmethod(StdCapture) captureclass = staticmethod(StdCapture)
@contextlib.contextmanager @contextlib.contextmanager
@ -1065,7 +1065,7 @@ class TestStdCapture(object):
with self.getcapture() as cap: with self.getcapture() as cap:
print("hxąć") print("hxąć")
out, err = cap.readouterr() out, err = cap.readouterr()
assert out == u"hxąć\n" assert out == "hxąć\n"
def test_reset_twice_error(self): def test_reset_twice_error(self):
with self.getcapture() as cap: with self.getcapture() as cap:
@ -1175,7 +1175,7 @@ class TestStdCaptureFD(TestStdCapture):
cap.stop_capturing() cap.stop_capturing()
class TestStdCaptureFDinvalidFD(object): class TestStdCaptureFDinvalidFD:
pytestmark = needsosdup pytestmark = needsosdup
def test_stdcapture_fd_invalid_fd(self, testdir): def test_stdcapture_fd_invalid_fd(self, testdir):
@ -1338,7 +1338,7 @@ def test_py36_windowsconsoleio_workaround_non_standard_streams():
""" """
from _pytest.capture import _py36_windowsconsoleio_workaround from _pytest.capture import _py36_windowsconsoleio_workaround
class DummyStream(object): class DummyStream:
def write(self, s): def write(self, s):
pass pass

View File

@ -12,7 +12,7 @@ from _pytest.main import EXIT_NOTESTSCOLLECTED
from _pytest.main import Session from _pytest.main import Session
class TestCollector(object): class TestCollector:
def test_collect_versus_item(self): def test_collect_versus_item(self):
from pytest import Collector, Item from pytest import Collector, Item
@ -102,7 +102,7 @@ class TestCollector(object):
result.stdout.fnmatch_lines(["collected 0 items", "*no tests ran in*"]) result.stdout.fnmatch_lines(["collected 0 items", "*no tests ran in*"])
class TestCollectFS(object): class TestCollectFS:
def test_ignored_certain_directories(self, testdir): def test_ignored_certain_directories(self, testdir):
tmpdir = testdir.tmpdir tmpdir = testdir.tmpdir
tmpdir.ensure("build", "test_notfound.py") tmpdir.ensure("build", "test_notfound.py")
@ -239,11 +239,11 @@ class TestCollectFS(object):
assert [x.name for x in items] == ["test_%s" % dirname] assert [x.name for x in items] == ["test_%s" % dirname]
class TestCollectPluginHookRelay(object): class TestCollectPluginHookRelay:
def test_pytest_collect_file(self, testdir): def test_pytest_collect_file(self, testdir):
wascalled = [] wascalled = []
class Plugin(object): class Plugin:
def pytest_collect_file(self, path, parent): def pytest_collect_file(self, path, parent):
if not path.basename.startswith("."): if not path.basename.startswith("."):
# Ignore hidden files, e.g. .testmondata. # Ignore hidden files, e.g. .testmondata.
@ -257,7 +257,7 @@ class TestCollectPluginHookRelay(object):
def test_pytest_collect_directory(self, testdir): def test_pytest_collect_directory(self, testdir):
wascalled = [] wascalled = []
class Plugin(object): class Plugin:
def pytest_collect_directory(self, path, parent): def pytest_collect_directory(self, path, parent):
wascalled.append(path.basename) wascalled.append(path.basename)
@ -268,7 +268,7 @@ class TestCollectPluginHookRelay(object):
assert "world" in wascalled assert "world" in wascalled
class TestPrunetraceback(object): class TestPrunetraceback:
def test_custom_repr_failure(self, testdir): def test_custom_repr_failure(self, testdir):
p = testdir.makepyfile( p = testdir.makepyfile(
""" """
@ -317,7 +317,7 @@ class TestPrunetraceback(object):
result.stdout.fnmatch_lines(["*ERROR collecting*", "*header1*"]) result.stdout.fnmatch_lines(["*ERROR collecting*", "*header1*"])
class TestCustomConftests(object): class TestCustomConftests:
def test_ignore_collect_path(self, testdir): def test_ignore_collect_path(self, testdir):
testdir.makeconftest( testdir.makeconftest(
""" """
@ -438,7 +438,7 @@ class TestCustomConftests(object):
result.stdout.fnmatch_lines(["*MyModule1*", "*MyModule2*", "*test_x*"]) result.stdout.fnmatch_lines(["*MyModule1*", "*MyModule2*", "*test_x*"])
class TestSession(object): class TestSession:
def test_parsearg(self, testdir): def test_parsearg(self, testdir):
p = testdir.makepyfile("def test_func(): pass") p = testdir.makepyfile("def test_func(): pass")
subdir = testdir.mkdir("sub") subdir = testdir.mkdir("sub")
@ -629,7 +629,7 @@ class TestSession(object):
assert [x.name for x in self.get_reported_items(hookrec)] == ["test_method"] assert [x.name for x in self.get_reported_items(hookrec)] == ["test_method"]
class Test_getinitialnodes(object): class Test_getinitialnodes:
def test_global_file(self, testdir, tmpdir): def test_global_file(self, testdir, tmpdir):
x = tmpdir.ensure("x.py") x = tmpdir.ensure("x.py")
with tmpdir.as_cwd(): with tmpdir.as_cwd():
@ -663,7 +663,7 @@ class Test_getinitialnodes(object):
assert col.config is config assert col.config is config
class Test_genitems(object): class Test_genitems:
def test_check_collect_hashes(self, testdir): def test_check_collect_hashes(self, testdir):
p = testdir.makepyfile( p = testdir.makepyfile(
""" """
@ -776,7 +776,7 @@ def test_matchnodes_two_collections_same_file(testdir):
res.stdout.fnmatch_lines(["*1 passed*"]) res.stdout.fnmatch_lines(["*1 passed*"])
class TestNodekeywords(object): class TestNodekeywords:
def test_no_under(self, testdir): def test_no_under(self, testdir):
modcol = testdir.getmodulecol( modcol = testdir.getmodulecol(
""" """

View File

@ -22,7 +22,7 @@ def test_is_generator():
def test_real_func_loop_limit(): def test_real_func_loop_limit():
class Evil(object): class Evil:
def __init__(self): def __init__(self):
self.left = 1000 self.left = 1000
@ -113,7 +113,7 @@ def test_is_generator_async_syntax(testdir):
result.stdout.fnmatch_lines(["*1 passed*"]) result.stdout.fnmatch_lines(["*1 passed*"])
class ErrorsHelper(object): class ErrorsHelper:
@property @property
def raise_exception(self): def raise_exception(self):
raise Exception("exception should be catched") raise Exception("exception should be catched")

View File

@ -16,7 +16,7 @@ from _pytest.main import EXIT_TESTSFAILED
from _pytest.main import EXIT_USAGEERROR from _pytest.main import EXIT_USAGEERROR
class TestParseIni(object): class TestParseIni:
@pytest.mark.parametrize( @pytest.mark.parametrize(
"section, filename", [("pytest", "pytest.ini"), ("tool:pytest", "setup.cfg")] "section, filename", [("pytest", "pytest.ini"), ("tool:pytest", "setup.cfg")]
) )
@ -139,7 +139,7 @@ class TestParseIni(object):
assert result.ret == 0 assert result.ret == 0
class TestConfigCmdlineParsing(object): class TestConfigCmdlineParsing:
def test_parsing_again_fails(self, testdir): def test_parsing_again_fails(self, testdir):
config = testdir.parseconfig() config = testdir.parseconfig()
pytest.raises(AssertionError, lambda: config.parse([])) pytest.raises(AssertionError, lambda: config.parse([]))
@ -192,7 +192,7 @@ class TestConfigCmdlineParsing(object):
assert ret == _pytest.main.EXIT_OK assert ret == _pytest.main.EXIT_OK
class TestConfigAPI(object): class TestConfigAPI:
def test_config_trace(self, testdir): def test_config_trace(self, testdir):
config = testdir.parseconfig() config = testdir.parseconfig()
values = [] values = []
@ -428,7 +428,7 @@ class TestConfigAPI(object):
assert list(_iter_rewritable_modules(["/".join(names)])) == expected assert list(_iter_rewritable_modules(["/".join(names)])) == expected
class TestConfigFromdictargs(object): class TestConfigFromdictargs:
def test_basic_behavior(self, _sys_snapshot): def test_basic_behavior(self, _sys_snapshot):
from _pytest.config import Config from _pytest.config import Config
@ -526,17 +526,17 @@ def test_options_on_small_file_do_not_blow_up(testdir):
def test_preparse_ordering_with_setuptools(testdir, monkeypatch): def test_preparse_ordering_with_setuptools(testdir, monkeypatch):
monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False) monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)
class EntryPoint(object): class EntryPoint:
name = "mytestplugin" name = "mytestplugin"
group = "pytest11" group = "pytest11"
def load(self): def load(self):
class PseudoPlugin(object): class PseudoPlugin:
x = 42 x = 42
return PseudoPlugin() return PseudoPlugin()
class Dist(object): class Dist:
files = () files = ()
entry_points = (EntryPoint(),) entry_points = (EntryPoint(),)
@ -558,14 +558,14 @@ def test_preparse_ordering_with_setuptools(testdir, monkeypatch):
def test_setuptools_importerror_issue1479(testdir, monkeypatch): def test_setuptools_importerror_issue1479(testdir, monkeypatch):
monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False) monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)
class DummyEntryPoint(object): class DummyEntryPoint:
name = "mytestplugin" name = "mytestplugin"
group = "pytest11" group = "pytest11"
def load(self): def load(self):
raise ImportError("Don't hide me!") raise ImportError("Don't hide me!")
class Distribution(object): class Distribution:
version = "1.0" version = "1.0"
files = ("foo.txt",) files = ("foo.txt",)
entry_points = (DummyEntryPoint(),) entry_points = (DummyEntryPoint(),)
@ -584,14 +584,14 @@ def test_plugin_preparse_prevents_setuptools_loading(testdir, monkeypatch, block
plugin_module_placeholder = object() plugin_module_placeholder = object()
class DummyEntryPoint(object): class DummyEntryPoint:
name = "mytestplugin" name = "mytestplugin"
group = "pytest11" group = "pytest11"
def load(self): def load(self):
return plugin_module_placeholder return plugin_module_placeholder
class Distribution(object): class Distribution:
version = "1.0" version = "1.0"
files = ("foo.txt",) files = ("foo.txt",)
entry_points = (DummyEntryPoint(),) entry_points = (DummyEntryPoint(),)
@ -616,7 +616,7 @@ def test_plugin_preparse_prevents_setuptools_loading(testdir, monkeypatch, block
"parse_args,should_load", [(("-p", "mytestplugin"), True), ((), False)] "parse_args,should_load", [(("-p", "mytestplugin"), True), ((), False)]
) )
def test_disable_plugin_autoload(testdir, monkeypatch, parse_args, should_load): def test_disable_plugin_autoload(testdir, monkeypatch, parse_args, should_load):
class DummyEntryPoint(object): class DummyEntryPoint:
project_name = name = "mytestplugin" project_name = name = "mytestplugin"
group = "pytest11" group = "pytest11"
version = "1.0" version = "1.0"
@ -624,11 +624,11 @@ def test_disable_plugin_autoload(testdir, monkeypatch, parse_args, should_load):
def load(self): def load(self):
return sys.modules[self.name] return sys.modules[self.name]
class Distribution(object): class Distribution:
entry_points = (DummyEntryPoint(),) entry_points = (DummyEntryPoint(),)
files = () files = ()
class PseudoPlugin(object): class PseudoPlugin:
x = 42 x = 42
def distributions(): def distributions():
@ -740,7 +740,7 @@ def test_notify_exception(testdir, capfd):
out, err = capfd.readouterr() out, err = capfd.readouterr()
assert "ValueError" in err assert "ValueError" in err
class A(object): class A:
def pytest_internalerror(self, excrepr): def pytest_internalerror(self, excrepr):
return True return True
@ -760,7 +760,7 @@ def test_notify_exception(testdir, capfd):
def test_load_initial_conftest_last_ordering(testdir, _config_for_test): def test_load_initial_conftest_last_ordering(testdir, _config_for_test):
pm = _config_for_test.pluginmanager pm = _config_for_test.pluginmanager
class My(object): class My:
def pytest_load_initial_conftests(self): def pytest_load_initial_conftests(self):
pass pass
@ -798,15 +798,15 @@ def test_collect_pytest_prefix_bug_integration(testdir):
def test_collect_pytest_prefix_bug(pytestconfig): def test_collect_pytest_prefix_bug(pytestconfig):
"""Ensure we collect only actual functions from conftest files (#3775)""" """Ensure we collect only actual functions from conftest files (#3775)"""
class Dummy(object): class Dummy:
class pytest_something(object): class pytest_something:
pass pass
pm = pytestconfig.pluginmanager pm = pytestconfig.pluginmanager
assert pm.parse_hookimpl_opts(Dummy(), "pytest_something") is None assert pm.parse_hookimpl_opts(Dummy(), "pytest_something") is None
class TestRootdir(object): class TestRootdir:
def test_simple_noini(self, tmpdir): def test_simple_noini(self, tmpdir):
assert get_common_ancestor([tmpdir]) == tmpdir assert get_common_ancestor([tmpdir]) == tmpdir
a = tmpdir.mkdir("a") a = tmpdir.mkdir("a")
@ -864,7 +864,7 @@ class TestRootdir(object):
assert rootdir == tmpdir assert rootdir == tmpdir
class TestOverrideIniArgs(object): class TestOverrideIniArgs:
@pytest.mark.parametrize("name", "setup.cfg tox.ini pytest.ini".split()) @pytest.mark.parametrize("name", "setup.cfg tox.ini pytest.ini".split())
def test_override_ini_names(self, testdir, name): def test_override_ini_names(self, testdir, name):
section = "[pytest]" if name != "setup.cfg" else "[tool:pytest]" section = "[pytest]" if name != "setup.cfg" else "[tool:pytest]"

View File

@ -16,7 +16,7 @@ def ConftestWithSetinitial(path):
def conftest_setinitial(conftest, args, confcutdir=None): def conftest_setinitial(conftest, args, confcutdir=None):
class Namespace(object): class Namespace:
def __init__(self): def __init__(self):
self.file_or_dir = args self.file_or_dir = args
self.confcutdir = str(confcutdir) self.confcutdir = str(confcutdir)
@ -27,7 +27,7 @@ def conftest_setinitial(conftest, args, confcutdir=None):
@pytest.mark.usefixtures("_sys_snapshot") @pytest.mark.usefixtures("_sys_snapshot")
class TestConftestValueAccessGlobal(object): class TestConftestValueAccessGlobal:
@pytest.fixture(scope="module", params=["global", "inpackage"]) @pytest.fixture(scope="module", params=["global", "inpackage"])
def basedir(self, request, tmpdir_factory): def basedir(self, request, tmpdir_factory):
tmpdir = tmpdir_factory.mktemp("basedir", numbered=True) tmpdir = tmpdir_factory.mktemp("basedir", numbered=True)
@ -396,7 +396,7 @@ def test_conftest_found_with_double_dash(testdir):
) )
class TestConftestVisibility(object): class TestConftestVisibility:
def _setup_tree(self, testdir): # for issue616 def _setup_tree(self, testdir): # for issue616
# example mostly taken from: # example mostly taken from:
# https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html

View File

@ -7,7 +7,7 @@ from _pytest.doctest import DoctestModule
from _pytest.doctest import DoctestTextfile from _pytest.doctest import DoctestTextfile
class TestDoctests(object): class TestDoctests:
def test_collect_testtextfile(self, testdir): def test_collect_testtextfile(self, testdir):
w = testdir.maketxtfile(whatever="") w = testdir.maketxtfile(whatever="")
checkfile = testdir.maketxtfile( checkfile = testdir.maketxtfile(
@ -139,7 +139,7 @@ class TestDoctests(object):
@pytest.mark.parametrize( @pytest.mark.parametrize(
" test_string, encoding", " test_string, encoding",
[(u"foo", "ascii"), (u"öäü", "latin1"), (u"öäü", "utf-8")], [("foo", "ascii"), ("öäü", "latin1"), ("öäü", "utf-8")],
) )
def test_encoding(self, testdir, test_string, encoding): def test_encoding(self, testdir, test_string, encoding):
"""Test support for doctest_encoding ini option. """Test support for doctest_encoding ini option.
@ -152,7 +152,7 @@ class TestDoctests(object):
encoding encoding
) )
) )
doctest = u""" doctest = """
>>> u"{}" >>> u"{}"
{} {}
""".format( """.format(
@ -574,7 +574,7 @@ class TestDoctests(object):
"""Fix internal error with docstrings containing non-ascii characters. """Fix internal error with docstrings containing non-ascii characters.
""" """
testdir.makepyfile( testdir.makepyfile(
u''' '''
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
def foo(): def foo():
""" """
@ -733,7 +733,7 @@ class TestDoctests(object):
result.stdout.fnmatch_lines(["*collected 1 item*"]) result.stdout.fnmatch_lines(["*collected 1 item*"])
class TestLiterals(object): class TestLiterals:
@pytest.mark.parametrize("config_mode", ["ini", "comment"]) @pytest.mark.parametrize("config_mode", ["ini", "comment"])
def test_allow_unicode(self, testdir, config_mode): def test_allow_unicode(self, testdir, config_mode):
"""Test that doctests which output unicode work in all python versions """Test that doctests which output unicode work in all python versions
@ -840,7 +840,7 @@ class TestLiterals(object):
reprec.assertoutcome(failed=1) reprec.assertoutcome(failed=1)
class TestDoctestSkips(object): class TestDoctestSkips:
""" """
If all examples in a doctest are skipped due to the SKIP option, then If all examples in a doctest are skipped due to the SKIP option, then
the tests should be SKIPPED rather than PASSED. (#957) the tests should be SKIPPED rather than PASSED. (#957)
@ -921,7 +921,7 @@ class TestDoctestSkips(object):
) )
class TestDoctestAutoUseFixtures(object): class TestDoctestAutoUseFixtures:
SCOPES = ["module", "session", "class", "function"] SCOPES = ["module", "session", "class", "function"]
@ -1065,7 +1065,7 @@ class TestDoctestAutoUseFixtures(object):
result.stdout.fnmatch_lines(["*=== 1 passed in *"]) result.stdout.fnmatch_lines(["*=== 1 passed in *"])
class TestDoctestNamespaceFixture(object): class TestDoctestNamespaceFixture:
SCOPES = ["module", "session", "class", "function"] SCOPES = ["module", "session", "class", "function"]
@ -1127,7 +1127,7 @@ class TestDoctestNamespaceFixture(object):
reprec.assertoutcome(passed=1) reprec.assertoutcome(passed=1)
class TestDoctestReportingOption(object): class TestDoctestReportingOption:
def _run_doctest_report(self, testdir, format): def _run_doctest_report(self, testdir, format):
testdir.makepyfile( testdir.makepyfile(
""" """

View File

@ -28,7 +28,7 @@ def assert_attr(node, **kwargs):
assert on_node == expected assert on_node == expected
class DomNode(object): class DomNode:
def __init__(self, dom): def __init__(self, dom):
self.__node = dom self.__node = dom
@ -79,7 +79,7 @@ class DomNode(object):
return type(self)(self.__node.nextSibling) return type(self)(self.__node.nextSibling)
class TestPython(object): class TestPython:
def test_summing_simple(self, testdir): def test_summing_simple(self, testdir):
testdir.makepyfile( testdir.makepyfile(
""" """
@ -696,7 +696,7 @@ def test_mangle_test_address():
def test_dont_configure_on_slaves(tmpdir): def test_dont_configure_on_slaves(tmpdir):
gotten = [] gotten = []
class FakeConfig(object): class FakeConfig:
def __init__(self): def __init__(self):
self.pluginmanager = self self.pluginmanager = self
self.option = self self.option = self
@ -719,7 +719,7 @@ def test_dont_configure_on_slaves(tmpdir):
assert len(gotten) == 1 assert len(gotten) == 1
class TestNonPython(object): class TestNonPython:
def test_summing_simple(self, testdir): def test_summing_simple(self, testdir):
testdir.makeconftest( testdir.makeconftest(
""" """
@ -922,7 +922,7 @@ def test_double_colon_split_method_issue469(testdir):
def test_unicode_issue368(testdir): def test_unicode_issue368(testdir):
path = testdir.tmpdir.join("test.xml") path = testdir.tmpdir.join("test.xml")
log = LogXML(str(path), None) log = LogXML(str(path), None)
ustr = u"ВНИ!" ustr = "ВНИ!"
class Report(BaseReport): class Report(BaseReport):
longrepr = ustr longrepr = ustr
@ -1166,13 +1166,13 @@ def test_fancy_items_regression(testdir):
pprint.pprint(items) pprint.pprint(items)
assert items == [ assert items == [
u"conftest a", "conftest a",
u"conftest a", "conftest a",
u"conftest b", "conftest b",
u"test_fancy_items_regression a", "test_fancy_items_regression a",
u"test_fancy_items_regression a", "test_fancy_items_regression a",
u"test_fancy_items_regression b", "test_fancy_items_regression b",
u"test_fancy_items_regression test_pass", "test_fancy_items_regression test_pass",
] ]

View File

@ -16,7 +16,7 @@ ignore_markinfo = pytest.mark.filterwarnings(
) )
class TestMark(object): class TestMark:
@pytest.mark.parametrize("attr", ["mark", "param"]) @pytest.mark.parametrize("attr", ["mark", "param"])
@pytest.mark.parametrize("modulename", ["py.test", "pytest"]) @pytest.mark.parametrize("modulename", ["py.test", "pytest"])
def test_pytest_exists_in_namespace_all(self, attr, modulename): def test_pytest_exists_in_namespace_all(self, attr, modulename):
@ -31,7 +31,7 @@ class TestMark(object):
def some_function(abc): def some_function(abc):
pass pass
class SomeClass(object): class SomeClass:
pass pass
assert pytest.mark.foo(some_function) is some_function assert pytest.mark.foo(some_function) is some_function
@ -424,7 +424,7 @@ def test_parametrize_iterator(testdir):
result.stdout.fnmatch_lines(["*3 passed*"]) result.stdout.fnmatch_lines(["*3 passed*"])
class TestFunctional(object): class TestFunctional:
def test_merging_markers_deep(self, testdir): def test_merging_markers_deep(self, testdir):
# issue 199 - propagate markers into nested classes # issue 199 - propagate markers into nested classes
p = testdir.makepyfile( p = testdir.makepyfile(
@ -693,7 +693,7 @@ class TestFunctional(object):
reprec.assertoutcome(skipped=1) reprec.assertoutcome(skipped=1)
class TestKeywordSelection(object): class TestKeywordSelection:
def test_select_simple(self, testdir): def test_select_simple(self, testdir):
file_test = testdir.makepyfile( file_test = testdir.makepyfile(
""" """
@ -824,7 +824,7 @@ class TestKeywordSelection(object):
assert_test_is_not_selected("()") assert_test_is_not_selected("()")
class TestMarkDecorator(object): class TestMarkDecorator:
@pytest.mark.parametrize( @pytest.mark.parametrize(
"lhs, rhs, expected", "lhs, rhs, expected",
[ [

View File

@ -17,7 +17,7 @@ def mp():
def test_setattr(): def test_setattr():
class A(object): class A:
x = 1 x = 1
monkeypatch = MonkeyPatch() monkeypatch = MonkeyPatch()
@ -40,7 +40,7 @@ def test_setattr():
assert A.x == 5 assert A.x == 5
class TestSetattrWithImportPath(object): class TestSetattrWithImportPath:
def test_string_expression(self, monkeypatch): def test_string_expression(self, monkeypatch):
monkeypatch.setattr("os.path.abspath", lambda x: "hello2") monkeypatch.setattr("os.path.abspath", lambda x: "hello2")
assert os.path.abspath("123") == "hello2" assert os.path.abspath("123") == "hello2"
@ -82,7 +82,7 @@ class TestSetattrWithImportPath(object):
def test_delattr(): def test_delattr():
class A(object): class A:
x = 1 x = 1
monkeypatch = MonkeyPatch() monkeypatch = MonkeyPatch()
@ -193,14 +193,14 @@ def test_delenv():
del os.environ[name] del os.environ[name]
class TestEnvironWarnings(object): class TestEnvironWarnings:
""" """
os.environ keys and values should be native strings, otherwise it will cause problems with other modules (notably os.environ keys and values should be native strings, otherwise it will cause problems with other modules (notably
subprocess). On Python 2 os.environ accepts anything without complaining, while Python 3 does the right thing subprocess). On Python 2 os.environ accepts anything without complaining, while Python 3 does the right thing
and raises an error. and raises an error.
""" """
VAR_NAME = u"PYTEST_INTERNAL_MY_VAR" VAR_NAME = "PYTEST_INTERNAL_MY_VAR"
def test_setenv_non_str_warning(self, monkeypatch): def test_setenv_non_str_warning(self, monkeypatch):
value = 2 value = 2
@ -331,7 +331,7 @@ def test_importerror(testdir):
) )
class SampleNew(object): class SampleNew:
@staticmethod @staticmethod
def hello(): def hello():
return True return True
@ -341,7 +341,7 @@ class SampleNewInherit(SampleNew):
pass pass
class SampleOld(object): class SampleOld:
# oldstyle on python2 # oldstyle on python2
@staticmethod @staticmethod
def hello(): def hello():
@ -368,7 +368,7 @@ def test_issue156_undo_staticmethod(Sample):
def test_undo_class_descriptors_delattr(): def test_undo_class_descriptors_delattr():
class SampleParent(object): class SampleParent:
@classmethod @classmethod
def hello(_cls): def hello(_cls):
pass pass

View File

@ -31,7 +31,7 @@ def test_setup_func_with_setup_decorator():
values = [] values = []
class A(object): class A:
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def f(self): def f(self):
values.append(1) values.append(1)
@ -43,7 +43,7 @@ def test_setup_func_with_setup_decorator():
def test_setup_func_not_callable(): def test_setup_func_not_callable():
from _pytest.nose import call_optional from _pytest.nose import call_optional
class A(object): class A:
f = 1 f = 1
call_optional(A(), "f") call_optional(A(), "f")

View File

@ -15,7 +15,7 @@ def parser():
return parseopt.Parser() return parseopt.Parser()
class TestParser(object): class TestParser:
def test_no_help_by_default(self): def test_no_help_by_default(self):
parser = parseopt.Parser(usage="xyz") parser = parseopt.Parser(usage="xyz")
pytest.raises(UsageError, lambda: parser.parse(["-h"])) pytest.raises(UsageError, lambda: parser.parse(["-h"]))
@ -152,7 +152,7 @@ class TestParser(object):
parser.addoption("--hello", dest="hello", action="store") parser.addoption("--hello", dest="hello", action="store")
parser.addoption("--world", dest="world", default=42) parser.addoption("--world", dest="world", default=42)
class A(object): class A:
pass pass
option = A() option = A()

View File

@ -1,7 +1,7 @@
import pytest import pytest
class TestPasteCapture(object): class TestPasteCapture:
@pytest.fixture @pytest.fixture
def pastebinlist(self, monkeypatch, request): def pastebinlist(self, monkeypatch, request):
pastebinlist = [] pastebinlist = []
@ -77,7 +77,7 @@ class TestPasteCapture(object):
) )
class TestPaste(object): class TestPaste:
@pytest.fixture @pytest.fixture
def pastebin(self, request): def pastebin(self, request):
return request.config.pluginmanager.getplugin("pastebin") return request.config.pluginmanager.getplugin("pastebin")
@ -93,7 +93,7 @@ class TestPaste(object):
def mocked(url, data): def mocked(url, data):
calls.append((url, data)) calls.append((url, data))
class DummyFile(object): class DummyFile:
def read(self): def read(self):
# part of html of a normal response # part of html of a normal response
return b'View <a href="/raw/3c0c6750bd">raw</a>.' return b'View <a href="/raw/3c0c6750bd">raw</a>.'

View File

@ -29,7 +29,7 @@ def custom_pdb_calls():
called = [] called = []
# install dummy debugger class and track which methods were called on it # install dummy debugger class and track which methods were called on it
class _CustomPdb(object): class _CustomPdb:
quitting = False quitting = False
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -50,7 +50,7 @@ def custom_debugger_hook():
called = [] called = []
# install dummy debugger class and track which methods were called on it # install dummy debugger class and track which methods were called on it
class _CustomDebugger(object): class _CustomDebugger:
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
called.append("init") called.append("init")
@ -69,7 +69,7 @@ def custom_debugger_hook():
del _pytest._CustomDebugger del _pytest._CustomDebugger
class TestPDB(object): class TestPDB:
@pytest.fixture @pytest.fixture
def pdblist(self, request): def pdblist(self, request):
monkeypatch = request.getfixturevalue("monkeypatch") monkeypatch = request.getfixturevalue("monkeypatch")
@ -666,7 +666,7 @@ class TestPDB(object):
set_trace() set_trace()
""" """
) )
child = testdir.spawn_pytest("--tb=short %s %s" % (p1, capture_arg)) child = testdir.spawn_pytest("--tb=short {} {}".format(p1, capture_arg))
child.expect("=== SET_TRACE ===") child.expect("=== SET_TRACE ===")
before = child.before.decode("utf8") before = child.before.decode("utf8")
if not capture_arg: if not capture_arg:
@ -846,7 +846,7 @@ class TestPDB(object):
self.flush(child) self.flush(child)
class TestDebuggingBreakpoints(object): class TestDebuggingBreakpoints:
def test_supports_breakpoint_module_global(self): def test_supports_breakpoint_module_global(self):
""" """
Test that supports breakpoint global marks on Python 3.7+ and not on Test that supports breakpoint global marks on Python 3.7+ and not on

View File

@ -14,7 +14,7 @@ def pytestpm():
return PytestPluginManager() return PytestPluginManager()
class TestPytestPluginInteractions(object): class TestPytestPluginInteractions:
def test_addhooks_conftestplugin(self, testdir, _config_for_test): def test_addhooks_conftestplugin(self, testdir, _config_for_test):
testdir.makepyfile( testdir.makepyfile(
newhooks=""" newhooks="""
@ -70,7 +70,7 @@ class TestPytestPluginInteractions(object):
config = testdir.parseconfig() config = testdir.parseconfig()
values = [] values = []
class A(object): class A:
def pytest_configure(self, config): def pytest_configure(self, config):
values.append(self) values.append(self)
@ -90,11 +90,11 @@ class TestPytestPluginInteractions(object):
pytestpm = _config_for_test.pluginmanager # fully initialized with plugins pytestpm = _config_for_test.pluginmanager # fully initialized with plugins
saveindent = [] saveindent = []
class api1(object): class api1:
def pytest_plugin_registered(self): def pytest_plugin_registered(self):
saveindent.append(pytestpm.trace.root.indent) saveindent.append(pytestpm.trace.root.indent)
class api2(object): class api2:
def pytest_plugin_registered(self): def pytest_plugin_registered(self):
saveindent.append(pytestpm.trace.root.indent) saveindent.append(pytestpm.trace.root.indent)
raise ValueError() raise ValueError()
@ -165,7 +165,7 @@ def test_importplugin_error_message(testdir, pytestpm):
assert "in test_traceback" in str(excinfo.traceback[-1]) assert "in test_traceback" in str(excinfo.traceback[-1])
class TestPytestPluginManager(object): class TestPytestPluginManager:
def test_register_imported_modules(self): def test_register_imported_modules(self):
pm = PytestPluginManager() pm = PytestPluginManager()
mod = types.ModuleType("x.y.pytest_hello") mod = types.ModuleType("x.y.pytest_hello")
@ -295,7 +295,7 @@ class TestPytestPluginManager(object):
pytestpm.consider_conftest(mod) pytestpm.consider_conftest(mod)
class TestPytestPluginManagerBootstrapming(object): class TestPytestPluginManagerBootstrapming:
def test_preparse_args(self, pytestpm): def test_preparse_args(self, pytestpm):
pytest.raises( pytest.raises(
ImportError, lambda: pytestpm.consider_preparse(["xyz", "-p", "hello123"]) ImportError, lambda: pytestpm.consider_preparse(["xyz", "-p", "hello123"])

View File

@ -25,7 +25,7 @@ def test_make_hook_recorder(testdir):
pytest.xfail("internal reportrecorder tests need refactoring") pytest.xfail("internal reportrecorder tests need refactoring")
class rep(object): class rep:
excinfo = None excinfo = None
passed = False passed = False
failed = True failed = True
@ -38,7 +38,7 @@ def test_make_hook_recorder(testdir):
failures = recorder.getfailures() failures = recorder.getfailures()
assert failures == [rep] assert failures == [rep]
class rep(object): class rep:
excinfo = None excinfo = None
passed = False passed = False
failed = False failed = False
@ -153,7 +153,7 @@ def test_xpassed_with_strict_is_considered_a_failure(testdir):
def make_holder(): def make_holder():
class apiclass(object): class apiclass:
def pytest_xyz(self, arg): def pytest_xyz(self, arg):
"x" "x"
@ -199,17 +199,17 @@ def test_makepyfile_unicode(testdir):
def test_makepyfile_utf8(testdir): def test_makepyfile_utf8(testdir):
"""Ensure makepyfile accepts utf-8 bytes as input (#2738)""" """Ensure makepyfile accepts utf-8 bytes as input (#2738)"""
utf8_contents = u""" utf8_contents = """
def setup_function(function): def setup_function(function):
mixed_encoding = u'São Paulo' mixed_encoding = u'São Paulo'
""".encode( """.encode(
"utf-8" "utf-8"
) )
p = testdir.makepyfile(utf8_contents) p = testdir.makepyfile(utf8_contents)
assert u"mixed_encoding = u'São Paulo'".encode("utf-8") in p.read("rb") assert "mixed_encoding = u'São Paulo'".encode() in p.read("rb")
class TestInlineRunModulesCleanup(object): class TestInlineRunModulesCleanup:
def test_inline_run_test_module_not_cleaned_up(self, testdir): def test_inline_run_test_module_not_cleaned_up(self, testdir):
test_mod = testdir.makepyfile("def test_foo(): assert True") test_mod = testdir.makepyfile("def test_foo(): assert True")
result = testdir.inline_run(str(test_mod)) result = testdir.inline_run(str(test_mod))
@ -220,7 +220,7 @@ class TestInlineRunModulesCleanup(object):
assert result2.ret == EXIT_TESTSFAILED assert result2.ret == EXIT_TESTSFAILED
def spy_factory(self): def spy_factory(self):
class SysModulesSnapshotSpy(object): class SysModulesSnapshotSpy:
instances = [] instances = []
def __init__(self, preserve=None): def __init__(self, preserve=None):
@ -303,7 +303,7 @@ def test_cwd_snapshot(tmpdir):
assert py.path.local() == foo assert py.path.local() == foo
class TestSysModulesSnapshot(object): class TestSysModulesSnapshot:
key = "my-test-module" key = "my-test-module"
def test_remove_added(self): def test_remove_added(self):
@ -366,7 +366,7 @@ class TestSysModulesSnapshot(object):
@pytest.mark.parametrize("path_type", ("path", "meta_path")) @pytest.mark.parametrize("path_type", ("path", "meta_path"))
class TestSysPathsSnapshot(object): class TestSysPathsSnapshot:
other_path = {"path": "meta_path", "meta_path": "path"} other_path = {"path": "meta_path", "meta_path": "path"}
@staticmethod @staticmethod
@ -417,7 +417,7 @@ def test_testdir_subprocess(testdir):
def test_unicode_args(testdir): def test_unicode_args(testdir):
result = testdir.runpytest("-k", u"💩") result = testdir.runpytest("-k", "💩")
assert result.ret == EXIT_NOTESTSCOLLECTED assert result.ret == EXIT_NOTESTSCOLLECTED

View File

@ -26,7 +26,7 @@ def test_recwarn_functional(testdir):
reprec.assertoutcome(passed=1) reprec.assertoutcome(passed=1)
class TestWarningsRecorderChecker(object): class TestWarningsRecorderChecker:
def test_recording(self): def test_recording(self):
rec = WarningsRecorder() rec = WarningsRecorder()
with rec: with rec:
@ -73,7 +73,7 @@ class TestWarningsRecorderChecker(object):
pass # can't enter twice pass # can't enter twice
class TestDeprecatedCall(object): class TestDeprecatedCall:
"""test pytest.deprecated_call()""" """test pytest.deprecated_call()"""
def dep(self, i, j=None): def dep(self, i, j=None):
@ -205,7 +205,7 @@ class TestDeprecatedCall(object):
warnings.warn("this is not here", DeprecationWarning) warnings.warn("this is not here", DeprecationWarning)
class TestWarns(object): class TestWarns:
def test_strings(self): def test_strings(self):
# different messages, b/c Python suppresses multiple identical warnings # different messages, b/c Python suppresses multiple identical warnings
source1 = "warnings.warn('w1', RuntimeWarning)" source1 = "warnings.warn('w1', RuntimeWarning)"

View File

@ -4,7 +4,7 @@ from _pytest.reports import CollectReport
from _pytest.reports import TestReport from _pytest.reports import TestReport
class TestReportSerialization(object): class TestReportSerialization:
def test_xdist_longrepr_to_str_issue_241(self, testdir): def test_xdist_longrepr_to_str_issue_241(self, testdir):
""" """
Regarding issue pytest-xdist#241 Regarding issue pytest-xdist#241
@ -43,7 +43,7 @@ class TestReportSerialization(object):
reports = reprec.getreports("pytest_runtest_logreport") reports = reprec.getreports("pytest_runtest_logreport")
assert len(reports) == 3 assert len(reports) == 3
rep = reports[1] rep = reports[1]
added_section = ("Failure Metadata", str("metadata metadata"), "*") added_section = ("Failure Metadata", "metadata metadata", "*")
rep.longrepr.sections.append(added_section) rep.longrepr.sections.append(added_section)
d = rep._to_json() d = rep._to_json()
a = TestReport._from_json(d) a = TestReport._from_json(d)

View File

@ -50,7 +50,7 @@ def test_write_log_entry():
assert entry_lines[1:] == [" " + line for line in longrepr.splitlines()] assert entry_lines[1:] == [" " + line for line in longrepr.splitlines()]
class TestWithFunctionIntegration(object): class TestWithFunctionIntegration:
# XXX (hpk) i think that the resultlog plugin should # XXX (hpk) i think that the resultlog plugin should
# provide a Parser object so that one can remain # provide a Parser object so that one can remain
# ignorant regarding formatting details. # ignorant regarding formatting details.

View File

@ -13,7 +13,7 @@ from _pytest import reports
from _pytest import runner from _pytest import runner
class TestSetupState(object): class TestSetupState:
def test_setup(self, testdir): def test_setup(self, testdir):
ss = runner.SetupState() ss = runner.SetupState()
item = testdir.getitem("def test_func(): pass") item = testdir.getitem("def test_func(): pass")
@ -101,7 +101,7 @@ class TestSetupState(object):
assert module_teardown assert module_teardown
class BaseFunctionalTests(object): class BaseFunctionalTests:
def test_passfunction(self, testdir): def test_passfunction(self, testdir):
reports = testdir.runitem( reports = testdir.runitem(
""" """
@ -436,7 +436,7 @@ class TestExecutionForked(BaseFunctionalTests):
assert rep.when == "???" assert rep.when == "???"
class TestSessionReports(object): class TestSessionReports:
def test_collect_result(self, testdir): def test_collect_result(self, testdir):
col = testdir.getmodulecol( col = testdir.getmodulecol(
""" """
@ -639,7 +639,7 @@ def test_pytest_fail_notrace_non_ascii(testdir, str_prefix):
This tests with native and unicode strings containing non-ascii chars. This tests with native and unicode strings containing non-ascii chars.
""" """
testdir.makepyfile( testdir.makepyfile(
u""" """
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import pytest import pytest
@ -868,7 +868,7 @@ def test_store_except_info_on_error():
sys.last_traceback and friends. sys.last_traceback and friends.
""" """
# Simulate item that might raise a specific exception, depending on `raise_error` class var # Simulate item that might raise a specific exception, depending on `raise_error` class var
class ItemMightRaise(object): class ItemMightRaise:
nodeid = "item_that_raises" nodeid = "item_that_raises"
raise_error = True raise_error = True
@ -925,7 +925,7 @@ def test_current_test_env_var(testdir, monkeypatch):
assert "PYTEST_CURRENT_TEST" not in os.environ assert "PYTEST_CURRENT_TEST" not in os.environ
class TestReportContents(object): class TestReportContents:
""" """
Test user-level API of ``TestReport`` objects. Test user-level API of ``TestReport`` objects.
""" """

View File

@ -2,7 +2,7 @@ import pytest
from _pytest.main import EXIT_NOTESTSCOLLECTED from _pytest.main import EXIT_NOTESTSCOLLECTED
class SessionTests(object): class SessionTests:
def test_basic_testitem_events(self, testdir): def test_basic_testitem_events(self, testdir):
tfile = testdir.makepyfile( tfile = testdir.makepyfile(
""" """
@ -71,7 +71,7 @@ class SessionTests(object):
values = reprec.getfailedcollections() values = reprec.getfailedcollections()
assert len(values) == 1 assert len(values) == 1
out = str(values[0].longrepr) out = str(values[0].longrepr)
assert out.find(str("not python")) != -1 assert out.find("not python") != -1
def test_exit_first_problem(self, testdir): def test_exit_first_problem(self, testdir):
reprec = testdir.inline_runsource( reprec = testdir.inline_runsource(

View File

@ -6,7 +6,7 @@ from _pytest.skipping import MarkEvaluator
from _pytest.skipping import pytest_runtest_setup from _pytest.skipping import pytest_runtest_setup
class TestEvaluator(object): class TestEvaluator:
def test_no_marker(self, testdir): def test_no_marker(self, testdir):
item = testdir.getitem("def test_func(): pass") item = testdir.getitem("def test_func(): pass")
evalskipif = MarkEvaluator(item, "skipif") evalskipif = MarkEvaluator(item, "skipif")
@ -131,7 +131,7 @@ class TestEvaluator(object):
assert expl == "condition: config._hackxyz" assert expl == "condition: config._hackxyz"
class TestXFail(object): class TestXFail:
@pytest.mark.parametrize("strict", [True, False]) @pytest.mark.parametrize("strict", [True, False])
def test_xfail_simple(self, testdir, strict): def test_xfail_simple(self, testdir, strict):
item = testdir.getitem( item = testdir.getitem(
@ -498,7 +498,7 @@ class TestXFail(object):
assert result.ret == (1 if strict else 0) assert result.ret == (1 if strict else 0)
class TestXFailwithSetupTeardown(object): class TestXFailwithSetupTeardown:
def test_failing_setup_issue9(self, testdir): def test_failing_setup_issue9(self, testdir):
testdir.makepyfile( testdir.makepyfile(
""" """
@ -530,7 +530,7 @@ class TestXFailwithSetupTeardown(object):
result.stdout.fnmatch_lines(["*1 xfail*"]) result.stdout.fnmatch_lines(["*1 xfail*"])
class TestSkip(object): class TestSkip:
def test_skip_class(self, testdir): def test_skip_class(self, testdir):
testdir.makepyfile( testdir.makepyfile(
""" """
@ -627,7 +627,7 @@ class TestSkip(object):
result.stdout.fnmatch_lines(["*unconditional skip*", "*1 skipped*"]) result.stdout.fnmatch_lines(["*unconditional skip*", "*1 skipped*"])
class TestSkipif(object): class TestSkipif:
def test_skipif_conditional(self, testdir): def test_skipif_conditional(self, testdir):
item = testdir.getitem( item = testdir.getitem(
""" """
@ -982,7 +982,7 @@ def test_imperativeskip_on_xfail_test(testdir):
) )
class TestBooleanCondition(object): class TestBooleanCondition:
def test_skipif(self, testdir): def test_skipif(self, testdir):
testdir.makepyfile( testdir.makepyfile(
""" """

View File

@ -22,7 +22,7 @@ from _pytest.terminal import TerminalReporter
DistInfo = collections.namedtuple("DistInfo", ["project_name", "version"]) DistInfo = collections.namedtuple("DistInfo", ["project_name", "version"])
class Option(object): class Option:
def __init__(self, verbosity=0, fulltrace=False): def __init__(self, verbosity=0, fulltrace=False):
self.verbosity = verbosity self.verbosity = verbosity
self.fulltrace = fulltrace self.fulltrace = fulltrace
@ -70,7 +70,7 @@ def test_plugin_nameversion(input, expected):
assert result == expected assert result == expected
class TestTerminal(object): class TestTerminal:
def test_pass_skip_fail(self, testdir, option): def test_pass_skip_fail(self, testdir, option):
testdir.makepyfile( testdir.makepyfile(
""" """
@ -277,7 +277,7 @@ class TestTerminal(object):
assert f.getvalue() == "hello" + "\r" + "hey" + (6 * " ") assert f.getvalue() == "hello" + "\r" + "hey" + (6 * " ")
class TestCollectonly(object): class TestCollectonly:
def test_collectonly_basic(self, testdir): def test_collectonly_basic(self, testdir):
testdir.makepyfile( testdir.makepyfile(
""" """
@ -385,7 +385,7 @@ class TestCollectonly(object):
result.stdout.fnmatch_lines(["*test_fun.py: 1*"]) result.stdout.fnmatch_lines(["*test_fun.py: 1*"])
class TestFixtureReporting(object): class TestFixtureReporting:
def test_setup_fixture_error(self, testdir): def test_setup_fixture_error(self, testdir):
testdir.makepyfile( testdir.makepyfile(
""" """
@ -485,7 +485,7 @@ class TestFixtureReporting(object):
) )
class TestTerminalFunctional(object): class TestTerminalFunctional:
def test_deselected(self, testdir): def test_deselected(self, testdir):
testpath = testdir.makepyfile( testpath = testdir.makepyfile(
""" """
@ -858,8 +858,8 @@ def test_color_yes_collection_on_non_atty(testdir, verbose):
def test_getreportopt(): def test_getreportopt():
class Config(object): class Config:
class Option(object): class Option:
reportchars = "" reportchars = ""
disable_warnings = True disable_warnings = True
@ -940,7 +940,7 @@ def test_traceconfig(testdir, monkeypatch):
assert result.ret == EXIT_NOTESTSCOLLECTED assert result.ret == EXIT_NOTESTSCOLLECTED
class TestGenericReporting(object): class TestGenericReporting:
""" this test class can be subclassed with a different option """ this test class can be subclassed with a different option
provider to run e.g. distributed tests. provider to run e.g. distributed tests.
""" """
@ -1320,7 +1320,7 @@ def test_skip_counting_towards_summary():
assert res == ("1 failed", "red") assert res == ("1 failed", "red")
class TestClassicOutputStyle(object): class TestClassicOutputStyle:
"""Ensure classic output style works as expected (#3883)""" """Ensure classic output style works as expected (#3883)"""
@pytest.fixture @pytest.fixture
@ -1366,7 +1366,7 @@ class TestClassicOutputStyle(object):
result.stdout.fnmatch_lines([".F.F.", "*2 failed, 3 passed in*"]) result.stdout.fnmatch_lines([".F.F.", "*2 failed, 3 passed in*"])
class TestProgressOutputStyle(object): class TestProgressOutputStyle:
@pytest.fixture @pytest.fixture
def many_tests_files(self, testdir): def many_tests_files(self, testdir):
testdir.makepyfile( testdir.makepyfile(
@ -1497,7 +1497,7 @@ class TestProgressOutputStyle(object):
assert "%]" not in output.stdout.str() assert "%]" not in output.stdout.str()
class TestProgressWithTeardown(object): class TestProgressWithTeardown:
"""Ensure we show the correct percentages for tests that fail during teardown (#3088)""" """Ensure we show the correct percentages for tests that fail during teardown (#3088)"""
@pytest.fixture @pytest.fixture
@ -1584,7 +1584,7 @@ def test_skip_reasons_folding():
message = "justso" message = "justso"
longrepr = (path, lineno, message) longrepr = (path, lineno, message)
class X(object): class X:
pass pass
ev1 = X() ev1 = X()
@ -1625,10 +1625,10 @@ def test_line_with_reprcrash(monkeypatch):
monkeypatch.setattr(_pytest.terminal, "_get_pos", mock_get_pos) monkeypatch.setattr(_pytest.terminal, "_get_pos", mock_get_pos)
class config(object): class config:
pass pass
class rep(object): class rep:
def _get_verbose_word(self, *args): def _get_verbose_word(self, *args):
return mocked_verbose_word return mocked_verbose_word
@ -1643,7 +1643,7 @@ def test_line_with_reprcrash(monkeypatch):
actual = _get_line_with_reprcrash_message(config, rep(), width) actual = _get_line_with_reprcrash_message(config, rep(), width)
assert actual == expected assert actual == expected
if actual != "%s %s" % (mocked_verbose_word, mocked_pos): if actual != "{} {}".format(mocked_verbose_word, mocked_pos):
assert len(actual) <= width assert len(actual) <= width
assert wcswidth(actual) <= width assert wcswidth(actual) <= width
@ -1665,17 +1665,17 @@ def test_line_with_reprcrash(monkeypatch):
check("some\nmessage", 80, "FAILED some::nodeid - some") check("some\nmessage", 80, "FAILED some::nodeid - some")
# Test unicode safety. # Test unicode safety.
check(u"😄😄😄😄😄\n2nd line", 25, u"FAILED some::nodeid - ...") check("😄😄😄😄😄\n2nd line", 25, "FAILED some::nodeid - ...")
check(u"😄😄😄😄😄\n2nd line", 26, u"FAILED some::nodeid - ...") check("😄😄😄😄😄\n2nd line", 26, "FAILED some::nodeid - ...")
check(u"😄😄😄😄😄\n2nd line", 27, u"FAILED some::nodeid - 😄...") check("😄😄😄😄😄\n2nd line", 27, "FAILED some::nodeid - 😄...")
check(u"😄😄😄😄😄\n2nd line", 28, u"FAILED some::nodeid - 😄...") check("😄😄😄😄😄\n2nd line", 28, "FAILED some::nodeid - 😄...")
check(u"😄😄😄😄😄\n2nd line", 29, u"FAILED some::nodeid - 😄😄...") check("😄😄😄😄😄\n2nd line", 29, "FAILED some::nodeid - 😄😄...")
# NOTE: constructed, not sure if this is supported. # NOTE: constructed, not sure if this is supported.
# It would fail if not using u"" in Python 2 for mocked_pos. # It would fail if not using u"" in Python 2 for mocked_pos.
mocked_pos = u"nodeid::😄::withunicode" mocked_pos = "nodeid::😄::withunicode"
check(u"😄😄😄😄😄\n2nd line", 29, u"FAILED nodeid::😄::withunicode") check("😄😄😄😄😄\n2nd line", 29, "FAILED nodeid::😄::withunicode")
check(u"😄😄😄😄😄\n2nd line", 40, u"FAILED nodeid::😄::withunicode - 😄😄...") check("😄😄😄😄😄\n2nd line", 40, "FAILED nodeid::😄::withunicode - 😄😄...")
check(u"😄😄😄😄😄\n2nd line", 41, u"FAILED nodeid::😄::withunicode - 😄😄...") check("😄😄😄😄😄\n2nd line", 41, "FAILED nodeid::😄::withunicode - 😄😄...")
check(u"😄😄😄😄😄\n2nd line", 42, u"FAILED nodeid::😄::withunicode - 😄😄😄...") check("😄😄😄😄😄\n2nd line", 42, "FAILED nodeid::😄::withunicode - 😄😄😄...")
check(u"😄😄😄😄😄\n2nd line", 80, u"FAILED nodeid::😄::withunicode - 😄😄😄😄😄") check("😄😄😄😄😄\n2nd line", 80, "FAILED nodeid::😄::withunicode - 😄😄😄😄😄")

View File

@ -22,7 +22,7 @@ def test_ensuretemp(recwarn):
@attr.s @attr.s
class FakeConfig(object): class FakeConfig:
basetemp = attr.ib() basetemp = attr.ib()
trace = attr.ib(default=None) trace = attr.ib(default=None)
@ -38,7 +38,7 @@ class FakeConfig(object):
return self return self
class TestTempdirHandler(object): class TestTempdirHandler:
def test_mktemp(self, tmp_path): def test_mktemp(self, tmp_path):
from _pytest.tmpdir import TempdirFactory, TempPathFactory from _pytest.tmpdir import TempdirFactory, TempPathFactory
@ -63,7 +63,7 @@ class TestTempdirHandler(object):
assert t.getbasetemp().resolve() == (tmp_path / "hello").resolve() assert t.getbasetemp().resolve() == (tmp_path / "hello").resolve()
class TestConfigTmpdir(object): class TestConfigTmpdir:
def test_getbasetemp_custom_removes_old(self, testdir): def test_getbasetemp_custom_removes_old(self, testdir):
mytemp = testdir.tmpdir.join("xyz") mytemp = testdir.tmpdir.join("xyz")
p = testdir.makepyfile( p = testdir.makepyfile(
@ -228,7 +228,7 @@ def test_get_user(monkeypatch):
assert get_user() is None assert get_user() is None
class TestNumberedDir(object): class TestNumberedDir:
PREFIX = "fun-" PREFIX = "fun-"
def test_make(self, tmp_path): def test_make(self, tmp_path):

View File

@ -388,7 +388,7 @@ def test_module_level_pytestmark(testdir):
reprec.assertoutcome(skipped=1) reprec.assertoutcome(skipped=1)
class TestTrialUnittest(object): class TestTrialUnittest:
def setup_class(cls): def setup_class(cls):
cls.ut = pytest.importorskip("twisted.trial.unittest") cls.ut = pytest.importorskip("twisted.trial.unittest")
# on windows trial uses a socket for a reactor and apparently doesn't close it properly # on windows trial uses a socket for a reactor and apparently doesn't close it properly

View File

@ -493,7 +493,7 @@ class TestDeprecationWarningsByDefault:
def test_hidden_by_system(self, testdir, monkeypatch): def test_hidden_by_system(self, testdir, monkeypatch):
self.create_file(testdir) self.create_file(testdir)
monkeypatch.setenv(str("PYTHONWARNINGS"), str("once::UserWarning")) monkeypatch.setenv("PYTHONWARNINGS", "once::UserWarning")
result = testdir.runpytest_subprocess() result = testdir.runpytest_subprocess()
assert WARNINGS_SUMMARY_HEADER not in result.stdout.str() assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()