```
feat(market): 添加市场分析数据基础架构和功能模块 - 新增市场分析相关数据库表结构,包括市场工具、每日报价、财务指标、 宏观指标和公告等数据模型 - 创建市场分析相关的Alembic迁移脚本,包含完整的up和downgrade逻辑 - 集成市场分析路由到主API路由器中 - 添加市场数据定时任务调度,支持盘前、收盘和周度市场分析报告 - 实现市场数据后台任务队列,包含报告生成和收盘分析功能 - 扩展系统配置设置,添加市场分析启用开关和相关参数配置 - 增加AI智能技能支持,包含市场概览分析和股票分析功能 - 添加审计日志记录,支持市场数据同步和自选股更新操作追踪 - 实现飞书命令集成,支持股票分析、自选股管理、公告查询等交互 - 提供市场数据服务层,包含行业分析、股票对比、市场概览等功能 ```
This commit is contained in:
@@ -30,6 +30,7 @@ os.environ["SCHEDULER_ENABLED"] = "false"
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.core.config import Settings, get_settings
|
||||
from app.core.background.scheduler import create_scheduler
|
||||
from app.core.database import Base, SessionLocal, engine
|
||||
from app.core.http.pagination import bounded_limit, bounded_offset
|
||||
from app.core.security import require_api_key, require_audit_api_key
|
||||
@@ -56,6 +57,11 @@ from app.modules.business.models import (
|
||||
ProjectContract,
|
||||
ProjectMember,
|
||||
ProjectMilestone,
|
||||
MarketDailyQuote,
|
||||
MarketAnnouncement,
|
||||
MarketFinancialMetric,
|
||||
MarketInstrument,
|
||||
MarketMacroIndicator,
|
||||
)
|
||||
from app.modules.business.service import _model_payload, serialize_model
|
||||
from app.modules.legacy_mysql.services import LegacyMySQLService
|
||||
@@ -101,6 +107,9 @@ from app.modules.feishu.commands import FeishuCommandService
|
||||
from app.modules.feishu.events import FeishuEventService
|
||||
from app.modules.feishu.constants import FeishuEventSource
|
||||
from app.modules.risk.constants import RiskEventActionValue
|
||||
from app.modules.market.chart import render_market_chart
|
||||
from app.modules.market.service import MarketService, TushareClient, normalize_symbol
|
||||
from app.modules.market.pipeline import MarketPipelineService
|
||||
from app.modules.workflows.constants import WorkflowStatus, WorkflowType
|
||||
from app.modules.workflows.models import WorkflowInstance
|
||||
|
||||
@@ -213,6 +222,8 @@ def test_feishu_webhook_routes_message_event() -> None:
|
||||
|
||||
|
||||
def test_feishu_rule_commands_create_list_disable_and_enable(monkeypatch) -> None:
|
||||
monkeypatch.setenv("READ_ONLY_MODE", "false")
|
||||
get_settings.cache_clear()
|
||||
monkeypatch.setattr(
|
||||
FeishuService,
|
||||
"send_text",
|
||||
@@ -256,9 +267,13 @@ def test_feishu_rule_commands_create_list_disable_and_enable(monkeypatch) -> Non
|
||||
assert rule.status == AIMemoryStatus.ACTIVE
|
||||
finally:
|
||||
db.close()
|
||||
monkeypatch.delenv("READ_ONLY_MODE", raising=False)
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_feishu_rule_command_preserves_sender_and_rejects_invalid_input() -> None:
|
||||
def test_feishu_rule_command_preserves_sender_and_rejects_invalid_input(monkeypatch) -> None:
|
||||
monkeypatch.setenv("READ_ONLY_MODE", "false")
|
||||
get_settings.cache_clear()
|
||||
payload = {
|
||||
"schema": "2.0",
|
||||
"header": {
|
||||
@@ -272,9 +287,7 @@ def test_feishu_rule_command_preserves_sender_and_rejects_invalid_input() -> Non
|
||||
"chat_id": "oc_test",
|
||||
"message_id": "om_smoke_rule_actor_001",
|
||||
"message_type": "text",
|
||||
"content": json.dumps(
|
||||
{"text": "学习规则:风险建议先写事实依据再写行动"}
|
||||
),
|
||||
"content": json.dumps({"text": "学习规则:风险建议先写事实依据再写行动"}),
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -287,9 +300,7 @@ def test_feishu_rule_command_preserves_sender_and_rejects_invalid_input() -> Non
|
||||
)
|
||||
assert result["result"]["command"] == "rule_create"
|
||||
rule = db.execute(
|
||||
select(AIMemoryEntry).where(
|
||||
AIMemoryEntry.content == "风险建议先写事实依据再写行动"
|
||||
)
|
||||
select(AIMemoryEntry).where(AIMemoryEntry.content == "风险建议先写事实依据再写行动")
|
||||
).scalar_one()
|
||||
assert rule.actor == "ou_rule_teacher"
|
||||
|
||||
@@ -310,6 +321,8 @@ def test_feishu_rule_command_preserves_sender_and_rejects_invalid_input() -> Non
|
||||
assert "已拒绝学习" in secret["content"]
|
||||
finally:
|
||||
db.close()
|
||||
monkeypatch.delenv("READ_ONLY_MODE", raising=False)
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_v3_request_id_health_and_metrics() -> None:
|
||||
@@ -609,9 +622,10 @@ def test_dashboard_and_response_masking() -> None:
|
||||
assert masked_response.status_code == 200
|
||||
masked_items = masked_response.json()["items"]
|
||||
assert any(item["code"] == "EXP-MASK-001" for item in masked_items)
|
||||
assert next(
|
||||
item["payment_account"] for item in masked_items if item["code"] == "EXP-MASK-001"
|
||||
) == "[MASKED]"
|
||||
assert (
|
||||
next(item["payment_account"] for item in masked_items if item["code"] == "EXP-MASK-001")
|
||||
== "[MASKED]"
|
||||
)
|
||||
|
||||
dashboard_response = client.get("/api/v1/dashboard/summary", headers=headers)
|
||||
assert dashboard_response.status_code == 200
|
||||
@@ -635,9 +649,7 @@ def test_configured_domain_response_masking(monkeypatch) -> None:
|
||||
list_response = client.get("/api/v1/business/expenses", headers=headers)
|
||||
assert list_response.status_code == 200
|
||||
item = next(
|
||||
item
|
||||
for item in list_response.json()["items"]
|
||||
if item["code"] == "EXP-MASK-CONFIG-001"
|
||||
item for item in list_response.json()["items"] if item["code"] == "EXP-MASK-CONFIG-001"
|
||||
)
|
||||
assert item["amount"] == "[MASKED]"
|
||||
finally:
|
||||
@@ -843,10 +855,7 @@ def test_project_lifecycle_report_summarizes_progress_cost_and_risk() -> None:
|
||||
assert data[LifecycleResponseKey.TITLE] == ReportTitle.PROJECT_LIFECYCLE
|
||||
assert data[LifecycleResponseKey.METRICS][LifecycleSection.PROJECTS][MetricKey.TOTAL] == 1
|
||||
assert data[LifecycleResponseKey.METRICS][LifecycleSection.PROJECTS][MetricKey.DELAYED] == 1
|
||||
assert (
|
||||
data[LifecycleResponseKey.METRICS][LifecycleSection.PROJECTS][MetricKey.OVER_BUDGET]
|
||||
== 1
|
||||
)
|
||||
assert data[LifecycleResponseKey.METRICS][LifecycleSection.PROJECTS][MetricKey.OVER_BUDGET] == 1
|
||||
assert data[LifecycleResponseKey.METRICS][LifecycleSection.TASKS][MetricKey.OVERDUE] == 1
|
||||
assert (
|
||||
data[LifecycleResponseKey.METRICS][LifecycleSection.PROCUREMENTS][
|
||||
@@ -855,9 +864,7 @@ def test_project_lifecycle_report_summarizes_progress_cost_and_risk() -> None:
|
||||
== 1
|
||||
)
|
||||
assert (
|
||||
data[LifecycleResponseKey.METRICS][LifecycleSection.EXPENSES][
|
||||
MetricKey.PENDING_APPROVAL
|
||||
]
|
||||
data[LifecycleResponseKey.METRICS][LifecycleSection.EXPENSES][MetricKey.PENDING_APPROVAL]
|
||||
== 1
|
||||
)
|
||||
assert data[LifecycleResponseKey.METRICS][LifecycleSection.ATTENDANCE][MetricKey.ABNORMAL] == 1
|
||||
@@ -875,10 +882,7 @@ def test_project_lifecycle_report_summarizes_progress_cost_and_risk() -> None:
|
||||
assert ai_response.status_code == 200
|
||||
ai_data = ai_response.json()
|
||||
assert ai_data[LifecycleResponseKey.AI_ANALYSIS][AIResponseKey.OK] is True
|
||||
assert (
|
||||
ai_data[LifecycleResponseKey.AI_ANALYSIS][AIResponseKey.PROVIDER]
|
||||
== AIProviderName.NOOP
|
||||
)
|
||||
assert ai_data[LifecycleResponseKey.AI_ANALYSIS][AIResponseKey.PROVIDER] == AIProviderName.NOOP
|
||||
|
||||
|
||||
def test_v3_enterprise_analytics_returns_read_only_sections() -> None:
|
||||
@@ -1078,10 +1082,7 @@ def test_report_push_failure_is_recorded() -> None:
|
||||
headers=headers,
|
||||
)
|
||||
assert runs_response.status_code == 200
|
||||
assert any(
|
||||
item["title"] == ReportTitle.DAILY_BRIEF
|
||||
for item in runs_response.json()["items"]
|
||||
)
|
||||
assert any(item["title"] == ReportTitle.DAILY_BRIEF for item in runs_response.json()["items"])
|
||||
|
||||
dashboard_response = client.get("/api/v1/dashboard/summary", headers=headers)
|
||||
assert dashboard_response.status_code == 200
|
||||
@@ -1267,9 +1268,7 @@ def test_intasect_full_sync_marks_missing_projects_inactive() -> None:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
IntasectSyncService(db, FakeSource([row])).sync_dataset("projects", "RUN-1")
|
||||
project = db.execute(
|
||||
select(Project).where(Project.external_id == "99101")
|
||||
).scalar_one()
|
||||
project = db.execute(select(Project).where(Project.external_id == "99101")).scalar_one()
|
||||
assert project.is_active is True
|
||||
assert project.display_code == "B-99101"
|
||||
|
||||
@@ -1353,12 +1352,12 @@ def test_personnel_lifecycle_does_not_treat_missing_ding_mapping_as_absence() ->
|
||||
|
||||
|
||||
def test_lifecycle_pipeline_is_idempotent(monkeypatch) -> None:
|
||||
monkeypatch.setenv("READ_ONLY_MODE", "false")
|
||||
get_settings.cache_clear()
|
||||
monkeypatch.setattr(
|
||||
IntasectSyncService,
|
||||
"sync_all",
|
||||
lambda self, run_code, force_full=False, batch_size=500: {
|
||||
"projects": {"processed": 1}
|
||||
},
|
||||
lambda self, run_code, force_full=False, batch_size=500: {"projects": {"processed": 1}},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ReportService,
|
||||
@@ -1383,6 +1382,8 @@ def test_lifecycle_pipeline_is_idempotent(monkeypatch) -> None:
|
||||
assert first["workflow_code"] == second["workflow_code"]
|
||||
finally:
|
||||
db.close()
|
||||
monkeypatch.delenv("READ_ONLY_MODE", raising=False)
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_lifecycle_enqueue_respects_read_only_guard(monkeypatch) -> None:
|
||||
@@ -1418,12 +1419,12 @@ def test_lifecycle_report_api_validates_filters_and_report_type() -> None:
|
||||
|
||||
|
||||
def test_ai_unavailable_sends_notice_without_business_report(monkeypatch) -> None:
|
||||
monkeypatch.setenv("READ_ONLY_MODE", "false")
|
||||
get_settings.cache_clear()
|
||||
monkeypatch.setattr(
|
||||
IntasectSyncService,
|
||||
"sync_all",
|
||||
lambda self, run_code, force_full=False, batch_size=500: {
|
||||
"projects": {"processed": 1}
|
||||
},
|
||||
lambda self, run_code, force_full=False, batch_size=500: {"projects": {"processed": 1}},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ReportService,
|
||||
@@ -1455,6 +1456,8 @@ def test_ai_unavailable_sends_notice_without_business_report(monkeypatch) -> Non
|
||||
assert result["notified"] is True
|
||||
finally:
|
||||
db.close()
|
||||
monkeypatch.delenv("READ_ONLY_MODE", raising=False)
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_user_rules_are_prioritized_in_ai_context(monkeypatch) -> None:
|
||||
@@ -1940,3 +1943,468 @@ def test_lifecycle_chart_renders_finance_section() -> None:
|
||||
}
|
||||
)
|
||||
assert png.startswith(b"\x89PNG\r\n\x1a\n")
|
||||
|
||||
|
||||
def test_market_sync_and_overview_use_deterministic_breadth() -> None:
|
||||
class FakeMarketProvider:
|
||||
def query(self, api_name, params, fields):
|
||||
if api_name == "trade_cal":
|
||||
return [{"exchange": "SSE", "cal_date": "20260710", "is_open": "1"}]
|
||||
if api_name == "stock_basic":
|
||||
return [
|
||||
{
|
||||
"ts_code": "600101.SH",
|
||||
"name": "Alpha",
|
||||
"exchange": "SSE",
|
||||
"industry": "科技",
|
||||
"list_date": "20200101",
|
||||
},
|
||||
{
|
||||
"ts_code": "000101.SZ",
|
||||
"name": "Beta",
|
||||
"exchange": "SZSE",
|
||||
"industry": "消费",
|
||||
"list_date": "20200101",
|
||||
},
|
||||
]
|
||||
if api_name == "daily":
|
||||
return [
|
||||
{
|
||||
"ts_code": "600101.SH",
|
||||
"trade_date": "20260710",
|
||||
"open": 10,
|
||||
"high": 11,
|
||||
"low": 9,
|
||||
"close": 11,
|
||||
"pre_close": 10,
|
||||
"pct_chg": 10,
|
||||
"vol": 100,
|
||||
"amount": 200,
|
||||
},
|
||||
{
|
||||
"ts_code": "000101.SZ",
|
||||
"trade_date": "20260710",
|
||||
"open": 10,
|
||||
"high": 10,
|
||||
"low": 8,
|
||||
"close": 9,
|
||||
"pre_close": 10,
|
||||
"pct_chg": -10,
|
||||
"vol": 100,
|
||||
"amount": 300,
|
||||
},
|
||||
]
|
||||
if api_name == "daily_basic":
|
||||
return [{"ts_code": "600101.SH", "pe_ttm": 20, "pb": 2, "total_mv": 10000}]
|
||||
if api_name == "index_daily":
|
||||
return [
|
||||
{
|
||||
"ts_code": params["ts_code"],
|
||||
"trade_date": "20260710",
|
||||
"open": 100,
|
||||
"high": 102,
|
||||
"low": 99,
|
||||
"close": 101,
|
||||
"pre_close": 100,
|
||||
"pct_chg": 1,
|
||||
"vol": 10,
|
||||
"amount": 20,
|
||||
}
|
||||
]
|
||||
return []
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
result = MarketService(db, FakeMarketProvider()).sync_daily(date(2026, 7, 10))
|
||||
assert result == {"instruments": 2, "quotes": 6, "valuations": 1}
|
||||
report = MarketService(db).market_overview(date(2026, 7, 10))
|
||||
assert report["data_available"] is True
|
||||
assert report["metrics"]["advances"] == 1
|
||||
assert report["metrics"]["declines"] == 1
|
||||
assert report["metrics"]["limit_up"] == 1
|
||||
assert report["metrics"]["limit_down"] == 1
|
||||
assert report["metrics"]["turnover_cny"] == 500000
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_stock_analysis_calculates_returns_risk_and_chart() -> None:
|
||||
db = SessionLocal()
|
||||
symbol = "600102.SH"
|
||||
try:
|
||||
db.add(MarketInstrument(symbol=symbol, name="Gamma", exchange="SSE", industry="金融"))
|
||||
for index in range(70):
|
||||
db.add(
|
||||
MarketDailyQuote(
|
||||
symbol=symbol,
|
||||
trade_date=date(2026, 4, 1) + timedelta(days=index),
|
||||
close_price=10 + index / 10,
|
||||
pct_change=1,
|
||||
pe=15,
|
||||
pb=1.5,
|
||||
)
|
||||
)
|
||||
db.add(
|
||||
MarketFinancialMetric(
|
||||
symbol=symbol,
|
||||
period_end=date(2026, 3, 31),
|
||||
revenue_yoy=12,
|
||||
net_profit_yoy=8,
|
||||
roe=10,
|
||||
debt_to_assets=40,
|
||||
operating_cashflow_yoy=None,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
report = MarketService(db).stock_analysis("600102")
|
||||
assert report["metrics"]["return_20d"] > 0
|
||||
assert report["metrics"]["max_drawdown"] == 0
|
||||
assert report["metrics"]["financial"]["revenue_yoy"] == 12
|
||||
assert report["metrics"]["financial"]["operating_cashflow_yoy"] is None
|
||||
assert render_market_chart(report).startswith(b"\x89PNG\r\n\x1a\n")
|
||||
assert normalize_symbol("000001") == "000001.SZ"
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_market_api_and_feishu_fail_closed_without_ai(monkeypatch) -> None:
|
||||
monkeypatch.setenv("MARKET_ANALYSIS_ENABLED", "true")
|
||||
get_settings.cache_clear()
|
||||
try:
|
||||
response = client.get(
|
||||
"/api/v1/market/overview",
|
||||
headers=headers,
|
||||
params={"trade_date": "2026-07-10"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["data_available"] is True
|
||||
db = SessionLocal()
|
||||
try:
|
||||
result = FeishuCommandService(db).handle_text(
|
||||
"市场分析", actor="ou_market", auto_reply=False
|
||||
)
|
||||
assert result["command"] == "market_overview"
|
||||
assert result["reply_type"] == "text"
|
||||
assert "AI 当前不可用" in result["content"]
|
||||
assert "领涨行业" not in result["content"]
|
||||
|
||||
industry = FeishuCommandService(db).handle_text(
|
||||
"行业分析 科技", actor="ou_market", auto_reply=False
|
||||
)
|
||||
assert "Alpha" in industry["content"]
|
||||
|
||||
comparison = FeishuCommandService(db).handle_text(
|
||||
"股票对比 600101 000101", actor="ou_market", auto_reply=False
|
||||
)
|
||||
assert "Alpha" in comparison["content"]
|
||||
assert "Beta" in comparison["content"]
|
||||
finally:
|
||||
db.close()
|
||||
finally:
|
||||
monkeypatch.delenv("MARKET_ANALYSIS_ENABLED", raising=False)
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_market_closed_day_skips_quote_collection() -> None:
|
||||
class ClosedProvider:
|
||||
def query(self, api_name, params, fields):
|
||||
assert api_name == "trade_cal"
|
||||
return [{"is_open": "0"}]
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
result = MarketService(db, ClosedProvider()).sync_daily(date(2026, 7, 11))
|
||||
assert result["market_closed"] == 1
|
||||
assert result["quotes"] == 0
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_market_scheduler_registers_close_and_weekly_jobs(monkeypatch) -> None:
|
||||
monkeypatch.setenv("MARKET_ANALYSIS_ENABLED", "true")
|
||||
get_settings.cache_clear()
|
||||
try:
|
||||
scheduler = create_scheduler()
|
||||
job_ids = {job.id for job in scheduler.get_jobs()}
|
||||
assert "market_premarket_analysis" in job_ids
|
||||
assert "market_close_analysis" in job_ids
|
||||
assert "market_weekly_analysis" in job_ids
|
||||
finally:
|
||||
monkeypatch.delenv("MARKET_ANALYSIS_ENABLED", raising=False)
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_market_ai_exception_is_reported_without_business_fallback(monkeypatch) -> None:
|
||||
class BrokenAdapter:
|
||||
provider_name = "broken"
|
||||
|
||||
def ask(self, prompt, context):
|
||||
raise TimeoutError("model timeout")
|
||||
|
||||
monkeypatch.setenv("MARKET_ANALYSIS_ENABLED", "true")
|
||||
get_settings.cache_clear()
|
||||
monkeypatch.setattr("app.modules.ai_agent.service.get_adapter", lambda: BrokenAdapter())
|
||||
db = SessionLocal()
|
||||
try:
|
||||
result = FeishuCommandService(db).handle_text(
|
||||
"市场分析", actor="ou_market", auto_reply=False
|
||||
)
|
||||
assert result["reply_type"] == "text"
|
||||
assert "AI 当前不可用" in result["content"]
|
||||
assert "上涨" not in result["content"]
|
||||
finally:
|
||||
db.close()
|
||||
monkeypatch.delenv("MARKET_ANALYSIS_ENABLED", raising=False)
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_tushare_http_failure_has_stable_error(monkeypatch) -> None:
|
||||
import httpx
|
||||
|
||||
monkeypatch.setenv("MARKET_DATA_TOKEN", "test-token")
|
||||
get_settings.cache_clear()
|
||||
monkeypatch.setattr(
|
||||
"app.modules.market.service.httpx.post",
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(httpx.ConnectTimeout("timeout")),
|
||||
)
|
||||
try:
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
TushareClient().query("trade_cal", {}, ["is_open"])
|
||||
assert exc_info.value.status_code == 503
|
||||
assert exc_info.value.detail == "Market data provider unavailable"
|
||||
finally:
|
||||
monkeypatch.delenv("MARKET_DATA_TOKEN", raising=False)
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_market_macro_and_announcement_sync_store_only_curated_fields() -> None:
|
||||
class Provider:
|
||||
def query(self, api_name, params, fields):
|
||||
if api_name == "shibor":
|
||||
return [{"date": "20260710", "on": "1.55"}]
|
||||
if api_name == "cn_cpi":
|
||||
return [{"month": "202606", "nt_yoy": "0.4"}]
|
||||
if api_name == "cn_gdp":
|
||||
return [{"quarter": "2026Q2", "gdp_yoy": "5.1"}]
|
||||
if api_name == "cn_m":
|
||||
return [{"month": "202606", "m2_yoy": "8.3"}]
|
||||
if api_name == "anns_d" and params["ann_date"] == "20260710":
|
||||
return [
|
||||
{
|
||||
"ann_date": "20260710",
|
||||
"ts_code": "600103.SH",
|
||||
"title": "年度报告披露提示",
|
||||
"url": "https://example.invalid/report.pdf",
|
||||
"rec_time": "2026-07-10 08:30:00",
|
||||
"content": "正文不得保存",
|
||||
}
|
||||
]
|
||||
return []
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
service = MarketService(db, Provider())
|
||||
result = service.sync_macro(date(2026, 7, 10))
|
||||
assert result == {"shibor": 1, "cn_cpi": 1, "cn_gdp": 1, "cn_m": 1}
|
||||
assert service.sync_announcements(date(2026, 7, 10), date(2026, 7, 10)) == 1
|
||||
codes = set(db.execute(select(MarketMacroIndicator.code)).scalars())
|
||||
assert {"SHIBOR_ON", "CPI_YOY", "GDP_YOY", "M2_YOY"}.issubset(codes)
|
||||
announcement = db.execute(
|
||||
select(MarketAnnouncement).where(MarketAnnouncement.symbol == "600103.SH")
|
||||
).scalar_one()
|
||||
assert announcement.title == "年度报告披露提示"
|
||||
assert not hasattr(announcement, "content")
|
||||
assert service.sync_announcements(date(2026, 7, 10), date(2026, 7, 10)) == 1
|
||||
count = len(
|
||||
list(
|
||||
db.execute(
|
||||
select(MarketAnnouncement).where(
|
||||
MarketAnnouncement.symbol == "600103.SH"
|
||||
)
|
||||
).scalars()
|
||||
)
|
||||
)
|
||||
assert count == 1
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_market_pipeline_is_idempotent_and_requires_complete_ai_chart_delivery(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
class FakeMarket:
|
||||
def sync_daily(self, target):
|
||||
return {"quotes": 2}
|
||||
|
||||
def sync_macro(self, target):
|
||||
return {"shibor": 1}
|
||||
|
||||
def sync_announcements(self, start, end):
|
||||
return 1
|
||||
|
||||
def sync_watchlist_financials(self):
|
||||
return {}
|
||||
|
||||
def market_overview(self, target=None, include_ai=False, actor="api"):
|
||||
return {
|
||||
"title": "市场收盘分析",
|
||||
"data_available": True,
|
||||
"metrics": {"advances": 1, "declines": 1, "flat": 0},
|
||||
"chart_data": {"advances": 1, "declines": 1, "flat": 0},
|
||||
"lines": ["- AI 已完成分析"],
|
||||
"content": "AI 已完成分析",
|
||||
"ai_analysis": {"ok": True, "answer": "分析完成"},
|
||||
}
|
||||
|
||||
monkeypatch.setenv("FEISHU_APP_ID", "test-app")
|
||||
monkeypatch.setenv("FEISHU_APP_SECRET", "test-secret")
|
||||
monkeypatch.setenv("FEISHU_DEFAULT_CHAT_ID", "oc_market")
|
||||
monkeypatch.setenv("READ_ONLY_MODE", "false")
|
||||
get_settings.cache_clear()
|
||||
monkeypatch.setattr(
|
||||
"app.modules.feishu.service.FeishuService.upload_image",
|
||||
lambda self, image, actor="system": {"data": {"image_key": "img-market"}},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.modules.feishu.service.FeishuService.send_card",
|
||||
lambda self, card, receive_id=None, receive_id_type="chat_id", actor="system": {
|
||||
"code": 0
|
||||
},
|
||||
)
|
||||
db = SessionLocal()
|
||||
try:
|
||||
pipeline = MarketPipelineService(db, FakeMarket())
|
||||
first = pipeline.run("close", date(2030, 7, 12), actor="pytest")
|
||||
second = pipeline.run("close", date(2030, 7, 12), actor="pytest")
|
||||
assert first["status"] == WorkflowStatus.COMPLETED
|
||||
assert second["deduplicated"] is True
|
||||
assert second["workflow_code"] == first["workflow_code"]
|
||||
finally:
|
||||
db.close()
|
||||
monkeypatch.delenv("FEISHU_APP_ID", raising=False)
|
||||
monkeypatch.delenv("FEISHU_APP_SECRET", raising=False)
|
||||
monkeypatch.delenv("FEISHU_DEFAULT_CHAT_ID", raising=False)
|
||||
monkeypatch.delenv("READ_ONLY_MODE", raising=False)
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_market_pipeline_fails_closed_when_ai_is_unavailable(monkeypatch) -> None:
|
||||
class FakeMarket:
|
||||
def sync_daily(self, target):
|
||||
return {"quotes": 1}
|
||||
|
||||
def sync_macro(self, target):
|
||||
return {}
|
||||
|
||||
def sync_announcements(self, start, end):
|
||||
return 0
|
||||
|
||||
def sync_watchlist_financials(self):
|
||||
return {}
|
||||
|
||||
def market_overview(self, target=None, include_ai=False, actor="api"):
|
||||
return {
|
||||
"title": "市场分析",
|
||||
"data_available": True,
|
||||
"metrics": {"advances": 1},
|
||||
"chart_data": {"advances": 1},
|
||||
"lines": ["- 不应推送"],
|
||||
"content": "不应推送",
|
||||
"ai_analysis": {"ok": False, "error": "timeout"},
|
||||
}
|
||||
|
||||
monkeypatch.setenv("READ_ONLY_MODE", "false")
|
||||
get_settings.cache_clear()
|
||||
db = SessionLocal()
|
||||
try:
|
||||
result = MarketPipelineService(db, FakeMarket()).run(
|
||||
"close", date(2030, 7, 15), actor="pytest"
|
||||
)
|
||||
assert result["status"] == WorkflowStatus.FAILED
|
||||
assert result["reason"] == "ai_unavailable"
|
||||
workflow = db.execute(
|
||||
select(WorkflowInstance).where(WorkflowInstance.code == result["workflow_code"])
|
||||
).scalar_one()
|
||||
assert workflow.current_step == "ai_unavailable"
|
||||
finally:
|
||||
db.close()
|
||||
monkeypatch.delenv("READ_ONLY_MODE", raising=False)
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_market_weekly_overview_uses_five_latest_trading_days() -> None:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
symbols = (("600104.SH", "Delta", "科技", 10, 12), ("000104.SZ", "Epsilon", "消费", 10, 8))
|
||||
days = [date(2031, 7, 7) + timedelta(days=index) for index in range(5)]
|
||||
for symbol, name, industry, first, last in symbols:
|
||||
db.add(MarketInstrument(symbol=symbol, name=name, industry=industry))
|
||||
for index, day in enumerate(days):
|
||||
close = first + (last - first) * index / 4
|
||||
db.add(MarketDailyQuote(symbol=symbol, trade_date=day, close_price=close))
|
||||
db.commit()
|
||||
report = MarketService(db).weekly_overview(date(2031, 7, 11))
|
||||
assert report["data_available"] is True
|
||||
assert report["metrics"]["trading_days"] == 5
|
||||
assert report["metrics"]["advances"] == 1
|
||||
assert report["metrics"]["declines"] == 1
|
||||
assert report["metrics"]["period_start"] == "2031-07-07"
|
||||
assert report["metrics"]["period_end"] == "2031-07-11"
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_feishu_market_rules_are_scoped_to_market(monkeypatch) -> None:
|
||||
monkeypatch.setenv("MARKET_ANALYSIS_ENABLED", "true")
|
||||
monkeypatch.setenv("READ_ONLY_MODE", "false")
|
||||
get_settings.cache_clear()
|
||||
db = SessionLocal()
|
||||
try:
|
||||
created = FeishuCommandService(db).handle_text(
|
||||
"学习市场规则 90:市场结论必须列出数据日期",
|
||||
actor="ou_market_rule",
|
||||
auto_reply=False,
|
||||
)
|
||||
assert "market / market" in created["content"]
|
||||
listed = FeishuCommandService(db).handle_text(
|
||||
"查看市场规则", actor="ou_market_rule", auto_reply=False
|
||||
)
|
||||
assert "市场结论必须列出数据日期" in listed["content"]
|
||||
assert "market/market" in listed["content"]
|
||||
finally:
|
||||
db.close()
|
||||
monkeypatch.delenv("MARKET_ANALYSIS_ENABLED", raising=False)
|
||||
monkeypatch.delenv("READ_ONLY_MODE", raising=False)
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_read_only_mode_blocks_feishu_mutations_and_market_pipeline(monkeypatch) -> None:
|
||||
class MustNotRunMarket:
|
||||
def sync_daily(self, target):
|
||||
pytest.fail("read-only mode must block market synchronization")
|
||||
|
||||
monkeypatch.setenv("READ_ONLY_MODE", "true")
|
||||
monkeypatch.setenv("MARKET_ANALYSIS_ENABLED", "true")
|
||||
get_settings.cache_clear()
|
||||
db = SessionLocal()
|
||||
try:
|
||||
rules = FeishuCommandService(db).handle_text(
|
||||
"学习市场规则:这条规则不应写入", actor="ou_read_only", auto_reply=False
|
||||
)
|
||||
watchlist = FeishuCommandService(db).handle_text(
|
||||
"加入自选 600105", actor="ou_read_only", auto_reply=False
|
||||
)
|
||||
pipeline = MarketPipelineService(db, MustNotRunMarket()).run(
|
||||
"close", date(2032, 7, 12), actor="pytest"
|
||||
)
|
||||
assert "只读模式" in rules["content"]
|
||||
assert "只读模式" in watchlist["content"]
|
||||
assert pipeline["status"] == "operations_disabled"
|
||||
assert db.execute(
|
||||
select(AIMemoryEntry).where(AIMemoryEntry.content == "这条规则不应写入")
|
||||
).scalar_one_or_none() is None
|
||||
finally:
|
||||
db.close()
|
||||
monkeypatch.delenv("READ_ONLY_MODE", raising=False)
|
||||
monkeypatch.delenv("MARKET_ANALYSIS_ENABLED", raising=False)
|
||||
get_settings.cache_clear()
|
||||
|
||||
Reference in New Issue
Block a user