Skip to content

Commit

Permalink
Merge pull request #3859 from asottile/pyupgrade_1_4
Browse files Browse the repository at this point in the history
Some pyupgrade 1.4.x changes
  • Loading branch information
asottile authored Aug 24, 2018
2 parents d10d59c + 0d65783 commit f2e35c8
Show file tree
Hide file tree
Showing 11 changed files with 51 additions and 44 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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))
49 changes: 26 additions & 23 deletions doc/en/example/multipython.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

Expand All @@ -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}])
Expand Down
16 changes: 8 additions & 8 deletions src/_pytest/_code/_py2traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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))
Expand All @@ -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


Expand All @@ -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__)
6 changes: 3 additions & 3 deletions testing/acceptance_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def test_not_collectable_arguments(self, testdir):
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("")
Expand Down Expand Up @@ -453,7 +453,7 @@ def test_earlyinit(self, testdir):
@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
Expand Down Expand Up @@ -836,7 +836,7 @@ def test_calls_showall(self, testdir):
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)
Expand Down
2 changes: 1 addition & 1 deletion testing/code/test_excinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ def test_traceback_messy_recursion(self):
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)
Expand Down
2 changes: 1 addition & 1 deletion testing/test_argcomplete.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
Expand Down
2 changes: 1 addition & 1 deletion testing/test_assertrewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,7 @@ def f():
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)

Expand Down
4 changes: 3 additions & 1 deletion testing/test_helpconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -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*"])

Expand Down
2 changes: 1 addition & 1 deletion testing/test_parseopt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions testing/test_pdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,9 @@ def test_1():
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")
Expand Down Expand Up @@ -473,7 +475,7 @@ def test_pdb_used_outside_test(self, testdir):
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)
Expand Down
4 changes: 2 additions & 2 deletions testing/test_terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1118,9 +1118,9 @@ def pytest_terminal_summary(terminalreporter):
)
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

Expand Down

0 comments on commit f2e35c8

Please sign in to comment.