Coverage for tests/test_inventory.py: 26.32%

34 statements  

« prev     ^ index     » next       coverage.py v7.6.2, created at 2024-10-12 18:59 +0200

1"""Tests for the inventory module.""" 

2 

3from __future__ import annotations 

4 

5import sys 

6from io import BytesIO 

7from os.path import join 

8from typing import TYPE_CHECKING 

9 

10import pytest 

11from mkdocs.commands.build import build 

12from mkdocs.config import load_config 

13 

14from mkdocstrings.inventory import Inventory, InventoryItem 

15 

16if TYPE_CHECKING: 

17 from mkdocstrings.plugin import MkdocstringsPlugin 

18sphinx = pytest.importorskip("sphinx.util.inventory", reason="Sphinx is not installed") 

19 

20 

21@pytest.mark.parametrize( 

22 "our_inv", 

23 [ 

24 Inventory(), 

25 Inventory([InventoryItem(name="object_path", domain="py", role="obj", uri="page_url")]), 

26 Inventory([InventoryItem(name="object_path", domain="py", role="obj", uri="page_url#object_path")]), 

27 Inventory([InventoryItem(name="object_path", domain="py", role="obj", uri="page_url#other_anchor")]), 

28 ], 

29) 

30def test_sphinx_load_inventory_file(our_inv: Inventory) -> None: 

31 """Perform the 'live' inventory load test.""" 

32 buffer = BytesIO(our_inv.format_sphinx()) 

33 sphinx_inv = sphinx.InventoryFile.load(buffer, "", join) 

34 

35 sphinx_inv_length = sum(len(sphinx_inv[key]) for key in sphinx_inv) 

36 assert sphinx_inv_length == len(our_inv.values()) 

37 

38 for item in our_inv.values(): 

39 assert item.name in sphinx_inv[f"{item.domain}:{item.role}"] 

40 

41 

42@pytest.mark.skipif(sys.version_info < (3, 7), reason="using plugins that require Python 3.7") 

43def test_sphinx_load_mkdocstrings_inventory_file() -> None: 

44 """Perform the 'live' inventory load test on mkdocstrings own inventory.""" 

45 mkdocs_config = load_config() 

46 mkdocs_config["plugins"].run_event("startup", command="build", dirty=False) 

47 try: 

48 build(mkdocs_config) 

49 finally: 

50 mkdocs_config["plugins"].run_event("shutdown") 

51 own_inv = mkdocs_config["plugins"]["mkdocstrings"].handlers.inventory 

52 

53 with open("site/objects.inv", "rb") as fp: 

54 sphinx_inv = sphinx.InventoryFile.load(fp, "", join) 

55 

56 sphinx_inv_length = sum(len(sphinx_inv[key]) for key in sphinx_inv) 

57 assert sphinx_inv_length == len(own_inv.values()) 

58 

59 for item in own_inv.values(): 

60 assert item.name in sphinx_inv[f"{item.domain}:{item.role}"] 

61 

62 

63def test_load_inventory(plugin: MkdocstringsPlugin) -> None: 

64 """Test the plugin inventory loading method. 

65 

66 Parameters: 

67 plugin: A mkdocstrings plugin instance. 

68 """ 

69 plugin._load_inventory(loader=lambda *args, **kwargs: (), url="https://example.com", domains=["a", "b"]) # type: ignore[misc,arg-type]