Debian Codegraph @

tests/utils.py

raw
1 from __future__ import annotations
2
3 __all__ = (
4 'http_server',
5 'extract_node',
6 'extract_element',
7 )
8
9 import os
10 import socket
11 from contextlib import contextmanager
12 from http.server import ThreadingHTTPServer
13 from pathlib import Path
14 from ssl import PROTOCOL_TLS_SERVER, SSLContext
15 from threading import Thread
16 from typing import TYPE_CHECKING
17 from urllib.parse import urlparse
18
19 from docutils import nodes
20
21 if TYPE_CHECKING:
22 from collections.abc import Iterator
23 from http.server import HTTPServer
24 from socketserver import BaseRequestHandler
25 from typing import Final
26
27 from docutils.nodes import Element, Node
28
29 from sphinx.application import Sphinx
30
31 TESTS_ROOT: Final[Path] = Path(__file__).resolve().parent
32 TEST_ROOTS_DIR: Final[Path] = TESTS_ROOT / (
33 'roots-read-only'
34 if 'CI' in os.environ and (TESTS_ROOT / 'roots-read-only').is_dir()
35 else 'roots'
36 )
37
38 # Generated with:
39 # $ openssl req -new -x509 -days 3650 -nodes -out cert.pem \
40 # -keyout cert.pem -addext "subjectAltName = DNS:localhost"
41 CERT_FILE: Final[str] = str(TESTS_ROOT / 'certs' / 'cert.pem')
42
43
44 class HttpServerThread(Thread):
45 def __init__(self, handler: type[BaseRequestHandler], *, port: int = 0) -> None:
46 """Constructs a threaded HTTP server.
47
48 The default port number of ``0`` delegates selection of a port number
49 to bind to Python.
50 See: https://docs.python.org/3/library/socketserver.html#asynchronous-mixins
51 """
52 super().__init__(daemon=True)
53 self.server = ThreadingHTTPServer(('localhost', port), handler)
54
55 def run(self) -> None:
56 self.server.serve_forever(poll_interval=0.001)
57
58 def terminate(self) -> None:
59 self.server.shutdown()
60 self.server.server_close()
61 self.join()
62
63
64 class HttpsServerThread(HttpServerThread):
65 def __init__(self, handler: type[BaseRequestHandler], *, port: int = 0) -> None:
66 super().__init__(handler, port=port)
67 sslcontext = SSLContext(PROTOCOL_TLS_SERVER)
68 sslcontext.load_cert_chain(CERT_FILE)
69 self.server.socket = sslcontext.wrap_socket(
70 self.server.socket, server_side=True
71 )
72
73
74 @contextmanager
75 def http_server(
76 handler: type[BaseRequestHandler],
77 *,
78 tls_enabled: bool = False,
79 port: int = 0,
80 ) -> Iterator[HTTPServer]:
81 server_cls = HttpsServerThread if tls_enabled else HttpServerThread
82 server_thread = server_cls(handler, port=port)
83 server_thread.start()
84 server_port = server_thread.server.server_port
85 assert port in {0, server_port}
86 try:
87 socket.create_connection(('localhost', server_port), timeout=0.5).close()
88 yield server_thread.server # Connection has been confirmed possible; proceed.
89 finally:
90 server_thread.terminate()
91
92
93 @contextmanager
94 def rewrite_hyperlinks(app: Sphinx, server: HTTPServer) -> Iterator[None]:
95 """Rewrite hyperlinks that refer to network location 'localhost:7777',
96 allowing that location to vary dynamically with the arbitrary test HTTP
97 server port assigned during unit testing.
98
99 :param app: The Sphinx application where link replacement is to occur.
100 :param server: Destination server to redirect the hyperlinks to.
101 """
102 match_netloc, replacement_netloc = (
103 'localhost:7777',
104 f'localhost:{server.server_port}',
105 )
106
107 def rewrite_hyperlink(_app: Sphinx, uri: str) -> str | None:
108 parsed_uri = urlparse(uri)
109 if parsed_uri.netloc != match_netloc:
110 return uri
111 return parsed_uri._replace(netloc=replacement_netloc).geturl()
112
113 listener_id = app.connect('linkcheck-process-uri', rewrite_hyperlink)
114 yield
115 app.disconnect(listener_id)
116
117
118 @contextmanager
119 def serve_application(
120 app: Sphinx,
121 handler: type[BaseRequestHandler],
122 *,
123 tls_enabled: bool = False,
124 port: int = 0,
125 ) -> Iterator[str]:
126 """Prepare a temporary server to handle HTTP requests related to the links
127 found in a Sphinx application project.
128
129 :param app: The Sphinx application.
130 :param handler: Determines how each request will be handled.
131 :param tls_enabled: Whether TLS (SSL) should be enabled for the server.
132 :param port: Optional server port (default: auto).
133
134 :return: The address of the temporary HTTP server.
135 """
136 with (
137 http_server(handler, tls_enabled=tls_enabled, port=port) as server,
138 rewrite_hyperlinks(app, server),
139 ):
140 yield f'localhost:{server.server_port}'
141
142
143 def extract_node(node: Node, /, *indices: int) -> Node:
144 """Walk down a docutils node tree by repeatedly indexing children.
145
146 Returns a Node (could be Element, Text, etc.)
147
148 Example::
149
150 extract_node(doc, 0, 2, 1) == doc[0][2][1]
151 """
152 current: Node = node
153
154 for depth, i in enumerate(indices):
155 path = ''.join(f'[{i}]' for i in indices[:depth])
156 assert isinstance(current, nodes.Element), (
157 f'Expected node{path} (at depth {depth}) to be an Element '
158 f'before indexing with [{i}], got {type(current).__name__!r}'
159 )
160 try:
161 current = current[i]
162 except IndexError as exc:
163 msg = (
164 f'Index {i} out of range for node{path} (at depth {depth}) '
165 f'for {type(current).__name__!r}'
166 )
167 raise AssertionError(msg) from exc
168
169 return current
170
171
172 def extract_element(node: Node, /, *indices: int) -> Element:
173 """Walk down a docutils node tree and return an Element.
174
175 Asserts the final result is an Element (for attribute/dict access).
176
177 Example::
178
179 node = extract_node(doc, 0, 2, 1)
180 node['uri'] # Safe: guaranteed to be docutils.nodes.Element
181 """
182 result = extract_node(node, *indices)
183 if isinstance(result, nodes.Element):
184 return result
185 path = ''.join(f'[{i}]' for i in indices)
186 msg = f'Expected node{path} to be an Element, got {type(result).__name__!r}'
187 raise AssertionError(msg)