summaryrefslogtreecommitdiff
path: root/shared/tests/test_db.py
blob: b9a9d5623ac1d39b8a897d1c7e4a3c51e675529e (plain)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"""Tests for the SQLAlchemy async database layer."""

import pytest
from decimal import Decimal
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock, patch


def make_candle():
    from shared.models import Candle

    return Candle(
        symbol="BTCUSDT",
        timeframe="1m",
        open_time=datetime(2024, 1, 1, tzinfo=timezone.utc),
        open=Decimal("50000"),
        high=Decimal("51000"),
        low=Decimal("49500"),
        close=Decimal("50500"),
        volume=Decimal("100"),
    )


def make_signal():
    from shared.models import Signal, OrderSide

    return Signal(
        id="sig-1",
        strategy="ma_cross",
        symbol="BTCUSDT",
        side=OrderSide.BUY,
        price=Decimal("50000"),
        quantity=Decimal("0.1"),
        reason="Golden cross",
        created_at=datetime(2024, 1, 1, tzinfo=timezone.utc),
    )


def make_order():
    from shared.models import Order, OrderSide, OrderType, OrderStatus

    return Order(
        id="ord-1",
        signal_id="sig-1",
        symbol="BTCUSDT",
        side=OrderSide.BUY,
        type=OrderType.LIMIT,
        price=Decimal("50000"),
        quantity=Decimal("0.1"),
        status=OrderStatus.PENDING,
        created_at=datetime(2024, 1, 1, tzinfo=timezone.utc),
    )


class TestDatabaseConstructor:
    def test_stores_url(self):
        from shared.db import Database

        db = Database("postgresql://user:pass@localhost/db")
        assert db._database_url == "postgresql+asyncpg://user:pass@localhost/db"

    def test_converts_url_prefix(self):
        from shared.db import Database

        db = Database("postgresql://host/db")
        assert db._database_url.startswith("postgresql+asyncpg://")

    def test_keeps_asyncpg_prefix(self):
        from shared.db import Database

        db = Database("postgresql+asyncpg://host/db")
        assert db._database_url == "postgresql+asyncpg://host/db"

    def test_get_session_exists(self):
        from shared.db import Database

        db = Database("postgresql+asyncpg://host/db")
        assert hasattr(db, "get_session")


class TestDatabaseConnect:
    @pytest.mark.asyncio
    async def test_connect_creates_engine_and_tables(self):
        from shared.db import Database

        db = Database("postgresql+asyncpg://host/db")

        mock_conn = AsyncMock()
        mock_cm = AsyncMock()
        mock_cm.__aenter__.return_value = mock_conn

        mock_engine = MagicMock()
        mock_engine.begin.return_value = mock_cm
        mock_engine.dispose = AsyncMock()

        with patch("shared.db.create_async_engine", return_value=mock_engine) as mock_create:
            with patch("shared.db.async_sessionmaker"):
                with patch("shared.db.Base") as mock_base:
                    mock_base.metadata.create_all = MagicMock()
                    await db.connect()
                    mock_create.assert_called_once()

    @pytest.mark.asyncio
    async def test_init_tables_is_alias_for_connect(self):
        from shared.db import Database

        db = Database("postgresql+asyncpg://host/db")

        mock_conn = AsyncMock()
        mock_cm = AsyncMock()
        mock_cm.__aenter__.return_value = mock_conn

        mock_engine = MagicMock()
        mock_engine.begin.return_value = mock_cm
        mock_engine.dispose = AsyncMock()

        with patch("shared.db.create_async_engine", return_value=mock_engine):
            with patch("shared.db.async_sessionmaker"):
                with patch("shared.db.Base") as mock_base:
                    mock_base.metadata.create_all = MagicMock()
                    await db.init_tables()
                    # Should succeed without error (same as connect)


class TestDatabaseClose:
    @pytest.mark.asyncio
    async def test_close_disposes_engine(self):
        from shared.db import Database

        db = Database("postgresql+asyncpg://host/db")
        mock_engine = AsyncMock()
        db._engine = mock_engine
        await db.close()
        mock_engine.dispose.assert_awaited_once()


class TestInsertCandle:
    @pytest.mark.asyncio
    async def test_insert_candle_uses_merge_and_commit(self):
        from shared.db import Database

        db = Database("postgresql+asyncpg://host/db")

        mock_session = AsyncMock()
        mock_session.merge = MagicMock(return_value=None)
        mock_session.__aenter__ = AsyncMock(return_value=mock_session)
        mock_session.__aexit__ = AsyncMock(return_value=False)

        db._session_factory = MagicMock(return_value=mock_session)

        candle = make_candle()
        await db.insert_candle(candle)

        mock_session.merge.assert_called_once()
        mock_session.commit.assert_awaited_once()


class TestInsertSignal:
    @pytest.mark.asyncio
    async def test_insert_signal_uses_add_and_commit(self):
        from shared.db import Database

        db = Database("postgresql+asyncpg://host/db")

        mock_session = AsyncMock()
        mock_session.add = MagicMock()
        mock_session.__aenter__ = AsyncMock(return_value=mock_session)
        mock_session.__aexit__ = AsyncMock(return_value=False)

        db._session_factory = MagicMock(return_value=mock_session)

        signal = make_signal()
        await db.insert_signal(signal)

        mock_session.add.assert_called_once()
        mock_session.commit.assert_awaited_once()


class TestInsertOrder:
    @pytest.mark.asyncio
    async def test_insert_order_uses_add_and_commit(self):
        from shared.db import Database

        db = Database("postgresql+asyncpg://host/db")

        mock_session = AsyncMock()
        mock_session.add = MagicMock()
        mock_session.__aenter__ = AsyncMock(return_value=mock_session)
        mock_session.__aexit__ = AsyncMock(return_value=False)

        db._session_factory = MagicMock(return_value=mock_session)

        order = make_order()
        await db.insert_order(order)

        mock_session.add.assert_called_once()
        mock_session.commit.assert_awaited_once()


class TestUpdateOrderStatus:
    @pytest.mark.asyncio
    async def test_update_order_status_uses_execute_and_commit(self):
        from shared.db import Database
        from shared.models import OrderStatus

        db = Database("postgresql+asyncpg://host/db")

        mock_session = AsyncMock()
        mock_session.__aenter__ = AsyncMock(return_value=mock_session)
        mock_session.__aexit__ = AsyncMock(return_value=False)

        db._session_factory = MagicMock(return_value=mock_session)

        filled = datetime(2024, 1, 2, tzinfo=timezone.utc)
        await db.update_order_status("ord-1", OrderStatus.FILLED, filled)

        mock_session.execute.assert_awaited_once()
        mock_session.commit.assert_awaited_once()


class TestGetCandles:
    @pytest.mark.asyncio
    async def test_get_candles_returns_list_of_dicts(self):
        from shared.db import Database

        db = Database("postgresql+asyncpg://host/db")

        # Create a mock row that behaves like a SA result row
        mock_row = MagicMock()
        mock_row._mapping = {
            "symbol": "BTCUSDT",
            "timeframe": "1m",
            "open_time": datetime(2024, 1, 1, tzinfo=timezone.utc),
            "open": Decimal("50000"),
            "high": Decimal("51000"),
            "low": Decimal("49500"),
            "close": Decimal("50500"),
            "volume": Decimal("100"),
        }

        mock_result = MagicMock()
        mock_result.fetchall.return_value = [mock_row]

        mock_session = AsyncMock()
        mock_session.execute = AsyncMock(return_value=mock_result)
        mock_session.__aenter__ = AsyncMock(return_value=mock_session)
        mock_session.__aexit__ = AsyncMock(return_value=False)

        db._session_factory = MagicMock(return_value=mock_session)

        result = await db.get_candles("BTCUSDT", "1m", 500)

        assert isinstance(result, list)
        assert len(result) == 1
        assert result[0]["symbol"] == "BTCUSDT"
        mock_session.execute.assert_awaited_once()