Exemple #1
0
    def test_rst2html_png(self):
        fLOG(__file__,
             self._testMethodName,
             OutputPrint=__name__ == "__main__")

        if is_travis_or_appveyor() in ('travis', 'appveyor'):
            # It requires latex.
            return

        temp = get_temp_folder(__file__, "temp_rst2html_png")
        rst = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data",
                           "hermionne.rst")
        with open(rst, "r", encoding="utf-8") as f:
            content = f.read()

        text = rst2html(content)

        ji = os.path.join(temp, "out.html")
        with open(ji, "w", encoding="utf-8") as f:
            f.write(text)
        text2 = rst2html(content, layout="sphinx")
        ji = os.path.join(temp, "out_sphinx.html")
        with open(ji, "w", encoding="utf-8") as f:
            f.write(text)
        self.assertTrue(len(text2) > len(text))
    def test_collapse_legend(self):
        from docutils import nodes as skip_

        content = """
                    before

                    .. collapse::
                        :legend: ABC/abcd

                        this code shoud appear___

                    after
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        # RST
        html = rst2html(content, writer="rst", keep_warnings=True)

        t1 = ":legend: ABC/abcd"
        if t1 not in html:
            raise Exception(html)

        t1 = ":hide:"
        if t1 in html:
            raise Exception(html)

        # HTML
        html = rst2html(content, writer="custom", keep_warnings=True)

        t1 = "b.innerText = 'abcd';"
        if t1 not in html:
            raise Exception(html)
    def test_rst2html_png(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        if is_travis_or_appveyor() in ('travis', 'appveyor'):
            # It requires latex.
            return

        temp = get_temp_folder(__file__, "temp_rst2html_png")
        rst = os.path.join(os.path.abspath(
            os.path.dirname(__file__)), "data", "hermionne.rst")
        with open(rst, "r", encoding="utf-8") as f:
            content = f.read()

        text = rst2html(content)

        ji = os.path.join(temp, "out.html")
        with open(ji, "w", encoding="utf-8") as f:
            f.write(text)
        text2 = rst2html(content, layout="sphinx")
        ji = os.path.join(temp, "out_sphinx.html")
        with open(ji, "w", encoding="utf-8") as f:
            f.write(text)
        self.assertTrue(len(text2) > len(text))
    def test_autosignature_path_option(self):
        newstring = [
            ".. autosignature:: pandas.core.frame.DataFrame", "    :path: name"
        ]
        newstring = "\n".join(newstring)
        res = rst2html(newstring, writer="rst", layout="sphinx")
        self.assertIn(':py:class:`DataFrame <pandas.core.frame.DataFrame>',
                      res)
        self.assertNotIn(
            ':py:class:`pandas.DataFrame <pandas.core.frame.DataFrame>', res)
        self.assertNotIn(':py:class:`pandas.core.frame.DataFrame', res)

        newstring = [
            ".. autosignature:: pandas.core.frame.DataFrame", "    :path: full"
        ]
        newstring = "\n".join(newstring)
        res = rst2html(newstring, writer="rst", layout="sphinx")
        self.assertNotIn('`DataFrame <pandas.core', res)
        self.assertNotIn('`pandas.DataFrame <pandas.core', res)

        newstring = [".. autosignature:: pandas.core.frame.DataFrame"]
        newstring = "\n".join(newstring)
        res = rst2html(newstring, writer="rst", layout="sphinx")
        self.assertIn(
            ':py:class:`pandas.DataFrame <pandas.core.frame.DataFrame>` (*self*',
            res)
    def test_md_only(self):
        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    .. only:: html

                        only for html

                    .. only:: md

                        only for md

                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        tives = [("cmdref", CmdRef, cmdref_node, visit_cmdref_node,
                  depart_cmdref_node)]

        text = rst2html(
            content,  # fLOG=fLOG,
            writer="md",
            keep_warnings=True,
            directives=tives,
            extlinks={'issue': ('http://%s', '_issue_')})

        temp = get_temp_folder(__file__, "temp_only")
        with open(os.path.join(temp, "out_cmdref.md"), "w",
                  encoding="utf8") as f:
            f.write(text)

        t1 = "only for md"
        if t1 not in text:
            raise Exception(text)
        t1 = "only for html"
        if t1 in text:
            raise Exception(text)

        text = rst2html(
            content,  # fLOG=fLOG,
            writer="html",
            keep_warnings=True,
            directives=tives,
            extlinks={'issue': ('http://%s', '_issue_')})

        temp = get_temp_folder(__file__, "temp_only")
        with open(os.path.join(temp, "out_cmdref.html"), "w",
                  encoding="utf8") as f:
            f.write(text)

        t1 = "only for md"
        if t1 in text:
            raise Exception(text)
        t1 = "only for html"
        if t1 not in text:
            raise Exception(text)
    def test_docstyle(self):
        fLOG(__file__,
             self._testMethodName,
             OutputPrint=__name__ == "__main__")

        extensions = get_default_standard_extensions(
        ) + get_default_extensions()
        extensions = [
            _ for _ in extensions
            if "matplotlib" not in _ and "images" not in _ and "IPython" not in
            _ and "nbsphinx" not in _ and "jupyter" not in _
            and "jsdemo" not in _ and "inheritance_diagram" not in _
        ]
        external_docnames = [
            "_modules/src/pyquickhelper/helpgen/_fake_function_to_documentation"
        ]
        funcs = [None, f1, f2, f3, f4, f5, f6]

        exps = [
            " * **a** -- parameter a", ":param      a:", ":param a:",
            "a: parameter a"
        ]

        for i in range(1, 7):
            content = ".. autofunction:: pyquickhelper.helpgen._fake_function_to_documentation.f{0}".format(
                i)
            text = rst2html(
                content,  # fLOG=fLOG,
                writer="rst",
                keep_warnings=True,
                layout="sphinx",
                extensions=extensions,
                external_docnames=external_docnames)
            filt = list(filter(lambda s: s in text, exps))
            if len(filt) == 0:
                doc = funcs[i].__doc__
                rows = doc.split("\n")
                conv = private_migrating_doxygen_doc(rows, 0, "f%d" % i)
                content = "\n".join(conv)
                text2 = rst2html(
                    content,  # fLOG=fLOG,
                    writer="rst",
                    keep_warnings=True,
                    layout="sphinx",
                    extensions=extensions,
                    external_docnames=external_docnames)
                filt = list(filter(lambda s: s in text2, exps))
                if len(filt) == 0:
                    fLOG("\n---- ORIGINAL", i, "\n", funcs[i].__doc__,
                         "\n---- RESULT", i, "\n", text, "\n**** CONVERTED\n",
                         content, "\n**** FINAL", i, "\n", text2,
                         "\n*************** END")
                else:
                    rep = text2.strip("\n ")
                    if not rep.startswith(".."):
                        raise Exception("\n" + text2)
    def test_rst_reference(self):
        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    :py:class:`pyquickhelper.sphinxext.sphinx_rst_builder.RstBuilder`

                    :py:class:`Renamed <pyquickhelper.sphinxext.sphinx_rst_builder.RstBuilder>`
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        tives = [("cmdref", CmdRef, cmdref_node, visit_cmdref_node,
                  depart_cmdref_node)]

        text = rst2html(
            content,  # fLOG=fLOG,
            writer="rst",
            keep_warnings=True,
            layout='sphinx',
            directives=tives,
            extlinks={'issue': ('http://%s', '_issue_')})

        temp = get_temp_folder(__file__, "temp_only")
        with open(os.path.join(temp, "out_cmdref.rst"), "w",
                  encoding="utf8") as f:
            f.write(text)

        t1 = "pyquickhelper.sphinxext.sphinx_rst_builder.RstBuilder"
        if t1 not in text:
            raise Exception(text)
        t1 = ":py:class:`Renamed"
        if t1 not in text:
            raise Exception(text)

        text = rst2html(
            content,  # fLOG=fLOG,
            writer="html",
            keep_warnings=True,
            layout='sphinx',
            directives=tives,
            extlinks={'issue': ('http://%s', '_issue_')})

        temp = get_temp_folder(__file__, "temp_only")
        with open(os.path.join(temp, "out_cmdref.rst"), "w",
                  encoding="utf8") as f:
            f.write(text)

        t1 = "pyquickhelper.sphinxext.sphinx_rst_builder.RstBuilder"
        if t1 not in text:
            raise Exception(text)
        t1 = "<p>Renamed</p>"
        if t1 not in text:
            raise Exception(text)
Exemple #8
0
    def test_postcontents(self):
        """
        this test also test the extension runpython
        """
        fLOG(__file__,
             self._testMethodName,
             OutputPrint=__name__ == "__main__")

        content = TestPostContentsExtension.content.replace(
            "contents", "postcontents")

        # 1

        rst = rst2html(
            content,  # fLOG=fLOG,
            # layout="sphinx",
            writer="rst",
            keep_warnings=True)

        if "* :ref:`title-outside`" in rst:
            raise Exception("\n" + rst)
        if "* :ref:`title-inside`" in rst:
            raise Exception("\n" + rst)

        # 2

        rst = rst2html(
            content,  # fLOG=fLOG,
            layout="sphinx",
            writer="html",
            keep_warnings=True)

        temp = get_temp_folder(__file__, "temp_postcontents")
        with open(os.path.join(temp, "postcontents.html"),
                  "w",
                  encoding="utf-8") as f:
            f.write(rst)
        if '<li><p><a class="reference internal" href="#title-inside2" title="Title inside2">Title inside2</a></p></li>' not in rst:
            raise Exception("\n" + rst)

        # 3

        rst = rst2html(
            content,  # fLOG=fLOG,
            layout="sphinx",
            writer="rst",
            keep_warnings=True)

        if "* :ref:`title-outside`" not in rst:
            raise Exception(rst)
        if "* :ref:`title-inside`" not in rst:
            raise Exception(rst)
    def test_rst_only(self):
        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    .. only:: html

                        only for html

                    .. only:: rst

                        only for rst

                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        tives = [("cmdref", CmdRef, cmdref_node,
                  visit_cmdref_node, depart_cmdref_node)]

        text = rst2html(content,  # fLOG=fLOG,
                        writer="rst", keep_warnings=True,
                        directives=tives, extlinks={'issue': ('http://%s', '_issue_')})

        temp = get_temp_folder(__file__, "temp_only")
        with open(os.path.join(temp, "out_cmdref.rst"), "w", encoding="utf8") as f:
            f.write(text)

        t1 = "only for rst"
        if t1 not in text:
            raise Exception(text)
        t1 = "only for html"
        if t1 in text:
            raise Exception(text)

        text = rst2html(content,  # fLOG=fLOG,
                        writer="html", keep_warnings=True,
                        directives=tives, extlinks={'issue': ('http://%s', '_issue_')})

        temp = get_temp_folder(__file__, "temp_only")
        with open(os.path.join(temp, "out_cmdref.rst"), "w", encoding="utf8") as f:
            f.write(text)

        t1 = "only for rst"
        if t1 in text:
            raise Exception(text)
        t1 = "only for html"
        if t1 not in text:
            raise Exception(text)
Exemple #10
0
    def test_tocdelay1(self):
        content = """
                    .. tocdelay::

                        blog/2015/2015-04-05_first_blogpost
                    """.replace("                    ", "")

        try:
            rst2html(content,
                     layout="sphinx",
                     writer="rst",
                     keep_warnings=True)
        except ValueError as e:
            self.assertIn("No found document", str(e))
    def test_blogpost_agg(self):

        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    before

                    .. blogpostagg::
                        :title: first blog post
                        :keywords: keyw
                        :categories: cat1
                        :date: 2018-03-24

                        this code shoud appear___.

                        this one not sure.

                    after
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        tives = [("blogpostagg", BlogPostDirectiveAgg, blogpostagg_node,
                  visit_blogpostagg_node, depart_blogpostagg_node)]

        text = rst2html(content,  # fLOG=fLOG,
                        layout="sphinx", writer="html", keep_warnings=True,
                        directives=tives, extlinks={'issue': ('http://%s', '_issue_')})

        temp = get_temp_folder(__file__, "temp_blogagg_ext")
        with open(os.path.join(temp, "out_blog.html"), "w", encoding="utf8") as f:
            f.write(text)

        self.assertIn('<font size="5">2018-03-24</font></p>', text)

        text = rst2html(content,  # fLOG=fLOG,
                        layout="sphinx", writer="rst", keep_warnings=True,
                        directives=tives, extlinks={'issue': ('http://%s', '_issue_')})

        with open(os.path.join(temp, "out_blog.rst"), "w", encoding="utf8") as f:
            f.write(text)

        self.assertIn('this code shoud appear___', text)
        self.assertIn('==========', text)
        self.assertIn(':bigger:`2018-03-24`', text)
        self.assertIn('after', text)
    def test_docstyle(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        extensions = get_default_standard_extensions() + get_default_extensions()
        extensions = [_ for _ in extensions if "matplotlib" not in _ and
                      "images" not in _ and "IPython" not in _ and
                      "nbsphinx" not in _ and "jupyter" not in _ and
                      "jsdemo" not in _ and
                      "inheritance_diagram" not in _]
        external_docnames = [
            "_modules/src/pyquickhelper/helpgen/_fake_function_to_documentation"]
        funcs = [None, f1, f2, f3, f4, f5, f6]

        exps = [" * **a** -- parameter a",
                ":param      a:",
                ":param a:",
                "a: parameter a"]

        for i in range(1, 7):
            content = ".. autofunction:: pyquickhelper.helpgen._fake_function_to_documentation.f{0}".format(
                i)
            text = rst2html(content,  # fLOG=fLOG,
                            writer="rst", keep_warnings=True,
                            layout="sphinx", extensions=extensions,
                            external_docnames=external_docnames)
            filt = list(filter(lambda s: s in text, exps))
            if len(filt) == 0:
                doc = funcs[i].__doc__
                rows = doc.split("\n")
                conv = private_migrating_doxygen_doc(rows, 0, "f%d" % i)
                content = "\n".join(conv)
                text2 = rst2html(content,  # fLOG=fLOG,
                                 writer="rst", keep_warnings=True,
                                 layout="sphinx", extensions=extensions,
                                 external_docnames=external_docnames)
                filt = list(filter(lambda s: s in text2, exps))
                if len(filt) == 0:
                    fLOG("\n---- ORIGINAL", i, "\n", funcs[i].__doc__,
                         "\n---- RESULT", i, "\n", text,
                         "\n**** CONVERTED\n", content,
                         "\n**** FINAL", i, "\n", text2,
                         "\n*************** END")
                else:
                    rep = text2.strip("\n ")
                    if not rep.startswith(".."):
                        raise Exception("\n" + text2)
Exemple #13
0
    def test_blogpost_agg(self):

        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    before

                    .. blogpostagg::
                        :title: first blog post
                        :keywords: keyw
                        :categories: cat1
                        :date: 2018-03-24

                        this code shoud appear___.

                        this one not sure.

                    after
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        tives = [("blogpostagg", BlogPostDirectiveAgg, blogpostagg_node,
                  visit_blogpostagg_node, depart_blogpostagg_node)]

        text = rst2html(content,  # fLOG=fLOG,
                        layout="sphinx", writer="html", keep_warnings=True,
                        directives=tives, extlinks={'issue': ('http://%s', '_issue_')})

        temp = get_temp_folder(__file__, "temp_blogagg_ext")
        with open(os.path.join(temp, "out_blog.html"), "w", encoding="utf8") as f:
            f.write(text)

        self.assertIn('<font size="5">2018-03-24</font></p>', text)

        text = rst2html(content,  # fLOG=fLOG,
                        layout="sphinx", writer="rst", keep_warnings=True,
                        directives=tives, extlinks={'issue': ('http://%s', '_issue_')})

        with open(os.path.join(temp, "out_blog.rst"), "w", encoding="utf8") as f:
            f.write(text)

        self.assertIn('this code shoud appear___', text)
        self.assertIn('==========', text)
        self.assertIn(':bigger:`2018-03-24`', text)
        self.assertIn('after', text)
Exemple #14
0
    def test_parse_readme_cb(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        fold = os.path.dirname(os.path.abspath(__file__))
        readme = os.path.join(fold, "data", "README.rst")
        fLOG(readme)
        assert os.path.exists(readme)
        with open(readme, "r", encoding="utf8") as f:
            content = f.read()
        r = parse_markdown(content)
        if "<p>.. _l-README:</p>" not in str(r):
            m = [ord(c) for c in content]
            m = ",".join(str(_) for _ in m[:20])
            raise Exception("IN\n{0}\nOUT:{1}".format(m, str(r)))

        ht = rst2html(content)
        # fLOG(ht)
        assert len(ht) > 0

        spl = content.split("\n")
        r = list(yield_sphinx_only_markup_for_pipy(spl))
        assert len(r) == len(spl)
    def test_md_reference(self):
        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    :py:class:`pyquickhelper.sphinxext.sphinx_md_builder.MdBuilder`

                    :py:class:`Renamed <pyquickhelper.sphinxext.sphinx_md_builder.MdBuilder>`
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        tives = [("cmdref", CmdRef, cmdref_node,
                  visit_cmdref_node, depart_cmdref_node)]

        text = rst2html(content,  # fLOG=fLOG,
                        writer="md", keep_warnings=True, layout='sphinx',
                        directives=tives, extlinks={'issue': ('http://%s', '_issue_')})

        temp = get_temp_folder(__file__, "temp_only")
        with open(os.path.join(temp, "out_cmdref.md"), "w", encoding="utf8") as f:
            f.write(text)

        t1 = "pyquickhelper.sphinxext.sphinx_md_builder.MdBuilder"
        if t1 not in text:
            raise Exception(text)
        t1 = "[Renamed]("
        if t1 not in text:
            raise Exception(text)
    def test_runpython_image(self):
        """
        this test also test the extension runpython
        """
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        from docutils import nodes

        class runpythonthis_node(nodes.Structural, nodes.Element):
            pass

        class RunPythonThisDirective (RunPythonDirective):
            runpython_class = runpythonthis_node

        def visit_rp_node(self, node):
            self.body.append("<p><b>visit_rp_node</b></p>")

        def depart_rp_node(self, node):
            self.body.append("<p><b>depart_rp_node</b></p>")

        if "enable_disabled_documented_pieces_of_code" in sys.__dict__:
            raise Exception("this case shoud not be")

        temp = get_temp_folder(__file__, "temp_runpython_image")
        content = """
                    test a directive
                    ================

                    .. runpythonthis::
                        :rst:
                        :showcode:

                        import matplotlib.pyplot as plt
                        fig, ax = plt.subplots(1, 1, figsize=(4, 4))
                        ax.plot([0, 1], [0, 1], '--')
                        if __WD__ is None:
                            raise Exception(__WD__)
                        fig.savefig("__FOLD__/oo.png")

                        text = ".. image:: oo.png\\n    :width: 200px"
                        print(text)

                    """.replace("                    ", "").replace("__FOLD__", temp.replace("\\", "/"))
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        tives = [("runpythonthis", RunPythonThisDirective, runpythonthis_node,
                  visit_rp_node, depart_rp_node)]

        html = rst2html(content,  # fLOG=fLOG,
                        writer="custom", keep_warnings=True,
                        directives=tives)

        with open(os.path.join(temp, "out.html"), "w", encoding="utf8") as f:
            f.write(html)
        img = os.path.join(temp, "oo.png")
        self.assertExists(img)
Exemple #17
0
    def test_param_sphinx(self):
        fLOG(__file__,
             self._testMethodName,
             OutputPrint=__name__ == "__main__")

        from docutils import nodes as skip_

        content = """
                    Addition 4

                    :param a: parameter a
                    :param b: parameter b

                    :returns: ``a+b``
                    """.replace("                    ", "")
        html = rst2html(
            content,  # fLOG=fLOG,
            writer="custom",
            keep_warnings=True,
            directives=None,
            layout="sphinx")

        temp = get_temp_folder(__file__, "temp_param_sphinx")
        with open(os.path.join(temp, "out_param_sphinx.html"),
                  "w",
                  encoding="utf8") as f:
            f.write(html)

        t1 = ":param a:"
        if t1 in html:
            raise Exception(html)
    def test_autosignature_class_onemethod2(self):
        this = os.path.abspath(os.path.dirname(__file__))
        data = os.path.join(this, "datadoc")
        with sys_path_append(data):

            newstring = ["AAAAAAAAAAAAAAAA",
                         "",
                         ".. autosignature:: exdocassert2.onefunction",
                         "",
                         "CCCCCCCCCCCCCCCC"]
            newstring = "\n".join(newstring)
            htmls = rst2html(newstring, layout="sphinx_body")

        self.assertIn("CCCCCCCCCCCCCCCC", htmls)

        html = htmls.split("CCCCCCCCCCCCCCCC")
        if "onefunction" not in html[0]:
            raise Exception(html[0])
        if "<strong>a</strong>" in html[0]:
            raise Exception(html[0])
        if ":param a:" in html[0]:
            raise Exception(html[0])
        if "`" in html[0]:
            raise Exception(html[0])
        if "if a and b have different types" in html[0]:
            raise Exception(html[0])
        if "Return the addition of" not in html[0]:
            raise Exception(html[0])
        if "Second line should be aligned." not in html[0]:
            raise Exception(html[0])
        if "<p>Return the addition of" not in html[0]:
            raise Exception(html[0])
        if "should be aligned.</p>" not in html[0]:
            raise Exception(html[0])
    def test_runpython_numpy(self):
        """
        this test also test the extension runpython
        """
        fLOG(__file__,
             self._testMethodName,
             OutputPrint=__name__ == "__main__")

        from docutils import nodes

        if "enable_disabled_documented_pieces_of_code" in sys.__dict__:
            raise Exception("this case shoud not be")

        content = """
                    test a directive
                    ================

                    .. runpythonthis::
                        :setsysvar:
                        :rst:
                        :showcode:
                        :numpy_precision: 2

                        import numpy
                        print(numpy.array([1.123456789, 1.987654321]))
                    """.replace("                    ", "")

        html = rst2html(
            content,  # fLOG=fLOG,
            writer="rst",
            keep_warnings=True)
        if "[1.12 1.99]" not in html:
            raise Exception(html)
Exemple #20
0
    def test_latex_title(self):
        from docutils import nodes as skip_

        content = """

                    title1
                    ======

                    title2
                    ======

                    title3
                    ++++++

                    title4
                    ******

                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        text = rst2html(
            content,  # fLOG=fLOG,
            writer="elatex",
            keep_warnings=False,
            layout='sphinx',
            extlinks={'issue': ('http://%s', '_issue_')})

        self.assertIn("\\chapter{title2}", text)
        self.assertIn("\\section{title3}", text)
        temp = get_temp_folder(__file__, "temp_latex_title")
        with open(os.path.join(temp, "out_md_title.tex"), "w",
                  encoding="utf8") as f:
            f.write(text)
    def test_autosignature_class_onemethod2(self):
        this = os.path.abspath(os.path.dirname(__file__))
        data = os.path.join(this, "datadoc")
        with sys_path_append(data):

            newstring = [
                "AAAAAAAAAAAAAAAA", "",
                ".. autosignature:: exdocassert2.onefunction", "",
                "CCCCCCCCCCCCCCCC"
            ]
            newstring = "\n".join(newstring)
            htmls = rst2html(newstring, layout="sphinx_body")

        self.assertIn("CCCCCCCCCCCCCCCC", htmls)

        html = htmls.split("CCCCCCCCCCCCCCCC")
        if "onefunction" not in html[0]:
            raise Exception(html[0])
        if "<strong>a</strong>" in html[0]:
            raise Exception(html[0])
        if ":param a:" in html[0]:
            raise Exception(html[0])
        if "`" in html[0]:
            raise Exception(html[0])
        if "if a and b have different types" in html[0]:
            raise Exception(html[0])
        if "Return the addition of" not in html[0]:
            raise Exception(html[0])
        if "Second line should be aligned." not in html[0]:
            raise Exception(html[0])
        if "<p>Return the addition of" not in html[0]:
            raise Exception(html[0])
        if "should be aligned.</p>" not in html[0]:
            raise Exception(html[0])
    def test_param_sphinx(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        from docutils import nodes as skip_

        content = """
                    Addition 4

                    :param a: parameter a
                    :param b: parameter b

                    :returns: ``a+b``
                    """.replace("                    ", "")
        html = rst2html(content,  # fLOG=fLOG,
                        writer="custom", keep_warnings=True,
                        directives=None, layout="sphinx")

        temp = get_temp_folder(__file__, "temp_param_sphinx")
        with open(os.path.join(temp, "out_param_sphinx.html"), "w", encoding="utf8") as f:
            f.write(html)

        t1 = ":param a:"
        if t1 in html:
            raise Exception(html)
    def test_md_image_target(self):

        temp = get_temp_folder(__file__, "temp_md_image_target")
        root = os.path.abspath(os.path.dirname(__file__))
        img1 = os.path.join(root, "data", "image", "im.png")
        content = """
                    .. image:: {0}
                        :target: https://github.com/sdpython
                        :width: 200
                        :alt: alternative1
                    """.replace("                    ", "").format(img1).replace("\\", "/")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        text = rst2html(content,  # fLOG=fLOG,
                        writer="md", keep_warnings=False, layout='sphinx',
                        extlinks={'issue': ('http://%s', '_issue_')},
                        md_image_dest=temp)

        text = text.replace("\r", "")
        self.assertIn('![alternative1]', text)
        self.assertIn('=200x', text)
        self.assertIn("![alternative1](5cf2985161e8ba56d893.png =200x)", text)
        self.assertExists(os.path.join(temp, '5cf2985161e8ba56d893.png'))
        with open(os.path.join(temp, "md_image.md"), "w", encoding="utf8") as f:
            f.write(text)
    def test_md_title(self):
        from docutils import nodes as skip_

        content = """

                    title1
                    ======

                    title2
                    ======

                    title3
                    ++++++

                    title4
                    ******

                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        text = rst2html(content,  # fLOG=fLOG,
                        writer="md", keep_warnings=False, layout='sphinx',
                        extlinks={'issue': ('http://%s', '_issue_')})

        self.assertIn("# title1", text)
        self.assertIn("# title2", text)
        self.assertIn("## title3", text)
        self.assertIn("### title4", text)
        temp = get_temp_folder(__file__, "temp_md_title")
        with open(os.path.join(temp, "out_md_title.md"), "w", encoding="utf8") as f:
            f.write(text)
    def test_autosignature_class_static_method(self):
        this = os.path.abspath(os.path.dirname(__file__))
        data = os.path.join(this, "datadoc")
        with sys_path_append(data):

            obj = import_object("exsig.clex.static_method", "staticmethod")
            self.assertTrue(obj is not None)

            newstring = ["AAAAAAAAAAAAAAAA",
                         "",
                         ".. autosignature:: exsig.clex.static_method",
                         "",
                         "CCCCCCCCCCCCCCCC"]
            newstring = "\n".join(newstring)
            htmls = rst2html(newstring, layout="sphinx_body")

        self.assertIn("CCCCCCCCCCCCCCCC", htmls)

        html = htmls.split("CCCCCCCCCCCCCCCC")
        if "static_method" not in html[0]:
            raise Exception(html[0])
        if "<strong>a</strong>" in html[0]:
            raise Exception(html[0])
        if ":param a:" in html[0]:
            raise Exception(html[0])
        if "`" in html[0]:
            raise Exception(html[0])
        if "if a and b have different types" in html[0]:
            raise Exception(html[0])
        if "Return the static addition of" not in html[0]:
            raise Exception(html[0])
        if "<p>Return the static addition of" not in html[0]:
            raise Exception(html[0])
    def test_doc_page(self):
        temp = get_temp_folder(__file__, "temp_doc_page")
        preamble = TestDocPage.preamble + TestDocPage.custom_preamble
        this = os.path.abspath(os.path.dirname(__file__))
        rst = os.path.join(this, "..", "..", "_doc", "sphinxdoc", "source",
                           "documentation_example.rst")
        content = self.read_file(rst)

        writer = 'html'
        ht = rst2html(content,
                      writer=writer,
                      layout="sphinx",
                      keep_warnings=True,
                      imgmath_latex_preamble=preamble,
                      outdir=temp,
                      load_bokeh=True,
                      epkg_dictionary={
                          'pep8': 'https://www.python.org/dev/peps/pep-0008/'
                      })
        ht = ht.replace('src="_images/', 'src="')
        ht = ht.replace('/scripts\\bokeh', '../bokeh_plot\\bokeh')
        ht = ht.replace('/scripts/bokeh', '../bokeh_plot/bokeh')
        rst = os.path.join(temp, "out.{0}".format(writer))
        self.write_file(rst, ht)

        # Tests the content.
        self.assertNotIn('runpythonerror', ht)
        self.assertIn("https://www.python.org/dev/peps/pep-0008/", ht)
    def test_autosignature_class_static_method(self):
        this = os.path.abspath(os.path.dirname(__file__))
        data = os.path.join(this, "datadoc")
        with sys_path_append(data):

            obj = import_object("exsig.clex.static_method", "staticmethod")
            self.assertTrue(obj is not None)

            newstring = [
                "AAAAAAAAAAAAAAAA", "",
                ".. autosignature:: exsig.clex.static_method", "",
                "CCCCCCCCCCCCCCCC"
            ]
            newstring = "\n".join(newstring)
            htmls = rst2html(newstring, layout="sphinx_body")

        self.assertIn("CCCCCCCCCCCCCCCC", htmls)

        html = htmls.split("CCCCCCCCCCCCCCCC")
        if "static_method" not in html[0]:
            raise Exception(html[0])
        if "<strong>a</strong>" in html[0]:
            raise Exception(html[0])
        if ":param a:" in html[0]:
            raise Exception(html[0])
        if "`" in html[0]:
            raise Exception(html[0])
        if "if a and b have different types" in html[0]:
            raise Exception(html[0])
        if "Return the static addition of" not in html[0]:
            raise Exception(html[0])
        if "<p>Return the static addition of" not in html[0]:
            raise Exception(html[0])
    def test_runpython_numpy(self):
        """
        this test also test the extension runpython
        """
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        from docutils import nodes

        if "enable_disabled_documented_pieces_of_code" in sys.__dict__:
            raise Exception("this case shoud not be")

        content = """
                    test a directive
                    ================

                    .. runpythonthis::
                        :setsysvar:
                        :rst:
                        :showcode:
                        :numpy_precision: 2

                        import numpy
                        print(numpy.array([1.123456789, 1.987654321]))
                    """.replace("                    ", "")

        html = rst2html(content,  # fLOG=fLOG,
                        writer="rst", keep_warnings=True)
        if "[1.12 1.99]" not in html:
            raise Exception(html)
    def test_latex_image_overwrite(self):

        temp = get_temp_folder(__file__, "temp_latex_image_overwrite")
        root = os.path.abspath(os.path.dirname(__file__))
        img1 = os.path.join(root, "data", "image", "im.png")
        img2 = os.path.join(root, "data", "thumbnail", "im.png")
        img1 = img1[2:]
        img2 = img2[2:]
        content = """
                    .. image:: {0}
                        :width: 59
                        :alt: alternative1

                    * .. image:: {1}
                        :width: 59
                        :alt: alternative2
                    """.replace("                    ", "").format(img1, img2).replace("\\", "/")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        text = rst2html(content,  # fLOG=fLOG,
                        writer="elatex", keep_warnings=False, layout='sphinx',
                        extlinks={'issue': ('http://%s', '_issue_')},
                        md_image_dest=temp, override_image_directive=True)

        text = text.replace("\r", "")
        self.assertIn('sphinxincludegraphics', text)
        self.assertIn('=59', text)
        self.assertIn("png", text)
        with open(os.path.join(temp, "elatex_image.tex"), "w", encoding="utf8") as f:
            f.write(text)
Exemple #30
0
    def test_epkg_module_twice(self):
        from docutils import nodes as skip_

        content = """
                    abeforea :epkg:`pandas` aaftera

                    test a directive
                    ================

                    abeforea :epkg:`pandas` aaftera
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        html = rst2html(
            content,
            writer="custom",
            keep_warnings=True,
            directives=None,
            layout="sphinx",
            epkg_dictionary={
                'pandas':
                'http://pandas.pydata.org/pandas-docs/stable/generated/',
            })
        self.assertIn("http://pandas.pydata.org/pandas-docs/stable/generated/",
                      html)
    def test_rst_image_target2(self):

        temp = get_temp_folder(__file__, "temp_rst_image_target2")
        root = os.path.abspath(os.path.dirname(__file__))
        img1 = os.path.join(root, "data", "image", "im.png")
        content = """
                    .. image:: {0}
                        :target: https://github.com/sdpython.png
                        :width: 200
                        :alt: alternative1
                    """.replace("                    ", "").format(img1).replace("\\", "/")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        text = rst2html(content,  # fLOG=fLOG,
                        writer="rst", keep_warnings=False, layout='sphinx',
                        extlinks={'issue': ('http://%s', '_issue_')},
                        rst_image_dest=temp)

        text = text.replace("\r", "")
        self.assertNotIn('data/image/im.png', text)
        self.assertIn('   :alt: alternative1', text)
        self.assertIn('   :width: 200', text)
        with open(os.path.join(temp, "out_image.rst"), "w", encoding="utf8") as f:
            f.write(text)
    def test_latex_image_overwrite(self):

        temp = get_temp_folder(__file__, "temp_latex_image_overwrite")
        root = os.path.abspath(os.path.dirname(__file__))
        img1 = os.path.join(root, "data", "image", "im.png")
        img2 = os.path.join(root, "data", "thumbnail", "im.png")
        img1 = img1[2:]
        img2 = img2[2:]
        content = """
                    .. image:: {0}
                        :width: 59
                        :alt: alternative1

                    * .. image:: {1}
                        :width: 59
                        :alt: alternative2
                    """.replace("                    ", "").format(img1, img2).replace("\\", "/")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        text = rst2html(content,  # fLOG=fLOG,
                        writer="elatex", keep_warnings=False, layout='sphinx',
                        extlinks={'issue': ('http://%s', '_issue_')},
                        md_image_dest=temp, override_image_directive=True)

        text = text.replace("\r", "")
        self.assertIn('sphinxincludegraphics', text)
        self.assertIn('=59', text)
        self.assertIn("png", text)
        with open(os.path.join(temp, "elatex_image.tex"), "w", encoding="utf8") as f:
            f.write(text)
    def test_autosignature_class_onemethod(self):
        this = os.path.abspath(os.path.dirname(__file__))
        data = os.path.join(this, "datadoc")
        with sys_path_append(data, 0):
            newstring = ["AAAAAAAAAAAAAAAA",
                         "",
                         ".. autosignature:: exsig.clex",
                         "    :members: onemethod",
                         "",
                         "CCCCCCCCCCCCCCCC"]
            newstring = "\n".join(newstring)
            htmls = rst2html(newstring, layout="sphinx_body")

        self.assertIn("CCCCCCCCCCCCCCCC", htmls)

        html = htmls.split("CCCCCCCCCCCCCCCC")
        if "onemethod" not in html[0]:
            raise Exception(html[0])
        if "<strong>a</strong>" in html[0]:
            raise Exception(html[0])
        if ":param a:" in html[0]:
            raise Exception(html[0])
        if "`" in html[0]:
            raise Exception(html[0])
        if "if a and b have different types" in html[0]:
            raise Exception(html[0])
        if "Return the addition of" not in html[0]:
            raise Exception(html[0])
    def test_rst_image_target2(self):

        temp = get_temp_folder(__file__, "temp_rst_image_target2")
        root = os.path.abspath(os.path.dirname(__file__))
        img1 = os.path.join(root, "data", "image", "im.png")
        content = """
                    .. image:: {0}
                        :target: https://github.com/sdpython.png
                        :width: 200
                        :alt: alternative1
                    """.replace("                    ",
                                "").format(img1).replace("\\", "/")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        text = rst2html(
            content,  # fLOG=fLOG,
            writer="rst",
            keep_warnings=False,
            layout='sphinx',
            extlinks={'issue': ('http://%s', '_issue_')},
            rst_image_dest=temp)

        text = text.replace("\r", "")
        self.assertNotIn('data/image/im.png', text)
        self.assertIn('   :alt: alternative1', text)
        self.assertIn('   :width: 200', text)
        with open(os.path.join(temp, "out_image.rst"), "w",
                  encoding="utf8") as f:
            f.write(text)
Exemple #35
0
    def test_rst2html_png_bug(self):
        fLOG(__file__,
             self._testMethodName,
             OutputPrint=__name__ == "__main__")

        if is_travis_or_appveyor() in ('travis', 'appveyor'):
            # It requires latex.
            return

        if sys.version_info[:2] <= (2, 7):
            # i don't want to fix it for Python 2.7
            return

        temp = get_temp_folder(__file__, "temp_rst2html_png_latex")
        rst = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data",
                           "puzzle_girafe.rst")
        with open(rst, "r", encoding="utf-8") as f:
            content = f.read()
        text = rst2html(content,
                        fLOG=fLOG,
                        outdir=temp,
                        warnings_log=True,
                        imgmath_latex_preamble="""
                    \\newcommand{\\acc}[1]{\\left\\{#1\\right\\}}
                    \\newcommand{\\cro}[1]{\\left[#1\\right]}
                    \\newcommand{\\pa}[1]{\\left(#1\\right)}
                    \\newcommand{\\girafedec}[3]{ \\begin{array}{ccccc} #1 &=& #2 &+& #3 \\\\ a' &=& a &-& o  \\end{array}}
                    \\newcommand{\\vecteur}[2]{\\pa{#1,\\dots,#2}}
                    \\newcommand{\\R}[0]{\\mathbb{R}}
                    \\newcommand{\\N}[0]{\\mathbb{N}}
                    """)
        # fLOG(text)
        ji = os.path.join(temp, "out.html")
        with open(ji, "w", encoding="utf-8") as f:
            f.write(text)
    def test_md_image_target(self):

        temp = get_temp_folder(__file__, "temp_md_image_target")
        root = os.path.abspath(os.path.dirname(__file__))
        img1 = os.path.join(root, "data", "image", "im.png")
        content = """
                    .. image:: {0}
                        :target: https://github.com/sdpython
                        :width: 200
                        :alt: alternative1
                    """.replace("                    ",
                                "").format(img1).replace("\\", "/")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        text = rst2html(
            content,  # fLOG=fLOG,
            writer="md",
            keep_warnings=False,
            layout='sphinx',
            extlinks={'issue': ('http://%s', '_issue_')},
            md_image_dest=temp)

        text = text.replace("\r", "")
        self.assertIn('![alternative1]', text)
        self.assertIn('=200x', text)
        self.assertIn("![alternative1](5cf2985161e8ba56d893.png =200x)", text)
        self.assertExists(os.path.join(temp, '5cf2985161e8ba56d893.png'))
        with open(os.path.join(temp, "md_image.md"), "w",
                  encoding="utf8") as f:
            f.write(text)
Exemple #37
0
    def test_epkg_class(self):
        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    abeforea :epkg:`pandas:DataFrame:to_html` aaftera

                    7za :epkg:`7z` 7zb
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        class pandas_link:
            def __call__(self, input):
                return "MYA", "|".join(input.split(":"))

        html = rst2html(
            content,
            writer="custom",
            keep_warnings=True,
            directives=None,
            layout="sphinx",
            epkg_dictionary={
                'pandas':
                ('http://pandas.pydata.org/pandas-docs/stable/generated/',
                 ('http://pandas.pydata.org/pandas-docs/stable/generated/{0}.html',
                  1), pandas_link),
                '7z':
                "http://www.7-zip.org/",
            })

        t1 = "abeforea"
        if t1 not in html:
            raise Exception(html)

        t1 = "aftera"
        if t1 not in html:
            raise Exception(html)

        spl = html.split("abeforea")[-1].split("aftera")[0]

        t1 = "`"
        if t1 in html:
            raise Exception("\n**{0}**\n----\n{1}".format(spl, html))

        t1 = 'href="http://www.7-zip.org/"'
        if t1 not in html:
            raise Exception(html)

        t1 = 'href="pandas|DataFrame|to_html"'
        if t1 not in html:
            raise Exception(html)

        temp = get_temp_folder(__file__, "temp_epkg_inline")
        with open(os.path.join(temp, "out_sharenet.html"),
                  "w",
                  encoding="utf8") as f:
            f.write(html)
    def test_thumbnail(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    before

                    .. thumbnail:: http://www.xavierdupre.fr/app/pyquickhelper/helpsphinx/_static/project_ico.png
                        :width: 10
                        :height: 20
                        :download: 1

                    after

                    this code shoud appear
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        logger2 = logging.getLogger("video")

        log_capture_string = StringIO()
        ch = logging.StreamHandler(log_capture_string)
        ch.setLevel(logging.DEBUG)
        logger2.addHandler(ch)
        with warnings.catch_warnings(record=True):
            html = rst2html(content,  # fLOG=fLOG,
                            writer="custom", keep_warnings=True,
                            directives=None)

        warns = log_capture_string.getvalue()
        if warns:
            raise Exception(warns)

        t1 = "this code shoud not appear"
        if t1 in html:
            raise Exception(html)

        t1 = "this code shoud appear"
        if t1 not in html:
            raise Exception(html)

        t1 = "_images"
        if t1 not in html:
            raise Exception(html)

        t1 = "linkedin"
        if t1 in html:
            raise Exception(html)

        temp = get_temp_folder(__file__, "temp_sphinx_thumbnail")
        with open(os.path.join(temp, "out_image.html"), "w", encoding="utf8") as f:
            f.write(html)
Exemple #39
0
    def test_epkg_function_long_link(self):
        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    `one link on two lines <http://first.part/
                    second part>`_.
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        html = rst2html(content,
                        writer="custom",
                        keep_warnings=True,
                        directives=None,
                        layout="sphinx")

        t1 = 'href="http://first.part/secondpart"'
        if t1 not in html:
            raise Exception(html)

        t1 = '>one link on two lines</a>'
        if t1 not in html:
            raise Exception(html)

        temp = get_temp_folder(__file__, "temp_epkg_inline")
        with open(os.path.join(temp, "out_sharenet.html"),
                  "w",
                  encoding="utf8") as f:
            f.write(html)
    def test_video_url(self):
        fLOG(__file__,
             self._testMethodName,
             OutputPrint=__name__ == "__main__")

        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    before

                    .. video:: http://www.xavierdupre.fr/ensae/video_hackathon_ensae_ey_label_emmaus_2017.mp4
                        :width: 300

                    after

                    this code shoud appear
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        logger2 = logging.getLogger("video")

        log_capture_string = StringIO()
        ch = logging.StreamHandler(log_capture_string)
        ch.setLevel(logging.DEBUG)
        logger2.addHandler(ch)
        with warnings.catch_warnings(record=True):
            html = rst2html(
                content,  # fLOG=fLOG,
                writer="custom",
                keep_warnings=True,
                directives=None)

        warns = log_capture_string.getvalue().strip("\n\r\t ")
        if len(warns) != 0 and 'Unable to find' not in warns:
            raise Exception("warnings '{0}'".format(warns))

        t1 = "this code shoud not appear"
        if t1 in html:
            raise Exception(html)

        t1 = "this code shoud appear"
        if t1 not in html:
            raise Exception(html)

        t1 = "video_hackathon_ensae_ey_label_emmaus_2017.mp4"
        if t1 not in html:
            raise Exception(html)

        t1 = "unable to find"
        if t1 in html:
            raise Exception(html)

        temp = get_temp_folder(__file__, "temp_video_url")
        with open(os.path.join(temp, "out_video.html"), "w",
                  encoding="utf8") as f:
            f.write(html)
    def test_sharenet_directive_rst(self):
        content = """
                    test a directive
                    ================

                    abeforea

                    .. sharenet::
                        :facebook: 1
                        :linkedin: 2
                        :twitter: 3
                        :head: False

                    aaftera
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        html = rst2html(content,  # fLOG=fLOG,
                        writer="rst", keep_warnings=True,
                        directives=None)

        t1 = ":sharenet:`facebook-linkedin-twitter-20-body`"
        if t1 not in html:
            raise Exception(html)
    def test_autosignature_html(self):
        this = os.path.abspath(os.path.dirname(__file__))
        data = os.path.join(this, "datadoc")
        with sys_path_append(data):
            obj, name = import_object("exdocassert.onefunction", "function")

            newstring = [
                "AAAAAAAAAAAAAAAA",
                ".. autosignature:: exdocassert.onefunction",
                "BBBBBBBBBBBBBBBB",
                ".. autofunction:: exdocassert.onefunction", "CCCCCCCCCCCCCCCC"
            ]
            newstring = "\n\n".join(newstring)
            htmls = rst2html(newstring, layout="sphinx_body")

        self.assertIn("CCCCCCCCCCCCCCCC", htmls)

        from docutils.parsers.rst.directives import _directives
        self.assertTrue("autosignature" in _directives)

        html = htmls.split("BBBBBBBBBBBBBBBB")
        self.assertIn("onefunction", html[0])
        self.assertIn("onefunction", html[1])
        self.assertIn("<strong>a</strong>", html[1])
        self.assertNotIn("<strong>a</strong>", html[0])
        self.assertNotIn(":param a:", html[0])
        self.assertNotIn("`", html[0])
        self.assertNotIn("if a and b have different types", html[0])
        self.assertIn("Return the addition of", html[0])
    def test_rst2html_autoclass(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        if is_travis_or_appveyor() in ('travis', 'appveyor'):
            # It requires latex.
            return

        if sys.version_info[:2] <= (2, 7):
            # i don't want to fix it for Python 2.7
            return

        content = """
                    ======
                    title1
                    ======

                    .. autoclass:: pyquickhelper.sphinxext.sphinx_runpython_extension.RunPythonDirective
                        :members:

        """.replace("                    ", "")

        temp = get_temp_folder(__file__, "temp_rst2html_autoclass")
        text = rst2html(content, outdir=temp, layout="sphinx", writer="rst")
        ji = os.path.join(temp, "out.rst")
        with open(ji, "w", encoding="utf-8") as f:
            f.write(text)
        self.assertIn("* ``:indent:<int>`` to indent the output", text)
    def test_autosignature_class(self):
        this = os.path.abspath(os.path.dirname(__file__))
        data = os.path.join(this, "datadoc")
        with sys_path_append(data):
            newstring = [
                "AAAAAAAAAAAAAAAA", "", ".. autosignature:: exsig.clex",
                "    :members:", "", "CCCCCCCCCCCCCCCC"
            ]
            newstring = "\n".join(newstring)
            htmls = rst2html(newstring, layout="sphinx_body")

        self.assertIn("CCCCCCCCCCCCCCCC", htmls)

        html = htmls.split("CCCCCCCCCCCCCCCC")
        if "onemethod" not in html[0]:
            raise Exception(html[0])
        if "<strong>a</strong>" in html[0]:
            raise Exception(html[0])
        if ":param a:" in html[0]:
            raise Exception(html[0])
        if "`" in html[0]:
            raise Exception(html[0])
        if "if a and b have different types" in html[0]:
            raise Exception(html[0])
        if "Return the addition of" not in html[0]:
            raise Exception(html[0])
    def test_epkg_module(self):
        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    abeforea :epkg:`pandas` aaftera
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        html = rst2html(content, writer="custom", keep_warnings=True,
                        directives=None, layout="sphinx",
                        epkg_dictionary={'pandas': ('http://pandas.pydata.org/pandas-docs/stable/generated/',
                                                    ('http://pandas.pydata.org/pandas-docs/stable/generated/{0}.html', 1))
                                         })

        t1 = "abeforea"
        if t1 not in html:
            raise Exception(html)

        t1 = "aftera"
        if t1 not in html:
            raise Exception(html)

        t1 = "http://pandas.pydata.org/pandas-docs/stable/generated/"
        if t1 not in html:
            raise Exception(html)
Exemple #46
0
    def test_sharenet_directive_rst(self):
        content = """
                    test a directive
                    ================

                    abeforea

                    .. sharenet::
                        :facebook: 1
                        :linkedin: 2
                        :twitter: 3
                        :head: False

                    aaftera
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        html = rst2html(
            content,  # fLOG=fLOG,
            writer="rst",
            keep_warnings=True,
            directives=None)

        t1 = ":sharenet:`facebook-linkedin-twitter-20-body`"
        if t1 not in html:
            raise Exception(html)
    def test_rst2html_png_bug(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        if is_travis_or_appveyor() in ('travis', 'appveyor'):
            # It requires latex.
            return

        if sys.version_info[:2] <= (2, 7):
            # i don't want to fix it for Python 2.7
            return

        temp = get_temp_folder(__file__, "temp_rst2html_png_latex")
        rst = os.path.join(os.path.abspath(
            os.path.dirname(__file__)), "data", "puzzle_girafe.rst")
        with open(rst, "r", encoding="utf-8") as f:
            content = f.read()
        text = rst2html(content, fLOG=fLOG, outdir=temp, warnings_log=True,
                        imgmath_latex_preamble="""
                    \\newcommand{\\acc}[1]{\\left\\{#1\\right\\}}
                    \\newcommand{\\cro}[1]{\\left[#1\\right]}
                    \\newcommand{\\pa}[1]{\\left(#1\\right)}
                    \\newcommand{\\girafedec}[3]{ \\begin{array}{ccccc} #1 &=& #2 &+& #3 \\\\ a' &=& a &-& o  \\end{array}}
                    \\newcommand{\\vecteur}[2]{\\pa{#1,\\dots,#2}}
                    \\newcommand{\\R}[0]{\\mathbb{R}}
                    \\newcommand{\\N}[0]{\\mathbb{N}}
                    """)
        # fLOG(text)
        ji = os.path.join(temp, "out.html")
        with open(ji, "w", encoding="utf-8") as f:
            f.write(text)
    def test_doctree_image(self):

        temp = get_temp_folder(__file__, "temp_doctree_image")
        root = os.path.abspath(os.path.dirname(__file__))
        img1 = os.path.join(root, "data", "image", "im.png")
        img2 = os.path.join(root, "data", "thumbnail", "im.png")
        content = """
                    .. image:: {0}
                        :width: 200
                        :alt: alternative1

                    * .. image:: {1}
                        :width: 200
                        :alt: alternative2
                    """.replace("                    ", "").format(img1, img2).replace("\\", "/")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        try:
            text = rst2html(content,  # fLOG=fLOG,
                            writer="doctree", keep_warnings=False, layout='sphinx',
                            extlinks={'issue': ('http://%s', '_issue_')})
        except Exception as e:
            raise Exception(
                "Issue with '{0}' and '{1}'".format(img1, img2)) from e

        text = text.replace("\r", "")
        self.assertIn('data/image/im.png', text)
        self.assertIn('alternative1', text)
        self.assertIn("alt='alternative2'", text)
        self.assertIn("width='200'", text)
        self.assertNotIn('\n\n', text)
        with open(os.path.join(temp, "out_image.doctree.txt"), "w", encoding="utf8") as f:
            f.write(text)
    def test_docassert_html(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        logger1 = getLogger("MockSphinxApp")
        logger2 = getLogger("docassert")

        log_capture_string = StringIO()
        ch = logging.StreamHandler(log_capture_string)
        ch.setLevel(logging.DEBUG)
        logger1.logger.addHandler(ch)
        logger2.logger.addHandler(ch)

        this = os.path.abspath(os.path.dirname(__file__))
        data = os.path.join(this, "datadoc")
        with sys_path_append(data):
            obj, name = import_object("exdocassert.onefunction", "function")
            docstring = obj.__doc__
            with warnings.catch_warnings(record=True) as ws:
                html = rst2html(docstring)
                if "if a and b have different" not in html:
                    raise Exception(html)

            newstring = ".. autofunction:: exdocassert.onefunction"
            with warnings.catch_warnings(record=True) as ws:
                html = rst2html(newstring)
                for i, w in enumerate(ws):
                    fLOG(i, ":", w)
                if "if a and b have different" not in html:
                    html = rst2html(newstring, fLOG=fLOG)
                    fLOG("number of warnings", len(ws))
                    for i, w in enumerate(ws):
                        fLOG(i, ":", str(w).replace("\\n", "\n"))
                    raise Exception(html)

            from docutils.parsers.rst.directives import _directives
            self.assertTrue("autofunction" in _directives)

        lines = log_capture_string.getvalue().split("\n")
        if len(lines) > 0:
            for line in lines:
                if "'onefunction' has no parameter 'TypeError'" in line:
                    raise Exception(
                        "This warning should not happen.\n{0}".format("\n".join(lines)))
        self.assertTrue("<strong>a</strong>" in html)
    def test_rst_builder(self):
        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    before

                    .. cmdref::
                        :title: first cmd
                        :tag: crypt
                        :lid: idcmd3
                        :cmd: pyquickhelper.cli.encryption_cli:encrypt

                        this code shoud appear___

                    after
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        tives = [("cmdref", CmdRef, cmdref_node,
                  visit_cmdref_node, depart_cmdref_node)]

        html = rst2html(content,  # fLOG=fLOG,
                        writer="rst", keep_warnings=True,
                        directives=tives, extlinks={'issue': ('http://%s', '_issue_')})

        temp = get_temp_folder(__file__, "temp_rst_builder")
        with open(os.path.join(temp, "out_cmdref.html"), "w", encoding="utf8") as f:
            f.write(html)

        t1 = "this code shoud appear"
        if t1 not in html:
            raise Exception(html)
        t1 = "before"
        if t1 not in html:
            raise Exception(html)

        t1 = "after"
        if t1 not in html:
            raise Exception(html)

        t1 = "before"
        if t1 not in html:
            raise Exception(html)

        t1 = "--help"
        if t1 not in html:
            raise Exception(html)

        t1 = '-s STATUS, --status STATUS'
        if t1 not in html:
            raise Exception(html)

        t1 = '.. _idcmd3:'
        if t1 not in html:
            raise Exception(html)
    def test_bokeh(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        from docutils import nodes as skip_
        from pyquickhelper.sphinxext.bokeh.bokeh_plot import BokehPlotDirective
        self.assertTrue(BokehPlotDirective is not None)

        content = """
                    =======
                    History
                    =======

                    "this code should appear

                    .. bokeh-plot::

                        from bokeh.plotting import figure, output_file, show

                        output_file("temp_unittest.html")

                        x = [1, 2, 3, 4, 5]
                        y = [6, 7, 6, 4, 5]

                        p = figure(title="example_bokeh", plot_width=300, plot_height=300)
                        p.line(x, y, line_width=2)
                        p.circle(x, y, size=10, fill_color="white")

                        show(p)

                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        html = rst2html(content,  # fLOG=fLOG,
                        writer="html", keep_warnings=True,
                        directives=None, layout="sphinx",
                        load_bokeh=True)

        t1 = "this code should appear"
        if t1 not in html:
            raise Exception(html)

        temp = get_temp_folder(__file__, "temp_bokeh_extension")
        with open(os.path.join(temp, "page_bokeh.html"), "w", encoding="utf-8") as f:
            f.write(html)

        if 'Unknown directive type' in html:
            raise Exception(html)

        if '<<string>>#document-<<string>>' in html:
            pass
        else:
            raise Exception(html)

        if 'bokeh-plot-string-inline' not in html:
            raise Exception(html)
Exemple #52
0
    def test_latex_builder_sphinx_table(self):
        from docutils import nodes as skip_

        content = """
                    test a --helpe
                    ================

                    before

                    +------+--------+
                    | a    | b1     |
                    +------+--------+
                    | a    | b2     |
                    +------+--------+

                    .. list-table::
                        :widths: 5 6
                        :header-rows: 1

                        * - h1
                          - h2
                        * - a1
                          - b1
                        * - d2
                          - e2

                    after
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        tives = [("cmdref", CmdRef, cmdref_node, visit_cmdref_node,
                  depart_cmdref_node)]

        html = rst2html(
            content,  # fLOG=fLOG,
            writer="elatex",
            keep_warnings=True,
            directives=tives,
            layout="sphinx")

        temp = get_temp_folder(__file__, "temp_latex_builder_sphinx")
        with open(os.path.join(temp, "out_cmdref.tex"), "w",
                  encoding="utf8") as f:
            f.write(html)

        t1 = "+--------+----------+"
        if t1 in html:
            raise Exception(html)

        t1 = "a&b1"
        t1b = "a&\\sphinxAtStartParb1"  # sphinx 3.5
        if t1 not in html.replace("\n", "") and t1b not in html.replace(
                "\n", ""):
            raise Exception(html)

        t1 = "\\begin{tabulary}{\\linewidth}[t]{|T|T|}"
        if t1 not in html.replace("\n", ""):
            raise Exception(html)
    def test_md_reference2(self):
        from docutils import nodes as skip_

        content = """

                    .. _l-test-ref:

                    test a directive
                    ================

                    :ref:`reftext <l-test-ref>`

                    :keyword:`ggg`

                    :py:exc:`ggg`

                    *italic*

                    :bigger:`ut`

                    :issue:`1`

                    * bul1
                    * bul2

                    ::

                        rawt

                    .. only:: md

                        gggg

                    .. only:: latex

                        hhhh

                    .. only:: html

                        jjjj

                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        text = rst2html(content,  # fLOG=fLOG,
                        writer="md", keep_warnings=False, layout='sphinx',
                        extlinks={'issue': ('http://%s', '_issue_')})

        self.assertIn("*italic*", text)
        self.assertIn("* bul1", text)
        self.assertIn("```", text)
        self.assertIn("gggg", text)
        self.assertNotIn("hhhh", text)
        self.assertNotIn("jjjj", text)
        self.assertNotIn("SYSTEM", text)
        temp = get_temp_folder(__file__, "temp_only")
        with open(os.path.join(temp, "out_cmdref.md"), "w", encoding="utf8") as f:
            f.write(text)
    def test_todoext_done(self):
        fLOG(__file__,
             self._testMethodName,
             OutputPrint=__name__ == "__main__")

        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    before

                    .. todoext::
                        :title: first todo
                        :tag: bug
                        :issue: 7
                        :hidden:

                        this code shoud appear___

                    after
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        tives = [("todoext", TodoExt, todoext_node, visit_todoext_node,
                  depart_todoext_node)]

        html = rst2html(content,
                        writer="custom",
                        keep_warnings=True,
                        directives=tives,
                        extlinks={'issue': ('http://%s', '_issue_')})

        temp = get_temp_folder(__file__, "temp_todoext")
        with open(os.path.join(temp, "out_todoext.html"), "w",
                  encoding="utf8") as f:
            f.write(html)

        t1 = "this code shoud appear"
        if t1 in html:
            raise Exception(html)

        t1 = "after"
        if t1 not in html:
            raise Exception(html)

        t1 = "first todo"
        if t1 in html:
            raise Exception(html)

        t1 = "(bug)"
        if t1 in html:
            raise Exception(html)

        t1 = 'href="http://7"'
        if t1 in html:
            raise Exception(html)
    def test_runpython_process_exception(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        from docutils import nodes

        class runpythonthis_node(nodes.Structural, nodes.Element):
            pass

        class RunPythonThisDirective (RunPythonDirective):
            runpython_class = runpythonthis_node

        def visit_rp_node(self, node):
            "local function"
            self.body.append("<p><b>visit_rp_node</b></p>")

        def depart_rp_node(self, node):
            self.body.append("<p><b>depart_rp_node</b></p>")

        if "enable_disabled_documented_pieces_of_code" in sys.__dict__:
            raise Exception("this case shoud not be")

        content = """
                    test a directive
                    ================

                    .. runpythonthis::
                        :showcode:
                        :exception:
                        :process:

                        print(u"this code shoud" + u" appear")
                        z = 1/0
                        print(u"this one should" + u" not")
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        tives = [("runpythonthis", RunPythonThisDirective, runpythonthis_node,
                  visit_rp_node, depart_rp_node)]

        html = rst2html(content,  # fLOG=fLOG,
                        writer="custom", keep_warnings=True,
                        directives=tives)

        t2 = "<p>&lt;&lt;&lt;</p>"
        if t2 not in html:
            raise Exception(html)
        t2 = "<p>&gt;&gt;&gt;</p>"
        if t2 not in html:
            raise Exception(html)
        if "ZeroDivisionError" not in html:
            temp = get_temp_folder(
                __file__, "temp_runpython_process_exception")
            with open(os.path.join(temp, "out.html"), "w", encoding="utf8") as f:
                f.write(html)
            raise Exception(html)
    def test_sharenet(self):
        content = """
                    test a directive
                    ================

                    before

                    .. sharenet::
                        :facebook: 1
                        :twitter:

                        this code shoud not appear___

                    after

                    this code shoud appear
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        html = rst2html(content,  # fLOG=fLOG,
                        writer="html", keep_warnings=True,
                        directives=None)

        t1 = "this code shoud not appear"
        if t1 in html:
            raise Exception(html)

        t1 = "this code shoud appear"
        if t1 not in html:
            raise Exception(html)

        t1 = "facebook"
        if t1 not in html:
            raise Exception(html)

        t1 = "linkedin"
        if t1 in html:
            raise Exception(html)

        t1 = "function share_icon(divid, text)"
        if t1 not in html:
            raise Exception(html)

        t1 = '<a href="#"'
        if t1 not in html:
            raise Exception(html)

        t1 = '{1}'
        if t1 in html:
            raise Exception(html)

        t1 = "visit_sharenet_node"
        if t1 in html:
            raise Exception(html)

        temp = get_temp_folder(__file__, "temp_sharenet")
        with open(os.path.join(temp, "out_sharenet.html"), "w", encoding="utf8") as f:
            f.write(html)
    def test_rst_reference2(self):
        from docutils import nodes as skip_

        content = """

                    .. _l-test-ref:

                    test a directive
                    ================

                    :ref:`reftext <l-test-ref>`

                    *italic*

                    :bigger:`ut`

                    :issue:`1`

                    * bul1
                    * bul2

                    ::

                        rawt

                    .. only:: rst

                        gggg

                    .. only:: latex

                        hhhh

                    .. only:: html

                        jjjj

                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        text = rst2html(
            content,  # fLOG=fLOG,
            writer="rst",
            keep_warnings=False,
            layout='sphinx',
            extlinks={'issue': ('http://%s', '_issue_')})

        self.assertIn("*italic*", text)
        self.assertIn("* bul1", text)
        self.assertIn("::", text)
        self.assertIn(":bigger:`ut`", text)
        self.assertIn("gggg", text)
        self.assertNotIn("hhhh", text)
        self.assertNotIn("jjjj", text)
        temp = get_temp_folder(__file__, "temp_rst_reference2")
        with open(os.path.join(temp, "out_cmdref.rst"), "w",
                  encoding="utf8") as f:
            f.write(text)
    def test_video_url(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        from docutils import nodes as skip_

        content = """
                    test a directive
                    ================

                    before

                    .. video:: http://www.xavierdupre.fr/ensae/video_hackathon_ensae_ey_label_emmaus_2017.mp4
                        :width: 300

                    after

                    this code shoud appear
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        logger2 = logging.getLogger("video")

        log_capture_string = StringIO()
        ch = logging.StreamHandler(log_capture_string)
        ch.setLevel(logging.DEBUG)
        logger2.addHandler(ch)
        with warnings.catch_warnings(record=True):
            html = rst2html(content,  # fLOG=fLOG,
                            writer="custom", keep_warnings=True,
                            directives=None)

        warns = log_capture_string.getvalue().strip("\n\r\t ")
        if len(warns) != 0 and 'Unable to find' not in warns:
            raise Exception("warnings '{0}'".format(warns))

        t1 = "this code shoud not appear"
        if t1 in html:
            raise Exception(html)

        t1 = "this code shoud appear"
        if t1 not in html:
            raise Exception(html)

        t1 = "video_hackathon_ensae_ey_label_emmaus_2017.mp4"
        if t1 not in html:
            raise Exception(html)

        t1 = "unable to find"
        if t1 in html:
            raise Exception(html)

        temp = get_temp_folder(__file__, "temp_video_url")
        with open(os.path.join(temp, "out_video.html"), "w", encoding="utf8") as f:
            f.write(html)
    def test_rst_builder_sphinx(self):
        from docutils import nodes as skip_

        content = """
                    test a --helpe
                    ================

                    before

                    .. cmdref::
                        :title: first cmd
                        :tag: freg
                        :lid: id3
                        :cmd: pyquickhelper.cli.encryption_cli:encrypt

                        this code shoud appear___

                    middle

                    .. cmdreflist::
                        :tag: freg
                        :sort: title

                    after
                    """.replace("                    ", "")
        if sys.version_info[0] >= 3:
            content = content.replace('u"', '"')

        tives = [("cmdref", CmdRef, cmdref_node,
                  visit_cmdref_node, depart_cmdref_node)]

        html = rst2html(content,  # fLOG=fLOG,
                        writer="rst", keep_warnings=True,
                        directives=tives, layout="sphinx")

        temp = get_temp_folder(__file__, "temp_rst_builder_sphinx")
        with open(os.path.join(temp, "out_cmdref.html"), "w", encoding="utf8") as f:
            f.write(html)

        t1 = "this code shoud appear"
        if t1 not in html:
            raise Exception(html)

        t1 = "--help"
        if t1 not in html:
            raise Exception(html)

        t1 = ' -s STATUS, --status STATUS'
        if t1 not in html:
            raise Exception(html)

        t1 = '.. _indexcmdreflistlist-0:'
        if t1 not in html:
            raise Exception(html)

        t1 = '(`original entry <#indexcmdref-freg0>`_ : <string>, line 7)'
        if t1 not in html:
            raise Exception(html)