Ejemplo n.º 1
0
def test_bad_config():
    """Test that bad config values are caught."""
    sphinx_gallery_conf = dict(example_dir='')
    with pytest.raises(ConfigError, match="example_dir.*did you mean 'examples_dirs'?.*"):  # noqa: E501
        _complete_gallery_conf(sphinx_gallery_conf, '', True, False)
    sphinx_gallery_conf = dict(n_subsection_order='')
    with pytest.raises(ConfigError, match=r"did you mean one of \['subsection_order', 'within_.*"):  # noqa: E501
        _complete_gallery_conf(sphinx_gallery_conf, '', True, False)
Ejemplo n.º 2
0
def test_custom_scraper(gallery_conf, monkeypatch):
    """Test custom scrapers."""
    # Test the API contract for custom scrapers
    complete_args = (gallery_conf, gallery_conf['gallery_dir'], True, False)
    with monkeypatch.context() as m:
        m.setattr(sphinx_gallery,
                  '_get_sg_image_scraper',
                  lambda: _custom_func,
                  raising=False)
        for cust in (_custom_func, 'sphinx_gallery'):
            gallery_conf.update(image_scrapers=[cust])
            # smoke test that it works
            _complete_gallery_conf(*complete_args, check_keys=False)
    # degenerate
    # without the monkey patch to add sphinx_gallery._get_sg_image_scraper,
    # we should get an error
    gallery_conf.update(image_scrapers=['sphinx_gallery'])
    with pytest.raises(ConfigError,
                       match="has no attribute '_get_sg_image_scraper'"):
        _complete_gallery_conf(*complete_args, check_keys=False)

    # other degenerate conditions
    gallery_conf.update(image_scrapers=['foo'])
    with pytest.raises(ConfigError, match='Unknown image scraper'):
        _complete_gallery_conf(*complete_args, check_keys=False)
    gallery_conf.update(image_scrapers=[_custom_func])
    fname_template = os.path.join(gallery_conf['gallery_dir'], 'image{0}.png')
    image_path_iterator = ImagePathIterator(fname_template)
    block = ('', ) * 3
    block_vars = dict(image_path_iterator=image_path_iterator)
    with pytest.raises(ExtensionError, match='did not produce expected image'):
        save_figures(block, block_vars, gallery_conf)
    gallery_conf.update(image_scrapers=[lambda x, y, z: 1.])
    with pytest.raises(ExtensionError, match='was not a string'):
        save_figures(block, block_vars, gallery_conf)
    # degenerate string interface
    gallery_conf.update(image_scrapers=['sphinx_gallery'])
    with monkeypatch.context() as m:
        m.setattr(sphinx_gallery,
                  '_get_sg_image_scraper',
                  'foo',
                  raising=False)
        with pytest.raises(ConfigError, match='^Unknown image.*\n.*callable'):
            _complete_gallery_conf(*complete_args, check_keys=False)
    with monkeypatch.context() as m:
        m.setattr(sphinx_gallery,
                  '_get_sg_image_scraper',
                  lambda: 'foo',
                  raising=False)
        with pytest.raises(ConfigError, match='^Scraper.*was not callable'):
            _complete_gallery_conf(*complete_args, check_keys=False)
Ejemplo n.º 3
0
def gallery_conf(tmpdir):
    """Sets up a test sphinx-gallery configuration"""
    # Skip if numpy not installed
    pytest.importorskip("numpy")

    gallery_conf = _complete_gallery_conf({}, str(tmpdir), True, False)
    gallery_conf.update(examples_dir=str(tmpdir), gallery_dir=str(tmpdir))
    return gallery_conf
Ejemplo n.º 4
0
def gallery_conf(tmpdir):
    """Set up a test sphinx-gallery configuration."""
    app = utils.Bunch()
    app.config = dict(source_suffix={'.rst': None})
    gallery_conf = gen_gallery._complete_gallery_conf(
        {}, str(tmpdir), True, False, app=app)
    gallery_conf.update(examples_dir=str(tmpdir), gallery_dir=str(tmpdir))
    return gallery_conf
Ejemplo n.º 5
0
def test_custom_scraper(gallery_conf, monkeypatch):
    """Test custom scrapers."""
    # custom finders
    with monkeypatch.context() as m:
        m.setattr(sphinx_gallery,
                  '_get_sg_image_scraper',
                  lambda: _custom_func,
                  raising=False)
        for cust in (_custom_func, 'sphinx_gallery'):
            gallery_conf.update(image_scrapers=[cust])
            fname_template = os.path.join(gallery_conf['gallery_dir'],
                                          'image{0}.png')
            image_path_iterator = ImagePathIterator(fname_template)
            block = ('', ) * 3
            block_vars = dict(image_path_iterator=image_path_iterator)

    # degenerate
    gallery_conf.update(image_scrapers=['foo'])
    complete_args = (gallery_conf, gallery_conf['gallery_dir'], True, False)
    with pytest.raises(ValueError, match='Unknown image scraper'):
        _complete_gallery_conf(*complete_args)
    gallery_conf.update(
        image_scrapers=[lambda x, y, z: y['image_path_iterator'].next()])
    with pytest.raises(RuntimeError, match='did not produce expected image'):
        save_figures(block, block_vars, gallery_conf)
    gallery_conf.update(image_scrapers=[lambda x, y, z: 1.])
    with pytest.raises(TypeError, match='was not a string'):
        save_figures(block, block_vars, gallery_conf)
    # degenerate string interface
    gallery_conf.update(image_scrapers=['sphinx_gallery'])
    with monkeypatch.context() as m:
        m.setattr(sphinx_gallery,
                  '_get_sg_image_scraper',
                  'foo',
                  raising=False)
        with pytest.raises(ValueError, match='^Unknown image.*\n.*callable'):
            _complete_gallery_conf(*complete_args)
    with monkeypatch.context() as m:
        m.setattr(sphinx_gallery,
                  '_get_sg_image_scraper',
                  lambda: 'foo',
                  raising=False)
        with pytest.raises(ValueError, match='^Scraper.*was not callable'):
            _complete_gallery_conf(*complete_args)
Ejemplo n.º 6
0
def gallery_conf(tmpdir):
    """Sets up a test sphinx-gallery configuration"""
    gallery_conf = _complete_gallery_conf({}, str(tmpdir), True, False)
    gallery_conf.update(examples_dir=_TempDir(), gallery_dir=str(tmpdir))
    return gallery_conf
Ejemplo n.º 7
0
def test_save_mayavi_figures(gallery_conf):
    """Test file naming when saving figures. Requires mayavi."""
    try:
        from mayavi import mlab
    except ImportError:
        raise pytest.skip('Mayavi not installed')
    import matplotlib.pyplot as plt
    mlab.options.offscreen = True

    gallery_conf.update(
        image_scrapers=(matplotlib_scraper, mayavi_scraper))
    fname_template = os.path.join(gallery_conf['gallery_dir'], 'image{0}.png')
    image_path_iterator = ImagePathIterator(fname_template)
    block = ('',) * 3
    block_vars = dict(image_path_iterator=image_path_iterator)

    plt.axes([-0.1, -0.1, 1.2, 1.2])
    plt.pcolor([[0]], cmap='Greens')
    mlab.test_plot3d()
    image_rst = save_figures(block, block_vars, gallery_conf)
    assert len(plt.get_fignums()) == 0
    assert len(image_path_iterator) == 2
    assert '/image0.png' not in image_rst
    assert '/image1.png' in image_rst
    assert '/image2.png' in image_rst
    assert '/image3.png' not in image_rst
    assert not os.path.isfile(fname_template.format(0))
    assert os.path.isfile(fname_template.format(1))
    assert os.path.isfile(fname_template.format(2))
    assert not os.path.isfile(fname_template.format(0))
    with Image.open(fname_template.format(1)) as img:
        pixels = np.asarray(img.convert("RGB"))
    assert (pixels == [247, 252, 245]).all()  # plt first

    # Test next-value handling, plus image_scrapers modification
    gallery_conf.update(image_scrapers=(matplotlib_scraper,))
    mlab.test_plot3d()
    plt.axes([-0.1, -0.1, 1.2, 1.2])
    plt.pcolor([[0]], cmap='Reds')
    image_rst = save_figures(block, block_vars, gallery_conf)
    assert len(plt.get_fignums()) == 0
    assert len(image_path_iterator) == 3
    assert '/image1.png' not in image_rst
    assert '/image2.png' not in image_rst
    assert '/image3.png' in image_rst
    assert '/image4.png' not in image_rst
    assert not os.path.isfile(fname_template.format(0))
    for ii in range(3):
        assert os.path.isfile(fname_template.format(ii + 1))
    assert not os.path.isfile(fname_template.format(4))
    with Image.open(fname_template.format(3)) as img:
        pixels = np.asarray(img.convert("RGB"))
    assert (pixels == [255, 245, 240]).all()

    # custom finders
    gallery_conf.update(image_scrapers=[lambda x, y, z: ''])
    image_rst = save_figures(block, block_vars, gallery_conf)
    assert len(image_path_iterator) == 3

    # degenerate
    gallery_conf.update(image_scrapers=['foo'])
    with pytest.raises(ValueError, match='Unknown image scraper'):
        _complete_gallery_conf(
            gallery_conf, gallery_conf['gallery_dir'], True, False)
    gallery_conf.update(
        image_scrapers=[lambda x, y, z: y['image_path_iterator'].next()])
    with pytest.raises(RuntimeError, match='did not produce expected image'):
        save_figures(block, block_vars, gallery_conf)
    gallery_conf.update(image_scrapers=[lambda x, y, z: 1.])
    with pytest.raises(TypeError, match='was not a string'):
        save_figures(block, block_vars, gallery_conf)
Ejemplo n.º 8
0
def gallery_conf(tmpdir):
    """Sets up a test sphinx-gallery configuration"""
    gallery_conf = _complete_gallery_conf({}, str(tmpdir), True, False)
    gallery_conf.update(examples_dir=_TempDir(), gallery_dir=str(tmpdir))
    return gallery_conf
Ejemplo n.º 9
0
def test_save_mayavi_figures(gallery_conf):
    """Test file naming when saving figures. Requires mayavi."""
    try:
        from mayavi import mlab
    except ImportError:
        raise pytest.skip('Mayavi not installed')
    import matplotlib.pyplot as plt
    mlab.options.offscreen = True

    gallery_conf.update(image_scrapers=(matplotlib_scraper, mayavi_scraper))
    fname_template = os.path.join(gallery_conf['gallery_dir'], 'image{0}.png')
    image_path_iterator = ImagePathIterator(fname_template)
    block = ('', ) * 3
    block_vars = dict(image_path_iterator=image_path_iterator)

    plt.axes([-0.1, -0.1, 1.2, 1.2])
    plt.pcolor([[0]], cmap='Greens')
    mlab.test_plot3d()
    image_rst = save_figures(block, block_vars, gallery_conf)
    assert len(plt.get_fignums()) == 0
    assert len(image_path_iterator) == 2
    assert '/image0.png' not in image_rst
    assert '/image1.png' in image_rst
    assert '/image2.png' in image_rst
    assert '/image3.png' not in image_rst
    assert not os.path.isfile(fname_template.format(0))
    assert os.path.isfile(fname_template.format(1))
    assert os.path.isfile(fname_template.format(2))
    assert not os.path.isfile(fname_template.format(0))
    with Image.open(fname_template.format(1)) as img:
        pixels = np.asarray(img.convert("RGB"))
    assert (pixels == [247, 252, 245]).all()  # plt first

    # Test next-value handling, plus image_scrapers modification
    gallery_conf.update(image_scrapers=(matplotlib_scraper, ))
    mlab.test_plot3d()
    plt.axes([-0.1, -0.1, 1.2, 1.2])
    plt.pcolor([[0]], cmap='Reds')
    image_rst = save_figures(block, block_vars, gallery_conf)
    assert len(plt.get_fignums()) == 0
    assert len(image_path_iterator) == 3
    assert '/image1.png' not in image_rst
    assert '/image2.png' not in image_rst
    assert '/image3.png' in image_rst
    assert '/image4.png' not in image_rst
    assert not os.path.isfile(fname_template.format(0))
    for ii in range(3):
        assert os.path.isfile(fname_template.format(ii + 1))
    assert not os.path.isfile(fname_template.format(4))
    with Image.open(fname_template.format(3)) as img:
        pixels = np.asarray(img.convert("RGB"))
    assert (pixels == [255, 245, 240]).all()

    # custom finders
    gallery_conf.update(image_scrapers=[lambda x, y, z: ''])
    image_rst = save_figures(block, block_vars, gallery_conf)
    assert len(image_path_iterator) == 3

    # degenerate
    gallery_conf.update(image_scrapers=['foo'])
    with pytest.raises(ValueError, match='Unknown image scraper'):
        _complete_gallery_conf(gallery_conf, gallery_conf['gallery_dir'], True,
                               False)
    gallery_conf.update(
        image_scrapers=[lambda x, y, z: y['image_path_iterator'].next()])
    with pytest.raises(RuntimeError, match='did not produce expected image'):
        save_figures(block, block_vars, gallery_conf)
    gallery_conf.update(image_scrapers=[lambda x, y, z: 1.])
    with pytest.raises(TypeError, match='was not a string'):
        save_figures(block, block_vars, gallery_conf)