Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c5c12dd

Browse files
authored
Merge pull request #17510 from QuLogic/invalid-font
Fix exception handling in FT2Font init.
2 parents f48e59c + 699a03b commit c5c12dd

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

lib/matplotlib/tests/test_font_manager.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from io import BytesIO
1+
from io import BytesIO, StringIO
22
import multiprocessing
33
import os
44
from pathlib import Path
@@ -128,6 +128,24 @@ def test_find_ttc():
128128
fig.savefig(BytesIO(), format="ps")
129129

130130

131+
def test_find_invalid(tmpdir):
132+
tmp_path = Path(tmpdir)
133+
134+
with pytest.raises(FileNotFoundError):
135+
get_font(tmp_path / 'non-existent-font-name.ttf')
136+
137+
with pytest.raises(FileNotFoundError):
138+
get_font(str(tmp_path / 'non-existent-font-name.ttf'))
139+
140+
with pytest.raises(FileNotFoundError):
141+
get_font(bytes(tmp_path / 'non-existent-font-name.ttf'))
142+
143+
# Not really public, but get_font doesn't expose non-filename constructor.
144+
from matplotlib.ft2font import FT2Font
145+
with pytest.raises(TypeError, match='path or binary-mode file'):
146+
FT2Font(StringIO())
147+
148+
131149
@pytest.mark.skipif(sys.platform != 'linux', reason='Linux only')
132150
def test_user_fonts_linux(tmpdir, monkeypatch):
133151
font_test_file = 'mpltest.ttf'

src/ft2font_wrapper.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -488,12 +488,14 @@ static int PyFT2Font_init(PyFT2Font *self, PyObject *args, PyObject *kwds)
488488
|| !PyBytes_Check(data)) {
489489
PyErr_SetString(PyExc_TypeError,
490490
"First argument must be a path or binary-mode file object");
491+
Py_CLEAR(data);
491492
goto exit;
492493
} else {
493494
self->py_file = filename;
494495
self->stream.close = NULL;
495496
Py_INCREF(filename);
496497
}
498+
Py_CLEAR(data);
497499

498500
CALL_CPP_FULL(
499501
"FT2Font", (self->x = new FT2Font(open_args, hinting_factor)),
@@ -505,9 +507,7 @@ static int PyFT2Font_init(PyFT2Font *self, PyObject *args, PyObject *kwds)
505507
self->fname = filename;
506508

507509
exit:
508-
Py_XDECREF(data);
509-
510-
return 0;
510+
return PyErr_Occurred() ? -1 : 0;
511511
}
512512

513513
static void PyFT2Font_dealloc(PyFT2Font *self)

0 commit comments

Comments
 (0)