log
2026-07-10 4ab857aa892499fedce46f94fc2d8d2a91f4314f
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
import importlib
import json
import sys
import unittest
from pathlib import Path
from unittest.mock import patch
 
import pandas as pd
 
 
PROJECT_ROOT = Path(__file__).resolve().parents[1]
(PROJECT_ROOT / "logs").mkdir(exist_ok=True)
sys.path.insert(0, str(PROJECT_ROOT / "scripts"))
 
data_update_v2 = importlib.import_module("data_update_v2")
 
 
class FakeBaoStockResult:
    def __init__(self, data, error_code="0", error_msg="success"):
        self.error_code = error_code
        self.error_msg = error_msg
        self.fields = list(data.columns) if data is not None else []
        self._rows = data.values.tolist() if data is not None else []
        self._index = -1
 
    def get_data(self):
        raise AssertionError("fallback should iterate BaoStock rows without get_data()")
 
    def next(self):
        self._index += 1
        return self._index < len(self._rows)
 
    def get_row_data(self):
        return self._rows[self._index]
 
 
class FakeBaoStock:
    def __init__(self):
        self.logged_out = False
        self.stock_basic_calls = 0
        self.history_codes = []
        self.login_calls = 0
 
    def login(self):
        self.login_calls += 1
        return type("LoginResult", (), {"error_code": "0", "error_msg": "success"})()
 
    def logout(self):
        self.logged_out = True
 
    def query_stock_basic(self):
        self.stock_basic_calls += 1
        return FakeBaoStockResult(
            pd.DataFrame(
                [
                    {
                        "code": "sh.600519",
                        "code_name": "贵州茅台",
                        "ipoDate": "2001-08-27",
                        "outDate": "",
                        "type": "1",
                        "status": "1",
                    }
                ]
            )
        )
 
    def query_history_k_data_plus(
        self, code, fields, start_date, end_date, frequency, adjustflag
    ):
        self.history_codes.append(code)
        return FakeBaoStockResult(
            pd.DataFrame(
                [
                    {
                        "date": "2026-07-08",
                        "code": code,
                        "open": "1500.0",
                        "high": "1510.0",
                        "low": "1495.0",
                        "close": "1508.0",
                        "preclose": "1490.0",
                        "volume": "10000",
                        "amount": "15080000",
                        "turn": "0.12",
                        "pctChg": "1.20",
                    }
                ]
            )
        )
 
 
class DataUpdateV2BaoStockTests(unittest.TestCase):
    def test_fetch_akshare_stock_list_prefers_exchange_code_name_api(self):
        class FakeAkShare:
            def stock_info_a_code_name(self):
                return pd.DataFrame(
                    [
                        {"code": "000001", "name": "平安银行"},
                        {"code": "600519", "name": "贵州茅台"},
                    ]
                )
 
            def stock_zh_a_spot_em(self):
                raise AssertionError("stock_zh_a_spot_em should not be called")
 
        result = data_update_v2.fetch_akshare_stock_list(FakeAkShare())
 
        self.assertEqual(
            result.to_dict("records"),
            [
                {"代码": "000001", "名称": "平安银行"},
                {"代码": "600519", "名称": "贵州茅台"},
            ],
        )
 
    def test_parse_n_stocks_supports_all(self):
        self.assertIsNone(data_update_v2.parse_n_stocks("all"))
        self.assertIsNone(data_update_v2.parse_n_stocks("全部"))
        self.assertEqual(data_update_v2.parse_n_stocks("6000"), 6000)
 
    def test_parse_args_supports_bse_only(self):
        args = data_update_v2.parse_args(["--bse-only", "--days", "30"])
 
        self.assertTrue(args.bse_only)
        self.assertEqual(args.days, 30)
 
    def test_bse_codes_use_tencent_instead_of_baostock(self):
        self.assertIsNone(data_update_v2.to_baostock_code("920099"))
        self.assertIsNone(data_update_v2.to_baostock_code("830001"))
        self.assertEqual(data_update_v2.to_tencent_code("920099"), "bj920099")
        self.assertEqual(data_update_v2.to_tencent_code("830001"), "bj830001")
        self.assertEqual(data_update_v2.to_baostock_code("600519"), "sh.600519")
        self.assertEqual(data_update_v2.to_baostock_code("000001"), "sz.000001")
 
    def test_load_bse_code_mapping_contains_bettery_old_code(self):
        mapping = data_update_v2.load_bse_code_mapping()
 
        self.assertEqual(mapping["920185"], "835185")
        self.assertEqual(len(mapping), 248)
 
    def test_tencent_bse_symbol_candidates_include_legacy_code(self):
        symbols = data_update_v2.tencent_bse_symbol_candidates(
            "920185", {"920185": "835185"}
        )
 
        self.assertEqual(symbols, ["bj920185", "bj835185"])
 
    def test_convert_tencent_history_matches_existing_schema(self):
        raw = pd.DataFrame(
            [
                {
                    "date": "2026-07-07",
                    "open": 20.0,
                    "close": 20.5,
                    "high": 20.8,
                    "low": 19.8,
                    "amount": 1000.0,
                },
                {
                    "date": "2026-07-08",
                    "open": 20.6,
                    "close": 21.0,
                    "high": 21.2,
                    "low": 20.4,
                    "amount": 1200.0,
                },
            ]
        )
 
        result = data_update_v2.convert_tencent_history(
            raw, stock_code="920099", stock_name="测试北交所"
        )
 
        self.assertEqual(result.loc[0, "stock_code_api"], "bj920099")
        self.assertEqual(result.loc[0, "volume"], 1000.0)
        self.assertEqual(result.loc[0, "amount"], 2050000.0)
        self.assertAlmostEqual(result.loc[1, "change_pct"], (21.0 / 20.5 - 1) * 100)
        self.assertTrue(pd.isna(result.loc[0, "turnover"]))
 
    def test_fetch_tencent_history_raw_accepts_day_and_qfqday(self):
        row = ["2026-07-09", "20.0", "20.5", "20.8", "19.8", "1000"]
 
        class FakeResponse:
            def __init__(self, payload):
                self.text = "kline=" + json.dumps(payload)
 
            def raise_for_status(self):
                return None
 
        for data_key in ("day", "qfqday"):
            def fake_get(url, params, timeout, key=data_key):
                payload = {"data": {"bj920187": {key: [row]}}}
                return FakeResponse(payload)
 
            with self.subTest(data_key=data_key):
                result = data_update_v2.fetch_tencent_history_raw(
                    symbol="bj920187",
                    start_date="20260701",
                    end_date="20260710",
                    request_get=fake_get,
                )
 
                self.assertEqual(len(result), 1)
                self.assertEqual(result.loc[0, "date"], pd.Timestamp("2026-07-09"))
                self.assertEqual(result.loc[0, "close"], 20.5)
 
    def test_fetch_tencent_history_raw_returns_empty_for_unknown_code(self):
        class FakeResponse:
            text = 'kline={"data":{"bj999999":{"day":[]}}}'
 
            def raise_for_status(self):
                return None
 
        result = data_update_v2.fetch_tencent_history_raw(
            symbol="bj999999",
            start_date="20260701",
            end_date="20260710",
            request_get=lambda *args, **kwargs: FakeResponse(),
        )
 
        self.assertTrue(result.empty)
 
    def test_merge_replacement_data_replaces_only_downloaded_stocks(self):
        existing = pd.DataFrame(
            [
                {"stock_code": "600519", "date": pd.Timestamp("2026-07-08"), "close": 1.0},
                {"stock_code": "920185", "date": pd.Timestamp("2026-07-08"), "close": 2.0},
                {"stock_code": "920187", "date": pd.Timestamp("2026-07-08"), "close": 3.0},
            ]
        )
        replacement = pd.DataFrame(
            [
                {"stock_code": "920185", "date": pd.Timestamp("2026-07-09"), "close": 4.0},
            ]
        )
 
        result = data_update_v2.merge_replacement_data(existing, replacement)
 
        self.assertEqual(
            set(result["stock_code"]), {"600519", "920185", "920187"}
        )
        self.assertEqual(
            result[result["stock_code"] == "920185"]["close"].tolist(), [4.0]
        )
 
    def test_tencent_bse_fetch_uses_bj_market_prefix(self):
        class FakeFetcher:
            def __init__(self):
                self.symbols = []
 
            def __call__(self, **kwargs):
                self.symbols.append(kwargs["symbol"])
                return pd.DataFrame(
                    [
                        {
                            "date": "2026-07-08",
                            "open": 20.0,
                            "close": 20.5,
                            "high": 20.8,
                            "low": 19.8,
                            "amount": 1000.0,
                        }
                    ]
                )
 
        fake_fetch = FakeFetcher()
        stock_list = pd.DataFrame(
            [
                {"代码": "600519", "名称": "贵州茅台"},
                {"代码": "920099", "名称": "瑞华技术"},
            ]
        )
 
        with patch.object(
            data_update_v2,
            "fetch_tencent_history_raw",
            side_effect=fake_fetch,
        ):
            result = data_update_v2.fetch_real_stock_data_from_tencent_bse(
                stock_list=stock_list,
                days=10,
                request_delay=0,
            )
 
        self.assertIsNotNone(result)
        self.assertEqual(fake_fetch.symbols, ["bj920099"])
        self.assertEqual(result["stock_code"].unique().tolist(), ["920099"])
 
    def test_tencent_bse_fetch_falls_back_to_legacy_code_on_empty_new_code(self):
        class FakeFetcher:
            def __init__(self):
                self.symbols = []
 
            def __call__(self, **kwargs):
                symbol = kwargs["symbol"]
                self.symbols.append(symbol)
                if symbol == "bj920185":
                    return pd.DataFrame()
                return pd.DataFrame(
                    [
                        {
                            "date": "2026-07-08",
                            "open": 20.0,
                            "close": 20.5,
                            "high": 20.8,
                            "low": 19.8,
                            "amount": 1000.0,
                        }
                    ]
                )
 
        fake_fetch = FakeFetcher()
        stock_list = pd.DataFrame([{"代码": "920185", "名称": "贝特瑞"}])
 
        with patch.object(
            data_update_v2,
            "fetch_tencent_history_raw",
            side_effect=fake_fetch,
        ):
            with patch.object(
                data_update_v2,
                "load_bse_code_mapping",
                return_value={"920185": "835185"},
            ):
                result = data_update_v2.fetch_real_stock_data_from_tencent_bse(
                    stock_list=stock_list,
                    days=365,
                    max_retries=2,
                    retry_delay=0,
                    request_delay=0,
                )
 
        self.assertIsNotNone(result)
        self.assertEqual(fake_fetch.symbols, ["bj920185", "bj835185"])
        self.assertEqual(result.loc[0, "stock_code"], "920185")
        self.assertEqual(result.loc[0, "stock_code_api"], "bj835185")
 
    def test_tencent_bse_fetch_splits_date_range_at_code_switch(self):
        class FakeFetcher:
            def __init__(self):
                self.calls = []
 
            def __call__(self, **kwargs):
                self.calls.append(kwargs)
                date = "2026-07-08" if kwargs["symbol"] == "bj920185" else "2025-10-08"
                return pd.DataFrame(
                    [
                        {
                            "date": date,
                            "open": 20.0,
                            "close": 20.5,
                            "high": 20.8,
                            "low": 19.8,
                            "amount": 1000.0,
                        }
                    ]
                )
 
        fake_fetch = FakeFetcher()
        stock_list = pd.DataFrame([{"代码": "920185", "名称": "贝特瑞"}])
 
        with patch.object(
            data_update_v2,
            "fetch_tencent_history_raw",
            side_effect=fake_fetch,
        ):
            with patch.object(
                data_update_v2,
                "load_bse_code_mapping",
                return_value={"920185": "835185"},
            ):
                result = data_update_v2.fetch_real_stock_data_from_tencent_bse(
                    stock_list=stock_list,
                    days=365,
                    request_delay=0,
                )
 
        self.assertEqual(len(result), 2)
        self.assertEqual(fake_fetch.calls[0]["symbol"], "bj920185")
        self.assertEqual(fake_fetch.calls[0]["start_date"], "20251009")
        self.assertEqual(fake_fetch.calls[1]["symbol"], "bj835185")
        self.assertEqual(fake_fetch.calls[1]["end_date"], "20251008")
 
    def test_fetch_stock_list_from_akshare_all_keeps_full_list(self):
        stock_list = pd.DataFrame(
            [{"代码": f"{index:06d}", "名称": f"测试{index}"} for index in range(10)]
        )
 
        with patch.object(
            data_update_v2,
            "fetch_akshare_stock_list",
            return_value=stock_list,
        ):
            with patch.dict(sys.modules, {"akshare": object()}):
                result = data_update_v2.fetch_stock_list_from_akshare(n_stocks=None)
 
        self.assertEqual(len(result), 10)
 
    def test_akshare_history_failures_abort_before_full_stock_pool(self):
        class FakeAkShare:
            def __init__(self):
                self.history_calls = 0
 
            def stock_info_a_code_name(self):
                return pd.DataFrame(
                    [
                        {"code": f"{index:06d}", "name": f"测试{index}"}
                        for index in range(1, 21)
                    ]
                )
 
            def stock_zh_a_hist(self, **kwargs):
                self.history_calls += 1
                raise ConnectionError(
                    "Remote end closed connection without response"
                )
 
        fake_ak = FakeAkShare()
 
        with patch.dict(sys.modules, {"akshare": fake_ak}):
            result = data_update_v2.fetch_real_stock_data_from_akshare_only(
                n_stocks=20, days=10, max_consecutive_failures=3
            )
 
        self.assertIsNone(result)
        self.assertEqual(fake_ak.history_calls, 3)
 
    def test_convert_baostock_history_matches_existing_schema(self):
        raw = pd.DataFrame(
            [
                {
                    "date": "2026-07-08",
                    "code": "sh.600519",
                    "open": "1500.0",
                    "high": "1510.0",
                    "low": "1495.0",
                    "close": "1508.0",
                    "preclose": "1490.0",
                    "volume": "10000",
                    "amount": "15080000",
                    "turn": "0.12",
                    "pctChg": "1.20",
                }
            ]
        )
 
        result = data_update_v2.convert_baostock_history(
            raw, stock_code="600519", stock_name="贵州茅台"
        )
 
        self.assertEqual(result.loc[0, "stock_code"], "600519")
        self.assertEqual(result.loc[0, "stock_name"], "贵州茅台")
        self.assertEqual(result.loc[0, "stock_code_api"], "sh.600519")
        self.assertEqual(float(result.loc[0, "change_pct"]), 1.20)
        self.assertEqual(float(result.loc[0, "turnover"]), 0.12)
        self.assertTrue(pd.api.types.is_datetime64_any_dtype(result["date"]))
        for col in ["open", "close", "high", "low", "volume", "amount"]:
            self.assertTrue(pd.api.types.is_numeric_dtype(result[col]))
 
    def test_fetch_uses_baostock_when_akshare_returns_no_rows(self):
        fake_bs = FakeBaoStock()
        akshare_stock_list = pd.DataFrame(
            [{"代码": "600519", "名称": "贵州茅台"}]
        )
 
        with patch.dict(sys.modules, {"baostock": fake_bs}):
            with patch.object(
                data_update_v2,
                "fetch_stock_list_from_akshare",
                return_value=akshare_stock_list,
            ):
                with patch.object(
                    data_update_v2,
                    "fetch_real_stock_data_from_akshare_only",
                    return_value=None,
                ):
                    result = data_update_v2.fetch_real_stock_data_from_akshare(
                        n_stocks=1, days=10
                    )
 
        self.assertIsNotNone(result)
        self.assertEqual(result["stock_code"].unique().tolist(), ["600519"])
        self.assertEqual(fake_bs.history_codes, ["sh.600519"])
        self.assertEqual(fake_bs.stock_basic_calls, 0)
        self.assertIn("ma5", result.columns)
        self.assertTrue(fake_bs.logged_out)
 
    def test_fallback_merges_baostock_and_tencent_bse_rows(self):
        class FakeTencentFetcher:
            def __init__(self):
                self.symbols = []
 
            def __call__(self, **kwargs):
                self.symbols.append(kwargs["symbol"])
                return pd.DataFrame(
                    [
                        {
                            "date": "2026-07-08",
                            "open": 20.0,
                            "close": 20.5,
                            "high": 20.8,
                            "low": 19.8,
                            "amount": 1000.0,
                        }
                    ]
                )
 
        fake_bs = FakeBaoStock()
        fake_tencent = FakeTencentFetcher()
        stock_list = pd.DataFrame(
            [
                {"代码": "600519", "名称": "贵州茅台"},
                {"代码": "920099", "名称": "瑞华技术"},
            ]
        )
 
        with patch.dict(sys.modules, {"baostock": fake_bs}):
            with patch.object(
                data_update_v2,
                "fetch_stock_list_from_akshare",
                return_value=stock_list,
            ):
                with patch.object(
                    data_update_v2,
                    "fetch_real_stock_data_from_akshare_only",
                    return_value=None,
                ):
                    with patch.object(
                        data_update_v2,
                        "fetch_tencent_history_raw",
                        side_effect=fake_tencent,
                    ):
                        result = data_update_v2.fetch_real_stock_data_from_akshare(
                            n_stocks=None, days=10
                        )
 
        self.assertEqual(fake_bs.history_codes, ["sh.600519"])
        self.assertEqual(fake_tencent.symbols, ["bj920099"])
        self.assertEqual(
            set(result["stock_code"].unique()), {"600519", "920099"}
        )
        self.assertEqual(result.attrs["source"], "baostock_tencent_real")
 
    def test_fetch_baostock_can_use_akshare_stock_list(self):
        fake_bs = FakeBaoStock()
        stock_list = pd.DataFrame(
            [
                {"代码": "000001", "名称": "平安银行"},
                {"代码": "600519", "名称": "贵州茅台"},
            ]
        )
 
        with patch.dict(sys.modules, {"baostock": fake_bs}):
            result = data_update_v2.fetch_real_stock_data_from_baostock(
                n_stocks=2, days=10, stock_list=stock_list
            )
 
        self.assertIsNotNone(result)
        self.assertEqual(fake_bs.history_codes, ["sz.000001", "sh.600519"])
        self.assertEqual(fake_bs.stock_basic_calls, 0)
        self.assertEqual(
            result[["stock_code", "stock_name"]].drop_duplicates().to_dict("records"),
            [
                {"stock_code": "000001", "stock_name": "平安银行"},
                {"stock_code": "600519", "stock_name": "贵州茅台"},
            ],
        )
        self.assertTrue(fake_bs.logged_out)
 
    def test_fetch_baostock_falls_back_to_baostock_list_without_akshare_list(self):
        fake_bs = FakeBaoStock()
 
        with patch.dict(sys.modules, {"baostock": fake_bs}):
            with patch.object(
                data_update_v2, "fetch_stock_list_from_akshare", return_value=None
            ), patch.object(
                data_update_v2, "fetch_real_stock_data_from_akshare_only", return_value=None
            ):
                result = data_update_v2.fetch_real_stock_data_from_akshare(
                    n_stocks=1, days=10
                )
 
        self.assertIsNotNone(result)
        self.assertEqual(result["stock_code"].unique().tolist(), ["600519"])
        self.assertEqual(fake_bs.stock_basic_calls, 1)
        self.assertIn("ma5", result.columns)
        self.assertTrue(fake_bs.logged_out)
 
    def test_fetch_baostock_relogs_in_and_retries_after_network_error(self):
        class FlakyBaoStock(FakeBaoStock):
            def __init__(self):
                super().__init__()
                self.fail_once = True
 
            def query_history_k_data_plus(
                self, code, fields, start_date, end_date, frequency, adjustflag
            ):
                self.history_codes.append(code)
                if self.fail_once:
                    self.fail_once = False
                    raise OSError("网络接收错误。")
                return FakeBaoStockResult(
                    pd.DataFrame(
                        [
                            {
                                "date": "2026-07-08",
                                "code": code,
                                "open": "1500.0",
                                "high": "1510.0",
                                "low": "1495.0",
                                "close": "1508.0",
                                "preclose": "1490.0",
                                "volume": "10000",
                                "amount": "15080000",
                                "turn": "0.12",
                                "pctChg": "1.20",
                            }
                        ]
                    )
                )
 
        fake_bs = FlakyBaoStock()
        stock_list = pd.DataFrame([{"代码": "600519", "名称": "贵州茅台"}])
 
        with patch.dict(sys.modules, {"baostock": fake_bs}):
            result = data_update_v2.fetch_real_stock_data_from_baostock(
                n_stocks=1,
                days=10,
                stock_list=stock_list,
                max_retries=1,
                retry_delay=0,
            )
 
        self.assertIsNotNone(result)
        self.assertEqual(fake_bs.history_codes, ["sh.600519", "sh.600519"])
        self.assertEqual(fake_bs.login_calls, 2)
        self.assertEqual(result["stock_code"].unique().tolist(), ["600519"])
 
    def test_fetch_baostock_retries_network_error_result(self):
        class NetworkErrorResultBaoStock(FakeBaoStock):
            def __init__(self):
                super().__init__()
                self.fail_once = True
 
            def query_history_k_data_plus(
                self, code, fields, start_date, end_date, frequency, adjustflag
            ):
                self.history_codes.append(code)
                if self.fail_once:
                    self.fail_once = False
                    return FakeBaoStockResult(
                        None,
                        error_code="10054",
                        error_msg="网络接收错误。",
                    )
                return FakeBaoStockResult(
                    pd.DataFrame(
                        [
                            {
                                "date": "2026-07-08",
                                "code": code,
                                "open": "1500.0",
                                "high": "1510.0",
                                "low": "1495.0",
                                "close": "1508.0",
                                "preclose": "1490.0",
                                "volume": "10000",
                                "amount": "15080000",
                                "turn": "0.12",
                                "pctChg": "1.20",
                            }
                        ]
                    )
                )
 
        fake_bs = NetworkErrorResultBaoStock()
        stock_list = pd.DataFrame([{"代码": "600519", "名称": "贵州茅台"}])
 
        with patch.dict(sys.modules, {"baostock": fake_bs}):
            result = data_update_v2.fetch_real_stock_data_from_baostock(
                n_stocks=1,
                days=10,
                stock_list=stock_list,
                max_retries=1,
                retry_delay=0,
                request_delay=0,
            )
 
        self.assertIsNotNone(result)
        self.assertEqual(fake_bs.history_codes, ["sh.600519", "sh.600519"])
        self.assertEqual(fake_bs.login_calls, 2)
        self.assertEqual(result["stock_code"].unique().tolist(), ["600519"])
 
    def test_fetch_baostock_sets_and_restores_socket_timeout(self):
        fake_bs = FakeBaoStock()
        stock_list = pd.DataFrame([{"代码": "600519", "名称": "贵州茅台"}])
 
        with patch.dict(sys.modules, {"baostock": fake_bs}):
            with patch.object(data_update_v2.socket, "getdefaulttimeout", return_value=None):
                with patch.object(data_update_v2.socket, "setdefaulttimeout") as set_timeout:
                    result = data_update_v2.fetch_real_stock_data_from_baostock(
                        n_stocks=1,
                        days=10,
                        stock_list=stock_list,
                        socket_timeout=12,
                        request_delay=0,
                    )
 
        self.assertIsNotNone(result)
        self.assertEqual(set_timeout.call_args_list[0].args, (12,))
        self.assertEqual(set_timeout.call_args_list[-1].args, (None,))
 
    def test_baostock_result_to_dataframe_uses_iterator_api(self):
        raw = pd.DataFrame([{"code": "sh.600519", "code_name": "贵州茅台"}])
 
        result = data_update_v2.baostock_result_to_dataframe(FakeBaoStockResult(raw))
 
        self.assertEqual(result.to_dict("records"), raw.to_dict("records"))
 
 
if __name__ == "__main__":
    unittest.main()