| 1 |
"""Test the intersphinx extension.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import posixpath |
| 6 |
import re |
| 7 |
import shutil |
| 8 |
import zlib |
| 9 |
from http.server import BaseHTTPRequestHandler |
| 10 |
from io import BytesIO |
| 11 |
from typing import TYPE_CHECKING |
| 12 |
|
| 13 |
from sphinx.ext.intersphinx._shared import InventoryAdapter |
| 14 |
from sphinx.testing.util import SphinxTestApp |
| 15 |
from sphinx.util.inventory import _InventoryItem |
| 16 |
|
| 17 |
from tests.utils import http_server |
| 18 |
|
| 19 |
if TYPE_CHECKING: |
| 20 |
from collections.abc import Iterable |
| 21 |
from pathlib import Path |
| 22 |
from typing import Any, BinaryIO |
| 23 |
|
| 24 |
BASE_CONFIG = { |
| 25 |
'extensions': ['sphinx.ext.intersphinx'], |
| 26 |
'intersphinx_timeout': 0.1, |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
class InventoryEntry: |
| 31 |
"""Entry in the Intersphinx inventory.""" |
| 32 |
|
| 33 |
__slots__ = ( |
| 34 |
'name', |
| 35 |
'display_name', |
| 36 |
'domain_name', |
| 37 |
'object_type', |
| 38 |
'uri', |
| 39 |
'anchor', |
| 40 |
'priority', |
| 41 |
) |
| 42 |
|
| 43 |
def __init__( |
| 44 |
self, |
| 45 |
name: str = 'this', |
| 46 |
*, |
| 47 |
display_name: str | None = None, |
| 48 |
domain_name: str = 'py', |
| 49 |
object_type: str = 'obj', |
| 50 |
uri: str = 'index.html', |
| 51 |
anchor: str = '', |
| 52 |
priority: int = 0, |
| 53 |
): |
| 54 |
if anchor.endswith(name): |
| 55 |
anchor = anchor.removesuffix(name) + '$' |
| 56 |
|
| 57 |
if anchor: |
| 58 |
uri += '#' + anchor |
| 59 |
|
| 60 |
if display_name is None or display_name == name: |
| 61 |
display_name = '-' |
| 62 |
|
| 63 |
self.name = name |
| 64 |
self.display_name = display_name |
| 65 |
self.domain_name = domain_name |
| 66 |
self.object_type = object_type |
| 67 |
self.uri = uri |
| 68 |
self.anchor = anchor |
| 69 |
self.priority = priority |
| 70 |
|
| 71 |
def format(self) -> str: |
| 72 |
"""Format the entry as it appears in the inventory file.""" |
| 73 |
return ( |
| 74 |
f'{self.name} {self.domain_name}:{self.object_type} ' |
| 75 |
f'{self.priority} {self.uri} {self.display_name}\n' |
| 76 |
) |
| 77 |
|
| 78 |
|
| 79 |
class IntersphinxProject: |
| 80 |
def __init__( |
| 81 |
self, |
| 82 |
*, |
| 83 |
name: str = 'spam', |
| 84 |
version: str | int = 1, |
| 85 |
baseurl: str = '', |
| 86 |
baseuri: str = '', |
| 87 |
file: str | None = None, |
| 88 |
) -> None: |
| 89 |
#: The project name. |
| 90 |
self.name = name |
| 91 |
#: The escaped project name. |
| 92 |
self.safe_name = re.sub(r'\\s+', ' ', name) |
| 93 |
|
| 94 |
#: The project version as a string. |
| 95 |
self.version = version = str(version) |
| 96 |
#: The escaped project version. |
| 97 |
self.safe_version = re.sub(r'\\s+', ' ', version) |
| 98 |
|
| 99 |
#: The project base URL (e.g., http://localhost:9341). |
| 100 |
self.baseurl = baseurl |
| 101 |
#: The project base URI, relative to *baseurl* (e.g., 'spam'). |
| 102 |
self.uri = baseuri |
| 103 |
#: The project URL, as specified in :confval:`intersphinx_mapping`. |
| 104 |
self.url = posixpath.join(baseurl, baseuri) |
| 105 |
#: The project local file, if any. |
| 106 |
self.file = file |
| 107 |
|
| 108 |
@property |
| 109 |
def record(self) -> dict[str, tuple[str | None, str | None]]: |
| 110 |
"""The :confval:`intersphinx_mapping` record for this project.""" |
| 111 |
return {self.name: (self.url, self.file)} |
| 112 |
|
| 113 |
def normalise(self, entry: InventoryEntry) -> tuple[str, _InventoryItem]: |
| 114 |
"""Format an inventory entry as if it were part of this project.""" |
| 115 |
return entry.name, _InventoryItem( |
| 116 |
project_name=self.safe_name, |
| 117 |
project_version=self.safe_version, |
| 118 |
uri=posixpath.join(self.url, entry.uri), |
| 119 |
display_name=entry.display_name, |
| 120 |
) |
| 121 |
|
| 122 |
|
| 123 |
class FakeInventory: |
| 124 |
protocol_version: int |
| 125 |
|
| 126 |
def __init__(self, project: IntersphinxProject | None = None) -> None: |
| 127 |
self.project = project or IntersphinxProject() |
| 128 |
|
| 129 |
def serialise(self, entries: Iterable[InventoryEntry] | None = None) -> bytes: |
| 130 |
buffer = BytesIO() |
| 131 |
self._write_headers(buffer) |
| 132 |
entries = entries or [InventoryEntry()] |
| 133 |
self._write_body(buffer, (item.format().encode() for item in entries)) |
| 134 |
return buffer.getvalue() |
| 135 |
|
| 136 |
def _write_headers(self, buffer: BinaryIO) -> None: |
| 137 |
headers = ( |
| 138 |
f'# Sphinx inventory version {self.protocol_version}\n' |
| 139 |
f'# Project: {self.project.safe_name}\n' |
| 140 |
f'# Version: {self.project.safe_version}\n' |
| 141 |
).encode() |
| 142 |
buffer.write(headers) |
| 143 |
|
| 144 |
def _write_body(self, buffer: BinaryIO, lines: Iterable[bytes]) -> None: |
| 145 |
raise NotImplementedError |
| 146 |
|
| 147 |
|
| 148 |
class FakeInventoryV2(FakeInventory): |
| 149 |
protocol_version = 2 |
| 150 |
|
| 151 |
def _write_headers(self, buffer: BinaryIO) -> None: |
| 152 |
super()._write_headers(buffer) |
| 153 |
buffer.write(b'# The remainder of this file is compressed using zlib.\n') |
| 154 |
|
| 155 |
def _write_body(self, buffer: BinaryIO, lines: Iterable[bytes]) -> None: |
| 156 |
compressor = zlib.compressobj(9) |
| 157 |
buffer.writelines(map(compressor.compress, lines)) |
| 158 |
buffer.write(compressor.flush()) |
| 159 |
|
| 160 |
|
| 161 |
class SingleEntryProject(IntersphinxProject): |
| 162 |
name = 'spam' |
| 163 |
port = 9341 # needed since otherwise it's an automatic port |
| 164 |
|
| 165 |
def __init__( |
| 166 |
self, |
| 167 |
version: int, |
| 168 |
route: str, |
| 169 |
*, |
| 170 |
item_name: str = 'ham', |
| 171 |
domain_name: str = 'py', |
| 172 |
object_type: str = 'module', |
| 173 |
) -> None: |
| 174 |
super().__init__( |
| 175 |
name=self.name, |
| 176 |
version=version, |
| 177 |
baseurl=f'http://localhost:{self.port}', |
| 178 |
baseuri=route, |
| 179 |
) |
| 180 |
self.item_name = item_name |
| 181 |
self.domain_name = domain_name |
| 182 |
self.object_type = object_type |
| 183 |
self.reftype = f'{domain_name}:{object_type}' |
| 184 |
|
| 185 |
def make_entry(self) -> InventoryEntry: |
| 186 |
"""Get an inventory entry for this project.""" |
| 187 |
name = f'{self.item_name}_{self.version}' |
| 188 |
return InventoryEntry( |
| 189 |
name, domain_name=self.domain_name, object_type=self.object_type |
| 190 |
) |
| 191 |
|
| 192 |
|
| 193 |
def make_inventory_handler( |
| 194 |
*projects: SingleEntryProject, |
| 195 |
) -> type[BaseHTTPRequestHandler]: |
| 196 |
name, port = projects[0].name, projects[0].port |
| 197 |
assert all(p.name == name for p in projects) |
| 198 |
assert all(p.port == port for p in projects) |
| 199 |
|
| 200 |
class InventoryHandler(BaseHTTPRequestHandler): |
| 201 |
def do_GET(self) -> None: |
| 202 |
self.send_response(200, 'OK') |
| 203 |
|
| 204 |
data = b'' |
| 205 |
for project in projects: |
| 206 |
# create the data to return depending on the endpoint |
| 207 |
if self.path.startswith(f'/{project.uri}/'): |
| 208 |
entry = project.make_entry() |
| 209 |
data = FakeInventoryV2(project).serialise([entry]) |
| 210 |
break |
| 211 |
|
| 212 |
self.send_header('Content-Length', str(len(data))) |
| 213 |
self.end_headers() |
| 214 |
self.wfile.write(data) |
| 215 |
|
| 216 |
def log_message(*args: Any, **kwargs: Any) -> None: |
| 217 |
pass |
| 218 |
|
| 219 |
return InventoryHandler |
| 220 |
|
| 221 |
|
| 222 |
def test_intersphinx_project_fixture() -> None: |
| 223 |
# check that our fixture class is correct |
| 224 |
project = SingleEntryProject(1, 'route') |
| 225 |
assert project.url == 'http://localhost:9341/route' |
| 226 |
|
| 227 |
|
| 228 |
def test_load_mappings_cache(tmp_path: Path) -> None: |
| 229 |
tmp_path.joinpath('conf.py').touch() |
| 230 |
tmp_path.joinpath('index.rst').touch() |
| 231 |
project = SingleEntryProject(1, 'a') |
| 232 |
|
| 233 |
InventoryHandler = make_inventory_handler(project) |
| 234 |
with http_server(InventoryHandler, port=project.port): |
| 235 |
# clean build |
| 236 |
confoverrides = BASE_CONFIG | {'intersphinx_mapping': project.record} |
| 237 |
app = SphinxTestApp('dummy', srcdir=tmp_path, confoverrides=confoverrides) |
| 238 |
app.build() |
| 239 |
app.cleanup() |
| 240 |
|
| 241 |
# the inventory when querying the 'old' URL |
| 242 |
entry = project.make_entry() |
| 243 |
item = dict((project.normalise(entry),)) |
| 244 |
inventories = InventoryAdapter(app.env) |
| 245 |
assert list(inventories.cache) == ['http://localhost:9341/a'] |
| 246 |
e_name, _e_time, e_inv = inventories.cache['http://localhost:9341/a'] |
| 247 |
assert e_name == 'spam' |
| 248 |
assert e_inv == {'py:module': item} |
| 249 |
assert inventories.named_inventory == {'spam': {'py:module': item}} |
| 250 |
|
| 251 |
|
| 252 |
def test_load_mappings_cache_update(tmp_path: Path) -> None: |
| 253 |
tmp_path.joinpath('conf.py').touch() |
| 254 |
tmp_path.joinpath('index.rst').touch() |
| 255 |
old_project = SingleEntryProject(1337, 'old') |
| 256 |
new_project = SingleEntryProject(1701, 'new') |
| 257 |
|
| 258 |
InventoryHandler = make_inventory_handler(old_project, new_project) |
| 259 |
with http_server(InventoryHandler, port=SingleEntryProject.port): |
| 260 |
# build normally to create an initial cache |
| 261 |
confoverrides1 = BASE_CONFIG | {'intersphinx_mapping': old_project.record} |
| 262 |
app1 = SphinxTestApp('dummy', srcdir=tmp_path, confoverrides=confoverrides1) |
| 263 |
app1.build() |
| 264 |
app1.cleanup() |
| 265 |
shutil.rmtree(app1.doctreedir / '__intersphinx_cache__', ignore_errors=True) |
| 266 |
|
| 267 |
# switch to new url and assert that the old URL is no more stored |
| 268 |
confoverrides2 = BASE_CONFIG | {'intersphinx_mapping': new_project.record} |
| 269 |
app2 = SphinxTestApp('dummy', srcdir=tmp_path, confoverrides=confoverrides2) |
| 270 |
app2.build() |
| 271 |
app2.cleanup() |
| 272 |
shutil.rmtree(app2.doctreedir / '__intersphinx_cache__', ignore_errors=True) |
| 273 |
|
| 274 |
entry = new_project.make_entry() |
| 275 |
item = dict((new_project.normalise(entry),)) |
| 276 |
inventories = InventoryAdapter(app2.env) |
| 277 |
# check that the URLs were changed accordingly |
| 278 |
assert list(inventories.cache) == ['http://localhost:9341/new'] |
| 279 |
e_name, _e_time, e_inv = inventories.cache['http://localhost:9341/new'] |
| 280 |
assert e_name == 'spam' |
| 281 |
assert e_inv == {'py:module': item} |
| 282 |
assert inventories.named_inventory == {'spam': {'py:module': item}} |
| 283 |
|
| 284 |
|
| 285 |
def test_load_mappings_cache_revert_update(tmp_path: Path) -> None: |
| 286 |
tmp_path.joinpath('conf.py').touch() |
| 287 |
tmp_path.joinpath('index.rst').touch() |
| 288 |
old_project = SingleEntryProject(1337, 'old') |
| 289 |
new_project = SingleEntryProject(1701, 'new') |
| 290 |
|
| 291 |
InventoryHandler = make_inventory_handler(old_project, new_project) |
| 292 |
with http_server(InventoryHandler, port=SingleEntryProject.port): |
| 293 |
# build normally to create an initial cache |
| 294 |
confoverrides1 = BASE_CONFIG | {'intersphinx_mapping': old_project.record} |
| 295 |
app1 = SphinxTestApp('dummy', srcdir=tmp_path, confoverrides=confoverrides1) |
| 296 |
app1.build() |
| 297 |
app1.cleanup() |
| 298 |
|
| 299 |
# switch to new url and build |
| 300 |
confoverrides2 = BASE_CONFIG | {'intersphinx_mapping': new_project.record} |
| 301 |
app2 = SphinxTestApp('dummy', srcdir=tmp_path, confoverrides=confoverrides2) |
| 302 |
app2.build() |
| 303 |
app2.cleanup() |
| 304 |
|
| 305 |
# switch back to old url (reuse 'old_item') |
| 306 |
confoverrides3 = BASE_CONFIG | {'intersphinx_mapping': old_project.record} |
| 307 |
app3 = SphinxTestApp('dummy', srcdir=tmp_path, confoverrides=confoverrides3) |
| 308 |
app3.build() |
| 309 |
app3.cleanup() |
| 310 |
|
| 311 |
entry = old_project.make_entry() |
| 312 |
item = dict((old_project.normalise(entry),)) |
| 313 |
inventories = InventoryAdapter(app3.env) |
| 314 |
# check that the URLs were changed accordingly |
| 315 |
assert list(inventories.cache) == ['http://localhost:9341/old'] |
| 316 |
e_name, _e_time, e_inv = inventories.cache['http://localhost:9341/old'] |
| 317 |
assert e_name == 'spam' |
| 318 |
assert e_inv == {'py:module': item} |
| 319 |
assert inventories.named_inventory == {'spam': {'py:module': item}} |