test: keep tests off the network

- conftest refuses socket connections outside tests marked integration
- the one test that probed Yahoo for real now stubs the reachability check
This commit is contained in:
Yijia-Xiao
2026-09-24 05:00:36 +00:00
parent 1e9ad314d8
commit 91c4319147
3 changed files with 35 additions and 0 deletions
+14
View File
@@ -1,6 +1,7 @@
"""Shared pytest fixtures that prevent CI hangs when API keys are absent.""" """Shared pytest fixtures that prevent CI hangs when API keys are absent."""
import os import os
import socket
import pytest import pytest
@@ -31,6 +32,19 @@ def pytest_configure(config):
config.addinivalue_line("markers", f"{marker}: {marker}-level tests") config.addinivalue_line("markers", f"{marker}: {marker}-level tests")
@pytest.fixture(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 = ( _API_KEY_ENV_VARS = (
"OPENAI_API_KEY", "OPENAI_API_KEY",
"GOOGLE_API_KEY", "GOOGLE_API_KEY",
+4
View File
@@ -34,6 +34,10 @@ class TestLoadOhlcvNoPoison(unittest.TestCase):
def test_empty_download_raises_and_does_not_cache(self): def test_empty_download_raises_and_does_not_cache(self):
empty = pd.DataFrame() 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), \ with mock.patch.object(ohlcv.yf, "download", return_value=empty), \
self.assertRaises(NoMarketDataError): self.assertRaises(NoMarketDataError):
ohlcv.load_ohlcv("FAKE", "2026-01-01") ohlcv.load_ohlcv("FAKE", "2026-01-01")
+17
View File
@@ -0,0 +1,17 @@
"""The suite runs the same on any machine: no test reaches the network."""
import socket
import pytest
@pytest.mark.unit
@pytest.mark.parametrize("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()