Skip to content

Commit

Permalink
Upgrade Python syntax for 3.6+
Browse files Browse the repository at this point in the history
Co-authored-by: nulano <[email protected]>
  • Loading branch information
hugovk and nulano committed Jul 30, 2020
1 parent e42aec8 commit 10615a7
Show file tree
Hide file tree
Showing 69 changed files with 323 additions and 363 deletions.
10 changes: 6 additions & 4 deletions Tests/bench_cffi_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,17 @@ def timer(func, label, *args):
func(*args)
if time.time() - starttime > 10:
print(
"%s: breaking at %s iterations, %.6f per iteration"
% (label, x + 1, (time.time() - starttime) / (x + 1.0))
"{}: breaking at {} iterations, {:.6f} per iteration".format(
label, x + 1, (time.time() - starttime) / (x + 1.0)
)
)
break
if x == iterations - 1:
endtime = time.time()
print(
"%s: %.4f s %.6f per iteration"
% (label, endtime - starttime, (endtime - starttime) / (x + 1.0))
"{}: {:.4f} s {:.6f} per iteration".format(
label, endtime - starttime, (endtime - starttime) / (x + 1.0)
)
)


Expand Down
2 changes: 1 addition & 1 deletion Tests/check_imaging_leaks.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def _test_leak(min_iterations, max_iterations, fn, *args, **kwargs):
if i < min_iterations:
mem_limit = mem + 1
continue
msg = "memory usage limit exceeded after %d iterations" % (i + 1)
msg = f"memory usage limit exceeded after {i + 1} iterations"
assert mem <= mem_limit, msg


Expand Down
4 changes: 2 additions & 2 deletions Tests/check_png_dos.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ def test_dos_total_memory():
info = PngImagePlugin.PngInfo()

for x in range(64):
info.add_text("t%s" % x, compressed_data, zip=True)
info.add_itxt("i%s" % x, compressed_data, zip=True)
info.add_text(f"t{x}", compressed_data, zip=True)
info.add_itxt(f"i{x}", compressed_data, zip=True)

b = BytesIO()
im.save(b, "PNG", pnginfo=info)
Expand Down
2 changes: 1 addition & 1 deletion Tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ def pytest_report_header(config):
features.pilinfo(out=out, supported_formats=False)
return out.getvalue()
except Exception as e:
return "pytest_report_header failed: %s" % e
return f"pytest_report_header failed: {e}"
2 changes: 1 addition & 1 deletion Tests/createfontdatachunk.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
# create font data chunk for embedding
font = "Tests/images/courB08"
print(" f._load_pilfont_data(")
print(" # %s" % os.path.basename(font))
print(f" # {os.path.basename(font)}")
print(" BytesIO(base64.decodestring(b'''")
with open(font + ".pil", "rb") as fp:
print(base64.b64encode(fp.read()).decode())
Expand Down
41 changes: 16 additions & 25 deletions Tests/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,37 +67,31 @@ def convert_to_comparable(a, b):

def assert_deep_equal(a, b, msg=None):
try:
assert len(a) == len(b), msg or "got length {}, expected {}".format(
len(a), len(b)
)
assert len(a) == len(b), msg or f"got length {len(a)}, expected {len(b)}"
except Exception:
assert a == b, msg


def assert_image(im, mode, size, msg=None):
if mode is not None:
assert im.mode == mode, msg or "got mode {!r}, expected {!r}".format(
im.mode, mode
assert im.mode == mode, (
msg or f"got mode {repr(im.mode)}, expected {repr(mode)}"
)

if size is not None:
assert im.size == size, msg or "got size {!r}, expected {!r}".format(
im.size, size
assert im.size == size, (
msg or f"got size {repr(im.size)}, expected {repr(size)}"
)


def assert_image_equal(a, b, msg=None):
assert a.mode == b.mode, msg or "got mode {!r}, expected {!r}".format(
a.mode, b.mode
)
assert a.size == b.size, msg or "got size {!r}, expected {!r}".format(
a.size, b.size
)
assert a.mode == b.mode, msg or f"got mode {repr(a.mode)}, expected {repr(b.mode)}"
assert a.size == b.size, msg or f"got size {repr(a.size)}, expected {repr(b.size)}"
if a.tobytes() != b.tobytes():
if HAS_UPLOADER:
try:
url = test_image_results.upload(a, b)
logger.error("Url for test images: %s" % url)
logger.error(f"Url for test images: {url}")
except Exception:
pass

Expand All @@ -112,12 +106,8 @@ def assert_image_equal_tofile(a, filename, msg=None, mode=None):


def assert_image_similar(a, b, epsilon, msg=None):
assert a.mode == b.mode, msg or "got mode {!r}, expected {!r}".format(
a.mode, b.mode
)
assert a.size == b.size, msg or "got size {!r}, expected {!r}".format(
a.size, b.size
)
assert a.mode == b.mode, msg or f"got mode {repr(a.mode)}, expected {repr(b.mode)}"
assert a.size == b.size, msg or f"got size {repr(a.size)}, expected {repr(b.size)}"

a, b = convert_to_comparable(a, b)

Expand All @@ -129,13 +119,14 @@ def assert_image_similar(a, b, epsilon, msg=None):
ave_diff = diff / (a.size[0] * a.size[1])
try:
assert epsilon >= ave_diff, (
msg or ""
) + " average pixel value difference %.4f > epsilon %.4f" % (ave_diff, epsilon)
(msg or "")
+ f" average pixel value difference {ave_diff:.4f} > epsilon {epsilon:.4f}"
)
except Exception as e:
if HAS_UPLOADER:
try:
url = test_image_results.upload(a, b)
logger.error("Url for test images: %s" % url)
logger.error(f"Url for test images: {url}")
except Exception:
pass
raise e
Expand Down Expand Up @@ -166,7 +157,7 @@ def assert_tuple_approx_equal(actuals, targets, threshold, msg):


def skip_unless_feature(feature):
reason = "%s not available" % feature
reason = f"{feature} not available"
return pytest.mark.skipif(not features.check(feature), reason=reason)


Expand Down Expand Up @@ -204,7 +195,7 @@ def _test_leak(self, core):
for cycle in range(self.iterations):
core()
mem = self._get_mem_usage() - start_mem
msg = "memory usage limit exceeded in iteration %d" % cycle
msg = f"memory usage limit exceeded in iteration {cycle}"
assert mem < self.mem_limit, msg


Expand Down
6 changes: 3 additions & 3 deletions Tests/test_bmp_reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def test_questionable():
with Image.open(f) as im:
im.load()
if os.path.basename(f) not in supported:
print("Please add %s to the partially supported bmp specs." % f)
print(f"Please add {f} to the partially supported bmp specs.")
except Exception: # as msg:
if os.path.basename(f) in supported:
raise
Expand Down Expand Up @@ -84,7 +84,7 @@ def get_compare(f):
if name in file_map:
return os.path.join(base, "html", file_map[name])
name = os.path.splitext(name)[0]
return os.path.join(base, "html", "%s.png" % name)
return os.path.join(base, "html", f"{name}.png")

for f in get_files("g"):
try:
Expand All @@ -107,4 +107,4 @@ def get_compare(f):
os.path.join(base, "g", "pal8rle.bmp"),
os.path.join(base, "g", "pal4rle.bmp"),
)
assert f in unsupported, "Unsupported Image {}: {}".format(f, msg)
assert f in unsupported, f"Unsupported Image {f}: {msg}"
2 changes: 1 addition & 1 deletion Tests/test_file_apng.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def test_apng_sequence_errors():
]
for f in test_files:
with pytest.raises(SyntaxError):
with Image.open("Tests/images/apng/{0}".format(f)) as im:
with Image.open(f"Tests/images/apng/{f}") as im:
im.seek(im.n_frames - 1)
im.load()

Expand Down
12 changes: 6 additions & 6 deletions Tests/test_file_libtiff.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,18 +173,18 @@ def test_write_metadata(self, tmp_path):
assert (
c_float(val[0][0] / val[0][1]).value
== c_float(value[0][0] / value[0][1]).value
), ("%s didn't roundtrip" % tag)
), f"{tag} didn't roundtrip"
else:
assert c_float(val).value == c_float(value).value, (
"%s didn't roundtrip" % tag
)
assert (
c_float(val).value == c_float(value).value
), f"{tag} didn't roundtrip"
else:
assert val == value, "%s didn't roundtrip" % tag
assert val == value, f"{tag} didn't roundtrip"

# https://github.com/python-pillow/Pillow/issues/1561
requested_fields = ["StripByteCounts", "RowsPerStrip", "StripOffsets"]
for field in requested_fields:
assert field in reloaded, "%s not in metadata" % field
assert field in reloaded, f"{field} not in metadata"

def test_additional_metadata(self, tmp_path):
# these should not crash. Seriously dummy data, most of it doesn't make
Expand Down
2 changes: 1 addition & 1 deletion Tests/test_file_sun.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def test_others():
with Image.open(path) as im:
im.load()
assert isinstance(im, SunImagePlugin.SunImageFile)
target_path = "%s.png" % os.path.splitext(path)[0]
target_path = f"{os.path.splitext(path)[0]}.png"
# im.save(target_file)
with Image.open(target_path) as target:
assert_image_equal(im, target)
4 changes: 1 addition & 3 deletions Tests/test_file_tga.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,7 @@ def roundtrip(original_im):

assert_image_equal(saved_im, original_im)

png_paths = glob(
os.path.join(_TGA_DIR_COMMON, "*x*_{}.png".format(mode.lower()))
)
png_paths = glob(os.path.join(_TGA_DIR_COMMON, f"*x*_{mode.lower()}.png"))

for png_path in png_paths:
with Image.open(png_path) as reference_im:
Expand Down
10 changes: 5 additions & 5 deletions Tests/test_file_tiff_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,16 +144,16 @@ def test_write_metadata(tmp_path):
assert_deep_equal(
original[tag],
value,
"{} didn't roundtrip, {}, {}".format(tag, original[tag], value),
f"{tag} didn't roundtrip, {original[tag]}, {value}",
)
else:
assert original[tag] == value, "{} didn't roundtrip, {}, {}".format(
tag, original[tag], value
)
assert (
original[tag] == value
), f"{tag} didn't roundtrip, {original[tag]}, {value}"

for tag, value in original.items():
if tag not in ignored:
assert value == reloaded[tag], "%s didn't roundtrip" % tag
assert value == reloaded[tag], f"{tag} didn't roundtrip"


def test_change_stripbytecounts_tag_type(tmp_path):
Expand Down
4 changes: 2 additions & 2 deletions Tests/test_font_pcf_charsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ def delete_tempfile():
font.save(tempname)

with Image.open(tempname.replace(".pil", ".pbm")) as loaded:
with Image.open("Tests/fonts/ter-x20b-%s.pbm" % encoding) as target:
with Image.open(f"Tests/fonts/ter-x20b-{encoding}.pbm") as target:
assert_image_equal(loaded, target)

with open(tempname, "rb") as f_loaded:
with open("Tests/fonts/ter-x20b-%s.pil" % encoding, "rb") as f_target:
with open(f"Tests/fonts/ter-x20b-{encoding}.pil", "rb") as f_target:
assert f_loaded.read() == f_target.read()
return tempname

Expand Down
13 changes: 6 additions & 7 deletions Tests/test_image_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,14 +125,13 @@ def check(self, mode, c=None):
im.putpixel((0, 0), c)
assert (
im.getpixel((0, 0)) == c
), "put/getpixel roundtrip failed for mode {}, color {}".format(mode, c)
), f"put/getpixel roundtrip failed for mode {mode}, color {c}"

# check putpixel negative index
im.putpixel((-1, -1), c)
assert im.getpixel((-1, -1)) == c, (
"put/getpixel roundtrip negative index failed for mode %s, color %s"
% (mode, c)
)
assert (
im.getpixel((-1, -1)) == c
), f"put/getpixel roundtrip negative index failed for mode {mode}, color {c}"

# Check 0
im = Image.new(mode, (0, 0), None)
Expand All @@ -150,11 +149,11 @@ def check(self, mode, c=None):
im = Image.new(mode, (1, 1), c)
assert (
im.getpixel((0, 0)) == c
), "initial color failed for mode {}, color {} ".format(mode, c)
), f"initial color failed for mode {mode}, color {c} "
# check initial color negative index
assert (
im.getpixel((-1, -1)) == c
), "initial color failed with negative index for mode %s, color %s " % (mode, c)
), f"initial color failed with negative index for mode {mode}, color {c} "

# Check 0
im = Image.new(mode, (0, 0), c)
Expand Down
15 changes: 7 additions & 8 deletions Tests/test_image_reduce.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,8 @@ def compare_reduce_with_reference(im, factor, average_diff=0.4, max_diff=1):


def assert_compare_images(a, b, max_average_diff, max_diff=255):
assert a.mode == b.mode, "got mode %r, expected %r" % (a.mode, b.mode)
assert a.size == b.size, "got size %r, expected %r" % (a.size, b.size)
assert a.mode == b.mode, f"got mode {repr(a.mode)}, expected {repr(b.mode)}"
assert a.size == b.size, f"got size {repr(a.size)}, expected {repr(b.size)}"

a, b = convert_to_comparable(a, b)

Expand All @@ -175,16 +175,15 @@ def assert_compare_images(a, b, max_average_diff, max_diff=255):
a.size[0] * a.size[1]
)
msg = (
"average pixel value difference {:.4f} > expected {:.4f} "
"for '{}' band".format(average_diff, max_average_diff, band)
f"average pixel value difference {average_diff:.4f} > "
f"expected {max_average_diff:.4f} for '{band}' band"
)
assert max_average_diff >= average_diff, msg

last_diff = [i for i, num in enumerate(ch_hist) if num > 0][-1]
assert (
max_diff >= last_diff
), "max pixel value difference {} > expected {} for '{}' band".format(
last_diff, max_diff, band
assert max_diff >= last_diff, (
f"max pixel value difference {last_diff} > expected {max_diff} "
f"for '{band}' band"
)


Expand Down
Loading

0 comments on commit 10615a7

Please sign in to comment.