repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
Vibe-Trading
agent/tests/test_regime.py
.py
"""Tests for backtest/regime.py and the /correlation/regime route. The math tests pin the Mode 1 semantics of the correlation-regime skill: edge density in [0, 1] with NaN warmup, hysteresis that suppresses dead-band chatter, and strict causality (future bars never change past states). The route tests mirror test_syst...
353
13,627
Vibe-Trading
agent/tests/test_futu_stringified_excel_serial.py
.py
"""Futu Excel serial dates must survive load_dataframe dtype=str.""" from __future__ import annotations import tempfile from pathlib import Path import pandas as pd from src.tools.trade_journal_parsers import load_dataframe, parse_file, parse_futu def test_parse_futu_stringified_excel_serial_date_and_time() -> No...
50
1,326
Vibe-Trading
agent/tests/test_optimizer_causality.py
.py
"""Causality regression tests for portfolio optimizer lookback windows.""" from __future__ import annotations import numpy as np import pandas as pd from backtest.optimizers.base import BaseOptimizer class _LastObservationOptimizer(BaseOptimizer): """Allocate fully to the asset with the best last visible retur...
66
2,238
Vibe-Trading
agent/tests/test_swarm_presets_packaging.py
.py
"""Regression tests for swarm preset discovery. These guard against the v0.1.5 packaging bug (issue #55), where preset YAMLs were declared via ``[tool.setuptools.data-files]`` and ended up at ``<venv>/config/swarm/`` while the loader looked under ``<site-packages>/config/swarm/``. Moving the YAMLs into the ``src.swarm...
211
7,730
Vibe-Trading
agent/tests/test_eastmoney_float_dates.py
.py
"""Eastmoney YYYYMMDD dates from Excel floats must normalize to ISO.""" from __future__ import annotations import pandas as pd from src.tools.trade_journal_parsers import parse_eastmoney def test_parse_eastmoney_float_yyyymmdd_date() -> None: df = pd.DataFrame([{ "成交日期": 20260115.0, "成交时间": "09...
44
1,207
Vibe-Trading
agent/tests/test_options_bs_nonpositive_strike.py
.py
"""Treat non-positive spot/strike as intrinsic in Black-Scholes helpers.""" from __future__ import annotations from backtest.engines.options_portfolio import bs_greeks, bs_price def test_bs_price_zero_strike_returns_intrinsic() -> None: # Call with K=0 is deep ITM; intrinsic is max(S-K, 0) == S. assert bs_p...
25
824
Vibe-Trading
agent/tests/test_goal_tools.py
.py
"""Tests for local agent research goal tools.""" from __future__ import annotations import hashlib import json from pathlib import Path from src.agent.skills import SkillsLoader from src.goal import GoalStore from src.tools.goal_tool import ( AddGoalEvidenceTool, GetResearchGoalTool, StartResearchGoalToo...
214
7,643
Vibe-Trading
agent/tests/test_remember_tool_security.py
.py
"""Security regressions for RememberTool persistent memory writes.""" from __future__ import annotations import json from pathlib import Path from src.memory.persistent import PersistentMemory from src.tools.remember_tool import RememberTool def test_remember_rejects_memory_type_path_traversal(tmp_path: Path) -> N...
41
1,426
Vibe-Trading
agent/tests/test_user_state_paths.py
.py
"""User-level state directory resolution (issue #904). Session/run/upload history must live under the runtime root (``~/.vibe-trading`` by default), never relative to the installed code. """ from __future__ import annotations from pathlib import Path import pytest from src.config.paths import get_runtime_root de...
267
8,448
Vibe-Trading
agent/tests/test_content_filter_e2e.py
.py
"""E2E content-filter resilience: detection -> skip -> ratio -> warning -> trace. Simulates a full agent run where semiconductor/geopolitics news triggers DashScope/Qwen content moderation on some LLM calls (e.g. event-driven backtest on 159516.SZ). Verifies the entire pipeline: 1. Run completes successfully despite...
221
7,475
Vibe-Trading
agent/tests/test_research_reports_tool.py
.py
"""Tests for get_research_reports: success + error envelopes, HTTP mocked. Eastmoney is mocked at ``get_json`` (imported into the tool module) and THS at ``throttled_get`` (imported as ``research_reports_tool.throttled_get``), so no test reaches a live endpoint. """ from __future__ import annotations import json fro...
229
8,416
Vibe-Trading
agent/tests/test_mt5_loader_week_month_reject.py
.py
"""MT5 loader must map week/month tokens and never rewrite unknown intervals to daily.""" from __future__ import annotations from unittest.mock import MagicMock, patch from backtest.loaders.mt5_loader import DataLoader, _INTERVAL_MAP def test_week_and_month_tokens_map_like_connector() -> None: assert _INTERVAL...
38
1,297
Vibe-Trading
agent/tests/test_constraints.py
.py
"""Tests for the composable weight-constraint layer (Portfolio Studio step 2).""" from __future__ import annotations import numpy as np import pandas as pd import pytest from backtest.constraints import ( GroupExposure, MaxWeight, MinWeight, apply_constraints_frame, load_constraints, ) def _fra...
211
8,407
Vibe-Trading
agent/tests/test_forex_engine.py
.py
"""Tests for ForexEngine market rules. Validates: - 24x5: no restrictions on direction or timing - Zero explicit commission (cost via spread) - Spread-based slippage - Micro-lot rounding (1000 units) - Swap (overnight rollover) - Symbol normalization - Pip value detection """ from __future__ import anno...
281
9,735
Vibe-Trading
agent/tests/test_fundamentals_pit.py
.py
from __future__ import annotations import sys from types import ModuleType import pandas as pd import pytest from backtest.loaders import fundamentals_loader def _install_schema_stub(monkeypatch: pytest.MonkeyPatch) -> None: schema = ModuleType("backtest.loaders._fundamental_schema") schema.SEC_CONCEPT_MAP...
369
11,450
Vibe-Trading
agent/tests/test_symbol_search_tool.py
.py
"""Tests for the search_symbol tool. All HTTP is mocked at the client functions the tool imports (``eastmoney_client.get_json``, ``yahoo_client.search``, ``sec_edgar_client.cik_for``), so no test ever reaches a live endpoint. """ from __future__ import annotations import json from unittest.mock import patch from sr...
437
16,311
Vibe-Trading
agent/tests/test_shadow_codegen_security.py
.py
"""Security tests for Shadow Account code generation.""" from __future__ import annotations import ast import uuid import numpy as np import pandas as pd import pytest from backtest.runner import _load_module_from_file from src.shadow_account.codegen import render_signal_engine, validate_generated from src.shadow_a...
164
5,813
Vibe-Trading
agent/tests/test_alphavantage_interval_reject.py
.py
"""Alpha Vantage must reject non-daily intervals instead of silently returning day bars.""" from __future__ import annotations from unittest.mock import patch from backtest.loaders import alphavantage_loader as av def test_unsupported_interval_does_not_hit_api(monkeypatch) -> None: """Runner ``1H`` must not fa...
44
1,573
Vibe-Trading
agent/tests/test_korea_equity_engine.py
.py
"""Tests for KoreaEquityEngine (KRX: KOSPI / KOSDAQ) market rules. Validates: - Long-only by construction: allow_short is refused, never mis-modelled - Same-day sell is ALLOWED (no T+1 — unlike China A-share / India delivery) - KRX tick grid (호가가격단위) and the published limit-price arithmetic - ±30% band derived...
324
13,718
Vibe-Trading
agent/tests/test_returns_gaps_and_infinities.py
.py
"""bar_returns must not change behaviour for gapped positive series. #872 replaced ``close.pct_change().fillna(0.0)`` with :func:`bar_returns` and claimed results for strictly positive series are bit-identical. That claim was verified only on gapless series. On the pinned pandas (``>=2.0,<3.0``) ``pct_change`` default...
183
7,204
Vibe-Trading
agent/tests/test_openai_codex.py
.py
"""Tests for the OpenAI Codex OAuth provider adapter.""" from __future__ import annotations import json import time from pathlib import Path from types import SimpleNamespace import pytest from src.providers import llm as llm_mod from src.providers.chat import ProviderStreamError from src.providers.openai_codex imp...
565
18,464
Vibe-Trading
agent/tests/test_cli_interactive.py
.py
"""Tests for the interactive CLI scaffolding. Covers: * Slash-router fuzzy matching and exact lookup * ``cli.main`` routing helpers (interactive detection, max-iter extraction) * ``cli.input._has_unbalanced_brackets`` (multi-line Enter semantics) * The bottom hint-bar renderer * Tool-event row rendering * ``cli.input...
633
24,737
Vibe-Trading
agent/tests/test_autopilot_phase3.py
.py
"""Tests for Research Autopilot Phase 3 tools. Covers ``scaffold_signal_engine`` (contract-correct stub generation) and ``link_autopilot_backtest`` (run-card metrics -> hypothesis link) in ``src.tools.autopilot_tool``. """ from __future__ import annotations import importlib.util import inspect import json from pathl...
265
8,958
Vibe-Trading
agent/tests/test_swarm_worker_report.py
.py
"""Tests for swarm worker report.md → summary handoff.""" from __future__ import annotations from pathlib import Path from src.swarm.worker import _preview_tool_arguments, _resolve_summary, _best_summary def test_resolve_summary_reads_report_md(tmp_path: Path) -> None: """When report.md exists in artifact dir,...
79
2,898
Vibe-Trading
agent/tests/test_fetch_sina_penalties.py
.py
"""ashare-pre-st-filter / fetch_sina_penalties.py 单元测试。 覆盖 CR P0/P1 修复点: - HTMLParser 解析正确性(替代灾难性回溯正则) - event_type 结构化提取(不会把"公告日期"误识别) - subject_normalized 主体识别 + 优先级 - 日期过滤边界 - HTTP 失败时 fetch_penalty_list 返回 fallback JSON - _validate_stockid 输入校验 """ from __future__ import annotations import importlib.util from pa...
469
20,354
Vibe-Trading
agent/tests/test_india_backtest_smoke.py
.py
"""End-to-end smoke test: backtest runs on Indian (NSE) symbols. Drives ``IndiaEquityEngine`` so strategies can run on NSE/BSE data with the India cost stack. This test feeds NSE bars through a fake loader + trivial long signal and asserts: 1. The backtest completes and emits metrics + a run card. 2. India tradin...
97
3,155
Vibe-Trading
agent/tests/test_alpha_bench_strict_cli.py
.py
"""Tests for the ``alpha bench --strict`` CLI wiring (issue #773).""" from __future__ import annotations import argparse import json import pytest from src.factors import cli_handlers def _ns(**overrides): base = dict( zoo="alpha101", universe="csi300", period="2020-2025", top=...
249
8,058
Vibe-Trading
agent/tests/test_futu_excel_serial_dates.py
.py
"""Futu Date/Time Excel serial floats must normalize to ISO datetime.""" from __future__ import annotations import pandas as pd from src.tools.trade_journal_parsers import parse_futu def test_parse_futu_excel_serial_date_and_time() -> None: # Excel serial 45321.0 + 0.375 day = 2024-01-30 09:00:00 df = pd.D...
64
1,699
Vibe-Trading
agent/tests/test_mcp_oauth_schema.py
.py
"""Unit tests for the MCP OAuth schema + ``_build_client`` OAuth wiring. Covers: * ``MCPOAuthConfig`` / ``MCPServerConfig.auth`` pydantic round-trip (camelCase and snake_case keys) and the seeded Robinhood config. * Validator rejections: OAuth requires https, auth and static headers are mutually exclusive, stdio ...
317
11,437
Vibe-Trading
agent/tests/test_run_card.py
.py
"""Tests for Trust Layer run card generation.""" from __future__ import annotations import hashlib import json from pathlib import Path import pandas as pd from backtest.run_card import write_run_card from src.core.runner import Runner def test_config_hash_is_deterministic_independent_of_key_order(tmp_path: Path)...
355
12,517
Vibe-Trading
agent/tests/test_swarm_grounding.py
.py
"""Unit tests for the swarm grounding module. Network-touching paths (the actual loader fetch) are exercised through a monkeypatched stub so the suite stays offline; symbol extraction and the markdown formatter are pure-function tests. """ from __future__ import annotations import threading from datetime import date...
333
12,755
Vibe-Trading
agent/tests/test_mandate_enforcement.py
.py
"""Mandate enforcement gate tests (SPEC.md Mandate Enforcement §3–§6). Parametrized per limit: each case submits an order breaching exactly one limit and asserts a refusal carrying the breach; one in-mandate case asserts the order forwards through to the underlying mock MCP tool. Universe market-cap/liquidity floors a...
589
23,175
Vibe-Trading
agent/tests/test_financial_rigor_benford_inf.py
.py
"""Regression test for benford_check handling infinite values in financial_rigor_tool. Locks out a bug where benford_check crashed with OverflowError: cannot convert float infinity to integer when input values list contained inf or -inf. """ from src.tools.financial_rigor_tool import benford_check def test_benford_...
20
780
Vibe-Trading
agent/tests/test_alpha_bench_qfq.py
.py
"""Regression: CSI300 bench prices must be corporate-action adjusted. ``pro.daily`` returns raw prices, so a close-to-close return taken across an ex-date spans the mechanical drop of a split or bonus issue. Measured against Tushare's own ``pct_chg`` over 2020-2024: 300750.SZ on 2023-04-26 reads -41.82% raw against a ...
135
5,223
Vibe-Trading
agent/tests/test_stock_news_tool.py
.py
"""Tests for the stock-news tool. No request leaves the process: the Eastmoney HTTP boundary (:func:`backtest.loaders.eastmoney_client.throttled_get_json`) and the Yahoo :func:`backtest.loaders.yahoo_client.search_news` helper are mocked so the real client + tool parsing run fully offline. """ from __future__ import ...
246
8,802
Vibe-Trading
agent/tests/test_cli_swarm_run_args.py
.py
"""Regression tests for ``--swarm-run`` argument handling.""" from __future__ import annotations from unittest.mock import patch import pytest def test_swarm_run_rejects_extra_tokens(capsys: pytest.CaptureFixture[str]) -> None: """Extra vars tokens must fail explicitly instead of being dropped.""" from cli...
65
2,262
Vibe-Trading
agent/tests/test_ccxt_loader_proxy.py
.py
"""Regression tests for CCXT proxy environment handling.""" from __future__ import annotations import ccxt from backtest.loaders.ccxt_loader import DataLoader class _FakeExchange: def __init__(self, config): self.config = config def _clear_proxy_env(monkeypatch): for name in ( "HTTP_PROXY...
65
1,843
Vibe-Trading
agent/tests/test_distribution_skill_manifest.py
.py
"""Keep the packaged agent skill's capability counts in sync with source.""" from __future__ import annotations import ast import re from pathlib import Path AGENT_ROOT = Path(__file__).resolve().parents[1] MANIFEST_PATH = AGENT_ROOT / "SKILL.md" SKILLS_DIR = AGENT_ROOT / "src" / "skills" ZOOS_DIR = AGENT_ROOT / "s...
122
4,471
Vibe-Trading
agent/tests/test_etoro_runtime.py
.py
"""Tests for eToro connector runtime status surfaced through /live/status.""" from __future__ import annotations from pathlib import Path import pytest from fastapi.testclient import TestClient import api_server pytestmark = pytest.mark.unit def _client(tmp_path: Path, monkeypatch) -> TestClient: monkeypatch...
153
5,455
Vibe-Trading
agent/tests/test_indicator_period_nonpositive.py
.py
"""Reject non-positive MA periods in run-detail indicator overlays.""" from __future__ import annotations import json from pathlib import Path from src.ui_services import build_indicator_series, infer_indicator_periods def _rows(): return [ { "time": f"2020-01-0{i}", "code": "AA...
48
1,243
Vibe-Trading
agent/tests/test_qveris_minute_granularity_tokens.py
.py
"""QVeris must rank minute intervals as intraday, not fall through to daily.""" from __future__ import annotations from backtest.loaders.qveris_loader import _granularity_tokens, _select_capabilities def _sample_results() -> list[dict]: return [ { "tool_id": "daily-ohlcv", "name"...
48
1,473
Vibe-Trading
agent/tests/test_ccxt_perpetual_loader.py
.py
"""Historical Binance USD-M data-contract tests.""" from __future__ import annotations import hashlib import json import pytest import pandas as pd from backtest.loaders.base import make_loader_cache_key from backtest.loaders.ccxt_loader import _parse_ccxt_symbol, _validate_bracket_artifact def _hourly_rows(opens...
380
13,936
Vibe-Trading
agent/tests/test_agent_loop_no_assistant_prefill.py
.py
"""Regression test: agent loop must not end messages with assistant prefill. Claude Opus 4.8+ (and other new Anthropic models) reject API requests when the conversation ends with an assistant-role message, because the API treats it as an "assistant prefill" which these models no longer support. Two code paths in Agen...
147
4,789
Vibe-Trading
agent/tests/test_security_auth_api.py
.py
"""Security regression tests for API authentication boundaries.""" from __future__ import annotations import ipaddress from types import SimpleNamespace import pytest from fastapi.testclient import TestClient import api_server def _remote_client() -> TestClient: """Return a TestClient that simulates a non-loo...
735
25,665
Vibe-Trading
agent/tests/test_doc_reader_unicode_page_dashes.py
.py
"""Unicode dash page ranges must parse like ASCII hyphens, not yield empty.""" from __future__ import annotations import pytest from src.tools.doc_reader_tool import _parse_pages def test_en_dash_page_range_parses() -> None: assert _parse_pages("1\u201310", 20) == list(range(10)) def test_em_dash_page_range_...
29
748
Vibe-Trading
agent/tests/test_tencent_loader.py
.py
"""Tests for Tencent's daily-only market-data contract.""" from __future__ import annotations import json import urllib.request import pandas as pd from backtest.loaders import tencent_loader class _FakeResponse: def __init__(self, payload: str) -> None: self._payload = payload def read(self) -> ...
120
3,115
Vibe-Trading
agent/tests/test_akshare_interval_reject.py
.py
"""AKShare a-share fetch must not silently remap unknown intervals to daily.""" from __future__ import annotations from unittest.mock import MagicMock import pytest from backtest.loaders.akshare_loader import DataLoader, _INTERVAL_MAP_DAILY def test_akshare_a_share_rejects_minute_interval() -> None: ak = Magi...
38
1,196
Vibe-Trading
agent/tests/test_mcp_alpha_zoo_contract.py
.py
from __future__ import annotations import asyncio import datetime as dt import inspect import json import re from pathlib import Path import mcp_server from src.tools.alpha_bench_tool import AlphaBenchTool from src.tools.alpha_zoo_tool import AlphaZooTool from src.tools import alpha_bench_tool as alpha_bench_module ...
255
8,475
Vibe-Trading
agent/tests/test_ths_stringified_excel_serial.py
.py
"""Tonghuashun Excel serials must survive load_dataframe dtype=str.""" from __future__ import annotations import tempfile from pathlib import Path import pandas as pd from src.tools.trade_journal_parsers import load_dataframe, parse_file, parse_tonghuashun def test_parse_tonghuashun_stringified_excel_serial() -> ...
50
1,445
Vibe-Trading
agent/tests/test_options_smile_consistency.py
.py
"""Regression: a leg must be marked at the vol it was opened at. The engine applied the IV smile when pricing an opening leg but marked every position at the flat at-the-money vol, so a position booked a profit the instant it existed. Measured on a 30-day call at ``skew=-0.15``, ``curvature=0.05``, ``S=100``, ``r=0``:...
181
6,278
Vibe-Trading
agent/tests/test_orderbook_depth_tool.py
.py
"""Tests for orderbook_depth_tool: validation, spread/imbalance/impact math, edge cases. No test ever reaches a live exchange. The tool isolates the network call in its own module-level function, ``_fetch_raw_book`` — see the tool's module docstring — and every test here monkeypatches exactly that name on the ``orderb...
412
17,018
Vibe-Trading
agent/tests/test_options_routes.py
.py
"""API tests for ``POST /options/payoff`` + ``GET /options/chain``. Deterministic by construction — no network anywhere: * the payoff route runs the REAL ``OptionsPayoffTool`` (pure math), so happy path, multi-leg, validation and tool-error mapping are exercised end to end; * greeks parity is asserted against a dir...
230
7,995
Vibe-Trading
agent/tests/test_local_loader.py
.py
"""Tests for the config-driven local data loader.""" from __future__ import annotations import logging from pathlib import Path import pandas as pd import pytest import yaml import backtest.loaders.local_loader as local_loader def _configure(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, sources: list[dict]) ->...
298
9,060
Vibe-Trading
agent/tests/test_sdk_connectors.py
.py
"""Tests for the direct-SDK trading connectors (Tiger, Longbridge). Layer A is read-only; these tests exercise the parts that do not require the optional broker SDKs or live credentials: profile registration, the paper/live identity guard, config resolution, read/write classification, secret redaction, and the service...
798
33,178
Vibe-Trading
agent/tests/test_options_chain_tool.py
.py
"""Tests for the get_options_chain tool. All HTTP is mocked at ``yahoo_client.get_options`` (the client function the tool imports), so no test ever reaches a live Yahoo endpoint. """ from __future__ import annotations import json from unittest.mock import patch from src.tools import options_chain_tool as oc def _...
145
5,207
Vibe-Trading
agent/tests/test_system_routes.py
.py
"""Route-level contracts for the system endpoints. Exercises the REST surface mounted by ``register_system_routes``: ``/live`` + ``/ready`` (VT-008 liveness/readiness split) and the hardened ``/correlation`` endpoint (VT-005: auth + per-IP rate limit + masked errors). Each test drives the app through ``TestClient``. ...
207
7,868
Vibe-Trading
agent/tests/test_ccxt_interval_map.py
.py
"""CCXT interval map must keep weekly/monthly tokens (not silent daily).""" from __future__ import annotations from backtest.loaders.ccxt_loader import _INTERVAL_MAP def test_ccxt_interval_map_keeps_week_and_month() -> None: assert _INTERVAL_MAP["1W"] == "1w" assert _INTERVAL_MAP["1M"] == "1M" assert _I...
21
650
Vibe-Trading
agent/tests/test_strategy_store.py
.py
"""Unit tests for the Strategy Development Manager store and tools.""" from __future__ import annotations import json import uuid import pytest from src.strategy_store.models import ( Artifact, ArtifactStatus, ArtifactType, BenchResult, BenchCategory, DecaySnapshot, DecaySignal, Mode...
1,398
53,555
Vibe-Trading
agent/tests/test_skill_reference_links.py
.py
"""Regression tests: every ``references/`` link in data-source SKILL.md files resolves through the ``read_file`` tool. Background: ``read_file`` roots reads at the bundled ``skills/`` directory, so a link must carry the skill-name prefix (e.g. ``tushare/references/...``) to be reachable. Bare ``references/...
111
4,024
Vibe-Trading
agent/tests/test_financial_rigor_tool.py
.py
"""Tests for the ``financial_rigor`` agent tool. Covers the pure core routines (exact decimal, safe arithmetic, valuation math, cross-validation, Benford, three-scenario), the tool's JSON-Schema contract, ``execute`` happy/error paths, calc injection rejection, and that the tool is auto-discovered into the default reg...
268
10,467
Vibe-Trading
agent/tests/test_cli_provider_login.py
.py
from __future__ import annotations from unittest.mock import patch from cli import _legacy def test_provider_login_explains_docker_tty_requirement(capsys) -> None: """An EOF from the OAuth prompt should point Docker users to a TTY command.""" with patch( "src.providers.openai_codex.login_openai_cod...
22
659
Vibe-Trading
agent/tests/test_pattern_tool.py
.py
"""Tests for the chart pattern recognition tool. Covers the deterministic pattern-detection functions in ``src.tools.pattern_tool`` (peaks/valleys, candlestick, support/resistance, trend slope, head-and-shoulders, double top/bottom, triangle, broadening) and the ``run_pattern`` dispatch + error paths. """ from __futu...
328
11,627
Vibe-Trading
agent/tests/test_iwencai_tool.py
.py
"""Tests for the iWenCai (问财) natural-language A-share search tool. No request leaves the process: the HTTP boundary (:func:`backtest.loaders._http.throttled_get_json`, imported into the tool module) is mocked so the real auth/parsing/envelope path runs offline. """ from __future__ import annotations import json fro...
139
5,387
Vibe-Trading
agent/tests/test_swarm_preset_inspect.py
.py
"""Tests for swarm preset inspection and static validation.""" from __future__ import annotations from pathlib import Path from src.swarm import presets def test_all_bundled_presets_inspect_without_errors() -> None: """Bundled presets should have valid agent/task references and DAGs.""" for entry in preset...
66
2,034
Vibe-Trading
agent/tests/test_channels_api.py
.py
"""API contracts for IM channel runtime controls.""" from __future__ import annotations import json from pathlib import Path from fastapi.testclient import TestClient import api_server class FakeSessionService: """SessionService placeholder for channel status tests.""" def _client( tmp_path: Path, m...
102
3,514
Vibe-Trading
agent/tests/test_entities_spine.py
.py
"""Unit tests for the entity and irregular cash-flow spine.""" from __future__ import annotations import dataclasses from datetime import date, datetime import pytest from src.entities.cashflow import ( CashFlow, CashFlowSeries, CurrencyMismatchError, normalize_kind, ) from src.entities.ingest impor...
1,055
39,073
Vibe-Trading
agent/tests/test_run_manifest_wiring.py
.py
"""The run manifest must actually be produced by a run. `build_run_manifest` existed with no caller, so nothing in the system could answer "what methodology produced that number". These tests pin the wiring, and pin the two properties that make the record safe to keep: it stores no prompt text, and it can never break ...
133
4,712
Vibe-Trading
agent/tests/test_ui_services.py
.py
"""Tests for UI-oriented run reconstruction services.""" from __future__ import annotations import json from pathlib import Path from types import SimpleNamespace import pandas as pd import pytest import backtest.runner as runner from backtest.loaders.base import NoAvailableSourceError from src.ui_services import r...
391
12,060
Vibe-Trading
agent/tests/test_cli_update.py
.py
"""Tests for the ``vibe-trading update`` self-upgrade command.""" from __future__ import annotations import json import pytest import requests from cli import _legacy from cli.commands import update as update_mod # --------------------------------------------------------------------------- # Helpers # -----------...
299
12,090
Vibe-Trading
agent/tests/test_fmp_daily_aliases.py
.py
"""FMP daily gate must accept connector-style daily aliases like sina/tencent.""" from __future__ import annotations from unittest.mock import patch from backtest.loaders import fmp_loader as fl from backtest.loaders.fmp_loader import DataLoader def _body(symbol, bars): return {"symbol": symbol, "historical": ...
36
1,294
Vibe-Trading
agent/tests/test_agent_loop_dsml_tool_calls.py
.py
"""Regression tests for DSML textual tool calls in the ReAct loop.""" from __future__ import annotations import json from pathlib import Path from typing import Any from src.agent.loop import AgentLoop from src.agent.progress import emit_progress from src.agent.tools import BaseTool, ToolRegistry from src.memory.per...
131
4,160
Vibe-Trading
agent/tests/test_readme_counts.py
.py
"""The five READMEs must agree with the code about how much of everything ships. Every number these tests check is one a reader uses to decide whether the project does what they need — how many MCP tools they get, how many skills, how many backtest engines. They drift silently: a feature lands, the English README is u...
450
18,062
Vibe-Trading
agent/tests/test_scheduled_research_store.py
.py
"""Tests for the scheduled research job store. Covers: happy-path CRUD, atomic persistence, invalid schedule rejection, idempotent upsert, and empty-store behaviour. """ from __future__ import annotations import json import time from pathlib import Path import pytest from src.scheduled_research.models import ( ...
400
15,707
Vibe-Trading
agent/tests/test_llm_reasoning_effort.py
.py
"""LANGCHAIN_REASONING_EFFORT delivery per provider. The setting has two mutually exclusive delivery paths: * Relays that require an opt-in (OpenRouter, Requesty) receive ``extra_body={"reasoning": {"effort": ...}}``. * ChatOpenAI-compatible providers receive a top-level ``reasoning_effort``. Its ``gpt-5.6-*`` mo...
581
21,876
Vibe-Trading
agent/tests/test_binance_fallback.py
.py
"""Regression coverage for the dedicated Binance crypto fallback.""" from __future__ import annotations import pandas as pd from backtest.loaders.registry import FALLBACK_CHAINS from src import market_data def test_market_data_falls_back_from_okx_to_binance() -> None: calls: list[str] = [] def resolver(so...
42
1,224
Vibe-Trading
agent/tests/test_env_schema.py
.py
"""Comprehensive tests for EnvConfig schema and accessor singleton. Covers: - Default values for every sub-model - Type coercion (int, float, bool) - Validation errors on bad input - Environment variable override - API key alias resolution - Singleton caching and reset - Thread safety - _parse_bool utility - get_env_o...
539
20,404
Vibe-Trading
agent/tests/test_llm.py
.py
"""Tests for LLM provider mapping and JSON extraction.""" from __future__ import annotations import os from types import SimpleNamespace from unittest.mock import patch import pytest from src.providers.capabilities import ( get_llm_credentials, get_provider_capabilities, provider_env_names, ) from src.p...
870
32,840
Vibe-Trading
agent/tests/test_enforcement_l6.py
.py
"""L6 — real Robinhood catalog + quantity→quote pricing (SPEC.md §4, §7.5). Covers: * The frozen canonical Robinhood read/write catalog. * The extractor's finalized ``place_equity_order`` field mapping (symbol/side/size, unknown keys ignored, ambiguity → ``None``). * Quantity-only quote derivation: broker ``get_equ...
276
11,016
Vibe-Trading
agent/tests/test_mcp_stdio_integration.py
.py
"""Integration tests: full-stack MCP client path with a real stdio subprocess. These tests spawn an actual fake MCP server process (agent/tests/fixtures/ fake_mcp_server.py) over stdio and exercise the entire path: load_agent_config() -> build_registry(agent_config=...) -> MCPServerAdapter ...
220
8,152
Vibe-Trading
agent/tests/test_rebalance_notes.py
.py
"""Tests for the rebalance notes module.""" from __future__ import annotations import json import numpy as np import pandas as pd import pytest from backtest.rebalance_notes import ( compute_rebalance_notes, render_rebalance_notes_markdown, write_rebalance_notes, ) def _frame(rows, codes=("A", "B")): ...
114
3,412
Vibe-Trading
agent/tests/test_lockup_expiry_integer_code.py
.py
"""Test suite for LockupExpiryTool non-string symbol code handling.""" import json import pytest from src.tools.lockup_expiry_tool import LockupExpiryTool def test_lockup_expiry_tool_integer_code_handling(): """Verify LockupExpiryTool.execute handles integer stock codes without raising AttributeError on .strip()...
15
497
Vibe-Trading
agent/tests/test_get_market_data_size.py
.py
"""Regression test for P07 — get_market_data must bound its per-symbol output. Pre-fix: every row of every symbol was emitted, so "1 symbol, 1 year, daily" (~251 rows) already breached the MCP token cap and had to spool to a file. Post-fix (G3): a `max_rows` cap (default 250) returns an *even-stride* downsample (every...
121
4,738
Vibe-Trading
agent/tests/test_run_card_content_filter.py
.py
"""Tests that content_filter_warnings from config flows through to run_card.json warnings.""" from __future__ import annotations import json from pathlib import Path import pandas as pd from backtest.run_card import write_run_card def test_content_filter_warnings_surfaced_in_run_card(tmp_path: Path) -> None: ...
188
5,975
Vibe-Trading
agent/tests/test_responses_stream_compat.py
.py
"""Regression tests for OpenAI-compatible Responses event streams.""" from __future__ import annotations import asyncio from contextlib import contextmanager from typing import Any, Iterator import pytest from langchain_core.messages import HumanMessage from src.providers.llm import ChatOpenAIWithReasoning class ...
139
4,149
Vibe-Trading
agent/tests/test_dividend_analysis_skill.py
.py
"""Tests for the bundled dividend-analysis skill.""" from __future__ import annotations from pathlib import Path from src.agent.skills import SkillsLoader, _parse_frontmatter SKILL_DIR = Path(__file__).resolve().parents[1] / "src" / "skills" / "dividend-analysis" SKILL_MD = SKILL_DIR / "SKILL.md" def test_divide...
54
1,789
Vibe-Trading
agent/tests/test_margin_trading_prefix_symbol.py
.py
"""Regression test for _extract_code handling prefix-style A-share symbols in margin_trading_tool. Locks out a bug where _extract_code returned None for prefix-style symbols like "sh.600519" or "sz.000001" because token.rpartition(".")[0] extracted the prefix part before the dot. """ from src.tools.margin_trading_too...
21
894
Vibe-Trading
agent/tests/test_engine_robustness.py
.py
"""E2E tests for engine robustness fixes: 1. ffill(limit=5) — long suspensions stay NaN instead of using stale prices 2. All-NaN symbol detection — symbols with no data are dropped with warning 3. Single symbol exception isolation — one symbol crash doesn't kill the backtest 4. Config schema validation — invalid confi...
642
25,040
Vibe-Trading
agent/tests/test_factor_api.py
.py
"""API regressions for the run factor-analysis artifact endpoint.""" from __future__ import annotations import json from pathlib import Path from fastapi.testclient import TestClient import api_server from src.api import runs_routes def _client(tmp_path: Path, monkeypatch) -> TestClient: monkeypatch.setattr(a...
347
12,770
Vibe-Trading
agent/tests/test_channels_runtime.py
.py
"""Contracts for the IM channel runtime wiring.""" from __future__ import annotations import asyncio import base64 from pathlib import Path from typing import Any import pytest from src.channels.bus.events import InboundMessage, OutboundMessage from src.channels.bus.queue import MessageBus from src.channels.manager...
896
32,235
Vibe-Trading
agent/tests/test_eastmoney_excel_day_serial.py
.py
"""Eastmoney Excel day-count serials must normalize to ISO dates.""" from __future__ import annotations import tempfile from pathlib import Path import pandas as pd from src.tools.trade_journal_parsers import load_dataframe, parse_eastmoney, parse_file def test_parse_eastmoney_stringified_excel_day_serial() -> No...
87
2,568
Vibe-Trading
agent/tests/test_session_service_lifecycle.py
.py
"""Session lifecycle invariants: one run per session, honest terminal states.""" from __future__ import annotations import asyncio from pathlib import Path import pytest from src.session.events import EventBus from src.session.models import Attempt, AttemptStatus from src.session.service import SessionBusyError, Se...
316
12,178
Vibe-Trading
agent/tests/test_market_data.py
.py
"""Tests for the shared market-data helper layer. ``src.market_data`` is the source-resolution + normalization layer shared by the MCP server and the agent ``get_market_data`` tool. It shipped (with the #270 global data layer) without dedicated tests. These cover the network-free logic: source detection, row capping, ...
438
13,989
Vibe-Trading
agent/tests/test_trade_journal_parser_to_float_nan.py
.py
"""Regression test for _to_float handling of NaN strings in trade journal parsers. Locks out a bug where _to_float returned float("nan") (where math.isnan is True) when parsing "nan" or "NaN" cell strings instead of returning the specified default float. """ import math from src.tools.trade_journal_parsers import _to...
23
853
Vibe-Trading
agent/tests/test_mcp_goal_session_contract.py
.py
"""The MCP goal tools must not ask the model to invent a session id. Issue #885, second half: the in-process tool registry injects the host session and keeps ``session_id`` optional, while the MCP entry points declared it required. The two paths declared opposite contracts, and on the MCP path the model was asked for ...
85
2,777
Vibe-Trading
agent/tests/test_cli_connector_env.py
.py
"""Regression (#901): the ``connector`` CLI path must load ``~/.vibe-trading/.env``. ``EnvConfig`` reads only ``os.environ``; ``_ensure_dotenv()`` is what populates it from ``~/.vibe-trading/.env``. ``main()`` routes the ``connector`` group straight to ``_dispatch_connector`` without the interactive TUI's preflight, s...
118
4,317
Vibe-Trading
agent/tests/test_sdk_order_gate.py
.py
"""Tests for the direct-SDK live order gate + service order routing (Layer B/C). The gate is the red-line code: live orders must pass mandate + kill-switch + fail-closed pre-trade checks before any broker call. These tests use a fake connector module + a stubbed mandate/halt so they need no broker SDK. """ from __fut...
426
17,116
Vibe-Trading
agent/tests/test_paper_capped_connectors_refuse_live.py
.py
"""Structural gate: paper-capped connectors refuse a live order before anything else. ``docs/paper-trading/PLAN.md`` promised a CRITICAL grep gate called ``test_paper_adapters_no_live_endpoints.py`` over ``src/paper_trading/adapters/``. That layer never shipped — the connector architecture replaced it — so the gate wa...
129
5,476
Vibe-Trading
agent/tests/test_session_events.py
.py
"""Session SSE event buffer recovery tests.""" from __future__ import annotations from src.session.events import EventBus, SSEEvent def test_first_connect_does_not_replay_completed_history_by_default() -> None: bus = EventBus() bus.emit("s1", "tool_call", {"tool": "load_skill"}) assert bus.replay("s1")...
51
1,747
Vibe-Trading
agent/tests/test_mcp_server_http_transport.py
.py
"""Integration test for the Vibe-Trading MCP server's Streamable HTTP transport. Spawns the real ``mcp_server.py --transport http`` and verifies the single ``/mcp`` endpoint behaves per the MCP Streamable HTTP transport: 1. POST ``initialize`` returns a valid JSON-RPC InitializeResult with an ``MCP-Session-Id`` he...
138
4,428
Vibe-Trading
agent/tests/conftest.py
.py
"""Shared fixtures and sys.path setup for all tests.""" from __future__ import annotations import sys from pathlib import Path import pytest # Ensure agent/ is on sys.path so imports like `backtest.*` and `src.*` work. AGENT_DIR = Path(__file__).resolve().parent.parent if str(AGENT_DIR) not in sys.path: sys.pat...
46
1,633