summaryrefslogtreecommitdiffstats
path: root/openbb_platform/core/tests/app/service/test_hub_service.py
blob: 37cab472d2286c1774ee5d3c47598cf95d6b6515 (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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
"""Test the hub_service.py module."""

# pylint: disable=W0212
# ruff: noqa: S105 S106


from pathlib import Path
from time import time
from unittest.mock import MagicMock, patch

import pytest
from jwt import encode
from openbb_core.app.service.hub_service import (
    Credentials,
    HubService,
    HubSession,
    HubUserSettings,
    OpenBBError,
)
from pydantic import SecretStr


@pytest.fixture
def mocker():
    """Fixture for mocker."""
    with patch("openbb_core.app.service.hub_service.HubService") as mock:
        yield mock


def test_v3tov4_map():
    """Test v3 to v4 map."""

    v3_keys = {
        "databento": "API_DATABENTO_KEY",
        "alpha_vantage": "API_KEY_ALPHAVANTAGE",
        "fmp": "API_KEY_FINANCIALMODELINGPREP",
        "nasdaq": "API_KEY_QUANDL",
        "polygon": "API_POLYGON_KEY",
        "fred": "API_FRED_KEY",
        "news_api": "API_NEWS_TOKEN",
        "biztoc": "API_BIZTOC_TOKEN",
        "cmc": "API_CMC_KEY",
        "finnhub": "API_FINNHUB_KEY",
        "whale_alert": "API_WHALE_ALERT_KEY",
        "glassnode": "API_GLASSNODE_KEY",
        "coinglass": "API_COINGLASS_KEY",
        "ethplorer": "API_ETHPLORER_KEY",
        "cryptopanic": "API_CRYPTO_PANIC_KEY",
        "crypto_panic": "API_CRYPTO_PANIC_KEY",  # If dev choses to use this name
        "bitquery": "API_BITQUERY_KEY",
        "smartstake": ["API_SMARTSTAKE_KEY", "API_SMARTSTAKE_TOKEN"],
        "messari": "API_MESSARI_KEY",
        "shroom": "API_SHROOM_KEY",
        "santiment": "API_SANTIMENT_KEY",
        "eodhd": "API_EODHD_KEY",
        "tokenterminal": "API_TOKEN_TERMINAL_KEY",
        "token_terminal": "API_TOKEN_TERMINAL_KEY",  # If dev choses to use this name
        "intrinio": "API_INTRINIO_KEY",
        "github": "API_GITHUB_KEY",
        "reddit": [
            "API_REDDIT_CLIENT_ID",
            "API_REDDIT_CLIENT_SECRET",
            "API_REDDIT_USERNAME",
            "API_REDDIT_USER_AGENT",
            "API_REDDIT_PASSWORD",
        ],
        "companies_house": "API_COMPANIESHOUSE_KEY",
        "companieshouse": "API_COMPANIESHOUSE_KEY",  # If dev choses to use this name
        "dappradar": "API_DAPPRADAR_KEY",
        "nixtla": "API_KEY_NIXTLA",
    }

    providers = sorted(
        [
            p.stem
            for p in Path("openbb_platform", "providers").glob("*")
            if p.is_dir() and p.name not in ("__pycache__", "tests")
        ]
    )

    for provider in providers:
        if provider in v3_keys:
            keys = v3_keys[provider]
            if not isinstance(keys, list):
                keys = [keys]
            for k in keys:
                assert k in HubService.V3TOV4


def test_connect_with_email_password():
    """Test connect with email and password."""
    mock_hub_session = MagicMock(spec=HubSession)
    with patch(
        "requests.post", return_value=MagicMock(status_code=200, json=lambda: {})
    ), patch.object(
        HubService,
        "_get_session_from_email_password",
        return_value=mock_hub_session,
    ):
        hub_service = HubService()
        result = hub_service.connect(email="test@example.com", password="password")

        assert result == mock_hub_session
        assert hub_service.session == mock_hub_session


def test_connect_with_sdk_token():
    """Test connect with Platform personal access token."""
    mock_hub_session = MagicMock(spec=HubSession)
    with patch(
        "requests.post", return_value=MagicMock(status_code=200, json=lambda: {})
    ), patch.object(
        HubService, "_get_session_from_platform_token", return_value=mock_hub_session
    ):
        hub_service = HubService()
        result = hub_service.connect(pat="pat")

        assert result == mock_hub_session
        assert hub_service.session == mock_hub_session


def test_connect_without_credentials():
    """Test connect without credentials."""
    hub_service = HubService()
    with pytest.raises(
        OpenBBError, match="Please provide 'email' and 'password' or 'pat'"
    ):
        hub_service.connect()


def test_get_session_from_email_password():
    """Test get session from email and password."""

    with patch(
        "openbb_core.app.service.hub_service.post",
        return_value=MagicMock(
            status_code=200,
            json=lambda: {
                "access_token": "token",
                "token_type": "Bearer",
                "uuid": "uuid",
                "email": "email",
                "username": "username",
                "primary_usage": "primary_usage",
            },
        ),
    ):
        result = HubService()._get_session_from_email_password("email", "password")
        assert isinstance(result, HubSession)


def test_get_session_from_platform_token():
    """Test get session from Platform personal access token."""

    with patch(
        "openbb_core.app.service.hub_service.post",
        return_value=MagicMock(
            status_code=200,
            json=lambda: {
                "access_token": "token",
                "token_type": "Bearer",
                "uuid": "uuid",
                "username": "username",
                "email": "email",
                "primary_usage": "primary_usage",
            },
        ),
    ):
        mock_token = (
            "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiIsImtpZCI6ImRiMjEyZDdhZj"
            "c2MWI0ZTNlOGNjZGM3OWQ5Zjk4YWM5In0.eyJhY2Nlc3NfdG9rZW4iOiJ0"
            "b2tlbiIsInRva2VuX3R5cGUiOiJCZWFyZXIiLCJ1dWlkIjoidXVpZCIsInV"
            "zZXJuYW1lIjoidXNlcm5hbWUiLCJlbWFpbCI6ImVtYWlsIiwicHJpbWFyeV9"
            "1c2FnZSI6InByaW1hcnlfdXNhZ2UifQ.FAtE8-a1a-313Zoa6dREIxGZOHaW9"
            "-JLZnFzyJ6dlHBZnkjQT2tfaaefxnTdAlSmToQwxGykvuatmI7L0wztPQ"
        )

        result = HubService()._get_session_from_platform_token(mock_token)
        assert isinstance(result, HubSession)


def test_disconnect():
    """Test disconnect."""

    with patch(
        "openbb_core.app.service.hub_service.get",
        return_value=MagicMock(
            status_code=200,
            json=lambda: {"success": True},
        ),
    ):
        mock_hub_session = MagicMock(
            spec=HubSession, access_token=SecretStr("token"), token_type="Bearer"
        )
        hub_service = HubService(session=mock_hub_session)

        assert hub_service.disconnect() is True
        assert hub_service.session is None


def test_get_user_settings():
    """Test get user settings."""
    with patch(
        "openbb_core.app.service.hub_service.get",
        return_value=MagicMock(
            status_code=200,
            json=lambda: {},
        ),
    ):
        mock_hub_session = MagicMock(
            spec=HubSession, access_token=SecretStr("token"), token_type="Bearer"
        )

        user_settings = HubService()._get_user_settings(mock_hub_session)
        assert isinstance(user_settings, HubUserSettings)


def test_put_user_settings():
    """Test put user settings."""

    with patch(
        "openbb_core.app.service.hub_service.put",
        return_value=MagicMock(
            status_code=200,
        ),
    ):
        mock_hub_session = MagicMock(
            spec=HubSession, access_token=SecretStr("token"), token_type="Bearer"
        )
        mock_user_settings = MagicMock(spec=HubUserSettings)

        assert (
            HubService()._put_user_settings(mock_hub_session, mock_user_settings)
            is True
        )


def test_hub2platform_v4_only():
    """Test hub2platform."""
    mock_user_settings = MagicMock(spec=HubUserSettings)
    mock_user_settings.features_keys = {
        "fmp_api_key": "abc",
        "polygon_api_key": "def",
        "fred_api_key": "ghi",
    }

    credentials = HubService().hub2platform(mock_user_settings)
    assert isinstance(credentials, Credentials)
    assert credentials.fmp_api_key.get_secret_value() == "abc"
    assert credentials.polygon_api_key.get_secret_value() == "def"
    assert credentials.fred_api_key.get_secret_value() == "ghi"


def test_hub2platform_v3_only():
    """Test hub2platform."""
    mock_user_settings = MagicMock(spec=HubUserSettings)
    mock_user_settings.features_keys = {
        "API_KEY_FINANCIALMODELINGPREP": "abc",
        "API_POLYGON_KEY": "def",
        "API_FRED_KEY": "ghi",
    }

    credentials = HubService().hub2platform(mock_user_settings)
    assert isinstance(credentials, Credentials)
    assert credentials.fmp_api_key.get_secret_value() == "abc"
    assert credentials.polygon_api_key.get_secret_value() == "def"
    assert credentials.fred