1
1
from datetime import datetime
2
+ import gc
3
+ import inspect
2
4
import io
3
5
import warnings
4
6
@@ -881,7 +883,12 @@ def test_pdf_chars_beyond_bmp():
881
883
882
884
@needs_usetex
883
885
def test_metrics_cache ():
884
- mpl .text ._get_text_metrics_with_cache_impl .cache_clear ()
886
+ # dig into the signature to get the mutable default used as a cache
887
+ renderer_cache = inspect .signature (
888
+ mpl .text ._get_text_metrics_function
889
+ ).parameters ['_cache' ].default
890
+
891
+ renderer_cache .clear ()
885
892
886
893
fig = plt .figure ()
887
894
fig .text (.3 , .5 , "foo\n bar" )
@@ -890,6 +897,7 @@ def test_metrics_cache():
890
897
fig .canvas .draw ()
891
898
renderer = fig ._get_renderer ()
892
899
ys = {} # mapping of strings to where they were drawn in y with draw_tex.
900
+ assert renderer in renderer_cache
893
901
894
902
def call (* args , ** kwargs ):
895
903
renderer , x , y , s , * _ = args
@@ -904,12 +912,39 @@ def call(*args, **kwargs):
904
912
# get incorrectly reused by the first TeX string.
905
913
assert len (ys ["foo" ]) == len (ys ["bar" ]) == 1
906
914
907
- info = mpl . text . _get_text_metrics_with_cache_impl .cache_info ()
915
+ info = renderer_cache [ renderer ] .cache_info ()
908
916
# Every string gets a miss for the first layouting (extents), then a hit
909
917
# when drawing, but "foo\nbar" gets two hits as it's drawn twice.
910
918
assert info .hits > info .misses
911
919
912
920
921
+ def test_metrics_cache2 ():
922
+ # dig into the signature to get the mutable default used as a cache
923
+ renderer_cache = inspect .signature (
924
+ mpl .text ._get_text_metrics_function
925
+ ).parameters ['_cache' ].default
926
+ gc .collect ()
927
+ assert len (renderer_cache ) == 0
928
+
929
+ def helper ():
930
+ fig , ax = plt .subplots ()
931
+ fig .draw_without_rendering ()
932
+ # show we hit the outer cache
933
+ assert len (renderer_cache ) == 1
934
+ func = renderer_cache [fig .canvas .get_renderer ()]
935
+ cache_info = func .cache_info ()
936
+ # show we hit the inner cache
937
+ assert cache_info .currsize > 0
938
+ assert cache_info .currsize == cache_info .misses
939
+ assert cache_info .hits > cache_info .misses
940
+ plt .close (fig )
941
+
942
+ helper ()
943
+ gc .collect ()
944
+ # show the outer cache has a lifetime tied to the renderer (via the figure)
945
+ assert len (renderer_cache ) == 0
946
+
947
+
913
948
def test_annotate_offset_fontsize ():
914
949
# Test that offset_fontsize parameter works and uses accurate values
915
950
fig , ax = plt .subplots ()
0 commit comments