Coverage for tests/conftest.py: 100.00%

28 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-02-18 01:11 +0100

1"""Configuration for the pytest test suite.""" 

2 

3from __future__ import annotations 

4 

5from collections import ChainMap 

6from typing import TYPE_CHECKING, Any 

7 

8import pytest 

9from markdown.core import Markdown 

10from mkdocs.config.defaults import MkDocsConfig 

11 

12if TYPE_CHECKING: 

13 from collections.abc import Iterator 

14 from pathlib import Path 

15 

16 from mkdocs import config 

17 from mkdocstrings_handlers.python.handler import PythonHandler 

18 

19 

20@pytest.fixture(name="mkdocs_conf") 

21def fixture_mkdocs_conf(request: pytest.FixtureRequest, tmp_path: Path) -> Iterator[config.Config]: 

22 """Yield a MkDocs configuration object.""" 

23 conf = MkDocsConfig() 

24 while hasattr(request, "_parent_request") and hasattr(request._parent_request, "_parent_request"): 

25 request = request._parent_request 

26 

27 conf_dict = { 

28 "site_name": "foo", 

29 "site_url": "https://example.org/", 

30 "site_dir": str(tmp_path), 

31 "plugins": [{"mkdocstrings": {"default_handler": "python"}}], 

32 **getattr(request, "param", {}), 

33 } 

34 # Re-create it manually as a workaround for https://github.com/mkdocs/mkdocs/issues/2289 

35 mdx_configs: dict[str, Any] = dict(ChainMap(*conf_dict.get("markdown_extensions", []))) 

36 

37 conf.load_dict(conf_dict) 

38 assert conf.validate() == ([], []) 

39 

40 conf["mdx_configs"] = mdx_configs 

41 conf["markdown_extensions"].insert(0, "toc") # Guaranteed to be added by MkDocs. 

42 

43 conf = conf["plugins"]["mkdocstrings"].on_config(conf) 

44 conf = conf["plugins"]["autorefs"].on_config(conf) 

45 yield conf 

46 conf["plugins"]["mkdocstrings"].on_post_build(conf) 

47 

48 

49@pytest.fixture(name="python_handler") 

50def fixture_python_handler(mkdocs_conf: MkDocsConfig) -> PythonHandler: 

51 """Return a PythonHandler instance.""" 

52 handlers = mkdocs_conf.plugins["mkdocstrings"].handlers # type: ignore[attr-defined] 

53 handler = handlers.get_handler("python") 

54 handler._update_env(md=Markdown(extensions=["toc"])) 

55 handler.env.filters["convert_markdown"] = lambda *args, **kwargs: str(args) + str(kwargs) 

56 return handler