test_font_manager.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. from io import BytesIO
  2. import multiprocessing
  3. import os
  4. from pathlib import Path
  5. import shutil
  6. import sys
  7. import warnings
  8. import numpy as np
  9. import pytest
  10. from matplotlib import font_manager as fm
  11. from matplotlib.font_manager import (
  12. findfont, findSystemFonts, FontProperties, fontManager, json_dump,
  13. json_load, get_font, get_fontconfig_fonts, is_opentype_cff_font,
  14. MSUserFontDirectories, _call_fc_list)
  15. from matplotlib import pyplot as plt, rc_context
  16. has_fclist = shutil.which('fc-list') is not None
  17. def test_font_priority():
  18. with rc_context(rc={
  19. 'font.sans-serif':
  20. ['cmmi10', 'Bitstream Vera Sans']}):
  21. font = findfont(FontProperties(family=["sans-serif"]))
  22. assert Path(font).name == 'cmmi10.ttf'
  23. # Smoketest get_charmap, which isn't used internally anymore
  24. font = get_font(font)
  25. cmap = font.get_charmap()
  26. assert len(cmap) == 131
  27. assert cmap[8729] == 30
  28. def test_score_weight():
  29. assert 0 == fontManager.score_weight("regular", "regular")
  30. assert 0 == fontManager.score_weight("bold", "bold")
  31. assert (0 < fontManager.score_weight(400, 400) <
  32. fontManager.score_weight("normal", "bold"))
  33. assert (0 < fontManager.score_weight("normal", "regular") <
  34. fontManager.score_weight("normal", "bold"))
  35. assert (fontManager.score_weight("normal", "regular") ==
  36. fontManager.score_weight(400, 400))
  37. def test_json_serialization(tmpdir):
  38. # Can't open a NamedTemporaryFile twice on Windows, so use a temporary
  39. # directory instead.
  40. path = Path(tmpdir, "fontlist.json")
  41. json_dump(fontManager, path)
  42. copy = json_load(path)
  43. with warnings.catch_warnings():
  44. warnings.filterwarnings('ignore', 'findfont: Font family.*not found')
  45. for prop in ({'family': 'STIXGeneral'},
  46. {'family': 'Bitstream Vera Sans', 'weight': 700},
  47. {'family': 'no such font family'}):
  48. fp = FontProperties(**prop)
  49. assert (fontManager.findfont(fp, rebuild_if_missing=False) ==
  50. copy.findfont(fp, rebuild_if_missing=False))
  51. def test_otf():
  52. fname = '/usr/share/fonts/opentype/freefont/FreeMono.otf'
  53. if Path(fname).exists():
  54. assert is_opentype_cff_font(fname)
  55. for f in fontManager.ttflist:
  56. if 'otf' in f.fname:
  57. with open(f.fname, 'rb') as fd:
  58. res = fd.read(4) == b'OTTO'
  59. assert res == is_opentype_cff_font(f.fname)
  60. @pytest.mark.skipif(not has_fclist, reason='no fontconfig installed')
  61. def test_get_fontconfig_fonts():
  62. assert len(get_fontconfig_fonts()) > 1
  63. @pytest.mark.parametrize('factor', [2, 4, 6, 8])
  64. def test_hinting_factor(factor):
  65. font = findfont(FontProperties(family=["sans-serif"]))
  66. font1 = get_font(font, hinting_factor=1)
  67. font1.clear()
  68. font1.set_size(12, 100)
  69. font1.set_text('abc')
  70. expected = font1.get_width_height()
  71. hinted_font = get_font(font, hinting_factor=factor)
  72. hinted_font.clear()
  73. hinted_font.set_size(12, 100)
  74. hinted_font.set_text('abc')
  75. # Check that hinting only changes text layout by a small (10%) amount.
  76. np.testing.assert_allclose(hinted_font.get_width_height(), expected,
  77. rtol=0.1)
  78. @pytest.mark.skipif(sys.platform != "win32",
  79. reason="Need Windows font to test against")
  80. def test_utf16m_sfnt():
  81. segoe_ui_semibold = None
  82. for f in fontManager.ttflist:
  83. # seguisbi = Microsoft Segoe UI Semibold
  84. if f.fname[-12:] == "seguisbi.ttf":
  85. segoe_ui_semibold = f
  86. break
  87. else:
  88. pytest.xfail(reason="Couldn't find font to test against.")
  89. # Check that we successfully read the "semibold" from the font's
  90. # sfnt table and set its weight accordingly
  91. assert segoe_ui_semibold.weight == "semibold"
  92. @pytest.mark.xfail(not (os.environ.get("TRAVIS") and sys.platform == "linux"),
  93. reason="Font may be missing.")
  94. def test_find_ttc():
  95. fp = FontProperties(family=["WenQuanYi Zen Hei"])
  96. if Path(findfont(fp)).name != "wqy-zenhei.ttc":
  97. # Travis appears to fail to pick up the ttc file sometimes. Try to
  98. # rebuild the cache and try again.
  99. fm._rebuild()
  100. assert Path(findfont(fp)).name == "wqy-zenhei.ttc"
  101. fig, ax = plt.subplots()
  102. ax.text(.5, .5, "\N{KANGXI RADICAL DRAGON}", fontproperties=fp)
  103. fig.savefig(BytesIO(), format="raw")
  104. fig.savefig(BytesIO(), format="svg")
  105. with pytest.raises(RuntimeError):
  106. fig.savefig(BytesIO(), format="pdf")
  107. with pytest.raises(RuntimeError):
  108. fig.savefig(BytesIO(), format="ps")
  109. @pytest.mark.skipif(sys.platform != 'linux', reason='Linux only')
  110. def test_user_fonts_linux(tmpdir, monkeypatch):
  111. font_test_file = 'mpltest.ttf'
  112. # Precondition: the test font should not be available
  113. fonts = findSystemFonts()
  114. if any(font_test_file in font for font in fonts):
  115. pytest.skip(f'{font_test_file} already exists in system fonts')
  116. # Prepare a temporary user font directory
  117. user_fonts_dir = tmpdir.join('fonts')
  118. user_fonts_dir.ensure(dir=True)
  119. shutil.copyfile(Path(__file__).parent / font_test_file,
  120. user_fonts_dir.join(font_test_file))
  121. with monkeypatch.context() as m:
  122. m.setenv('XDG_DATA_HOME', str(tmpdir))
  123. _call_fc_list.cache_clear()
  124. # Now, the font should be available
  125. fonts = findSystemFonts()
  126. assert any(font_test_file in font for font in fonts)
  127. # Make sure the temporary directory is no longer cached.
  128. _call_fc_list.cache_clear()
  129. @pytest.mark.skipif(sys.platform != 'win32', reason='Windows only')
  130. def test_user_fonts_win32():
  131. if not (os.environ.get('APPVEYOR', False) or
  132. os.environ.get('TF_BUILD', False)):
  133. pytest.xfail("This test should only run on CI (appveyor or azure) "
  134. "as the developer's font directory should remain "
  135. "unchanged.")
  136. font_test_file = 'mpltest.ttf'
  137. # Precondition: the test font should not be available
  138. fonts = findSystemFonts()
  139. if any(font_test_file in font for font in fonts):
  140. pytest.skip(f'{font_test_file} already exists in system fonts')
  141. user_fonts_dir = MSUserFontDirectories[0]
  142. # Make sure that the user font directory exists (this is probably not the
  143. # case on Windows versions < 1809)
  144. os.makedirs(user_fonts_dir)
  145. # Copy the test font to the user font directory
  146. shutil.copyfile(os.path.join(os.path.dirname(__file__), font_test_file),
  147. os.path.join(user_fonts_dir, font_test_file))
  148. # Now, the font should be available
  149. fonts = findSystemFonts()
  150. assert any(font_test_file in font for font in fonts)
  151. def _model_handler(_):
  152. fig, ax = plt.subplots()
  153. fig.savefig(BytesIO(), format="pdf")
  154. plt.close()
  155. @pytest.mark.skipif(not hasattr(os, "register_at_fork"),
  156. reason="Cannot register at_fork handlers")
  157. def test_fork():
  158. _model_handler(0) # Make sure the font cache is filled.
  159. ctx = multiprocessing.get_context("fork")
  160. with ctx.Pool(processes=2) as pool:
  161. pool.map(_model_handler, range(2))