From dafc4fe746e538a1d3a801dac9a17a63580aaa0b Mon Sep 17 00:00:00 2001 From: James Addison Date: Tue, 18 Apr 2023 17:41:07 +0100 Subject: [PATCH] tests: linkcheck: add connection-count measurement --- tests/test_build_linkcheck.py | 38 ++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/tests/test_build_linkcheck.py b/tests/test_build_linkcheck.py index acfebd64999..0528bc39f54 100644 --- a/tests/test_build_linkcheck.py +++ b/tests/test_build_linkcheck.py @@ -15,6 +15,7 @@ from unittest import mock import pytest +from urllib3.poolmanager import PoolManager from sphinx.builders.linkcheck import HyperlinkAvailabilityCheckWorker, RateLimit from sphinx.testing.util import strip_escseq @@ -41,10 +42,45 @@ def do_GET(self): self.wfile.write(b"ok\n\n") +class ConnectionMeasurement: + """Measure the number of distinct host connections created during linkchecking""" + + def __init__(self): + self.connections = set() + self.urllib3_connection_from_url = PoolManager.connection_from_url + self.patcher = mock.patch.object( + target=PoolManager, + attribute='connection_from_url', + new=self._collect_connections(), + ) + + def _collect_connections(self): + def connection_collector(obj, url): + connection = self.urllib3_connection_from_url(obj, url) + self.connections.add(connection) + return connection + return connection_collector + + def __enter__(self): + self.patcher.start() + return self + + def __exit__(self, *args, **kwargs): + for connection in self.connections: + connection.close() + self.patcher.stop() + + @property + def connection_count(self): + return len(self.connections) + + @pytest.mark.sphinx('linkcheck', testroot='linkcheck', freshenv=True) def test_defaults(app): with http_server(DefaultsHandler): - app.build() + with ConnectionMeasurement() as m: + app.build() + assert m.connection_count <= 10 # Text output assert (app.outdir / 'output.txt').exists()