Initial commit: cnfinancialscraper v1.0.47

This commit is contained in:
MoBai
2026-09-13 23:43:57 +08:00
commit 126e43db6f
172 changed files with 76156 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
# -*- coding: utf-8 -*-
"""cn-financial-scraper 测试根 conftest.
设计要点:
1. 第一时间禁用 Python 字节码生成(设置 sys.dont_write_bytecode = True),
同时通过环境变量 PYTHONDONTWRITEBYTECODE=1 让子进程继承。
注意:conftest.py 自身的 pyc 在 pytest import 它时已先于本文件执行而写入,
无法阻止,因此启动时主动清理历史残留(兼兜底 `py -m pytest` 直跑场景)。
2. 把 scripts/ 加入 sys.path,方便 `import sentiment_crawler` 等绝对导入。
"""
import os
import sys
import shutil
from pathlib import Path
# ---- 1) 阻止字节码生成 ----
os.environ.setdefault("PYTHONDONTWRITEBYTECODE", "1")
sys.dont_write_bytecode = True
# ---- 1.5) 启动即清理历史 __pycache__/.pyc 残留 ----
# 直跑 `py -m pytest`(未设环境变量)时本次仍会生成 conftest 自身 pyc,
# 但历史残留在此被清除;本次新生成的由 pytest_sessionfinish 收尾清理。
_project_root = Path(__file__).resolve().parent.parent
for _cache_dir in _project_root.rglob("__pycache__"):
try:
shutil.rmtree(_cache_dir)
except OSError:
pass
for _pyc in _project_root.rglob("*.pyc"):
try:
_pyc.unlink()
except OSError:
pass
# ---- 2) 确保 scripts/ 可导入 ----
scripts_dir = Path(__file__).parent.parent / "scripts"
sys.path.insert(0, str(scripts_dir))
def pytest_configure(config):
"""pytest 启动时再次确认字节码关闭。"""
sys.dont_write_bytecode = True
os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
def pytest_load_initial_conftests(early_config, parser, args):
"""在加载其他 conftest 之前强制设置(无需 pytest hook 装饰器)。"""
sys.dont_write_bytecode = True
os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
def pytest_sessionfinish(session, exitstatus):
"""测试会话结束后清理本次运行生成的字节码残留(含 conftest 自身 pyc)。
兜底直跑 `py -m pytest`(未走 runtests.py 包装、无环境变量)的场景,
保证无论哪种方式跑完测试,交付目录都不残留 __pycache__/.pyc。"""
for cache_dir in _project_root.rglob("__pycache__"):
try:
shutil.rmtree(cache_dir)
except OSError:
pass
for pyc in _project_root.rglob("*.pyc"):
try:
pyc.unlink()
except OSError:
pass
+231
View File
@@ -0,0 +1,231 @@
# -*- coding: utf-8 -*-
"""v5.0.0 模块B:akshare 兜底接线 + requests 限流接线测试(离线 mock)"""
import pytest
from scripts.akshare_fallback import akshare_to_records, fallback_akshare
# ============================================================
# 1. akshare_fallback 公共 helper
# ============================================================
def test_akshare_to_records_none():
assert akshare_to_records(None) == []
def test_akshare_to_records_list_of_dict():
assert akshare_to_records([{"a": 1, "b": 2}]) == [{"a": 1, "b": 2}]
def test_akshare_to_records_with_map(monkeypatch):
class FakeDF:
def to_dict(self, orient):
return [{"标题": "A", "链接": "http://x", "其他": "y"}]
out = akshare_to_records(FakeDF(), {"title": ["标题"], "url": ["链接"]})
assert out == [{"title": "A", "url": "http://x"}]
def test_akshare_to_records_bad_type():
assert akshare_to_records("not-a-list") == []
def test_fallback_akshare_no_such_func_returns_empty():
# akshare 未装或函数不存在 → 返回 [] 不抛
assert fallback_akshare("__no_such_func__", {}) == []
# ============================================================
# 2. cls_scraper 兜底接线
# ============================================================
def test_cls_get_telegraph_falls_back(monkeypatch):
"""主路径失败时降级到 akshare"""
from scripts import cls_scraper
monkeypatch.setattr(cls_scraper, "http_post", lambda *a, **k: (_ for _ in ()).throw(RuntimeError("blocked")))
fake = [{"title": "降级新闻", "url": "http://x", "publish_time": "2026-08-01"}]
monkeypatch.setattr("scripts.akshare_fallback.fallback_akshare", lambda *a, **k: fake)
out = cls_scraper.get_telegraph(limit=5)
assert out == fake
def test_cls_get_hot_articles_falls_back(monkeypatch):
from scripts import cls_scraper
monkeypatch.setattr(cls_scraper, "http_post", lambda *a, **k: None) # 返回空 → 主路径空
fake = [{"title": "hot"}]
monkeypatch.setattr("scripts.akshare_fallback.fallback_akshare", lambda *a, **k: fake)
# 主路径 resp is None → 直接 return [](不触发 except),只验证 except 分支的降级
# 通过抛异常验证
monkeypatch.setattr(cls_scraper, "http_post", lambda *a, **k: (_ for _ in ()).throw(ValueError("boom")))
assert cls_scraper.get_hot_articles(limit=3) == fake
def test_cls_search_articles_falls_back(monkeypatch):
from scripts import cls_scraper
monkeypatch.setattr(cls_scraper, "http_post", lambda *a, **k: (_ for _ in ()).throw(ValueError("boom")))
fake = [{"title": "搜到", "url": "http://y"}]
monkeypatch.setattr("scripts.akshare_fallback.fallback_akshare", lambda *a, **k: fake)
assert cls_scraper.search_articles("茅台", limit=3) == fake
def test_cls_fallback_internal_import_error_safe(monkeypatch):
"""fallback_akshare 本身抛异常时,scraper 返回空不崩"""
from scripts import cls_scraper
monkeypatch.setattr(cls_scraper, "http_post", lambda *a, **k: (_ for _ in ()).throw(ValueError("boom")))
def _boom(*a, **k):
raise RuntimeError("akshare broken")
monkeypatch.setattr("scripts.akshare_fallback.fallback_akshare", _boom)
assert cls_scraper.get_telegraph(limit=3) == []
# ============================================================
# 3. jisilu 兜底接线
# ============================================================
def test_jisilu_bond_fallback(monkeypatch):
from scripts.jisilu_scraper import _akshare_bond_fallback
fake = [{"bond_id": "113050", "bond_nm": "南银转债", "price": 120.5}]
monkeypatch.setattr("scripts.akshare_fallback.fallback_akshare", lambda *a, **k: fake)
assert _akshare_bond_fallback() == fake
def test_jisilu_bond_fallback_returns_empty_on_error(monkeypatch):
from scripts.jisilu_scraper import _akshare_bond_fallback
monkeypatch.setattr("scripts.akshare_fallback.fallback_akshare",
lambda *a, **k: (_ for _ in ()).throw(RuntimeError()))
assert _akshare_bond_fallback() == []
def test_jisilu_get_convertible_bonds_falls_back(monkeypatch):
"""resp is None 时降级到 akshare"""
from scripts import jisilu_scraper
monkeypatch.setattr(jisilu_scraper, "get_session", lambda headers=None: None)
monkeypatch.setattr(jisilu_scraper, "http_get", lambda *a, **k: None)
monkeypatch.setattr(jisilu_scraper, "rate_limit", lambda *a, **k: None)
monkeypatch.setattr(jisilu_scraper, "http_post", lambda *a, **k: None)
fake = [{"bond_id": "110000"}]
monkeypatch.setattr("scripts.akshare_fallback.fallback_akshare", lambda *a, **k: fake)
assert jisilu_scraper.get_convertible_bonds() == fake
# ============================================================
# 4. sina / wallstreetcn 兜底接线
# ============================================================
def test_sina_realtime_falls_back(monkeypatch):
from scripts import sina_scraper
monkeypatch.setattr(sina_scraper, "fetch_text", lambda *a, **k: "")
fake = [{"代码": "600519", "名称": "贵州茅台", "最新价": 1800.0, "涨跌幅": 2.3}]
monkeypatch.setattr("scripts.akshare_fallback.fallback_akshare", lambda *a, **k: fake)
out = sina_scraper.get_realtime_quote(["600519"])
assert "600519" in out
assert out["600519"]["name"] == "贵州茅台"
def test_wallstreetcn_live_falls_back(monkeypatch):
from scripts import wallstreetcn_scraper
monkeypatch.setattr(wallstreetcn_scraper, "http_get_json", lambda *a, **k: None)
monkeypatch.setattr(wallstreetcn_scraper, "rate_limit", lambda *a, **k: None)
fake = [{"title": "快讯", "content_text": "内容", "uri": "http://x"}]
monkeypatch.setattr("scripts.akshare_fallback.fallback_akshare", lambda *a, **k: fake)
out = wallstreetcn_scraper.get_live_news(limit=5)
assert out["total"] == 1
assert out["items"][0]["title"] == "快讯"
def test_wallstreetcn_articles_falls_back(monkeypatch):
from scripts import wallstreetcn_scraper
monkeypatch.setattr(wallstreetcn_scraper, "http_get_json", lambda *a, **k: None)
monkeypatch.setattr(wallstreetcn_scraper, "rate_limit", lambda *a, **k: None)
fake = [{"title": "文章"}]
monkeypatch.setattr("scripts.akshare_fallback.fallback_akshare", lambda *a, **k: fake)
out = wallstreetcn_scraper.get_articles(limit=5)
assert out["total"] == 1
# ============================================================
# 5. requests 限流接线(B4)
# ============================================================
def test_ratelimited_session_calls_rate_limit(monkeypatch):
from scripts.http_utils import RatelimitedSession
calls = []
monkeypatch.setattr("scripts.http_utils.rate_limit", lambda *a, **k: calls.append(k.get("url")))
class FakeResp:
def __init__(self): self.ok = True
class FakeSession:
def __init__(self): self.last_url = None
def get(self, url, **kw): self.last_url = url; return FakeResp()
inner = FakeSession()
rs = RatelimitedSession(inner)
rs.get("https://eastmoney.com/api?a=1")
assert inner.last_url == "https://eastmoney.com/api?a=1"
assert calls == ["https://eastmoney.com/api?a=1"]
def test_ratelimited_session_proxies_attributes():
from scripts.http_utils import RatelimitedSession
class Fake:
def __init__(self): self.headers = {"UA": "x"}
def close(self): return "closed"
rs = RatelimitedSession(Fake())
assert rs.headers == {"UA": "x"}
assert rs.close() == "closed"
def test_company_report_session_is_ratelimited():
from scripts.company_report_scraper import EastMoneyReportAPI
from scripts.http_utils import RatelimitedSession
api = EastMoneyReportAPI()
if api.session is not None: # requests 可用时
assert isinstance(api.session, RatelimitedSession)
def test_news_session_is_ratelimited():
from scripts.news_scraper import EastMoneyNewsAPI
from scripts.http_utils import RatelimitedSession
api = EastMoneyNewsAPI()
if api.session is not None:
assert isinstance(api.session, RatelimitedSession)
def test_em_json_get_requests_branch_ratelimited(monkeypatch):
"""_em_json_get 的 requests 分支也调用 rate_limit"""
from scripts import eastmoney_scraper
rate_calls = []
monkeypatch.setattr("scripts.http_utils.rate_limit", lambda *a, **k: rate_calls.append(k.get("url", "")))
class FakeResp:
text = '{"ok": true}'
def raise_for_status(self): pass
monkeypatch.setattr(eastmoney_scraper, "_requests", type("R", (), {"get": lambda *a, **k: FakeResp()})())
monkeypatch.setattr(eastmoney_scraper, "_HAS_REQUESTS", True)
out = eastmoney_scraper._em_json_get("https://push2.eastmoney.com/api/1")
assert out == {"ok": True}
assert len(rate_calls) == 1
+186
View File
@@ -0,0 +1,186 @@
# -*- coding: utf-8 -*-
"""v5.0.0 模块D:analyzer 重写测试(离线,无网络)"""
import json
from pathlib import Path
import pytest
from scripts.analyzer import (
calculate_risk_metrics, analyze_investment_style, suggest_similar_products,
generate_portfolio_replication, suggest_alternatives, analyze_product,
_normalize_series, _pct_changes, _max_drawdown,
)
def _synthetic_series(n=120, start=1.0, step=0.001):
return [{"date": f"d{i}", "nav": start + step * i} for i in range(n)]
# ============================================================
# 1. 真实风险指标
# ============================================================
def test_risk_metrics_returns_full_keys():
m = calculate_risk_metrics(_synthetic_series())
for k in ["annualized_return", "annualized_volatility", "max_drawdown",
"sharpe_ratio", "calmar_ratio", "positive_days", "total_days"]:
assert k in m, f"缺 {k}"
def test_risk_metrics_positive_series():
"""严格上涨序列:收益为正、回撤近 0、正收益天数 = 总天数"""
m = calculate_risk_metrics(_synthetic_series(120, step=0.001))
assert m["annualized_return"] > 0
assert m["max_drawdown"] < 0.01
assert m["positive_days"] == m["total_days"]
def test_risk_metrics_insufficient_data():
assert calculate_risk_metrics([{"nav": 1.0}, {"nav": 1.1}])["insufficient_data"] is True
def test_risk_metrics_sharpe_zero_when_flat():
"""平坦序列波动为 0 → 夏普为 0 而非除零"""
flat = [{"date": f"d{i}", "nav": 1.0} for i in range(60)]
m = calculate_risk_metrics(flat)
assert m["sharpe_ratio"] == 0.0
assert m["annualized_volatility"] == 0.0
def test_risk_metrics_drawdown_detected():
"""先涨后大跌 → 检测到显著回撤"""
vals = [1.0]
for i in range(1, 80):
vals.append(1.0 + 0.005 * i) # 上涨
vals += [vals[-1] * 0.7] # 单日 -30%
m = calculate_risk_metrics([{"nav": v} for v in vals])
assert m["max_drawdown"] > 0.25
def test_risk_metrics_numeric_list_input():
"""纯数值列表入参"""
m = calculate_risk_metrics([1.0 + 0.01 * i for i in range(60)])
assert m["annualized_return"] > 0
def test_risk_metrics_legacy_dict_estimate():
m = calculate_risk_metrics({"1year": 15.67, "3year": 50.0})
assert m.get("estimate") is True
assert m.get("annual_return") == pytest.approx(0.1567)
# ============================================================
# 2. 辅助函数
# ============================================================
def test_normalize_series_filters_invalid():
out = _normalize_series([{"nav": 1.0}, {"nav": None}, {"nav": "abc"}, {"nav": 2.0}])
assert out == [1.0, 2.0]
def test_max_drawdown():
assert _max_drawdown([1.0, 1.2, 0.9, 1.1]) == pytest.approx(0.25)
# ============================================================
# 3. 投资风格
# ============================================================
def test_style_concentration():
stocks = [{"code": f"60000{i}", "weight": w} for i, w in enumerate([20, 15, 12, 10, 8, 3, 2])]
style = analyze_investment_style({"stocks": stocks}, {"1year": 20})
assert "集中" in style # CR5 = 65 ≥ 50
def test_style_diversified():
stocks = [{"code": f"60000{i}", "weight": 3} for i in range(10)]
style = analyze_investment_style({"stocks": stocks}, {"1year": 8})
assert "分散" in style
def test_style_growth_vs_stable():
g = analyze_investment_style({"stocks": []}, {"1year": 40})
assert "成长" in g
s = analyze_investment_style({"stocks": []}, {"1year": 2})
assert "稳健" in s
def test_style_board_detection():
stocks = [{"code": "688111", "weight": 5}, {"code": "600519", "weight": 5}]
style = analyze_investment_style({"stocks": stocks}, None)
assert "科创板" in style or "沪主板" in style
# ============================================================
# 4. 组合复刻
# ============================================================
def test_replication_fallback_mapping():
rep = generate_portfolio_replication({
"product_name": "测试基金",
"holdings": {"stocks": [{"code": "600519", "name": "贵州茅台", "weight": 5}]},
"historical_nav": {"1year": 15},
})
assert rep["allocation"][0]["mapping_source"] == "fallback"
assert rep["allocation"][0]["alternative"] == suggest_alternatives("贵州茅台")
def test_replication_data_driven_mapping():
candidates = [
{"code": "000858", "name": "五粮液", "weight": 4.5},
{"code": "600036", "name": "招商银行", "weight": 9.0},
{"code": "300750", "name": "宁德时代", "weight": 3.0},
]
rep = generate_portfolio_replication({
"product_name": "白酒基金",
"holdings": {"stocks": [{"code": "600519", "name": "贵州茅台", "weight": 5.2}]},
"historical_nav": {"1year": 15},
}, candidates=candidates)
item = rep["allocation"][0]
assert item["mapping_source"] == "data-driven"
assert item["alternative"][0] == "五粮液" # 同沪/深主板 + 权重接近
def test_replication_similar_products_present():
rep = generate_portfolio_replication({
"product_name": "x", "holdings": {"stocks": []}, "historical_nav": {},
})
assert "similar_products" in rep
assert rep["total_suggestion"]
# ============================================================
# 5. 相似推荐 & 报告
# ============================================================
def test_suggest_similar_products_db_missing(tmp_path, monkeypatch):
monkeypatch.setattr("scripts.analyzer.SKILL_DATA_DIR", tmp_path)
out = suggest_similar_products({"product_type": "混合型", "historical_nav": {}})
assert out and ("note" in out[0] or "error" in out[0])
def test_suggest_similar_products_orders_by_distance(tmp_path, monkeypatch):
db = tmp_path / "fund_managers_distilled.json"
db.write_text(json.dumps({"managers": [
{"name": "近", "fund_type": "混合型", "annual_return": 15.0,
"volatility": 5.0, "max_drawdown": 10.0},
{"name": "远", "fund_type": "债券型", "annual_return": -40.0,
"volatility": 90.0, "max_drawdown": 80.0},
]}), encoding="utf-8")
monkeypatch.setattr("scripts.analyzer.SKILL_DATA_DIR", tmp_path)
out = suggest_similar_products({
"product_type": "混合型",
"historical_nav": [{"nav": 1.0 + 0.001 * i} for i in range(60)],
}, limit=2)
assert out[0]["name"] == "近" # 距离更近排前
def test_analyze_product_report_generation():
report = analyze_product({
"product_name": "测试", "product_code": "0001", "product_type": "混合型",
"company": "公司", "manager": "经理", "risk_level": "中",
"historical_nav": {"1year": 12},
})
assert "【产品分析报告】" in report
assert "风险指标" in report
+406
View File
@@ -0,0 +1,406 @@
# -*- coding: utf-8 -*-
"""浏览器层合并测试(原 4 个测试文件合并,减少文件数):
- browser_paginate:增强方法 + PageOperator 扩展(纯函数,无 IO)
- browser_fixes:v4.7 类人爬取加固(STEALTH_JS / humanlike_fetch / 资源泄漏)
- browser_enhancements:v5.0 广告拦截 / proxy / 重试 / 单例(离线 mock)
- humanlike:类人操作方法挂载与向后兼容(不依赖 Playwright)
完整 E2E 测试请在 playwright 环境运行。
"""
import inspect
import unittest
import pytest
# 注意:scripts/ 同时在 sys.path 上,`scripts.browser_scraper` 与 `browser_scraper`
# 会各自加载一份模块。本文件统一以 scripts 副本为唯一来源(别名回旧名),
# 否则 monkeypatch 补丁可能打不到被测函数/类所在的模块。
import scripts.browser_scraper as bs_mod
browser_scraper = bs_mod
from scripts.browser_scraper import (
BrowserScraper,
_strip_dynamic_markers, _guess_image_ext,
_should_block_url, _get_browser_scraper, release_browser,
AD_BLOCK_DOMAINS,
)
# ════════════ A. browser_paginate:增强方法 + PageOperator ════════════
class TestStripDynamic(unittest.TestCase):
def test_strips_scripts(self):
html = "<div>x<script>alert(1)</script></div>"
out = _strip_dynamic_markers(html)
self.assertNotIn("alert", out)
def test_strips_timestamp_10_13(self):
html = "<p>Published at 1700000000</p>"
out = _strip_dynamic_markers(html)
self.assertNotIn("1700000000", out)
self.assertIn("TS", out)
def test_strips_iso_datetime(self):
html = "<p>2026-07-29T10:00:00</p>"
out = _strip_dynamic_markers(html)
self.assertNotIn("2026-07-29T10:00:00", out)
def test_keeps_normal_content(self):
html = "<p>Static content 123</p>"
out = _strip_dynamic_markers(html)
self.assertIn("Static content", out)
class TestGuessImageExt(unittest.TestCase):
def test_jpg(self):
self.assertEqual(_guess_image_ext("https://x.com/a.jpg"), ".jpg")
def test_jpeg(self):
self.assertEqual(_guess_image_ext("https://x.com/a.jpeg"), ".jpg")
def test_png(self):
self.assertEqual(_guess_image_ext("https://x.com/path/b.png"), ".png")
def test_webp(self):
self.assertEqual(_guess_image_ext("https://x.com/x.webp?v=1"), ".webp")
def test_default(self):
self.assertEqual(_guess_image_ext("https://x.com/noext"), ".jpg")
class TestBrowserMethodsExist(unittest.TestCase):
"""检查所有新方法都已挂载到 BrowserScraper 类。"""
def test_all_methods_mounted(self):
for name in ("paginate", "extract_links", "follow_links",
"download_images", "capture_canvas", "fetch_full_article"):
with self.subTest(method=name):
self.assertTrue(hasattr(BrowserScraper, name),
f"BrowserScraper.{name} 未挂载")
class TestPageOperatorMethodsExist(unittest.TestCase):
"""检查 PageOperator 已扩展三个方法。"""
def test_all_methods_exist(self):
from scripts.web_parser import PageOperator
for name in ("paginate", "extract_all_links", "follow_links"):
with self.subTest(method=name):
self.assertTrue(hasattr(PageOperator, name),
f"PageOperator.{name} 未实现")
# ════════════ B. browser_fixes:v4.7 类人爬取加固 ════════════
class TestStealthJsContent(unittest.TestCase):
"""STEALTH_JS 应覆盖主要反检测指纹。"""
@classmethod
def setUpClass(cls):
cls.js = browser_scraper.STEALTH_JS
def test_webdriver_hidden(self):
self.assertIn("navigator", self.js)
self.assertIn("webdriver", self.js)
def test_plugins_spoof(self):
self.assertIn("PluginArray", self.js)
self.assertIn("namedItem", self.js)
def test_languages_platform(self):
self.assertIn("languages", self.js)
self.assertIn("platform", self.js)
def test_hardware_fingerprints(self):
self.assertIn("hardwareConcurrency", self.js)
self.assertIn("deviceMemory", self.js)
def test_permissions_api(self):
self.assertIn("permissions.query", self.js)
def test_chrome_runtime(self):
self.assertIn("chrome.runtime", self.js)
def test_webgl_spoof(self):
self.assertIn("37445", self.js) # UNMASKED_VENDOR_WEBGL
self.assertIn("37446", self.js) # UNMASKED_RENDERER_WEBGL
def test_window_outer(self):
self.assertIn("outerWidth", self.js)
self.assertIn("outerHeight", self.js)
def test_phantom_cleanup(self):
self.assertIn("callPhantom", self.js)
def test_min_fingerprint_count(self):
"""覆盖至少 10 个指纹项。"""
markers = ["webdriver", "PluginArray", "languages", "platform",
"hardwareConcurrency", "deviceMemory", "permissions.query",
"chrome.runtime", "37445", "outerWidth", "connection.rtt",
"callPhantom"]
hits = sum(1 for m in markers if m in self.js)
self.assertGreaterEqual(hits, 10, f"STEALTH_JS 指纹覆盖不足: {hits}/12")
class TestHumanlikeFetchSignature(unittest.TestCase):
"""humanlike_fetch 应支持新参数。"""
def test_new_params(self):
sig = inspect.signature(browser_scraper.BrowserScraper.humanlike_fetch)
for param in ("mouse_simulation", "input_selector", "input_text"):
self.assertIn(param, sig.parameters, f"缺少参数 {param}")
self.assertEqual(sig.parameters["mouse_simulation"].default, True)
def test_body_uses_mouse_and_type(self):
"""humanlike_fetch 方法体应调用 _human_mouse_move 与 _human_type。"""
src = inspect.getsource(browser_scraper.BrowserScraper.humanlike_fetch)
self.assertIn("_human_mouse_move", src)
self.assertIn("_human_type", src)
def test_finally_closes_page(self):
src = inspect.getsource(browser_scraper.BrowserScraper.humanlike_fetch)
self.assertIn("finally", src)
self.assertIn("page.close", src)
class TestResourceLeakFixes(unittest.TestCase):
"""fetch/extract_text 等应使用 try/finally 关闭 page。"""
def _src_of(self, func_name):
cls = browser_scraper.BrowserScraper
return inspect.getsource(getattr(cls, func_name))
def test_fetch_has_finally(self):
src = self._src_of("fetch")
self.assertIn("finally", src)
self.assertIn("page.close", src)
def test_extract_text_has_finally(self):
src = self._src_of("extract_text")
self.assertIn("finally", src)
self.assertIn("page.close", src)
def test_extract_multiple_has_finally(self):
src = self._src_of("extract_multiple")
self.assertIn("finally", src)
def test_extract_table_has_finally(self):
src = self._src_of("extract_table")
self.assertIn("finally", src)
class TestFetchRetry(unittest.TestCase):
"""fetch 应支持 retries 参数。"""
def test_retries_param(self):
sig = inspect.signature(browser_scraper.BrowserScraper.fetch)
self.assertIn("retries", sig.parameters)
self.assertEqual(sig.parameters["retries"].default, 2)
# ════════════ C. browser_enhancements:v5.0 广告拦截/代理/重试/单例 ════════════
def test_should_block_ad_image():
assert _should_block_url("https://ad.doubleclick.net/banner.jpg", "image") is True
def test_should_block_baidu_track():
assert _should_block_url("https://hm.baidu.com/hm.js?x=1", "script") is False # script 不拦
assert _should_block_url("https://hm.baidu.com/hm.js?x=1", "image") is True
def test_should_block_not_block_regular():
assert _should_block_url("https://eastmoney.com/pic.png", "image") is False
assert _should_block_url("https://example.com/article.html", "document") is False
def test_should_block_small_resources_kept():
# 非 image/media/font 类型(脚本/样式)不拦截,避免破坏页面
assert _should_block_url("https://doubleclick.net/x.js", "script") is False
assert _should_block_url("https://doubleclick.net/x.css", "stylesheet") is False
def test_ad_block_domains_nonempty():
assert len(AD_BLOCK_DOMAINS) >= 8
def test_resolve_proxy_string():
assert BrowserScraper._resolve_proxy("http://127.0.0.1:8080") == {"server": "http://127.0.0.1:8080"}
def test_resolve_proxy_socks():
assert BrowserScraper._resolve_proxy("socks5://1.2.3.4:1080") == {"server": "socks5://1.2.3.4:1080"}
def test_resolve_proxy_dict():
assert BrowserScraper._resolve_proxy({"server": "http://x", "username": "u"}) == \
{"server": "http://x", "username": "u"}
def test_init_accepts_new_params():
if not bs_mod.PLAYWRIGHT_AVAILABLE:
pytest.skip("Playwright 不可用")
bs = BrowserScraper(headless=True, proxy="http://127.0.0.1:8080", ad_block=False, channel="chromium")
assert bs.proxy == "http://127.0.0.1:8080"
assert bs.ad_block is False
assert bs.channel == "chromium"
def test_init_default_params():
if not bs_mod.PLAYWRIGHT_AVAILABLE:
pytest.skip("Playwright 不可用")
bs = BrowserScraper(headless=True)
assert bs.proxy is None
assert bs.ad_block is True
assert bs.channel == "chromium"
def test_extract_many_empty():
bs = object.__new__(BrowserScraper)
bs.timeout_ms = 30000
assert bs.extract_many([]) == []
def test_extract_many_playwright_missing(monkeypatch):
monkeypatch.setattr(bs_mod, "PLAYWRIGHT_AVAILABLE", False)
bs = object.__new__(BrowserScraper)
bs.timeout_ms = 30000
out = bs.extract_many(["https://a.com/1", "https://b.com/2"])
assert out == [("https://a.com/1", None), ("https://b.com/2", None)]
def test_with_retry_success():
if not bs_mod.PLAYWRIGHT_AVAILABLE:
pytest.skip("Playwright 不可用")
bs = BrowserScraper(headless=True)
assert bs._with_retry(lambda: 42, retries=2) == 42
def test_with_retry_failure(monkeypatch):
if not bs_mod.PLAYWRIGHT_AVAILABLE:
pytest.skip("Playwright 不可用")
monkeypatch.setattr(bs_mod.time, "sleep", lambda *a, **k: None)
bs = BrowserScraper(headless=True)
def _boom():
raise ValueError("x")
assert bs._with_retry(_boom, retries=1) is None
def test_singleton_none_when_unavailable(monkeypatch):
monkeypatch.setattr(bs_mod, "PLAYWRIGHT_AVAILABLE", False)
assert _get_browser_scraper(headless=True) is None
def test_release_browser_safe():
release_browser() # 不应抛异常
def test_singleton_idempotent_release(monkeypatch):
"""连续 release 幂等"""
release_browser()
release_browser()
def test_is_soft_blocked_detects_captcha():
from scripts.sentiment_crawler import SentimentCrawler
c = SentimentCrawler()
html = "<html><body>访问频率过高,请稍后再试,请输入验证码</body></html>"
assert c._is_soft_blocked(html) is True
def test_is_soft_blocked_false_for_normal():
from scripts.sentiment_crawler import SentimentCrawler
c = SentimentCrawler()
assert c._is_soft_blocked("<html>正常新闻内容</html>") is False
def test_is_soft_blocked_empty():
from scripts.sentiment_crawler import SentimentCrawler
c = SentimentCrawler()
assert c._is_soft_blocked("") is False
# ════════════ D. humanlike:类人操作方法挂载与兼容 ════════════
class TestHumanlikeMethodsExist(unittest.TestCase):
"""验证类人操作方法已挂载到 BrowserScraper 类。"""
@classmethod
def setUpClass(cls):
cls.methods = [m for m in dir(BrowserScraper) if not m.startswith("__")]
def test_human_mouse_move_exists(self):
self.assertIn("_human_mouse_move", self.methods)
def test_human_type_exists(self):
self.assertIn("_human_type", self.methods)
def test_human_dwell_exists(self):
self.assertIn("_human_dwell", self.methods)
def test_random_scroll_exists(self):
self.assertIn("_random_scroll", self.methods)
def test_random_viewport_exists(self):
self.assertIn("_random_viewport", self.methods)
def test_humanlike_fetch_exists(self):
self.assertIn("humanlike_fetch", self.methods)
def test_legacy_methods_still_present(self):
"""确保重构后原有方法仍然存在。"""
legacy = ["fetch", "extract_text", "screenshot", "paginate",
"extract_links", "follow_links", "download_images",
"capture_canvas", "fetch_full_article", "smart_fetch"]
for m in legacy:
self.assertIn(m, self.methods, f"Missing legacy method: {m}")
class TestHumanlikeDesign(unittest.TestCase):
"""测试类人操作设计的合理性(参数验证等)。"""
def test_humanlike_fetch_accepts_all_params(self):
"""验证 humanlike_fetch 接受预期参数。"""
sig = inspect.signature(BrowserScraper.humanlike_fetch)
params = list(sig.parameters.keys())
self.assertIn("url", params)
self.assertIn("scroll", params)
self.assertIn("dwell", params)
self.assertIn("random_viewport", params)
def test_no_new_dependencies(self):
"""验证类人操作不引入新依赖(全部基于标准库 + Playwright)。"""
from pathlib import Path as _Path
source = _Path(browser_scraper.__file__).read_text(encoding="utf-8")
# 确认不使用 AI/ML 库
self.assertNotIn("import torch", source)
self.assertNotIn("import tensorflow", source)
self.assertNotIn("import opencv", source)
self.assertNotIn("import cv2", source)
self.assertNotIn("from PIL", source)
self.assertNotIn("import selenium", source)
class TestBackwardCompatibility(unittest.TestCase):
"""确保增强后向后兼容。"""
def test_original_fetch_still_works(self):
"""原始 fetch 方法签名不变。"""
sig = inspect.signature(BrowserScraper.fetch)
params = list(sig.parameters.keys())
self.assertIn("url", params)
# 仍支持 wait_until, wait_selector, scroll, dismiss_cookies
self.assertIn("wait_until", params)
self.assertIn("scroll", params)
self.assertIn("dismiss_cookies", params)
def test_extract_text_unchanged(self):
"""extract_text 方法签名不变。"""
sig = inspect.signature(BrowserScraper.extract_text)
params = list(sig.parameters.keys())
self.assertIn("url", params)
self.assertIn("selector", params)
if __name__ == "__main__":
unittest.main()
+263
View File
@@ -0,0 +1,263 @@
# -*- coding: utf-8 -*-
"""
爬虫性能优化模块测试
"""
import os
import sys
import time
import pytest
from unittest.mock import MagicMock, patch
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts"))
# ============================================================
# DNS 缓存测试
# ============================================================
class TestDNSCache:
"""DNS 缓存测试"""
def test_cache_resolve(self):
"""测试 DNS 缓存解析"""
from crawl_performance import DNSCache
cache = DNSCache(ttl=60)
# 首次解析
ip1 = cache.resolve("localhost")
# 缓存命中
ip2 = cache.resolve("localhost")
assert ip1 is not None
assert ip1 == ip2
def test_cache_ttl(self):
"""测试缓存过期"""
from crawl_performance import DNSCache
cache = DNSCache(ttl=0) # 立即过期
ip1 = cache.resolve("localhost")
ip2 = cache.resolve("localhost")
# 即使 TTL=0,相同域名应该能解析
assert ip1 is not None
def test_cache_clear(self):
"""测试清除缓存"""
from crawl_performance import DNSCache
cache = DNSCache()
cache.resolve("localhost")
assert len(cache._cache) > 0
cache.clear()
assert len(cache._cache) == 0
# ============================================================
# CrawlResult 测试
# ============================================================
class TestCrawlResult:
"""CrawlResult 测试"""
def test_success_result(self):
"""测试成功结果"""
from crawl_performance import CrawlResult
result = CrawlResult(
url="https://example.com",
success=True,
status_code=200,
text="Hello",
elapsed=0.5,
)
assert result.success == True
assert result.status_code == 200
assert result.text == "Hello"
assert result.from_cache == False
def test_failure_result(self):
"""测试失败结果"""
from crawl_performance import CrawlResult
result = CrawlResult(
url="https://example.com",
success=False,
error="Connection timeout",
)
assert result.success == False
assert result.error == "Connection timeout"
# ============================================================
# PerformanceCrawler 测试
# ============================================================
class TestPerformanceCrawler:
"""PerformanceCrawler 测试"""
def test_init(self):
"""测试初始化"""
from crawl_performance import PerformanceCrawler
crawler = PerformanceCrawler(max_workers=3, timeout=10)
assert crawler.max_workers == 3
assert crawler.timeout == 10
def test_cache_mechanism(self):
"""测试缓存机制"""
from crawl_performance import PerformanceCrawler, CrawlResult
crawler = PerformanceCrawler()
# 手动设置缓存
result = CrawlResult(
url="https://example.com",
success=True,
status_code=200,
text="cached",
)
crawler._set_cache("https://example.com", result)
# 从缓存获取
cached = crawler._get_from_cache("https://example.com")
assert cached is not None
assert cached.text == "cached"
def test_cache_miss(self):
"""测试缓存未命中"""
from crawl_performance import PerformanceCrawler
crawler = PerformanceCrawler()
cached = crawler._get_from_cache("https://nonexistent.com")
assert cached is None
def test_stats(self):
"""测试统计信息"""
from crawl_performance import PerformanceCrawler
crawler = PerformanceCrawler()
stats = crawler.get_stats()
assert 'total_requests' in stats
assert 'cache_hits' in stats
assert 'errors' in stats
assert 'cache_hit_rate' in stats
assert 'avg_response_time' in stats
def test_clear_cache(self):
"""测试清除缓存"""
from crawl_performance import PerformanceCrawler, CrawlResult
crawler = PerformanceCrawler()
result = CrawlResult(url="https://example.com", success=True)
crawler._set_cache("https://example.com", result)
assert len(crawler._cache) > 0
crawler.clear_cache()
assert len(crawler._cache) == 0
def test_rate_limit(self):
"""测试限流"""
from crawl_performance import PerformanceCrawler
crawler = PerformanceCrawler()
# 首次请求不应等待
start = time.time()
crawler._rate_limit("https://example.com", delay=0.1)
elapsed = time.time() - start
# 应该很快完成
assert elapsed < 0.5
# ============================================================
# 全局函数测试
# ============================================================
class TestGlobalFunctions:
"""全局函数测试"""
def test_get_crawler(self):
"""测试获取全局爬虫"""
from crawl_performance import get_crawler, PerformanceCrawler
crawler = get_crawler(max_workers=2)
assert isinstance(crawler, PerformanceCrawler)
assert crawler.max_workers == 2
def test_get_crawler_singleton(self):
"""测试单例模式"""
from crawl_performance import get_crawler
crawler1 = get_crawler()
crawler2 = get_crawler()
assert crawler1 is crawler2
# ============================================================
# 集成测试(可选,需要网络)
# ============================================================
@pytest.mark.skipif(
os.environ.get("CI") == "true",
reason="跳过网络测试"
)
class TestNetworkIntegration:
"""网络集成测试(可选)"""
@pytest.mark.skip(reason="需要网络连接")
def test_single_get(self):
"""测试单个请求"""
from crawl_performance import PerformanceCrawler
crawler = PerformanceCrawler()
result = crawler.get("https://www.baidu.com", use_cache=False)
assert result.success == True
assert result.status_code == 200
assert result.text is not None
assert result.elapsed > 0
@pytest.mark.skip(reason="需要网络连接")
def test_batch_get(self):
"""测试批量请求"""
from crawl_performance import PerformanceCrawler
crawler = PerformanceCrawler(max_workers=3)
urls = [
"https://www.baidu.com",
"https://www.qq.com",
"https://www.sina.com",
]
results = crawler.batch_get(urls, rate_limit=False)
assert len(results) == 3
assert all(r.success for r in results)
@pytest.mark.skip(reason="需要网络连接")
def test_cache_hit(self):
"""测试缓存命中"""
from crawl_performance import PerformanceCrawler
crawler = PerformanceCrawler()
# 首次请求
result1 = crawler.get("https://www.baidu.com", use_cache=True)
assert result1.from_cache == False
# 第二次请求(应该命中缓存)
result2 = crawler.get("https://www.baidu.com", use_cache=True)
assert result2.from_cache == True
if __name__ == "__main__":
pytest.main([__file__, "-v"])
+237
View File
@@ -0,0 +1,237 @@
# -*- coding: utf-8 -*-
"""v5.0.0 模块A:数据源扩充测试(离线 mock,无网络)"""
import json
import re
from pathlib import Path
import pytest
from scripts.scrapable_registry import ScrapableRegistry, PREDEFINED_URLS
SKILL_DIR = Path(__file__).resolve().parent.parent
SOURCES_FILE = SKILL_DIR / "data" / "sentiment_sources.json"
# ============================================================
# 1. sentiment_sources.json schema 校验
# ============================================================
@pytest.fixture(scope="module")
def sources():
return json.loads(SOURCES_FILE.read_text(encoding="utf-8"))
REQUIRED_KEYS = ["name", "homepage", "search_urls", "credibility", "language", "tags"]
CATEGORIES = ["authoritative", "financial_vertical", "self_media", "international"]
def test_meta_version_is_700(sources):
assert sources["_meta"]["version"] == "7.0.0"
def test_total_sites_gte_50(sources):
total = sum(len(sources[c]) for c in CATEGORIES)
assert total >= 50, f"站点数 {total} < 50"
def test_every_category_grows(sources):
"""每类站点数相比 v4.9(9/11/10/7) 均有增加"""
baseline = {"authoritative": 14, "financial_vertical": 11,
"self_media": 10, "international": 7}
for cat in CATEGORIES:
assert len(sources[cat]) > baseline[cat], f"{cat} 未增长"
def test_required_keys_present(sources):
bad = []
for cat in CATEGORIES:
for s in sources[cat]:
for k in REQUIRED_KEYS:
if k not in s:
bad.append((s.get("name"), k))
assert not bad, f"缺必填键: {bad}"
def test_rss_feeds_key_on_all_sites(sources):
missing = [s["name"] for cat in CATEGORIES for s in sources[cat] if "rss_feeds" not in s]
assert not missing, f"无 rss_feeds 键: {missing}"
def test_some_sites_have_real_rss(sources):
"""至少 2 个站点有非空 RSS(v6.0.0 商业媒体源)"""
n = sum(1 for cat in CATEGORIES for s in sources[cat] if s.get("rss_feeds"))
assert n >= 2, f"非空 RSS 站点过少: {n}"
def test_homepage_urls_valid(sources):
bad = []
for cat in CATEGORIES:
for s in sources[cat]:
hp = s.get("homepage", "")
if not (hp.startswith("http://") or hp.startswith("https://")):
bad.append((s["name"], hp))
assert not bad, f"非法 homepage: {bad}"
def test_search_urls_templates_valid(sources):
"""search_urls 模板必须含 {kw} 占位符"""
bad = []
for cat in CATEGORIES:
for s in sources[cat]:
for tpl in s.get("search_urls", []):
if "{kw}" not in tpl:
bad.append((s["name"], tpl))
assert not bad, f"search_urls 缺 {{kw}}: {bad}"
def test_search_engines_include_baidu_sogou(sources):
engines = sources.get("search_engines", [])
names = {e["name"] for e in engines}
assert "baidu" in names, "缺 baidu 搜索引擎"
assert "sogou" in names, "缺 sogou 搜索引擎"
by_name = {e["name"]: e for e in engines}
assert by_name["baidu"]["engine"] == "baidu_html"
assert by_name["sogou"]["engine"] == "sogou_html"
assert by_name["baidu"]["needs_api_key"] is False
assert by_name["baidu"]["enabled"] is True
# ============================================================
# 2. scrapable_registry PREDEFINED_URLS 校验
# ============================================================
def test_predefined_urls_gte_220():
assert len(PREDEFINED_URLS) >= 220, f"PREDEFINED_URLS {len(PREDEFINED_URLS)} < 220"
def test_predefined_urls_format():
bad = [(n, u) for n, u in PREDEFINED_URLS.items()
if not (u.startswith("http://") or u.startswith("https://"))]
assert not bad, f"非法 URL: {bad}"
def test_new_entities_added():
for name in ["上海期货交易所", "上海银行间同业拆放利率", "香港交易所",
"中国银行业协会", "中国证券业协会"]:
assert name in PREDEFINED_URLS, f"缺少 {name}"
def test_futures_exchanges_all_present():
for name in ["上海期货交易所", "大连商品交易所", "郑州商品交易所",
"中国金融期货交易所", "上海国际能源交易中心", "广州期货交易所"]:
assert name in PREDEFINED_URLS
def test_registry_loadable():
reg = ScrapableRegistry()
assert reg.total > 0
inst = reg.get("中国工商银行")
assert inst is not None
# PREDEFINED_URLS 作为 URL 补全表:已注册机构缺 website 时用预定义补全
assert inst["website"] == PREDEFINED_URLS["中国工商银行"]
assert inst["scrapable"] is True
# ============================================================
# 3. structured_market_data 模块(akshare 缺失时安全降级)
# ============================================================
def test_list_data_types_nonempty():
from scripts.structured_market_data import list_data_types, AKSHARE_ROUTES
types = list_data_types()
assert len(types) >= 10
for t in types:
assert t["data_type"] in AKSHARE_ROUTES
def test_unknown_data_type_returns_none():
from scripts.structured_market_data import get_structured_data
assert get_structured_data("not_exist") is None
def test_akshare_missing_returns_none(monkeypatch):
"""akshare 不可用时:非宏观类型返回 None;宏观 4 项走 v7.0.0 HTTP 兜底"""
from scripts.structured_market_data import get_structured_data
monkeypatch.setattr("scripts.structured_market_data._call_akshare", lambda *a, **k: None)
# HTTP 兜底也模拟失败 → 全部 None(不抛异常)
monkeypatch.setattr("scripts.market_data_scraper.get_macro_indicator",
lambda *a, **k: [])
for dt in ["futures_spot", "macro_cpi", "shibor", "hk_spot", "us_spot",
"futures_daily", "futures_holding", "macro_gdp", "macro_ppi",
"macro_pmi", "macro_fx_reserves", "repo_rate"]:
assert get_structured_data(dt) is None, f"{dt} 应返回 None"
def test_akshare_missing_macro_http_fallback(monkeypatch):
"""v7.0.0: akshare 缺失但 HTTP 兜底可用时,宏观返回数据而非 None"""
from scripts.structured_market_data import get_structured_data
monkeypatch.setattr("scripts.structured_market_data._call_akshare", lambda *a, **k: None)
monkeypatch.setattr("scripts.market_data_scraper.get_macro_indicator",
lambda *a, **k: [{"date": "2026-07-01", "yoy": 0.5}])
rows = get_structured_data("macro_cpi", limit=2)
assert isinstance(rows, list) and rows and rows[0]["yoy"] == 0.5
# 非宏观类型不启用 HTTP 兜底
assert get_structured_data("shibor") is None
def test_akshare_missing_never_raises(monkeypatch):
"""_call_akshare 抛异常时 get_structured_data 吞掉;宏观兜底也失败时返回 None"""
from scripts.structured_market_data import get_structured_data
def _boom(*a, **k):
raise RuntimeError("akshare 异常")
monkeypatch.setattr("scripts.structured_market_data._call_akshare", _boom)
monkeypatch.setattr("scripts.market_data_scraper.get_macro_indicator",
lambda *a, **k: [])
assert get_structured_data("shibor") is None
assert get_structured_data("macro_cpi") is None
def test_kwargs_override_defaults(monkeypatch):
"""kwargs 覆盖默认参数;显式 None 不覆盖"""
from scripts.structured_market_data import get_structured_data
calls = {}
def _fake_call(func_name, kwargs):
calls["func"] = func_name
calls["kwargs"] = dict(kwargs)
return "OK"
monkeypatch.setattr("scripts.structured_market_data._call_akshare", _fake_call)
assert get_structured_data("macro_cpi", start_year="2022") == "OK"
assert calls["func"] == "macro_china_cpi"
assert calls["kwargs"]["start_year"] == "2022"
def test_fallback_to_empty_kwargs(monkeypatch):
"""默认参数调用失败时降级为空参数调用"""
from scripts.structured_market_data import get_structured_data
calls = []
def _fake_call(func_name, kwargs):
calls.append(dict(kwargs))
if kwargs:
return None
return "EMPTY_OK"
monkeypatch.setattr("scripts.structured_market_data._call_akshare", _fake_call)
assert get_structured_data("repo_rate") == "EMPTY_OK"
assert len(calls) == 2
assert calls[1] == {}
def test_akshare_routes_shape():
from scripts.structured_market_data import AKSHARE_ROUTES
for k, v in AKSHARE_ROUTES.items():
assert isinstance(v["func"], str) and v["func"]
assert isinstance(v["defaults"], dict)
def test_predefined_urls_no_duplicates():
"""PREDEFINED_URLS 无重复 URL(与既有 test_scrapable_registry 约束一致)"""
from collections import Counter
c = Counter(PREDEFINED_URLS.values())
dups = {u: n for u, n in c.items() if n > 1}
assert not dups, f"重复 URL: {dups}"
+209
View File
@@ -0,0 +1,209 @@
# -*- coding: utf-8 -*-
"""Tests for data_validator.py — data integrity validation"""
import json
import pytest
import tempfile
from pathlib import Path
from scripts.data_validator import (
validate_institution_registry,
validate_list_file,
validate_all_list_files,
run_full_validation,
)
class TestValidateInstitutionRegistry:
"""Test institution_registry.json validation"""
def test_passes_on_valid_registry(self):
"""Valid registry should pass"""
ok, msg, details = validate_institution_registry()
assert ok, f"Registry validation failed: {msg}"
assert "验证通过" in msg
assert details["total"] > 0
assert "types" in details
# Should have at least the major types
types = details["types"]
assert any("基金" in t for t in types), f"No fund type found in {list(types.keys())[:5]}"
def test_returns_details_with_types(self):
"""Details should contain type distribution"""
ok, msg, details = validate_institution_registry()
assert ok
types = details["types"]
total_from_types = sum(types.values())
assert total_from_types == details["total"]
class TestValidateListFile:
"""Test individual list file validation"""
def test_passes_with_valid_list_file(self):
"""A well-formed list file should pass"""
test_data = {
"type": "测试机构",
"institutions": [
{"name": "测试银行A", "code": "001"},
{"name": "测试银行B", "code": "002"},
],
"data_source": "测试数据源",
"update_time": "2026-01-01",
}
with tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False, encoding="utf-8"
) as f:
json.dump(test_data, f)
path = Path(f.name)
try:
ok, msg, details = validate_list_file(path)
assert ok, f"Validation failed: {msg}"
assert details["count"] == 2
assert details["type"] == "测试机构"
finally:
path.unlink(missing_ok=True)
def test_fails_on_missing_type_field(self):
"""Missing 'type' field should fail"""
test_data = {"institutions": [{"name": "X"}]}
with tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False, encoding="utf-8"
) as f:
json.dump(test_data, f)
path = Path(f.name)
try:
ok, msg, _ = validate_list_file(path)
assert not ok
assert "type" in msg.lower()
finally:
path.unlink(missing_ok=True)
def test_fails_on_missing_institutions_field(self):
"""Missing 'institutions' field should fail"""
test_data = {"type": "银行"}
with tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False, encoding="utf-8"
) as f:
json.dump(test_data, f)
path = Path(f.name)
try:
ok, msg, _ = validate_list_file(path)
assert not ok
assert "institutions" in msg.lower()
finally:
path.unlink(missing_ok=True)
def test_fails_on_empty_institutions(self):
"""Empty institutions list should fail"""
test_data = {"type": "银行", "institutions": []}
with tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False, encoding="utf-8"
) as f:
json.dump(test_data, f)
path = Path(f.name)
try:
ok, msg, _ = validate_list_file(path)
assert not ok
assert "空" in msg or "empty" in msg.lower()
finally:
path.unlink(missing_ok=True)
def test_fails_on_institutions_not_list(self):
"""institutions field should be a list"""
test_data = {"type": "银行", "institutions": "not-a-list"}
with tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False, encoding="utf-8"
) as f:
json.dump(test_data, f)
path = Path(f.name)
try:
ok, msg, _ = validate_list_file(path)
assert not ok
assert "数组" in msg or "array" in msg.lower()
finally:
path.unlink(missing_ok=True)
def test_fails_on_missing_name_in_record(self):
"""Each institution record must have a 'name' field"""
test_data = {
"type": "银行",
"institutions": [{"name": "OK"}, {"code": "no-name"}],
}
with tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False, encoding="utf-8"
) as f:
json.dump(test_data, f)
path = Path(f.name)
try:
ok, msg, _ = validate_list_file(path)
assert not ok
# Message should indicate data format error
assert "格式" in msg or "name" in msg.lower() or "错误" in msg
finally:
path.unlink(missing_ok=True)
def test_fails_on_invalid_json(self):
"""Invalid JSON should fail gracefully"""
path = Path(tempfile.mktemp(suffix=".json"))
path.write_text("not valid json {{{", encoding="utf-8")
try:
ok, msg, _ = validate_list_file(path)
assert not ok
assert "json" in msg.lower() or "解析" in msg
finally:
path.unlink(missing_ok=True)
def test_fails_on_nonexistent_file(self):
"""Nonexistent file should fail"""
# validate_list_file doesn't check existence explicitly —
# it will get a FileNotFoundError caught by the except block
pass # This is tested implicitly
class TestValidateAllListFiles:
"""Test batch list file validation"""
def test_returns_dict_of_results(self):
"""Should return results for all *_list.json files"""
results = validate_all_list_files()
assert isinstance(results, dict), f"Expected dict, got {type(results)}"
assert len(results) > 20, f"Expected >20 list files, got {len(results)}"
# All should be tuples of (bool, str, dict)
for fname, result in results.items():
assert isinstance(result, tuple), f"{fname}: expected tuple, got {type(result)}"
assert len(result) == 3, f"{fname}: expected 3-tuple, got {len(result)}"
def test_all_list_files_pass(self):
"""All real list files should pass validation"""
results = validate_all_list_files()
for fname, (ok, msg, _) in results.items():
assert ok, f"{fname} failed: {msg}"
class TestRunFullValidation:
"""Test the complete validation pipeline"""
def test_returns_expected_structure(self):
"""Should return dict with registry, list_files, summary keys"""
results = run_full_validation()
assert "registry" in results
assert "list_files" in results
assert "summary" in results
assert results["registry"]["passed"], f"Registry failed: {results['registry']['message']}"
def test_summary_counts_are_consistent(self):
"""Summary pass+fail should equal total"""
results = run_full_validation()
s = results["summary"]
assert s["passed"] + s["failed"] == s["total"]
assert s["total"] > 25
def test_total_institutions_positive(self):
"""Total institution count should be positive"""
results = run_full_validation()
assert results["summary"]["total_institutions"] > 1000
+325
View File
@@ -0,0 +1,325 @@
"""v1.1 .docx 字体乱码回归测试。
问题:生成的 .docx 在线查看正常,下载保存后字体乱掉。
原因:StdlibDocxWriter 的 <w:rPrDefault><w:rPr><w:rFonts ...></w:rPr></w:rPrDefault>
缺 w:eastAsia 属性 + w:hint + w:lang。
Word 在解析时对没有 eastAsia 属性的 CJK 字符使用系统默认字体,
当系统字体集不规范或字体缺失时,CJK 字符会被替换为非预期字体(乱码)。
修复后检查项:
1. <w:rPrDefault> 中 <w:rFonts> 必须含 w:ascii/w:hAnsi/w:eastAsia/w:cs 四个属性
2. 必须有 w:hint="eastAsia" 属性
3. 必含 <w:lang> 显式声明中文
4. 用 universal 字体(宋体/Times New Roman),不依赖特定字体存在
"""
from __future__ import annotations
import os
import sys
import re
import tempfile
import zipfile
from pathlib import Path
SKILL_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(SKILL_DIR / "scripts"))
# ============================================================
# 测试
# ============================================================
def test_docx_has_eastasia_font():
"""生成的 docx 必须含 w:eastAsia 属性(核心 bug 修复)。"""
from report_stdlib_fallbacks import StdlibDocxWriter
data = {
"summary": {"stock_name": "测试", "periodic_count": 1, "broker_count": 1, "announcement_count": 1, "has_buy_rating": True},
"periodic_reports": [],
"broker_reports": [],
"announcements": [],
}
with tempfile.TemporaryDirectory() as tmp:
output = os.path.join(tmp, "test.docx")
writer = StdlibDocxWriter()
writer.export_comprehensive_report(data, "000001", output)
# 读取 styles.xml
with zipfile.ZipFile(output, "r") as zf:
styles = zf.read("word/styles.xml").decode("utf-8")
# 核心检查:rFonts 含 eastAsia
assert 'w:eastAsia=' in styles, "缺少 w:eastAsia 字体定义(CJK 渲染关键)"
print(" ✓ 含 w:eastAsia 字体定义")
def test_docx_has_complete_font_quad():
"""rFonts 必须含 4 个字体属性:ascii/hAnsi/eastAsia/cs。"""
from report_stdlib_fallbacks import StdlibDocxWriter
data = {"summary": {}, "periodic_reports": [], "broker_reports": [], "announcements": []}
with tempfile.TemporaryDirectory() as tmp:
output = os.path.join(tmp, "test.docx")
StdlibDocxWriter().export_comprehensive_report(data, "T", output)
with zipfile.ZipFile(output, "r") as zf:
styles = zf.read("word/styles.xml").decode("utf-8")
# 提取 rFonts 那一行(默认的)
match = re.search(r'<w:rFonts\s+([^/]*?)/>', styles)
assert match, "未找到 <w:rFonts>"
attrs = match.group(1)
required = ["w:ascii", "w:hAnsi", "w:eastAsia", "w:cs"]
for attr in required:
assert attr in attrs, f"缺少字体属性 {attr}"
print(f" ✓ 4 个字体属性齐全:{required}")
def test_docx_has_hint_eastasia():
"""必须有 w:hint="eastAsia" 告诉 Word 优先按东亚字体处理。"""
from report_stdlib_fallbacks import StdlibDocxWriter
data = {"summary": {}, "periodic_reports": [], "broker_reports": [], "announcements": []}
with tempfile.TemporaryDirectory() as tmp:
output = os.path.join(tmp, "test.docx")
StdlibDocxWriter().export_comprehensive_report(data, "T", output)
with zipfile.ZipFile(output, "r") as zf:
styles = zf.read("word/styles.xml").decode("utf-8")
assert 'w:hint="eastAsia"' in styles, "缺少 w:hint='eastAsia'"
print(" ✓ 含 w:hint='eastAsia'")
def test_docx_has_language_tag():
"""必须有 <w:lang> 显式声明中文。"""
from report_stdlib_fallbacks import StdlibDocxWriter
data = {"summary": {}, "periodic_reports": [], "broker_reports": [], "announcements": []}
with tempfile.TemporaryDirectory() as tmp:
output = os.path.join(tmp, "test.docx")
StdlibDocxWriter().export_comprehensive_report(data, "T", output)
with zipfile.ZipFile(output, "r") as zf:
styles = zf.read("word/styles.xml").decode("utf-8")
assert "<w:lang" in styles, "缺少 <w:lang>"
# 必须声明 eastAsia 为中文(zh-CN/zh-TW/zh-HK 任一)
match = re.search(r'<w:lang[^>]+w:eastAsia="([^"]+)"', styles)
assert match and "zh" in match.group(1).lower(), f"eastAsia 语言应含 zh,实际: {match.group(1) if match else 'NOT FOUND'}"
print(f" ✓ <w:lang> 中文标记:{match.group(1)}")
def test_docx_uses_universal_fonts():
"""字体选择应该是 universal 字体(不依赖特定系统)。"""
from report_stdlib_fallbacks import StdlibDocxWriter
data = {"summary": {}, "periodic_reports": [], "broker_reports": [], "announcements": []}
with tempfile.TemporaryDirectory() as tmp:
output = os.path.join(tmp, "test.docx")
StdlibDocxWriter().export_comprehensive_report(data, "T", output)
with zipfile.ZipFile(output, "r") as zf:
styles = zf.read("word/styles.xml").decode("utf-8")
# 不应依赖 "微软雅黑"(Mac/Linux 没有)
# 应是 宋体 (SimSun) 或 宋体 unicode 字符串
# 微软雅黑 is risky on Mac/Linux
if "微软雅黑" in styles:
print(" ⚠️ 含微软雅黑,在 Mac/Linux 用户可能无此字体")
else:
print(" ✓ 不依赖中文专属字体(微软雅黑)")
# 应该含 宋体 或 SimSun
assert "宋体" in styles or "SimSun" in styles, "eastAsia 应使用 universal 字体(宋体/SimSun)"
print(" ✓ 使用 universal 字体(宋体/SimSun)")
def test_docx_validation_lifecycle():
"""完整生成 + 解析 + 检查生命周期。"""
from report_stdlib_fallbacks import StdlibDocxWriter
data = {
"summary": {"stock_name": "中文测试股", "periodic_count": 1, "broker_count": 1, "announcement_count": 1, "has_buy_rating": True},
"periodic_reports": [{"title": "测试报告", "publish_date": "2026-07-28", "url": "https://example.com"}],
"broker_reports": [{"title": "买入评级", "publish_date": "2026-07-28", "broker_name": "测试券商", "analyst": "分析师", "rating": "买入", "target_price": 100.0}],
"announcements": [{"title": "测试公告", "publish_date": "2026-07-28", "announcement_type": "分红", "url": ""}],
}
with tempfile.TemporaryDirectory() as tmp:
output = os.path.join(tmp, "test.docx")
StdlibDocxWriter().export_comprehensive_report(data, "000001", output)
# 用 python-docx 解析验证
try:
from docx import Document
doc = Document(output)
# 验证文本正确写入
text_found = False
for p in doc.paragraphs:
if "中文测试股" in p.text:
text_found = True
break
for tbl in doc.tables:
for row in tbl.rows:
for cell in row.cells:
if "中文测试股" in cell.text:
text_found = True
break
assert text_found, "中文内容未正确写入"
print(" ✓ python-docx 可正确解析,中文写入无误")
except ImportError:
print(" ⊘ python-docx 未安装,跳过解析验证")
pass
# 文件应 < 50KB(典型报告大小)
size = os.path.getsize(output)
assert size < 100_000, f"文件过大: {size} 字节"
print(f" ✓ 文件大小合理: {size} 字节")
# ============================================================
# PPTX 字体检查(v1.1 新增)
# ============================================================
def _read_pptx_theme(path: str) -> str:
"""从 pptx 文件读取 theme1.xml 的内容。"""
import zipfile
with zipfile.ZipFile(path, "r") as zf:
for n in zf.namelist():
if n.endswith("theme/theme1.xml"):
return zf.read(n).decode("utf-8")
return ""
def test_pptx_theme_has_ea_font():
"""PPTX theme 必须声明东亚字体(v1.1 修复:之前是空字符串)。"""
from report_stdlib_fallbacks import StdlibPptxWriter
data = {"summary": {}, "periodic_reports": [], "broker_reports": [], "announcements": []}
with tempfile.TemporaryDirectory() as tmp:
output = os.path.join(tmp, "test.pptx")
StdlibPptxWriter().export_comprehensive_report(data, "T", output)
theme = _read_pptx_theme(output)
# 必须含 ea typeface 且非空
import re
ea_matches = re.findall(r'<a:ea\s+typeface="([^"]*)"', theme)
assert ea_matches, "<a:ea typeface=...> 应在 theme 中声明"
for ea in ea_matches:
assert ea.strip(), f"<a:ea typeface> 不能为空字符串(v1.1 修复)"
print(f" ✓ PPTX theme 含东亚字体:{ea_matches}")
def test_pptx_theme_uses_universal_fonts():
"""PPTX theme 应使用 universal 字体(不依赖 微软雅黑)。"""
from report_stdlib_fallbacks import StdlibPptxWriter
data = {"summary": {}, "periodic_reports": [], "broker_reports": [], "announcements": []}
with tempfile.TemporaryDirectory() as tmp:
output = os.path.join(tmp, "test.pptx")
StdlibPptxWriter().export_comprehensive_report(data, "T", output)
theme = _read_pptx_theme(output)
if "微软雅黑" in theme:
print(" ⚠️ PPTX theme 含微软雅黑")
else:
print(" ✓ PPTX theme 不依赖 微软雅黑")
# ============================================================
# XLSX 字体检查(v1.1 新增)
# ============================================================
def _read_xlsx_styles(path: str) -> str:
"""从 xlsx 文件读取 styles.xml 内容。"""
import zipfile
with zipfile.ZipFile(path, "r") as zf:
return zf.read("xl/styles.xml").decode("utf-8")
def test_xlsx_uses_universal_font():
"""XLSX style 必须使用 universal 字体(v1.1 修复:之前用 微软雅黑)。"""
from report_stdlib_fallbacks import StdlibXlsxWriter
data = {"summary": {}, "periodic_reports": [], "broker_reports": [], "announcements": []}
with tempfile.TemporaryDirectory() as tmp:
output = os.path.join(tmp, "test.xlsx")
StdlibXlsxWriter().export_comprehensive_report(data, "T", output)
styles = _read_xlsx_styles(output)
# 不应该用 微软雅黑(Mac/Linux 没有)
assert "微软雅黑" not in styles, "XLSX 不应依赖 微软雅黑"
# 应该用 宋体 或其他 universal 字体
assert "宋体" in styles or "SimSun" in styles, "XLSX 应使用 universal 字体"
print(f" ✓ XLSX 使用 universal 字体(宋体/SimSun)")
def test_xlsx_openpyxl_path_uses_universal_font():
"""openpyxl 路径下生成的 xlsx 也用 universal 字体。"""
try:
from openpyxl import load_workbook
except ImportError:
print(" ⊘ openpyxl 未安装,跳过")
return
# 写一个使用 宋体 字体的工作簿,验证能 round-trip
from openpyxl import Workbook
from openpyxl.styles import Font
wb = Workbook()
ws = wb.active
ws['A1'] = "中文测试"
ws['A1'].font = Font(name='宋体')
with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False) as f:
path = f.name
try:
wb.save(path)
# 重新加载看是否能识别中文字体
wb2 = load_workbook(path)
font = wb2.active['A1'].font
assert font.name == "宋体", f"字体应为宋体,实际: {font.name}"
print(f" ✓ openpyxl 路径字体声明一致:{font.name}")
finally:
os.remove(path)
# ============================================================
# 运行所有
# ============================================================
def main():
tests = [
(name, obj)
for name, obj in globals().items()
if name.startswith("test_") and callable(obj)
]
passed = 0
failed = 0
for name, fn in tests:
try:
fn()
passed += 1
print(f" ✓ {name}")
except Exception as e:
print(f" ✗ {name}: {e}")
import traceback
traceback.print_exc()
failed += 1
print(f"\n{'='*60}\n字体修复测试: {passed} 通过, {failed} 失败\n{'='*60}")
return 0 if failed == 0 else 1
if __name__ == "__main__":
sys.exit(main())
+220
View File
@@ -0,0 +1,220 @@
# -*- coding: utf-8 -*-
"""v4.7 东方财富新增数据函数测试(两融/大宗/ETF流/龙虎榜席位/股东增减持)。
全部使用 mock,不发起真实网络请求,可在离线环境运行。
"""
import sys
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
# ==================== 两融 ====================
class TestMarginTrading(unittest.TestCase):
def _sample(self):
return [{
"DATE": "2026-07-31 00:00:00", "MARKET": "1", "SCODE": "600519",
"SECNAME": "贵州茅台", "RZYE": "18520000000", "RQYE": "130000000",
"RZRQYE": "18650000000", "RZRQYECZ": "210000000",
"RZMRE": "560000000", "RZCHE": "380000000", "RZJME": "180000000",
"RQMCL": "125000", "RQYL": "89000",
}]
def test_parse_fields(self):
with mock.patch("eastmoney_scraper._em_datacenter_get",
return_value=self._sample()):
from eastmoney_scraper import get_margin_trading
r = get_margin_trading(limit=10)
self.assertEqual(len(r), 1)
item = r[0]
self.assertEqual(item["code"], "600519")
self.assertEqual(item["name"], "贵州茅台")
self.assertEqual(item["margin_balance"], 185.2) # 亿元
self.assertEqual(item["short_balance"], 1.3)
self.assertEqual(item["margin_short_total"], 186.5)
self.assertEqual(item["margin_net_buy"], 1.8)
def test_empty_on_failure(self):
with mock.patch("eastmoney_scraper._em_datacenter_get", return_value=[]):
from eastmoney_scraper import get_margin_trading
self.assertEqual(get_margin_trading(), [])
def test_date_filter(self):
data = [{"DATE": "2026-07-31 00:00:00", "SCODE": "600519", "SECNAME": "A", "RZYE": "1"},
{"DATE": "2026-07-01 00:00:00", "SCODE": "000001", "SECNAME": "B", "RZYE": "2"}]
with mock.patch("eastmoney_scraper._em_datacenter_get", return_value=data):
from eastmoney_scraper import get_margin_trading
r = get_margin_trading(start_date="2026-07-30", end_date="2026-07-31")
self.assertEqual(len(r), 1)
self.assertEqual(r[0]["code"], "600519")
def test_market_filter_passed(self):
with mock.patch("eastmoney_scraper._em_datacenter_get",
return_value=[]) as mocked:
from eastmoney_scraper import get_margin_trading
get_margin_trading(market="sh")
# 校验 filter 包含 MARKET='1'
args, kwargs = mocked.call_args
self.assertIn("(MARKET='1')", kwargs.get("filter_str", ""))
# ==================== 大宗交易 ====================
class TestBlockTrades(unittest.TestCase):
def test_parse_datacenter(self):
data = [{
"TRADE_DATE": "2026-07-31 00:00:00", "SECURITY_CODE": "600519",
"SECURITY_NAME_ABBR": "贵州茅台", "DEAL_PRICE": 1600.0,
"CLOSE_PRICE": 1650.0, "PREMIUM_RATIO": -0.0303,
"DEAL_VOLUME": 500000, "DEAL_AMT": 800000000,
"BUYER_NAME": "机构专用", "SELLER_NAME": "中信证券",
"CHANGE_RATE": 1.2, "TURNOVER_RATE": 0.5,
}]
with mock.patch("eastmoney_scraper._em_datacenter_get", return_value=data):
from eastmoney_scraper import get_block_trades
r = get_block_trades(limit=10)
self.assertEqual(len(r), 1)
item = r[0]
self.assertEqual(item["code"], "600519")
self.assertEqual(item["price"], 1600.0)
self.assertEqual(item["discount_pct"], -3.03)
self.assertEqual(item["volume"], 500000)
self.assertEqual(item["buyer_branch"], "机构专用")
def test_empty_on_failure(self):
with mock.patch("eastmoney_scraper._em_datacenter_get", return_value=[]):
from eastmoney_scraper import get_block_trades
self.assertEqual(get_block_trades(), [])
# ==================== ETF 资金流 ====================
class TestEtfFundFlow(unittest.TestCase):
def test_parse(self):
data = {"data": {"diff": [{
"f12": "510050", "f14": "上证50ETF", "f2": 2.865, "f3": 0.35,
"f20": 58050000000, "f62": 250000000, "f66": 120000000,
"f72": 130000000, "f78": -50000000, "f84": -200000000,
"f124": "2026-07-31",
}]}}
with mock.patch("eastmoney_scraper._em_json_get", return_value=data):
from eastmoney_scraper import get_etf_fund_flow
r = get_etf_fund_flow(limit=10)
self.assertEqual(len(r), 1)
item = r[0]
self.assertEqual(item["code"], "510050")
self.assertEqual(item["name"], "上证50ETF")
self.assertEqual(item["main_net_inflow"], 2.5)
self.assertEqual(item["super_large_net"], 1.2)
def test_empty_on_failure(self):
with mock.patch("eastmoney_scraper._em_json_get", return_value=None):
from eastmoney_scraper import get_etf_fund_flow
self.assertEqual(get_etf_fund_flow(), [])
# ==================== 龙虎榜席位 ====================
class TestDragonTigerSeats(unittest.TestCase):
def test_parse(self):
data = [{
"SECURITY_CODE": "000628", "SECURITY_NAME_ABBR": "高新发展",
"TRADE_DATE": "2026-07-31 00:00:00",
"BILLBOARD_BUY_AMT": 1580000000, "BILLBOARD_SELL_AMT": 1230000000,
"BILLBOARD_NET_AMT": 350000000, "CHANGE_RATE": 10.02,
"CLOSE_PRICE": 35.5, "EXPLANATION": "日涨幅偏离值达7%",
"BUY_RATIO": 8.5, "SELL_RATIO": 6.2,
"BUY_SEAT": "机构专用;中信证券深圳分公司",
"SELL_SEAT": "机构专用",
}]
with mock.patch("eastmoney_scraper._em_datacenter_get", return_value=data):
from eastmoney_scraper import get_dragon_tiger_seats
r = get_dragon_tiger_seats("000628")
self.assertEqual(r["code"], "000628")
self.assertEqual(r["total_buy"], 15.8)
self.assertEqual(r["net"], 3.5)
self.assertIn("机构专用", r["buy_seats"])
def test_fallback_on_empty(self):
with mock.patch("eastmoney_scraper._em_datacenter_get", return_value=[]), \
mock.patch("eastmoney_scraper.get_dragon_tiger", return_value=[]):
from eastmoney_scraper import get_dragon_tiger_seats
r = get_dragon_tiger_seats("000628")
self.assertIn("warning", r)
self.assertIn("error", r)
# ==================== 股东增减持 ====================
class TestShareholderChanges(unittest.TestCase):
def _sample(self):
return [{
"CHANGE_DATE": "2026-07-31 00:00:00", "SECURITY_CODE": "600519",
"SECURITY_NAME": "贵州茅台", "PERSON_NAME": "张三",
"CHANGE_SHARES": -50000, "CHANGE_RATIO": -0.12,
"AVERAGE_PRICE": 1650.0, "CHANGE_AMOUNT": -82500000,
"CHANGE_AFTER_HOLDNUM": 25000000, "CHANGE_REASON": "个人资金需求",
"POSITION_NAME": "董事",
}]
def test_parse_direction(self):
with mock.patch("eastmoney_scraper._em_datacenter_get",
return_value=self._sample()):
from eastmoney_scraper import get_shareholder_changes
r = get_shareholder_changes(limit=10)
self.assertEqual(len(r), 1)
item = r[0]
# 负变动 → 减持
self.assertEqual(item["change_type"], "减持")
self.assertEqual(item["change_shares"], -50000)
self.assertEqual(item["person"], "张三")
def test_change_type_filter(self):
data = self._sample() + [{
"CHANGE_DATE": "2026-07-30 00:00:00", "SECURITY_CODE": "000001",
"SECURITY_NAME": "平安银行", "PERSON_NAME": "李四",
"CHANGE_SHARES": 100000, "CHANGE_REASON": "增持",
"POSITION_NAME": "",
}]
with mock.patch("eastmoney_scraper._em_datacenter_get", return_value=data):
from eastmoney_scraper import get_shareholder_changes
r = get_shareholder_changes(change_type="增持")
self.assertEqual(len(r), 1)
self.assertEqual(r[0]["person"], "李四")
def test_empty_on_failure(self):
with mock.patch("eastmoney_scraper._em_datacenter_get", return_value=[]):
from eastmoney_scraper import get_shareholder_changes
self.assertEqual(get_shareholder_changes(), [])
# ==================== 安全转换边界 ====================
class TestSafeConvertBoundary(unittest.TestCase):
def test_safe_float_edge(self):
from eastmoney_scraper import _safe_float
self.assertEqual(_safe_float(None), 0.0)
self.assertEqual(_safe_float("-"), 0.0)
self.assertEqual(_safe_float("--"), 0.0)
self.assertEqual(_safe_float(""), 0.0)
self.assertEqual(_safe_float("1.23"), 1.23)
self.assertEqual(_safe_float("abc", 9.9), 9.9)
def test_safe_int_edge(self):
from eastmoney_scraper import _safe_int
self.assertEqual(_safe_int("0"), 0)
self.assertEqual(_safe_int(None), 0)
self.assertEqual(_safe_int("42"), 42)
if __name__ == "__main__":
unittest.main()
+218
View File
@@ -0,0 +1,218 @@
# -*- coding: utf-8 -*-
"""测试 fullpage_archiver.py — 纯函数部分(不依赖浏览器)。"""
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
sys.dont_write_bytecode = True
from fullpage_archiver import (
FullPageArchiver, ArchiveResult, _IMG_SRC_RE, _TABLE_RE,
)
class TestArchiveResult(unittest.TestCase):
"""ArchiveResult 数据类测试。"""
def test_to_dict(self):
r = ArchiveResult(
url="https://example.com",
title="Test Article",
page_count=3,
image_count=10,
canvas_count=2,
table_count=5,
)
d = r.to_dict()
self.assertEqual(d["url"], "https://example.com")
self.assertEqual(d["title"], "Test Article")
self.assertEqual(d["page_count"], 3)
def test_summary_contains_key_info(self):
r = ArchiveResult(
url="https://example.com",
title="测试文章",
page_count=2,
image_count=5,
canvas_count=1,
table_count=3,
inline_html_path="/tmp/test_inline.html",
)
s = r.summary
self.assertIn("测试文章", s)
self.assertIn("2", s) # page count
self.assertIn("5", s) # image count
self.assertIn("test_inline.html", s)
def test_summary_handles_errors(self):
r = ArchiveResult(
url="https://example.com",
errors=["连接超时", "图片下载失败"],
)
self.assertIn("2 个错误", r.summary)
class TestImageExtraction(unittest.TestCase):
"""图片 URL 提取正则测试。"""
def test_img_src_simple(self):
html = '<img src="https://example.com/img.jpg">'
matches = _IMG_SRC_RE.findall(html)
self.assertEqual(len(matches), 1)
self.assertEqual(matches[0], "https://example.com/img.jpg")
def test_img_src_single_quotes(self):
html = "<img src='https://example.com/img.png'>"
matches = _IMG_SRC_RE.findall(html)
self.assertEqual(len(matches), 1)
def test_img_src_multiple(self):
html = """
<img src="a.jpg" alt="A">
<img src="b.png" alt="B">
<img src="c.gif" alt="C">
"""
matches = _IMG_SRC_RE.findall(html)
self.assertEqual(len(matches), 3)
def test_img_data_uri_ignored(self):
"""data: URI 不应该被提取(由 _download_single_image 处理)。"""
html = '<img src="data:image/png;base64,ABC123">'
matches = _IMG_SRC_RE.findall(html)
self.assertEqual(len(matches), 1) # 提取出来,但在下载时跳过
self.assertIn("data:image/png", matches[0])
class TestTableExtraction(unittest.TestCase):
"""表格提取测试。"""
def test_simple_table(self):
html = """
<table>
<tr><th>Name</th><th>Value</th></tr>
<tr><td>营收</td><td>1500亿</td></tr>
<tr><td>净利润</td><td>300亿</td></tr>
</table>
"""
archiver = FullPageArchiver()
tables = archiver._extract_page_tables(html, 1, tempfile.mkdtemp())
self.assertEqual(len(tables), 1)
self.assertEqual(tables[0]["rows"], 3)
self.assertEqual(tables[0]["cols"], 2)
def test_empty_table_no_rows(self):
html = "<table></table>"
archiver = FullPageArchiver()
tables = archiver._extract_page_tables(html, 1, tempfile.mkdtemp())
self.assertEqual(len(tables), 0)
def test_table_with_colspan(self):
html = """
<table>
<tr><th>Header</th></tr>
<tr><td>Value 1</td></tr>
</table>
"""
archiver = FullPageArchiver()
tables = archiver._extract_page_tables(html, 1, tempfile.mkdtemp())
self.assertEqual(len(tables), 1)
def test_multiple_tables(self):
html = "<table><tr><td>A</td></tr></table><table><tr><td>B</td></tr></table>"
archiver = FullPageArchiver()
tables = archiver._extract_page_tables(html, 1, tempfile.mkdtemp())
self.assertEqual(len(tables), 2)
class TestHTMLProcessing(unittest.TestCase):
"""HTML 处理函数测试。"""
def test_extract_title(self):
html = "<html><head><title>测试标题</title></head><body></body></html>"
title = FullPageArchiver._extract_title(html)
self.assertEqual(title, "测试标题")
def test_extract_title_none(self):
title = FullPageArchiver._extract_title("<html></html>")
self.assertEqual(title, "")
def test_extract_domain(self):
domain = FullPageArchiver._extract_domain("https://www.example.com/path?a=1")
self.assertEqual(domain, "example.com")
def test_guess_image_ext(self):
self.assertEqual(FullPageArchiver._guess_image_ext("https://x.com/img.png"), ".png")
self.assertEqual(FullPageArchiver._guess_image_ext("https://x.com/img.jpg"), ".jpg")
self.assertEqual(FullPageArchiver._guess_image_ext("https://x.com/img.jpeg"), ".jpg")
self.assertEqual(FullPageArchiver._guess_image_ext("https://x.com/img.webp"), ".webp")
self.assertEqual(FullPageArchiver._guess_image_ext("https://x.com/img"), ".jpg") # default
def test_escape_html(self):
self.assertEqual(
FullPageArchiver._escape_html('<script>alert("XSS")</script>'),
'&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;',
)
def test_file_to_base64(self):
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False, mode="w") as f:
f.write("hello")
path = f.name
try:
b64 = FullPageArchiver._file_to_base64(path)
self.assertTrue(len(b64) > 0)
finally:
os.unlink(path)
def test_file_to_base64_missing(self):
b64 = FullPageArchiver._file_to_base64("/nonexistent/file.jpg")
self.assertEqual(b64, "")
class TestFallbackFetch(unittest.TestCase):
"""HTTP 回退抓取测试(不依赖浏览器)。"""
def test_http_fallback_returns_list(self):
archiver = FullPageArchiver()
# 用不存在的 URL 测试回退逻辑
result = archiver._fetch_pages_http("https://invalid.example.com/nonexistent")
self.assertIsInstance(result, list)
def test_http_fallback_empty_on_failure(self):
archiver = FullPageArchiver()
result = archiver._fetch_pages_http("https://192.0.2.1/nonexistent")
self.assertEqual(len(result), 0)
class TestInlineImageReplacement(unittest.TestCase):
"""图片内嵌替换测试。"""
def setUp(self):
self.archiver = FullPageArchiver()
def test_inline_with_no_images(self):
html = "<p>No images here</p>"
result = self.archiver._inline_images_in_html(html, {}, "https://example.com")
self.assertIn("No images here", result)
def test_relink_with_no_images(self):
html = "<p>No images here</p>"
result = self.archiver._relink_images_in_html(html, {})
self.assertIn("No images here", result)
def test_extract_body_content(self):
html = "<html><head></head><body><p>Hello</p></body></html>"
content = self.archiver._extract_body_content(html)
self.assertIn("Hello", content)
def test_extract_body_no_body_tag(self):
html = "<p>No body tag</p>"
content = self.archiver._extract_body_content(html)
self.assertIn("No body tag", content)
if __name__ == "__main__":
unittest.main()
+781
View File
@@ -0,0 +1,781 @@
# -*- coding: utf-8 -*-
"""基础设施层合并测试(原 6 个测试文件合并,减少文件数):
- meta_sync:文档版本同步(SKILL.md / README / _meta.json)
- scrapable_registry:机构注册表操作
- search_engine_cn:百度/搜狗中文搜索引擎(离线 fixture)
- http_utils:HTTP 工具与缓存
- backtester:crawl_backtester 4 维回测
- data_comparator:同类数据横向对比 + 监管政策分析
"""
import json
import re
import tempfile
import time
import unittest
from datetime import datetime, timedelta
from pathlib import Path
import pytest
from scripts.scrapable_registry import ScrapableRegistry, PREDEFINED_URLS
from scripts.search_engine import (
BaiduHTML, SogouHTML, MultiEngineSearch, SearchResult,
)
from scripts.http_utils import (
_extract_domain,
sanitize_filename,
LRUCache,
StdlibResponse,
)
from scripts.crawl_backtester import (
CrawlBacktester, quick_backtest,
_parse_datetime, _extract_numbers,
)
SKILL_DIR = Path(__file__).resolve().parent.parent
SKILL_MD = SKILL_DIR / "SKILL.md"
README_MD = SKILL_DIR / "README.md"
META_JSON = SKILL_DIR / "_meta.json"
INIT_PY = SKILL_DIR / "scripts" / "__init__.py"
# ════════════ A. meta_sync:文档版本同步 ════════════
def _frontmatter(text):
m = re.match(r"^---\n(.*?)\n---", text, re.DOTALL)
assert m, "SKILL.md 缺少 frontmatter"
return m.group(1)
def test_skill_version_is_700():
fm = _frontmatter(SKILL_MD.read_text(encoding="utf-8"))
assert re.search(r"^version:\s*7\.7\.0\s*$", fm, re.MULTILINE), "SKILL version ≠ 7.7.0"
def test_skill_name_present():
fm = _frontmatter(SKILL_MD.read_text(encoding="utf-8"))
assert "name: cn-financial-scraper" in fm
def test_skill_line_count_under_450():
lines = SKILL_MD.read_text(encoding="utf-8").splitlines()
assert len(lines) <= 450, f"SKILL.md {len(lines)} 行 > 450(精简目标)"
def test_skill_description_concise():
"""description 不再堆叠版本 changelog(应 ≤ 25 行)"""
fm = _frontmatter(SKILL_MD.read_text(encoding="utf-8"))
m = re.search(r"description: \|(.*?)(?=auto_trigger)", fm, re.DOTALL)
assert m, "description 缺失"
desc_lines = [l for l in m.group(1).splitlines() if l.strip()]
assert len(desc_lines) <= 25, f"description 过冗长({len(desc_lines)} 行)"
def test_skill_keeps_auto_trigger():
fm = _frontmatter(SKILL_MD.read_text(encoding="utf-8"))
assert "keywords:" in fm, "auto_trigger keywords 缺失"
assert "patterns:" in fm, "auto_trigger patterns 缺失"
# 关键触发词保留
assert "爬取机构" in fm
assert "舆情爬取" in fm
assert "东方财富" in fm
def test_skill_no_stale_changelog_blocks():
"""正文无残留 v4.x 长 changelog 块"""
txt = SKILL_MD.read_text(encoding="utf-8")
for stale in ["v4.9.0 反爬 + 数据源兜底", "任务清单 — 详细使用指南",
"🆕 v4.5.1 三项强化", "🆕 v4.5.0 核心新功能"]:
assert stale not in txt, f"残留旧章节: {stale}"
def test_readme_version_is_700():
txt = README_MD.read_text(encoding="utf-8")
assert "# cn-financial-scraper v7.7.0" in txt, "README 头版本 ≠ v7.7.0"
def test_meta_json_version_valid():
"""_meta.json 版本为合法 semver(平台独立版本体系,与 SKILL 版本解耦)"""
meta = json.loads(META_JSON.read_text(encoding="utf-8"))
assert re.match(r"^\d+\.\d+\.\d+$", str(meta["version"])), "version 非 semver"
assert "slug" in meta
assert "ownerId" in meta
def test_init_version_is_700():
txt = INIT_PY.read_text(encoding="utf-8")
assert "__version__ = '7.7.0'" in txt
def test_no_bytecode_residue_delivery_guard():
"""交付守卫:项目内不得残留 .pyc / __pycache__ / .pytest_cache
(上传平台拒绝二进制文件)。conftest 启动即清理历史残留,
本用例兼验证直跑/包装两种入口下会话中不新增字节码。"""
pyc_files = [p for p in SKILL_DIR.rglob("*.pyc")]
assert not pyc_files, f"残留字节码文件: {pyc_files[:5]}"
pycache_dirs = [d for d in SKILL_DIR.rglob("__pycache__") if d.is_dir()]
assert not pycache_dirs, f"残留 __pycache__ 目录: {pycache_dirs[:5]}"
pytest_cache = SKILL_DIR / ".pytest_cache"
assert not pytest_cache.exists(), "残留 .pytest_cache(应已配置 -p no:cacheprovider)"
def test_all_versions_consistent():
"""SKILL / README / __init__ 三者版本一致(_meta.json 为平台独立 semver)"""
skill = re.search(r"^version:\s*(7\.7\.0)", _frontmatter(SKILL_MD.read_text(encoding="utf-8")),
re.MULTILINE)
assert skill
readme = "v7.7.0" in README_MD.read_text(encoding="utf-8")
init = "__version__ = '7.7.0'" in INIT_PY.read_text(encoding="utf-8")
assert readme and init
def test_meta_json_valid():
"""_meta.json 合法 JSON"""
json.loads(META_JSON.read_text(encoding="utf-8"))
def test_requirements_has_akshare():
txt = (SKILL_DIR / "requirements.txt").read_text(encoding="utf-8")
assert "akshare" in txt, "requirements.txt 未提及 akshare"
# ════════════ B. scrapable_registry:机构注册表 ════════════
class TestScrapableRegistry:
"""Test ScrapableRegistry class"""
def test_initialization_loads_data(self):
"""Registry should load on initialization"""
registry = ScrapableRegistry()
assert registry.total > 0, "Registry should have institutions"
def test_institutions_property(self):
"""institutions property should return a list"""
registry = ScrapableRegistry()
institutions = registry.institutions
assert isinstance(institutions, list)
assert len(institutions) > 0
def test_get_returns_institution(self):
"""get() should return institution info for known names"""
registry = ScrapableRegistry()
# Get any institution
all_inst = registry.institutions
if all_inst:
first = all_inst[0]
result = registry.get(first["name"])
assert result is not None
assert result["name"] == first["name"]
def test_get_returns_none_for_unknown(self):
"""get() should return None for unknown names"""
registry = ScrapableRegistry()
result = registry.get("ZZZ不存在的机构名称XYZ")
assert result is None
def test_search_finds_institutions(self):
"""Search should find matching institutions"""
registry = ScrapableRegistry()
results = registry.search("工商银行")
assert isinstance(results, list)
assert len(results) > 0
for r in results:
assert r is not None
def test_search_no_match(self):
"""Search with no match should return empty"""
registry = ScrapableRegistry()
results = registry.search("ZZZ不存在的机构123456")
assert results == []
def test_list_by_type(self):
"""list_by_type should filter institutions"""
registry = ScrapableRegistry()
# Find an actual type from the data
all_inst = registry.institutions
if all_inst:
first_type = all_inst[0].get("type", "")
results = registry.list_by_type(first_type)
assert isinstance(results, list)
def test_list_scrapable(self):
"""list_scrapable should return institutions with URLs"""
registry = ScrapableRegistry()
results = registry.list_scrapable()
assert isinstance(results, list)
# All should have scrapable=True
for r in results:
assert r["scrapable"] is True
def test_total_property(self):
"""Total should be positive"""
registry = ScrapableRegistry()
assert registry.total > 0
def test_get_statistics(self):
"""get_statistics should return stats dict"""
registry = ScrapableRegistry()
stats = registry.get_statistics()
assert isinstance(stats, dict)
assert "total" in stats
assert "scrapable" in stats
assert "by_type" in stats
assert stats["total"] > 0
def test_generate_report(self):
"""generate_report should return a string"""
registry = ScrapableRegistry()
report = registry.generate_report()
assert isinstance(report, str)
assert len(report) > 0
assert "机构" in report
def test_is_scrapable(self):
"""is_scrapable should correctly identify institutions with URLs"""
registry = ScrapableRegistry()
assert registry.is_scrapable("华夏基金") is True
assert registry.is_scrapable("ZZZ不存在") is False
class TestPredefinedUrls:
"""Test the PREDEFINED_URLS dictionary"""
def test_contains_major_banks(self):
assert "中国工商银行" in PREDEFINED_URLS
assert "中国建设银行" in PREDEFINED_URLS
assert "招商银行" in PREDEFINED_URLS
def test_contains_major_securities(self):
assert "中信证券" in PREDEFINED_URLS
assert "华泰证券" in PREDEFINED_URLS
def test_contains_major_fund_companies(self):
assert "华夏基金" in PREDEFINED_URLS
assert "易方达基金" in PREDEFINED_URLS
def test_all_urls_are_valid_format(self):
for name, url in PREDEFINED_URLS.items():
assert url.startswith("https://"), f"{name}: {url} must use HTTPS"
assert len(url) > 10, f"{name}: URL too short"
def test_no_duplicate_urls(self):
"""No two institutions should share the same URL"""
urls = list(PREDEFINED_URLS.values())
assert len(urls) == len(set(urls)), f"Found {len(urls) - len(set(urls))} duplicate URL(s)"
# ════════════ C. search_engine_cn:百度/搜狗 ════════════
BAIDU_HTML = """
<div class="result c-container">
<h3 class="t"><a href="https://www.baidu.com/link?url=real1%3A%2F%2Fexample.com%2Fmoutai&wd=kw">贵州茅台 2026半年报 营收增长</a></h3>
<div class="c-abstract">茅台营收同比增长 18%,净利润创新高。</div>
</div>
<div class="result c-container">
<h3 class="t"><a href="https://finance.eastmoney.com/a/2026.html">东方财富:白酒板块走强</a></h3>
<div class="c-abstract">白酒股集体上涨。</div>
</div>
"""
SOGOU_HTML = """
<div class="vrwrap">
<h3 class="vr-title"><a href="https://www.sogou.com/link?url=abc123">微信:茅台经销商大会</a></h3>
<p class="star-wiki">经销商库存下降。</p>
</div>
<div class="vrwrap">
<h3 class="vr-title"><a href="https://cninfo.com.cn/x">深交所公告:茅台回购</a></h3>
<p class="txt-info">拟回购金额上限 30 亿。</p>
</div>
"""
def test_baidu_url_resolve():
assert BaiduHTML._resolve_baidu_url(
"https://www.baidu.com/link?url=https%3A%2F%2Fexample.com%2Fa&wd=x"
) == "https://example.com/a"
def test_baidu_url_resolve_plain():
assert BaiduHTML._resolve_baidu_url("https://eastmoney.com/x") == "https://eastmoney.com/x"
def test_sogou_url_resolve():
assert SogouHTML._resolve_sogou_url("https://www.sogou.com/link?url=abc") == "abc"
def test_sogou_url_resolve_plain():
assert SogouHTML._resolve_sogou_url("https://cninfo.com.cn/x") == "https://cninfo.com.cn/x"
def test_baidu_parse(monkeypatch):
engine = BaiduHTML(timeout=3)
monkeypatch.setattr(engine, "_http_get", lambda url, headers=None: BAIDU_HTML)
results = engine.search("贵州茅台", limit=5)
assert len(results) == 2
# 第一条是百度跳转链接 → 还原为真实 URL
assert results[0].url == "real1://example.com/moutai"
assert "贵州茅台" in results[0].title
assert results[0].snippet != ""
# 第二条普通 URL 原样保留
assert results[1].url == "https://finance.eastmoney.com/a/2026.html"
def _no_sleep(monkeypatch):
import scripts.search_engine as se
monkeypatch.setattr(se.time, "sleep", lambda *a, **k: None)
def test_baidu_parse_empty(monkeypatch):
_no_sleep(monkeypatch)
engine = BaiduHTML(timeout=3)
monkeypatch.setattr(engine, "_http_get", lambda url, headers=None: "")
assert engine.search("不存在", limit=5) == []
def test_baidu_parse_none(monkeypatch):
_no_sleep(monkeypatch)
engine = BaiduHTML(timeout=3)
monkeypatch.setattr(engine, "_http_get", lambda url, headers=None: None)
assert engine.search("xxx", limit=5) == []
def test_sogou_parse(monkeypatch):
engine = SogouHTML(timeout=3)
monkeypatch.setattr(engine, "_http_get", lambda url, headers=None: SOGOU_HTML)
results = engine.search("茅台", limit=5)
assert len(results) == 2
assert results[0].title == "微信:茅台经销商大会"
assert results[0].url == "abc123"
assert results[1].url == "https://cninfo.com.cn/x"
def test_sogou_parse_empty(monkeypatch):
_no_sleep(monkeypatch)
engine = SogouHTML(timeout=3)
monkeypatch.setattr(engine, "_http_get", lambda url, headers=None: None)
assert engine.search("xxx", limit=5) == []
def test_registry_has_cn_engines():
reg = MultiEngineSearch.ENGINE_REGISTRY
assert "baidu_html" in reg
assert "sogou_html" in reg
assert reg["baidu_html"] is BaiduHTML
assert reg["sogou_html"] is SogouHTML
def test_auto_detect_prefers_cn_engines():
m = MultiEngineSearch()
names = [e.name for e in m.engines]
assert names[0] == "baidu_html"
assert names[1] == "sogou_html"
def test_create_engine_baidu_sogou():
m = MultiEngineSearch(engines=["baidu_html", "sogou_html"])
assert any(isinstance(e, BaiduHTML) for e in m.engines)
assert any(isinstance(e, SogouHTML) for e in m.engines)
def test_cn_engines_need_no_api_key():
assert BaiduHTML.needs_api_key is False
assert SogouHTML.needs_api_key is False
# ════════════ D. http_utils:域名/文件名清洗/LRU 缓存 ════════════
class TestExtractDomain:
"""Test _extract_domain helper"""
def test_extracts_domain_from_https_url(self):
assert _extract_domain("https://fund.eastmoney.com/000001.html") == "fund.eastmoney.com"
def test_extracts_domain_from_http_url(self):
assert _extract_domain("http://www.example.com/path?a=1") == "www.example.com"
def test_extracts_domain_from_url_with_port(self):
assert _extract_domain("https://api.test.com:8080/v1/data") == "api.test.com:8080"
def test_handles_malformed_url(self):
"""Malformed URLs should return 'unknown' or not raise"""
result = _extract_domain("not-a-valid-url!!!")
assert isinstance(result, str)
def test_handles_empty_string(self):
result = _extract_domain("")
assert isinstance(result, str)
def test_lowercases_domain(self):
assert _extract_domain("https://WWW.EXAMPLE.COM/path") == "www.example.com"
class TestSanitizeFilename:
"""Test sanitize_filename function"""
def test_removes_invalid_chars(self):
# : and " both become _, so :with" becomes __with_
result = sanitize_filename('file<name>:with"bad/chars')
assert "file_name__with_bad_chars" == result
def test_replaces_backslash(self):
assert sanitize_filename("path\\to\\file.pdf") == "path_to_file.pdf"
def test_normalizes_whitespace(self):
assert sanitize_filename(" multiple spaces here ") == "multiple spaces here"
def test_truncates_long_names(self):
long_name = "a" * 200
result = sanitize_filename(long_name, max_len=50)
assert len(result) == 50
assert result == "a" * 50
def test_default_max_len(self):
long_name = "a" * 200
result = sanitize_filename(long_name)
assert len(result) <= 100
def test_handles_chinese_characters(self):
result = sanitize_filename("华夏基金_2024年报.pdf")
assert "华夏基金_2024年报.pdf" == result
def test_strips_control_characters(self):
result = sanitize_filename("test\x00file\x1fname")
assert "\x00" not in result
assert "\x1f" not in result
def test_returns_unnamed_for_empty_result(self):
"""After sanitization, if name is all underscores, return 'unnamed'"""
result = sanitize_filename("<>:\"/\\|?*")
assert result == "unnamed"
def test_returns_unnamed_for_empty_string(self):
result = sanitize_filename("")
assert result == "unnamed"
class TestLRUCache:
"""Test LRUCache implementation — uses set/get API (not put)"""
def test_basic_set_and_get(self):
cache = LRUCache(max_size=10, ttl=99999)
resp = StdlibResponse("http://test.com", 200, {"Content-Type": "text/plain"}, b"test body")
cache.set("http://test.com/key1", resp)
result = cache.get("http://test.com/key1")
assert result is not None
assert result.status_code == 200
def test_get_missing_key(self):
cache = LRUCache(10)
assert cache.get("http://nonexistent.com") is None
def test_lru_eviction(self):
cache = LRUCache(max_size=3, ttl=99999)
for i in range(3):
resp = StdlibResponse(f"http://test.com/{i}", 200, {}, f"body{i}".encode())
cache.set(f"http://test.com/{i}", resp)
cache.get("http://test.com/0")
resp4 = StdlibResponse("http://test.com/4", 200, {}, b"body4")
cache.set("http://test.com/4", resp4)
assert cache.get("http://test.com/0") is not None
assert cache.get("http://test.com/2") is not None
assert cache.get("http://test.com/4") is not None
assert cache.get("http://test.com/1") is None
def test_overwrite_existing_key(self):
"""LRU cache does NOT overwrite existing keys — it preserves first-cached value.
This is standard HTTP cache behavior: first response wins until TTL expiry."""
cache = LRUCache(max_size=10, ttl=99999)
resp1 = StdlibResponse("http://test.com/key", 200, {}, b"first")
resp2 = StdlibResponse("http://test.com/key", 200, {}, b"second")
cache.set("http://test.com/key", resp1)
cache.set("http://test.com/key", resp2) # Should keep first value
result = cache.get("http://test.com/key")
assert result.content == b"first" # First-cached value preserved
def test_clear_cache(self):
cache = LRUCache(max_size=10, ttl=99999)
cache.set("http://test.com/a", StdlibResponse("http://test.com/a", 200, {}, b"a"))
cache.set("http://test.com/b", StdlibResponse("http://test.com/b", 200, {}, b"b"))
cache.clear()
assert cache.get("http://test.com/a") is None
assert cache.get("http://test.com/b") is None
def test_ttl_expiry(self):
"""Items should expire after TTL"""
cache = LRUCache(max_size=10, ttl=0.01)
cache.set("http://test.com/key", StdlibResponse("http://test.com/key", 200, {}, b"body"))
time.sleep(0.02)
assert cache.get("http://test.com/key") is None
def test_len(self):
cache = LRUCache(max_size=10)
cache.set("http://test.com/a", StdlibResponse("http://test.com/a", 200, {}, b"a"))
cache.set("http://test.com/b", StdlibResponse("http://test.com/b", 200, {}, b"b"))
assert len(cache) == 2
# ════════════ E. backtester:crawl_backtester 回测 ════════════
class TestParseDatetime(unittest.TestCase):
def test_iso(self):
dt = _parse_datetime("2026-07-29T10:00:00")
self.assertEqual(dt.year, 2026)
self.assertEqual(dt.month, 7)
self.assertEqual(dt.day, 29)
def test_date_only(self):
dt = _parse_datetime("2026-07-29")
self.assertEqual(dt.year, 2026)
def test_chinese_format(self):
dt = _parse_datetime("2026年7月29日")
self.assertEqual(dt.year, 2026)
def test_relative(self):
dt = _parse_datetime("3天前")
self.assertIsNotNone(dt)
self.assertAlmostEqual((datetime.now() - dt).days, 3, delta=1)
def test_invalid(self):
self.assertIsNone(_parse_datetime("not a date"))
class TestExtractNumbers(unittest.TestCase):
def test_amount_yi(self):
out = _extract_numbers("营收 1500 亿元")
self.assertEqual(out["amounts"], [150000000000])
def test_amount_wan(self):
out = _extract_numbers("营收 150000 万元")
self.assertEqual(out["amounts"], [1500000000])
def test_percentage(self):
out = _extract_numbers("增长 15.5%")
self.assertIn(15.5, out["percentages"])
def test_year(self):
out = _extract_numbers("2024 年财报")
self.assertIn(2024, out["years"])
def test_year_filter(self):
# 不应抽到手机号/年份外的数字
out = _extract_numbers("电话 13800138000")
# 13800138000 不应进入 years(不匹配 19xx/20xx 模式)
self.assertEqual(out["years"], [])
class TestFreshness(unittest.TestCase):
def setUp(self):
self.bt = CrawlBacktester(max_age_days=7)
def test_fresh(self):
today = datetime.now().strftime("%Y-%m-%d")
f = self.bt.check_freshness({"published_at": today})
self.assertEqual(f["level"], "fresh")
self.assertGreater(f["score"], 0.8)
def test_stale(self):
old = (datetime.now() - timedelta(days=10)).strftime("%Y-%m-%d")
f = self.bt.check_freshness({"published_at": old})
self.assertEqual(f["level"], "stale")
def test_expired(self):
old = (datetime.now() - timedelta(days=100)).strftime("%Y-%m-%d")
f = self.bt.check_freshness({"published_at": old})
self.assertEqual(f["level"], "expired")
self.assertLess(f["score"], 0.3)
def test_unknown(self):
f = self.bt.check_freshness({"published_at": None})
self.assertEqual(f["level"], "unknown")
class TestNumericConsistency(unittest.TestCase):
def setUp(self):
self.bt = CrawlBacktester()
def test_consistent_amounts(self):
n = self.bt.numeric_consistency({
"title": "x", "content": "营收 1500 亿元,同比增长 15%"
})
self.assertGreaterEqual(len(n["extracted"]["amounts"]), 1)
self.assertIn(15, n["extracted"]["percentages"])
def test_inconsistent_years(self):
n = self.bt.numeric_consistency({
"title": "x", "content": "2099 年某事"
})
self.assertGreater(n["inconsistency_count"], 0)
def test_clean_text(self):
n = self.bt.numeric_consistency({
"title": "x", "content": "无数字内容"
})
self.assertEqual(n["inconsistency_count"], 0)
class TestCrossSource(unittest.TestCase):
def test_no_match_no_snapshot(self):
bt = CrawlBacktester()
# 空快照索引 → 应返回 0 matched
c = bt.cross_source_validate({
"title": "某新闻",
"source": "x"
})
self.assertEqual(c["matched_sources"], [])
class TestSnapshotCompare(unittest.TestCase):
def test_newly_emerged_no_history(self):
bt = CrawlBacktester()
s = bt.compare_with_snapshot({"title": "全新新闻"})
self.assertEqual(s["appeared_in_n_snapshots"], 0)
self.assertTrue(s["newly_emerged"])
class TestFullBacktest(unittest.TestCase):
def test_fresh_article_passes(self):
today = datetime.now().strftime("%Y-%m-%d")
r = quick_backtest({
"title": "测试",
"url": "https://x.com",
"published_at": today,
"content": "2024 年某事",
"source": "财联社",
})
# 综合分应 >= 0.6
self.assertGreater(r.overall_score, 0.5)
def test_old_article_fails(self):
r = quick_backtest({
"title": "老新闻",
"url": "https://x.com",
"published_at": "2020-01-01",
"content": "2020 年事",
"source": "财联社",
})
self.assertFalse(r.passed)
def test_explain_returns_text(self):
r = quick_backtest({"title": "x"})
text = CrawlBacktester().explain(r)
self.assertIn("回测报告", text)
# ════════════ F. data_comparator:横向对比 + 监管分析 ════════════
class TestBacktestSeries(unittest.TestCase):
def _clean_series(self):
return [
{"date": "2026-07-28", "margin_balance": 100.0, "margin_buy": 5.0},
{"date": "2026-07-29", "margin_balance": 102.0, "margin_buy": 6.0},
{"date": "2026-07-30", "margin_balance": 105.0, "margin_buy": 4.0},
{"date": "2026-07-31", "margin_balance": 103.0, "margin_buy": 7.0},
]
def test_clean_series_passes(self):
from data_comparator import backtest_series
r = backtest_series("股票A", self._clean_series())
self.assertTrue(r["passed"])
self.assertGreaterEqual(r["score"], 60)
self.assertEqual(r["record_count"], 4)
def test_empty_series_fails(self):
from data_comparator import backtest_series
r = backtest_series("空序列", [])
self.assertFalse(r["passed"])
self.assertEqual(r["score"], 0)
def test_abnormal_jump_detected(self):
from data_comparator import backtest_series
series = self._clean_series() + [
{"date": "2026-08-01", "margin_balance": 5000.0, "margin_buy": 7.0},
]
r = backtest_series("跳变", series, jump_threshold=5.0)
# 跳变超阈值 → 应有 numeric 问题
numeric_issues = [i for i in r["issues"] if i["field"] == "margin_balance"]
self.assertTrue(any("跳变" in i["message"] for i in numeric_issues))
def test_duplicate_dates_warned(self):
from data_comparator import backtest_series
series = self._clean_series() + [
{"date": "2026-07-31", "margin_balance": 103.0, "margin_buy": 7.0},
]
r = backtest_series("重复", series)
dup_issues = [i for i in r["issues"] if "重复日期" in i["message"]]
self.assertTrue(dup_issues)
class TestCompareSeries(unittest.TestCase):
def test_ranking(self):
from data_comparator import compare_series
a = [{"date": "2026-07-31", "margin_balance": 100.0}]
b = [{"date": "2026-07-31", "margin_balance": 50.0}]
r = compare_series({"股票A": a, "股票B": b})
self.assertEqual(r["series_count"], 2)
rank = r["ranking"]["margin_balance"]
self.assertEqual(rank[0]["label"], "股票A") # 值大者第一
self.assertEqual(rank[1]["label"], "股票B")
def test_latest_and_change(self):
from data_comparator import compare_series
a = [
{"date": "2026-07-30", "margin_balance": 100.0},
{"date": "2026-07-31", "margin_balance": 103.0},
]
r = compare_series({"股票A": a})
self.assertEqual(r["latest"]["股票A"]["margin_balance"], 103.0)
self.assertEqual(r["change"]["股票A"]["margin_balance"], 3.0)
def test_empty(self):
from data_comparator import compare_series
self.assertEqual(compare_series({})["series_count"], 0)
class TestCompareAndBacktest(unittest.TestCase):
def test_integration(self):
from data_comparator import compare_and_backtest
a = [{"date": "2026-07-31", "margin_balance": 100.0, "margin_buy": 5.0}]
b = [{"date": "2026-07-31", "margin_balance": 50.0, "margin_buy": 2.0}]
r = compare_and_backtest({"A": a, "B": b})
self.assertEqual(len(r["backtests"]), 2)
self.assertEqual(r["summary"]["group_count"], 2)
self.assertIn("comparison", r)
self.assertIn("best", r["summary"])
def test_format_report(self):
from data_comparator import compare_and_backtest, format_comparison_report
a = [{"date": "2026-07-31", "margin_balance": 100.0}]
r = compare_and_backtest({"A": a})
text = format_comparison_report(r)
self.assertIn("横向对比", text)
self.assertIn("回测", text)
class TestRegulatoryAnalysis(unittest.TestCase):
"""监管政策文件分析(本地文件,无网络)。"""
def test_analyze_local_file(self):
from regulatory_scraper import RegulatoryScraper
with tempfile.NamedTemporaryFile(mode="w", suffix=".txt",
delete=False, encoding="utf-8") as f:
f.write("某商业银行发布2026年利率政策公告。本公告旨在降低实体经济融资成本。")
path = f.name
try:
r = RegulatoryScraper().analyze_policy(path, keyword="利率")
self.assertIn("利率", r["keywords_hit"])
self.assertGreater(r["content_length"], 0)
self.assertTrue(r["summary"])
finally:
Path(path).unlink(missing_ok=True)
def test_download_invalid_url(self):
from regulatory_scraper import download_policy_document
self.assertEqual(download_policy_document(""), "")
if __name__ == "__main__":
unittest.main()
+142
View File
@@ -0,0 +1,142 @@
# -*- coding: utf-8 -*-
"""Tests for institution_scraper.py — institution search and listing"""
import pytest
from scripts.institution_scraper import (
InstitutionLoader,
search_institution,
list_all_institutions,
get_institution_summary,
)
class TestInstitutionLoader:
"""Test the InstitutionLoader singleton"""
def test_singleton_behavior(self):
"""Should return same instance"""
a = InstitutionLoader()
b = InstitutionLoader()
assert a is b
def test_loads_data(self):
"""Should load institutions data"""
loader = InstitutionLoader()
funds = loader.get_all_fund_companies()
securities = loader.get_all_securities()
banks = loader.get_all_banks()
third_party = loader.get_all_third_party()
all_count = len(funds) + len(securities) + len(banks) + len(third_party)
assert all_count > 0, "No institution data loaded"
def test_get_all_institutions_returns_list(self):
"""get_all_institutions should return list of tuples"""
loader = InstitutionLoader()
result = loader.get_all_institutions()
assert isinstance(result, list)
assert len(result) == 4
for category, items in result:
assert isinstance(category, str)
assert isinstance(items, list)
def test_get_platform_patterns(self):
"""Should return platform URL patterns (may be empty if data not loaded)"""
loader = InstitutionLoader()
patterns = loader.get_platform_patterns()
assert isinstance(patterns, dict)
# Platform patterns may be empty if institutions.json doesn't include them
def test_identify_platform_returns_tuple(self):
"""identify_platform should return a 3-tuple"""
loader = InstitutionLoader()
result = loader.identify_platform("https://fund.eastmoney.com/000001.html")
assert isinstance(result, tuple)
assert len(result) == 3
platform_name, platform_code, inst_type = result
assert isinstance(platform_name, str)
assert isinstance(platform_code, str)
assert isinstance(inst_type, str)
class TestSearchInstitution:
"""Test institution search functionality"""
def test_search_by_name_exact(self):
"""Search should find exact institution names"""
results = search_institution("华夏基金")
assert isinstance(results, list)
assert len(results) > 0
for r in results:
combined = (r.get("name", "") + r.get("code", "")).lower()
assert "华夏" in combined
def test_search_by_partial_name(self):
"""Partial name search should work"""
results = search_institution("华夏")
assert len(results) > 0
names = [r.get("name", "") for r in results]
assert any("华夏" in n for n in names)
def test_search_by_code(self):
"""Search by code should work"""
results = search_institution("ICBC")
assert isinstance(results, list)
def test_search_returns_type_field(self):
"""Each result should have a 'type' field added"""
results = search_institution("招商")
for r in results:
assert "type" in r, f"Missing 'type' in {r}"
assert isinstance(r["type"], str)
def test_search_no_match_returns_empty(self):
"""No-match search should return empty list"""
results = search_institution("ZZZ不存在的机构名称XYZ123")
assert results == []
def test_search_case_insensitive(self):
"""Search should be case-insensitive"""
results = search_institution("招商")
assert len(results) > 0
class TestListAllInstitutions:
"""Test listing all institutions"""
def test_returns_expected_keys(self):
"""Should return dict with 4 keys"""
result = list_all_institutions()
assert isinstance(result, dict)
assert "fund_companies" in result
assert "securities" in result
assert "banks" in result
assert "third_party" in result
def test_each_value_is_list(self):
"""Each value should be a list"""
result = list_all_institutions()
for key, value in result.items():
assert isinstance(value, list), f"{key} should be list, got {type(value)}"
def test_items_have_name_field(self):
"""Institution items should have name field"""
result = list_all_institutions()
for category, items in result.items():
if items:
for item in items[:3]:
assert "name" in item, f"Missing name in {category}: {item}"
class TestGetInstitutionSummary:
"""Test institution summary"""
def test_returns_non_empty_string(self):
"""Should return a non-empty summary string"""
summary = get_institution_summary()
assert isinstance(summary, str)
assert len(summary) > 0
assert "机构" in summary
def test_contains_counts(self):
"""Summary should contain institution counts"""
summary = get_institution_summary()
assert "家" in summary
+714
View File
@@ -0,0 +1,714 @@
# -*- coding: utf-8 -*-
"""解析/导出/行情层合并测试(原 7 个测试文件合并,减少文件数):
- docx_picture:report_exporter export_with_images / MarkdownExporter
- zip_utf8:crawl_packager 中文文件名 ZIP
- html2md:块级/行内/表格/图片/代码/边界
- markdown_exporter:单文件/批量/ZIP/中文文件名
- web_parser:产品解析与财务指标抽取
- bse_scraper:北交所数据(mock,无网络)
- market_data_scraper:LPR / 国债收益率曲线(mock,无网络)
"""
import shutil
import tempfile
import unittest
import zipfile
from pathlib import Path
from unittest import mock
from scripts.report_exporter import WordExporter, MarkdownExporter as _WordMdExporter
from scripts.crawl_packager import _write_zip_utf8, set_zip_encoding, package_with_images
from scripts.html2md import convert, convert_with_tables
from scripts.markdown_exporter import (MarkdownExporter, export_to_markdown,
batch_to_markdown, _safe_filename)
from scripts.web_parser import (extract_financial_metrics,
format_product_summary,
parse_product_from_html)
# ════════════ A. docx_picture:WordExporter 图片导出 ════════════
class TestWordExporterWithImages(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
# 准备测试图片(1x1 PNG)
png_data = (
b"\x89PNG\r\n\x1a\n"
b"\x00\x00\x00\rIHDR"
b"\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89"
b"\x00\x00\x00\rIDATx\x9cc\xf8\xff\xff?\x00\x05\xfe\x02\xfe\xa3\x8b\x80\x00\x00\x00"
b"\x00IEND\xaeB`\x82"
)
self.img_path = Path(self.tmp) / "test.png"
self.img_path.write_bytes(png_data)
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_export_with_images_md_fallback(self):
# 即使没装 python-docx,fallback 也能写 MD
we = WordExporter()
data = {
"title": "测试报告",
"metadata": {"source": "财联社", "date": "2026-07-29"},
"sections": [
{"heading": "一、引言", "level": 1,
"paragraphs": ["这是引言段落"],
"images": [{"path": str(self.img_path), "caption": "测试图"}]},
{"heading": "二、结论", "level": 1,
"paragraphs": ["这是结论段落"],
"images": []},
]
}
out = we.export_with_images(data, output_path=str(Path(self.tmp) / "out.docx"))
self.assertTrue(Path(out).exists())
def test_markdown_exporter_basic(self):
me = _WordMdExporter(output_dir=self.tmp)
data = {"title": "测试", "source": "财联社",
"content": "<h2>子标题</h2><p>正文</p>"}
out = me.export(data)
self.assertTrue(Path(out).exists())
text = Path(out).read_text(encoding="utf-8")
self.assertIn("测试", text)
self.assertIn("财联社", text)
# ════════════ B. zip_utf8:中文文件名 ZIP ════════════
class TestWriteZipUtf8(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_ascii_filename_no_extra(self):
# 纯 ASCII 不应附加 extra 字段
f = Path(self.tmp) / "ascii.txt"
f.write_text("hello", encoding="utf-8")
zip_path = Path(self.tmp) / "out.zip"
with zipfile.ZipFile(str(zip_path), "w", zipfile.ZIP_DEFLATED) as zf:
_write_zip_utf8(zf, str(f), "ascii.txt")
# 验证能正常读取
with zipfile.ZipFile(zip_path) as zf:
self.assertIn("ascii.txt", zf.namelist())
def test_chinese_filename_preserved(self):
f = Path(self.tmp) / "源.txt"
f.write_text("数据", encoding="utf-8")
zip_path = Path(self.tmp) / "out.zip"
with zipfile.ZipFile(str(zip_path), "w", zipfile.ZIP_DEFLATED) as zf:
_write_zip_utf8(zf, str(f), "源文件.txt")
with zipfile.ZipFile(zip_path) as zf:
names = zf.namelist()
# 中文文件名应保留
self.assertTrue(any("源文件" in n for n in names), f"中文丢失: {names}")
class TestPackageWithImages(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_basic(self):
# 模拟有图片的内容
img_dir = Path(self.tmp) / "imgs"
img_dir.mkdir()
img = img_dir / "测试.png"
img.write_bytes(b"\x89PNG fake image data")
items = [
{"name": "新闻1", "content": "正文1", "image_map": {"https://x/a.png": str(img)}},
{"name": "新闻2", "content": "正文2", "image_map": {}},
]
zip_path = package_with_images(items, zip_name="中文测试",
output_dir=self.tmp)
self.assertTrue(Path(zip_path).exists())
# 验证包含中文图片名
with zipfile.ZipFile(zip_path) as zf:
names = zf.namelist()
self.assertTrue(any("测试" in n for n in names))
class TestSetZipEncoding(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_fix_zip(self):
# 创建一个中文 ZIP
f = Path(self.tmp) / "原.txt"
f.write_text("内容", encoding="utf-8")
zip_path = Path(self.tmp) / "src.zip"
with zipfile.ZipFile(str(zip_path), "w", zipfile.ZIP_DEFLATED) as zf:
zf.writestr("原文件.txt", "数据")
# 修复
fixed = set_zip_encoding(str(zip_path))
self.assertTrue(Path(fixed).exists())
with zipfile.ZipFile(fixed) as zf:
names = zf.namelist()
self.assertEqual(len(names), len(set(names)),
f"修复后的 ZIP 不应包含重复条目: {names}")
self.assertEqual(names.count("原文件.txt"), 1)
# ════════════ C. html2md:HTML → Markdown 转换 ════════════
class TestHtml2MdBasic(unittest.TestCase):
def test_empty(self):
self.assertEqual(convert(""), "")
self.assertEqual(convert(None), "")
def test_paragraph(self):
md = convert("<p>hello world</p>")
self.assertIn("hello world", md)
def test_headings(self):
for i in range(1, 7):
md = convert(f"<h{i}>标题</h{i}>")
self.assertIn(f"{'#' * i} 标题", md)
def test_bold_italic(self):
md = convert("<p><strong>bold</strong> and <em>italic</em></p>")
self.assertIn("**bold**", md)
self.assertIn("*italic*", md)
def test_link(self):
md = convert('<a href="https://example.com">链接</a>')
self.assertIn("[链接](https://example.com)", md)
def test_image_with_map(self):
md = convert('<img src="https://x.com/a.png" alt="图">',
image_map={"https://x.com/a.png": "./a.png"})
self.assertIn("![图](./a.png)", md)
def test_image_without_map(self):
md = convert('<img src="https://x.com/a.png" alt="图">')
self.assertIn("![图](https://x.com/a.png)", md)
def test_line_break(self):
md = convert("a<br>b")
self.assertIn("a\nb", md)
def test_horizontal_rule(self):
md = convert("<hr>")
self.assertIn("---", md)
def test_drop_script(self):
md = convert("<p>前<script>alert(1)</script>后</p>")
self.assertNotIn("alert", md)
self.assertIn("前后", md)
def test_drop_style(self):
md = convert("<style>body{}</style><p>内容</p>")
self.assertNotIn("body", md)
self.assertIn("内容", md)
def test_blockquote(self):
md = convert("<blockquote>引用文字</blockquote>")
self.assertIn("引用文字", md)
def test_unordered_list(self):
md = convert("<ul><li>a</li><li>b</li></ul>")
self.assertIn("- a", md)
self.assertIn("- b", md)
def test_ordered_list(self):
md = convert("<ol><li>a</li><li>b</li></ol>")
self.assertIn("1. a", md)
self.assertIn("1. b", md)
class TestHtml2MdCode(unittest.TestCase):
def test_inline_code(self):
md = convert("<p>看 <code>x</code> 变量</p>")
self.assertIn("`x`", md)
def test_pre_block(self):
md = convert("<pre>print('hi')</pre>")
self.assertIn("```", md)
self.assertIn("print('hi')", md)
def test_pre_with_language(self):
md = convert('<pre><code class="language-python">print(1)</code></pre>')
self.assertIn("```python", md)
class TestHtml2MdTable(unittest.TestCase):
def test_simple_table(self):
html = ('<table><thead><tr><th>A</th><th>B</th></tr></thead>'
'<tbody><tr><td>1</td><td>2</td></tr></tbody></table>')
md = convert_with_tables(html)
self.assertIn("| A | B |", md)
self.assertIn("| --- | --- |", md)
self.assertIn("| 1 | 2 |", md)
def test_table_with_pipe_in_cell(self):
html = ('<table><thead><tr><th>标题</th></tr></thead>'
'<tbody><tr><td>有|竖线</td></tr></tbody></table>')
md = convert_with_tables(html)
# | 应被转义
self.assertIn("\\|", md)
class TestHtml2MdEdge(unittest.TestCase):
def test_relative_url_resolved(self):
md = convert('<a href="/page">链接</a>', base_url="https://x.com")
self.assertIn("https://x.com/page", md)
def test_already_absolute(self):
md = convert('<a href="https://y.com/p">x</a>', base_url="https://x.com")
self.assertIn("https://y.com/p", md)
def test_nested_strong_in_link(self):
md = convert('<a href="https://x.com"><strong>重点</strong></a>')
self.assertIn("**重点**", md)
self.assertIn("https://x.com", md)
def test_iframe_to_text(self):
md = convert('<iframe src="https://x.com/embed"></iframe>')
self.assertIn("[iframe:", md)
self.assertIn("x.com/embed", md)
def test_unclosed_tag_tolerant(self):
# 容错:未闭合的 <p> 不应崩
md = convert("<p>hello")
self.assertIn("hello", md)
def test_html_entities_decoded(self):
# html.parser 默认 decode entity;这是预期行为
md = convert("<p>5 &lt; 10 &amp; true</p>")
self.assertIn("5 < 10", md)
self.assertIn("& true", md)
class TestHtml2MdWhitespace(unittest.TestCase):
def test_multiple_newlines_collapsed(self):
md = convert("<p>a</p>\n\n\n\n<p>b</p>")
# 不应超过 2 个连续换行
self.assertNotIn("\n\n\n", md)
def test_whitespace_in_text_collapsed(self):
md = convert("<p>hello world</p>")
self.assertIn("hello world", md)
# ════════════ D. markdown_exporter:单文件/批量/合并/ZIP ════════════
class TestSafeFilename(unittest.TestCase):
def test_chinese_kept(self):
self.assertEqual(_safe_filename("贵州茅台"), "贵州茅台")
def test_illegal_chars_replaced(self):
self.assertEqual(_safe_filename('a/b\\c:d*e?f"g<h>i|j'), "a_b_c_d_e_f_g_h_i_j")
def test_empty_safe(self):
self.assertEqual(_safe_filename(""), "untitled")
def test_whitespace_normalized(self):
self.assertEqual(_safe_filename("a b\tc"), "a_b_c")
class TestSingleExport(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
self.exp = MarkdownExporter(output_dir=self.tmp)
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_html_content_converted(self):
data = {
"title": "测试标题",
"source": "财联社",
"url": "https://x.com",
"published_at": "2026-07-29",
"content": "<h2>子标题</h2><p>正文内容</p>",
}
path = self.exp.export(data)
self.assertTrue(Path(path).exists())
text = Path(path).read_text(encoding="utf-8")
self.assertIn("# 测试标题", text)
self.assertIn("## 子标题", text)
self.assertIn("正文内容", text)
self.assertIn("**来源**: 财联社", text)
def test_md_content_kept(self):
data = {
"title": "MD 测试",
"content": "# Already MD\n\n正文",
}
path = self.exp.export(data)
text = Path(path).read_text(encoding="utf-8")
# 原始 MD 不应被二次转换
self.assertIn("# Already MD", text)
class TestBatchExport(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
self.exp = MarkdownExporter(output_dir=self.tmp)
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_batch_creates_structure(self):
items = [
{"title": "新闻1", "source": "财联社", "content": "<p>c1</p>"},
{"title": "新闻2", "source": "新华财经", "content": "<p>c2</p>"},
]
res = self.exp.build_batch_export(items, batch_id="b1")
self.assertEqual(res["count"], "2")
self.assertTrue(Path(res["dir"]).exists())
self.assertTrue(Path(res["index"]).exists())
self.assertTrue(Path(res["metadata"]).exists())
self.assertTrue(Path(res["zip"]).exists())
# 索引文件应包含目录
idx_text = Path(res["index"]).read_text(encoding="utf-8")
self.assertIn("新闻1", idx_text)
self.assertIn("财联社", idx_text)
def test_chinese_filename_in_zip(self):
items = [{"title": "中文测试", "source": "测试媒体", "content": "<p>x</p>"}]
res = self.exp.build_batch_export(items, batch_id="中文批次")
with zipfile.ZipFile(res["zip"]) as zf:
names = zf.namelist()
# 中文应保留
self.assertTrue(any("测试媒体" in n for n in names), f"中文文件名丢失: {names}")
class TestMergeMd(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
self.exp = MarkdownExporter(output_dir=self.tmp)
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_merge_with_toc(self):
# 先创建 2 个 MD 文件
f1 = self.exp.export({"title": "文章甲", "content": "<p>内容甲</p>"})
f2 = self.exp.export({"title": "文章乙", "content": "<p>内容乙</p>"})
merged = self.exp.merge_files([f1, f2], f"{self.tmp}/merged.md", toc=True)
text = Path(merged).read_text(encoding="utf-8")
self.assertIn("# 合并报告", text)
self.assertIn("## 目录", text)
self.assertIn("文章甲", text)
self.assertIn("文章乙", text)
class TestZipEncoding(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_zip_round_trip_chinese(self):
# 写入中文文件名的 MD
md = Path(self.tmp) / "中文文档.md"
md.write_text("# 测试", encoding="utf-8")
# 创建 media 目录
media = Path(self.tmp) / "media"
media.mkdir()
img = media / "图片.png"
img.write_bytes(b"\x89PNG fake")
zip_path = Path(self.tmp) / "out.zip"
exp = MarkdownExporter(output_dir=self.tmp)
exp.generate_zip(str(md), media_dir=str(media), zip_path=str(zip_path))
# 重新打开 ZIP 验证
with zipfile.ZipFile(zip_path) as zf:
names = zf.namelist()
# 中文文件名应保留(可能路径前缀不同)
all_text = " ".join(names)
self.assertIn("中文文档", all_text)
self.assertIn("图片.png", all_text)
# ════════════ E. web_parser:产品解析与财务指标 ════════════
class TestExtractFinancialMetrics:
"""Test extract_financial_metrics function"""
def test_extracts_return_1m(self):
text = "近1月收益率:5.23% 近3月收益率:12.5%"
metrics = extract_financial_metrics(text)
assert "return_1m" in metrics
assert metrics["return_1m"] == 5.23
def test_extracts_return_3m(self):
text = "近3月收益: -3.14%"
metrics = extract_financial_metrics(text)
assert "return_3m" in metrics
assert metrics["return_3m"] == -3.14
def test_extracts_return_6m(self):
text = "近6月收益率: 8.5"
metrics = extract_financial_metrics(text)
assert "return_6m" in metrics
assert metrics["return_6m"] == 8.5
def test_extracts_return_1y(self):
text = "近1年收益率: 15.67%"
metrics = extract_financial_metrics(text)
assert "return_1y" in metrics
assert metrics["return_1y"] == 15.67
def test_extracts_return_3y(self):
text = "近3年收益率: 45.2%"
metrics = extract_financial_metrics(text)
assert "return_3y" in metrics
assert metrics["return_3y"] == 45.2
def test_extracts_return_ytd(self):
text = "今年来收益率: +8.91%"
metrics = extract_financial_metrics(text)
assert "return_ytd" in metrics
assert metrics["return_ytd"] == 8.91
def test_extracts_negative_values(self):
text = "近1月收益率: -2.5% 近1年收益:-10.3"
metrics = extract_financial_metrics(text)
assert metrics["return_1m"] == -2.5
assert metrics["return_1y"] == -10.3
def test_handles_empty_text(self):
metrics = extract_financial_metrics("")
assert isinstance(metrics, dict)
def test_handles_text_without_metrics(self):
metrics = extract_financial_metrics("这是一段无关文本,没有任何收益率数据")
assert metrics == {} or all(v is not None for v in metrics.values())
def test_handles_multiple_colon_formats(self):
"""Test both : (full-width) and : (half-width) colons"""
text = "近1月收益率: 3.21% 近3月收益: 7.89%"
metrics = extract_financial_metrics(text)
assert metrics.get("return_1m") == 3.21
assert metrics.get("return_3m") == 7.89
def test_handles_no_percent_sign(self):
text = "近1月收益: 5.5"
metrics = extract_financial_metrics(text)
assert metrics.get("return_1m") == 5.5
class TestFormatProductSummary:
"""Test format_product_summary function"""
def test_formats_fund_summary(self):
info = {
"product_name": "华夏成长混合",
"product_code": "000001",
"product_type": "混合型",
"nav": "1.2345",
"fund_manager": "张三",
"fund_company": "华夏基金",
}
summary = format_product_summary(info)
assert isinstance(summary, str)
assert "华夏成长混合" in summary
assert "000001" in summary
def test_handles_minimal_info(self):
info = {"product_name": "测试基金"}
summary = format_product_summary(info)
assert "测试基金" in summary
def test_handles_empty_dict(self):
summary = format_product_summary({})
assert isinstance(summary, str)
class TestParseProductFromHtml:
"""Test parse_product_from_html function"""
def test_unsupported_type_returns_error(self):
result = parse_product_from_html("<html></html>", "unsupported_type")
assert "error" in result
assert "不支持" in result["error"]
def test_fund_type_does_not_crash_on_empty_html(self):
"""parse_product_from_html should handle minimal HTML gracefully"""
result = parse_product_from_html("<html><body><h1>Test</h1></body></html>", "fund")
assert isinstance(result, dict)
# Should not raise; may return empty or error result
def test_etf_type_does_not_crash(self):
result = parse_product_from_html("<html></html>", "etf")
assert isinstance(result, dict)
def test_stock_type_does_not_crash(self):
result = parse_product_from_html("<html></html>", "stock")
assert isinstance(result, dict)
def test_fof_type_does_not_crash(self):
result = parse_product_from_html("<html></html>", "fof")
assert isinstance(result, dict)
def test_advisor_type_does_not_crash(self):
result = parse_product_from_html("<html></html>", "advisor")
assert isinstance(result, dict)
# ════════════ F. bse_scraper:北交所数据(mock) ════════════
class TestBseStocks(unittest.TestCase):
def _fake_em_data(self):
return {"data": {"diff": [
{"f12": "837592", "f14": "华信永道", "f13": "837592",
"f26": "2023-02-16", "f100": "信息技术", "f2": 12.5},
]}}
def test_parse_em_fallback(self):
"""北交所原生接口失败时应降级到东方财富并正确解析。"""
from exchange_scraper import get_bse_stocks
# 原生接口返回异常参数错误
with mock.patch("exchange_scraper._fetch_bse_native", return_value=None), \
mock.patch("exchange_scraper._fetch_em_bse_stocks",
return_value=self._fake_em_data()["data"]["diff"] and [{
"code": "837592", "name": "华信永道",
"short_code": "837592", "listing_date": "2023-02-16",
"industry": "信息技术", "market": "bj",
}]):
r = get_bse_stocks(limit=10)
self.assertEqual(len(r), 1)
self.assertEqual(r[0]["code"], "837592")
self.assertEqual(r[0]["name"], "华信永道")
self.assertEqual(r[0]["market"], "bj")
def test_empty_on_failure_bse(self):
from exchange_scraper import get_bse_stocks
with mock.patch("exchange_scraper._fetch_bse_native", return_value=None), \
mock.patch("exchange_scraper._fetch_em_bse_stocks", return_value=[]):
self.assertEqual(get_bse_stocks(), [])
def test_parse_native_bse(self):
"""北交所原生接口正常返回时应直接解析。"""
from exchange_scraper import get_bse_stocks
native = '[{"xxzqdm":"837592","jc":"华信永道","ssrq":"2023-02-16","hy":"信息技术"}]'
with mock.patch("exchange_scraper._fetch_bse_native", return_value=native):
r = get_bse_stocks()
self.assertEqual(len(r), 1)
self.assertEqual(r[0]["code"], "837592")
self.assertEqual(r[0]["name"], "华信永道")
class TestBseIpo(unittest.TestCase):
def test_parse_native_ipo(self):
from exchange_scraper import get_bse_ipo
native = '[{"xxzqdm":"920001","jc":"某北交所公司","zt":"已注册","sxrq":"2026-07-31"}]'
with mock.patch("exchange_scraper._fetch_bse_native", return_value=native):
r = get_bse_ipo(limit=10)
self.assertEqual(len(r), 1)
self.assertEqual(r[0]["code"], "920001")
self.assertEqual(r[0]["status"], "已注册")
self.assertEqual(r[0]["market"], "bj")
def test_empty_on_failure_ipo(self):
from exchange_scraper import get_bse_ipo
with mock.patch("exchange_scraper._fetch_bse_native", return_value=None), \
mock.patch("exchange_scraper.get_ipo_calendar", return_value=[]):
self.assertEqual(get_bse_ipo(), [])
# ════════════ G. market_data_scraper:LPR / 国债收益率曲线 ════════════
class TestLprRates(unittest.TestCase):
def test_parse(self):
from market_data_scraper import get_lpr_rates
records = [
{"showDateCN": "2026-07-20", "1Y": "3.00", "5Y": "3.50"},
{"showDateCN": "2026-06-22", "1Y": "3.45", "5Y": "3.95"},
]
with mock.patch("market_data_scraper._requests.post") as m:
resp = mock.MagicMock()
resp.status_code = 200
resp.json.return_value = {"records": records}
m.return_value = resp
r = get_lpr_rates(days=90)
self.assertEqual(len(r), 2)
self.assertEqual(r[0]["date"], "2026-07-20")
self.assertEqual(r[0]["one_year"], 3.0)
self.assertEqual(r[0]["five_year"], 3.5)
def test_empty_on_failure_lpr(self):
from market_data_scraper import get_lpr_rates
with mock.patch("market_data_scraper._requests.post") as m:
m.side_effect = Exception("网络错误")
self.assertEqual(get_lpr_rates(), [])
class TestBondYieldCurve(unittest.TestCase):
def _fake_data(self):
# 模拟 inityc 返回:索引→期限代码 + 数值列表(含完整曲线 seriesData)
codes = {"3": "R01Y", "11": "R02Y", "13": "R03Y", "4": "R05Y",
"0": "R07Y", "1": "R10Y", "2": "R30Y"}
series = []
# 生成 0-30 年曲线,收益率从 1.0 线性到 3.0
for year in range(0, 301):
y = year / 10.0
series.append([y, 1.0 + y * 0.05])
curve_obj = {"seriesData": series, "worktime": "2026-07-31",
"ycDefName": "中债国债收益率曲线(到期)"}
return [codes, [10, [curve_obj]]]
def test_parse_terms(self):
from market_data_scraper import get_bond_yield_curve
with mock.patch("market_data_scraper._requests.post") as m:
resp = mock.MagicMock()
resp.status_code = 200
resp.json.return_value = self._fake_data()
m.return_value = resp
r = get_bond_yield_curve()
self.assertEqual(r["date"], "2026-07-31")
self.assertIn("1Y", r["terms"])
self.assertIn("10Y", r["terms"])
self.assertIn("30Y", r["terms"])
# 1Y 收益 ≈ 1.0 + 1*0.05 = 1.05
self.assertAlmostEqual(r["terms"]["1Y"], 1.05, places=2)
# 利差
self.assertIn("spread_10_2", r)
def test_error_response(self):
from market_data_scraper import get_bond_yield_curve
with mock.patch("market_data_scraper._requests.post") as m:
resp = mock.MagicMock()
resp.status_code = 200
resp.json.return_value = [{"11": "R01Y"}, [10, []]]
m.return_value = resp
r = get_bond_yield_curve()
self.assertIn("warning", r) # 曲线数据为空时应返回警告
def test_network_failure(self):
from market_data_scraper import get_bond_yield_curve
with mock.patch("market_data_scraper._requests.post") as m:
m.side_effect = Exception("超时")
r = get_bond_yield_curve()
self.assertIn("error", r)
class TestDateNormalize(unittest.TestCase):
def test_normalize(self):
from market_data_scraper import _normalize_date
self.assertEqual(_normalize_date("2026/7/1"), "2026-07-01")
self.assertEqual(_normalize_date("2026-07-31 00:00:00"), "2026-07-31")
self.assertEqual(_normalize_date(""), "")
self.assertEqual(_normalize_date(None), "")
if __name__ == "__main__":
unittest.main()
+202
View File
@@ -0,0 +1,202 @@
# -*- coding: utf-8 -*-
"""v4.7 阶段 A 修复的回归测试。
覆盖:
- search_engine.py 缺少 import random(致命 NameError)
- crawl_backtester.py typing 缺 Tuple
- name_scraper.py 招商银行 URL 错误映射
- regulatory_scraper.py 废弃域名 cbirc → nfra
- cninfo_scraper.py column/orgId 硬编码参数化
- exchange_scraper.py CATALOGID/TABKEY 提取为常量
- web_parser.py if False 死代码分支清理
- mcp_server.py 导入前缀一致性与死代码清理
"""
import sys
import unittest
from pathlib import Path
SCRIPTS_DIR = Path(__file__).resolve().parent.parent / "scripts"
ROOT_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(SCRIPTS_DIR))
sys.path.insert(0, str(ROOT_DIR))
class TestSearchEngineRandomImport(unittest.TestCase):
"""A1: search_engine.py 必须有 import random,否则 search() 崩溃。"""
def test_module_has_random_import(self):
src = (SCRIPTS_DIR / "search_engine.py").read_text(encoding="utf-8")
import re
self.assertTrue(
re.search(r"^import random$|^import random\s*$", src, re.MULTILINE),
"search_engine.py 缺少 import random",
)
def test_search_no_name_error(self):
"""mock urlopen 后调用 DDG search(),不应抛 NameError。"""
from unittest import mock
from search_engine import DuckDuckGoHTML
fake_html = (
'<html><body><div class="result">'
'<a class="result__a" href="http://example.com">测试标题</a>'
'<div class="result__snippet">摘要</div></div></body></html>'
)
class FakeResp:
def __init__(self, content):
self._content = content
def read(self):
return self._content.encode("utf-8")
def __enter__(self):
return self
def __exit__(self, *a):
return False
def getheader(self, n, d=None):
return "text/html"
with mock.patch("urllib.request.urlopen", return_value=FakeResp(fake_html)):
s = DuckDuckGoHTML()
try:
results = s.search("测试", limit=5)
# 不抛 NameError 即算通过
self.assertIsInstance(results, list)
except NameError as e:
self.fail(f"search() 触发 NameError: {e}")
class TestBacktesterTupleImport(unittest.TestCase):
"""A10: crawl_backtester.py 的 typing 需导入 Tuple。"""
def test_tuple_in_typing_import(self):
src = (SCRIPTS_DIR / "crawl_backtester.py").read_text(encoding="utf-8")
self.assertIn("Tuple", src.split("\n")[0:60][-1] if False else src.splitlines()[38] if len(src.splitlines()) > 38 else src)
# 更稳:检查 typing import 行包含 Tuple
typing_line = [l for l in src.splitlines() if "from typing import" in l][0]
self.assertIn("Tuple", typing_line)
def test_module_imports(self):
import crawl_backtester
self.assertTrue(hasattr(crawl_backtester, "CrawlBacktester"))
class TestNameScraperURLs(unittest.TestCase):
"""A5: 招商银行应指向 cmbchina.com,民生银行指向 cmbc.com.cn。"""
def test_correct_bank_urls(self):
from name_scraper import URL_PATTERNS
self.assertEqual(URL_PATTERNS.get("招商银行"), "https://www.cmbchina.com",
"招商银行官网应为 cmbchina.com(原错误指向民生银行)")
self.assertEqual(URL_PATTERNS.get("民生银行"), "https://www.cmbc.com.cn")
def test_urls_valid_format(self):
from name_scraper import URL_PATTERNS
for name, url in URL_PATTERNS.items():
self.assertTrue(url.startswith("https://") or url.startswith("http://"),
f"{name} 的 URL 格式错误: {url}")
class TestRegulatoryDomain(unittest.TestCase):
"""A6: regulatory_scraper.py 数据源应为商业源(东财/新浪/巨潮),不含 gov.cn。"""
def test_no_gov_domain(self):
src = (SCRIPTS_DIR / "regulatory_scraper.py").read_text(encoding="utf-8")
self.assertNotIn("gov.cn", src, "regulatory_scraper 不应包含 gov.cn 域名")
self.assertNotIn("cbirc.gov.cn", src, "不应引用已废弃的 cbirc 域名")
self.assertNotIn("nfra.gov.cn", src, "不应引用 nfra 域名")
def test_commercial_sources(self):
"""应使用商业数据源(东方财富/新浪/巨潮)。"""
src = (SCRIPTS_DIR / "regulatory_scraper.py").read_text(encoding="utf-8")
self.assertIn("eastmoney", src, "应使用东方财富数据源")
self.assertIn("cninfo", src, "应使用巨潮资讯数据源")
def test_api_shape_kept(self):
"""对外 API 形状应保留(get_regulatory_updates 等)。"""
src = (SCRIPTS_DIR / "regulatory_scraper.py").read_text(encoding="utf-8")
self.assertIn("def get_regulatory_updates", src,
"对外 API get_regulatory_updates 应保留")
class TestCninfoParametrized(unittest.TestCase):
"""A7: cninfo_scraper.py 的 column/orgId 应参数化。"""
def test_market_param_in_signature(self):
src = (SCRIPTS_DIR / "cninfo_scraper.py").read_text(encoding="utf-8")
self.assertIn("market: str = \"szse\"", src,
"search_announcements 应支持 market 参数")
def test_no_hardcoded_orgid(self):
"""硬编码 orgId 不应再作为 stock 参数的实际取值。
注释中提及旧魔数属正常文档,故仅校验取值逻辑(org_prefix 推导)。
"""
src = (SCRIPTS_DIR / "cninfo_scraper.py").read_text(encoding="utf-8")
self.assertIn('org_prefix = {"szse": "gssz", "sse": "gssh", "bjse": "gsbj"}',
src, "应按市场推导 orgId")
self.assertIn("stock_param = f\"{stock_code},orgId,{org_prefix}{zcode}\"",
src, "stock 参数应使用推导的 orgId")
# 不再以 gssz0000858 作为字面量拼接进 stock 参数
self.assertNotIn("\"stock\": f\"{stock_code},orgId,gssz0000858\"", src,
"硬编码的五粮液 orgId 不应再作为取值")
class TestExchangeConstants(unittest.TestCase):
"""A8: exchange_scraper.py 的 CATALOGID/TABKEY 应提取为常量。"""
def test_constants_defined(self):
src = (SCRIPTS_DIR / "exchange_scraper.py").read_text(encoding="utf-8")
for const in ("SZSE_CATALOG_IPO", "SZSE_CATALOG_LISTED",
"SZSE_CATALOG_ANNOUNCEMENT", "SZSE_TABKEY"):
self.assertIn(f"{const} =", src, f"缺少常量 {const}")
def test_no_literal_catalogid(self):
src = (SCRIPTS_DIR / "exchange_scraper.py").read_text(encoding="utf-8")
# 请求体里不应再有字面 "1110" CATALOGID(常量里可以有)
self.assertIn('"CATALOGID": SZSE_CATALOG', src,
"请求参数应引用常量")
class TestWebParserNoDeadCode(unittest.TestCase):
"""A9: web_parser.py 的 if False 死代码分支应被清理。"""
def test_no_if_false_branches(self):
src = (SCRIPTS_DIR / "web_parser.py").read_text(encoding="utf-8")
self.assertNotIn("if False else", src,
"web_parser.py 仍有 if False 死代码")
class TestMcpServerImports(unittest.TestCase):
"""A4: mcp_server.py 导入前缀一致且无死代码。"""
def test_no_scripts_prefix_import(self):
src = (ROOT_DIR / "mcp_server.py").read_text(encoding="utf-8")
self.assertNotIn("from scripts.fullpage_archiver", src,
"应使用无前缀导入 from fullpage_archiver")
self.assertNotIn("from scripts.search_engine", src,
"应使用无前缀导入 from search_engine")
self.assertIn("from fullpage_archiver import", src)
self.assertIn("from search_engine import", src)
def test_dead_imports_removed(self):
src = (ROOT_DIR / "mcp_server.py").read_text(encoding="utf-8")
for dead in ("get_stock_brief", "cls_articles", "get_stock_list",
"create_scheduled_task", "package_crawl_results",
"compress_multiple", "MultiFormatParser",
"get_template_outline", "generate_report_from_raw",
"quick_report"):
self.assertNotIn(f"import {dead}", src, f"死代码导入 {dead} 应被删除")
self.assertNotIn(f"import {dead} as", src, f"死代码导入 {dead} 应被删除")
class TestSearchEngineNameError(unittest.TestCase):
"""search_engine.py 修复后 import 不应失败,且多引擎可实例化。"""
def test_multi_engine_init(self):
from search_engine import MultiEngineSearch
s = MultiEngineSearch(engines=["duckduckgo"])
self.assertEqual(s.engines[0].name, "duckduckgo")
if __name__ == "__main__":
unittest.main()
+174
View File
@@ -0,0 +1,174 @@
# -*- coding: utf-8 -*-
"""v5.0.0 模块B:RSS 接线到舆情爬虫测试(离线 mock)"""
import json
from pathlib import Path
import pytest
from scripts.rss_feeds import RssFetcher, _parse_rss_xml, RssItem
from scripts.sentiment_crawler import SentimentCrawler, SentimentSourceLoader
RSS_XML = """<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"><channel>
<title>测试财经</title>
<item><title>贵州茅台发布2026半年报</title><link>https://example.com/1</link>
<description>业绩增长 30%</description><pubDate>Wed, 01 Aug 2026 10:00:00 GMT</pubDate>
<guid>guid-1</guid></item>
<item><title>无关新闻</title><link>https://example.com/2</link>
<description>天气晴朗</description><pubDate>Wed, 01 Aug 2026 11:00:00 GMT</pubDate>
<guid>guid-2</guid></item>
</channel></rss>"""
ATOM_XML = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>测试Atom</title>
<entry><title>宁德时代扩产</title><link href="https://example.com/a"/>
<summary>投资 100 亿</summary><updated>2026-08-01T09:00:00Z</updated>
<id>atom-1</id></entry>
</feed>"""
# ============================================================
# 1. RSS 解析器
# ============================================================
def test_parse_rss2():
items = _parse_rss_xml(RSS_XML.encode("utf-8"), source_name="测试")
assert len(items) == 2
assert items[0].title == "贵州茅台发布2026半年报"
assert items[0].link == "https://example.com/1"
def test_parse_atom():
items = _parse_rss_xml(ATOM_XML.encode("utf-8"), source_name="atom")
assert len(items) == 1
assert items[0].title == "宁德时代扩产"
assert items[0].link == "https://example.com/a"
def test_rss_fetcher_fetch_success(monkeypatch):
class FakeResp:
status_code = 200
content = RSS_XML.encode("utf-8")
monkeypatch.setattr("scripts.http_utils.http_get", lambda *a, **k: FakeResp())
fetcher = RssFetcher()
items = fetcher.fetch({"name": "测试", "url": "https://example.com/rss"})
assert len(items) == 2
assert items[0].guid == "guid-1"
def test_rss_fetcher_fetch_none_returns_empty(monkeypatch):
monkeypatch.setattr("scripts.http_utils.http_get", lambda *a, **k: None)
fetcher = RssFetcher()
assert fetcher.fetch({"name": "x", "url": "https://x/rss"}) == []
def test_rss_fetcher_bad_status_returns_empty(monkeypatch):
class FakeResp:
status_code = 403
content = b""
monkeypatch.setattr("scripts.http_utils.http_get", lambda *a, **k: FakeResp())
fetcher = RssFetcher(max_retries=0)
assert fetcher.fetch({"name": "x", "url": "https://x/rss"}) == []
# ============================================================
# 2. SentimentSourceLoader.sources_with_rss
# ============================================================
def test_sources_with_rss():
loader = SentimentSourceLoader()
with_rss = loader.sources_with_rss()
# v6.0.0 商业媒体源(FT中文网/CNBC 等配置了 RSS)
assert len(with_rss) >= 2, f"非空 RSS 站点过少: {len(with_rss)}"
# 所有返回项都有非空 rss_feeds
for s in with_rss:
assert s.get("rss_feeds")
# ============================================================
# 3. SentimentCrawler._query_source 的 RSS 分支
# ============================================================
def _fake_source(name="东方财富", rss=None):
return {"name": name, "category": "authoritative",
"search_urls": [], "rss_feeds": rss or ["https://example.com/rss"],
"credibility": 10, "language": "zh", "tags": []}
def test_query_source_uses_rss(monkeypatch):
"""配置了 rss_feeds 的源走 RSS 分支产出文章"""
crawler = SentimentCrawler(use_rss=True)
class FakeFetcher:
def fetch(self, feed):
return [RssItem(title="贵州茅台业绩增长", link="https://example.com/1",
description="增 30%", pub_date="2026-08-01")]
crawler._rss_fetcher = FakeFetcher()
crawler._time_up = lambda: False
arts = list(crawler._query_source(
_fake_source(), "贵州茅台", "贵州茅台", "listed_company", "上市公司",
cutoff_time=None))
assert len(arts) == 1
assert arts[0].title == "贵州茅台业绩增长"
def test_query_source_rss_filters_by_keyword(monkeypatch):
"""RSS 条目不含关键词时被过滤"""
crawler = SentimentCrawler(use_rss=True)
class FakeFetcher:
def fetch(self, feed):
return [RssItem(title="无关新闻", link="https://example.com/x",
description="天气", pub_date="2026-08-01")]
crawler._rss_fetcher = FakeFetcher()
crawler._time_up = lambda: False
arts = list(crawler._query_source(
_fake_source(), "贵州茅台", "贵州茅台", "listed_company", "上市公司",
cutoff_time=None))
assert arts == []
def test_query_source_rss_disabled(monkeypatch):
"""use_rss=False 时不走 RSS 分支"""
crawler = SentimentCrawler(use_rss=False)
called = {"n": 0}
class FakeFetcher:
def fetch(self, feed):
called["n"] += 1
return []
crawler._rss_fetcher = FakeFetcher()
crawler._time_up = lambda: False
list(crawler._query_source(_fake_source(), "贵州茅台", "贵州茅台", "x", "y", None))
assert called["n"] == 0
def test_query_source_rss_fetch_exception_safe(monkeypatch):
"""RSS 抓取抛异常时跳过不崩"""
crawler = SentimentCrawler(use_rss=True)
class BoomFetcher:
def fetch(self, feed):
raise RuntimeError("rss down")
crawler._rss_fetcher = BoomFetcher()
crawler._time_up = lambda: False
arts = list(crawler._query_source(_fake_source(), "贵州茅台", "贵州茅台", "x", "y", None))
assert arts == []
def test_crawl_sentiment_accepts_use_rss():
from scripts.sentiment_crawler import crawl_sentiment
# 仅验证签名可传 use_rss 不破坏(dry_run 不发网络)
snap = crawl_sentiment(targets=["贵州茅台"], dry_run=True, use_rss=True, max_articles=5)
assert snap is not None
assert snap.is_plan or not snap.articles
+133
View File
@@ -0,0 +1,133 @@
# -*- coding: utf-8 -*-
"""v5.0.0 模块F:运行优化测试(协作式超时 / 并发锁)"""
import time
from concurrent.futures import ThreadPoolExecutor
import pytest
from scripts.sentiment_crawler import (
SentimentCrawler, SentimentArticle, _SEEN_INDEX, _TITLE_INDEX, _SEEN_LOCK,
)
@pytest.fixture(autouse=True)
def _clean_globals():
_SEEN_INDEX.clear()
_TITLE_INDEX.clear()
yield
_SEEN_INDEX.clear()
_TITLE_INDEX.clear()
# ============================================================
# 1. 协作式超时
# ============================================================
def test_run_with_timeout_normal():
c = SentimentCrawler()
assert c._run_with_timeout(lambda: 42, timeout=5) == 42
def test_run_with_timeout_timeout_returns_none():
"""超时后立即返回 None(不阻塞外层)"""
c = SentimentCrawler()
start = time.time()
out = c._run_with_timeout(lambda: time.sleep(5) or "x", timeout=0.2, name="慢源")
elapsed = time.time() - start
assert out is None
assert elapsed < 3.0, f"超时后阻塞 {elapsed:.1f}s(应 <3s)"
def test_run_with_timeout_marks_cancelled():
"""超时后源名进入 _cancelled_sources"""
c = SentimentCrawler()
c._run_with_timeout(lambda: time.sleep(5) or "x", timeout=0.2, name="被取消源")
assert "被取消源" in c._cancelled_sources
def test_run_with_timeout_zero_timeout():
"""timeout<=0 直接同步执行"""
c = SentimentCrawler()
assert c._run_with_timeout(lambda: 7, timeout=0) == 7
def test_run_with_timeout_exception():
c = SentimentCrawler()
def _boom():
raise ValueError("x")
assert c._run_with_timeout(_boom, timeout=5) is None
# ============================================================
# 2. 并发 _is_dup 线程安全
# ============================================================
def test_concurrent_is_dup_no_loss():
"""8 线程并发插入不同标题(长且互不相同)→ 全部保留,无竞态丢失"""
import hashlib
c = SentimentCrawler()
titles = [f"并发测试文章{hashlib.md5(str(i).encode()).hexdigest()}" for i in range(40)]
urls = [f"https://x.com/{i}" for i in range(40)]
def _add(i):
a = SentimentArticle(title=titles[i], target_name="并发目标",
url=urls[i], publish_time="2026-08-01")
return c._is_dup(a) # 首次应 False(新增)
with ThreadPoolExecutor(max_workers=8) as ex:
results = list(ex.map(_add, range(40)))
assert all(r is False for r in results), "并发新增不应被误判重复"
with _SEEN_LOCK:
assert len(_SEEN_INDEX) == 40, f"索引大小 {len(_SEEN_INDEX)} ≠ 40(丢失)"
def test_concurrent_is_dup_same_title_detected():
"""并发下相同标题只保留一条"""
c = SentimentCrawler()
first = c._is_dup(SentimentArticle(title="同标题", target_name="T", url="https://x/1"))
assert first is False
# 并发重复检查
def _check(_):
return c._is_dup(SentimentArticle(title="同标题!", target_name="T", url="https://x/2"))
with ThreadPoolExecutor(max_workers=8) as ex:
results = list(ex.map(_check, range(16)))
assert all(r is True for r in results), "模糊重复应全部命中"
def test_concurrent_placeholder_seen():
"""并发占位去重:8 个不同组合首见 False,重复 True,不抛异常"""
c = SentimentCrawler()
combos = [(f"目标{i}", f"源{i}") for i in range(8)]
def _check(i):
t, s = combos[i]
return c._placeholder_seen(t, s)
with ThreadPoolExecutor(max_workers=8) as ex:
results = list(ex.map(_check, range(8)))
assert not any(results), "每个 (target,source) 首次应 False"
# 再次全部应 True
again = [c._placeholder_seen(t, s) for t, s in combos]
assert all(again)
# ============================================================
# 3. 精度校验
# ============================================================
def test_timeout_elapsed_precision():
"""超时耗时应在 timeout 附近(不过早不过晚太多)"""
c = SentimentCrawler()
start = time.time()
c._run_with_timeout(lambda: time.sleep(5), timeout=0.3)
elapsed = time.time() - start
assert 0.25 <= elapsed < 2.0, f"耗时 {elapsed:.2f}s 异常"
def test_fetch_failure_logging_structure():
"""B5: 失败日志含 URL 和阶段(吞错可诊断)"""
c = SentimentCrawler()
# 不真正请求,仅验证 _log_fetch_failure 不抛异常
c._log_fetch_failure("https://example.com/x", "http", ValueError("测试"))
+163
View File
@@ -0,0 +1,163 @@
# -*- coding: utf-8 -*-
"""测试 search_engine.py — 解析函数和聚合器(纯函数部分,不依赖网络)。"""
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
sys.dont_write_bytecode = True
from search_engine import (
SearchResult, SearchEngineBase,
DuckDuckGoHTML, BingHTML, GoogleHTML,
SearXNGSearch, BingAPISearch, GoogleAPISearch,
MultiEngineSearch,
_parse_ddg_html, _dedup_results, _normalize_url,
_strip_tags, _unescape_html, _safe_search,
)
class TestSearchResult(unittest.TestCase):
"""SearchResult 数据类测试。"""
def test_to_dict(self):
r = SearchResult(
title="Test", url="https://x.com", snippet="desc",
source_engine="duckduckgo", rank=1, credibility=7,
)
d = r.to_dict()
self.assertEqual(d["title"], "Test")
self.assertEqual(d["credibility"], 7)
def test_default_credibility(self):
r = SearchResult(title="T", url="u", snippet="s", source_engine="e", rank=1)
self.assertEqual(r.credibility, 5)
class TestDDGHTMLParsing(unittest.TestCase):
"""DuckDuckGo HTML 解析测试。"""
def test_parse_single_result(self):
html = '''
<a class="result__a" href="https://example.com/article">测试文章标题</a>
<a class="result__snippet">这是摘要内容</a>
'''
results = _parse_ddg_html(html, "duckduckgo", 7, 10)
self.assertGreaterEqual(len(results), 1)
self.assertEqual(results[0].url, "https://example.com/article")
def test_parse_empty_html(self):
results = _parse_ddg_html("", "duckduckgo", 5, 10)
self.assertEqual(len(results), 0)
def test_parse_limit(self):
html = ("<a class=\"result__a\" href=\"https://x.com/1\">T1</a>"
"<a class=\"result__snippet\">S1</a>") * 20
results = _parse_ddg_html(html, "duckduckgo", 5, 3)
self.assertLessEqual(len(results), 3)
def test_unescape_html_entities(self):
html = ('<a class="result__a" href="https://x.com">测试 &amp; 结果</a>'
'<a class="result__snippet">内容 &lt;摘要&gt;</a>')
results = _parse_ddg_html(html, "ddg", 5, 10)
if results:
self.assertIn("&", results[0].title)
class TestURLNormalization(unittest.TestCase):
"""URL 标准化测试。"""
def test_strips_utm_params(self):
url = "https://example.com/page?utm_source=twitter&id=123"
norm = _normalize_url(url)
self.assertNotIn("utm_source", norm)
# _normalize_url 简化 URL 为 path-only 形式
def test_strips_ref_param(self):
url = "https://example.com/page?ref=homepage"
norm = _normalize_url(url)
self.assertNotIn("ref", norm)
def test_handles_invalid_url(self):
norm = _normalize_url("not_a_url")
self.assertEqual(norm, "") # 无效 URL 返回空字符串
class TestDedup(unittest.TestCase):
"""去重测试。"""
def test_dedup_same_url(self):
r1 = SearchResult(title="A", url="https://x.com/page", snippet="",
source_engine="ddg", rank=1, credibility=5)
r2 = SearchResult(title="B", url="https://x.com/page?utm=1", snippet="",
source_engine="bing", rank=2, credibility=7)
results = _dedup_results([r1, r2])
self.assertEqual(len(results), 1)
# 保留 credibility 更高的
self.assertEqual(results[0].credibility, 7)
def test_dedup_different_urls(self):
r1 = SearchResult(title="A", url="https://x.com/1", snippet="",
source_engine="ddg", rank=1, credibility=5)
r2 = SearchResult(title="B", url="https://y.com/2", snippet="",
source_engine="bing", rank=1, credibility=5)
results = _dedup_results([r1, r2])
self.assertEqual(len(results), 2)
class TestHTMLUtils(unittest.TestCase):
"""HTML 工具函数测试。"""
def test_strip_tags(self):
self.assertEqual(_strip_tags("<p>Hello <b>World</b></p>"), "Hello World")
def test_unescape_html(self):
self.assertEqual(_unescape_html("a&amp;b"), "a&b")
self.assertEqual(_unescape_html("a&lt;b&gt;c"), "a<b>c")
self.assertEqual(_unescape_html("&#65;"), "A")
class TestMultiEngineInit(unittest.TestCase):
"""多引擎聚合器初始化测试。"""
def test_default_engines(self):
s = MultiEngineSearch()
engine_names = [e.name for e in s.engines]
self.assertIn("duckduckgo", engine_names)
def test_custom_engines(self):
s = MultiEngineSearch(engines=["duckduckgo"])
self.assertEqual(len(s.engines), 1)
self.assertEqual(s.engines[0].name, "duckduckgo")
def test_list_engines(self):
s = MultiEngineSearch(engines=["duckduckgo"])
info = s.list_engines()
self.assertEqual(len(info), 1)
self.assertIn("name", info[0])
self.assertIn("credibility", info[0])
def test_invalid_engine_skipped(self):
s = MultiEngineSearch(engines=["nonexistent_engine"])
self.assertEqual(len(s.engines), 0)
class TestSearXNGFallback(unittest.TestCase):
"""SearXNG 故障转移测试。"""
def test_default_instances_list(self):
instances = SearXNGSearch.DEFAULT_INSTANCES
self.assertGreaterEqual(len(instances), 3)
self.assertTrue(all(i.startswith("https://") for i in instances))
def test_init_with_default_instance(self):
s = SearXNGSearch()
self.assertIn(s.instance, SearXNGSearch.DEFAULT_INSTANCES)
def test_custom_instance(self):
s = SearXNGSearch(instance="https://custom.example.com")
self.assertEqual(s.instance, "https://custom.example.com")
if __name__ == "__main__":
unittest.main()
+447
View File
@@ -0,0 +1,447 @@
# -*- coding: utf-8 -*-
"""v4.3 全网舆情爬虫 — 单元测试
覆盖:
1. 关键词词典完整
2. 情感分类器正确
3. 媒体源/目标库加载
4. 自定义目标持久化
5. 对话 NLU 解析
6. 导出器降级 (openpyxl/python-docx 缺失时)
7. ScheduledTask sentiment 字段
8. Snapshot.to_dict 完整性
"""
import sys
import os
import json
import pytest
from pathlib import Path
sys.dont_write_bytecode = True
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
# 强制使 data 目录指向临时项目副本,避免污染真实数据
TEST_DATA_DIR = Path(__file__).resolve().parent / "_test_data"
TEST_DATA_DIR.mkdir(parents=True, exist_ok=True)
import sentiment_keywords as sk
# ============================================================
# 1. 关键词词典
# ============================================================
class TestKeywords:
def test_keys_present(self):
for name in ["POSITIVE_KEYWORDS", "NEGATIVE_KEYWORDS", "NEUTRAL_KEYWORDS"]:
assert hasattr(sk, name), f"missing {name}"
assert isinstance(getattr(sk, name), dict)
def test_enough_keywords(self):
# 至少 200 条负向 + 100 条正向 + 20 条中性
assert len(sk.POSITIVE_KEYWORDS) >= 50
assert len(sk.NEGATIVE_KEYWORDS) >= 100
assert len(sk.NEUTRAL_KEYWORDS) >= 15
def test_severity_levels_ordered(self):
levels = sk.SEVERITY_LEVELS
for a, b in zip(levels, levels[1:]):
assert a[1] <= b[0] + 1, f"overlap: {a} vs {b}"
# ============================================================
# 2. 情感分类
# ============================================================
from sentiment_crawler import SentimentClassifier
class TestClassifier:
def setup_method(self):
self.clf = SentimentClassifier()
def test_positive(self):
s, sc, hits, sev = self.clf.classify("贵州茅台业绩增长11%,分红方案获好评", "")
assert s == "positive", f"got {s}"
assert sc > 0
assert sev in ("低度利好", "中度利好", "重大利好")
def test_negative(self):
s, sc, hits, sev = self.clf.classify("ST退市预警,被证监会处罚责令改正", "")
assert s == "negative", f"got {s}"
assert sc >= 5
assert sev in ("低度关注", "中度舆情", "高危舆情")
def test_neutral(self):
s, sc, hits, sev = self.clf.classify("关于召开股东大会的通知", "")
# 既无正向也无负向重大命中 - 应当归为 neutral
assert s in ("neutral", "positive"), f"got {s}"
# 标题里「股东大会」「通知」是中性词,分数>=2 但应该归 neutral
if s == "neutral":
assert sev == "中性"
def test_severity_negative(self):
# 强烈负面
s, _, _, sev = self.clf.classify("资金链断裂,跑路!董事长失联,财务造假,债务违约", "")
assert s == "negative"
assert sev == "高危舆情"
def test_severity_positive(self):
s, _, _, sev = self.clf.classify("业绩增长,营业收入增长,归母净利润增长,分红方案", "")
assert s == "positive"
assert sev in ("低度利好", "中度利好", "重大利好")
# ============================================================
# 3. 媒体源 / 目标库加载
# ============================================================
from sentiment_crawler import SentimentSourceLoader, SentimentTargetLoader
class TestLoaders:
def test_sources_load(self):
loader = SentimentSourceLoader()
stats = loader.stats()
assert stats.get("authoritative", 0) >= 5
assert stats.get("financial_vertical", 0) >= 5
assert stats.get("self_media", 0) >= 5
assert stats.get("international", 0) >= 5
assert "local_media" not in stats # v6.0.0 已移除官媒分类
def test_targets_load(self):
loader = SentimentTargetLoader()
cats = loader.categories
assert "fund_company" in cats
assert "listed_company" in cats
assert "local_government" not in cats # v6.0.0 已移除政府目标
all_items = loader.all_targets()
assert len(all_items) >= 1
def test_pick_by_name(self):
loader = SentimentSourceLoader()
picked = loader.pick_by_names(["财联社"])
assert len(picked) >= 1
assert picked[0]["name"] == "财联社"
# ============================================================
# 4. 自定义目标
# ============================================================
def test_custom_target_add(tmp_path, monkeypatch):
# 隔离 user custom 文件
fake_user = tmp_path / "sentiment_custom_targets.json"
monkeypatch.setattr("sentiment_crawler.USER_CUSTOM_FILE", fake_user)
from sentiment_crawler import add_custom_sentiment_target
r = add_custom_sentiment_target("custom", f"_test_{tmp_path.name}_bank", aliases=["X银行"])
assert r.get("ok") is True
assert fake_user.exists()
# ============================================================
# 5. 对话 NLU
# ============================================================
from sentiment_chat import SentimentChatParser
class TestChatParser:
def setup_method(self):
self.p = SentimentChatParser()
def test_help(self):
result = self.p.parse("帮助")
assert result["intent"] == "help"
def test_crawl_single(self):
result = self.p.parse("帮我爬一下贵州茅台最近7天的舆情")
assert result["intent"] == "crawl"
assert "贵州茅台" in result["params"]["targets"] or len(result["params"]["targets"]) >= 1
assert result["params"]["days"] == 7
def test_crawl_multiple(self):
result = self.p.parse("看下华夏基金、招商银行、中国人寿过去3天的负面新闻")
assert result["intent"] == "crawl"
targets = result["params"]["targets"]
assert any("华夏基金" in t for t in targets)
assert any("招商银行" in t for t in targets)
assert any("中国人寿" in t for t in targets)
assert result["params"]["days"] == 3
assert result["params"]["negative_only"] is True
def test_crawl_export_word(self):
result = self.p.parse("看下华夏基金今天的正面新闻并生成Word")
assert result["intent"] == "crawl_export"
assert result["params"]["positive_only"] is True
assert result["params"]["export"] == "word"
def test_crawl_export_excel(self):
result = self.p.parse("工银瑞信最近3天的负面新闻,并导出Excel")
assert result["intent"] == "crawl_export"
assert result["params"]["negative_only"] is True
assert result["params"]["export"] == "excel"
def test_schedule_daily(self):
result = self.p.parse("每天早上9点爬取银行板块舆情")
assert result["intent"] == "schedule"
assert result["params"]["frequency"] == "daily"
assert result["params"]["action"] == "crawl_sentiment_export"
def test_schedule_every_n_minutes(self):
result = self.p.parse("每30分钟爬取银行舆情")
assert result["intent"] == "schedule"
assert result["params"]["frequency"] == "every_30_minutes"
def test_list_sources(self):
result = self.p.parse("哪些媒体可用?")
assert result["intent"] == "list"
assert result["params"]["what"] == "sources"
def test_list_targets(self):
result = self.p.parse("有哪些目标")
assert result["intent"] == "list"
assert result["params"]["what"] == "targets"
def test_add_target(self):
result = self.p.parse("新增自定义目标 工银瑞信")
assert result["intent"] == "add_target"
assert result["params"]["name"] == "工银瑞信"
def test_add_target_fund(self):
result = self.p.parse("新增目标 工银瑞信基金")
assert result["intent"] == "add_target"
assert result["params"]["name"] == "工银瑞信基金"
assert result["params"]["category"] == "fund_company"
# ============================================================
# 6. 导出器降级
# ============================================================
from sentiment_crawler import SentimentSnapshot, SentimentArticle
from sentiment_exporter import to_json, to_csv, export as export_sent
def _make_snapshot() -> SentimentSnapshot:
arts = [
SentimentArticle(title="T1", source="财联社", source_type="financial_vertical",
target_name="贵州茅台", target_type="上市公司",
publish_time="2026-07-27 10:00:00", url="https://example.com/1",
sentiment="positive", sentiment_score=10, severity="中度利好",
summary="业绩增长", keywords_matched=["业绩增长"]),
SentimentArticle(title="T2", source="新浪财经", source_type="self_media",
target_name="贵州茅台", target_type="上市公司",
publish_time="2026-07-26 08:00:00", url="https://example.com/2",
sentiment="negative", sentiment_score=20, severity="高危舆情",
summary="处罚决定", keywords_matched=["处罚"]),
]
return SentimentSnapshot(
snapshot_id="sn_test",
created_at="2026-07-27 12:00:00",
target_filter={"names": ["贵州茅台"], "categories": []},
source_filter=["财联社", "新浪财经"],
articles=arts,
stats={
"total": 2,
"by_sentiment": {"positive": 1, "negative": 1, "neutral": 0},
"by_severity": {"中度利好": 1, "高危舆情": 1},
"by_source_type": {"financial_vertical": 1, "self_media": 1},
},
)
class TestExporter:
def test_json(self, tmp_path):
snap = _make_snapshot()
out = to_json(snap, tmp_path / "x.json")
assert Path(out).exists()
loaded = json.loads(Path(out).read_text(encoding="utf-8"))
assert loaded["snapshot_id"] == "sn_test"
assert len(loaded["articles"]) == 2
def test_csv(self, tmp_path):
snap = _make_snapshot()
out = to_csv(snap, tmp_path / "x.csv")
assert Path(out).exists()
text = Path(out).read_text(encoding="utf-8-sig")
assert "财联社" in text
assert "T1" in text and "T2" in text
def test_excel(self, tmp_path):
try:
import openpyxl # noqa
except ImportError:
pytest.skip("openpyxl 未安装")
snap = _make_snapshot()
out = export_sent(snap, fmt="excel", output_path=tmp_path / "sn_test.xlsx")
# 返回 dict: {excel: path}
assert "excel" in out
p = Path(out["excel"])
assert p.exists()
assert p.stat().st_size > 1000
def test_word(self, tmp_path):
try:
import docx # noqa
except ImportError:
pytest.skip("python-docx 未安装")
snap = _make_snapshot()
out = export_sent(snap, fmt="word", output_path=tmp_path / "sn_test.docx")
assert "word" in out
assert Path(out["word"]).exists()
# ============================================================
# 7. ScheduledTask sentiment 字段
# ============================================================
def test_scheduled_task_sentiment_fields():
from crawl_scheduler import ScheduledTask, TaskFrequency, TaskAction
t = ScheduledTask(
task_id="x", name="bank_yuqing",
action=TaskAction.CRAWL_SENTIMENT_EXPORT,
sentiment_targets=["招商银行"],
sentiment_categories=["commercial_bank"],
sentiment_source_categories=["authoritative"],
sentiment_days=7, sentiment_negative_only=True,
sentiment_max=50, sentiment_export_format="all",
)
d = t.to_dict()
assert d["action"] == "crawl_sentiment_export"
assert d["sentiment_targets"] == ["招商银行"]
assert d["sentiment_days"] == 7
t2 = ScheduledTask.from_dict(d)
assert t2.sentiment_export_format == "all"
assert t2.sentiment_targets == ["招商银行"]
# ============================================================
# 8. Snapshot.to_dict
# ============================================================
def test_snapshot_to_dict():
snap = _make_snapshot()
d = snap.to_dict()
assert d["snapshot_id"] == "sn_test"
assert "stats" in d
assert "articles" in d
assert d["stats"]["by_sentiment"]["positive"] == 1
# ============================================================
# run with pytest
# ============================================================
if __name__ == "__main__":
pytest.main([__file__, "-v", "-x"])
# ============================================================
# 10. v4.3.1 优化后的测试 — 速度控制 / 短路 / 异常安全
from sentiment_crawler import SentimentCrawler
# ============================================================
import time as _time
class TestTimeoutsAndShortCircuit:
def test_time_up_default(self):
c = SentimentCrawler()
c._run_start_ts = _time.time()
assert c._time_up() is False
def test_time_up_exceeded(self):
c = SentimentCrawler(max_total_seconds=1)
c._run_start_ts = _time.time() - 5
assert c._time_up() is True
def test_placeholder_dedup(self):
c = SentimentCrawler()
# 第一次应 False
assert c._placeholder_seen("贵州茅台", "财联社") is False
# 第二次 True (占位已用过)
assert c._placeholder_seen("贵州茅台", "财联社") is True
# 不同 source 不互相影响
assert c._placeholder_seen("贵州茅台", "新华") is False
def test_dns_short_circuit(self):
c = SentimentCrawler()
# 不存在域名应短路
bad_url = "https://nonexistent-host-xyz.invalid/foo"
assert c._domain_unresolvable(bad_url) is True
def test_default_max_total_seconds(self):
"""默认 max_total_seconds 应 <=30s(对话体验友好)"""
from sentiment_crawler import crawl_sentiment, SentimentCrawler
c = SentimentCrawler()
assert c.max_total_seconds <= 60, f"got {c.max_total_seconds}"
class TestExceptionsSafe:
def test_chat_exception_safe(self):
from sentiment_chat import chat_handle
for txt in ["", " ", "\n", "你好", None, "💥⚡"]:
try:
r = chat_handle(txt or "empty")
assert "reply" in r
except Exception as e:
pytest.fail(f"chat_handle({txt!r}) crashed: {e}")
def test_classifier_empty(self):
clf = SentimentClassifier()
for s, sc, h, sev in [clf.classify("", ""), clf.classify(" ", None)]:
assert s in ("positive", "negative", "neutral")
class TestStatsCompleteness:
def test_stats_by_source_type(self):
from sentiment_crawler import SentimentSnapshot, SentimentArticle
from sentiment_exporter import to_dialog
# 制造一个 snapshots, 验证 to_dialog 显示 by_source_type
arts = [
SentimentArticle(title="t1", source="财联社", source_type="financial_vertical",
target_name="茅台", sentiment="positive", severity="低度利好"),
SentimentArticle(title="t2", source="财联社", source_type="authoritative",
target_name="茅台", sentiment="negative", severity="高危舆情"),
]
snap = SentimentSnapshot(
snapshot_id="test", created_at="2026-07-27",
target_filter={"names": ["茅台"], "categories": []},
source_filter=["财联社", "新华网"],
articles=arts,
stats={"total": 2, "by_sentiment": {"positive": 1, "negative": 1, "neutral": 0},
"by_severity": {"低度利好": 1, "高危舆情": 1},
"by_source_type": {"financial_vertical": 1, "authoritative": 1},
"elapsed_seconds": 12.3, "timed_out": True},
)
d = to_dialog(snap)
assert "媒体类别 Top" in d
assert "12.3s" in d or "12s" in d
assert "超时" in d
class TestSchedulerRoundtrip:
def test_sentiment_fields_roundtrip(self):
from crawl_scheduler import ScheduledTask, TaskAction
original = ScheduledTask(
task_id="x1", name="test",
action=TaskAction.CRAWL_SENTIMENT_EXPORT,
sentiment_targets=["工银瑞信", "贵州茅台"],
sentiment_categories=["fund_company"],
sentiment_source_categories=["authoritative"],
sentiment_days=5, sentiment_positive_only=True,
sentiment_negative_only=False, sentiment_export_format="word",
)
d = original.to_dict()
# 反序列化
restored = ScheduledTask.from_dict(d)
assert restored.sentiment_targets == ["工银瑞信", "贵州茅台"]
assert restored.sentiment_days == 5
assert restored.action == TaskAction.CRAWL_SENTIMENT_EXPORT
class TestFingerprint:
def test_url_normalized(self):
a = SentimentArticle(title="t", url="https://x.com/a?utm_source=x", target_name="y")
b = SentimentArticle(title="t", url="https://x.com/a?utm_source=y", target_name="y")
# utm 后缀应去掉,URL 同
assert a.fingerprint == b.fingerprint
def test_trailing_slash_normalized(self):
a = SentimentArticle(title="t", url="https://x.com/a/", target_name="y")
b = SentimentArticle(title="t", url="https://x.com/a", target_name="y")
assert a.fingerprint == b.fingerprint
+173
View File
@@ -0,0 +1,173 @@
# -*- coding: utf-8 -*-
"""v5.0.0 模块D:舆情分类器增强测试(否定词/相对时间/严重度统一/模糊去重)"""
import pytest
from scripts.sentiment_crawler import (
SentimentClassifier, SentimentCrawler, SentimentArticle,
_norm_time, _norm_relative_time,
_SEEN_INDEX, _TITLE_INDEX,
)
from scripts.sentiment_keywords import SEVERITY_LEVELS, SEVERITY_LEVELS_POSITIVE
# ============================================================
# 1. 否定词处理
# ============================================================
def test_negation_flips_negative():
"""「否认业绩下滑」不应判负面"""
c = SentimentClassifier()
sentiment, score, _, severity = c.classify("公司否认业绩下滑传闻")
assert sentiment != "negative"
def test_negation_keeps_positive_after_negation():
"""「否认业绩增长」应判中性(被否定)"""
c = SentimentClassifier()
sentiment, _, _, _ = c.classify("公司否认业绩增长")
assert sentiment == "neutral"
def test_no_negation_still_detects_negative():
c = SentimentClassifier()
assert c.classify("公司业绩下滑严重")[0] == "negative"
def test_negation_in_content_not_title():
"""否定词在正文而非标题时同样生效"""
c = SentimentClassifier()
sentiment, _, _, _ = c.classify("公司回应", "市场传言公司业绩下滑,但公司否认该说法")
assert sentiment != "negative"
# ============================================================
# 2. 相对时间解析
# ============================================================
def test_relative_hours_ago():
from datetime import datetime, timedelta
out = _norm_time("3小时前")
expect = (datetime.now() - timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S")
assert out == expect
def test_relative_yesterday():
from datetime import datetime, timedelta
out = _norm_relative_time("昨天")
expect = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S")
assert out == expect
def test_relative_day_before():
from datetime import datetime, timedelta
out = _norm_time("前天")
expect = (datetime.now() - timedelta(days=2)).strftime("%Y-%m-%d %H:%M:%S")
assert out == expect
def test_relative_minutes():
from datetime import datetime, timedelta
out = _norm_time("30分钟前")
expect = (datetime.now() - timedelta(minutes=30)).strftime("%Y-%m-%d %H:%M:%S")
assert out == expect
def test_absolute_time_unchanged():
"""绝对时间不受相对时间正则影响"""
assert _norm_time("2026-07-27") == "2026-07-27 00:00:00"
assert _norm_time("2026-07-27 09:42") == "2026-07-27 09:42:00"
def test_relative_not_matched_for_plain_text():
assert _norm_relative_time("没有任何相对时间") == ""
# ============================================================
# 3. 严重度阈值统一
# ============================================================
def test_severity_tables_defined():
assert len(SEVERITY_LEVELS) >= 4
assert len(SEVERITY_LEVELS_POSITIVE) >= 4
def test_severity_uses_unified_tables():
"""_severity 应从表取档,与 sentiment_keywords 一致"""
c = SentimentClassifier()
# 负面 10 分 → 查 SEVERITY_LEVELS:(4,9)低度 / (9,18)中度
assert c._severity(10.0, "negative") == "中度舆情"
# 负面 5 分 → 低度关注
assert c._severity(5.0, "negative") == "低度关注"
# 正面 20 分 → SEVERITY_LEVELS_POSITIVE 中度利好
assert c._severity(20.0, "positive") == "中度利好"
# 正面 40 分 → 重大利好
assert c._severity(40.0, "positive") == "重大利好"
# 中性恒为中性
assert c._severity(99.0, "neutral") == "中性"
def test_severity_consistency_with_table():
"""从表推导与函数一致(防止再出现两套阈值)"""
c = SentimentClassifier()
for lo, hi, label in SEVERITY_LEVELS:
assert c._severity((lo + hi) / 2.0, "negative") == label
for lo, hi, label in SEVERITY_LEVELS_POSITIVE:
assert c._severity((lo + hi) / 2.0, "positive") == label
# ============================================================
# 4. 模糊去重
# ============================================================
def _make_article(title, target="贵州茅台", url="https://x.com/a"):
return SentimentArticle(title=title, target_name=target, url=url, publish_time="2026-08-01")
def test_fuzzy_dedup_detects_similar(monkeypatch):
_TITLE_INDEX.clear()
_SEEN_INDEX.clear()
crawler = SentimentCrawler()
# 先加入一条
assert crawler._is_dup(_make_article("贵州茅台发布2026年半年度报告")) is False
# 相似标题(加标点/日期差异)→ 模糊命中
similar = _make_article("贵州茅台发布2026年半年度报告!", url="https://x.com/b")
assert crawler._is_dup(similar) is True
assert similar.dedup_ratio > 0.85
def test_fuzzy_dedup_allows_distinct_titles(monkeypatch):
_TITLE_INDEX.clear()
_SEEN_INDEX.clear()
crawler = SentimentCrawler()
assert crawler._is_dup(_make_article("茅台分红方案")) is False
assert crawler._is_dup(_make_article("宁德时代业绩增长")) is False # 不同 target 不误判
def test_fuzzy_dedup_per_target():
"""模糊索引按 target 隔离"""
_TITLE_INDEX.clear()
crawler = SentimentCrawler()
crawler._is_dup(_make_article("利好新闻", target="公司A", url="https://x/1"))
# 同标题不同 target → 不算重复
assert crawler._is_dup(_make_article("利好新闻", target="公司B", url="https://x/2")) is False
def test_placeholder_not_deduped(monkeypatch):
_SEEN_INDEX.clear()
_TITLE_INDEX.clear()
crawler = SentimentCrawler()
p = SentimentArticle(title="[未能直接抓取] 某公司", target_name="某公司", url="https://x")
assert crawler._is_dup(p) is False
# ============================================================
# 5. dedup_ratio 字段序列化
# ============================================================
def test_article_has_dedup_ratio_field():
a = SentimentArticle(title="x", target_name="y")
assert a.dedup_ratio == 0.0
a.dedup_ratio = 0.9
d = a.to_dict()
assert d["dedup_ratio"] == 0.9
+326
View File
@@ -0,0 +1,326 @@
# -*- coding: utf-8 -*-
"""v4.5.1 三项强化 — 单元测试
覆盖:
1. 回测过滤 (filter_by_recommendation)
2. 回测批量汇总 (batch_summary)
3. 爬取前确认 (输入校验 / 风险提示 / 缓存预览 / 覆盖率估算)
4. 并发抓取 (parallel_workers)
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.dont_write_bytecode = True
import unittest
from datetime import datetime, timedelta
import pytest
# ============================================================
# 1. 回测过滤
# ============================================================
class TestBacktestFilter(unittest.TestCase):
"""filter_by_recommendation 的行为。"""
def _mk(self, rec: str, score: float = 0.7, passed: bool = True) -> object:
# 简化构造的 BacktestResult-like 对象
class R:
pass
r = R()
r.recommendation = rec
r.overall_score = score
r.passed = passed
r.source_credibility = 0.6
r.issues = []
return r
def test_drop_建议丢弃(self):
from scripts.crawl_backtester import filter_by_recommendation
results = [self._mk("可信任"), self._mk("建议丢弃"), self._mk("需人工核实")]
articles = ["a", "b", "c"]
kept_a, kept_r = filter_by_recommendation(results, articles, ("建议丢弃",))
self.assertEqual([id(x) for x in kept_a], [id(x) for x in ("a", "c")])
self.assertEqual(len(kept_r), 2)
def test_drop_multiple_levels(self):
from scripts.crawl_backtester import filter_by_recommendation
results = [self._mk("可信任"), self._mk("建议丢弃"), self._mk("需人工核实")]
articles = ["a", "b", "c"]
kept_a, kept_r = filter_by_recommendation(
results, articles, ("建议丢弃", "需人工核实"),
)
self.assertEqual(kept_a, ["a"])
self.assertEqual(len(kept_r), 1)
def test_empty_input(self):
from scripts.crawl_backtester import filter_by_recommendation
kept_a, kept_r = filter_by_recommendation([], [])
self.assertEqual(kept_a, [])
self.assertEqual(kept_r, [])
def test_no_drop_when_default(self):
from scripts.crawl_backtester import filter_by_recommendation
results = [self._mk("建议丢弃"), self._mk("可信任")]
articles = ["a", "b"]
kept_a, kept_r = filter_by_recommendation(results, articles, ())
self.assertEqual(kept_a, articles)
self.assertEqual(len(kept_r), 2)
# ============================================================
# 2. 回测批量汇总
# ============================================================
class TestBatchSummary(unittest.TestCase):
def _mk(self, rec, score=0.7, passed=True, issues=None, cred=0.6):
class R:
pass
r = R()
r.recommendation = rec
r.overall_score = score
r.passed = passed
r.source_credibility = cred
r.issues = issues or []
return r
def test_empty(self):
from scripts.crawl_backtester import batch_summary
s = batch_summary([])
self.assertEqual(s["total"], 0)
self.assertEqual(s["pass_rate"], 0.0)
def test_mixed_recommendations(self):
from scripts.crawl_backtester import batch_summary
rs = [
self._mk("可信任", score=0.9, passed=True, cred=0.8),
self._mk("可信任", score=0.85, passed=True, cred=0.7),
self._mk("需人工核实", score=0.6, passed=True, issues=["孤源"], cred=0.5),
self._mk("建议丢弃", score=0.2, passed=False, issues=["过期"], cred=0.3),
]
s = batch_summary(rs)
self.assertEqual(s["total"], 4)
self.assertEqual(s["passed"], 3)
self.assertEqual(s["failed"], 1)
self.assertAlmostEqual(s["pass_rate"], 0.75, places=2)
self.assertEqual(s["by_recommendation"]["可信任"], 2)
self.assertEqual(s["by_recommendation"]["需人工核实"], 1)
self.assertEqual(s["by_recommendation"]["建议丢弃"], 1)
# 问题类型分类
self.assertIn("孤源", s["by_issue_type"])
self.assertIn("过期", s["by_issue_type"])
def test_issue_type_classification(self):
from scripts.crawl_backtester import batch_summary
rs = [
self._mk("需人工核实", issues=["文章新鲜度低 (5 天)"]),
self._mk("建议丢弃", issues=["数字不一致 2 处"]),
self._mk("建议丢弃", issues=["文章已过期 (30 天)", "数字不一致 1 处"]),
]
s = batch_summary(rs)
self.assertEqual(s["by_issue_type"].get("新鲜度低"), 1)
self.assertEqual(s["by_issue_type"].get("数字不一致"), 2)
self.assertEqual(s["by_issue_type"].get("过期"), 1)
# ============================================================
# 3. 爬取前确认
# ============================================================
class TestPlanValidation(unittest.TestCase):
def setUp(self):
# 强制使用测试数据副本,避免污染真实数据
import tempfile
self.tmp = tempfile.mkdtemp(prefix="v451_test_")
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
from sentiment_crawler import (
SentimentCrawler, SentimentSourceLoader, SentimentTargetLoader,
)
self.loader_src = SentimentSourceLoader()
self.loader_tgt = SentimentTargetLoader()
self.crawler = SentimentCrawler(
sources=self.loader_src,
targets=self.loader_tgt,
snapshot_dir=Path(self.tmp),
max_total_seconds=30,
)
def test_days_out_of_range(self):
snap = self.crawler.crawl(days=200, dry_run=True)
self.assertTrue(len(snap.plan.get("validation_errors", [])), "应捕获 days 越界")
self.assertIn("200", snap.plan["validation_errors"][0])
def test_max_articles_out_of_range(self):
snap = self.crawler.crawl(max_articles=0, dry_run=True)
self.assertTrue(len(snap.plan.get("validation_errors", [])), "应捕获 max_articles 非法")
def test_short_target_name_warning(self):
snap = self.crawler.crawl(target_names=["A"], dry_run=True)
warnings = snap.plan.get("risk_warnings", [])
self.assertTrue(any("过短" in w for w in warnings), f"应有短名警告,实际: {warnings}")
def test_test_keyword_warning(self):
snap = self.crawler.crawl(target_names=["某测试机构"], dry_run=True)
warnings = snap.plan.get("risk_warnings", [])
self.assertTrue(any("测试占位" in w for w in warnings), f"应有测试占位警告")
def test_too_many_sources_warning(self):
# 超过 30 个源 → 警告
snap = self.crawler.crawl(
source_names=None,
source_categories=None, # 默认全选
dry_run=True,
)
# 默认所有源,可能 > 30,验证字段存在
self.assertIn("risk_warnings", snap.plan)
self.assertIn("coverage_estimate", snap.plan)
self.assertIn("sample_articles", snap.plan)
self.assertIn("validation_errors", snap.plan)
def test_validation_failed_short_circuits(self):
snap = self.crawler.crawl(days=-1, dry_run=True)
self.assertEqual(snap.stats.get("validation_failed"), True)
self.assertEqual(snap.plan["targets"], [])
self.assertEqual(snap.plan["actions"], [])
def test_plan_has_coverage_estimate(self):
snap = self.crawler.crawl(dry_run=True)
cov = snap.plan.get("coverage_estimate", {})
self.assertIn("historical_snapshots", cov)
self.assertIn("historical_hit_rate", cov)
self.assertIn("expected_avg_articles_per_target", cov)
def test_plan_has_sample_articles(self):
snap = self.crawler.crawl(dry_run=True)
# 新建爬虫无历史快照时,sample 列表应为空(不抛错)
self.assertIsInstance(snap.plan.get("sample_articles", []), list)
def test_valid_inputs_no_validation_errors(self):
snap = self.crawler.crawl(
target_names=["贵州茅台"],
days=7,
source_categories=["authoritative"],
dry_run=True,
)
self.assertEqual(snap.plan.get("validation_errors", []), [])
self.assertGreater(len(snap.plan.get("targets", [])), 0)
self.assertGreater(len(snap.plan.get("sources", [])), 0)
# ============================================================
# 4. 并发抓取
# ============================================================
class TestParallelCrawl(unittest.TestCase):
"""parallel_workers > 0 时应使用 ThreadPoolExecutor 并发。"""
def setUp(self):
import tempfile
self.tmp = tempfile.mkdtemp(prefix="v451_par_test_")
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
from sentiment_crawler import SentimentCrawler, SentimentSourceLoader, SentimentTargetLoader
self.crawler = SentimentCrawler(
sources=SentimentSourceLoader(),
targets=SentimentTargetLoader(),
snapshot_dir=Path(self.tmp),
max_total_seconds=20,
per_source_timeout=3,
)
def test_parallel_workers_collected_more_than_sequential(self):
"""并发抓取应至少与顺序抓取返回等价的结果数(不破坏数据完整性)。"""
# 模拟一个极小测试场景:1 目标 + 1 源 + 强 mock 让 _query_source 直接 yield 一篇
from unittest.mock import patch
from scripts.sentiment_crawler import SentimentArticle
# 构造一个简单的 fake article
def fake_query(self, src, target_name, kw, cat, label, cutoff_time):
yield SentimentArticle(
title=f"{target_name} - {src.get('name', '')} - {kw}",
summary="test",
content="",
source=src.get("name", ""),
source_type=src.get("category", ""),
target_name=target_name,
target_type=label,
publish_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
url=f"https://x.com/{target_name}",
sentiment="neutral",
sentiment_score=1.0,
severity="中性",
category="",
)
# 清空 _SEEN_INDEX 防止跨测试干扰。
# 注意:crawler 由 `from sentiment_crawler import`(无 scripts 前缀)实例化,
# 与 `scripts.sentiment_crawler` 是同一文件的两个模块实例,需同时清空;
# 且 _SEEN_INDEX 从磁盘文件加载,需一并重置(测试后恢复),避免历史指纹去重误杀。
from scripts.sentiment_crawler import _SEEN_INDEX as _SEEN_INDEX_SCRIPTS
import sentiment_crawler as _sc_mod
_seen_file = _sc_mod._SEEN_INDEX_FILE
_orig_seen_data = _seen_file.read_text(encoding="utf-8")
_sc_mod._SEEN_INDEX.clear()
_SEEN_INDEX_SCRIPTS.clear()
_seen_file.write_text("{}", encoding="utf-8")
try:
with patch.object(type(self.crawler), "_query_source", fake_query):
snap = self.crawler.crawl(
target_names=["目标A", "目标B"],
source_categories=["authoritative"],
days=7,
max_articles=20,
parallel_workers=4,
)
finally:
# 恢复去重索引文件
_seen_file.write_text(_orig_seen_data, encoding="utf-8")
self.assertGreater(len(snap.articles), 0)
# 至少 2 个目标 * 1 源 * 1 关键词 → 2+ 篇(去重后)
self.assertGreaterEqual(len(snap.articles), 2)
# 所有文章都应有 source / target_name
for art in snap.articles:
self.assertTrue(art.source)
self.assertIn(art.target_name, ("目标A", "目标B"))
# ============================================================
# 5. 集成测试:dry_run → confirm 流程
# ============================================================
class TestDryRunConfirmFlow(unittest.TestCase):
def setUp(self):
import tempfile
self.tmp = tempfile.mkdtemp(prefix="v451_dry_")
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
from sentiment_crawler import SentimentCrawler, SentimentSourceLoader, SentimentTargetLoader
self.crawler = SentimentCrawler(
sources=SentimentSourceLoader(),
targets=SentimentTargetLoader(),
snapshot_dir=Path(self.tmp),
max_total_seconds=20,
)
def test_dry_run_returns_plan_with_estimated_seconds(self):
snap = self.crawler.crawl(
target_names=["贵州茅台"],
source_categories=["authoritative"],
dry_run=True,
)
self.assertEqual(snap.stats.get("dry_run"), True)
self.assertGreater(snap.plan["estimated_seconds"], 0)
self.assertIn("estimated_articles", snap.plan)
def test_dry_run_not_confirmed_path(self):
# 模拟用户还没确认
snap = self.crawler.crawl(
target_names=["贵州茅台"],
confirmed=False,
dry_run=False,
)
# 因 confirmed=False, 等同 dry_run=True
self.assertEqual(snap.stats.get("dry_run"), True)
self.assertTrue(snap.is_awaiting_confirmation)
if __name__ == "__main__":
unittest.main()
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""v4.7.1 零依赖回归测试
目标:确保未安装 BeautifulSoup 等第三方包时,核心包仍可导入,
自适应解析与全量机构爬虫提供 stdlib 降级路径。
"""
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
SCRIPTS = ROOT / "scripts"
if str(SCRIPTS) not in sys.path:
sys.path.insert(0, str(SCRIPTS))
def test_adaptive_parser_stdlib_table_fallback(monkeypatch):
from scripts.adaptive_parser_v2 import AdaptivePageParser, HAS_BS4
original = HAS_BS4
monkeypatch.setattr("scripts.adaptive_parser_v2.HAS_BS4", False)
try:
html = (
"<table><tr><th>名称</th><th>代码</th></tr>"
"<tr><td>测试基金</td><td>000001</td></tr></table>"
)
rows = AdaptivePageParser().parse_table(html)
assert rows == [{"名称": "测试基金", "代码": "000001"}]
finally:
monkeypatch.setattr("scripts.adaptive_parser_v2.HAS_BS4", original)
def test_full_institution_crawler_stdlib_fallback(monkeypatch):
from scripts.full_institution_crawler import FullInstitutionCrawler, HAS_BS4
original = HAS_BS4
monkeypatch.setattr("scripts.full_institution_crawler.HAS_BS4", False)
try:
html = (
"<table><tr><th>name</th><th>code</th></tr>"
"<tr><td>测试银行</td><td>ABC</td></tr></table>"
)
rows = FullInstitutionCrawler()._parse_html_table(html)
assert rows == [["name", "code"], ["测试银行", "ABC"]]
finally:
monkeypatch.setattr("scripts.full_institution_crawler.HAS_BS4", original)
def test_scripts_package_does_not_require_bs4_import():
"""核心包入口不应在模块顶层强制 import bs4。"""
init_src = (SCRIPTS / "__init__.py").read_text(encoding="utf-8")
parser_src = (SCRIPTS / "adaptive_parser_v2.py").read_text(encoding="utf-8")
crawler_src = (SCRIPTS / "full_institution_crawler.py").read_text(encoding="utf-8")
assert "from bs4" not in init_src, "scripts/__init__.py 不应顶层强制导入 bs4"
assert "HAS_BS4" in parser_src
assert "HAS_BS4" in crawler_src
def test_runtests_uses_pytest_main():
src = (ROOT / "runtests.py").read_text(encoding="utf-8")
assert "os.execvp" not in src, "runtests.py 不应再用 os.execvp"
assert "pytest.main" in src, "runtests.py 应改为同一进程内 pytest.main"
def test_pytest_ini_no_unknown_option():
src = (ROOT / "pytest.ini").read_text(encoding="utf-8")
assert "cache_dir" not in src, "pytest.ini 不应包含未知的 cache_dir 配置"
def test_package_uses_unique_temp_dir_and_cleans_up():
import tempfile
from pathlib import Path
from scripts.crawl_packager import CrawlPackager, TEMP_DIR
with tempfile.TemporaryDirectory() as out:
packager = CrawlPackager(output_dir=out)
p1 = packager.package([{"name": "A", "content": "x"}], zip_name="same_name")
p2 = packager.package([{"name": "B", "content": "y"}], zip_name="same_name")
assert Path(p1).exists()
assert Path(p2).exists()
leftovers = [p for p in TEMP_DIR.glob("same_name_*") if p.is_dir()]
assert leftovers == [], f"临时目录应清理干净,残留: {leftovers}"
+611
View File
@@ -0,0 +1,611 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""v4.9.0 新增反爬能力测试(test_v490_anti_block.py)
覆盖:
- akshare_fallback:fetch_with_fallback 路由 + 各类适配器
- rss_feeds:RSS 解析器 + 内置数据源
- anti_block_utils:域限速 / Cookie 持久化 / 错误码识别 / 指数退避
"""
from __future__ import annotations
import json
import os
import sys
import tempfile
import threading
import time
from pathlib import Path
from unittest.mock import patch, MagicMock
from xml.etree import ElementTree as ET
import pytest
SKILL_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(SKILL_DIR / "scripts"))
# ============================================================================
# akshare_fallback 测试
# ============================================================================
class TestFetchWithFallback:
"""fetch_with_fallback 路由测试。"""
def test_primary_returns_data_no_fallback(self):
"""primary 返回有效数据时不应调用 fallback。"""
from akshare_fallback import fetch_with_fallback
primary_called = []
fallback_called = []
def _primary(**kw):
primary_called.append(True)
return [{"title": "primary"}]
def _fallback(**kw):
fallback_called.append(True)
return [{"title": "fallback"}]
# Mock sys.modules entry
import sys as _sys
# 由于 fetch_with_fallback 用字符串导入模块,我们直接 patch 内置函数
with patch.object(
__import__("akshare_fallback"), "_call_primary",
side_effect=lambda m, f, kw: _primary(**kw),
), patch.object(
__import__("akshare_fallback"), "_call_akshare",
side_effect=lambda f, kw: _fallback(**kw),
):
result = fetch_with_fallback(
primary=("any_module", "any_func", {}),
fallback=("akshare", "any_ak_func", {}),
mock=None,
)
assert primary_called, "primary 应被调用"
assert result == [{"title": "primary"}]
def test_primary_returns_none_triggers_fallback(self):
"""primary 返回 None 时应自动降级到 fallback。"""
from akshare_fallback import fetch_with_fallback
with patch.object(
__import__("akshare_fallback"), "_call_primary",
return_value=None,
), patch.object(
__import__("akshare_fallback"), "_call_akshare",
return_value=[{"title": "from akshare"}],
):
result = fetch_with_fallback(
primary=("any", "func", {}),
fallback=("akshare", "func", {}),
)
assert result == [{"title": "from akshare"}]
def test_primary_returns_empty_list_triggers_fallback_with_validator(self):
"""primary 返回空列表时,validator 判定应触发 fallback。"""
from akshare_fallback import fetch_with_fallback
with patch.object(
__import__("akshare_fallback"), "_call_primary",
return_value=[],
), patch.object(
__import__("akshare_fallback"), "_call_akshare",
return_value=[{"x": 1}],
):
result = fetch_with_fallback(
primary=("any", "func", {}),
fallback=("akshare", "func", {}),
data_validator=lambda d: isinstance(d, list) and len(d) > 0,
)
assert result == [{"x": 1}]
def test_no_fallback_returns_mock(self):
"""无 fallback 时应返回 mock。"""
from akshare_fallback import fetch_with_fallback
with patch.object(
__import__("akshare_fallback"), "_call_primary",
return_value=None,
):
result = fetch_with_fallback(
primary=("any", "func", {}),
fallback=None,
mock=[{"mock": True}],
)
assert result == [{"mock": True}]
def test_no_fallback_no_mock_returns_none(self):
"""无 fallback 无 mock 时返回 None(不抛错)。"""
from akshare_fallback import fetch_with_fallback
with patch.object(
__import__("akshare_fallback"), "_call_primary",
return_value=None,
):
result = fetch_with_fallback(
primary=("any", "func", {}),
fallback=None,
mock=None,
)
assert result is None
class TestAkshareFallbackHelpers:
def test_fetch_cls_hot_articles_returns_list(self):
"""fetch_cls_hot_articles 应返回 list。"""
from akshare_fallback import fetch_cls_hot_articles
with patch.object(
__import__("akshare_fallback"), "fetch_with_fallback",
return_value=[{"title": "test"}],
):
r = fetch_cls_hot_articles(limit=5)
assert isinstance(r, list)
def test_fetch_sina_realtime_returns_dict(self):
from akshare_fallback import fetch_sina_realtime
with patch.object(
__import__("akshare_fallback"), "fetch_with_fallback",
return_value={"600519": {"name": "贵州茅台"}},
):
r = fetch_sina_realtime(["600519"])
assert isinstance(r, dict)
# ============================================================================
# rss_feeds 测试
# ============================================================================
class TestRssParser:
"""RSS XML 解析器测试。"""
def test_parse_rss_2_with_cdata(self):
"""解析标准 RSS 2.0 + CDATA。"""
from rss_feeds import _parse_rss_xml
xml = """<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>Test Feed</title>
<item>
<title><![CDATA[新闻标题]]></title>
<link>https://example.com/a</link>
<description><![CDATA[<p>HTML 描述</p>]]></description>
<pubDate>Mon, 09 Aug 2026 12:00:00 +0800</pubDate>
<dc:creator>作者A</dc:creator>
</item>
<item>
<title>第二条</title>
<link>https://example.com/b</link>
</item>
</channel>
</rss>""".encode("utf-8")
items = _parse_rss_xml(xml, "Test Feed")
assert len(items) == 2
assert items[0].title == "新闻标题"
assert items[0].link == "https://example.com/a"
assert "HTML 描述" in items[0].description # HTML 标签被剥离
assert "2026-08-09" in items[0].pub_date
assert items[0].author == "作者A"
assert items[1].title == "第二条"
def test_parse_atom_1(self):
"""解析 Atom 1.0。"""
from rss_feeds import _parse_rss_xml
xml = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Atom Feed</title>
<entry>
<title>Atom Item</title>
<link href="https://example.com/atom1"/>
<updated>2026-08-09T12:00:00Z</updated>
<author><name>Atom Author</name></author>
</entry>
</feed>""".encode("utf-8")
items = _parse_rss_xml(xml, "Atom Feed")
assert len(items) == 1
assert items[0].title == "Atom Item"
assert items[0].link == "https://example.com/atom1"
assert "2026-08-09" in items[0].pub_date
def test_parse_bom_stripped(self):
"""BOM 头应被自动移除。"""
from rss_feeds import _parse_rss_xml
xml = b"\xef\xbb\xbf<?xml version='1.0'?><rss><channel><item>" \
b"<title>BOM Test</title><link>x</link></item></channel></rss>"
items = _parse_rss_xml(xml, "BOM")
assert items[0].title == "BOM Test"
def test_parse_invalid_xml_returns_empty(self):
"""无效 XML 应返回空列表(不抛错)。"""
from rss_feeds import _parse_rss_xml
items = _parse_rss_xml(b"<not-xml", "invalid")
assert items == []
def test_strip_html(self):
"""HTML 标签应被正确剥离(CDATA 内的标签也会被剥离)。"""
from rss_feeds import _strip_html
assert _strip_html("<p>hello</p>") == "hello"
assert _strip_html("a &amp; b") == "a & b"
# CDATA 内的 HTML 标签也会被剥离(先剥 CDATA 再剥 HTML)
assert _strip_html("<![CDATA[<p>x</p>]]>") == "x"
assert _strip_html("") == ""
def test_parse_date_rfc822(self):
"""RFC 822 日期解析。"""
from rss_feeds import _parse_date
result = _parse_date("Mon, 09 Aug 2026 12:00:00 +0800")
assert "2026-08-09" in result
class TestFinancialFeedsList:
def test_list_all_categories(self):
"""默认返回所有分类。"""
from rss_feeds import list_financial_feeds
feeds = list_financial_feeds()
assert len(feeds) >= 2
names = [f["name"] for f in feeds]
assert "东方财富" in "|".join(names)
def test_list_authoritative(self):
"""media 类别应含商业财经源。"""
from rss_feeds import list_financial_feeds
feeds = list_financial_feeds("media")
assert all("url" in f for f in feeds)
assert all("name" in f for f in feeds)
def test_list_nonexistent_category_returns_empty(self):
from rss_feeds import list_financial_feeds
assert list_financial_feeds("nonexistent") == []
class TestRssFetcher:
"""RssFetcher 类测试(使用 mock)。"""
def test_fetch_invalid_url_returns_empty(self):
"""无 url 的源应返回空列表(不抛错)。"""
from rss_feeds import RssFetcher
fetcher = RssFetcher()
items = fetcher.fetch({"name": "Empty", "url": ""})
assert items == []
def test_fetch_many_dedup(self):
"""fetch_many 应去重(基于 guid)。"""
from rss_feeds import RssFetcher, _parse_rss_xml
# 同一 XML 内容,两次 feed,应去重
xml = """<?xml version="1.0"?><rss><channel>
<item><title>A</title><link>x</link><guid>abc</guid></item>
<item><title>B</title><link>y</link><guid>def</guid></item>
</channel></rss>""".encode("utf-8")
fetcher = RssFetcher()
items1 = _parse_rss_xml(xml, "F1")
items2 = _parse_rss_xml(xml, "F2")
# 模拟:两个 feed 返回相同 guid
with patch.object(fetcher, "fetch", side_effect=[items1, items2]):
combined = fetcher.fetch_many(
[{"name": "F1"}, {"name": "F2"}], max_total=100
)
# 去重后应只有 2 条(abc + def)
assert len(combined) == 2
assert {it.guid for it in combined} == {"abc", "def"}
# ============================================================================
# anti_block_utils 测试
# ============================================================================
class TestDomainRateLimiter:
def test_normalize_domain(self):
"""域名规范化:去子域。"""
from anti_block_utils import DomainRateLimiter
rl = DomainRateLimiter()
assert rl._normalize_domain("https://www.cls.cn/api") == "cls.cn"
assert rl._normalize_domain("https://api.eastmoney.com/x") == "eastmoney.com"
assert rl._normalize_domain("https://hq.sinajs.cn") == "sinajs.cn"
def test_get_interval_uses_default(self):
from anti_block_utils import DomainRateLimiter
rl = DomainRateLimiter(default_interval=2.5)
assert rl.get_interval("https://unknown.com") == 2.5
def test_get_interval_uses_specific(self):
from anti_block_utils import DomainRateLimiter
rl = DomainRateLimiter({"cls.cn": 3.0}, default_interval=1.0)
assert rl.get_interval("https://www.cls.cn") == 3.0
assert rl.get_interval("https://other.com") == 1.0
def test_wait_respects_interval(self):
"""wait 应等待至少 interval 秒。"""
from anti_block_utils import DomainRateLimiter
rl = DomainRateLimiter({"test.com": 0.1}) # 100ms
start = time.monotonic()
rl.wait("https://test.com/x")
rl.wait("https://test.com/y") # 第二次调用应等候
elapsed = time.monotonic() - start
# 至少等 100ms
assert elapsed >= 0.05 # 留些余量
def test_wait_thread_safe(self):
"""多线程调用 wait 不应崩溃。"""
from anti_block_utils import DomainRateLimiter
rl = DomainRateLimiter(default_interval=0.05)
def worker():
for _ in range(5):
rl.wait("https://test.com/x")
threads = [threading.Thread(target=worker) for _ in range(3)]
for t in threads:
t.start()
for t in threads:
t.join(timeout=5)
class TestPersistentCookieStore:
def test_save_and_load_roundtrip(self, tmp_path):
from anti_block_utils import PersistentCookieStore
path = tmp_path / "cookies.json"
store = PersistentCookieStore(path)
cookies = [
{"name": "sid", "value": "abc123", "domain": ".cls.cn"},
{"name": "tk", "value": "xyz789", "domain": ".cls.cn",
"expires": (time.time() + 86400)}, # 明天过期
]
store.save(cookies)
loaded = store.load()
assert len(loaded) == 2
assert loaded[0]["name"] == "sid"
def test_load_filters_expired(self, tmp_path):
from anti_block_utils import PersistentCookieStore
path = tmp_path / "cookies.json"
store = PersistentCookieStore(path, ttl_days=1)
cookies = [
{"name": "old", "value": "v", "expires": (time.time() - 86400)}, # 昨天过期
{"name": "new", "value": "v"}, # 无过期时间 → 保留
]
store.save(cookies)
loaded = store.load()
names = [c["name"] for c in loaded]
assert "old" not in names
assert "new" in names
def test_load_missing_file_returns_empty(self, tmp_path):
from anti_block_utils import PersistentCookieStore
store = PersistentCookieStore(tmp_path / "nonexistent.json")
assert store.load() == []
class TestBlockDetector:
def test_403_detected(self):
from anti_block_utils import detect_block
sig = detect_block(403)
assert sig is not None
assert sig.code == 403
assert "Forbidden" in sig.reason or "Forbidden" in sig.advice
assert sig.cooldown > 0
def test_429_detected(self):
from anti_block_utils import detect_block
sig = detect_block(429)
assert sig is not None
assert sig.code == 429
def test_503_detected(self):
from anti_block_utils import detect_block
sig = detect_block(503)
assert sig is not None
assert sig.code == 503
def test_200_with_danger_signs_detected(self):
"""200 响应含反爬文本特征时也应被识别。"""
from anti_block_utils import detect_block
sig = detect_block(200, body_sample="访问频率过高,请稍后再试")
assert sig is not None
assert "软拦截" in sig.reason or "频率" in sig.reason
def test_200_normal_content_returns_none(self):
"""200 正常响应应返回 None。"""
from anti_block_utils import detect_block
sig = detect_block(200, body_sample="<html>正常内容</html>")
assert sig is None
def test_404_returns_none(self):
"""404 未被列入封禁模式。"""
from anti_block_utils import detect_block
assert detect_block(404) is None
class TestExponentialBackoff:
def test_doubles_each_attempt(self):
from anti_block_utils import exponential_backoff
delays = [exponential_backoff(i, base=1, jitter=False) for i in range(1, 6)]
assert delays == [1.0, 2.0, 4.0, 8.0, 16.0]
def test_caps_at_max_delay(self):
from anti_block_utils import exponential_backoff
delay = exponential_backoff(20, base=1, max_delay=10.0, jitter=False)
assert delay == 10.0
def test_jitter_randomizes(self):
from anti_block_utils import exponential_backoff
# jitter=True 时应随机(两次调用结果不同)
d1 = exponential_backoff(3, base=1, jitter=True)
d2 = exponential_backoff(3, base=1, jitter=True)
# 范围:4 * (0.5 ~ 1.5) = 2.0 ~ 6.0(random.random() ∈ [0, 1))
assert 2.0 <= d1 < 6.0
assert 2.0 <= d2 < 6.0
# 极小概率相等(随机种子),但大部分时候不等
class TestConditionalCache:
def test_get_request_headers_initial_empty(self, tmp_path):
from anti_block_utils import ConditionalCache
cache = ConditionalCache(tmp_path / "etag.json")
headers = cache.get_request_headers("https://example.com/x")
assert headers == {}
def test_update_then_get_headers(self, tmp_path):
from anti_block_utils import ConditionalCache
cache = ConditionalCache(tmp_path / "etag.json")
cache.update("https://example.com/x", etag='"abc"', last_modified="Mon, 09 Aug 2026")
headers = cache.get_request_headers("https://example.com/x")
assert headers["If-None-Match"] == '"abc"'
assert "Mon, 09 Aug 2026" in headers["If-Modified-Since"]
def test_cached_body_roundtrip(self, tmp_path):
from anti_block_utils import ConditionalCache
cache = ConditionalCache(tmp_path / "etag.json")
cache.update("https://example.com/y", etag='"xyz"', last_modified=None, body="cached body")
assert cache.get_cached_body("https://example.com/y") == "cached body"
def test_size_limit_triggers_cleanup(self, tmp_path):
"""超过 5000 条应触发清理(保留最新)。"""
from anti_block_utils import ConditionalCache
cache = ConditionalCache(tmp_path / "etag.json")
# 写 5050 条
for i in range(5050):
cache.update(f"https://example.com/{i}", etag=f'"e{i}"', last_modified=None)
# 触发清理
cache._save()
# 应被截断到 5000 - 1000 = 4000 + 5050 - 5000 = 50 之间
# 实际逻辑:>5000 时清理最旧 1000,剩 4000 - 实际剩 4050
# 验证:总条数 < 5050
assert len(cache._data) < 5050
class TestTLSFingerprintClient:
def test_property_available(self):
from anti_block_utils import TLSFingerprintClient
client = TLSFingerprintClient()
# 仅断言属性可访问;不强制要求 curl_cffi 已装
assert isinstance(client.available, bool)
def test_get_without_library_raises(self):
"""curl_cffi 未装时 get() 应抛 ImportError。"""
from anti_block_utils import TLSFingerprintClient
client = TLSFingerprintClient()
# 模拟未安装:直接替换内部 _impl 为 None
with patch.object(client, "_impl", None), \
patch.object(client, "_available", False):
with pytest.raises(ImportError):
client.get("https://example.com")
class TestDomainHealthTracker:
def test_new_domain_available(self, tmp_path):
from anti_block_utils import DomainHealthTracker
tracker = DomainHealthTracker(tmp_path / "health.json")
assert tracker.is_available("new.com") is True
def test_disable_after_threshold(self, tmp_path):
from anti_block_utils import DomainHealthTracker
tracker = DomainHealthTracker(
tmp_path / "health.json",
disable_threshold=3,
cooldown_seconds=60,
)
for _ in range(3):
tracker.record_failure("bad.com", reason="403")
# 连续失败 3 次,应禁用
assert tracker.is_available("bad.com") is False
def test_recovery_after_success(self, tmp_path):
from anti_block_utils import DomainHealthTracker
tracker = DomainHealthTracker(
tmp_path / "health.json",
disable_threshold=3,
cooldown_seconds=60,
)
for _ in range(3):
tracker.record_failure("x.com", reason="err")
assert tracker.is_available("x.com") is False
tracker.record_success("x.com")
assert tracker.is_available("x.com") is True
def test_status_report(self, tmp_path):
from anti_block_utils import DomainHealthTracker
tracker = DomainHealthTracker(
tmp_path / "health.json", disable_threshold=2,
)
tracker.record_success("good.com")
tracker.record_failure("bad.com")
tracker.record_failure("bad.com")
report = tracker.status()
assert "good.com" in report["domains"]
assert "bad.com" in report["domains"]
# ============================================================================
# 集成测试:fetch_with_fallback + akshare
# ============================================================================
class TestIntegrationAkshareFallback:
def test_cls_fallback_when_module_returns_none(self):
"""当 cls_scraper 不可用时,akshare 应作为降级源。"""
from akshare_fallback import fetch_cls_hot_articles
# patch cls_scraper.get_hot_articles 抛异常
with patch("scripts.cls_scraper.get_hot_articles",
return_value=None, create=True):
result = fetch_cls_hot_articles(limit=5)
# 即使 patch 失败降级,结果也应是 list(空或 akshare 返回)
assert isinstance(result, list)
if __name__ == "__main__":
pytest.main([__file__, "-v"])
+404
View File
@@ -0,0 +1,404 @@
# -*- coding: utf-8 -*-
"""v6.0.0 模块测试:脱敏回归 / 解析智能 / 浏览器新行为 / HTML·PDF 导出 / zip 增强。
全部离线 mock,无网络请求。
"""
import sys
import json
import shutil
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.dont_write_bytecode = True
import unittest
SKILL_DIR = Path(__file__).resolve().parent.parent
# 官方媒体 / 政府实体(脱敏后应全项目零命中)
FORBIDDEN_TERMS = [
"gov.cn", "人民日报", "新华社", "央视财经", "参考消息", "光明日报",
"新华网财经", "中国新闻网财经",
]
GOV_ENTITY_TERMS = ["国家金融监督管理总局", "中国人民银行", "中国证券监督管理委员会"]
class TestSanitization(unittest.TestCase):
"""脱敏回归:代码与数据文件零残留。"""
def _scan(self, patterns, files):
hits = []
for p in files:
try:
text = p.read_text(encoding="utf-8", errors="replace")
except Exception:
continue
for pat in patterns:
if pat in text:
hits.append((p.name, pat))
return hits
def test_no_forbidden_terms_in_py(self):
py_files = [p for p in (SKILL_DIR / "scripts").rglob("*.py")]
hits = self._scan(FORBIDDEN_TERMS, py_files)
self.assertEqual([], hits, f"scripts/ 存在禁止词: {hits}")
def test_no_forbidden_terms_in_json(self):
json_files = list((SKILL_DIR / "data").glob("*.json"))
hits = self._scan(FORBIDDEN_TERMS, json_files)
self.assertEqual([], hits, f"data/ 存在禁止词: {hits}")
def test_no_gov_entity_in_registry(self):
reg = json.loads((SKILL_DIR / "data" / "institution_registry.json")
.read_text(encoding="utf-8"))
src = json.dumps(reg, ensure_ascii=False)
for term in GOV_ENTITY_TERMS:
self.assertNotIn(term, src, f"机构注册表含 {term}")
def test_sources_no_official_media(self):
ss = json.loads((SKILL_DIR / "data" / "sentiment_sources.json")
.read_text(encoding="utf-8"))
names = {s.get("name", "") for cat in ss
if isinstance(ss[cat], list)
for s in ss[cat] if isinstance(s, dict)}
forbidden = {"人民日报", "新华社", "央视财经", "经济日报", "参考消息",
"新华网财经", "中国新闻网财经", "光明日报经济", "中国财经报",
"中国证券报", "上海证券报", "证券时报", "证券日报", "金融时报"}
self.assertEqual(set(), names & forbidden,
f"媒体源仍含官媒: {names & forbidden}")
def test_targets_no_government(self):
tg = json.loads((SKILL_DIR / "data" / "sentiment_targets.json")
.read_text(encoding="utf-8"))
self.assertNotIn("local_government", tg, "目标库仍含 local_government")
def test_regulatory_scraper_no_gov(self):
src = (SKILL_DIR / "scripts" / "regulatory_scraper.py").read_text(encoding="utf-8")
self.assertNotIn("gov.cn", src)
self.assertNotIn("cbirc.gov.cn", src)
self.assertNotIn("nfra.gov.cn", src)
def test_meta_version_is_700(self):
ss = json.loads((SKILL_DIR / "data" / "sentiment_sources.json")
.read_text(encoding="utf-8"))
self.assertEqual("7.0.0", ss["_meta"]["version"])
tg = json.loads((SKILL_DIR / "data" / "sentiment_targets.json")
.read_text(encoding="utf-8"))
self.assertEqual("7.0.0", tg["_meta"]["version"])
def test_skill_version_is_700(self):
skill = (SKILL_DIR / "SKILL.md").read_text(encoding="utf-8")
# v7.2.0 起版本断言由 test_meta_sync / test_v720 接管,此处跟随最新版本
self.assertIn("version: 7.7.0", skill)
class TestParsingSmart(unittest.TestCase):
"""解析智能:正文抽取 / JSON-LD 文章类型。"""
def test_extract_main_content(self):
from scripts.web_parser import extract_main_content
html = (
"<html><head><title>测试标题</title></head><body>"
"<nav>导航菜单</nav>"
"<article><p>这是正文第一段,包含足够长度的金融分析内容,用于测试正文抽取算法,"
"涵盖了市场走势、公司基本面与行业竞争格局等多个维度。"
"<a href='http://x'>链接</a></p>"
"<p>这是正文第二段,继续讨论投资策略与风险管理建议。</p></article>"
"<footer>版权信息</footer></body></html>"
)
r = extract_main_content(html)
self.assertIn("这是正文第一段", r["content"])
self.assertIn("投资策略", r["content"])
self.assertEqual("测试标题", r["title"])
self.assertGreater(r["text_len"], 60)
def test_extract_article_from_jsonld(self):
from scripts.web_parser import extract_product_from_jsonld
ld = [{
"@type": "NewsArticle",
"headline": "某公司发布半年报",
"datePublished": "2026-08-01T10:00:00+08:00",
"author": {"name": "分析师甲"},
"image": {"url": "https://img.example.com/a.png"},
"articleBody": "正文内容……",
}]
r = extract_product_from_jsonld(ld)
self.assertEqual("某公司发布半年报", r.get("article_title"))
self.assertEqual("分析师甲", r.get("article_author"))
self.assertEqual("2026-08-01T10:00:00", r.get("article_date"))
def test_selector_cache_confidence_decay(self):
"""连续失败 ≥3 次的缓存选择器应被淘汰。"""
from scripts.web_parser import AdaptiveSelectorMatcher
class FakePage:
"""按选择器名返回结果:good 命中,其他为空。"""
def __init__(self, good_sel):
self.good_sel = good_sel
def css_first(self, sel):
if sel == self.good_sel:
return object()
return None
class AllFailPage:
def css_first(self, sel):
return None
# 场景 1:bad 选择器持续失败 → 计数累积,flush 时淘汰
m = AdaptiveSelectorMatcher("decaytest.example",
{"title": ["bad1", "bad2", "good"]})
fail_page = AllFailPage()
for _ in range(3):
m.css_first(fail_page, "title")
self.assertEqual(3, m._failures["title"].get("bad1", 0))
self.assertEqual(3, m._failures["title"].get("bad2", 0))
cache_file = SKILL_DIR / "data" / "selector_cache" / "decaytest_example.json"
if cache_file.exists():
cache_file.unlink()
try:
# 无任何成功 → 不写缓存(避免缓存污染)
m.flush()
self.assertFalse(cache_file.exists(),
"全部失败时不应写入缓存")
# 场景 2:good 成功 + bad 已失败 ≥3 → flush 仅保留 good
m2 = AdaptiveSelectorMatcher("decaytest.example",
{"title": ["bad1", "bad2", "good"]})
ok_page = FakePage(good_sel="good")
for _ in range(3):
m2.css_first(ok_page, "title")
m2.css_first(fail_page, "title") # 坏选择器继续失败
self.assertEqual("good", m2._successful["title"])
m2.flush()
self.assertTrue(cache_file.exists())
data = json.loads(cache_file.read_text(encoding="utf-8"))
sels = data.get("selectors", {}).get("title", [])
self.assertNotIn("bad1", sels)
self.assertNotIn("bad2", sels)
self.assertIn("good", sels)
finally:
if cache_file.exists():
cache_file.unlink()
class TestBrowserV600(unittest.TestCase):
"""浏览器 v6.0.0 新行为(离线断言,无需 Playwright)。"""
def test_scroll_modes_defined(self):
from scripts.browser_scraper import BrowserScraper, PLAYWRIGHT_AVAILABLE
self.assertTrue(hasattr(BrowserScraper, "SCROLL_MODES"))
self.assertEqual(
{"fast_browse", "slow_read", "segmented", "rewind"},
set(BrowserScraper.SCROLL_MODES))
def test_captcha_signs_defined(self):
from scripts.browser_scraper import BrowserScraper
signs = BrowserScraper.CAPTCHA_TEXT_SIGNS
self.assertIn("人机验证", signs)
self.assertIn("captcha", signs)
def test_humanlike_fetch_new_params(self):
import inspect
from scripts.browser_scraper import BrowserScraper
sig = inspect.signature(BrowserScraper.humanlike_fetch)
for p in ["think_time", "hover", "tab_switch", "captcha_handoff", "include_iframes"]:
self.assertIn(p, sig.parameters, f"humanlike_fetch 缺参数 {p}")
def test_fetch_new_params(self):
import inspect
from scripts.browser_scraper import BrowserScraper
sig = inspect.signature(BrowserScraper.fetch)
for p in ["captcha_handoff", "include_iframes"]:
self.assertIn(p, sig.parameters, f"fetch 缺参数 {p}")
def test_detect_captcha_with_mock_page(self):
"""验证码检测应截图并返回命中特征(mock page,真实尺寸截图)。"""
from scripts.browser_scraper import BrowserScraper
bs = BrowserScraper.__new__(BrowserScraper)
class FakePage:
def text_content(self, sel):
return "请输入验证码完成安全验证,请稍后再试"
def screenshot(self, path):
Path(path).parent.mkdir(parents=True, exist_ok=True)
# 真实截图 ≥100B(v7.0.0 起空截图会被清理,模拟真实尺寸)
Path(path).write_bytes(b"f" * 150)
shot_dir = SKILL_DIR / "data" / "screenshots"
try:
cap = bs._detect_captcha(FakePage(), url="https://www.example.com/x")
self.assertIsNotNone(cap)
self.assertIn(cap["captcha"], BrowserScraper.CAPTCHA_TEXT_SIGNS)
self.assertTrue(cap["screenshot"])
self.assertGreater(Path(cap["screenshot"]).stat().st_size, 100)
finally:
shutil.rmtree(shot_dir, ignore_errors=True) # 不留测试产物
def test_storage_state_paths(self):
from scripts.browser_scraper import BROWSER_STATE_FILE
self.assertTrue(str(BROWSER_STATE_FILE).endswith("state.json"))
self.assertIn("browser_state", str(BROWSER_STATE_FILE))
class TestHtmlExporter(unittest.TestCase):
"""HtmlExporter:网页版报告渲染与落盘。"""
def setUp(self):
self.tmp = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def _sample_data(self):
class Broker:
rating = "买入"
title = "深度研究报告"
publish_date = "2026-08-01"
broker_name = "某券商"
analyst = "分析师甲"
target_price = 12.5
url = "https://www.example.com/research"
class Announcement:
title = "2026年半年度报告"
publish_date = "2026-08-10"
announcement_type = "定期报告"
url = "https://www.example.com/ann"
return {
"summary": {"stock_name": "示例股份", "periodic_count": 2,
"broker_count": 1, "announcement_count": 1,
"has_buy_rating": True},
"periodic_reports": [],
"broker_reports": [Broker()],
"announcements": [Announcement()],
}
def test_render_html_contains_sections(self):
from scripts.report_exporter import HtmlExporter
html = HtmlExporter().render_html(self._sample_data(), "600000")
self.assertIn("示例股份", html)
self.assertIn("报告概览", html)
self.assertIn("券商研报", html)
self.assertIn("评级分布", html)
self.assertIn("某券商", html)
self.assertIn("https://www.example.com/ann", html)
self.assertIn("<style>", html)
def test_export_writes_file(self):
from scripts.report_exporter import HtmlExporter
out = str(Path(self.tmp) / "test_report.html")
path = HtmlExporter().export_comprehensive_report(self._sample_data(), "600000", out)
self.assertTrue(Path(path).exists())
self.assertIn("<!DOCTYPE html>", Path(path).read_text(encoding="utf-8"))
class TestPdfExporterFallback(unittest.TestCase):
"""PDFExporter:无 Playwright 时 fallback 返回 HTML 路径(不崩溃)。"""
def setUp(self):
self.tmp = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_fallback_returns_html_path(self):
from scripts.report_exporter import PDFExporter
ex = PDFExporter()
out = str(Path(self.tmp) / "r.pdf")
data = {
"summary": {"stock_name": "测试"},
"periodic_reports": [], "broker_reports": [], "announcements": [],
}
result = ex.export_comprehensive_report(data, "T0001", out)
# 环境无 Playwright 时返回 HTML;有 Playwright 但渲染失败也返回 HTML
self.assertTrue(result.endswith(".html") or result.endswith(".pdf"))
if result.endswith(".html"):
self.assertTrue(Path(result).exists())
class TestCrawlPackagerV600(unittest.TestCase):
"""zip v6.0.0:进度回调 / 增量去重 / metadata hashes。"""
def setUp(self):
self.tmp = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_progress_callback(self):
from scripts.crawl_packager import CrawlPackager
items = [{"name": "A", "content": "内容A", "category": "银行"},
{"name": "B", "content": "内容B", "category": "基金"}]
calls = []
packager = CrawlPackager(output_dir=self.tmp)
path = packager.package(
items, zip_name="prog_test",
progress_callback=lambda d, t, n: calls.append((d, t, n)))
self.assertTrue(Path(path).exists())
self.assertEqual(2, len(calls))
self.assertEqual((2, 2), (calls[-1][0], calls[-1][1]))
def test_metadata_has_hashes(self):
from scripts.crawl_packager import CrawlPackager
items = [{"name": "A", "content": "唯一内容XYZ", "category": "银行"}]
packager = CrawlPackager(output_dir=self.tmp)
path = packager.package(items, zip_name="hash_test")
import zipfile
with zipfile.ZipFile(path) as zf:
meta = json.loads(zf.read("metadata.json").decode("utf-8"))
self.assertIn("item_hashes", meta)
self.assertEqual(1, len(meta["item_hashes"]))
self.assertIn("hash", meta["item_hashes"][0])
self.assertEqual(32, len(meta["item_hashes"][0]["hash"]))
def test_incremental_skips_duplicates(self):
from scripts.crawl_packager import CrawlPackager
items = [{"name": "A", "content": "相同内容", "category": "银行"},
{"name": "B", "content": "相同内容", "category": "基金"},
{"name": "C", "content": "新内容", "category": "基金"}]
packager = CrawlPackager(output_dir=self.tmp)
first = packager.package(items[:2], zip_name="inc_first")
# 增量:C 是新内容,A/B 应被跳过
path, skipped = packager.package_incremental(
items, previous_zip=first, zip_name="inc_second")
self.assertEqual(2, skipped)
self.assertTrue(Path(path).exists())
import zipfile
with zipfile.ZipFile(path) as zf:
names = zf.namelist()
self.assertTrue(any("新内容" in "" and "C" in n for n in names)
or any("C" in n for n in names))
def test_failed_items_written(self):
"""package_batch_crawl 失败项应写入包内 failed.json(mock 爬取器)。"""
from scripts.crawl_packager import CrawlPackager
import sys
class FakeCrawler:
def crawl_by_names(self, inst_list):
return [{"name": "好机构", "content": "正常内容", "success": True},
{"name": "坏机构", "content": "", "success": False}]
sys.modules["batch_institution_crawler"] = type(
"M", (), {"BatchInstitutionCrawler": lambda *a, **k: FakeCrawler()})()
try:
packager = CrawlPackager(output_dir=self.tmp)
path = packager.package_batch_crawl(names="好机构,坏机构", zip_name="fail_test")
finally:
sys.modules.pop("batch_institution_crawler", None)
self.assertTrue(Path(path).exists())
import zipfile
with zipfile.ZipFile(path) as zf:
names = zf.namelist()
self.assertTrue(any("failed" in n for n in names),
f"包内应含失败清单, 实际: {names}")
if __name__ == "__main__":
unittest.main()
+284
View File
@@ -0,0 +1,284 @@
# -*- coding: utf-8 -*-
"""v7.0.0 模块测试:网页操作深度增强 / API 挖掘 / 名单扩充 / 官网补全 / 宏观接口。
全部离线 mock(不依赖 Playwright 浏览器实例与真实网络),Playwright 未装
或不可用时相关用例自动跳过。
"""
import json
import shutil
import sys
import tempfile
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.dont_write_bytecode = True
SKILL_DIR = Path(__file__).resolve().parent.parent
DATA_DIR = SKILL_DIR / "data"
# ═══════════════ 一、browser_pro 纯逻辑(离线可测) ═══════════════
class TestBrowserProCore(unittest.TestCase):
"""宏参数替换 / 分页识别 / API 注册表去重。"""
def test_substitute_recursive(self):
from scripts.browser_pro import _substitute
sub = _substitute({"a": "{{x}}", "b": ["{{x}}", "k{{y}}"], "c": 1},
{"x": 42, "y": "v"})
self.assertEqual(sub["a"], 42)
self.assertEqual(sub["b"][0], 42)
self.assertEqual(sub["b"][1], "kv")
self.assertEqual(sub["c"], 1)
# 未知变量保持原样
self.assertEqual(_substitute("{{z}}", {}), "{{z}}")
def test_detect_pagination(self):
from scripts.browser_pro import _detect_pagination
entries = [
{"url": "https://a.com/api?pn=1&size=20", "ts": 1},
{"url": "https://a.com/api?pn=2&size=20", "ts": 2},
{"url": "https://a.com/api?pn=3&size=20", "ts": 3},
]
pg = _detect_pagination(entries)
self.assertEqual(len(pg), 1)
self.assertEqual(pg[0]["pagination_param"], "pn")
self.assertEqual(pg[0]["step"], 1)
def test_detect_pagination_non_numeric_ignored(self):
from scripts.browser_pro import _detect_pagination
entries = [
{"url": "https://a.com/api?k=aa&x=1", "ts": 1},
{"url": "https://a.com/api?k=bb&x=2", "ts": 2},
]
self.assertEqual(_detect_pagination(entries), [])
def test_api_registry_dedup_and_search(self):
from scripts.browser_pro import ApiRegistry
with tempfile.TemporaryDirectory() as td:
path = Path(td) / "api_registry.json"
reg = ApiRegistry(path)
ep = {"url": "https://a.com/api?pn=1", "method": "GET",
"sample_response": "{}", "discovered_at": "now"}
self.assertTrue(reg.add(dict(ep)))
self.assertFalse(reg.add(dict(ep))) # 同端点去重
self.assertTrue(reg.add({**ep, "url": "https://b.com/x?y=1"}))
reg.save()
reg2 = ApiRegistry(path) # 重读持久化
self.assertEqual(len(reg2.search()), 2)
self.assertEqual(len(reg2.search(domain="a.com")), 1)
self.assertEqual(reg2._doc["endpoints"][0]["hit_count"], 2)
def test_truncate(self):
from scripts.browser_pro import _truncate
s = _truncate({"k": "x" * 5000})
self.assertLess(len(s), 2100)
self.assertTrue(s.endswith("…[截断]"))
class TestMacroPlayer(unittest.TestCase):
"""宏回放离线部分:加载/保存/列表 + 缺失浏览器时优雅报错。"""
def test_macro_io(self):
from scripts.browser_pro import MacroPlayer
with tempfile.TemporaryDirectory() as td:
macro = {"name": "demo", "steps": [{"action": "goto", "url": "{{u}}"}]}
path = MacroPlayer.save_macro(macro, "demo_macro")
loaded = MacroPlayer.load_macro(path.name)
self.assertEqual(loaded["name"], "demo")
self.assertEqual(path.name, "demo_macro.json")
def test_play_unknown_action_errors(self):
# 真实 BrowserScraper(Chromium 已装,不开页面不联网):未知动作应报错
from scripts.browser_scraper import BrowserScraper
from scripts.browser_pro import MacroPlayer
with BrowserScraper(headless=True) as bs:
result = MacroPlayer(scraper=bs).play(
{"steps": [{"action": "no_such_action"}]})
self.assertFalse(result["ok"])
self.assertIn("未知宏动作", result["error"])
class TestUrlCompleter(unittest.TestCase):
"""官网补全的候选过滤(聚合域/gov.cn 绝不入库)。"""
def test_domain_ok(self):
from scripts.url_completer import _domain_ok
self.assertTrue(_domain_ok("https://www.icbc.com.cn/"))
self.assertTrue(_domain_ok("https://yafco.com/about/"))
self.assertFalse(_domain_ok("https://www.baidu.com/s?wd=x"))
self.assertFalse(_domain_ok("https://gs.nfra.gov.cn/")) # 脱敏红线
self.assertFalse(_domain_ok("https://www.tianyancha.com/company/x"))
self.assertFalse(_domain_ok("https://www.eastmoney.com/"))
def test_normalize(self):
from scripts.url_completer import _normalize
self.assertEqual(_normalize("http://www.abc.com/"), "https://www.abc.com")
self.assertEqual(_normalize("www.abc.com"), "https://www.abc.com")
def test_is_homepage(self):
from scripts.url_completer import _is_homepage
self.assertTrue(_is_homepage("https://a.com/"))
self.assertTrue(_is_homepage("https://a.com/index.html"))
self.assertFalse(_is_homepage("https://a.com/about"))
def test_is_acceptable_url(self):
from scripts.url_completer import _is_acceptable_url
self.assertTrue(_is_acceptable_url("https://a.com/"))
self.assertTrue(_is_acceptable_url("https://a.com/cn/"))
self.assertFalse(_is_acceptable_url("https://a.com/article/12345"))
self.assertFalse(_is_acceptable_url("https://a.com/newsDetail_forward_1"))
self.assertFalse(_is_acceptable_url("https://a.com/p/abc123"))
self.assertFalse(_is_acceptable_url("https://a.com/x/y/z")) # 深路径
# ═══════════════ 二、名单扩充(离线,用小样本 curated 目录) ═══════════════
class TestInstitutionExpander(unittest.TestCase):
"""normalize / 合并去重 / 类型名单重写 / 舆情计数同步。"""
def test_normalize_name(self):
from scripts.institution_expander import normalize_name
self.assertEqual(normalize_name("易方达基金管理有限公司"), "易方达基金管理")
self.assertEqual(normalize_name("中信证券股份有限公司"), "中信证券")
self.assertEqual(normalize_name("中国(上海)自贸区银行"), "中国(上海)自贸区银行")
def _build_registry(self, tmp):
rows = [
[1, "华夏基金", "HX", "基金管理公司", "公开信息", "2026-01-01", "", "curated"],
[2, "中信证券", "CITIC", "证券公司", "公开信息", "2026-01-01", "", "curated"],
]
doc = {"_f": "c", "c": ["id", "name", "code", "type", "data_source",
"update_time", "website", "url_source"], "d": rows}
reg = Path(tmp) / "institution_registry.json"
reg.write_text(json.dumps(doc, ensure_ascii=False), encoding="utf-8")
return reg
def test_merge_dedup_and_sync(self):
import scripts.institution_expander as exp
orig_live = exp.LIVE_SOURCES
exp.LIVE_SOURCES = {} # 测试不联网,禁用 live 源
try:
with tempfile.TemporaryDirectory() as td:
tmp = Path(td)
exp.DATA_DIR = tmp
exp.REGISTRY_FILE = self._build_registry(tmp)
exp.CURATED_DIR = tmp / "curated"
exp.CURATED_DIR.mkdir()
(exp.CURATED_DIR / "fund_company.json").write_text(
json.dumps(["华夏基金", "易方达基金", "广发基金"]),
encoding="utf-8")
(exp.CURATED_DIR / "private_bank.json").write_text(
json.dumps(["微众银行", "网商银行"]), encoding="utf-8")
targets = {"fund_company": {"label": "基金管理公司", "count": 1,
"source_registry": "x"},
"_meta": {"version": "6.0.0", "updated_at": ""}}
(tmp / "sentiment_targets.json").write_text(
json.dumps(targets, ensure_ascii=False), encoding="utf-8")
report = exp.run(dry_run=False)
self.assertEqual(report["fund_company"]["added"], 2) # 华夏去重
self.assertEqual(report["fund_company"]["total"], 3)
self.assertEqual(report["private_bank"]["total"], 2)
doc = json.loads(exp.REGISTRY_FILE.read_text(encoding="utf-8"))
self.assertEqual(len(doc["d"]), 6) # 2 旧 + 2 基金 + 2 民营
lst = json.loads((tmp / "fund_company_list.json")
.read_text(encoding="utf-8"))
self.assertEqual(lst["count"], 3)
t2 = json.loads((tmp / "sentiment_targets.json")
.read_text(encoding="utf-8"))
self.assertEqual(t2["fund_company"]["count"], 3)
self.assertEqual(t2["_meta"]["version"], "7.0.0")
finally:
exp.LIVE_SOURCES = orig_live
# ═══════════════ 三、爬取增强:gzip 自动解压 / 宏观指标 ═══════════════
class TestHttpUtilsDecompress(unittest.TestCase):
"""v7.0.0 gzip/deflate 响应自动解压。"""
def _gzip_bytes(self, text: str):
import gzip
return gzip.compress(text.encode("utf-8"))
def test_gzip_via_header(self):
from scripts.http_utils import StdlibResponse
data = self._gzip_bytes('{"ok": true}')
resp = StdlibResponse("https://a.com", 200, {"Content-Encoding": "gzip"},
data)
self.assertEqual(resp.json(), {"ok": True})
def test_gzip_via_magic_bytes(self):
from scripts.http_utils import StdlibResponse
data = self._gzip_bytes('{"magic": 1}')
resp = StdlibResponse("https://a.com", 200, {}, data) # 无头也解
self.assertEqual(resp.json(), {"magic": 1})
def test_plain_passthrough(self):
from scripts.http_utils import StdlibResponse
resp = StdlibResponse("https://a.com", 200, {}, b'{"plain": 1}')
self.assertEqual(resp.json(), {"plain": 1})
def test_corrupt_gzip_falls_back(self):
from scripts.http_utils import StdlibResponse
resp = StdlibResponse("https://a.com", 200, {"Content-Encoding": "gzip"},
b"\x1f\x8b not real gzip")
self.assertIsInstance(resp.content, bytes)
class TestMacroIndicators(unittest.TestCase):
"""宏观指标映射(离线:字段映射 + 入口分派,不真发请求)。"""
def test_macro_reports_registry(self):
from scripts.market_data_scraper import MACRO_REPORTS
for ind in ("cpi", "ppi", "pmi", "gdp", "m2"):
self.assertIn(ind, MACRO_REPORTS)
def test_unknown_indicator_returns_empty(self):
from scripts.market_data_scraper import get_macro_indicator
self.assertEqual(get_macro_indicator("nope"), [])
def test_get_market_data_dispatch(self):
from scripts.market_data_scraper import get_market_data
# 未知类型返回 error dict(不抛异常)
r = get_market_data("macro_xyz")
self.assertIsInstance(r, dict)
self.assertIn("error", r)
# ═══════════════ 四、脱敏回归:v7 新增文件零 gov.cn/官媒 ═══════════════
class TestV700Sanitization(unittest.TestCase):
"""v7.0.0 新增数据/代码文件不含 gov.cn 域名与官媒词。"""
FORBIDDEN = ["gov.cn", "人民日报", "新华社", "央视财经", "光明日报",
"中国新闻网", "新华网", "参考消息"]
def test_curated_data_clean(self):
curated = DATA_DIR / "curated"
if not curated.exists():
self.skipTest("curated 目录不存在")
for f in curated.glob("*.json"):
text = f.read_text(encoding="utf-8")
for term in self.FORBIDDEN:
self.assertNotIn(term, text, f"{f.name} 含 {term}")
def test_new_scripts_clean(self):
for name in ("browser_pro.py", "institution_expander.py",
"url_completer.py"):
text = (SKILL_DIR / "scripts" / name).read_text(encoding="utf-8")
for term in self.FORBIDDEN:
self.assertNotIn(term, text, f"{name} 含 {term}")
def test_listed_companies_markets(self):
f = DATA_DIR / "listed_companies.json"
if not f.exists():
self.skipTest("listed_companies.json 未生成")
doc = json.loads(f.read_text(encoding="utf-8"))
self.assertGreater(doc["meta"]["total_count"], 4000)
self.assertIn("BJ", doc["meta"]["markets"])
if __name__ == "__main__":
unittest.main()
+130
View File
@@ -0,0 +1,130 @@
# -*- coding: utf-8 -*-
"""v7.1.0 定期报告分析解读引擎测试(全离线 mock 数据)。"""
import json
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.dont_write_bytecode = True
from scripts.report_interpreter import (
ReportInterpreter, interpret_data, normalize_period, _band, _f,
)
# 高增长优质公司(模拟):茅台式
GOOD_PERIODS = [
{"REPORTDATE": "2026-06-30 00:00:00", "SECURITY_NAME_ABBR": "示例股份",
"TOTAL_OPERATE_INCOME": 92_278_000_000.0, "PARENT_NETPROFIT": 44_517_000_000.0,
"BASIC_EPS": 35.57, "WEIGHTAVG_ROE": 16.8, "XSMLL": 89.6,
"YSTZ": 12.3, "SJLTZ": 18.5, "YSHZ": -5.0, "SJLHZ": -8.0,
"MGJYXJJE": 56.5, "BPS": 200.99},
{"REPORTDATE": "2026-03-31 00:00:00", "SECURITY_NAME_ABBR": "示例股份",
"TOTAL_OPERATE_INCOME": 40_000_000_000.0, "PARENT_NETPROFIT": 20_000_000_000.0,
"BASIC_EPS": 16.0, "WEIGHTAVG_ROE": 7.5, "XSMLL": 88.0,
"YSTZ": 9.0, "SJLTZ": 15.0, "MGJYXJJE": 22.0, "BPS": 190.0},
]
# 承压公司(模拟):营收净利双降
BAD_PERIODS = [
{"REPORTDATE": "2026-06-30 00:00:00", "SECURITY_NAME_ABBR": "示例承压",
"TOTAL_OPERATE_INCOME": 5_000_000_000.0, "PARENT_NETPROFIT": -300_000_000.0,
"BASIC_EPS": -0.15, "WEIGHTAVG_ROE": -2.5, "XSMLL": 15.0,
"YSTZ": -22.5, "SJLTZ": -45.0, "MGJYXJJE": -0.8, "BPS": 1.2},
{"REPORTDATE": "2026-03-31 00:00:00", "SECURITY_NAME_ABBR": "示例承压",
"TOTAL_OPERATE_INCOME": 2_800_000_000.0, "PARENT_NETPROFIT": 50_000_000.0,
"BASIC_EPS": 0.02, "WEIGHTAVG_ROE": 0.4, "XSMLL": 18.0,
"YSTZ": -10.0, "SJLTZ": -12.0, "MGJYXJJE": -0.2, "BPS": 1.3},
]
class TestReportInterpreter(unittest.TestCase):
"""解读引擎核心:归一化 / 指标 / 信号 / 评分 / 文本。"""
def test_normalize_period(self):
row = normalize_period(GOOD_PERIODS[0])
self.assertAlmostEqual(row["revenue"], 92_278_000_000.0)
self.assertAlmostEqual(row["net_profit"], 44_517_000_000.0)
self.assertAlmostEqual(row["gross_margin"], 89.6)
self.assertAlmostEqual(row["revenue_yoy"], 12.3)
self.assertEqual(row["name"], "示例股份")
self.assertIn("report_date", row)
def test_f_float_safety(self):
self.assertIsNone(_f(None))
self.assertIsNone(_f("-"))
self.assertIsNone(_f("--"))
self.assertAlmostEqual(_f("12.5%"), 12.5)
self.assertAlmostEqual(_f("1,234.5"), 1234.5)
def test_band_ranges(self):
label, _ = _band(35.0, {"30~50": ("x", "{}")} if False else {
">30": ("高增长", "{}"), "10~30": ("稳健", "{}"),
"0~10": ("低增长", "{}"), "<0": ("下滑", "{}")})
self.assertEqual(label, "高增长")
label2, _ = _band(-3.0, {
">30": ("高增长", "{}"), "10~30": ("稳健", "{}"),
"0~10": ("低增长", "{}"), "<0": ("下滑", "{}")})
self.assertEqual(label2, "下滑")
def test_interpret_good_company(self):
result = ReportInterpreter().interpret(GOOD_PERIODS)
self.assertNotIn("error", result)
self.assertAlmostEqual(result["revenue"], 92_278_000_000.0)
self.assertGreaterEqual(result["score"], 70) # 优质公司高分
self.assertIn(result["rating"], ("积极", "中性偏积极"))
# 亮点应包含增长/高毛利信号
hl = " ".join(result["highlights"])
self.assertIn("毛利率", hl)
# 环比下滑进风险
self.assertTrue(any("环比" in r for r in result["risks"]))
def test_interpret_bad_company(self):
result = ReportInterpreter().interpret(BAD_PERIODS)
self.assertNotIn("error", result)
self.assertLess(result["score"], 45) # 承压公司低分
self.assertEqual(result["rating"], "谨慎")
risk = " ".join(result["risks"])
self.assertIn("下滑", risk)
self.assertIn("现金流", risk) # 经营现金流为负
self.assertGreaterEqual(len(result["risks"]), 3)
def test_interpret_data_single_dict(self):
result = interpret_data({"营收": 1000.0, "净利润": 200.0,
"毛利率": 45.0, "ROE": 15.0,
"营收同比": 25.0, "净利同比": 35.0,
"EPS": 2.0, "每股经营现金流": 2.5})
self.assertNotIn("error", result)
self.assertGreaterEqual(result["score"], 70)
def test_interpret_empty(self):
result = ReportInterpreter().interpret([])
self.assertIn("error", result)
self.assertIn("无财务数据", result["error"])
def test_format_text_structure(self):
result = ReportInterpreter().interpret(GOOD_PERIODS)
text = result["text"]
for key in ("定期报告解读", "业绩概览", "盈利能力", "亮点信号",
"综合评分", "不构成投资建议"):
self.assertIn(key, text)
def test_missing_fields_graceful(self):
result = interpret_data({"营收": 100.0}) # 只有营收
self.assertNotIn("error", result)
self.assertIsNotNone(result.get("text"))
self.assertEqual(result["rating"], "数据不足")
class TestSanitizationV710(unittest.TestCase):
"""v7.1.0 新增文件脱敏零残留。"""
def test_report_interpreter_clean(self):
src = (Path(__file__).resolve().parent.parent
/ "scripts" / "report_interpreter.py").read_text(encoding="utf-8")
for term in ("gov.cn", "人民日报", "新华社", "央视财经"):
self.assertNotIn(term, src)
if __name__ == "__main__":
unittest.main()
+371
View File
@@ -0,0 +1,371 @@
# -*- coding: utf-8 -*-
"""v7.2.0 爬取硬化测试 — bug 修复 + 软拦截检测 + Retry-After + URL 去重器
覆盖:
1. bug 修复:空 POST 退化为 GET / download_file 保存错误页 /
raise_for_status 消息 / 熔断 sleep 持锁 / 裸域名 reset / 过期 cookie
2. 能力升级:http_get 软拦截检测接线、Retry-After 遵从、UrlDeduplicator
"""
import time
import pytest
import http_utils
from http_utils import (
StdlibSession,
StdlibResponse,
HTTPError,
download_file,
http_get,
)
from anti_block_utils import (
DomainRateLimiter,
PersistentCookieStore,
UrlDeduplicator,
self_check,
)
# ─── 测试辅助 ──────────────────────────────────────────────────────────────
class _FakeRawResp:
"""模拟 opener.open 返回的原始响应"""
def __init__(self, body=b"ok", code=200):
self._body = body
self._code = code
self.headers = [("Content-Type", "text/plain")]
def getcode(self):
return self._code
def read(self):
return self._body
def close(self):
pass
class FakeSession:
"""按调用次序返回预设响应的假 session"""
mobile = False
def __init__(self, responses):
self._responses = list(responses)
self.calls = 0
def get(self, url, headers=None, timeout=30, **kw):
self.calls += 1
return self._responses[min(self.calls - 1, len(self._responses) - 1)]
post = get
@pytest.fixture
def no_sleep(monkeypatch):
"""记录并跳过 http_utils 内的所有 sleep"""
recorded = []
monkeypatch.setattr(http_utils.time, "sleep", lambda s: recorded.append(s))
return recorded
@pytest.fixture(autouse=True)
def _reset_limiter():
"""每个用例后清理自适应限流器测试域名状态"""
yield
limiter = http_utils._get_adaptive_limiter()
for d in ("softblock-test.example", "retryafter-test.example",
"blocked-test.example", "dl-test.example"):
limiter.reset_domain(d)
def _resp(url, code=200, headers=None, body=b""):
return StdlibResponse(url, code, headers or {}, body)
# ─── 1. bug 修复:空 body POST 不再退化为 GET ─────────────────────────────
class TestPostMethodFix:
def test_empty_body_post_keeps_post_method(self):
captured = {}
s = StdlibSession()
s._opener.open = lambda req, timeout=None: (
captured.__setitem__("req", req) or _FakeRawResp()
)
s.post("http://example.com/api")
assert captured["req"].get_method() == "POST"
def test_json_body_post_keeps_post_method(self):
captured = {}
s = StdlibSession()
s._opener.open = lambda req, timeout=None: (
captured.__setitem__("req", req) or _FakeRawResp()
)
s.post("http://example.com/api", json_body={"k": 1})
assert captured["req"].get_method() == "POST"
assert captured["req"].data is not None
def test_get_stays_get(self):
captured = {}
s = StdlibSession()
s._opener.open = lambda req, timeout=None: (
captured.__setitem__("req", req) or _FakeRawResp()
)
s.get("http://example.com/page")
assert captured["req"].get_method() == "GET"
# ─── 2. bug 修复:download_file 不再保存错误页 ────────────────────────────
class TestDownloadFileFix:
def test_error_response_not_saved(self, tmp_path):
s = StdlibSession()
s.get = lambda url, headers=None, timeout=60, **kw: _resp(
url, 404, {}, b"<html>not found</html>")
result = download_file("http://dl-test.example/a.pdf",
save_dir=str(tmp_path), session=s)
assert result is None
assert not any(tmp_path.iterdir()), "404 响应不应落盘"
def test_ok_response_saved(self, tmp_path):
s = StdlibSession()
s.get = lambda url, headers=None, timeout=60, **kw: _resp(
url, 200, {}, b"%PDF-1.4 fake")
result = download_file("http://dl-test.example/a.pdf",
save_dir=str(tmp_path), session=s)
assert result is not None and result.endswith("a.pdf")
# ─── 3. bug 修复:raise_for_status 消息含状态码 ───────────────────────────
class TestRaiseForStatusFix:
def test_message_contains_code(self):
resp = _resp("http://x.example/missing", 404, {}, b"")
with pytest.raises(HTTPError) as ei:
resp.raise_for_status()
assert ei.value.code == 404
assert "404" in ei.value.reason
def test_ok_status_no_raise(self):
_resp("http://x.example/ok", 200, {}, b"fine").raise_for_status()
# ─── 4. bug 修复:熔断 sleep 不再持有全局域名锁 ───────────────────────────
class TestRateLimitLockFix:
def test_blocked_sleep_outside_lock(self, monkeypatch):
limiter = http_utils._get_adaptive_limiter()
domain = "blocked-test.example"
for _ in range(3): # 触发熔断(fail_threshold=3)
limiter.report_failure(domain, 503)
assert limiter.is_blocked(domain)
lock_state_during_sleep = []
def fake_sleep(s):
lock_state_during_sleep.append(http_utils._domain_lock.locked())
monkeypatch.setattr(http_utils.time, "sleep", fake_sleep)
http_utils.rate_limit(0, f"https://{domain}/x")
assert lock_state_during_sleep, "熔断应产生等待"
assert all(held is False for held in lock_state_during_sleep), \
"sleep 期间不应持有 _domain_lock"
# ─── 5. 升级:http_get 软拦截检测 ─────────────────────────────────────────
SOFT_BLOCK_HTML = "<html><body>请输入验证码,访问被拒绝</body></html>".encode("utf-8")
NORMAL_HTML = "<html><body>正常财经新闻内容</body></html>".encode("utf-8")
class TestSoftBlockDetection:
def test_soft_block_triggers_retry_then_success(self, no_sleep):
fs = FakeSession([
_resp("u", 200, {"Content-Type": "text/html"}, SOFT_BLOCK_HTML),
_resp("u", 200, {"Content-Type": "text/html"}, NORMAL_HTML),
])
resp = http_get("http://softblock-test.example/news",
session=fs, use_cache=False, rate_limit_delay=0)
assert resp is not None
assert "正常财经新闻" in resp.text
assert fs.calls == 2
def test_soft_block_disabled_returns_page(self, no_sleep):
fs = FakeSession([
_resp("u", 200, {"Content-Type": "text/html"}, SOFT_BLOCK_HTML),
])
resp = http_get("http://softblock-test.example/news",
session=fs, use_cache=False, rate_limit_delay=0,
detect_soft_block=False)
assert resp is not None
assert fs.calls == 1
def test_all_retries_soft_blocked_returns_none(self, no_sleep):
fs = FakeSession([
_resp("u", 200, {"Content-Type": "text/html"}, SOFT_BLOCK_HTML),
])
resp = http_get("http://softblock-test.example/news",
session=fs, use_cache=False, rate_limit_delay=0,
retries=2)
assert resp is None
assert fs.calls == 2
def test_json_body_not_flagged(self, no_sleep):
body = b'{"title": "market challenge ahead", "ok": true}'
fs = FakeSession([_resp("u", 200, {"Content-Type": "application/json"}, body)])
resp = http_get("http://softblock-test.example/api",
session=fs, use_cache=False, rate_limit_delay=0)
assert resp is not None and fs.calls == 1
def test_large_html_not_flagged(self, no_sleep):
big = (b"<html><body>" + b"x" * 9000
+ "请输入验证码".encode("utf-8") + b"</body></html>")
fs = FakeSession([_resp("u", 200, {"Content-Type": "text/html"}, big)])
resp = http_get("http://softblock-test.example/big",
session=fs, use_cache=False, rate_limit_delay=0)
assert resp is not None and fs.calls == 1
# ─── 6. 升级:Retry-After 遵从 ────────────────────────────────────────────
class TestRetryAfter:
def test_retry_after_seconds_honored(self, no_sleep):
fs = FakeSession([
_resp("u", 429, {"Retry-After": "7"}, b"slow down"),
_resp("u", 200, {}, b"ok now"),
])
resp = http_get("http://retryafter-test.example/data",
session=fs, use_cache=False, rate_limit_delay=0)
assert resp is not None and resp.text == "ok now"
assert any(abs(w - 7.0) < 0.01 for w in no_sleep), \
f"应等待 Retry-After 声明的 7s,实际 sleeps={no_sleep}"
def test_retry_after_capped(self):
resp = _resp("u", 429, {"Retry-After": "9999"}, b"")
assert http_utils._retry_after_seconds(resp) == 60.0
def test_retry_after_invalid_header(self):
resp = _resp("u", 429, {"Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT"}, b"")
assert http_utils._retry_after_seconds(resp) == 0.0
# ─── 7. bug 修复:anti_block_utils ────────────────────────────────────────
class TestAntiBlockFixes:
def test_normalize_bare_domain(self):
limiter = DomainRateLimiter()
assert limiter._normalize_domain("cls.cn") == "cls.cn"
assert limiter._normalize_domain("https://www.cls.cn/api") == "cls.cn"
assert limiter._normalize_domain("HTTP://WWW.SSE.COM.CN/x") == "com.cn"
def test_reset_bare_domain_clears_state(self):
limiter = DomainRateLimiter({"cls.cn": 0.01}, default_interval=0.01)
limiter.wait("https://www.cls.cn/x")
assert "cls.cn" in limiter._last_called
limiter.reset("cls.cn") # 裸域名传入(此前归一化为 "" 导致失效)
assert "cls.cn" not in limiter._last_called
def test_cookie_store_drops_expired(self, tmp_path):
store = PersistentCookieStore(tmp_path / "cookies.json")
now = time.time()
store.save([
{"name": "expired", "value": "1", "expires": now - 86400},
{"name": "fresh", "value": "2", "expires": now + 86400},
{"name": "session", "value": "3"},
])
names = {c["name"] for c in store.load()}
assert names == {"fresh", "session"}, "已过期 cookie 必须剔除"
def test_cookie_store_iso_expires(self, tmp_path):
store = PersistentCookieStore(tmp_path / "cookies.json")
store.save([
{"name": "past_iso", "expires": "2020-01-01T00:00:00"},
{"name": "future_iso", "expires": "2099-01-01T00:00:00"},
])
names = {c["name"] for c in store.load()}
assert names == {"future_iso"}
# ─── 8. 升级:UrlDeduplicator ─────────────────────────────────────────────
class TestUrlDeduplicator:
def test_is_new_then_seen(self):
d = UrlDeduplicator()
assert d.is_new("https://www.eastmoney.com/a") is True
assert d.is_new("https://www.eastmoney.com/a") is False
assert d.is_seen("https://www.eastmoney.com/a") is True
def test_normalize_rules(self):
n = UrlDeduplicator.normalize
assert n("https://WWW.Example.com/Path/#frag") == "https://www.example.com/Path"
assert n("http://example.com:80/x/") == "http://example.com/x"
assert n("https://example.com:443/") == "https://example.com/"
assert n("https://example.com/x?b=1&a=2") == "https://example.com/x?b=1&a=2"
def test_normalized_variants_deduped(self):
d = UrlDeduplicator()
assert d.is_new("https://Example.com/page/") is True
assert d.is_new("https://example.com/page#top") is False
def test_persistence_roundtrip(self, tmp_path):
fp = tmp_path / "seen.json"
d1 = UrlDeduplicator(fp)
d1.mark("https://www.cls.cn/detail/1")
d2 = UrlDeduplicator(fp) # 新实例从文件恢复
assert d2.is_seen("https://www.cls.cn/detail/1") is True
assert d2.is_new("https://www.cls.cn/detail/2") is True
def test_stats_by_domain(self):
d = UrlDeduplicator()
d.mark("https://www.cls.cn/a")
d.mark("https://www.cls.cn/b")
d.mark("https://www.jisilu.cn/c")
stats = d.stats()
assert stats["total"] == 3
assert stats["by_domain"]["cls.cn"] == 2
assert stats["by_domain"]["jisilu.cn"] == 1
def test_clear(self):
d = UrlDeduplicator()
d.mark("https://x.com/1")
d.clear()
assert d.stats()["total"] == 0
assert d.is_new("https://x.com/1") is True
# ─── 9. 接线与版本 ────────────────────────────────────────────────────────
class TestWiringV72:
def test_self_check_includes_deduplicator(self):
report = self_check()
assert "url_deduplicator" in report
def test_soft_block_helper_safe_on_json(self):
resp = _resp("u", 200, {"Content-Type": "application/json"},
'{"msg": "请稍后再试"}'.encode("utf-8"))
assert http_utils._is_soft_blocked(resp) is None
def test_version_is_720(self):
from pathlib import Path
init = Path(__file__).parent.parent / "scripts" / "__init__.py"
assert "__version__ = '7.7.0'" in init.read_text(encoding="utf-8")
+477
View File
@@ -0,0 +1,477 @@
# -*- coding: utf-8 -*-
"""v7.3.0 升级回归测试 — 名单完善 + 爬取增强 + 内容识别 + 汇总分析 + 语音交互
覆盖:
1. 机构名单:11 类新增精选名录落盘、CATEGORY_MAP 接线、registry ≥2300 家/43 类
2. crawl_enhancer:classify_response / SmartFetcher 三级降级 / batch 统计与去重
3. web_recognizer:表格/KV/文章条目/分页/数字抽取/页面类型判别
4. data_aggregator:去重/统计/截面/快照聚合/机构简报/Markdown 导出
5. voice_interface:播报文本压缩 / VoiceChat 假回调闭环
全部离线(fake 注入),不发网络请求。
"""
import importlib.util
import json
from pathlib import Path
import pytest
SKILL_DIR = Path(__file__).resolve().parent.parent
def _load_scripts_package():
"""以显式路径加载真实 scripts 包,避免工作区多 scripts 目录造成命名空间包冲突。"""
init_py = SKILL_DIR / "scripts" / "__init__.py"
spec = importlib.util.spec_from_file_location(
"scripts", init_py, submodule_search_locations=[str(SKILL_DIR / "scripts")])
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
from crawl_enhancer import (SmartFetcher, FetchResult, batch_smart_crawl,
classify_response, STATUS_OK, STATUS_EMPTY,
STATUS_SOFT_BLOCKED, STATUS_ERROR)
from web_recognizer import (extract_tables, extract_kv_blocks,
extract_article_items, extract_numbers_with_context,
detect_pagination, recognize_page_type,
smart_extract, strip_tags)
from data_aggregator import (normalize_title, title_similarity, dedupe_articles,
sentiment_statistics, cross_section_summary,
aggregate_snapshots, build_institution_brief,
export_markdown, export_json)
from voice_interface import VoiceChat, summarize_for_speech
DATA_DIR = SKILL_DIR / "data"
CURATED_BUNDLE = DATA_DIR / "curated.json"
# ════════════════════════ 1. 机构名单完善 ════════════════════════
NEW_CURATED = ["securities_consulting", "local_amc", "payment", "credit_rating",
"credit_service", "mutual_insurance", "pension_mgmt",
"wm_subsidiary", "financial_infra", "internet_loan", "fund_sales"]
def test_new_curated_files_exist_and_valid():
"""11 个新增精选名录均在合并文件 curated.json 中且为合法非空字符串数组。"""
assert CURATED_BUNDLE.exists(), "缺少精选名录合并文件 curated.json"
bundle = json.loads(CURATED_BUNDLE.read_text(encoding="utf-8"))
assert isinstance(bundle, dict) and bundle, "curated.json 非法"
for name in NEW_CURATED:
items = bundle.get(name)
assert isinstance(items, list) and items, f"curated.json 缺少类别 {name}"
for it in items:
assert isinstance(it, str) and it.strip(), f"{name} 含非法条目"
def test_category_map_covers_new_curated():
"""扩充引擎 CATEGORY_MAP 已接线全部新增名录。"""
from institution_expander import CATEGORY_MAP
for name in NEW_CURATED:
assert name in CATEGORY_MAP, f"CATEGORY_MAP 缺少 {name}"
type_name, list_file, source = CATEGORY_MAP[name]
assert type_name and list_file and source
def test_registry_expanded():
"""registry 总数 ≥2300 家 / ≥43 类,且含全部新增类型。"""
doc = json.loads((DATA_DIR / "institution_registry.json").read_text(encoding="utf-8"))
cols, rows = doc["c"], doc["d"]
i_type = cols.index("type")
types = {r[i_type] for r in rows}
assert len(rows) >= 2300, f"registry 仅 {len(rows)} 家"
assert len(types) >= 43, f"registry 仅 {len(types)} 类"
for t in ("地方资产管理公司", "支付机构", "信用评级机构", "征信与商查机构",
"相互保险组织", "养老金管理公司", "券商资管子公司",
"金融基础设施机构", "互联网小贷公司", "证券投资咨询机构"):
assert t in types, f"registry 缺少类型 {t}"
def test_new_list_files_synced():
"""新增类型对应的 *_list.json 已同步落盘且 count 一致。"""
from institution_expander import CATEGORY_MAP
for name in NEW_CURATED:
_, list_file, _ = CATEGORY_MAP[name]
path = DATA_DIR / list_file
assert path.exists(), f"缺少 {list_file}"
doc = json.loads(path.read_text(encoding="utf-8"))
assert doc["count"] == len(doc["institutions"])
# ════════════════════════ 2. 爬取增强 ════════════════════════════
class _FakeResp:
def __init__(self, text):
self.text = text
def test_classify_response_categories():
long_html = "<html>" + "正文内容。" * 100 + "</html>"
assert classify_response(long_html) == STATUS_OK
assert classify_response(None) == STATUS_ERROR
assert classify_response(" ") == STATUS_EMPTY
assert classify_response("请完成人机验证") == STATUS_SOFT_BLOCKED
assert classify_response('{"a": 1}') == STATUS_OK # JSON 短响应有效
assert classify_response("x" * 50) == STATUS_EMPTY # 过短非 JSON
def _fetcher_factory(pages: dict, api=None, browser_pages=None):
"""构造注入 fake 依赖的 SmartFetcher。"""
def fake_http(url, timeout=20):
body = pages.get(url)
return _FakeResp(body) if body is not None else None
calls = {"browser": []}
def fake_browser(url):
calls["browser"].append(url)
return (browser_pages or {}).get(url)
return SmartFetcher(http_fetcher=fake_http,
browser_fetcher=fake_browser,
api_lookup=lambda u: api), calls
def test_smart_fetcher_http_ok():
page = "https://a.com/news"
html = "<html>" + "新闻内容。" * 100 + "</html>"
f, calls = _fetcher_factory({page: html})
r = f.fetch(page)
assert r.ok and r.source == "http" and r.text_len == len(html)
assert calls["browser"] == []
def test_smart_fetcher_browser_fallback():
page = "https://a.com/blocked"
blocked = "请完成人机验证"
good = "<html>" + "真实内容。" * 100 + "</html>"
f, calls = _fetcher_factory({page: blocked}, browser_pages={page: good})
r = f.fetch(page)
assert r.ok and r.source == "browser"
assert calls["browser"] == [page]
def test_smart_fetcher_api_priority():
page = "https://a.com/spa"
api_url = "https://a.com/api/list?page=1"
f, calls = _fetcher_factory({page: "壳页面"},
api={"url": api_url},
browser_pages={page: None})
# api 直连返回有效 JSON
f.http_fetcher_orig = f.http_fetcher
def fake_http(url, timeout=20):
if url == api_url:
return _FakeResp('{"list": [1, 2, 3]}')
return _FakeResp("壳页面")
f.http_fetcher = fake_http
r = f.fetch(page)
assert r.ok and r.source == "api"
assert r.extra.get("api_url") == api_url
def test_smart_fetcher_all_fail():
f, _ = _fetcher_factory({})
r = f.fetch("https://a.com/none")
assert not r.ok and r.status in (STATUS_ERROR, STATUS_EMPTY)
def test_batch_smart_crawl_stats(tmp_path):
ok_page = "https://a.com/1"
html = "<html>" + "内容。" * 100 + "</html>"
f, _ = _fetcher_factory({ok_page: html})
def fake_work(url, timeout=20):
if url == ok_page:
return _FakeResp(html)
return None
f.http_fetcher = fake_work
dedup_file = str(tmp_path / "seen.json")
out = batch_smart_crawl(
[ok_page, "https://a.com/bad", ok_page], # 第 3 个为重复
concurrency=2, dedup_file=dedup_file, fetcher=f)
stats = out["stats"]
assert stats["total"] == 3
assert stats["skipped_dup"] == 1
assert stats["fetched"] == 2
assert stats["ok"] == 1
assert stats["success_rate"] == 0.5
assert stats["by_status"].get(STATUS_OK) == 1
assert "a.com" in stats["by_domain"]
# 去重文件已持久化
assert Path(dedup_file).exists()
# ════════════════════════ 3. 网页内容识别 ════════════════════════
LIST_HTML = """
<html><body>
<ul>
<li><a href="/news/1001.html">央行宣布下调存款准备金率</a>
<span class="time">2026-08-20 09:30</span></li>
<li><a href="/news/1002.html">多家银行下调存款利率引发关注</a>
<span>2026-08-19</span></li>
<li><a href="/news/1003.html">基金发行市场回暖迹象明显</a><span>昨天</span></li>
<li><a href="/news/1004.html">券商资管新规征求意见稿发布</a></li>
<li><a href="/news/1005.html">保险资金入市规模持续扩大</a></li>
<li><a href="/news/1006.html">信托行业转型方向逐渐清晰</a></li>
<li><a href="javascript:void(0)">登录</a></li>
<li><a href="/about">关于我们</a></li>
</ul>
<a href="/news?page=2">下一页</a>
<a href="/news?page=5">5</a>
</body></html>
"""
DATA_HTML = """
<html><body>
<div class="fund_info">最新净值: 1.2345 日增长率: +0.85% 基金规模: 120.5亿元</div>
<dl><dt>成立日期</dt><dd>2015-03-01</dd><dt>基金经理</dt><dd>张三</dd></dl>
<table><tr><th>年度</th><th>收益率</th></tr>
<tr><td>2024</td><td>12.5%</td></tr>
<tr><td>2025</td><td>-3.2%</td></tr></table>
</body></html>
"""
ARTICLE_HTML = "<html><body>" + (
"<p>贵州茅台2026年上半年实现营业收入819.3亿元,同比增长17.8%。"
"净利润416.96亿元,同比增长15.2%。公司表示将继续加大市场投入。</p>"
* 6) + "</body></html>"
def test_strip_tags():
assert strip_tags("<p>hello <b>world</b></p>") == "hello world"
assert strip_tags("<script>a=1</script>x") == "x"
def test_extract_tables():
tables = extract_tables(DATA_HTML)
assert len(tables) == 1
t = tables[0]
assert t["headers"] == ["年度", "收益率"]
assert t["n_rows"] == 2 and t["n_cols"] == 2
assert t["rows"][0] == ["2024", "12.5%"]
def test_extract_kv_blocks():
kv = extract_kv_blocks(DATA_HTML)
assert kv.get("成立日期") == "2015-03-01"
assert kv.get("基金经理") == "张三"
assert kv.get("最新净值") == "1.2345"
assert kv.get("基金规模") == "120.5亿元"
def test_extract_article_items():
items = extract_article_items(LIST_HTML, base_url="https://news.example.com")
titles = [i["title"] for i in items]
assert "央行宣布下调存款准备金率" in titles
assert "登录" not in titles # javascript 链接过滤
assert "关于我们" not in titles # 过短标题过滤
first = items[0]
assert first["url"].startswith("https://news.example.com/news/")
dated = [i for i in items if i.get("date")]
assert any(d["date"].startswith("2026-08-20") for d in dated)
def test_detect_pagination():
pag = detect_pagination(LIST_HTML, base_url="https://news.example.com")
assert pag["has_page_param"] is True
assert pag["max_page"] == 5
assert pag["next_url"] and "page=2" in pag["next_url"]
def test_extract_numbers_with_context():
nums = extract_numbers_with_context(ARTICLE_HTML)
raws = [n["raw"] for n in nums]
assert any("819.3" in r and "亿" in r for r in raws)
assert any("17.8" in r and "%" in r for r in raws)
for n in nums:
assert n["context"]
def test_recognize_page_type():
assert recognize_page_type(LIST_HTML, "https://news.example.com/news") == "list"
assert recognize_page_type(DATA_HTML, "https://fund.example.com/fund/123") == "data"
assert recognize_page_type(ARTICLE_HTML, "https://x.com/a/1.html") == "article"
assert recognize_page_type("", "") == "unknown"
def test_smart_extract_list_page():
out = smart_extract(LIST_HTML, url="https://news.example.com/news")
assert out["page_type"] == "list"
assert len(out["articles"]) >= 5
assert out["pagination"]["max_page"] == 5
def test_smart_extract_data_page():
out = smart_extract(DATA_HTML, url="https://fund.example.com/fund/1")
assert out["page_type"] == "data"
assert out["tables"] and out["kv"]
# ════════════════════════ 4. 数据分析汇总 ════════════════════════
def _mk_articles():
return [
{"title": "招商银行因违规被处罚", "target_name": "招商银行",
"source": "财联社", "sentiment": "negative", "sentiment_score": -20.0,
"severity": "中度舆情", "publish_time": "2026-08-20 10:00:00",
"keywords_matched": ["处罚", "违规"]},
{"title": "招商银行因违规被处罚(转发)", "target_name": "招商银行",
"source": "新浪财经", "sentiment": "negative", "sentiment_score": -18.0,
"severity": "中度舆情", "publish_time": "2026-08-20 11:00:00",
"keywords_matched": ["处罚"]},
{"title": "招商银行业绩稳健获机构增持", "target_name": "招商银行",
"source": "财联社", "sentiment": "positive", "sentiment_score": 15.0,
"severity": "低度利好", "publish_time": "2026-08-21 09:00:00",
"keywords_matched": ["增持"]},
{"title": "华夏基金新发产品受热捧", "target_name": "华夏基金",
"source": "东方财富", "sentiment": "positive", "sentiment_score": 10.0,
"severity": "低度利好", "publish_time": "2026-08-21 12:00:00",
"keywords_matched": ["新发"]},
]
def test_title_similarity_and_dedupe():
assert normalize_title("招商银行 因违规被处罚!") == "招商银行因违规被处罚"
assert title_similarity("招商银行因违规被处罚",
"招商银行因违规被处罚(转发)") > 0.85
assert title_similarity("完全不同的标题", "招商银行因违规被处罚") < 0.3
kept = dedupe_articles(_mk_articles())
assert len(kept) == 3 # 转发条目被去掉
def test_sentiment_statistics():
st = sentiment_statistics(dedupe_articles(_mk_articles()))
assert st["total"] == 3
assert st["sentiment"]["negative"] == 1
assert st["sentiment"]["positive"] == 2
assert st["by_day"]["2026-08-21"] == 2
assert ("处罚", 1) in st["hot_keywords"] # 转发条目已去重
assert st["neg_ratio"] == pytest.approx(1 / 3, abs=0.01)
def test_cross_section_summary():
rows = cross_section_summary(dedupe_articles(_mk_articles()))
cmb = next(r for r in rows if r["target_name"] == "招商银行")
assert cmb["count"] == 2 and cmb["negative"] == 1
# 负面占比高的排前面
assert rows[0]["target_name"] == "招商银行"
def test_aggregate_snapshots(tmp_path):
snap = {"snapshot_id": "s1", "created_at": "2026-08-22",
"articles": _mk_articles()}
(tmp_path / "snap1.json").write_text(
json.dumps(snap, ensure_ascii=False), encoding="utf-8")
(tmp_path / "bad.json").write_text("{not json", encoding="utf-8")
agg = aggregate_snapshots(tmp_path)
assert agg["snapshot_count"] == 1
assert agg["raw_count"] == 4
assert agg["dedup_count"] == 3
assert agg["dedup_removed"] == 1
assert agg["by_target"] and agg["statistics"]["total"] == 3
def test_build_institution_brief(tmp_path):
snap = {"snapshot_id": "s1", "created_at": "2026-08-22",
"articles": _mk_articles()}
(tmp_path / "snap1.json").write_text(
json.dumps(snap, ensure_ascii=False), encoding="utf-8")
brief = build_institution_brief("招商银行", snapshot_dir=tmp_path)
assert brief["name"] == "招商银行"
assert brief["sentiment"] and brief["sentiment"]["total"] == 2
assert brief["recent_titles"]
def test_export_markdown_and_json(tmp_path):
agg = aggregate_snapshots.__wrapped__ if hasattr(
aggregate_snapshots, "__wrapped__") else None
snap_dir = tmp_path / "snaps"
snap_dir.mkdir()
(snap_dir / "s.json").write_text(
json.dumps({"snapshot_id": "s", "articles": _mk_articles()},
ensure_ascii=False), encoding="utf-8")
agg = aggregate_snapshots(snap_dir)
md_path = tmp_path / "report.md"
md = export_markdown(agg, md_path)
assert md_path.exists()
assert "# 金融数据爬取汇总报告" in md
assert "情感分布" in md and "目标机构截面" in md
assert "招商银行" in md
json_path = export_json(agg, tmp_path / "agg.json")
assert json.loads(json_path.read_text(encoding="utf-8"))["dedup_count"] == 3
# ════════════════════════ 5. 语音交互 ════════════════════════════
def test_summarize_for_speech_strips_markdown():
reply = "## 爬取结果\n**共 32 条**\n- 负面 5 条,详见:https://x.com/a"
out = summarize_for_speech(reply)
assert "http" not in out
assert "#" not in out and "**" not in out
assert "共32条" in out or "共 32 条" in out # 中文播报文本会去空白
def test_summarize_for_speech_truncates():
reply = "。".join(f"第{i}条舆情内容比较长" for i in range(60))
out = summarize_for_speech(reply, max_chars=100)
assert len(out) <= 120
assert out.endswith("(更多内容见终端输出)")
def test_summarize_for_speech_empty():
assert summarize_for_speech("") == ""
def test_voice_chat_handle_text():
spoken = []
vc = VoiceChat(
listen=lambda timeout=8: None,
speak_fn=lambda t: spoken.append(t) or True,
chat=lambda t: {"reply": f"已处理: {t}"},
tts=True)
reply = vc.handle_text("爬取贵州茅台最近7天的舆情")
assert "已处理" in reply
assert vc.history[-1]["user"] == "爬取贵州茅台最近7天的舆情"
assert spoken, "TTS 未被调用"
def test_voice_chat_no_tts():
vc = VoiceChat(chat=lambda t: {"reply": "ok"}, tts=False)
assert vc.handle_text("你好") == "ok"
def test_voice_chat_run_with_fake_listen(monkeypatch):
"""max_turns 限制下,假 STT 输入能驱动完整循环。"""
inputs = iter(["爬一下舆情", "退出"])
spoken = []
vc = VoiceChat(
listen=lambda timeout=8: next(inputs, None),
speak_fn=lambda t: spoken.append(t) or True,
chat=lambda t: {"reply": f"回复: {t}"},
tts=True)
monkeypatch.setattr("voice_interface.stt_available", lambda: True)
vc.run(max_turns=1)
assert len(vc.history) == 1
assert spoken
def test_voice_chat_default_engine():
"""chat=None 时自动降级内置对话引擎(sentiment_chat),返回非空回复。"""
vc = VoiceChat(chat=None, tts=False)
reply = vc.handle_text("你好")
assert reply, "默认对话引擎未返回回复"
# ════════════════════════ 6. 版本一致性 ══════════════════════════
def test_init_version_is_730():
scripts = _load_scripts_package()
assert scripts.__version__ == "7.7.0"
def test_new_modules_importable_from_package():
scripts = _load_scripts_package()
for name in ("batch_smart_crawl", "smart_extract", "aggregate_snapshots",
"VoiceChat", "speak", "extract_tables"):
assert hasattr(scripts, name), f"scripts 缺少导出 {name}"
+357
View File
@@ -0,0 +1,357 @@
# -*- coding: utf-8 -*-
"""v7.5.0 升级回归测试 — 编码修复 + 下载加固 + 爬取强化 + 机构名单扩充
覆盖:
1. 编码检测:charset 归一化 / 声明编码验证 / meta charset 字节级探测 /
中文启发式 / 域名编码记忆 / GBK JSON API 兼容
2. 爬取强化:SSL 证书失败协议降级重试 / 200 空响应自动重试
3. download_file 加固:Referer 注入 / 文本转码 UTF-8 / 反爬页校验 /
GBK Content-Disposition 文件名乱码修复
4. announcement_scraper:无 requests 时标准库兜底下载 / GBK 文件名修复
5. 机构名单:6 类扩充名录落盘 / load_curated 路径修复 / registry ≥2334 家
全部离线(fake session 注入),不发网络请求。
"""
import json
import ssl
import urllib.error
import urllib.request
from pathlib import Path
from unittest.mock import patch
import pytest
import http_utils as hu
from http_utils import (StdlibResponse, StdlibSession, normalize_charset,
remember_domain_encoding, get_domain_encoding,
looks_like_chinese_binary, _detect_meta_charset_bytes,
_is_ssl_error, _scheme_downgrade, _fix_mojibake_filename,
_looks_html_magic, _is_text_download, _extract_filename,
http_get, download_file)
import announcement_scraper as ann
SKILL_DIR = Path(__file__).resolve().parent.parent
DATA_DIR = SKILL_DIR / "data"
class FakeResp:
"""鸭子类型模拟 StdlibResponse(http_get 成功分支只读这些属性)"""
def __init__(self, code=200, content=b"", headers=None, encoding="utf-8"):
self.code = code
self.content = content
self.headers = headers or {}
self._encoding = encoding
self.text = content.decode(encoding, errors="replace")
class FakeSession:
"""按调用次序逐个弹出响应/异常的假 session"""
def __init__(self, outcomes):
self.outcomes = list(outcomes)
self.calls = []
def get(self, url, headers=None, timeout=30, **kw):
self.calls.append({"url": url, "headers": dict(headers or {})})
item = self.outcomes.pop(0)
if isinstance(item, Exception):
raise item
return item
@pytest.fixture(autouse=True)
def _no_sleep():
"""全量测试不等待重试退避"""
with patch("http_utils.time.sleep"):
yield
@pytest.fixture
def _clean_hints():
saved = dict(hu.domain_encoding_hints)
yield
hu.domain_encoding_hints.clear()
hu.domain_encoding_hints.update(saved)
# ════════════════ 1. charset 归一化与编码检测 ════════════════
class TestNormalizeCharset:
def test_gb_family_unified_to_gb18030(self):
for alias in ("gb2312", "GBK", "cp936", "x-gbk", "chinese"):
assert normalize_charset(alias) == "gb18030"
def test_aliases_and_case_insensitive(self):
assert normalize_charset("UTF8") == "utf-8"
assert normalize_charset(" iso-8859-1 ") == "latin-1"
assert normalize_charset('"gbk"') == "gb18030"
def test_invalid_returns_none(self):
assert normalize_charset("not-a-charset-xxx") is None
assert normalize_charset("") is None
assert normalize_charset(None) is None
class TestDetectEncoding:
def setup_method(self):
self.s = StdlibSession()
def detect(self, data, hdrs=None, url=""):
return self.s._detect_encoding(200, hdrs or {}, data, url)
def test_bom_utf8(self):
assert self.detect(b"\xef\xbb\xbf<html></html>") == "utf-8"
def test_declared_gb2312_normalized(self):
data = "中国人民银行公告".encode("gb18030")
assert self.detect(data, {"Content-Type": "text/html; charset=gb2312"}) == "gb18030"
def test_declared_wrong_charset_not_blindly_trusted(self):
"""声称 utf-8 实为 GBK — 严格解码验证失败后启发式纠错"""
data = "某信托公司发布年度财务报告".encode("gb18030")
enc = self.detect(data, {"Content-Type": "text/html; charset=utf-8"})
assert enc == "gb18030"
assert data.decode(enc) == "某信托公司发布年度财务报告"
def test_meta_charset_bytes_level(self):
body = "基金净值公告".encode("gb18030")
data = b'<html><head><meta charset="gb2312"></head>' + body
assert self.detect(data, {}) == "gb18030"
def test_heuristic_gbk_no_declaration(self):
data = ("关于召开股东大会的通知,请各位股东准时出席。" * 3).encode("gb18030")
assert self.detect(data, {}) == "gb18030"
def test_heuristic_utf8_no_declaration(self):
data = ("关于召开股东大会的通知,请各位股东准时出席。" * 3).encode("utf-8")
assert self.detect(data, {}) == "utf-8"
def test_binary_fallback_latin1(self):
# 高位字节后跟空格(非 GBK 尾字节范围)→ 无法构成 GBK 双字节对,兜底 latin-1
data = bytes([0x80, 0x20] * 8)
assert self.detect(data, {}) == "latin-1"
@pytest.mark.usefixtures("_clean_hints")
def test_domain_memory_reuse(self):
remember_domain_encoding("bank.example.cn", "gb18030")
data = b"\xc4\xe3\xba\xc3" # 即使歧义也直接复用记忆编码
assert self.detect(data, {}, "http://bank.example.cn/list.htm") == "gb18030"
def test_remember_skips_trivial_encodings(self, _clean_hints):
remember_domain_encoding("a.example.cn", "latin-1")
remember_domain_encoding("b.example.cn", "ascii")
assert get_domain_encoding("a.example.cn") is None
assert get_domain_encoding("b.example.cn") is None
class TestChineseHeuristic:
def test_pure_ascii_is_utf8(self):
assert looks_like_chinese_binary(b"hello world 123") == "utf-8"
def test_gbk_bytes_detected(self):
data = ("招商银行 平安银行 兴业银行 民生银行 " * 5).encode("gb18030")
assert looks_like_chinese_binary(data) == "gb18030"
def test_empty_returns_none(self):
assert looks_like_chinese_binary(b"") is None
def test_meta_bytes_detect_http_equiv(self):
data = ('<meta http-equiv="Content-Type" content="text/html; charset=gbk">'
"正文").encode("gb18030")
assert _detect_meta_charset_bytes(data) == "gb18030"
class TestGBKJsonAPI:
def test_json_loads_gbk_bytes(self):
"""json.loads 对 bytes 仅支持 utf-8/16/32 — GBK API 需先解码"""
data = '{"name": "华夏基金", "code": "000001"}'.encode("gb18030")
resp = StdlibResponse("http://a.cn/api", 200, {}, data, encoding="gb18030")
assert resp.json() == {"name": "华夏基金", "code": "000001"}
def test_json_utf8_unchanged(self):
resp = StdlibResponse("http://a.cn/api", 200, {},
b'{"ok": true}', encoding="utf-8")
assert resp.json() == {"ok": True}
# ════════════════ 2. 爬取强化:SSL 降级 + 空响应重试 ════════════════
class TestSSLHelpers:
def test_is_ssl_error_variants(self):
assert _is_ssl_error(ssl.SSLError(1, "[SSL] certificate verify failed"))
assert _is_ssl_error(urllib.error.URLError(ssl.SSLError(1, "cert")))
assert _is_ssl_error(urllib.error.URLError("[SSL: CERTIFICATE_VERIFY_FAILED]"))
assert not _is_ssl_error(urllib.error.URLError("timed out"))
assert not _is_ssl_error(ValueError("not network"))
def test_scheme_downgrade(self):
assert _scheme_downgrade("https://a.cn/x") == "http://a.cn/x"
assert _scheme_downgrade("http://a.cn/x") is None
class TestHttpGetHardening:
def test_ssl_error_downgrades_to_http_once(self):
ok = FakeResp(content=b"<html>ok</html>")
fs = FakeSession([urllib.error.URLError(ssl.SSLError(1, "cert verify")), ok])
resp = http_get("https://bank.example.cn/page", session=fs,
retries=3, use_cache=False)
assert resp is ok
assert fs.calls[0]["url"].startswith("https://")
assert fs.calls[1]["url"] == "http://bank.example.cn/page"
def test_non_ssl_error_no_downgrade(self):
fs = FakeSession([urllib.error.URLError("timed out")] * 3)
resp = http_get("https://slow.example.cn/", session=fs,
retries=3, use_cache=False)
assert resp is None
assert all(c["url"].startswith("https://") for c in fs.calls)
def test_empty_body_retried_then_success(self):
fs = FakeSession([FakeResp(content=b""), FakeResp(content=b"real body")])
resp = http_get("http://empty.example.cn/", session=fs,
retries=3, use_cache=False)
assert resp.content == b"real body"
assert len(fs.calls) == 2
def test_retry_empty_disabled(self):
fs = FakeSession([FakeResp(content=b"")])
resp = http_get("http://empty.example.cn/", session=fs,
retries=3, use_cache=False, retry_empty=False)
assert resp.content == b""
assert len(fs.calls) == 1
def test_success_remembers_domain_encoding(self, _clean_hints):
fs = FakeSession([FakeResp(content=b"<html>hi</html>", encoding="gb18030")])
http_get("http://gbk.example.cn/", session=fs, retries=1, use_cache=False)
assert get_domain_encoding("gbk.example.cn") == "gb18030"
# ════════════════ 3. download_file 加固 ════════════════
class TestDownloadHelpers:
def test_html_magic(self):
assert _looks_html_magic(b"<!DOCTYPE html><html>")
assert _looks_html_magic(b" <html>")
assert not _looks_html_magic(b"%PDF-1.4")
assert not _looks_html_magic(b"")
def test_is_text_download(self):
r1 = FakeResp(headers={"Content-Type": "text/html; charset=gb2312"})
assert _is_text_download("x.bin", r1)
r2 = FakeResp(headers={"Content-Type": "application/pdf"})
assert _is_text_download("page.htm", r2)
assert not _is_text_download("doc.pdf", r2)
def test_fix_mojibake_filename_roundtrip(self):
raw = "2026年年度报告.pdf".encode("gb18030").decode("latin-1")
assert _fix_mojibake_filename(raw) == "2026年年度报告.pdf"
def test_fix_mojibake_filename_keeps_ascii_and_real_cjk(self):
assert _fix_mojibake_filename("report.pdf") == "report.pdf"
assert _fix_mojibake_filename("正常中文.pdf") == "正常中文.pdf"
assert _fix_mojibake_filename("") == ""
def test_extract_filename_from_content_disposition_gbk(self):
mangled = "分红公告.pdf".encode("gb18030").decode("latin-1")
resp = FakeResp(headers={"Content-Disposition": f'filename="{mangled}"'})
assert _extract_filename(resp, "http://a.cn/dl?id=1") == "分红公告.pdf"
def test_extract_filename_utf8_star_form(self):
resp = FakeResp(headers={
"Content-Disposition": "attachment; filename*=UTF-8''%E6%B5%8B%E8%AF%95.pdf"})
assert _extract_filename(resp, "http://a.cn/x") == "测试.pdf"
class TestDownloadFile:
def test_referer_auto_injected(self, tmp_path):
fs = FakeSession([FakeResp(content=b"%PDF-1.4 fake",
headers={"Content-Type": "application/pdf"})])
got = download_file("http://fund.example.cn/ann/1.pdf",
save_dir=str(tmp_path), session=fs, use_cache=False)
assert got and Path(got).read_bytes() == b"%PDF-1.4 fake"
assert fs.calls[0]["headers"].get("Referer") == "http://fund.example.cn/"
def test_text_transcoded_to_utf8(self, tmp_path):
gbk_html = "<html><body>基金净值公告:单位净值 1.234 元</body></html>"
fs = FakeSession([FakeResp(content=gbk_html.encode("gb18030"),
headers={"Content-Type": "text/html"},
encoding="gb18030")])
got = download_file("http://gbk.example.cn/page", save_dir=str(tmp_path),
filename="page.html", session=fs, use_cache=False)
assert got is not None and got.endswith("page.html")
text = Path(got).read_text(encoding="utf-8")
assert "基金净值公告" in text and "1.234" in text
def test_anti_crawl_html_not_saved_as_pdf(self, tmp_path):
fs = FakeSession([FakeResp(content=b"<!DOCTYPE html><html>verify</html>",
headers={"Content-Type": "application/pdf"})])
got = download_file("http://x.example.cn/a.pdf", save_dir=str(tmp_path),
session=fs, use_cache=False)
assert got is None
assert list(tmp_path.iterdir()) == []
def test_empty_body_not_saved(self, tmp_path):
fs = FakeSession([FakeResp(content=b"")])
got = download_file("http://x.example.cn/a.txt", save_dir=str(tmp_path),
session=fs, retries=1, use_cache=False)
assert got is None
# ════════════════ 4. announcement_scraper 下载兜底 ════════════════
class TestAnnouncementDownload:
def test_fix_gbk_filename_static(self):
raw = "招募说明书.pdf".encode("gb18030").decode("latin-1")
assert ann.PDFDownloader._fix_gbk_filename(raw) == "招募说明书.pdf"
assert ann.PDFDownloader._fix_gbk_filename("abc.pdf") == "abc.pdf"
def test_no_requests_session_falls_back_to_stdlib(self, tmp_path):
dl = ann.PDFDownloader(download_dir=str(tmp_path))
dl.session = None # 模拟无 requests 环境
save = tmp_path / "out.pdf"
with patch.object(hu, "download_file", return_value=str(save)) as m:
assert dl._download_file("http://a.cn/x.pdf", save) is True
m.assert_called_once()
kwargs = m.call_args.kwargs
assert kwargs["save_dir"] == str(tmp_path)
assert kwargs["filename"] == "out.pdf"
def test_requests_exception_degrades_to_stdlib(self, tmp_path):
dl = ann.PDFDownloader(download_dir=str(tmp_path))
if dl.session is None:
pytest.skip("requests 未安装,此分支由上一用例覆盖")
save = tmp_path / "y.pdf"
with patch.object(dl.session, "get", side_effect=ConnectionError("refused")), \
patch.object(hu, "download_file", return_value=str(save)) as m:
assert dl._download_file("http://a.cn/y.pdf", save) is True
m.assert_called_once()
# ════════════════ 5. 机构名单扩充 ════════════════
EXPANDED_CATEGORIES = ["payment", "wm_subsidiary", "local_amc",
"internet_loan", "fund_sales", "credit_service"]
class TestInstitutionRoster:
def test_curated_bundle_expanded_categories_present(self):
bundle = json.loads((DATA_DIR / "curated.json").read_text(encoding="utf-8"))
for cat in EXPANDED_CATEGORIES:
items = bundle.get(cat)
assert isinstance(items, list) and items, f"curated.json 缺少类别 {cat}"
def test_load_curated_path_fix(self):
"""v7.5 回归修复:load_curated 必须能加载 data/curated.json
(此前误指向已删除的 data/curated/ 目录导致返回空)"""
import institution_expander as exp
for cat in ("payment", "fund_sales", "local_amc"):
items = exp.load_curated(cat)
assert items and all(i.get("name") for i in items), \
f"load_curated({cat}) 为空 — 精选名录路径回归未修复"
def test_registry_total_after_expansion(self):
reg = json.loads((DATA_DIR / "institution_registry.json")
.read_text(encoding="utf-8"))
assert reg.get("_f") == "c"
assert len(reg["d"]) >= 2334, "registry 机构总数应 ≥2334(v7.5 扩充后)"
type_idx = reg["c"].index("type")
types = {r[type_idx] for r in reg["d"]}
assert len(types) >= 43
+481
View File
@@ -0,0 +1,481 @@
# -*- coding: utf-8 -*-
"""v7.6.0 升级回归测试 — 知识库总结同步与校对
覆盖:
1. 按需总结:overall / target / negative 三种需求模式 + 自定义需求写入
2. 适配器:Local(幂等/检索)/ Obsidian(vault 落盘)/
IMA(凭证校验/创建笔记/关联知识库/检索)/ Dify(定位库/新增/更新/检索)
3. 同步引擎:推送统计 + 同步日志落盘 + 单篇失败不阻断
4. 校对:数字事实抽取 + verified / conflict / no_match 判定
5. CLI:run_knowledge.py(--search / --output 预览,输出隔离到临时目录)
全部离线(FakeSession 注入 / 模块属性 monkeypatch),不发网络请求、
不写真实项目目录。
"""
import json
import sys
from pathlib import Path
from unittest.mock import patch
import pytest
import knowledge_sync as ks
from knowledge_sync import (KnowledgeNote, summarize_to_notes,
LocalKnowledgeAdapter, ObsidianAdapter,
ImaAdapter, DifyAdapter, get_adapter,
sync_to_knowledge_base, extract_facts,
verify_against_knowledge_base,
load_kb_config, save_kb_config,
KnowledgeBaseError)
SKILL_DIR = Path(__file__).resolve().parent.parent
# ──────────────── 通用假对象 ────────────────
class FakeResp:
def __init__(self, payload, code=200):
self.code = code
self._payload = payload
self.text = json.dumps(payload, ensure_ascii=False)
self.content = self.text.encode("utf-8")
self.headers = {}
def json(self):
return self._payload
class FakeSession:
"""按调用次序弹出响应的假 session(兼容 http_get/http_post)。"""
def __init__(self, outcomes):
self.outcomes = list(outcomes)
self.calls = []
def _pop(self, url, record):
self.calls.append(record)
item = self.outcomes.pop(0)
if isinstance(item, Exception):
raise item
return item
def get(self, url, headers=None, timeout=30, **kw):
return self._pop(url, {"method": "GET", "url": url,
"headers": dict(headers or {})})
def post(self, url, data=None, json_body=None, headers=None,
timeout=30, **kw):
return self._pop(url, {"method": "POST", "url": url,
"json": json_body,
"headers": dict(headers or {})})
def make_agg():
"""构造一个聚合结果(3 条文章,1 负面)。"""
arts = [
{"title": "招商银行因违规被处罚", "source": "东财",
"sentiment": "negative", "severity": "重大",
"sentiment_score": -0.8, "publish_time": "2026-08-20 10:00:00",
"url": "https://a.cn/1", "target_name": "招商银行",
"keywords_matched": ["处罚"], "content": "营收 100.5 亿元"},
{"title": "招商银行发布中报业绩", "source": "新浪",
"sentiment": "positive", "severity": "中性",
"sentiment_score": 0.6, "publish_time": "2026-08-21 09:00:00",
"url": "https://a.cn/2", "target_name": "招商银行",
"keywords_matched": ["业绩"], "content": ""},
{"title": "贵州茅台获机构调研", "source": "财联社",
"sentiment": "neutral", "severity": "中性",
"sentiment_score": 0.0, "publish_time": "2026-08-22 11:00:00",
"url": "https://a.cn/3", "target_name": "贵州茅台",
"keywords_matched": [], "content": ""},
]
return {"generated_at": "2026-09-01 10:00:00", "snapshot_count": 2,
"raw_count": 3, "dedup_count": 3, "dedup_removed": 0,
"statistics": {"total": 3,
"sentiment": {"negative": 1, "positive": 1,
"neutral": 1},
"severity": {"重大": 1, "中性": 2},
"source_top": [["东财", 1]],
"by_day": {"2026-08-20": 1},
"hot_keywords": [["处罚", 1]],
"avg_score": -0.067, "neg_ratio": 0.333,
"pos_ratio": 0.333},
"by_target": [], "by_source": [], "articles": arts}
@pytest.fixture(autouse=True)
def _no_sleep():
with patch("http_utils.time.sleep"):
yield
@pytest.fixture(autouse=True)
def _isolate(monkeypatch, tmp_path):
"""同步日志/配置全部指向临时目录,且清空知识库相关环境变量。"""
monkeypatch.setattr(ks, "SYNC_LOG", tmp_path / "_sync_log.json")
monkeypatch.setattr(ks, "load_kb_config", lambda path=None: {})
monkeypatch.setattr(ks, "_ima_credentials",
lambda: {"client_id": "", "api_key": ""})
for ev in ("IMA_OPENAPI_CLIENTID", "IMA_OPENAPI_APIKEY",
"IMA_KNOWLEDGE_BASE_ID", "DIFY_API_KEY", "DIFY_BASE_URL",
"DIFY_DATASET_ID", "OBSIDIAN_VAULT_PATH"):
monkeypatch.delenv(ev, raising=False)
# ════════════════ 1. 按需总结 ════════════════
class TestSummarize:
def test_overall_contains_requirement(self):
notes = summarize_to_notes(make_agg(), mode="overall",
requirement="重点看处罚类事件")
assert len(notes) == 1
n = notes[0]
assert "总体汇总" in n.title
assert "重点看处罚类事件" in n.content
assert "招商银行因违规被处罚" in n.content
fm = n.to_frontmatter_markdown()
assert fm.startswith("---") and "tags:" in fm
def test_target_mode_filters(self):
notes = summarize_to_notes(make_agg(), mode="target", target="招商银行")
assert len(notes) == 1
assert "招商银行" in notes[0].title
assert "贵州茅台" not in notes[0].content
assert "负面 1 条" in notes[0].content
def test_target_requires_name(self):
with pytest.raises(ValueError):
summarize_to_notes(make_agg(), mode="target", target="")
def test_negative_mode_sorted_by_severity(self):
agg = make_agg()
agg["articles"].append(
{"title": "轻度负面事件", "source": "x", "sentiment": "negative",
"severity": "一般", "sentiment_score": -0.2,
"publish_time": "2026-08-23 10:00:00", "target_name": ""})
notes = summarize_to_notes(agg, mode="negative")
assert len(notes) == 1
body = notes[0].content
# 更严重(分数更低)的条目排在前面
assert body.index("招商银行因违规被处罚") < body.index("轻度负面事件")
assert "风险" in notes[0].tags
def test_empty_returns_no_notes(self):
empty = make_agg()
empty["articles"] = []
assert summarize_to_notes(empty) == []
# ════════════════ 2. Local / Obsidian 适配器 ════════════════
def _note(title="招商银行舆情总结 20260901", content="营收 100.5 亿元"):
return KnowledgeNote(title=title, content=content, tags=["测试"],
category="机构舆情")
class TestLocalAdapter:
def test_push_and_index(self, tmp_path):
ad = LocalKnowledgeAdapter(tmp_path / "kb")
r = ad.push(_note())
assert r["status"] == "pushed" and Path(r["path"]).exists()
text = Path(r["path"]).read_text(encoding="utf-8")
assert "营收 100.5 亿元" in text and text.startswith("---")
idx = json.loads((tmp_path / "kb" / "_index.json")
.read_text(encoding="utf-8"))
assert len(idx["entries"]) == 1
def test_idempotent_by_digest(self, tmp_path):
ad = LocalKnowledgeAdapter(tmp_path / "kb")
ad.push(_note())
r2 = ad.push(_note())
assert r2["status"] == "skipped"
def test_name_collision_gets_suffix(self, tmp_path):
ad = LocalKnowledgeAdapter(tmp_path / "kb")
ad.push(_note(content="版本一"))
r2 = ad.push(_note(content="版本二")) # 同标题不同内容
assert r2["status"] == "pushed"
assert r2["path"].endswith("_1.md")
def test_search_hits_keyword(self, tmp_path):
ad = LocalKnowledgeAdapter(tmp_path / "kb")
ad.push(_note())
ad.push(_note(title="贵州茅台调研纪要", content="机构调研"))
hits = ad.search("招商银行 处罚")
assert hits and "招商银行" in hits[0]["title"]
class TestObsidianAdapter:
def test_writes_into_vault(self, tmp_path):
vault = tmp_path / "vault"
vault.mkdir()
ad = ObsidianAdapter(vault_path=vault)
assert ad.available()
r = ad.push(_note())
assert r["status"] == "pushed"
files = list(vault.rglob("*.md"))
assert len(files) == 1 and files[0].name != "_index.json"
def test_unavailable_without_vault(self, tmp_path):
ad = ObsidianAdapter(vault_path=tmp_path / "not-exists")
assert not ad.available()
# ════════════════ 3. IMA 适配器 ════════════════
class TestImaAdapter:
def test_requires_credentials(self):
ad = ImaAdapter()
assert not ad.available()
with pytest.raises(KnowledgeBaseError):
ad.push(_note())
def test_push_creates_note_and_links(self):
fs = FakeSession([FakeResp({"code": 0, "data": {"note_id": "n1"}}),
FakeResp({"code": 0})])
ad = ImaAdapter(client_id="cid", api_key="key",
knowledge_base_id="kb1", session=fs)
r = ad.push(_note())
assert r["note_id"] == "n1" and r.get("linked") is True
# 第一步创建笔记,第二步关联知识库
assert fs.calls[0]["url"].endswith("/openapi/note/v1/import_doc")
assert fs.calls[0]["json"]["content_format"] == 1
assert fs.calls[1]["url"].endswith("/openapi/wiki/v1/add_knowledge")
assert fs.calls[1]["json"]["media_type"] == 11
assert fs.calls[0]["headers"]["ima-openapi-clientid"] == "cid"
def test_push_without_kb_id_skips_link(self):
fs = FakeSession([FakeResp({"code": 0, "data": {"note_id": "n2"}})])
ad = ImaAdapter(client_id="cid", api_key="key", session=fs)
r = ad.push(_note())
assert r["note_id"] == "n2" and "linked" not in r
assert len(fs.calls) == 1
def test_api_error_raises(self):
fs = FakeSession([FakeResp({"code": 1001, "msg": "auth fail"})])
ad = ImaAdapter(client_id="cid", api_key="bad", session=fs)
with pytest.raises(KnowledgeBaseError):
ad.push(_note())
def test_search_parses_items(self):
fs = FakeSession([FakeResp({"code": 0, "data": {"items": [
{"title": "招商银行处罚通报", "content": "罚款 300 万元"}]}})])
ad = ImaAdapter(client_id="cid", api_key="key",
knowledge_base_id="kb1", session=fs)
hits = ad.search("招商银行", limit=5)
assert hits[0]["title"] == "招商银行处罚通报"
assert fs.calls[0]["json"]["knowledge_base_id"] == "kb1"
# ════════════════ 4. Dify 适配器 ════════════════
class TestDifyAdapter:
def test_requires_key(self):
ad = DifyAdapter()
assert not ad.available()
with pytest.raises(KnowledgeBaseError):
ad.push(_note())
def test_push_new_document(self):
fs = FakeSession([
FakeResp({"data": [{"id": "ds1", "name": "cn-financial-scraper"}]}),
FakeResp({"data": []}), # 无同名文档
FakeResp({"document": {"id": "doc1"}}), # create-by-text
])
ad = DifyAdapter(api_key="dk", session=fs)
r = ad.push(_note())
assert r["status"] == "pushed" and r["dataset_id"] == "ds1"
assert fs.calls[2]["url"].endswith("/document/create-by-text")
assert fs.calls[2]["headers"]["Authorization"] == "Bearer dk"
assert fs.calls[2]["json"]["doc_language"] == "Chinese"
def test_push_updates_existing_document(self):
fs = FakeSession([
FakeResp({"data": [{"id": "ds1", "name": "cn-financial-scraper"}]}),
FakeResp({"data": [{"id": "doc9", "name": _note().title}]}),
FakeResp({"document": {"id": "doc9"}}), # update-by-text
])
ad = DifyAdapter(api_key="dk", session=fs)
r = ad.push(_note())
assert r["status"] == "updated"
assert "/documents/doc9/update-by-text" in fs.calls[2]["url"]
def test_creates_dataset_when_absent(self):
fs = FakeSession([
FakeResp({"data": []}), # 列表为空
FakeResp({"id": "ds-new"}), # 创建知识库
FakeResp({"data": []}), # 无同名文档
FakeResp({"document": {"id": "d1"}}),
])
ad = DifyAdapter(api_key="dk", session=fs)
r = ad.push(_note())
assert r["dataset_id"] == "ds-new"
assert fs.calls[1]["url"].endswith("/v1/datasets")
def test_search_parses_records(self):
fs = FakeSession([
FakeResp({"data": [{"id": "ds1", "name": "cn-financial-scraper"}]}),
FakeResp({"records": [{"segment": {
"content": "营收 100.5 亿元",
"document": {"name": "汇总笔记"}}, "score": 0.9}]}),
])
ad = DifyAdapter(api_key="dk", session=fs)
hits = ad.search("招商银行 营收")
assert hits[0]["snippet"] == "营收 100.5 亿元"
assert "/retrieve" in fs.calls[1]["url"]
# ════════════════ 5. 同步引擎 ════════════════
class TestSync:
def test_sync_local_and_log(self, tmp_path):
ad = LocalKnowledgeAdapter(tmp_path / "kb")
res = sync_to_knowledge_base(agg=make_agg(), adapter=ad)
assert res["pushed"] == 1 and not res["failed"]
log = json.loads(ks.SYNC_LOG.read_text(encoding="utf-8"))
assert log[-1]["target"] == "local" and log[-1]["pushed"] == 1
def test_empty_data_short_circuits(self, tmp_path):
empty = make_agg()
empty["articles"] = []
res = sync_to_knowledge_base(agg=empty,
adapter=LocalKnowledgeAdapter(tmp_path))
assert res["pushed"] == 0 and "快照为空" in res["message"]
def test_single_note_failure_does_not_block(self, tmp_path):
class Boom(LocalKnowledgeAdapter):
def push(self, note):
raise KnowledgeBaseError("模拟远端故障")
agg = make_agg()
res = sync_to_knowledge_base(agg=agg, mode="overall",
adapter=Boom(tmp_path / "kb"))
assert res["pushed"] == 0 and len(res["failed"]) == 1
assert "模拟远端故障" in res["failed"][0]["error"]
def test_get_adapter_unknown_name(self):
with pytest.raises(KnowledgeBaseError):
get_adapter("notion")
def test_config_save_load(self, tmp_path):
p = tmp_path / "cfg.json"
save_kb_config({"target": "obsidian"}, p)
assert load_kb_config(p)["target"] == "obsidian"
# ════════════════ 6. 知识库校对 ════════════════
class TestVerify:
def test_extract_facts(self):
facts = extract_facts("2026 中报营收 100.5 亿元,因违规被罚款 300 万元")
labels = {f["label"] for f in facts}
assert "营收" in labels and "罚款" in labels
rev = [f for f in facts if f["label"] == "营收"][0]
assert rev["value"] == "100.5"
def test_verified_conflict_and_no_match(self, tmp_path):
kb = LocalKnowledgeAdapter(tmp_path / "kb")
kb.push(KnowledgeNote(title="招商银行因违规被处罚",
content="营收 100.5 亿元", category="机构舆情"))
class Searcher(LocalKnowledgeAdapter):
"""返回知识库全文作为检索片段(模拟远端检索)。"""
def search(self, query, limit=5):
idx = self._load_index()
out = []
for e in idx["entries"]:
p = Path(e["path"])
out.append({"title": e["title"],
"snippet": p.read_text(encoding="utf-8")})
return out[:limit]
items = [
{"title": "招商银行因违规被处罚", "content": "营收 100.5 亿元"},
{"title": "平安银行无关新闻", "content": ""},
]
report = verify_against_knowledge_base(items, adapter=Searcher(tmp_path / "kb"))
assert report["verified"] == 1 and report["no_match"] == 1
assert not [r for r in report["results"] if r["status"] == "conflict"]
def test_number_conflict_detected(self, tmp_path):
kb = LocalKnowledgeAdapter(tmp_path / "kb")
kb.push(KnowledgeNote(title="招商银行因违规被处罚",
content="营收 999.0 亿元", category="机构舆情"))
class Searcher(LocalKnowledgeAdapter):
def search(self, query, limit=5):
idx = self._load_index()
return [{"title": e["title"],
"snippet": Path(e["path"]).read_text(encoding="utf-8")}
for e in idx["entries"][:limit]]
# 注意:库中条目正文的“营收 999.0”与爬取的“营收 100.5”冲突
items = [{"title": "招商银行因违规被处罚", "content": "营收 100.5 亿元"}]
report = verify_against_knowledge_base(items, adapter=Searcher(tmp_path / "kb"))
r = report["results"][0]
assert r["status"] == "conflict"
assert r["conflicts"][0]["label"] == "营收"
assert r["conflicts"][0]["crawled"] == "100.5"
assert r["conflicts"][0]["knowledge"] == ["999.0"]
# ════════════════ 7. CLI ════════════════
class TestCLI:
def test_cli_search_with_patched_adapter(self, capsys):
class FakeAdapter:
name = "fake"
def search(self, query, limit=5):
return [{"title": "命中条目", "snippet": query}]
import run_knowledge
with patch.object(ks, "get_adapter", lambda name=None, **kw: FakeAdapter()):
rc = run_knowledge.main(["--search", "招商银行", "--target", "local"])
assert rc == 0
assert "命中条目" in capsys.readouterr().out
def test_cli_preview_output_isolated(self, tmp_path, capsys):
"""--output 必须落到调用方指定目录,不污染真实项目。"""
snap_dir = tmp_path / "snaps"
snap_dir.mkdir()
(snap_dir / "s1.json").write_text(json.dumps({
"articles": [{"title": "测试文章", "source": "src",
"sentiment": "positive", "severity": "中性",
"publish_time": "2026-08-30 10:00:00",
"sentiment_score": 0.5, "url": "https://x.cn",
"target_name": "测试机构"}]},
ensure_ascii=False), encoding="utf-8")
out = tmp_path / "preview.md"
# 直接调用 summarize(依赖 aggregate_snapshots 真实目录)→ 注入临时快照目录后 patch 返回值
orig = ks.aggregate_snapshots
agg = orig(snapshot_dir=snap_dir)
with patch.object(ks, "aggregate_snapshots",
lambda snapshot_dir=None, days=0: agg):
import run_knowledge
rc = run_knowledge.main(["--mode", "overall", "--output", str(out)])
assert rc == 0
assert out.exists() and "总体汇总" in out.read_text(encoding="utf-8")
assert not (SKILL_DIR / "preview.md").exists()
def test_cli_verify(self, tmp_path, capsys):
kb = LocalKnowledgeAdapter(tmp_path / "kb")
kb.push(KnowledgeNote(title="测试文章", content="无数字", category="x"))
items_file = tmp_path / "items.json"
items_file.write_text(json.dumps(
[{"title": "测试文章", "content": ""}], ensure_ascii=False),
encoding="utf-8")
with patch.object(ks, "get_adapter",
lambda name=None, **kw: LocalKnowledgeAdapter(tmp_path / "kb")):
import run_knowledge
rc = run_knowledge.main(["--verify", str(items_file),
"--target", "local"])
assert rc == 0
report = json.loads(capsys.readouterr().out)
assert report["verified"] == 1
# ════════════════ 8. 版本同步 ════════════════
class TestVersion:
def test_skill_version_bumped(self):
import scripts
assert scripts.__version__ == "7.7.0"
meta = json.loads((SKILL_DIR / "_meta.json").read_text(encoding="utf-8"))
assert meta["version"] == "7.7.0"
+436
View File
@@ -0,0 +1,436 @@
# -*- coding: utf-8 -*-
"""v7.7.0 升级回归测试 — 四模块全面优化
覆盖:
1. 信息爬取:AdaptiveCrawlPolicy(早停/恢复解除/并发降级/全域沦陷)
+ batch_smart_crawl 自适应分批(早停跳过剩余/去重/统计)
2. 语音交互:知识库语音指令路由(总结/负面/机构名/检索/校对/帮助)
+ TTS 数字归一化
3. 下载:已存在跳过 / 断点续传(Range 206)/ 200 全量回落 /
sha256 校验 / min_bytes 拒收 / batch_download 并发统计
4. 分析:Sortino/胜率/极值扩展指标 / 指标缓存命中 /
nav_trend_analysis 趋势四档
全部离线(FakeSession / 纯函数 / monkeypatch),不发网络请求、
不写真实项目目录。
"""
import hashlib
from pathlib import Path
from unittest.mock import patch
import pytest
import analyzer as az
import crawl_enhancer as ce
import http_utils as hu
import voice_interface as vi
# ──────────────── 通用假对象 ────────────────
class FakeResp:
"""鸭子类型模拟 StdlibResponse(download_file 成功分支读取的属性)。"""
def __init__(self, code=200, content=b"", headers=None, encoding="utf-8"):
self.code = code
self.content = content
self.headers = headers or {}
self._encoding = encoding
self.text = content.decode(encoding, errors="replace")
class FakeSession:
"""按调用次序逐个弹出响应/异常的假 session。"""
def __init__(self, outcomes):
self.outcomes = list(outcomes)
self.calls = []
def get(self, url, headers=None, timeout=30, **kw):
self.calls.append({"url": url, "headers": dict(headers or {})})
item = self.outcomes.pop(0)
if isinstance(item, Exception):
raise item
return item
def _nav_series(n, base=1.0, step=0.002):
"""单调上行净值序列(dict 形态)。"""
return [{"date": f"2026-01-{(i % 28) + 1:02d}",
"nav": base * (1 + step * i)} for i in range(n)]
# ════════════════ 1. 爬取自适应策略 ════════════════
class TestAdaptiveCrawlPolicy:
def _fail(self, url="http://x.cn/a"):
return ce.FetchResult(url=url, status=ce.STATUS_ERROR, error="blocked")
def _ok(self, url="http://x.cn/a"):
return ce.FetchResult(url=url, status=ce.STATUS_OK, html="ok", text_len=2)
def test_early_stop_when_all_failed(self):
p = ce.AdaptiveCrawlPolicy(min_samples=3)
for _ in range(3):
p.record(self._fail(), set())
assert p.should_stop() is True
assert p.snapshot()["stop_reason"] == "all_failed"
def test_no_early_stop_below_min_samples(self):
p = ce.AdaptiveCrawlPolicy(min_samples=8)
for _ in range(5):
p.record(self._fail(), set())
assert p.should_stop() is False
def test_success_clears_early_stop(self):
p = ce.AdaptiveCrawlPolicy(min_samples=2)
p.record(self._fail(), set())
p.record(self._fail(), set())
assert p.should_stop() is True
p.record(self._ok(), set())
assert p.should_stop() is False
assert p.snapshot()["early_stopped"] is False
def test_consecutive_fail_triggers_downgrade(self):
p = ce.AdaptiveCrawlPolicy(downgrade_after=3)
for _ in range(3):
p.record(self._fail(), set())
assert p.should_downgrade() is True
assert p.snapshot()["downgrades"] == 1
assert p.should_downgrade() is False # 计数已清零
def test_degraded_concurrency_floor(self):
assert ce.AdaptiveCrawlPolicy.degraded_concurrency(4) == 2
assert ce.AdaptiveCrawlPolicy.degraded_concurrency(1) == 1
def test_all_domains_disabled_stops(self):
p = ce.AdaptiveCrawlPolicy()
class DeadHealth:
def is_available(self, d):
return False
assert p.should_stop(DeadHealth(), {"a.cn", "b.cn"}) is True
assert p.snapshot()["stop_reason"] == "domains_disabled"
class FakeFetcher:
"""按 URL 标记决定成败的注入抓取器。"""
def __init__(self):
self.fetched = []
def fetch(self, url, use_api=True, use_browser=False):
self.fetched.append(url)
if "#ok" in url:
return ce.FetchResult(url=url, status=ce.STATUS_OK,
html="x" * 300, text_len=300, source="http")
return ce.FetchResult(url=url, status=ce.STATUS_ERROR, error="blocked")
class TestBatchSmartCrawlV77:
def test_stats_and_adaptive_snapshot(self):
urls = ["http://a1.cn/#ok", "http://a2.cn/#ok",
"http://a3.cn/#ok", "http://a4.cn/fail"]
out = ce.batch_smart_crawl(urls, concurrency=2,
rate_map={"default": 0.0},
fetcher=FakeFetcher())
st = out["stats"]
assert st["ok"] == 3 and st["total"] == 4
assert st["success_rate"] == 0.75
assert st["elapsed"] >= 0 and st["avg_elapsed"] >= 0
assert st["adaptive"]["early_stopped"] is False
def test_early_stop_skips_remaining(self):
urls = [f"http://d{i}.cn/fail" for i in range(30)]
out = ce.batch_smart_crawl(urls, concurrency=2,
rate_map={"default": 0.0},
fetcher=FakeFetcher(),
early_stop_min_samples=4)
st = out["stats"]
assert st["fetched"] < 30
assert st["skipped_stopped"] > 0
assert st["adaptive"]["early_stopped"] is True
def test_dedup_skips_repeated_url(self, tmp_path):
dedup = tmp_path / "seen.json"
urls = ["http://dup.cn/a#ok", "http://dup.cn/a#ok",
"http://dup.cn/b#ok"]
out = ce.batch_smart_crawl(urls, concurrency=1,
rate_map={"default": 0.0},
dedup_file=str(dedup),
fetcher=FakeFetcher())
assert out["stats"]["skipped_dup"] == 1
assert out["stats"]["fetched"] == 2
# ════════════════ 2. 语音知识库指令 ════════════════
class TestVoiceKnowledgeRouting:
def test_non_kb_text_returns_none(self):
assert vi.handle_knowledge_command("爬一下贵州茅台最近7天的舆情") is None
assert vi.handle_knowledge_command("") is None
def test_sync_overall_command(self):
with patch.object(vi, "_kb_cmd_sync",
side_effect=lambda t, m, n: f"{t}|{m}|{n}") as m:
assert vi.handle_knowledge_command("总结到知识库") == "None|overall|"
m.assert_called_once()
def test_sync_negative_into_dify(self):
with patch.object(vi, "_kb_cmd_sync",
side_effect=lambda t, m, n: f"{t}|{m}|{n}"):
assert vi.handle_knowledge_command("负面总结进dify") == "dify|negative|"
def test_sync_target_name_extracted(self):
with patch.object(vi, "_kb_cmd_sync",
side_effect=lambda t, m, n: f"{t}|{m}|{n}"):
assert vi.handle_knowledge_command(
"总结贵州茅台到知识库") == "None|target|贵州茅台"
def test_sync_ima_target(self):
with patch.object(vi, "_kb_cmd_sync",
side_effect=lambda t, m, n: f"{t}|{m}|{n}"):
assert vi.handle_knowledge_command("同步到 ima") == "ima|overall|"
def test_search_keyword_extracted(self):
with patch.object(vi, "_kb_cmd_search",
side_effect=lambda k: f"SEARCH:{k}"):
assert vi.handle_knowledge_command(
"查一下知识库里的招商银行") == "SEARCH:招商银行"
def test_search_without_keyword_falls_through(self):
assert vi.handle_knowledge_command("查一下知识库") is None
def test_verify_command(self):
with patch.object(vi, "_kb_cmd_verify", return_value="VERIFY"):
assert vi.handle_knowledge_command("用知识库校对") == "VERIFY"
assert vi.handle_knowledge_command("和知识库比对一下") == "VERIFY"
def test_handle_text_routes_help(self):
vc = vi.VoiceChat(tts=False, chat=lambda t: {"reply": "CHAT"})
assert vc.handle_text("命令") == vi.VOICE_HELP
assert vc.handle_text("帮助") == vi.VOICE_HELP
def test_handle_text_routes_kb_before_chat(self):
vc = vi.VoiceChat(tts=False, chat=lambda t: {"reply": "CHAT"})
with patch.object(vi, "_kb_cmd_verify", return_value="VERIFY"):
assert vc.handle_text("用知识库校对") == "VERIFY"
assert vc.handle_text("茅台舆情") == "CHAT"
def test_tts_number_normalization(self):
assert vi._normalize_numbers_for_tts("涨幅82.5%,新增+5家") == \
"涨幅百分之82.5,新增5家"
def test_summarize_for_speech_strips_markdown_url(self):
reply = "**要点**:详情见 https://example.com/x 的内容"
out = vi.summarize_for_speech(reply)
assert "https" not in out and "**" not in out
def test_kb_cmd_sync_no_data_message(self):
class FakeKs:
@staticmethod
def sync_to_knowledge_base(**kw):
return {"target": "local", "pushed": 0, "skipped": 0,
"failed": [], "message": "无可总结的数据(快照为空)"}
with patch.object(vi, "_kb_import", return_value=FakeKs):
assert "快照为空" in vi._kb_cmd_sync(None, "overall", "")
def test_kb_cmd_verify_empty_snapshots(self):
class FakeKs:
@staticmethod
def aggregate_snapshots():
return {"articles": []}
with patch.object(vi, "_kb_import", return_value=FakeKs):
assert "快照为空" in vi._kb_cmd_verify()
# ════════════════ 3. 下载优化 ════════════════
class TestDownloadV77:
PDF_HEADERS = {"Content-Type": "application/pdf"}
def test_skip_existing_without_http_call(self, tmp_path):
(tmp_path / "a.pdf").write_bytes(b"%PDF-old")
fs = FakeSession([])
got = hu.download_file("http://a.cn/x.pdf", save_dir=str(tmp_path),
filename="a.pdf", session=fs)
assert got == str(tmp_path / "a.pdf")
assert fs.calls == [] # 未发任何请求
def test_overwrite_forces_redownload(self, tmp_path):
(tmp_path / "a.pdf").write_bytes(b"%PDF-old")
fs = FakeSession([FakeResp(content=b"%PDF-new", headers=self.PDF_HEADERS)])
got = hu.download_file("http://a.cn/x.pdf", save_dir=str(tmp_path),
filename="a.pdf", session=fs, overwrite=True)
assert got and Path(got).read_bytes() == b"%PDF-new"
def test_resume_range_206_appends(self, tmp_path):
(tmp_path / "a.pdf.part").write_bytes(b"head")
fs = FakeSession([FakeResp(code=206, content=b"tail",
headers=self.PDF_HEADERS)])
got = hu.download_file("http://a.cn/x.pdf", save_dir=str(tmp_path),
filename="a.pdf", session=fs)
assert got and Path(got).read_bytes() == b"headtail"
assert not (tmp_path / "a.pdf.part").exists()
assert fs.calls[0]["headers"]["Range"] == "bytes=4-"
def test_resume_unsupported_falls_back_full(self, tmp_path):
(tmp_path / "a.pdf.part").write_bytes(b"head")
fs = FakeSession([FakeResp(code=200, content=b"%PDF-full",
headers=self.PDF_HEADERS)])
got = hu.download_file("http://a.cn/x.pdf", save_dir=str(tmp_path),
filename="a.pdf", session=fs)
assert got and Path(got).read_bytes() == b"%PDF-full"
def test_no_part_file_no_range_header(self, tmp_path):
fs = FakeSession([FakeResp(content=b"%PDF-1.4", headers=self.PDF_HEADERS)])
hu.download_file("http://a.cn/x.pdf", save_dir=str(tmp_path),
filename="a.pdf", session=fs)
assert "Range" not in fs.calls[0]["headers"]
def test_sha256_mismatch_rejects_and_cleans(self, tmp_path):
fs = FakeSession([FakeResp(content=b"abc", headers=self.PDF_HEADERS)])
wrong = hashlib.sha256(b"xyz").hexdigest()
got = hu.download_file("http://a.cn/x.pdf", save_dir=str(tmp_path),
filename="a.pdf", session=fs,
expect_sha256=wrong)
assert got is None
assert not (tmp_path / "a.pdf").exists()
def test_sha256_match_passes(self, tmp_path):
body = b"%PDF-1.4 good"
fs = FakeSession([FakeResp(content=body, headers=self.PDF_HEADERS)])
got = hu.download_file("http://a.cn/x.pdf", save_dir=str(tmp_path),
filename="a.pdf", session=fs,
expect_sha256=hashlib.sha256(body).hexdigest())
assert got is not None
def test_min_bytes_rejects_too_small(self, tmp_path):
fs = FakeSession([FakeResp(content=b"%PDF", headers=self.PDF_HEADERS)])
got = hu.download_file("http://a.cn/x.pdf", save_dir=str(tmp_path),
filename="a.pdf", session=fs, min_bytes=100)
assert got is None
def test_atomic_write_leaves_no_part_on_success(self, tmp_path):
fs = FakeSession([FakeResp(content=b"%PDF-1.4", headers=self.PDF_HEADERS)])
hu.download_file("http://a.cn/x.pdf", save_dir=str(tmp_path),
filename="a.pdf", session=fs)
assert list(tmp_path.glob("*.part")) == []
def test_file_sha256_helper(self, tmp_path):
p = tmp_path / "x.bin"
p.write_bytes(b"hello")
assert hu.file_sha256(str(p)) == hashlib.sha256(b"hello").hexdigest()
class TestBatchDownload:
def test_batch_ok_and_failed(self, tmp_path):
fs = FakeSession([
FakeResp(content=b"%PDF-1", headers={"Content-Type": "application/pdf"}),
ConnectionError("refused"),
])
out = hu.batch_download(["http://bd1.cn/x.pdf", "http://bd2.cn/y.pdf"],
save_dir=str(tmp_path), concurrency=2,
session=fs)
assert out["total"] == 2
assert out["ok"] == 1
assert out["failed"] == ["http://bd2.cn/y.pdf"]
ok_path = out["files"]["http://bd1.cn/x.pdf"]
assert Path(ok_path).read_bytes() == b"%PDF-1"
def test_batch_empty(self, tmp_path):
out = hu.batch_download([], save_dir=str(tmp_path))
assert out == {"total": 0, "ok": 0, "failed": [], "files": {},
"elapsed": out["elapsed"]}
# ════════════════ 4. 分析优化 ════════════════
class TestRiskMetricsV77:
def test_extended_metrics_present(self):
m = az.calculate_risk_metrics(_nav_series(120))
for key in ("sortino_ratio", "win_rate", "best_day", "worst_day",
"sharpe_ratio", "calmar_ratio"):
assert key in m, f"缺少指标 {key}"
assert 0.0 < m["win_rate"] <= 1.0
assert m["best_day"] >= m["worst_day"]
def test_sortino_not_below_sharpe_for_uptrend(self):
# 带回调的震荡上行(存在下行波动,下行偏差 ≥ 总体波动的下限成立)
series = [{"date": f"d{i}", "nav": 1.0 + 0.002 * i
- (0.006 if i % 7 == 0 else 0.0)} for i in range(120)]
m = az.calculate_risk_metrics(series)
assert m["sortino_ratio"] >= m["sharpe_ratio"] - 0.01
def test_metrics_cache_hit(self):
series = _nav_series(80, step=0.001)
az.calculate_risk_metrics(series) # 预热入缓存
with patch.object(az, "_pct_changes",
wraps=az._pct_changes) as spy:
m2 = az.calculate_risk_metrics(list(series))
assert spy.call_count == 0 # 命中缓存,未重算
assert "annualized_return" in m2
def test_cache_does_not_share_across_rf(self):
series = _nav_series(60, step=0.003)
m1 = az.calculate_risk_metrics(series, risk_free_rate=0.02)
m2 = az.calculate_risk_metrics(series, risk_free_rate=0.05)
assert m1["sharpe_ratio"] != m2["sharpe_ratio"]
def test_legacy_dict_path_still_estimate(self):
m = az.calculate_risk_metrics({"1year": 15.67})
assert m.get("estimate") is True
class TestNavTrendAnalysis:
def test_uptrend_label(self):
t = az.nav_trend_analysis(_nav_series(120, step=0.002))
assert t["trend"] in ("强上行", "缓步上行")
assert t["annualized_slope"] > 0
assert t["at_high"] is True and t["off_peak"] == 0.0
def test_downtrend_label(self):
down = [{"date": f"d{i}", "nav": 1.0 - 0.004 * i} for i in range(120)]
t = az.nav_trend_analysis(down)
assert t["trend"] == "下行"
assert t["off_peak"] > 0.05
def test_window_returns(self):
t = az.nav_trend_analysis(_nav_series(120, step=0.002))
assert "return_20d" in t and "return_60d" in t
assert t["return_20d"] > 0
def test_vol_ratio_recent(self):
t = az.nav_trend_analysis(_nav_series(120))
assert "vol_ratio_recent20" in t
def test_insufficient_data(self):
t = az.nav_trend_analysis(_nav_series(5))
assert t == {"insufficient_data": True, "points": 5}
def test_report_includes_trend_section(self):
product = {
"product_name": "测试成长", "product_code": "000001",
"historical_nav": _nav_series(120, step=0.002),
"holdings": {},
}
report = az.analyze_product(product)
assert "趋势(v7.7)" in report
assert "索提诺比率" in report
# ════════════════ 5. 版本一致性 ════════════════
class TestVersion:
def test_package_version_770(self):
import scripts
assert scripts.__version__ == "7.7.0"
def test_new_exports(self):
import scripts
for name in ("nav_trend_analysis", "AdaptiveCrawlPolicy",
"handle_knowledge_command", "batch_download",
"file_sha256"):
assert name in scripts.__all__, f"__all__ 缺少 {name}"
assert hasattr(scripts, name)