File: test_sphinx_ext.py

package info (click to toggle)
python-sphinx-chango 0.5.0-2
  • links: PTS
  • area: main
  • in suites: sid
  • size: 1,776 kB
  • sloc: python: 4,909; javascript: 74; makefile: 23
file content (354 lines) | stat: -rw-r--r-- 11,796 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#  SPDX-FileCopyrightText: 2024-present Hinrich Mahler <chango@mahlerhome.de>
#
#  SPDX-License-Identifier: MIT
import logging
from collections.abc import Callable, Sequence
from pathlib import Path
from string import Template
from typing import Annotated

import pytest
import shortuuid
from _pytest.tmpdir import TempPathFactory
from sphinx.testing.util import SphinxTestApp
from sphinx.util.logging import pending_warnings

from chango import __version__
from chango._utils.types import PathLike
from chango.constants import MarkupLanguage
from tests.auxil.files import data_path, path_to_python_string
from tests.sphinx_ext.conftest import MockChanGo, MockStorage

MAKE_APP_TYPE = Callable[..., SphinxTestApp]


class SphinxBuildError(RuntimeError):
    pass


class TestSphinxExt:
    SPHINX_EXT_TEST_ROOT = data_path("sphinx_ext")

    @staticmethod
    def assert_successful_build(app: SphinxTestApp):
        with pending_warnings() as mem_handler:
            app.build()

            for record in mem_handler.buffer:
                if record.levelno == logging.ERROR:
                    raise SphinxBuildError(record.getMessage())

    @classmethod
    def create_template(
        cls,
        *,
        tmp_path_factory: TempPathFactory,
        conf_value_insert: str | None = None,
        directive_insert: str = ".. chango::",
    ) -> Path:
        uid = shortuuid.uuid()
        src_dir = f"test-{uid}"
        tmp_dir = tmp_path_factory.mktemp(src_dir)

        conf_template = Template(
            (cls.SPHINX_EXT_TEST_ROOT / "conf_value.py.template").read_text(encoding="utf-8")
        )
        index_template = Template(
            (cls.SPHINX_EXT_TEST_ROOT / "index.rst.template").read_text(encoding="utf-8")
        )

        (tmp_dir / "conf.py").write_text(
            conf_template.substitute(chango_pyproject_toml_path=conf_value_insert),
            encoding="utf-8",
        )
        (tmp_dir / "index.rst").write_text(
            index_template.substitute(directive=directive_insert), encoding="utf-8"
        )

        return tmp_dir

    @staticmethod
    def compute_chango_pyproject_toml_path_insert(
        path: str | Path, path_representation: PathLike
    ) -> str:
        if path == "explicit_none":
            return "chango_pyproject_toml_path = None"
        if path is None:
            return ""
        return f"chango_pyproject_toml_path = {path_to_python_string(path, path_representation)}"

    @pytest.mark.parametrize(
        "path",
        [
            None,
            "explicit_none",
            data_path("config/pyproject.toml"),
            data_path("config/pyproject.toml").relative_to(Path.cwd(), walk_up=True),
            data_path("config"),
        ],
        ids=["None", "explicit_none", "absolute", "relative", "directory"],
    )
    @pytest.mark.parametrize("path_representation", [str, Path])
    def test_chango_pyproject_toml_path_valid(
        self, path, path_representation, make_app: MAKE_APP_TYPE, tmp_path_factory: TempPathFactory
    ):
        app = make_app(
            srcdir=self.create_template(
                conf_value_insert=self.compute_chango_pyproject_toml_path_insert(
                    path, path_representation
                ),
                tmp_path_factory=tmp_path_factory,
            )
        )

        if path in ("explicit_none", None):
            assert app.config.chango_pyproject_toml_path is None
        else:
            assert (
                app.config.chango_pyproject_toml_path == path.as_posix()
                if path_representation is str
                else path
            )

    @pytest.mark.parametrize("path", [1, {"key": "value"}, [1, 2, 3]], ids=["int", "dict", "list"])
    def test_chango_pyproject_toml_path_invalid(
        self, path, make_app: MAKE_APP_TYPE, tmp_path_factory: TempPathFactory
    ):
        insert = f"chango_pyproject_toml_path = {path!r}"

        with pytest.raises(
            TypeError, match="Expected 'chango_pyproject_toml_path' to be a string or Path"
        ):
            make_app(
                srcdir=self.create_template(
                    conf_value_insert=insert, tmp_path_factory=tmp_path_factory
                )
            )

    def test_metadata(self, app: SphinxTestApp):
        assert app.extensions["chango.sphinx_ext"].version == __version__
        assert app.extensions["chango.sphinx_ext"].parallel_read_safe is True
        assert app.extensions["chango.sphinx_ext"].parallel_write_safe is True

    @pytest.mark.parametrize(
        "path",
        [
            None,
            "explicit_none",
            data_path("config/pyproject.toml"),
            data_path("config/pyproject.toml").relative_to(Path.cwd(), walk_up=True),
            data_path("config"),
        ],
        ids=["None", "explicit_none", "absolute", "relative", "directory"],
    )
    @pytest.mark.parametrize("path_representation", [str, Path])
    def test_directive_chango_instance_loading(
        self,
        make_app: MAKE_APP_TYPE,
        path,
        path_representation,
        tmp_path_factory: TempPathFactory,
        cg_config_mock,
    ):
        app = make_app(
            srcdir=self.create_template(
                conf_value_insert=self.compute_chango_pyproject_toml_path_insert(
                    path, path_representation
                ),
                tmp_path_factory=tmp_path_factory,
            )
        )
        self.assert_successful_build(app)
        received_sys_path = cg_config_mock.get().sys_path

        if path in ("explicit_none", None):
            assert received_sys_path is None
        else:
            assert received_sys_path == path

    @pytest.mark.parametrize(
        "headline", [None, "This is a headline"], ids=["no_headline", "headline"]
    )
    def test_directive_rendering_basic(
        self, cg_config_mock, make_app: MAKE_APP_TYPE, tmp_path_factory: TempPathFactory, headline
    ):
        directive = f".. chango:: {headline}" if headline else ".. chango::"

        app = make_app(
            srcdir=self.create_template(
                directive_insert=directive, tmp_path_factory=tmp_path_factory
            )
        )

        self.assert_successful_build(app)

        index = app.outdir.joinpath("index.html")
        assert index.exists()

        content = index.read_text(encoding="utf-8")
        assert cg_config_mock.rendered_content in content

        if headline:
            assert f"<h1>{headline}" in content
        else:
            assert f"<h1>{headline}" not in content

    def test_directive_rendering_passed_markup_language(self, cg_config_mock, app: SphinxTestApp):
        self.assert_successful_build(app)
        received_args = cg_config_mock.get().chango.version_history.received_args
        received_kwargs = cg_config_mock.get().chango.version_history.received_kwargs
        assert received_args == (MarkupLanguage.RESTRUCTUREDTEXT,)
        assert received_kwargs == {}

    def test_argument_passing_basic(
        self,
        cg_config_mock: MockStorage,
        make_app: MAKE_APP_TYPE,
        tmp_path_factory: TempPathFactory,
    ):
        directive = """
.. chango::
   :start_from: "start_from"
   :end_at: "end_at"
"""
        app = make_app(
            srcdir=self.create_template(
                directive_insert=directive, tmp_path_factory=tmp_path_factory
            )
        )

        self.assert_successful_build(app)
        received_kwargs = cg_config_mock.get().chango.received_kwargs
        assert received_kwargs == {"start_from": "start_from", "end_at": "end_at"}

    def test_argument_passing_unknown_option(
        self, make_app: MAKE_APP_TYPE, tmp_path_factory: TempPathFactory
    ):
        directive = """
.. chango::
   :unknown:
"""
        app = make_app(
            srcdir=self.create_template(
                directive_insert=directive, tmp_path_factory=tmp_path_factory
            )
        )

        with pytest.raises(SphinxBuildError, match='unknown option: "unknown"'):
            self.assert_successful_build(app)

    def test_argument_passing_json_data(
        self,
        cg_config_mock: MockStorage,
        make_app: MAKE_APP_TYPE,
        tmp_path_factory: TempPathFactory,
    ):
        directive = """
.. chango::
   :start_from: {"key": "value"}
   :end_at: [false, true, null]
"""
        app = make_app(
            srcdir=self.create_template(
                directive_insert=directive, tmp_path_factory=tmp_path_factory
            )
        )

        self.assert_successful_build(app)
        received_kwargs = cg_config_mock.get().chango.received_kwargs
        assert received_kwargs == {"start_from": {"key": "value"}, "end_at": [False, True, None]}

    def test_argument_passing_invalid_json_data(
        self, make_app: MAKE_APP_TYPE, tmp_path_factory: TempPathFactory
    ):
        directive = """
.. chango::
    :start_from: {"key": "value}
    """
        app = make_app(
            srcdir=self.create_template(
                directive_insert=directive, tmp_path_factory=tmp_path_factory
            )
        )

        with pytest.raises(SphinxBuildError, match="must be a JSON-loadable value"):
            self.assert_successful_build(app)

    def test_argument_passing_missing_value(
        self, make_app: MAKE_APP_TYPE, tmp_path_factory: TempPathFactory
    ):
        directive = """
.. chango::
    :start_from:
    """
        app = make_app(
            srcdir=self.create_template(
                directive_insert=directive, tmp_path_factory=tmp_path_factory
            )
        )

        with pytest.raises(SphinxBuildError, match="must be a JSON-loadable value"):
            self.assert_successful_build(app)

    def test_argument_passing_custom_signature(
        self,
        cg_config_mock: MockStorage,
        make_app: MAKE_APP_TYPE,
        tmp_path_factory: TempPathFactory,
        monkeypatch,
    ):
        validator_kwargs = {}

        def sequence_validator(value: str | None) -> Sequence[int]:
            validator_kwargs["sequence_validator"] = value
            return tuple(map(int, value.split(",")))

        def flag_validator(value: str | None) -> bool:
            validator_kwargs["flag_validator"] = value
            return True

        original_load_version_history = MockChanGo.load_version_history

        def load_version_history(
            *args,
            start_from: str | None = None,
            end_at: str | None = None,
            json_dict_arg: dict[str, str] | None = None,
            sequence_arg: Annotated[Sequence[int], sequence_validator] = (1, 2, 3),
            flag_arg: Annotated[bool, flag_validator] = False,
        ):
            return original_load_version_history(
                *args,
                start_from=start_from,
                end_at=end_at,
                json_dict_arg=json_dict_arg,
                sequence_arg=sequence_arg,
                flag_arg=flag_arg,
            )

        monkeypatch.setattr(MockChanGo, "load_version_history", load_version_history)

        directive = """
.. chango::
    :json_dict_arg: {"key": "value"}
    :sequence_arg: 1,2,3
    :flag_arg:
    """

        app = make_app(
            srcdir=self.create_template(
                directive_insert=directive, tmp_path_factory=tmp_path_factory
            )
        )

        self.assert_successful_build(app)

        received_kwargs = cg_config_mock.get().chango.received_kwargs
        assert received_kwargs == {
            "json_dict_arg": {"key": "value"},
            "sequence_arg": (1, 2, 3),
            "flag_arg": True,
            "start_from": None,
            "end_at": None,
        }
        assert validator_kwargs == {"sequence_validator": "1,2,3", "flag_validator": None}