import os import sys import pandas as pd from unittest.mock import MagicMock from src.fetchers.hk_fetcher import HkFetcher # Mock the IFindClient to avoid actual network requests and credentials class MockIFindClient: def __init__(self, refresh_token): pass def post(self, endpoint, params): # Simulate data availability logic # If querying for 20261231, return empty # If querying for 20251231, return data # Extract date from params date = "unknown" if "indipara" in params: for item in params["indipara"]: if "indiparams" in item and len(item["indiparams"]) > 0: param0 = item["indiparams"][0] if len(param0) == 8: # YYYYMMDD date = param0 break # Test Case 1: Detect year logic if "20261231" in date: return {"tables": [{"time": [], "table": {}}]} # Empty if "20251231" in date: return { "tables": [{ "time": ["2025-12-31"], "table": { "revenue_oas": [1000], "roe": [15.5], "total_oi": [5000] } }] } if "20241231" in date: return { "tables": [{ "time": ["2024-12-31"], "table": { "revenue_oas": [900], "roe": [14.0], "total_oi": [4000] } }] } return {"tables": []} def test_hk_fetcher_year_detection(): print("Testing HK Fetcher Year Detection Logic...") # Mock time.strftime to return 2026 import time original_strftime = time.strftime time.strftime = MagicMock(return_value="2026") try: fetcher = HkFetcher("fake_token") # Replace the client with our mock fetcher.cli = MockIFindClient("fake_token") # 1. Test get_income_statement logic print("\nTesting _fetch_financial_data_annual (via income statement)...") # We expect it to try 2026 (fail), then 2025 (succeed), then fetch 2025-2021 df_income = fetcher.get_income_statement("0700.HK") if not df_income.empty: dates = df_income['end_date'].tolist() print(f"Fetched Income Statement Dates: {dates}") if "20251231" in dates and "20261231" not in dates: print("PASS: Correctly anchored to 2025 instead of 2026.") else: print(f"FAIL: Logic incorrect. Dates found: {dates}") else: print("FAIL: No data returned.") # 2. Test get_financial_ratios logic print("\nTesting get_financial_ratios...") df_ratios = fetcher.get_financial_ratios("0700.HK") if not df_ratios.empty: dates = df_ratios['end_date'].tolist() print(f"Fetched Ratios Dates: {dates}") if "20251231" in dates and "20261231" not in dates: print("PASS: Correctly anchored to 2025 instead of 2026.") else: print(f"FAIL: Logic incorrect. Dates found: {dates}") else: print("FAIL: No data returned.") finally: # Restore time time.strftime = original_strftime if __name__ == "__main__": test_hk_fetcher_year_detection()