Example #1
0
def rootdir(tmpdir):
    src = path(__file__).parent.abspath() / "books"
    dst = tmpdir.join("books")
    shutil.copytree(src, dst)
    books = path(dst)
    yield books
    shutil.rmtree(dst)
Example #2
0
def setup(app: Sphinx) -> None:
    app.add_html_theme(
        "revealjs",
        path(__file__).parent.abspath() / "revealjs",
    )
    app.add_html_theme(
        "handouts",
        path(__file__).parent.abspath() / "handouts",
    )
Example #3
0
def find_files(root, suffix=None):
    # type: (unicode, bool) -> Generator
    for dirpath, dirs, files in os.walk(root, followlinks=True):
        dirpath = path(dirpath)
        for f in [f for f in files if not suffix or f.endswith(suffix)]:  # type: ignore
            fpath = dirpath / f
            yield relpath(fpath, root)
Example #4
0
    def read(
        app,
        buildername="html",
        filename="index.html",
        encoding="utf-8",
        regress_html=False,
        regress_ext=".html",
        replace=None,
    ):

        outpath = path(
            os.path.join(str(app.srcdir), "_build", buildername, filename))
        if not outpath.exists():
            raise OSError(f"no output file exists: {outpath}")

        try:
            # introduced in sphinx 3.0
            content = outpath.read_text(encoding=encoding)
        except AttributeError:
            content = outpath.text(encoding=encoding)

        if regress_html:
            # only regress the inner body, since other sections are non-deterministic
            soup = BeautifulSoup(content, "html.parser")
            doc_div = soup.findAll("div", {"class": "documentwrapper"})[0]
            # pygments 2.11.0 introduces a whitespace tag
            for pygment_whitespace in doc_div.select("pre > span.w"):
                pygment_whitespace.replace_with(pygment_whitespace.text)
            text = doc_div.prettify()
            for find, rep in (replace or {}).items():
                text = text.replace(find, rep)
            file_regression.check(text, extension=regress_ext, encoding="utf8")

        return content
    def create_directive(self):
        """
        Helper function to create a a "directive" suitable
        for instantiating the TraitDocumenter with, along with resources
        to support that directive, and clean up the resources afterwards.

        Returns
        -------
        contextmanager
            A context manager that returns a DocumenterBridge instance.
        """
        with self.tmpdir() as tmpdir:
            # Ensure configuration file exists.
            conf_file = os.path.join(tmpdir, "conf.py")
            with open(conf_file, "w", encoding="utf-8") as f:
                f.write(CONF_PY)

            app = SphinxTestApp(srcdir=path(tmpdir))
            app.builder.env.app = app
            app.builder.env.temp_data["docname"] = "dummy"

            # Backwards compatibility hack: for now, we need to be compatible
            # with both Sphinx < 2.1 (whose DocumenterBridge doesn't take
            # a state argument) and Sphinx >= 2.3 (which warns if the state
            # isn't passed). Eventually we should be able to drop support
            # for Sphinx < 2.1.
            kwds = {}
            if sphinx.version_info >= (2, 1):
                state = mock.Mock()
                state.document.settings.tab_width = 8
                kwds["state"] = state
            yield DocumenterBridge(
                app.env, LoggingReporter(''), Options(), 1, **kwds)
Example #6
0
    def read(
        app,
        buildername="html",
        filename="index.html",
        encoding="utf-8",
        extract_body=False,
        remove_scripts=False,
        regress_html=False,
    ):

        outpath = path(
            os.path.join(str(app.srcdir), "_build", buildername, filename))
        if not outpath.exists():
            raise IOError("no output file exists: {}".format(outpath))

        content = outpath.text(encoding=encoding)

        if regress_html:
            # only regress the inner body, since other sections are non-deterministic
            from bs4 import BeautifulSoup

            soup = BeautifulSoup(content, "html.parser")
            doc_div = soup.findAll("div", {"class": "documentwrapper"})[0]
            file_regression.check(doc_div.prettify(), extension=".html")

        return content
Example #7
0
    def read(app,
             buildername='html',
             filename="contents.html",
             encoding='utf-8',
             extract_body=False,
             remove_scripts=False):

        outpath = path(
            os.path.join(str(app.srcdir), '_build', buildername, filename))
        if not outpath.exists():
            raise IOError("no output file exists: {}".format(outpath))

        content = outpath.text(encoding=encoding)

        if extract_body:
            body_rgx = re.compile("\\<body\\>(.*)\\</body\\>", re.DOTALL)
            body_search = body_rgx.search(content)
            if not body_search:
                raise IOError("could not find body content of {}".format(path))
            content = body_search.group(1)

        if remove_scripts:
            # remove script environments which can change
            script_rgx = re.compile("\\<script\\>(.*)\\</script\\>", re.DOTALL)
            content = script_rgx.sub("<script></script>", content)

        return content
Example #8
0
    def read(
        app,
        buildername="html",
        filename="index.html",
        encoding="utf-8",
        extract_body=False,
        remove_scripts=False,
        regress_html=False,
        replace=None,
    ):

        outpath = path(
            os.path.join(str(app.srcdir), "_build", buildername, filename))
        if not outpath.exists():
            raise IOError("no output file exists: {}".format(outpath))

        try:
            # introduced in sphinx 3.0
            content = outpath.read_text(encoding=encoding)
        except AttributeError:
            content = outpath.text(encoding=encoding)

        if regress_html:
            # only regress the inner body, since other sections are non-deterministic
            from bs4 import BeautifulSoup

            soup = BeautifulSoup(content, "html.parser")
            doc_div = soup.findAll("div", {"class": "documentwrapper"})[0]
            text = doc_div.prettify()
            for find, rep in (replace or {}).items():
                text = text.replace(find, rep)
            file_regression.check(text, extension=".html", encoding="utf8")

        return content
Example #9
0
def find_files(root, suffix=None):
    # type: (unicode, bool) -> Generator
    for dirpath, dirs, files in os.walk(root, followlinks=True):
        dirpath = path(dirpath)
        for f in [f for f in files if not suffix or f.endswith(suffix)]:  # type: ignore
            fpath = dirpath / f
            yield relpath(fpath, root)
def setup(app: Sphinx):
    app.add_directive("docexample", DocExample)
    app.add_node(docexample, handouts=(visit_docexample, depart_docexample))
    app.add_html_theme(
        "docs",
        path(__file__).parent.abspath() / "theme",
    )
Example #11
0
def find_files(root: str, suffix: bool = None) -> Generator[str, None, None]:
    for dirpath, dirs, files in os.walk(root, followlinks=True):
        dirpath = path(dirpath)
        for f in [f for f in files
                  if not suffix or f.endswith(suffix)]:  # type: ignore
            fpath = dirpath / f
            yield relpath(fpath, root)
Example #12
0
def test_app(make_app, sphinx_test_tempdir, request):
    # get builder parameters from test case
    builder_params = request.param

    # copy plantuml.jar to current test temdir
    plantuml_jar_file = path(__file__).parent.abspath() / "doc_test/utils"
    shutil.copytree(plantuml_jar_file, sphinx_test_tempdir / "utils")

    # copy test srcdir to test temporary directory sphinx_test_tempdir
    srcdir = builder_params.get("srcdir", None)
    src_dir = copy_srcdir_to_tmpdir(srcdir, sphinx_test_tempdir)

    # return sphinx.testing fixture make_app and new srcdir which in sphinx_test_tempdir
    app = make_app(
        buildername=builder_params.get("buildername", "html"),
        srcdir=src_dir,
        # builddir=builder_params.get("builddir", None),  # sphinx 3.5.4 not compatible
        freshenv=builder_params.get("freshenv", None),
        confoverrides=builder_params.get("confoverrides", None),
        status=builder_params.get("status", None),
        warning=builder_params.get("warning", None),
        tags=builder_params.get("tags", None),
        docutilsconf=builder_params.get("docutilsconf", None),
        parallel=builder_params.get("parallel", 0),
    )

    try:
        yield app
    finally:
        # cleanup test temporary directory
        shutil.rmtree(sphinx_test_tempdir, True)
    def create_directive(self):
        """
        Helper function to create a a "directive" suitable
        for instantiating the TraitDocumenter with, along with resources
        to support that directive, and clean up the resources afterwards.

        Returns
        -------
        contextmanager
            A context manager that returns a DocumenterBridge instance.
        """
        with self.tmpdir() as tmpdir:
            # Ensure configuration file exists.
            conf_file = os.path.join(tmpdir, "conf.py")
            with open(conf_file, "w", encoding="utf-8") as f:
                f.write(CONF_PY)

            app = SphinxTestApp(srcdir=path(tmpdir))
            app.builder.env.app = app
            app.builder.env.temp_data["docname"] = "dummy"

            kwds = {}
            state = mock.Mock()
            state.document.settings.tab_width = 8
            kwds["state"] = state
            yield DocumenterBridge(
                app.env, LoggingReporter(''), Options(), 1, **kwds)
Example #14
0
def test_package_file_module_first(tempdir):
    outdir = path(tempdir)
    (outdir / 'testpkg').makedirs()
    (outdir / 'testpkg' / '__init__.py').write_text('', encoding='utf8')
    (outdir / 'testpkg' / 'example.py').write_text('', encoding='utf8')
    apidoc_main(['--module-first', '-o', tempdir, tempdir])

    content = (outdir / 'testpkg.rst').read_text(encoding='utf8')
    assert content == ("testpkg package\n"
                       "===============\n"
                       "\n"
                       ".. automodule:: testpkg\n"
                       "   :members:\n"
                       "   :undoc-members:\n"
                       "   :show-inheritance:\n"
                       "\n"
                       "Submodules\n"
                       "----------\n"
                       "\n"
                       "testpkg.example module\n"
                       "----------------------\n"
                       "\n"
                       ".. automodule:: testpkg.example\n"
                       "   :members:\n"
                       "   :undoc-members:\n"
                       "   :show-inheritance:\n")
Example #15
0
def sphinx_test_tempdir():
    """
    temporary directory that wrapped with `path` class.
    """
    def make_tmpdir():
        return os.path.join(gettempdir(), str(os.getpid()))
    return path(os.environ.get('SPHINX_TEST_TEMPDIR', make_tmpdir())).abspath()
Example #16
0
            def _rootdir(self, app_params):
                # Create the test project's 'docs' dir with a conf.py and index.rst.

                # the root directory name is generated from the test name
                testroot = os.path.join(
                    TEST_PROJECTS_ROOT, self.test_project,
                    "docs_{0}_{1}".format(self.__class__.__name__,
                                          self._testMethodName))
                if os.path.isdir(testroot):
                    shutil.rmtree(testroot)
                os.makedirs(testroot)

                # Make the testing root available for this test case for when separate
                # source / build directories are used (in this case, self.app.srcdir
                # is a subdirectory of testroot).
                self.testroot = testroot

                # set the 'testroot' kwarg so that sphinx knows about it
                app_params.kwargs["srcdir"] = path(testroot)

                # Sphinx demands a `conf.py` is present
                with open(os.path.join(testroot, "conf.py"), "w") as conf_py:
                    conf_py.write(
                        textwrap.dedent('''\
                        # -*- coding: utf-8 -*-
                        extensions = ["breathe", "exhale"]
                        master_doc = "index"
                        source_suffix = [".rst"]
                    '''))

                # If a given test case needs to run app.build(), make sure index.rst
                # is available as well
                with open(os.path.join(testroot, "index.rst"),
                          "w") as index_rst:
                    index_rst.write(
                        textwrap.dedent('''
                        Exhale Test Case
                        ================
                        .. toctree::
                           :maxdepth: 2

                           {containmentFolder}/{rootFileName}
                    ''').format(
                            # containmentFolder and rootFileName are always in exhale_args
                            **app_params.kwargs["confoverrides"]
                            ["exhale_args"]))

                # run the test in testroot
                yield testroot

                # perform cleanup by deleting the docs dir
                # @no_cleanup sets self.testroot to [self.testroot] as a flag that
                # cleanup should not transpire
                if isinstance(self.testroot,
                              six.string_types) and os.path.isdir(
                                  self.testroot):
                    shutil.rmtree(self.testroot)

                self.testroot = None
def sphinx_test_tempdir():
    """
    temporary directory that wrapped with `path` class.
    """
    tmpdir = path(gettempdir()).abspath() / 'reviewbuilder'
    if tmpdir.exists():
        tmpdir.rmtree()

    return tmpdir
Example #18
0
def test_image_glob(app, status, warning):
    app.builder.build_all()

    # index.rst
    doctree = pickle.loads((app.doctreedir / 'index.doctree').bytes())

    assert isinstance(doctree[0][1], nodes.image)
    assert doctree[0][1]['candidates'] == {'*': 'rimg.png'}
    assert doctree[0][1]['uri'] == 'rimg.png'

    assert isinstance(doctree[0][2], nodes.figure)
    assert isinstance(doctree[0][2][0], nodes.image)
    assert doctree[0][2][0]['candidates'] == {'*': 'rimg.png'}
    assert doctree[0][2][0]['uri'] == 'rimg.png'

    assert isinstance(doctree[0][3], nodes.image)
    assert doctree[0][3]['candidates'] == {
        'application/pdf': 'img.pdf',
        'image/gif': 'img.gif',
        'image/png': 'img.png'
    }
    assert doctree[0][3]['uri'] == 'img.*'

    assert isinstance(doctree[0][4], nodes.figure)
    assert isinstance(doctree[0][4][0], nodes.image)
    assert doctree[0][4][0]['candidates'] == {
        'application/pdf': 'img.pdf',
        'image/gif': 'img.gif',
        'image/png': 'img.png'
    }
    assert doctree[0][4][0]['uri'] == 'img.*'

    # subdir/index.rst
    doctree = pickle.loads((app.doctreedir / 'subdir/index.doctree').bytes())

    assert isinstance(doctree[0][1], nodes.image)
    sub = path('subdir')
    assert doctree[0][1]['candidates'] == {'*': sub / 'rimg.png'}
    assert doctree[0][1]['uri'] == sub / 'rimg.png'

    assert isinstance(doctree[0][2], nodes.image)
    assert doctree[0][2]['candidates'] == {
        'application/pdf': 'subdir/svgimg.pdf',
        'image/svg+xml': 'subdir/svgimg.svg'
    }
    assert doctree[0][2]['uri'] == sub / 'svgimg.*'

    assert isinstance(doctree[0][3], nodes.figure)
    assert isinstance(doctree[0][3][0], nodes.image)
    assert doctree[0][3][0]['candidates'] == {
        'application/pdf': 'subdir/svgimg.pdf',
        'image/svg+xml': 'subdir/svgimg.svg'
    }
    assert doctree[0][3][0]['uri'] == sub / 'svgimg.*'
Example #19
0
def test_applehelp_output(app, status, warning):
    (app.srcdir / 'en.lproj').makedirs()
    (app.srcdir / 'en.lproj' / 'localized.txt').write_text('')
    app.builder.build_all()

    # Have to use bundle_path, not outdir, because we alter the latter
    # to point to the lproj directory so that the HTML arrives in the
    # correct location.
    bundle_path = path(app.builder.bundle_path)
    check_structure(bundle_path)
    check_localization(bundle_path)
Example #20
0
def test_module_file_noheadings(tempdir):
    outdir = path(tempdir)
    (outdir / 'example.py').write_text('', encoding='utf8')
    apidoc_main(['--no-headings', '-o', tempdir, tempdir])
    assert (outdir / 'example.rst').exists()

    content = (outdir / 'example.rst').read_text(encoding='utf8')
    assert content == (".. automodule:: example\n"
                       "   :members:\n"
                       "   :undoc-members:\n"
                       "   :show-inheritance:\n")
def test_applehelp_output(app, status, warning):
    (app.srcdir / 'en.lproj').makedirs()
    (app.srcdir / 'en.lproj' / 'localized.txt').write_text('')
    app.builder.build_all()

    # Have to use bundle_path, not outdir, because we alter the latter
    # to point to the lproj directory so that the HTML arrives in the
    # correct location.
    bundle_path = path(app.builder.bundle_path)
    check_structure(bundle_path)
    check_localization(bundle_path)
Example #22
0
def test_docutils_source_link_with_nonascii_file(app, status, warning):
    srcdir = path(app.srcdir)
    mb_name = u'\u65e5\u672c\u8a9e'
    try:
        (srcdir / (mb_name + '.txt')).write_text('')
    except UnicodeEncodeError:
        from sphinx.testing.path import FILESYSTEMENCODING
        raise pytest.skip.Exception(
            'nonascii filename not supported on this filesystem encoding: '
            '%s', FILESYSTEMENCODING)

    app.builder.build_all()
def test_docutils_source_link_with_nonascii_file(app, status, warning):
    srcdir = path(app.srcdir)
    mb_name = u'\u65e5\u672c\u8a9e'
    try:
        (srcdir / (mb_name + '.txt')).write_text('')
    except UnicodeEncodeError:
        from sphinx.testing.path import FILESYSTEMENCODING
        raise pytest.skip.Exception(
            'nonascii filename not supported on this filesystem encoding: '
            '%s', FILESYSTEMENCODING)

    app.builder.build_all()
Example #24
0
def test_package_file(tempdir):
    outdir = path(tempdir)
    (outdir / 'testpkg').makedirs()
    (outdir / 'testpkg' / '__init__.py').write_text('')
    (outdir / 'testpkg' / 'example.py').write_text('')
    (outdir / 'testpkg' / 'subpkg').makedirs()
    (outdir / 'testpkg' / 'subpkg' / '__init__.py').write_text('')
    apidoc_main(['-o', tempdir, tempdir / 'testpkg'])
    assert (outdir / 'testpkg.rst').exists()
    assert (outdir / 'testpkg.subpkg.rst').exists()

    content = (outdir / 'testpkg.rst').text()
    assert content == ("testpkg package\n"
                       "===============\n"
                       "\n"
                       "Subpackages\n"
                       "-----------\n"
                       "\n"
                       ".. toctree::\n"
                       "\n"
                       "   testpkg.subpkg\n"
                       "\n"
                       "Submodules\n"
                       "----------\n"
                       "\n"
                       "testpkg.example module\n"
                       "----------------------\n"
                       "\n"
                       ".. automodule:: testpkg.example\n"
                       "   :members:\n"
                       "   :undoc-members:\n"
                       "   :show-inheritance:\n"
                       "\n"
                       "\n"
                       "Module contents\n"
                       "---------------\n"
                       "\n"
                       ".. automodule:: testpkg\n"
                       "   :members:\n"
                       "   :undoc-members:\n"
                       "   :show-inheritance:\n")

    content = (outdir / 'testpkg.subpkg.rst').text()
    assert content == ("testpkg.subpkg package\n"
                       "======================\n"
                       "\n"
                       "Module contents\n"
                       "---------------\n"
                       "\n"
                       ".. automodule:: testpkg.subpkg\n"
                       "   :members:\n"
                       "   :undoc-members:\n"
                       "   :show-inheritance:\n")
def sphinx_run(sphinx_params, make_app, tempdir):
    """A fixture to setup and run a sphinx build, in a sandboxed folder.

    The `myst_nb` extension ius added by default,
    and the first file will be set as the materdoc

    """
    assert len(sphinx_params["files"]) > 0, sphinx_params["files"]
    conf = sphinx_params.get("conf", {})
    buildername = sphinx_params.get("buildername", "html")

    confoverrides = {
        "extensions": ["myst_nb"],
        "master_doc": os.path.splitext(sphinx_params["files"][0])[0],
        "exclude_patterns": ["_build"],
        "execution_show_tb": True,
    }
    confoverrides.update(conf)

    current_dir = os.getcwd()
    if "working_dir" in sphinx_params:
        from sphinx.testing.path import path

        base_dir = path(sphinx_params["working_dir"]) / str(uuid.uuid4())
    else:
        base_dir = tempdir
    srcdir = base_dir / "source"
    srcdir.makedirs(exist_ok=True)
    os.chdir(base_dir)
    (
        srcdir / "conf.py"
    ).write_text("# conf overrides (passed directly to sphinx):\n" + "\n".join(
        ["# " + ll
         for ll in json.dumps(confoverrides, indent=2).splitlines()]) + "\n")

    for nb_file in sphinx_params["files"]:
        nb_path = TEST_FILE_DIR.joinpath(nb_file)
        assert nb_path.exists(), nb_path
        (srcdir / nb_file).parent.makedirs(exist_ok=True)
        (srcdir / nb_file).write_text(nb_path.read_text(encoding="utf8"))

    nocolor()
    app = make_app(buildername=buildername,
                   srcdir=srcdir,
                   confoverrides=confoverrides)

    yield SphinxFixture(app, sphinx_params["files"])

    # reset working directory
    os.chdir(current_dir)
Example #26
0
def test_module_file(tempdir):
    outdir = path(tempdir)
    (outdir / 'example.py').write_text('')
    apidoc_main(['-o', tempdir, tempdir])
    assert (outdir / 'example.rst').exists()

    content = (outdir / 'example.rst').read_text()
    assert content == ("example module\n"
                       "==============\n"
                       "\n"
                       ".. automodule:: example\n"
                       "   :members:\n"
                       "   :undoc-members:\n"
                       "   :show-inheritance:\n")
Example #27
0
def local_app(make_app):
    """
    Creates a sphinx app specific to this environment.

    The main thing that is set up is the path to the conf.py file.

    yields:
        SphinxApp: The sphinx app.

    """
    # Provide sphinx with the path to the documentation directory.
    conf_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "assets"))

    # Note the sphinx fixture expects a :class:`path` object, not a string
    yield make_app(srcdir=path(conf_dir))
Example #28
0
def test_toc_file(tempdir):
    outdir = path(tempdir)
    (outdir / 'module').makedirs()
    (outdir / 'example.py').write_text('', encoding='utf8')
    (outdir / 'module' / 'example.py').write_text('', encoding='utf8')
    apidoc_main(['-o', tempdir, tempdir])
    assert (outdir / 'modules.rst').exists()

    content = (outdir / 'modules.rst').read_text(encoding='utf8')
    assert content == ("test_toc_file0\n"
                       "==============\n"
                       "\n"
                       ".. toctree::\n"
                       "   :maxdepth: 4\n"
                       "\n"
                       "   example\n")
Example #29
0
def test_image_glob(app, status, warning):
    app.builder.build_all()

    # index.rst
    doctree = pickle.loads((app.doctreedir / 'index.doctree').bytes())

    assert isinstance(doctree[0][1], nodes.image)
    assert doctree[0][1]['candidates'] == {'*': 'rimg.png'}
    assert doctree[0][1]['uri'] == 'rimg.png'

    assert isinstance(doctree[0][2], nodes.figure)
    assert isinstance(doctree[0][2][0], nodes.image)
    assert doctree[0][2][0]['candidates'] == {'*': 'rimg.png'}
    assert doctree[0][2][0]['uri'] == 'rimg.png'

    assert isinstance(doctree[0][3], nodes.image)
    assert doctree[0][3]['candidates'] == {'application/pdf': 'img.pdf',
                                           'image/gif': 'img.gif',
                                           'image/png': 'img.png'}
    assert doctree[0][3]['uri'] == 'img.*'

    assert isinstance(doctree[0][4], nodes.figure)
    assert isinstance(doctree[0][4][0], nodes.image)
    assert doctree[0][4][0]['candidates'] == {'application/pdf': 'img.pdf',
                                              'image/gif': 'img.gif',
                                              'image/png': 'img.png'}
    assert doctree[0][4][0]['uri'] == 'img.*'

    # subdir/index.rst
    doctree = pickle.loads((app.doctreedir / 'subdir/index.doctree').bytes())

    assert isinstance(doctree[0][1], nodes.image)
    sub = path('subdir')
    assert doctree[0][1]['candidates'] == {'*': sub / 'rimg.png'}
    assert doctree[0][1]['uri'] == sub / 'rimg.png'

    assert isinstance(doctree[0][2], nodes.image)
    assert doctree[0][2]['candidates'] == {'application/pdf': 'subdir/svgimg.pdf',
                                           'image/svg+xml': 'subdir/svgimg.svg'}
    assert doctree[0][2]['uri'] == sub / 'svgimg.*'

    assert isinstance(doctree[0][3], nodes.figure)
    assert isinstance(doctree[0][3][0], nodes.image)
    assert doctree[0][3][0]['candidates'] == {'application/pdf': 'subdir/svgimg.pdf',
                                              'image/svg+xml': 'subdir/svgimg.svg'}
    assert doctree[0][3][0]['uri'] == sub / 'svgimg.*'
Example #30
0
def test_package_file_without_submodules(tempdir):
    outdir = path(tempdir)
    (outdir / 'testpkg').makedirs()
    (outdir / 'testpkg' / '__init__.py').write_text('', encoding='utf8')
    apidoc_main(['-o', tempdir, tempdir / 'testpkg'])
    assert (outdir / 'testpkg.rst').exists()

    content = (outdir / 'testpkg.rst').read_text(encoding='utf8')
    assert content == ("testpkg package\n"
                       "===============\n"
                       "\n"
                       "Module contents\n"
                       "---------------\n"
                       "\n"
                       ".. automodule:: testpkg\n"
                       "   :members:\n"
                       "   :undoc-members:\n"
                       "   :show-inheritance:\n")
Example #31
0
def test_get_ref_roles_list(make_app):
    cwd = Path(__file__).parent / "data/docs/"
    srcdir = path(str(cwd))
    app = make_app("html", srcdir=srcdir)
    app.build()

    settings = Settings(
        html_output_dirs=[str(app.outdir)],
        doctrees_output_dirs=[str(app.outdir)],
        include_intersphinx_data=False,
        always_use_scoped_targets=True,
        default_role="any",
        nvim=mock.MagicMock(),
    )

    expected = {
        "std:doc",
        "std:label",
    }
    result = get_ref_roles_list(cwd=cwd, settings=settings)
    assert set(result) == expected
Example #32
0
def test_instantiation(tmp_path_factory, rootdir: str, monkeypatch):
    # Given
    src_dir = tmp_path_factory.getbasetemp() / 'root'

    # special support for sphinx/tests
    if rootdir and not src_dir.exists():
        shutil.copytree(Path(str(rootdir)) / 'test-root', src_dir)

    monkeypatch.setattr('sphinx.application.abspath', lambda x: x)

    syspath = sys.path[:]

    # When
    app_ = SphinxTestApp(srcdir=path(src_dir),
                         status=StringIO(),
                         warning=StringIO())
    sys.path[:] = syspath
    app_.cleanup()

    # Then
    assert isinstance(app_, sphinx.application.Sphinx)
Example #33
0
def test_namespace_package_file(tempdir):
    outdir = path(tempdir)
    (outdir / 'testpkg').makedirs()
    (outdir / 'testpkg' / 'example.py').write_text('')
    apidoc_main(['--implicit-namespace', '-o', tempdir, tempdir / 'testpkg'])
    assert (outdir / 'testpkg.rst').exists()

    content = (outdir / 'testpkg.rst').read_text()
    assert content == ("testpkg namespace\n"
                       "=================\n"
                       "\n"
                       "Submodules\n"
                       "----------\n"
                       "\n"
                       "testpkg.example module\n"
                       "----------------------\n"
                       "\n"
                       ".. automodule:: testpkg.example\n"
                       "   :members:\n"
                       "   :undoc-members:\n"
                       "   :show-inheritance:\n")
    def create_directive(self):
        """
        Helper function to create a a "directive" suitable
        for instantiating the TraitDocumenter with, along with resources
        to support that directive, and clean up the resources afterwards.

        Returns
        -------
        contextmanager
            A context manager that returns a DocumenterBridge instance.
        """
        with self.tmpdir() as tmpdir:
            # The configuration file must exist, but it's okay if it's empty.
            conf_file = os.path.join(tmpdir, "conf.py")
            with io.open(conf_file, "w", encoding="utf-8"):
                pass

            app = SphinxTestApp(srcdir=path(tmpdir))
            app.builder.env.app = app
            app.builder.env.temp_data["docname"] = "dummy"
            yield DocumenterBridge(app.env, LoggingReporter(''), Options(), 1)
Example #35
0
            def _rootdir(self, app_params):
                # Create the test project's 'docs' dir with a conf.py and index.rst.

                # the root directory name is generated from the test name
                testroot = os.path.join(
                    TEST_PROJECTS_ROOT,
                    self.test_project,
                    "docs_{0}_{1}".format(self.__class__.__name__, self._testMethodName)
                )
                if os.path.isdir(testroot):
                    shutil.rmtree(testroot)
                os.makedirs(testroot)

                # Make the testing root available for this test case for when separate
                # source / build directories are used (in this case, self.app.srcdir
                # is a subdirectory of testroot).
                self.testroot = testroot

                # set the 'testroot' kwarg so that sphinx knows about it
                app_params.kwargs["srcdir"] = path(testroot)

                # Sphinx demands a `conf.py` is present
                with open(os.path.join(testroot, "conf.py"), "w") as conf_py:
                    conf_py.write(textwrap.dedent('''\
                        # -*- coding: utf-8 -*-
                        project = "{test_project}"
                        extensions = ["breathe", "exhale"]
                        master_doc = "index"
                        source_suffix = [".rst"]
                    ''').format(
                        test_project=test_project
                    ))
                    # Absurd test cases may need an increased recursion limit for Sphinx
                    if self.test_project in ["cpp_long_names"]:
                        conf_py.write(textwrap.dedent('''
                            import sys
                            sys.setrecursionlimit(2000)
                        '''))

                # If a given test case needs to run app.build(), make sure index.rst
                # is available as well
                with open(os.path.join(testroot, "index.rst"), "w") as index_rst:
                    index_rst.write(textwrap.dedent('''
                        Exhale Test Case
                        ================
                        .. toctree::
                           :maxdepth: 2

                           {containmentFolder}/{rootFileName}
                    ''').format(
                        # containmentFolder and rootFileName are always in exhale_args
                        **app_params.kwargs["confoverrides"]["exhale_args"])
                    )

                # run the test in testroot
                yield testroot

                # perform cleanup by deleting the docs dir
                # @no_cleanup sets self.testroot to [self.testroot] as a flag that
                # cleanup should not transpire
                if isinstance(self.testroot, six.string_types) and os.path.isdir(self.testroot):
                    shutil.rmtree(self.testroot)

                self.testroot = None
def rootdir(remove_sphinx_projects):
    roots = path(os.path.dirname(__file__) or ".").abspath() / "roots"
    yield roots
Example #37
0
 def _make_app(*args, **kw):
     kw.setdefault('srcdir', path(tempdir))
     return make_app(*args, **kw)
Example #38
0
def rootdir():
    return path(os.path.dirname(__file__) or '.').abspath() / 'roots'
Example #39
0
File: util.py Project: LFYG/sphinx
def find_files(root, suffix=None):
    for dirpath, dirs, files in os.walk(root, followlinks=True):
        dirpath = path(dirpath)
        for f in [f for f in files if not suffix or f.endswith(suffix)]:
            fpath = dirpath / f
            yield os.path.relpath(fpath, root)