Merge pull request #3859 from asottile/pyupgrade_1_4

Some pyupgrade 1.4.x changes
This commit is contained in:
Anthony Sottile 2018-08-23 18:32:53 -07:00 committed by GitHub
commit f2e35c8c4f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 51 additions and 44 deletions

View File

@ -10,4 +10,4 @@ def pytest_runtest_setup(item):
return
mod = item.getparent(pytest.Module).obj
if hasattr(mod, "hello"):
print("mod.hello %r" % (mod.hello,))
print("mod.hello {!r}".format(mod.hello))

View File

@ -2,9 +2,10 @@
module containing a parametrized tests testing cross-python
serialization via the pickle module.
"""
import textwrap
import py
import pytest
import _pytest._code
pythonlist = ["python2.7", "python3.4", "python3.5"]
@ -24,42 +25,44 @@ class Python(object):
def __init__(self, version, picklefile):
self.pythonpath = py.path.local.sysfind(version)
if not self.pythonpath:
pytest.skip("%r not found" % (version,))
pytest.skip("{!r} not found".format(version))
self.picklefile = picklefile
def dumps(self, obj):
dumpfile = self.picklefile.dirpath("dump.py")
dumpfile.write(
_pytest._code.Source(
"""
import pickle
f = open(%r, 'wb')
s = pickle.dump(%r, f, protocol=2)
f.close()
"""
% (str(self.picklefile), obj)
textwrap.dedent(
"""\
import pickle
f = open({!r}, 'wb')
s = pickle.dump({!r}, f, protocol=2)
f.close()
""".format(
str(self.picklefile), obj
)
)
)
py.process.cmdexec("%s %s" % (self.pythonpath, dumpfile))
py.process.cmdexec("{} {}".format(self.pythonpath, dumpfile))
def load_and_is_true(self, expression):
loadfile = self.picklefile.dirpath("load.py")
loadfile.write(
_pytest._code.Source(
"""
import pickle
f = open(%r, 'rb')
obj = pickle.load(f)
f.close()
res = eval(%r)
if not res:
raise SystemExit(1)
"""
% (str(self.picklefile), expression)
textwrap.dedent(
"""\
import pickle
f = open({!r}, 'rb')
obj = pickle.load(f)
f.close()
res = eval({!r})
if not res:
raise SystemExit(1)
""".format(
str(self.picklefile), expression
)
)
)
print(loadfile)
py.process.cmdexec("%s %s" % (self.pythonpath, loadfile))
py.process.cmdexec("{} {}".format(self.pythonpath, loadfile))
@pytest.mark.parametrize("obj", [42, {}, {1: 3}])

View File

@ -2,7 +2,7 @@
# CHANGES:
# - some_str is replaced, trying to create unicode strings
#
from __future__ import absolute_import, division, print_function
from __future__ import absolute_import, division, print_function, unicode_literals
import types
from six import text_type
@ -51,17 +51,17 @@ def format_exception_only(etype, value):
pass
else:
filename = filename or "<string>"
lines.append(' File "%s", line %d\n' % (filename, lineno))
lines.append(' File "{}", line {}\n'.format(filename, lineno))
if badline is not None:
if isinstance(badline, bytes): # python 2 only
badline = badline.decode("utf-8", "replace")
lines.append(u" %s\n" % badline.strip())
lines.append(" {}\n".format(badline.strip()))
if offset is not None:
caretspace = badline.rstrip("\n")[:offset].lstrip()
# non-space whitespace (likes tabs) must be kept for alignment
caretspace = ((c.isspace() and c or " ") for c in caretspace)
# only three spaces to account for offset1 == pos 0
lines.append(" %s^\n" % "".join(caretspace))
lines.append(" {}^\n".format("".join(caretspace)))
value = msg
lines.append(_format_final_exc_line(stype, value))
@ -72,9 +72,9 @@ def _format_final_exc_line(etype, value):
"""Return a list of a single line -- normal case for format_exception_only"""
valuestr = _some_str(value)
if value is None or not valuestr:
line = "%s\n" % etype
line = "{}\n".format(etype)
else:
line = "%s: %s\n" % (etype, valuestr)
line = "{}: {}\n".format(etype, valuestr)
return line
@ -83,7 +83,7 @@ def _some_str(value):
return text_type(value)
except Exception:
try:
return str(value)
return bytes(value).decode("UTF-8", "replace")
except Exception:
pass
return "<unprintable %s object>" % type(value).__name__
return "<unprintable {} object>".format(type(value).__name__)

View File

@ -131,7 +131,7 @@ class TestGeneralUsage(object):
p2 = testdir.makefile(".pyc", "123")
result = testdir.runpytest(p1, p2)
assert result.ret
result.stderr.fnmatch_lines(["*ERROR: not found:*%s" % (p2.basename,)])
result.stderr.fnmatch_lines(["*ERROR: not found:*{}".format(p2.basename)])
def test_issue486_better_reporting_on_conftest_load_failure(self, testdir):
testdir.makepyfile("")
@ -453,7 +453,7 @@ class TestInvocationVariants(object):
@pytest.mark.xfail("sys.platform.startswith('java')")
def test_pydoc(self, testdir):
for name in ("py.test", "pytest"):
result = testdir.runpython_c("import %s;help(%s)" % (name, name))
result = testdir.runpython_c("import {};help({})".format(name, name))
assert result.ret == 0
s = result.stdout.str()
assert "MarkGenerator" in s
@ -836,7 +836,7 @@ class TestDurations(object):
if ("test_%s" % x) in line and y in line:
break
else:
raise AssertionError("not found %s %s" % (x, y))
raise AssertionError("not found {} {}".format(x, y))
def test_with_deselected(self, testdir):
testdir.makepyfile(self.source)

View File

@ -270,7 +270,7 @@ class TestTraceback_f_g_h(object):
decorator = pytest.importorskip("decorator").decorator
def log(f, *k, **kw):
print("%s %s" % (k, kw))
print("{} {}".format(k, kw))
f(*k, **kw)
log = decorator(log)

View File

@ -11,7 +11,7 @@ def equal_with_bash(prefix, ffc, fc, out=None):
res_bash = set(fc(prefix))
retval = set(res) == res_bash
if out:
out.write("equal_with_bash %s %s\n" % (retval, res))
out.write("equal_with_bash {} {}\n".format(retval, res))
if not retval:
out.write(" python - bash: %s\n" % (set(res) - res_bash))
out.write(" bash - python: %s\n" % (res_bash - set(res)))

View File

@ -561,7 +561,7 @@ class TestAssertionRewrite(object):
assert getmsg(f) == "assert 42"
def my_reprcompare(op, left, right):
return "%s %s %s" % (left, op, right)
return "{} {} {}".format(left, op, right)
monkeypatch.setattr(util, "_reprcompare", my_reprcompare)

View File

@ -7,7 +7,9 @@ def test_version(testdir, pytestconfig):
result = testdir.runpytest("--version")
assert result.ret == 0
# p = py.path.local(py.__file__).dirpath()
result.stderr.fnmatch_lines(["*pytest*%s*imported from*" % (pytest.__version__,)])
result.stderr.fnmatch_lines(
["*pytest*{}*imported from*".format(pytest.__version__)]
)
if pytestconfig.pluginmanager.list_plugin_distinfo():
result.stderr.fnmatch_lines(["*setuptools registered plugins:", "*at*"])

View File

@ -294,7 +294,7 @@ def test_argcomplete(testdir, monkeypatch):
script = str(testdir.tmpdir.join("test_argcomplete"))
pytest_bin = sys.argv[0]
if "pytest" not in os.path.basename(pytest_bin):
pytest.skip("need to be run with pytest executable, not %s" % (pytest_bin,))
pytest.skip("need to be run with pytest executable, not {}".format(pytest_bin))
with open(str(script), "w") as fp:
# redirect output from argcomplete to stdin and stderr is not trivial

View File

@ -260,7 +260,9 @@ class TestPDB(object):
assert False
"""
)
child = testdir.spawn_pytest("--show-capture=%s --pdb %s" % (showcapture, p1))
child = testdir.spawn_pytest(
"--show-capture={} --pdb {}".format(showcapture, p1)
)
if showcapture in ("all", "log"):
child.expect("captured log")
child.expect("get rekt")
@ -473,7 +475,7 @@ class TestPDB(object):
x = 5
"""
)
child = testdir.spawn("%s %s" % (sys.executable, p1))
child = testdir.spawn("{} {}".format(sys.executable, p1))
child.expect("x = 5")
child.sendeof()
self.flush(child)

View File

@ -1118,9 +1118,9 @@ def test_terminal_summary_warnings_are_displayed(testdir):
)
def test_summary_stats(exp_line, exp_color, stats_arg):
print("Based on stats: %s" % stats_arg)
print('Expect summary: "%s"; with color "%s"' % (exp_line, exp_color))
print('Expect summary: "{}"; with color "{}"'.format(exp_line, exp_color))
(line, color) = build_summary_stats_line(stats_arg)
print('Actually got: "%s"; with color "%s"' % (line, color))
print('Actually got: "{}"; with color "{}"'.format(line, color))
assert line == exp_line
assert color == exp_color