コード例 #1
0
def test_notebook_images_data_uri(gallery_conf):
    gallery_conf = gallery_conf.copy()
    gallery_conf['notebook_images'] = True
    target_dir = os.path.join(gallery_conf['src_dir'],
                              gallery_conf['gallery_dirs'])

    test_image = os.path.join(os.path.dirname(__file__), 'tinybuild',
                              '_static_nonstandard', 'demo.png')
    # For windows we need to copy this to tmpdir because if tmpdir and this
    # file are on different drives there is no relpath between them
    dest_dir = os.path.join(gallery_conf['src_dir'], '_static_nonstandard')
    os.mkdir(dest_dir)
    dest_image = os.path.join(dest_dir, 'demo.png')
    shutil.copyfile(test_image, dest_image)
    # Make into "absolute" path from source directory
    test_image_rel = os.path.relpath(dest_image, gallery_conf['src_dir'])
    test_image_abs = '/' + test_image_rel.replace(os.sep, '/')
    rst = textwrap.dedent("""\
    .. image:: {}
       :width: 100px
    """).format(test_image_abs)
    markdown = rst2md(rst, gallery_conf, target_dir, {})

    assert 'data' in markdown
    assert 'src="data:image/png;base64,' in markdown
    with open(test_image, 'rb') as test_file:
        data = base64.b64encode(test_file.read())
    assert data.decode('ascii') in markdown

    rst = textwrap.dedent("""\
    .. image:: /this/image/is/missing.png
       :width: 500px
    """)
    with pytest.raises(ExtensionError):
        rst2md(rst, gallery_conf, target_dir, {})
コード例 #2
0
def test_notebook_images_data_uri(gallery_conf):
    gallery_conf = gallery_conf.copy()
    gallery_conf['notebook_images'] = True
    target_dir = os.path.join(gallery_conf['src_dir'],
                              gallery_conf['gallery_dirs'])

    test_image = os.path.join(os.path.dirname(__file__), 'tinybuild',
                              '_static', 'demo.png')
    # Make into "absolute" path from source directory
    test_image_rel = os.path.relpath(test_image, gallery_conf['src_dir'])
    test_image_abs = '/' + test_image_rel.replace(os.sep, '/')
    rst = textwrap.dedent("""\
    .. image:: {}
       :width: 100px
    """).format(test_image_abs)
    markdown = rst2md(rst, gallery_conf, target_dir, {})

    assert 'data' in markdown
    assert 'src="data:image/png;base64,' in markdown
    with open(test_image, 'rb') as test_file:
        data = base64.b64encode(test_file.read())
    assert data.decode('ascii') in markdown

    rst = textwrap.dedent("""\
    .. image:: /this/image/is/missing.png
       :width: 500px
    """)
    with pytest.raises(ExtensionError):
        rst2md(rst, gallery_conf, target_dir, {})
コード例 #3
0
def test_latex_conversion():
    """Latex parsing from rst into Jupyter Markdown"""
    double_inline_rst = r":math:`T<0` and :math:`U>0`"
    double_inline_jmd = r"$T<0$ and $U>0$"
    assert double_inline_jmd == rst2md(double_inline_rst)

    align_eq = r"""
.. math::
   \mathcal{H} &= 0 \\
   \mathcal{G} &= D"""

    align_eq_jmd = r"""
\begin{align}\mathcal{H} &= 0 \\
   \mathcal{G} &= D\end{align}"""
    assert align_eq_jmd == rst2md(align_eq)
コード例 #4
0
def test_latex_conversion():
    """Latex parsing from rst into Jupyter Markdown"""
    double_inline_rst = r":math:`T<0` and :math:`U>0`"
    double_inline_jmd = r"$T<0$ and $U>0$"
    assert double_inline_jmd == rst2md(double_inline_rst)

    align_eq = r"""
.. math::
   \mathcal{H} &= 0 \\
   \mathcal{G} &= D"""

    align_eq_jmd = r"""
\begin{align}\mathcal{H} &= 0 \\
   \mathcal{G} &= D\end{align}"""
    assert align_eq_jmd == rst2md(align_eq)
コード例 #5
0
    def find_cell_content(self, lines):
        """Parse cell till its end and set content, lines_to_next_cell.
        Return the position of next cell start"""
        cell_end_marker, next_cell_start, explicit_eoc = \
            self.find_cell_end(lines)

        if next_cell_start < len(lines) and \
                _BLANK_LINE.match(lines[next_cell_start]):
            next_cell_start += 1

        # Metadata to dict
        cell_start = 0
        if self.cell_type == 'markdown':
            if self.markdown_marker in ['"""', "'''"]:
                # Remove the triple quotes
                if lines[0].strip() == self.markdown_marker:
                    cell_start = 1
                else:
                    lines[0] = lines[0][3:]
                if not explicit_eoc:
                    last = lines[cell_end_marker - 1]
                    lines[cell_end_marker - 1] = \
                        last[:last.rfind(self.markdown_marker)]
            if self.twenty_hash.match(self.markdown_marker):
                cell_start = 1
        else:
            self.metadata = {}

        # Cell content
        source = lines[cell_start:cell_end_marker]

        if self.cell_type == 'code' and self.comment_magics:
            uncomment_magic(source, self.language or self.default_language)

        if self.cell_type == 'markdown' and source:
            if self.markdown_marker.startswith(self.comment):
                source = uncomment(source, self.comment)
                if self.rst2md:
                    if rst2md:
                        source = rst2md('\n'.join(source)).splitlines()
                    else:
                        raise ImportError('Could not import rst2md '
                                          'from sphinx_gallery.notebook')

        self.content = source

        self.lines_to_next_cell = count_lines_to_next_cell(
            cell_end_marker, next_cell_start, len(lines), explicit_eoc)

        return next_cell_start
コード例 #6
0
    def find_cell_content(self, lines):
        """Parse cell till its end and set content, lines_to_next_cell.
        Return the position of next cell start"""
        cell_end_marker, next_cell_start, explicit_eoc = self.find_cell_end(
            lines)

        # Metadata to dict
        cell_start = 0
        if self.cell_type == "markdown":
            if self.markdown_marker in ['"""', "'''"]:
                # Remove the triple quotes
                if lines[0].strip() == self.markdown_marker:
                    cell_start = 1
                else:
                    lines[0] = lines[0][3:]
                if not explicit_eoc:
                    last = lines[cell_end_marker - 1]
                    lines[cell_end_marker -
                          1] = last[:last.rfind(self.markdown_marker)]
            if self.twenty_hash.match(self.markdown_marker):
                cell_start = 1
        else:
            self.metadata = {}

        # Cell content
        source = lines[cell_start:cell_end_marker]
        self.org_content = copy(source)

        if self.cell_type == "code" and self.comment_magics:
            uncomment_magic(source, self.language or self.default_language)

        if self.cell_type == "markdown" and source:
            if self.markdown_marker.startswith(self.comment):
                source = uncomment(source, self.comment)
            if self.rst2md:
                if rst2md:
                    source = rst2md("\n".join(source)).splitlines()
                else:
                    raise ImportError(
                        "Could not import rst2md from sphinx_gallery.notebook"
                    )  # pragma: no cover

        self.content = source

        self.lines_to_next_cell = count_lines_to_next_cell(
            cell_end_marker, next_cell_start, len(lines), explicit_eoc)

        return next_cell_start
コード例 #7
0
def test_convert(gallery_conf):
    """Test ReST conversion"""
    rst = """hello

.. contents::
    :local:

This is :math:`some` math :math:`stuff`.

.. note::
    Interpolation is a linear operation that can be performed also on
    Raw and Epochs objects.

.. warning::
    Go away

For more details on interpolation see the page :ref:`channel_interpolation`.
.. _foo: bar

.. image:: foobar
  :alt: me
  :whatever: you
  :width: 200px
  :class: img_class
"""

    markdown = """hello

This is $some$ math $stuff$.

<div class="alert alert-info"><h4>Note</h4><p>Interpolation is a linear operation that can be performed also on
    Raw and Epochs objects.</p></div>

<div class="alert alert-danger"><h4>Warning</h4><p>Go away</p></div>

For more details on interpolation see the page `channel_interpolation`.

<img src="file://foobar" alt="me" whatever="you" width="200px" class="img_class">
"""  # noqa
    assert rst2md(rst, gallery_conf, "", {}) == markdown
コード例 #8
0
def test_notebook_images_prefix(gallery_conf, rst_path, md_path,
                                prefix_enabled):
    if prefix_enabled:
        gallery_conf = gallery_conf.copy()
        gallery_conf['notebook_images'] = "https://example.com/"
    target_dir = os.path.join(gallery_conf['src_dir'],
                              gallery_conf['gallery_dirs'])

    rst = textwrap.dedent("""\
    .. image:: {}
       :alt: My Image
       :width: 100px
       :height: 200px
       :class: image
    """).format(rst_path)
    markdown = rst2md(rst, gallery_conf, target_dir, {})

    assert 'src="{}"'.format(md_path) in markdown
    assert 'alt="My Image"' in markdown
    assert 'width="100px"' in markdown
    assert 'height="200px"' in markdown
    assert 'class="image"' in markdown
コード例 #9
0
def test_convert():
    """Test ReST conversion"""
    rst = """hello

.. contents::
    :local:

This is :math:`some` math :math:`stuff`.

.. note::
    Interpolation is a linear operation that can be performed also on
    Raw and Epochs objects.

.. warning::
    Go away

For more details on interpolation see the page :ref:`channel_interpolation`.
.. _foo: bar

.. image:: foobar
  :alt: me
  :whatever: you
"""

    markdown = """hello

This is $some$ math $stuff$.

<div class="alert alert-info"><h4>Note</h4><p>Interpolation is a linear operation that can be performed also on
    Raw and Epochs objects.</p></div>

<div class="alert alert-danger"><h4>Warning</h4><p>Go away</p></div>

For more details on interpolation see the page `channel_interpolation`.

![me](foobar)
"""  # noqa
    assert rst2md(rst) == markdown
コード例 #10
0
def test_convert():
    """Test ReST conversion"""
    rst = """hello

.. contents::
    :local:

This is :math:`some` math :math:`stuff`.

.. note::
    Interpolation is a linear operation that can be performed also on
    Raw and Epochs objects.

.. warning::
    Go away

For more details on interpolation see the page :ref:`channel_interpolation`.
.. _foo: bar

.. image:: foobar
  :alt: me
  :whatever: you
"""

    markdown = """hello

This is $some$ math $stuff$.

<div class="alert alert-info"><h4>Note</h4><p>Interpolation is a linear operation that can be performed also on
    Raw and Epochs objects.</p></div>

<div class="alert alert-danger"><h4>Warning</h4><p>Go away</p></div>

For more details on interpolation see the page `channel_interpolation`.

![me](foobar)
"""  # noqa
    assert rst2md(rst) == markdown
コード例 #11
0
def test_headings():
    rst = textwrap.dedent("""\
    =========
    Heading 1
    =========

    Heading 2
    =========

    =============
     Heading 1-2
    =============

    Heading 3
    ---------

    =============
    Not a Heading
    -------------
    Mismatch top and bottom

    Not another heading
    -=-=-=-=-=-=-=-=-=-
    Multiple characters

    -------
     Bad heading but okay
    -------------
    Over and under mismatch, not rendered and warning raised by Sphinx

    Another bad heading, but passable
    ^^^^^^^^^^^^^^^^^^^^^
    Too short, warning raised but is rendered by Sphinx

    A
    *

    BC
    **

    Some text
    And then a heading
    ------------------
    Not valid with no blank line above

    =======================
           Centered
    =======================

    ------------------------

    ------------------------
    Blank heading above.

    {0}
    ====================
      White space above
    ====================

    """).format('            ')
    # add whitespace afterward to avoid editors from automatically
    # removing the whitespace on save

    heading_level_counter = count(start=1)
    heading_levels = defaultdict(lambda: next(heading_level_counter))
    text = rst2md(rst, {}, "", heading_levels)

    assert text.startswith("# Heading 1\n")
    assert "\n## Heading 2\n" in text
    assert "\n# Heading 1-2\n" in text
    assert "\n### Heading 3\n" in text
    assert "# Not a Heading" not in text
    assert "# Not another Heading" not in text
    assert "\n#### Bad heading but okay\n" in text
    assert "\n##### Another bad heading, but passable\n" in text
    assert "\n###### A\n" in text
    assert "\n###### BC\n" in text
    assert "# And then a heading\n" not in text
    assert "\n# Centered\n" in text
    assert "#\nBlank heading above." not in text
    assert "# White space above\n" in text