def test_extras_config(self): """Test default configuration in extras/ is correct...""" _config_reset() # Helper function to convert a config object to a dictionary. # This also strips leading/trailing whitespace in the paths section as # all options can take multiline values. def to_dict(cfg): result = {} for section in cfg.sections(): conv = dict(cfg[section]) if section == "paths": conv = {k: v.strip() for k, v in conv.items()} result[section] = conv return result # Read the config file in extras/. # Note we use the base class read() method here to avoid some extra # error checking in our custom parser which gets in the way of this # test being accurately performed. extras_dir = os.path.join(os.path.dirname(__file__), '..', 'extras') extras_dir = os.path.normpath(extras_dir) extras = PgfutilsParser() super(PgfutilsParser, extras).read(os.path.join(extras_dir, 'pgfutils.cfg')) # Compare to the default options. assert to_dict(extras) == to_dict(_config)
def test_setup_both_dimensions(self): """setup_figure() with both sizes specific dimensions...""" # Dimensions and their size in inches. dims = { '1in': 1, '2.5 inch': 2.5, '3 inches': 3, '2.54cm': 1, '1 centimetre': 0.3937, '8 centimetres': 3.14961, '1.0 centimeter': 0.3937, '8.0 centimeters': 3.14961, '80mm': 3.14961, '200 millimetre': 7.8740, '123.4 millimetres': 4.8583, '200 millimeter': 7.8740, '123.4 millimeters': 4.8583, '340pt': 4.7046, '120point': 1.6604, '960 points': 13.2835, } # Check each combination. for wstr, winch in dims.items(): for hstr, hinch in dims.items(): _config_reset() setup_figure(width=wstr, height=hstr) w, h = matplotlib.rcParams['figure.figsize'] assert w == approx(winch, rel=1e-3) assert h == approx(hinch, rel=1e-3)
def test_rgba(self): """RGBA list/tuple color parsing...""" _config_reset() # Generate a set of valid colors. import numpy as np c = np.linspace(0, 1, 5) colors = np.stack(np.meshgrid(c, c, c, c), -1).reshape(-1, 4) # Check they are accepted. The parser always returns colors as tuples. for color in colors: l = list(color) t = tuple(color) _config.read_kwargs(figure_background=str(l)) assert _config['pgfutils'].getcolor('figure_background') == t _config.read_kwargs(axes_background=str(t)) assert _config['pgfutils'].getcolor('axes_background') == t # Check it fails on channels with invalid values. color = [0, 0, 0, 0] for channel in range(4): for value in (-0.1, 1.2, 'a', True, False, None): with pytest.raises(ColorError): color[channel] = value _config.read_kwargs(axes_background=color) _config['pgfutils'].getcolor('axes_background') color[channel] = 0 # And some invalid formats too. for value in ('1,1,1', 'fail', 'yes', 'no'): with pytest.raises(ColorError): _config.read_kwargs(axes_background=value) _config['pgfutils'].getcolor('axes_background')
def test_setup_height_fraction(self): """setup_figure() with specific width and height as a fraction...""" # Dimensions and their size in inches. dims = { '1in': 1, '2.5 inch': 2.5, '3 inches': 3, '2.54cm': 1, '1 centimetre': 0.3937, '8 centimetres': 3.14961, '1.0 centimeter': 0.3937, '8.0 centimeters': 3.14961, '80mm': 3.14961, '200 millimetre': 7.8740, '123.4 millimetres': 4.8583, '200 millimeter': 7.8740, '123.4 millimeters': 4.8583, '340pt': 4.7046, '120point': 1.6604, '960 points': 13.2835, } # Check various combinations. for wstr, winch in dims.items(): for n in np.linspace(0.3, 2.5, 17): _config_reset() setup_figure(width=wstr, height=n) w, h = matplotlib.rcParams['figure.figsize'] assert w == approx(winch, rel=1e-3) assert h == approx(n * _config['tex'].getdimension('text_height'))
def test_cycle(self): """Color cycle parsing...""" _config_reset() for i in range(0, 10): cycle = "C{0:d}".format(i) _config.read_kwargs(axes_background=cycle) assert _config['pgfutils'].getcolor('axes_background') == cycle
def test_dim_unknown_unit(self): """Dimension with unknown unit is rejected...""" _config_reset() with pytest.raises(DimensionError): _config.parsedimension("1.2kg") with pytest.raises(DimensionError): _config.read_kwargs(text_width='1.2kg') _config['tex'].getdimension('text_width')
def test_dimension_inches(self): """Dimensions without units are treated as inches...""" _config_reset() assert _config.parsedimension('7') == approx(7) assert _config.parsedimension('2.7') == approx(2.7) _config.read_kwargs(text_width='5') assert _config['tex'].getdimension('text_width') == approx(5) _config.read_kwargs(text_width='5.451') assert _config['tex'].getdimension('text_width') == approx(5.451)
def test_transparent(self): """Color parsing supports transparency...""" _config_reset() _config.read_kwargs(axes_background='none') assert _config['pgfutils'].getcolor('axes_background') == 'none' _config.read_kwargs(axes_background='transparent') assert _config['pgfutils'].getcolor('axes_background') == 'none' _config.read_kwargs(axes_background='') assert _config['pgfutils'].getcolor('axes_background') == 'none'
def test_invalid_tuples(self): """Check RGB/RGBA parsing rejects tuples of invalid length...""" _config_reset() with pytest.raises(ColorError): _config.read_kwargs(axes_background='(1,)') _config['pgfutils'].getcolor('axes_background') with pytest.raises(ColorError): _config.read_kwargs(axes_background='(1,1)') _config['pgfutils'].getcolor('axes_background') with pytest.raises(ColorError): _config.read_kwargs(axes_background='(1,1,1,1,1)') _config['pgfutils'].getcolor('axes_background')
def test_dimension_negative(self): """Negative dimensions are rejected...""" _config_reset() with pytest.raises(DimensionError): _config.parsedimension("-1.2") with pytest.raises(DimensionError): _config.parsedimension("-1.2cm") with pytest.raises(DimensionError): _config.read_kwargs(text_width="-1.2") _config['tex'].getdimension('text_width') with pytest.raises(DimensionError): _config.read_kwargs(text_width="-1.2cm") _config['tex'].getdimension('text_width')
def test_dimension_not_parsing(self): """Dimension rejects invalid strings...""" _config_reset() with pytest.raises(DimensionError): _config.parsedimension("cm1.2") with pytest.raises(DimensionError): _config.parsedimension("1.2.2cm") with pytest.raises(DimensionError): _config.read_kwargs(text_width='1.2.2cm') _config['tex'].getdimension('text_width') with pytest.raises(DimensionError): _config.read_kwargs(text_width='cm1.2') _config['tex'].getdimension('text_width')
def test_named(self): """Named color parsing...""" _config_reset() # Try all known Matplotlib colors. for color in get_named_colors_mapping().keys(): _config.read_kwargs(axes_background=color) assert _config['pgfutils'].getcolor('axes_background') == color # And check it rejects non-existent named colors. with pytest.raises(ColorError): _config.read_kwargs(axes_background='nonexistentuglycolor') _config['pgfutils'].getcolor('axes_background')
def test_dimension_empty(self): """Dimension cannot be empty string...""" _config_reset() with pytest.raises(DimensionError): _config.parsedimension("") with pytest.raises(DimensionError): _config.parsedimension(" ") with pytest.raises(DimensionError): _config.parsedimension(None) with pytest.raises(DimensionError): _config.read_kwargs(text_width='') _config['tex'].getdimension('text_width') with pytest.raises(DimensionError): _config.read_kwargs(text_width=' ') _config['tex'].getdimension('text_width')
def test_setup_both_fractions(self): """setup_figure() with both sizes fractions...""" # Simple case. _config_reset() setup_figure(width=1, height=1) w, h = matplotlib.rcParams['figure.figsize'] assert w == _config['tex'].getdimension('text_width') assert h == _config['tex'].getdimension('text_height') # More complicated fractions. for m in np.linspace(0.1, 2.1, 13): for n in np.linspace(0.1, 2.1, 13): _config_reset() setup_figure(width=m, height=n) w, h = matplotlib.rcParams['figure.figsize'] assert w == approx(m * _config['tex'].getdimension('text_width')) assert h == approx(n * _config['tex'].getdimension('text_height'))
def test_setup_margin(self): """Test setup_figure() generates margin figures with margin=True...""" setup_figure() margin = _config['tex'].getdimension('marginpar_width') height = _config['tex'].getdimension('text_height') # Fractional tests. for w_in in {1.0, 0.5, 1.2}: for h_in in {0.3, 0.25, 0.5}: _config_reset() setup_figure(width=w_in, height=h_in, margin=True) w, h = matplotlib.rcParams['figure.figsize'] assert w == approx(w_in * margin) assert h == approx(h_in * height) # Specific size. _config_reset() setup_figure(width="1.8in", height="1.2in", margin=True) w, h = matplotlib.rcParams['figure.figsize'] assert w == approx(1.8) assert h == approx(1.2)
def test_greyscale(self): """Grayscale fraction parsing...""" _config_reset() # Test a range of valid floats. # N.B., Matplotlib uses strings for greyscale. for f in (0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0): _config.read_kwargs(figure_background=f) assert _config['pgfutils'].getcolor('figure_background') == str(f) # The same things as strings. for s in ('0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1.0'): _config.read_kwargs(figure_background=s) assert _config['pgfutils'].getcolor('figure_background') == s # Check numbers outside the valid range. for f in (1.01, -1): with pytest.raises(ColorError): _config.read_kwargs(axes_background=f) _config['pgfutils'].getcolor('axes_background')
def test_setup_arg_priority(self): """Test priority of columns/margin/full_width arguments to setup_figure()...""" setup_figure() text = _config['tex'].getdimension('text_width') sep = _config['tex'].getdimension('marginpar_sep') margin = _config['tex'].getdimension('marginpar_width') full = text + sep + margin height = _config['tex'].getdimension('text_height') # All three: full width should take priority. _config_reset() setup_figure(width=1, height=0.4, columns=1, margin=True, full_width=True) w, h = matplotlib.rcParams['figure.figsize'] assert w == approx(full) assert h == approx(0.4 * height) # Margin and full width: full width should take priority. _config_reset() setup_figure(width=1, height=0.4, margin=True, full_width=True) w, h = matplotlib.rcParams['figure.figsize'] assert w == approx(full) assert h == approx(0.4 * height) # Margin and columns: margin should take priority. _config_reset() setup_figure(width=1, height=0.4, columns=1, margin=True) w, h = matplotlib.rcParams['figure.figsize'] assert w == approx(margin) assert h == approx(0.4 * height)
def test_setup_full_width(self): """Test setup_figure() generates full-width figures with full_width=True...""" setup_figure() text = _config['tex'].getdimension('text_width') sep = _config['tex'].getdimension('marginpar_sep') margin = _config['tex'].getdimension('marginpar_width') full = text + sep + margin height = _config['tex'].getdimension('text_height') # Fractional tests. for w_in in {1.0, 0.75, 1.1}: for h_in in {0.4, 0.35, 0.15}: _config_reset() setup_figure(width=w_in, height=h_in, full_width=True) w, h = matplotlib.rcParams['figure.figsize'] assert w == approx(w_in * full) assert h == approx(h_in * height) # Specific size. _config_reset() setup_figure(width="5.5in", height="3.6in", full_width=True) w, h = matplotlib.rcParams['figure.figsize'] assert w == approx(5.5) assert h == approx(3.6)
def test_cfg_unknown_rcparams(self): """Config parser rejects unknown options in config file also containing rcParams...""" _config_reset() with pytest.raises(KeyError): _config.read(os.path.join(base, 'sources', 'extra_options_rcparams.cfg'))
def test_cfg_rcparams(self): """Config parser allows rcParams in config file...""" _config_reset() _config.read(os.path.join(base, 'sources', 'extra_rcparams.cfg')) assert not _config['rcParams'].getboolean('ytick.left'), "ytick.left is incorrect" assert _config['rcParams'].getboolean('ytick.right'), "ytick.right is incorrect"
def test_kwargs_unknown(self): """Config parser rejects unknown keywords...""" _config_reset() with pytest.raises(KeyError): _config.read_kwargs(unknown_keyword='yellow')
def test_unknown_tracking_type(self): """Unknown tracking types are rejected...""" _config_reset() with pytest.raises(ValueError): _config.in_tracking_dir("unknown", "file.txt")