当前位置: 首页>>代码示例>>Python>>正文


Python errors.ExtensionError方法代码示例

本文整理汇总了Python中sphinx.errors.ExtensionError方法的典型用法代码示例。如果您正苦于以下问题:Python errors.ExtensionError方法的具体用法?Python errors.ExtensionError怎么用?Python errors.ExtensionError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sphinx.errors的用法示例。


在下文中一共展示了errors.ExtensionError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def test(monkeypatch, tmpdir, tail, expected_error):
    """Test valid and invalid values."""
    tmpdir.join('conf.py').write(BASE_CONFIG.format(py.path.local(__file__).join('..', '..')))
    tmpdir.join('conf.py').write(tail, mode='a')
    tmpdir.join('index.rst').write('====\nMain\n====\n\n.. toctree::\n    :maxdepth: 2\n.. disqus::')
    monkeypatch.setattr(directives, '_directives', getattr(directives, '_directives').copy())
    monkeypatch.setattr(roles, '_roles', getattr(roles, '_roles').copy())

    srcdir = confdir = str(tmpdir)
    outdir = tmpdir.join('_build', 'html')
    doctreedir = outdir.join('doctrees').ensure(dir=True, rec=True)
    app = application.Sphinx(srcdir, confdir, str(outdir), str(doctreedir), 'html')

    if not expected_error:
        app.builder.build_all()
        html_body = outdir.join('index.html').read()
        disqus_div = re.findall(r'(<div[^>]+ id="disqus_thread"[^>]*></div>)', html_body)[0]
        assert 'data-disqus-shortname="good"' in disqus_div
        return

    with pytest.raises(errors.ExtensionError) as exc:
        app.builder.build_all()
    assert expected_error == exc.value.args[0] 
开发者ID:Robpol86,项目名称:sphinxcontrib-disqus,代码行数:25,代码来源:test_shortname.py

示例2: _get_data

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def _get_data(url):
    """Get data over http(s) or from a local file."""
    if urllib_parse.urlparse(url).scheme in ('http', 'https'):
        user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'  # noqa: E501
        headers = {'User-Agent': user_agent}
        req = urllib_request.Request(url, None, headers)
        resp = urllib_request.urlopen(req)
        encoding = resp.headers.get('content-encoding', 'plain')
        data = resp.read()
        if encoding == 'gzip':
            data = gzip.GzipFile(fileobj=BytesIO(data)).read()
        elif encoding != 'plain':
            raise ExtensionError('unknown encoding %r' % (encoding,))
        data = data.decode('utf-8')
    else:
        with codecs.open(url, mode='r', encoding='utf-8') as fid:
            data = fid.read()

    return data 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:21,代码来源:docs_resolv.py

示例3: test_get_docstring_and_rest

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def test_get_docstring_and_rest(unicode_sample, tmpdir, monkeypatch):
    docstring, rest, lineno, _ = sg._get_docstring_and_rest(unicode_sample)
    assert u'Únicode' in docstring
    assert u'heiß' in rest
    # degenerate
    fname = op.join(str(tmpdir), 'temp')
    with open(fname, 'w') as fid:
        fid.write('print("hello")\n')
    with pytest.raises(ExtensionError, match='Could not find docstring'):
        sg._get_docstring_and_rest(fname)
    with open(fname, 'w') as fid:
        fid.write('print hello\n')
    assert sg._get_docstring_and_rest(fname)[0] == sg.SYNTAX_ERROR_DOCSTRING
    monkeypatch.setattr(sg, 'parse_source_file', lambda x: ('', None))
    with pytest.raises(ExtensionError, match='only supports modules'):
        sg._get_docstring_and_rest('') 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:18,代码来源:test_py_source_parser.py

示例4: test_thumbnail_div

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def test_thumbnail_div(content, tooltip, is_backref):
    """Test if the thumbnail div generates the correct string."""
    with pytest.raises(ExtensionError, match='internal sphinx-gallery thumb'):
        html_div = sg._thumbnail_div('fake_dir', '', 'test_file.py',
                                     '<"test">', '<"title">')
    content = _sanitize_rst(content)
    title = 'test title'
    html_div = sg._thumbnail_div('fake_dir', '', 'test_file.py',
                                 content, title, is_backref=is_backref,
                                 check=False)
    if is_backref:
        extra = """

.. only:: not html

 * :ref:`sphx_glr_fake_dir_test_file.py`"""
    else:
        extra = ''
    reference = REFERENCE.format(tooltip, extra)
    assert html_div == reference 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:22,代码来源:test_backreferences.py

示例5: test_gen_dir_rst

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def test_gen_dir_rst(gallery_conf, fakesphinxapp, ext):
    """Test gen_dir_rst."""
    print(os.listdir(gallery_conf['examples_dir']))
    fname_readme = os.path.join(gallery_conf['src_dir'], 'README.txt')
    with open(fname_readme, 'wb') as fid:
        fid.write(u"Testing\n=======\n\nÓscar here.".encode('utf-8'))
    fname_out = os.path.splitext(fname_readme)[0] + ext
    if fname_readme != fname_out:
        shutil.move(fname_readme, fname_out)
    args = (gallery_conf['src_dir'], gallery_conf['gallery_dir'],
            gallery_conf, [])
    if ext == '.bad':  # not found with correct ext
        with pytest.raises(ExtensionError, match='does not have a README'):
            generate_dir_rst(*args)
    else:
        out = generate_dir_rst(*args)
        assert u"Óscar here" in out[0] 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:19,代码来源:test_gen_rst.py

示例6: _thumbnail_div

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def _thumbnail_div(target_dir, src_dir, fname, snippet, title,
                   is_backref=False, check=True):
    """Generate RST to place a thumbnail in a gallery."""
    thumb, _ = _find_image_ext(
        os.path.join(target_dir, 'images', 'thumb',
                     'sphx_glr_%s_thumb.png' % fname[:-3]))
    if check and not os.path.isfile(thumb):
        # This means we have done something wrong in creating our thumbnail!
        raise ExtensionError('Could not find internal sphinx-gallery thumbnail'
                             ' file:\n%s' % (thumb,))
    thumb = os.path.relpath(thumb, src_dir)
    full_dir = os.path.relpath(target_dir, src_dir)

    # Inside rst files forward slash defines paths
    thumb = thumb.replace(os.sep, "/")

    ref_name = os.path.join(full_dir, fname).replace(os.path.sep, '_')

    template = BACKREF_THUMBNAIL_TEMPLATE if is_backref else THUMBNAIL_TEMPLATE
    return template.format(snippet=escape(snippet),
                           thumbnail=thumb, title=title, ref_name=ref_name) 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:23,代码来源:backreferences.py

示例7: __iter__

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def __iter__(self):
        """Iterate over paths.

        Returns
        -------
        paths : iterable of str

        This enables the use of this Python pattern::

            >>> for epoch in epochs:  # doctest: +SKIP
            >>>     print(epoch)  # doctest: +SKIP

        Where ``epoch`` is given by successive outputs of
        :func:`mne.Epochs.next`.
        """
        # we should really never have 1e6, let's prevent some user pain
        for ii in range(self._stop):
            yield self.next()
        else:
            raise ExtensionError('Generated over %s images' % (self._stop,)) 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:22,代码来源:scrapers.py

示例8: setup

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def setup(app):
    """Allow this module to be used as Sphinx extension.

    This is also called from the top-level ``__init__.py``.
    It adds the rules to allow :django:setting:`SITE_ID` to work.

    :type app: sphinx.application.Sphinx
    """
    try:
        app.add_crossref_type(
            directivename="setting",
            rolename="setting",
            indextemplate="pair: %s; setting",
        )
    except ExtensionError as e:
        logger.warning("Unable to register :django:setting:`..`: " + str(e)) 
开发者ID:edoburu,项目名称:sphinxcontrib-django,代码行数:18,代码来源:roles.py

示例9: extract_intro_and_title

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def extract_intro_and_title(filename, docstring):
    """Extract and clean the first paragraph of module-level docstring."""
    # lstrip is just in case docstring has a '\n\n' at the beginning
    paragraphs = docstring.lstrip().split('\n\n')
    # remove comments and other syntax like `.. _link:`
    paragraphs = [p for p in paragraphs
                  if not p.startswith('.. ') and len(p) > 0]
    if len(paragraphs) == 0:
        raise ExtensionError(
            "Example docstring should have a header for the example title. "
            "Please check the example file:\n {}\n".format(filename))
    # Title is the first paragraph with any ReSTructuredText title chars
    # removed, i.e. lines that consist of (3 or more of the same) 7-bit
    # non-ASCII chars.
    # This conditional is not perfect but should hopefully be good enough.
    title_paragraph = paragraphs[0]
    match = re.search(r'^(?!([\W _])\1{3,})(.+)', title_paragraph,
                      re.MULTILINE)

    if match is None:
        raise ExtensionError(
            'Could not find a title in first paragraph:\n{}'.format(
                title_paragraph))
    title = match.group(0).strip()
    # Use the title if no other paragraphs are provided
    intro_paragraph = title if len(paragraphs) < 2 else paragraphs[1]
    # Concatenate all lines of the first paragraph and truncate at 95 chars
    intro = re.sub('\n', ' ', intro_paragraph)
    intro = _sanitize_rst(intro)
    if len(intro) > 95:
        intro = intro[:95] + '...'
    return intro, title 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:34,代码来源:gen_rst.py

示例10: _get_readme

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def _get_readme(dir_, gallery_conf, raise_error=True):
    extensions = ['.txt'] + sorted(gallery_conf['app'].config['source_suffix'])
    for ext in extensions:
        for fname in ('README', 'readme'):
            fpth = os.path.join(dir_, fname + ext)
            if os.path.isfile(fpth):
                return fpth
    if raise_error:
        raise ExtensionError(
            "Example directory {0} does not have a README file with one "
            "of the expected file extensions {1}. Please write one to "
            "introduce your gallery.".format(dir_, extensions))
    return None 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:15,代码来源:gen_rst.py

示例11: _get_image

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def _get_image():
    try:
        from PIL import Image
    except ImportError as exc:  # capture the error for the modern way
        try:
            import Image
        except ImportError:
            raise ExtensionError(
                'Could not import pillow, which is required '
                'to rescale images (e.g., for thumbnails): %s' % (exc,))
    return Image 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:13,代码来源:utils.py

示例12: test_default_config

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def test_default_config(sphinx_app_wrapper):
    """Test the default Sphinx-Gallery configuration is loaded

    if only the extension is added to Sphinx"""
    sphinx_app = sphinx_app_wrapper.create_sphinx_app()
    cfg = sphinx_app.config
    assert cfg.project == "Sphinx-Gallery <Tests>"
    # no duplicate values allowed The config is present already
    with pytest.raises(ExtensionError) as excinfo:
        sphinx_app.add_config_value('sphinx_gallery_conf', 'x', True)
    assert 'already present' in str(excinfo.value) 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:13,代码来源:test_gen_gallery.py

示例13: test_failing_examples_raise_exception

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def test_failing_examples_raise_exception(sphinx_app_wrapper):
    example_dir = os.path.join(sphinx_app_wrapper.srcdir,
                               'src')
    with codecs.open(os.path.join(example_dir, 'plot_3.py'), 'a',
                     encoding='utf-8') as fid:
        fid.write('raise SyntaxError')
    with pytest.raises(ExtensionError) as excinfo:
        sphinx_app_wrapper.build_sphinx_app()
    assert "Unexpected failing examples" in str(excinfo.value) 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:11,代码来源:test_gen_gallery.py

示例14: test_examples_not_expected_to_pass

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def test_examples_not_expected_to_pass(sphinx_app_wrapper):
    with pytest.raises(ExtensionError) as excinfo:
        sphinx_app_wrapper.build_sphinx_app()
    assert "expected to fail, but not failing" in str(excinfo.value) 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:6,代码来源:test_gen_gallery.py

示例15: test_junit

# 需要导入模块: from sphinx import errors [as 别名]
# 或者: from sphinx.errors import ExtensionError [as 别名]
def test_junit(sphinx_app, tmpdir):
    out_dir = sphinx_app.outdir
    junit_file = op.join(out_dir, 'sphinx-gallery', 'junit-results.xml')
    assert op.isfile(junit_file)
    with codecs.open(junit_file, 'r', 'utf-8') as fid:
        contents = fid.read()
    assert contents.startswith('<?xml')
    assert 'errors="0" failures="0"' in contents
    assert 'tests="%d"' % (N_TOT,) in contents
    assert 'local_module' not in contents  # it's not actually run as an ex
    assert 'expected example failure' in contents
    assert '<failure message' not in contents
    src_dir = sphinx_app.srcdir
    new_src_dir = op.join(str(tmpdir), 'src')
    shutil.copytree(src_dir, new_src_dir)
    del src_dir
    new_out_dir = op.join(new_src_dir, '_build', 'html')
    new_toctree_dir = op.join(new_src_dir, '_build', 'toctrees')
    passing_fname = op.join(new_src_dir, 'examples',
                            'plot_numpy_matplotlib.py')
    failing_fname = op.join(new_src_dir, 'examples', 'future',
                            'plot_future_imports_broken.py')
    shutil.move(passing_fname, passing_fname + '.temp')
    shutil.move(failing_fname, passing_fname)
    shutil.move(passing_fname + '.temp', failing_fname)
    with docutils_namespace():
        app = Sphinx(new_src_dir, new_src_dir, new_out_dir,
                     new_toctree_dir,
                     buildername='html', status=StringIO())
        # need to build within the context manager
        # for automodule and backrefs to work
        with pytest.raises(ExtensionError, match='Here is a summary of the '):
            app.build(False, [])
    junit_file = op.join(new_out_dir, 'sphinx-gallery', 'junit-results.xml')
    assert op.isfile(junit_file)
    with codecs.open(junit_file, 'r', 'utf-8') as fid:
        contents = fid.read()
    assert 'errors="0" failures="2"' in contents
    assert 'tests="2"' in contents  # this time we only ran the two stale files
    assert '<failure message="RuntimeError: Forcing' in contents
    assert 'Passed even though it was marked to fail' in contents 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:43,代码来源:test_full.py


注:本文中的sphinx.errors.ExtensionError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。