test_font_manager.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. from io import BytesIO, StringIO
  2. import gc
  3. import multiprocessing
  4. import os
  5. from pathlib import Path
  6. from PIL import Image
  7. import shutil
  8. import sys
  9. import warnings
  10. import numpy as np
  11. import pytest
  12. import matplotlib as mpl
  13. from matplotlib.font_manager import (
  14. findfont, findSystemFonts, FontEntry, FontProperties, fontManager,
  15. json_dump, json_load, get_font, is_opentype_cff_font,
  16. MSUserFontDirectories, _get_fontconfig_fonts, ttfFontProperty)
  17. from matplotlib import cbook, ft2font, pyplot as plt, rc_context, figure as mfigure
  18. from matplotlib.testing import subprocess_run_helper, subprocess_run_for_testing
  19. has_fclist = shutil.which('fc-list') is not None
  20. def test_font_priority():
  21. with rc_context(rc={
  22. 'font.sans-serif':
  23. ['cmmi10', 'Bitstream Vera Sans']}):
  24. fontfile = findfont(FontProperties(family=["sans-serif"]))
  25. assert Path(fontfile).name == 'cmmi10.ttf'
  26. # Smoketest get_charmap, which isn't used internally anymore
  27. font = get_font(fontfile)
  28. cmap = font.get_charmap()
  29. assert len(cmap) == 131
  30. assert cmap[8729] == 30
  31. def test_score_weight():
  32. assert 0 == fontManager.score_weight("regular", "regular")
  33. assert 0 == fontManager.score_weight("bold", "bold")
  34. assert (0 < fontManager.score_weight(400, 400) <
  35. fontManager.score_weight("normal", "bold"))
  36. assert (0 < fontManager.score_weight("normal", "regular") <
  37. fontManager.score_weight("normal", "bold"))
  38. assert (fontManager.score_weight("normal", "regular") ==
  39. fontManager.score_weight(400, 400))
  40. def test_json_serialization(tmp_path):
  41. # Can't open a NamedTemporaryFile twice on Windows, so use a temporary
  42. # directory instead.
  43. json_dump(fontManager, tmp_path / "fontlist.json")
  44. copy = json_load(tmp_path / "fontlist.json")
  45. with warnings.catch_warnings():
  46. warnings.filterwarnings('ignore', 'findfont: Font family.*not found')
  47. for prop in ({'family': 'STIXGeneral'},
  48. {'family': 'Bitstream Vera Sans', 'weight': 700},
  49. {'family': 'no such font family'}):
  50. fp = FontProperties(**prop)
  51. assert (fontManager.findfont(fp, rebuild_if_missing=False) ==
  52. copy.findfont(fp, rebuild_if_missing=False))
  53. def test_otf():
  54. fname = '/usr/share/fonts/opentype/freefont/FreeMono.otf'
  55. if Path(fname).exists():
  56. assert is_opentype_cff_font(fname)
  57. for f in fontManager.ttflist:
  58. if 'otf' in f.fname:
  59. with open(f.fname, 'rb') as fd:
  60. res = fd.read(4) == b'OTTO'
  61. assert res == is_opentype_cff_font(f.fname)
  62. @pytest.mark.skipif(sys.platform == "win32" or not has_fclist,
  63. reason='no fontconfig installed')
  64. def test_get_fontconfig_fonts():
  65. assert len(_get_fontconfig_fonts()) > 1
  66. @pytest.mark.parametrize('factor', [2, 4, 6, 8])
  67. def test_hinting_factor(factor):
  68. font = findfont(FontProperties(family=["sans-serif"]))
  69. font1 = get_font(font, hinting_factor=1)
  70. font1.clear()
  71. font1.set_size(12, 100)
  72. font1.set_text('abc')
  73. expected = font1.get_width_height()
  74. hinted_font = get_font(font, hinting_factor=factor)
  75. hinted_font.clear()
  76. hinted_font.set_size(12, 100)
  77. hinted_font.set_text('abc')
  78. # Check that hinting only changes text layout by a small (10%) amount.
  79. np.testing.assert_allclose(hinted_font.get_width_height(), expected,
  80. rtol=0.1)
  81. def test_utf16m_sfnt():
  82. try:
  83. # seguisbi = Microsoft Segoe UI Semibold
  84. entry = next(entry for entry in fontManager.ttflist
  85. if Path(entry.fname).name == "seguisbi.ttf")
  86. except StopIteration:
  87. pytest.skip("Couldn't find seguisbi.ttf font to test against.")
  88. else:
  89. # Check that we successfully read "semibold" from the font's sfnt table
  90. # and set its weight accordingly.
  91. assert entry.weight == 600
  92. def test_find_ttc():
  93. fp = FontProperties(family=["WenQuanYi Zen Hei"])
  94. if Path(findfont(fp)).name != "wqy-zenhei.ttc":
  95. pytest.skip("Font wqy-zenhei.ttc may be missing")
  96. fig, ax = plt.subplots()
  97. ax.text(.5, .5, "\N{KANGXI RADICAL DRAGON}", fontproperties=fp)
  98. for fmt in ["raw", "svg", "pdf", "ps"]:
  99. fig.savefig(BytesIO(), format=fmt)
  100. def test_find_noto():
  101. fp = FontProperties(family=["Noto Sans CJK SC", "Noto Sans CJK JP"])
  102. name = Path(findfont(fp)).name
  103. if name not in ("NotoSansCJKsc-Regular.otf", "NotoSansCJK-Regular.ttc"):
  104. pytest.skip(f"Noto Sans CJK SC font may be missing (found {name})")
  105. fig, ax = plt.subplots()
  106. ax.text(0.5, 0.5, 'Hello, 你好', fontproperties=fp)
  107. for fmt in ["raw", "svg", "pdf", "ps"]:
  108. fig.savefig(BytesIO(), format=fmt)
  109. def test_find_invalid(tmp_path):
  110. with pytest.raises(FileNotFoundError):
  111. get_font(tmp_path / 'non-existent-font-name.ttf')
  112. with pytest.raises(FileNotFoundError):
  113. get_font(str(tmp_path / 'non-existent-font-name.ttf'))
  114. with pytest.raises(FileNotFoundError):
  115. get_font(bytes(tmp_path / 'non-existent-font-name.ttf'))
  116. # Not really public, but get_font doesn't expose non-filename constructor.
  117. from matplotlib.ft2font import FT2Font
  118. with pytest.raises(TypeError, match='font file or a binary-mode file'):
  119. FT2Font(StringIO()) # type: ignore[arg-type]
  120. @pytest.mark.skipif(sys.platform != 'linux' or not has_fclist,
  121. reason='only Linux with fontconfig installed')
  122. def test_user_fonts_linux(tmpdir, monkeypatch):
  123. font_test_file = 'mpltest.ttf'
  124. # Precondition: the test font should not be available
  125. fonts = findSystemFonts()
  126. if any(font_test_file in font for font in fonts):
  127. pytest.skip(f'{font_test_file} already exists in system fonts')
  128. # Prepare a temporary user font directory
  129. user_fonts_dir = tmpdir.join('fonts')
  130. user_fonts_dir.ensure(dir=True)
  131. shutil.copyfile(Path(__file__).parent / font_test_file,
  132. user_fonts_dir.join(font_test_file))
  133. with monkeypatch.context() as m:
  134. m.setenv('XDG_DATA_HOME', str(tmpdir))
  135. _get_fontconfig_fonts.cache_clear()
  136. # Now, the font should be available
  137. fonts = findSystemFonts()
  138. assert any(font_test_file in font for font in fonts)
  139. # Make sure the temporary directory is no longer cached.
  140. _get_fontconfig_fonts.cache_clear()
  141. def test_addfont_as_path():
  142. """Smoke test that addfont() accepts pathlib.Path."""
  143. font_test_file = 'mpltest.ttf'
  144. path = Path(__file__).parent / font_test_file
  145. try:
  146. fontManager.addfont(path)
  147. added, = (font for font in fontManager.ttflist
  148. if font.fname.endswith(font_test_file))
  149. fontManager.ttflist.remove(added)
  150. finally:
  151. to_remove = [font for font in fontManager.ttflist
  152. if font.fname.endswith(font_test_file)]
  153. for font in to_remove:
  154. fontManager.ttflist.remove(font)
  155. @pytest.mark.skipif(sys.platform != 'win32', reason='Windows only')
  156. def test_user_fonts_win32():
  157. if not (os.environ.get('APPVEYOR') or os.environ.get('TF_BUILD')):
  158. pytest.xfail("This test should only run on CI (appveyor or azure) "
  159. "as the developer's font directory should remain "
  160. "unchanged.")
  161. pytest.xfail("We need to update the registry for this test to work")
  162. font_test_file = 'mpltest.ttf'
  163. # Precondition: the test font should not be available
  164. fonts = findSystemFonts()
  165. if any(font_test_file in font for font in fonts):
  166. pytest.skip(f'{font_test_file} already exists in system fonts')
  167. user_fonts_dir = MSUserFontDirectories[0]
  168. # Make sure that the user font directory exists (this is probably not the
  169. # case on Windows versions < 1809)
  170. os.makedirs(user_fonts_dir)
  171. # Copy the test font to the user font directory
  172. shutil.copy(Path(__file__).parent / font_test_file, user_fonts_dir)
  173. # Now, the font should be available
  174. fonts = findSystemFonts()
  175. assert any(font_test_file in font for font in fonts)
  176. def _model_handler(_):
  177. fig, ax = plt.subplots()
  178. fig.savefig(BytesIO(), format="pdf")
  179. plt.close()
  180. @pytest.mark.skipif(not hasattr(os, "register_at_fork"),
  181. reason="Cannot register at_fork handlers")
  182. def test_fork():
  183. _model_handler(0) # Make sure the font cache is filled.
  184. ctx = multiprocessing.get_context("fork")
  185. with ctx.Pool(processes=2) as pool:
  186. pool.map(_model_handler, range(2))
  187. def test_missing_family(caplog):
  188. plt.rcParams["font.sans-serif"] = ["this-font-does-not-exist"]
  189. with caplog.at_level("WARNING"):
  190. findfont("sans")
  191. assert [rec.getMessage() for rec in caplog.records] == [
  192. "findfont: Font family ['sans'] not found. "
  193. "Falling back to DejaVu Sans.",
  194. "findfont: Generic family 'sans' not found because none of the "
  195. "following families were found: this-font-does-not-exist",
  196. ]
  197. def _test_threading():
  198. import threading
  199. from matplotlib.ft2font import LoadFlags
  200. import matplotlib.font_manager as fm
  201. def loud_excepthook(args):
  202. raise RuntimeError("error in thread!")
  203. threading.excepthook = loud_excepthook
  204. N = 10
  205. b = threading.Barrier(N)
  206. def bad_idea(n):
  207. b.wait(timeout=5)
  208. for j in range(100):
  209. font = fm.get_font(fm.findfont("DejaVu Sans"))
  210. font.set_text(str(n), 0.0, flags=LoadFlags.NO_HINTING)
  211. threads = [
  212. threading.Thread(target=bad_idea, name=f"bad_thread_{j}", args=(j,))
  213. for j in range(N)
  214. ]
  215. for t in threads:
  216. t.start()
  217. for t in threads:
  218. t.join(timeout=9)
  219. if t.is_alive():
  220. raise RuntimeError("thread failed to join")
  221. def test_fontcache_thread_safe():
  222. pytest.importorskip('threading')
  223. subprocess_run_helper(_test_threading, timeout=10)
  224. def test_lockfilefailure(tmp_path):
  225. # The logic here:
  226. # 1. get a temp directory from pytest
  227. # 2. import matplotlib which makes sure it exists
  228. # 3. get the cache dir (where we check it is writable)
  229. # 4. make it not writable
  230. # 5. try to write into it via font manager
  231. proc = subprocess_run_for_testing(
  232. [
  233. sys.executable,
  234. "-c",
  235. "import matplotlib;"
  236. "import os;"
  237. "p = matplotlib.get_cachedir();"
  238. "os.chmod(p, 0o555);"
  239. "import matplotlib.font_manager;"
  240. ],
  241. env={**os.environ, 'MPLCONFIGDIR': str(tmp_path)},
  242. check=True
  243. )
  244. def test_fontentry_dataclass():
  245. fontent = FontEntry(name='font-name')
  246. png = fontent._repr_png_()
  247. img = Image.open(BytesIO(png))
  248. assert img.width > 0
  249. assert img.height > 0
  250. html = fontent._repr_html_()
  251. assert html.startswith("<img src=\"data:image/png;base64")
  252. def test_fontentry_dataclass_invalid_path():
  253. with pytest.raises(FileNotFoundError):
  254. fontent = FontEntry(fname='/random', name='font-name')
  255. fontent._repr_html_()
  256. @pytest.mark.skipif(sys.platform == 'win32', reason='Linux or OS only')
  257. def test_get_font_names():
  258. paths_mpl = [cbook._get_data_path('fonts', subdir) for subdir in ['ttf']]
  259. fonts_mpl = findSystemFonts(paths_mpl, fontext='ttf')
  260. fonts_system = findSystemFonts(fontext='ttf')
  261. ttf_fonts = []
  262. for path in fonts_mpl + fonts_system:
  263. try:
  264. font = ft2font.FT2Font(path)
  265. prop = ttfFontProperty(font)
  266. ttf_fonts.append(prop.name)
  267. except Exception:
  268. pass
  269. available_fonts = sorted(list(set(ttf_fonts)))
  270. mpl_font_names = sorted(fontManager.get_font_names())
  271. assert set(available_fonts) == set(mpl_font_names)
  272. assert len(available_fonts) == len(mpl_font_names)
  273. assert available_fonts == mpl_font_names
  274. def test_donot_cache_tracebacks():
  275. class SomeObject:
  276. pass
  277. def inner():
  278. x = SomeObject()
  279. fig = mfigure.Figure()
  280. ax = fig.subplots()
  281. fig.text(.5, .5, 'aardvark', family='doesnotexist')
  282. with BytesIO() as out:
  283. with warnings.catch_warnings():
  284. warnings.filterwarnings('ignore')
  285. fig.savefig(out, format='raw')
  286. inner()
  287. for obj in gc.get_objects():
  288. if isinstance(obj, SomeObject):
  289. pytest.fail("object from inner stack still alive")
  290. def test_fontproperties_init_deprecation():
  291. """
  292. Test the deprecated API of FontProperties.__init__.
  293. The deprecation does not change behavior, it only adds a deprecation warning
  294. via a decorator. Therefore, the purpose of this test is limited to check
  295. which calls do and do not issue deprecation warnings. Behavior is still
  296. tested via the existing regular tests.
  297. """
  298. with pytest.warns(mpl.MatplotlibDeprecationWarning):
  299. # multiple positional arguments
  300. FontProperties("Times", "italic")
  301. with pytest.warns(mpl.MatplotlibDeprecationWarning):
  302. # Mixed positional and keyword arguments
  303. FontProperties("Times", size=10)
  304. with pytest.warns(mpl.MatplotlibDeprecationWarning):
  305. # passing a family list positionally
  306. FontProperties(["Times"])
  307. # still accepted:
  308. FontProperties(family="Times", style="italic")
  309. FontProperties(family="Times")
  310. FontProperties("Times") # works as pattern and family
  311. FontProperties("serif-24:style=oblique:weight=bold") # pattern
  312. # also still accepted:
  313. # passing as pattern via family kwarg was not covered by the docs but
  314. # historically worked. This is left unchanged for now.
  315. # AFAICT, we cannot detect this: We can determine whether a string
  316. # works as pattern, but that doesn't help, because there are strings
  317. # that are both pattern and family. We would need to identify, whether
  318. # a string is *not* a valid family.
  319. # Since this case is not covered by docs, I've refrained from jumping
  320. # extra hoops to detect this possible API misuse.
  321. FontProperties(family="serif-24:style=oblique:weight=bold")