|
| 1 | +import os |
| 2 | +import sys |
| 3 | +import types |
| 4 | +import unittest |
| 5 | +from unittest.mock import patch |
| 6 | + |
| 7 | +import pandas as pd |
| 8 | + |
| 9 | +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) |
| 10 | + |
| 11 | +from data_provider.efinance_fetcher import EfinanceFetcher |
| 12 | + |
| 13 | + |
| 14 | +class TestEfinanceMainIndices(unittest.TestCase): |
| 15 | + def test_get_main_indices_prefers_jinkai_column_for_open_price(self): |
| 16 | + fetcher = EfinanceFetcher() |
| 17 | + fake_df = pd.DataFrame( |
| 18 | + { |
| 19 | + "股票代码": ["000001"], |
| 20 | + "最新价": [3200.0], |
| 21 | + "涨跌幅": [0.63], |
| 22 | + "涨跌额": [20.0], |
| 23 | + "今开": [3188.0], |
| 24 | + "开盘": [0.0], |
| 25 | + "最高": [3215.0], |
| 26 | + "最低": [3170.0], |
| 27 | + "成交量": [123456789], |
| 28 | + "成交额": [9876543210.0], |
| 29 | + "振幅": [1.2], |
| 30 | + } |
| 31 | + ) |
| 32 | + fake_efinance = types.SimpleNamespace( |
| 33 | + stock=types.SimpleNamespace(get_realtime_quotes=lambda *args, **kwargs: fake_df) |
| 34 | + ) |
| 35 | + |
| 36 | + with patch.dict(sys.modules, {"efinance": fake_efinance}): |
| 37 | + with patch.object(fetcher, "_set_random_user_agent", return_value=None), patch.object( |
| 38 | + fetcher, "_enforce_rate_limit", return_value=None |
| 39 | + ): |
| 40 | + data = fetcher.get_main_indices(region="cn") |
| 41 | + |
| 42 | + self.assertIsNotNone(data) |
| 43 | + self.assertEqual(len(data), 1) |
| 44 | + self.assertEqual(data[0]["code"], "sh000001") |
| 45 | + self.assertEqual(data[0]["name"], "上证指数") |
| 46 | + self.assertAlmostEqual(data[0]["open"], 3188.0) |
| 47 | + self.assertAlmostEqual(data[0]["current"], 3200.0) |
| 48 | + |
| 49 | + def test_get_main_indices_falls_back_to_kaipan_when_jinkai_is_missing(self): |
| 50 | + fetcher = EfinanceFetcher() |
| 51 | + fake_df = pd.DataFrame( |
| 52 | + { |
| 53 | + "股票代码": ["000001"], |
| 54 | + "最新价": [3200.0], |
| 55 | + "涨跌幅": [0.63], |
| 56 | + "涨跌额": [20.0], |
| 57 | + "今开": [""], |
| 58 | + "开盘": [3186.0], |
| 59 | + "最高": [3215.0], |
| 60 | + "最低": [3170.0], |
| 61 | + "成交量": [123456789], |
| 62 | + "成交额": [9876543210.0], |
| 63 | + "振幅": [1.2], |
| 64 | + } |
| 65 | + ) |
| 66 | + fake_efinance = types.SimpleNamespace( |
| 67 | + stock=types.SimpleNamespace(get_realtime_quotes=lambda *args, **kwargs: fake_df) |
| 68 | + ) |
| 69 | + |
| 70 | + with patch.dict(sys.modules, {"efinance": fake_efinance}): |
| 71 | + with patch.object(fetcher, "_set_random_user_agent", return_value=None), patch.object( |
| 72 | + fetcher, "_enforce_rate_limit", return_value=None |
| 73 | + ): |
| 74 | + data = fetcher.get_main_indices(region="cn") |
| 75 | + |
| 76 | + self.assertIsNotNone(data) |
| 77 | + self.assertEqual(len(data), 1) |
| 78 | + self.assertAlmostEqual(data[0]["open"], 3186.0) |
| 79 | + |
| 80 | + |
| 81 | +if __name__ == "__main__": |
| 82 | + unittest.main() |
0 commit comments