Skip to content

Commit 77711d3

Browse files
committed
Use monkeypatch
1 parent cf7dd2f commit 77711d3

File tree

10 files changed

+92
-128
lines changed

10 files changed

+92
-128
lines changed

Tests/check_png_dos.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,18 @@
88
TEST_FILE = "Tests/images/png_decompression_dos.png"
99

1010

11-
def test_ignore_dos_text() -> None:
12-
ImageFile.LOAD_TRUNCATED_IMAGES = True
11+
def test_ignore_dos_text(monkeypatch: pytest.MonkeyPatch) -> None:
12+
monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True)
1313

14-
try:
15-
im = Image.open(TEST_FILE)
14+
with Image.open(TEST_FILE) as im:
1615
im.load()
17-
finally:
18-
ImageFile.LOAD_TRUNCATED_IMAGES = False
1916

20-
assert isinstance(im, PngImagePlugin.PngImageFile)
21-
for s in im.text.values():
22-
assert len(s) < 1024 * 1024, "Text chunk larger than 1M"
17+
assert isinstance(im, PngImagePlugin.PngImageFile)
18+
for s in im.text.values():
19+
assert len(s) < 1024 * 1024, "Text chunk larger than 1M"
2320

24-
for s in im.info.values():
25-
assert len(s) < 1024 * 1024, "Text chunk larger than 1M"
21+
for s in im.info.values():
22+
assert len(s) < 1024 * 1024, "Text chunk larger than 1M"
2623

2724

2825
def test_dos_text() -> None:

Tests/test_decompression_bomb.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,16 @@
1212

1313

1414
class TestDecompressionBomb:
15-
def teardown_method(self) -> None:
16-
Image.MAX_IMAGE_PIXELS = ORIGINAL_LIMIT
17-
1815
def test_no_warning_small_file(self) -> None:
1916
# Implicit assert: no warning.
2017
# A warning would cause a failure.
2118
with Image.open(TEST_FILE):
2219
pass
2320

24-
def test_no_warning_no_limit(self) -> None:
21+
def test_no_warning_no_limit(self, monkeypatch: pytest.MonkeyPatch) -> None:
2522
# Arrange
2623
# Turn limit off
27-
Image.MAX_IMAGE_PIXELS = None
24+
monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", None)
2825
assert Image.MAX_IMAGE_PIXELS is None
2926

3027
# Act / Assert
@@ -33,18 +30,18 @@ def test_no_warning_no_limit(self) -> None:
3330
with Image.open(TEST_FILE):
3431
pass
3532

36-
def test_warning(self) -> None:
33+
def test_warning(self, monkeypatch: pytest.MonkeyPatch) -> None:
3734
# Set limit to trigger warning on the test file
38-
Image.MAX_IMAGE_PIXELS = 128 * 128 - 1
35+
monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 128 * 128 - 1)
3936
assert Image.MAX_IMAGE_PIXELS == 128 * 128 - 1
4037

4138
with pytest.warns(Image.DecompressionBombWarning):
4239
with Image.open(TEST_FILE):
4340
pass
4441

45-
def test_exception(self) -> None:
42+
def test_exception(self, monkeypatch: pytest.MonkeyPatch) -> None:
4643
# Set limit to trigger exception on the test file
47-
Image.MAX_IMAGE_PIXELS = 64 * 128 - 1
44+
monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 64 * 128 - 1)
4845
assert Image.MAX_IMAGE_PIXELS == 64 * 128 - 1
4946

5047
with pytest.raises(Image.DecompressionBombError):
@@ -66,9 +63,9 @@ def test_exception_gif_extents(self) -> None:
6663
with pytest.raises(Image.DecompressionBombError):
6764
im.seek(1)
6865

69-
def test_exception_gif_zero_width(self) -> None:
66+
def test_exception_gif_zero_width(self, monkeypatch: pytest.MonkeyPatch) -> None:
7067
# Set limit to trigger exception on the test file
71-
Image.MAX_IMAGE_PIXELS = 4 * 64 * 128
68+
monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 4 * 64 * 128)
7269
assert Image.MAX_IMAGE_PIXELS == 4 * 64 * 128
7370

7471
with pytest.raises(Image.DecompressionBombError):

Tests/test_file_fli.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -35,22 +35,19 @@ def test_sanity() -> None:
3535
assert im.is_animated
3636

3737

38-
def test_prefix_chunk() -> None:
39-
ImageFile.LOAD_TRUNCATED_IMAGES = True
40-
try:
41-
with Image.open(animated_test_file_with_prefix_chunk) as im:
42-
assert im.mode == "P"
43-
assert im.size == (320, 200)
44-
assert im.format == "FLI"
45-
assert im.info["duration"] == 171
46-
assert im.is_animated
47-
48-
palette = im.getpalette()
49-
assert palette[3:6] == [255, 255, 255]
50-
assert palette[381:384] == [204, 204, 12]
51-
assert palette[765:] == [252, 0, 0]
52-
finally:
53-
ImageFile.LOAD_TRUNCATED_IMAGES = False
38+
def test_prefix_chunk(monkeypatch: pytest.MonkeyPatch) -> None:
39+
monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True)
40+
with Image.open(animated_test_file_with_prefix_chunk) as im:
41+
assert im.mode == "P"
42+
assert im.size == (320, 200)
43+
assert im.format == "FLI"
44+
assert im.info["duration"] == 171
45+
assert im.is_animated
46+
47+
palette = im.getpalette()
48+
assert palette[3:6] == [255, 255, 255]
49+
assert palette[381:384] == [204, 204, 12]
50+
assert palette[765:] == [252, 0, 0]
5451

5552

5653
@pytest.mark.skipif(is_pypy(), reason="Requires CPython")

Tests/test_file_ico.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -243,26 +243,23 @@ def test_draw_reloaded(tmp_path: Path) -> None:
243243
assert_image_equal_tofile(im, "Tests/images/hopper_draw.ico")
244244

245245

246-
def test_truncated_mask() -> None:
246+
def test_truncated_mask(monkeypatch: pytest.MonkeyPatch) -> None:
247247
# 1 bpp
248248
with open("Tests/images/hopper_mask.ico", "rb") as fp:
249249
data = fp.read()
250250

251-
ImageFile.LOAD_TRUNCATED_IMAGES = True
251+
monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True)
252252
data = data[:-3]
253253

254-
try:
255-
with Image.open(io.BytesIO(data)) as im:
256-
assert im.mode == "1"
254+
with Image.open(io.BytesIO(data)) as im:
255+
assert im.mode == "1"
257256

258-
# 32 bpp
259-
output = io.BytesIO()
260-
expected = hopper("RGBA")
261-
expected.save(output, "ico", bitmap_format="bmp")
257+
# 32 bpp
258+
output = io.BytesIO()
259+
expected = hopper("RGBA")
260+
expected.save(output, "ico", bitmap_format="bmp")
262261

263-
data = output.getvalue()[:-1]
262+
data = output.getvalue()[:-1]
264263

265-
with Image.open(io.BytesIO(data)) as im:
266-
assert im.mode == "RGB"
267-
finally:
268-
ImageFile.LOAD_TRUNCATED_IMAGES = False
264+
with Image.open(io.BytesIO(data)) as im:
265+
assert im.mode == "RGB"

Tests/test_file_jpeg.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -530,12 +530,13 @@ def test_ff00_jpeg_header(self) -> None:
530530
@mark_if_feature_version(
531531
pytest.mark.valgrind_known_error, "libjpeg_turbo", "2.0", reason="Known Failing"
532532
)
533-
def test_truncated_jpeg_should_read_all_the_data(self) -> None:
533+
def test_truncated_jpeg_should_read_all_the_data(
534+
self, monkeypatch: pytest.MonkeyPatch
535+
) -> None:
534536
filename = "Tests/images/truncated_jpeg.jpg"
535-
ImageFile.LOAD_TRUNCATED_IMAGES = True
537+
monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True)
536538
with Image.open(filename) as im:
537539
im.load()
538-
ImageFile.LOAD_TRUNCATED_IMAGES = False
539540
assert im.getbbox() is not None
540541

541542
def test_truncated_jpeg_throws_oserror(self) -> None:
@@ -1024,7 +1025,7 @@ def test_save_xmp(self, tmp_path: Path) -> None:
10241025
im.save(f, xmp=b"1" * 65505)
10251026

10261027
@pytest.mark.timeout(timeout=1)
1027-
def test_eof(self) -> None:
1028+
def test_eof(self, monkeypatch: pytest.MonkeyPatch) -> None:
10281029
# Even though this decoder never says that it is finished
10291030
# the image should still end when there is no new data
10301031
class InfiniteMockPyDecoder(ImageFile.PyDecoder):
@@ -1039,9 +1040,8 @@ def decode(
10391040
im.tile = [
10401041
ImageFile._Tile("INFINITE", (0, 0, 128, 128), 0, ("RGB", 0, 1)),
10411042
]
1042-
ImageFile.LOAD_TRUNCATED_IMAGES = True
1043+
monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True)
10431044
im.load()
1044-
ImageFile.LOAD_TRUNCATED_IMAGES = False
10451045

10461046
def test_separate_tables(self) -> None:
10471047
im = hopper()

Tests/test_file_jpeg2k.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -181,14 +181,11 @@ def test_load_dpi() -> None:
181181
assert "dpi" not in im.info
182182

183183

184-
def test_restricted_icc_profile() -> None:
185-
ImageFile.LOAD_TRUNCATED_IMAGES = True
186-
try:
187-
# JPEG2000 image with a restricted ICC profile and a known colorspace
188-
with Image.open("Tests/images/balloon_eciRGBv2_aware.jp2") as im:
189-
assert im.mode == "RGB"
190-
finally:
191-
ImageFile.LOAD_TRUNCATED_IMAGES = False
184+
def test_restricted_icc_profile(monkeypatch: pytest.MonkeyPatch) -> None:
185+
monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True)
186+
# JPEG2000 image with a restricted ICC profile and a known colorspace
187+
with Image.open("Tests/images/balloon_eciRGBv2_aware.jp2") as im:
188+
assert im.mode == "RGB"
192189

193190

194191
@pytest.mark.skipif(

Tests/test_file_png.py

Lines changed: 27 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,7 @@ def test_verify_struct_error(self) -> None:
363363
with pytest.raises((OSError, SyntaxError)):
364364
im.verify()
365365

366-
def test_verify_ignores_crc_error(self) -> None:
366+
def test_verify_ignores_crc_error(self, monkeypatch: pytest.MonkeyPatch) -> None:
367367
# check ignores crc errors in ancillary chunks
368368

369369
chunk_data = chunk(b"tEXt", b"spam")
@@ -373,24 +373,20 @@ def test_verify_ignores_crc_error(self) -> None:
373373
with pytest.raises(SyntaxError):
374374
PngImagePlugin.PngImageFile(BytesIO(image_data))
375375

376-
ImageFile.LOAD_TRUNCATED_IMAGES = True
377-
try:
378-
im = load(image_data)
379-
assert im is not None
380-
finally:
381-
ImageFile.LOAD_TRUNCATED_IMAGES = False
376+
monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True)
377+
im = load(image_data)
378+
assert im is not None
382379

383-
def test_verify_not_ignores_crc_error_in_required_chunk(self) -> None:
380+
def test_verify_not_ignores_crc_error_in_required_chunk(
381+
self, monkeypatch: pytest.MonkeyPatch
382+
) -> None:
384383
# check does not ignore crc errors in required chunks
385384

386385
image_data = MAGIC + IHDR[:-1] + b"q" + TAIL
387386

388-
ImageFile.LOAD_TRUNCATED_IMAGES = True
389-
try:
390-
with pytest.raises(SyntaxError):
391-
PngImagePlugin.PngImageFile(BytesIO(image_data))
392-
finally:
393-
ImageFile.LOAD_TRUNCATED_IMAGES = False
387+
monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True)
388+
with pytest.raises(SyntaxError):
389+
PngImagePlugin.PngImageFile(BytesIO(image_data))
394390

395391
def test_roundtrip_dpi(self) -> None:
396392
# Check dpi roundtripping
@@ -600,7 +596,7 @@ def test_roundtrip_private_chunk(self) -> None:
600596
(b"prIV", b"VALUE3", True),
601597
]
602598

603-
def test_textual_chunks_after_idat(self) -> None:
599+
def test_textual_chunks_after_idat(self, monkeypatch: pytest.MonkeyPatch) -> None:
604600
with Image.open("Tests/images/hopper.png") as im:
605601
assert "comment" in im.text
606602
for k, v in {
@@ -614,18 +610,17 @@ def test_textual_chunks_after_idat(self) -> None:
614610
with pytest.raises(OSError):
615611
assert isinstance(im.text, dict)
616612

613+
# Raises an EOFError in load_end
614+
with Image.open("Tests/images/hopper_idat_after_image_end.png") as im:
615+
assert im.text == {"TXT": "VALUE", "ZIP": "VALUE"}
616+
617617
# Raises a UnicodeDecodeError in load_end
618618
with Image.open("Tests/images/truncated_image.png") as im:
619619
# The file is truncated
620620
with pytest.raises(OSError):
621621
im.text
622-
ImageFile.LOAD_TRUNCATED_IMAGES = True
622+
monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True)
623623
assert isinstance(im.text, dict)
624-
ImageFile.LOAD_TRUNCATED_IMAGES = False
625-
626-
# Raises an EOFError in load_end
627-
with Image.open("Tests/images/hopper_idat_after_image_end.png") as im:
628-
assert im.text == {"TXT": "VALUE", "ZIP": "VALUE"}
629624

630625
def test_unknown_compression_method(self) -> None:
631626
with pytest.raises(SyntaxError, match="Unknown compression method"):
@@ -651,15 +646,16 @@ def test_padded_idat(self) -> None:
651646
@pytest.mark.parametrize(
652647
"cid", (b"IHDR", b"sRGB", b"pHYs", b"acTL", b"fcTL", b"fdAT")
653648
)
654-
def test_truncated_chunks(self, cid: bytes) -> None:
649+
def test_truncated_chunks(
650+
self, cid: bytes, monkeypatch: pytest.MonkeyPatch
651+
) -> None:
655652
fp = BytesIO()
656653
with PngImagePlugin.PngStream(fp) as png:
657654
with pytest.raises(ValueError):
658655
png.call(cid, 0, 0)
659656

660-
ImageFile.LOAD_TRUNCATED_IMAGES = True
657+
monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True)
661658
png.call(cid, 0, 0)
662-
ImageFile.LOAD_TRUNCATED_IMAGES = False
663659

664660
@pytest.mark.parametrize("save_all", (True, False))
665661
def test_specify_bits(self, save_all: bool, tmp_path: Path) -> None:
@@ -789,17 +785,14 @@ class MyStdOut:
789785
with Image.open(mystdout) as reloaded:
790786
assert_image_equal_tofile(reloaded, TEST_PNG_FILE)
791787

792-
def test_truncated_end_chunk(self) -> None:
788+
def test_truncated_end_chunk(self, monkeypatch: pytest.MonkeyPatch) -> None:
793789
with Image.open("Tests/images/truncated_end_chunk.png") as im:
794790
with pytest.raises(OSError):
795791
im.load()
796792

797-
ImageFile.LOAD_TRUNCATED_IMAGES = True
798-
try:
799-
with Image.open("Tests/images/truncated_end_chunk.png") as im:
800-
assert_image_equal_tofile(im, "Tests/images/hopper.png")
801-
finally:
802-
ImageFile.LOAD_TRUNCATED_IMAGES = False
793+
monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True)
794+
with Image.open("Tests/images/truncated_end_chunk.png") as im:
795+
assert_image_equal_tofile(im, "Tests/images/hopper.png")
803796

804797

805798
@pytest.mark.skipif(is_win32(), reason="Requires Unix or macOS")
@@ -808,19 +801,16 @@ class TestTruncatedPngPLeaks(PillowLeakTestCase):
808801
mem_limit = 2 * 1024 # max increase in K
809802
iterations = 100 # Leak is 56k/iteration, this will leak 5.6megs
810803

811-
def test_leak_load(self) -> None:
804+
def test_leak_load(self, monkeypatch: pytest.MonkeyPatch) -> None:
812805
with open("Tests/images/hopper.png", "rb") as f:
813806
DATA = BytesIO(f.read(16 * 1024))
814807

815-
ImageFile.LOAD_TRUNCATED_IMAGES = True
808+
monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True)
816809
with Image.open(DATA) as im:
817810
im.load()
818811

819812
def core() -> None:
820813
with Image.open(DATA) as im:
821814
im.load()
822815

823-
try:
824-
self._test_leak(core)
825-
finally:
826-
ImageFile.LOAD_TRUNCATED_IMAGES = False
816+
self._test_leak(core)

Tests/test_file_tiff.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -939,11 +939,10 @@ def test_string_dimension(self) -> None:
939939

940940
@pytest.mark.timeout(6)
941941
@pytest.mark.filterwarnings("ignore:Truncated File Read")
942-
def test_timeout(self) -> None:
942+
def test_timeout(self, monkeypatch: pytest.MonkeyPatch) -> None:
943943
with Image.open("Tests/images/timeout-6646305047838720") as im:
944-
ImageFile.LOAD_TRUNCATED_IMAGES = True
944+
monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True)
945945
im.load()
946-
ImageFile.LOAD_TRUNCATED_IMAGES = False
947946

948947
@pytest.mark.parametrize(
949948
"test_file",

0 commit comments

Comments
 (0)