Use tempfile.NamedTemporaryFile

This commit is contained in:
Andrew Murray 2024-08-31 20:51:26 +10:00
parent cdadf931e3
commit 95194a2050

View File

@ -5,6 +5,7 @@ import os
import re import re
import shutil import shutil
import sys import sys
import tempfile
from io import BytesIO from io import BytesIO
from pathlib import Path from pathlib import Path
from typing import Any, BinaryIO from typing import Any, BinaryIO
@ -460,15 +461,15 @@ def test_free_type_font_get_mask(font: ImageFont.FreeTypeFont) -> None:
assert mask.size == (108, 13) assert mask.size == (108, 13)
def test_load_raises_if_image_not_found(tmp_path) -> None: def test_load_when_image_not_found(tmp_path: Path) -> None:
font_path = tmp_path / "file.font" tmpfile = tmp_path / "file.font"
font_path.write_bytes(b"") tmpfile.write_bytes(b"")
with pytest.raises(OSError) as excinfo: tempfile = str(tmpfile)
ImageFont.load(font_path) with pytest.raises(OSError) as e:
ImageFont.load(tempfile)
pre = tmp_path / "file" root = os.path.splitext(tempfile)[0]
msg = f"cannot find glyph data file {pre}.{{png|gif|pbm}}" assert str(e.value) == f"cannot find glyph data file {root}.{{png|gif|pbm}}"
assert msg in str(excinfo.value)
def test_load_path_not_found() -> None: def test_load_path_not_found() -> None:
@ -476,26 +477,24 @@ def test_load_path_not_found() -> None:
filename = "somefilenamethatdoesntexist.ttf" filename = "somefilenamethatdoesntexist.ttf"
# Act/Assert # Act/Assert
with pytest.raises(OSError): with pytest.raises(OSError) as e:
ImageFont.load_path(filename) ImageFont.load_path(filename)
# The file doesn't exist, so don't suggest `load`
assert filename in str(e.value)
assert "did you mean" not in str(e.value)
with pytest.raises(OSError): with pytest.raises(OSError):
ImageFont.truetype(filename) ImageFont.truetype(filename)
def test_load_path_exisitng_path(tmp_path) -> None: def test_load_path_existing_path() -> None:
# First, the file doens't exist, so we don't suggest `load` with tempfile.NamedTemporaryFile() as tmp:
some_path = tmp_path / "file.ttf" with pytest.raises(OSError) as e:
with pytest.raises(OSError) as excinfo: ImageFont.load_path(tmp.name)
ImageFont.load_path(str(some_path))
assert str(some_path) in str(excinfo.value)
assert "did you mean" not in str(excinfo.value)
# The file exists, so the error message suggests to use `load` instead # The file exists, so the error message suggests to use `load` instead
some_path.write_bytes(b"") assert tmp.name in str(e.value)
with pytest.raises(OSError) as excinfo: assert " did you mean" in str(e.value)
ImageFont.load_path(str(some_path))
assert str(some_path) in str(excinfo.value)
assert " did you mean" in str(excinfo.value)
def test_load_non_font_bytes() -> None: def test_load_non_font_bytes() -> None: