Skip to content
Python

test: keep tests off the network

Yijia-Xiao91c431914707
diff --git a/tests/conftest.py b/tests/conftest.py
index 9a8e3cd59..acbd85276 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,6 +1,7 @@
"""Shared pytest fixtures that prevent CI hangs when API keys are absent."""
import os
+import socket
import pytest
@@ -31,6 +32,19 @@ def pytest_configure(config):
config.addinivalue_line("markers", f"{marker}: {marker}-level tests")
[email protected](autouse=True)
+def _no_network(request, monkeypatch):
+ """Tests do not reach the network; one that must is marked integration."""
+ if request.node.get_closest_marker("integration"):
+ return
+
+ def refuse(self, address):
+ raise OSError(f"test tried to reach the network: {address}")
+
+ monkeypatch.setattr(socket.socket, "connect", refuse)
+ monkeypatch.setattr(socket.socket, "connect_ex", refuse)
+
+
_API_KEY_ENV_VARS = (
"OPENAI_API_KEY",
"GOOGLE_API_KEY",
diff --git a/tests/test_no_data_handling.py b/tests/test_no_data_handling.py
index 7b63d91ff..11635541e 100644
--- a/tests/test_no_data_handling.py
+++ b/tests/test_no_data_handling.py
@@ -34,6 +34,10 @@ class TestLoadOhlcvNoPoison(unittest.TestCase):
def test_empty_download_raises_and_does_not_cache(self):
empty = pd.DataFrame()
+ # Yahoo answers, so an empty download means the symbol has no data.
+ reachable = mock.patch.object(ohlcv, "vendor_reachable", return_value=True)
+ reachable.start()
+ self.addCleanup(reachable.stop)
with mock.patch.object(ohlcv.yf, "download", return_value=empty), \
self.assertRaises(NoMarketDataError):
ohlcv.load_ohlcv("FAKE", "2026-01-01")
diff --git a/tests/test_suite_isolation.py b/tests/test_suite_isolation.py
new file mode 100644
index 000000000..dd325c984
--- /dev/null
+++ b/tests/test_suite_isolation.py
@@ -0,0 +1,17 @@
+"""The suite runs the same on any machine: no test reaches the network."""
+
+import socket
+
+import pytest
+
+
[email protected]("connect", [
+ lambda: socket.create_connection(("192.0.2.1", 80), timeout=1),
+ lambda: socket.socket().connect_ex(("192.0.2.1", 80)),
+], ids=["connect", "connect_ex"])
+def test_a_test_cannot_reach_the_network(connect):
+ """A test that silently depends on a live vendor passes or fails with the
+ machine it runs on; conftest refuses the connection instead."""
+ with pytest.raises(OSError, match="reach the network"):
+ connect()