-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconftest.py
More file actions
80 lines (57 loc) · 2.4 KB
/
Copy pathconftest.py
File metadata and controls
80 lines (57 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""Pytest bootstrap + test isolation.
Intent: tests must NEVER touch the production DuckDB store. Redirect both the
path resolver (``quant.paths.DB_FILE``) and the database module's bound
``DB_PATH`` to an ephemeral file, then reset the thread-local connection so the
redirect actually takes effect.
Invariants:
- ``quant.data.database.DB_PATH`` points at a tmp file for the whole session.
- The thread-local connection is dropped before ``init_db()`` so the patched
path is used (``database.py`` binds ``DB_PATH`` at import time).
- Production ``quant_cache.duckdb`` is never opened or deleted.
Dependencies: quant.paths, quant.data.database.
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
from pytest import MonkeyPatch
ROOT = Path(__file__).resolve().parent.parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
@pytest.fixture(scope="session", autouse=True)
def isolated_db(tmp_path_factory):
"""Isolate the whole test session in an ephemeral DuckDB file.
State Transition: real DB_PATH -> patched tmp DB_PATH -> init_db() ->
tests run -> connection dropped (tmp_path_factory cleans the file).
"""
from quant import paths
from quant.data import database
mp = MonkeyPatch()
test_db = tmp_path_factory.mktemp("test") / "test.duckdb"
mp.setattr(paths, "DB_FILE", str(test_db))
mp.setattr(database, "DB_PATH", str(test_db))
# database.py caches the connection in a thread-local; drop it so the
# patched DB_PATH is honoured on the next connect.
database._local.conn = None
database.init_db()
yield
database._local.conn = None
mp.undo()
@pytest.fixture(autouse=True)
def _offline_metadata(monkeypatch):
"""Keep tests hermetic by stubbing the SOURCES (yfinance, news), not our code.
D1: our production metadata/ISIN functions stay unmodified, so a recorded-source
test can replay the real path against a fixture by overriding the source only.
"""
import yfinance as yf
import quant.data.news as news
class _OfflineTicker:
isin = None
def __init__(self, *_a, **_k):
pass
def get_info(self):
return {}
monkeypatch.setattr(yf, "Ticker", _OfflineTicker, raising=False)
def _offline_fetch(*_a, **_k):
raise RuntimeError("offline")
monkeypatch.setattr(news, "_default_fetcher", _offline_fetch, raising=False)