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_reasoning_delta_throttle.py
.py
"""Regression test: reasoning_delta SSE events are throttled. Long DeepSeek/Kimi reasoning streams produce hundreds of chunks. Before the throttle, each chunk emitted one reasoning_delta event, flooding the 500-event session replay ring buffer and evicting the tool_call/text_delta events that reconnect replay depends ...
99
3,641
Vibe-Trading
agent/tests/test_preflight.py
.py
"""Tests for startup preflight checks.""" from __future__ import annotations import sys import requests from src import preflight def _configure_llm_preflight(monkeypatch) -> None: """Install a minimal OpenAI-compatible provider environment for preflight tests.""" import src.providers.llm as llm monk...
157
5,016
Vibe-Trading
agent/tests/test_runtime_runner.py
.py
"""Unit tests for the persistent live-trading runner (SPEC.md §7.5 #2, #7). The runner is exercised with all external dependencies stubbed — no live agent, no broker, no real audit ledger — so these tests assert pure control flow: * tick ordering (halt → expiry → reconcile → invoke → audit), * halt aborts before anyt...
569
18,458
Vibe-Trading
agent/tests/test_principal.py
.py
"""Tests for the session Principal and the auth surface that produces it. The point of these tests is not that a Principal exists. It is that the Principal cannot claim an attribution the authentication layer did not earn -- which is the only thing that makes it better than no principal at all. """ from __future__ im...
219
7,079
Vibe-Trading
agent/tests/test_preset_claim_backing.py
.py
"""CI gate: a swarm preset may not order work its own grants cannot reach. Swarm workers get a strict per-node tool whitelist. ``build_swarm_registry`` projects the full registry down to ``agent_spec.tools`` and merely *logs* a warning for anything it had to drop (``src/tools/__init__.py::_filter_registry``), so a pre...
244
9,226
Vibe-Trading
agent/tests/test_yahoo_loader.py
.py
"""Tests for yahoo_loader: symbol gating, epoch window, frame normalization. All network access is mocked at the loader's ``yahoo_client.get_chart`` import site, so no test ever reaches a live Yahoo endpoint. """ from __future__ import annotations import datetime as dt from unittest.mock import patch import pandas a...
320
11,627
Vibe-Trading
agent/tests/test_eventbus_clear_subscribers.py
.py
"""Regression: EventBus.clear must notify and remove subscribers. The original clear() only removed the buffer but left subscriber queues in self._subscribers. Subscribers would keep receiving heartbeats forever on a cleared session, and future publish() calls would still enqueue to those dead queues. The fix sends a...
108
3,336
Vibe-Trading
agent/tests/test_copilot_provider.py
.py
"""Coverage for the official GitHub Copilot SDK provider.""" from __future__ import annotations import json import threading from pathlib import Path import pytest import api_server # noqa: F401 from src.api import settings_routes from src.providers import capabilities as caps_mod from src.providers import copilot...
251
7,716
Vibe-Trading
agent/tests/test_swarm_store_atomic_write.py
.py
"""Regression tests for P13 — SwarmStore atomic write/read must survive the Windows concurrent-access race (os.replace WinError 5/32) deterministically. The behaviour tests drive the public ``SwarmStore`` API with a fake ``os.replace`` and therefore run on BOTH pre- and post-fix code: - pre-fix ``_atomic_write`` calls...
134
4,559
Vibe-Trading
agent/tests/test_mcp_json_string_args.py
.py
"""MCP list/dict parameters must tolerate JSON-string arguments (issue #987). FastMCP publishes optional list/dict parameters as ``anyOf`` schemas, and some MCP clients (observed with Claude Desktop / Claude Code) do not surface ``anyOf`` to the model as a concrete type — the model then serializes the argument as a JS...
281
10,684
Vibe-Trading
agent/tests/test_cli_continue.py
.py
"""Regression tests for continuing a persisted CLI conversation.""" from __future__ import annotations from pathlib import Path from cli import _legacy from src.agent.trace import TraceWriter def test_repeated_continue_reads_and_appends_one_canonical_trace( tmp_path, monkeypatch ) -> None: """A session con...
58
2,045
Vibe-Trading
agent/tests/test_scheduled_routes.py
.py
"""Route-level contracts for the scheduled research endpoints. Exercises the REST surface mounted by ``register_scheduled_routes``: ``POST /scheduled-runs`` (create), ``GET /scheduled-runs`` (list + filter), and ``DELETE /scheduled-runs/{job_id}`` (cancel). Each test drives the app through ``TestClient`` and asserts t...
412
13,337
Vibe-Trading
agent/tests/test_persistent_memory.py
.py
"""Tests for PersistentMemory: file-based cross-session memory.""" from __future__ import annotations from pathlib import Path import pytest from src.memory.persistent import ( MAX_ENTRY_CHARS, MemoryEntry, PersistentMemory, _coerce_str, _sanitize_body, _tokenize, _truncate_body, ) cla...
561
24,354
Vibe-Trading
agent/tests/test_finnhub_loader.py
.py
"""Tests for finnhub_loader: symbol mapping, payload parsing, auth gating, errors. All HTTP is mocked — no test ever reaches a live Finnhub endpoint. The loader imports ``throttled_get_json`` from :mod:`backtest.loaders._http` into its own namespace, so we monkeypatch that name on the ``finnhub_loader`` module. """ f...
214
8,102
Vibe-Trading
agent/tests/test_investor_lenses_skill.py
.py
"""Structural tests for the ``investor-lenses`` skill. The skill is pure markdown: a router ``SKILL.md`` plus one file per lens under ``references/``. Nothing here executes a lens — these tests guard the properties that silently rot as lenses are added or renamed: * the router is loadable by :class:`SkillsLoader` and...
271
10,738
Vibe-Trading
agent/tests/test_stooq_loader.py
.py
"""Tests for stooq_loader: symbol mapping, CSV parsing, batch isolation, errors. All HTTP is mocked — no test reaches a live Stooq endpoint. The loader imports ``throttled_get`` from :mod:`backtest.loaders._http` into its own namespace, so we monkeypatch that name on the ``stooq_loader`` module. """ from __future__ i...
177
6,171
Vibe-Trading
agent/tests/test_tools_type_value_safety.py
.py
"""Argument type/value safety at tool entrypoints (PR #913). Two rules are enforced here, and the distinction matters: * An **absent** optional argument may fall back to its documented default. * An **explicitly malformed** argument (non-numeric, NaN/Infinity, or an integer too large for a float) must NOT be silent...
500
20,302
Vibe-Trading
agent/tests/test_india_mandate.py
.py
"""India (IN_EQUITY) mandate-enforcement wiring. Confirms the ``in_equity`` asset class flows through the live mandate gate: - An IN_EQUITY order is denied (structural universe breach) when the mandate does not permit it. - It passes the asset-class gate when the mandate permits IN_EQUITY. - The enforcement ...
101
2,914
Vibe-Trading
agent/tests/test_options_pricing_degenerate.py
.py
"""Regression tests for P06 — analyze_options/options_pricing must not return confident `status:"ok"` numbers for degenerate or invalid inputs. Pre-fix: invalid inputs (σ≤0, spot/strike≤0, negative expiry, bad type) and T=0 all returned `status:"ok"`; NaN could leak into the JSON. Post-fix: invalid inputs are rejected...
133
5,481
Vibe-Trading
agent/tests/test_factor_gate_fund_prefix.py
.py
"""Fundamental factor panel gate and runner injection tests.""" from __future__ import annotations import sys import types from typing import Any import pandas as pd import pytest from backtest import runner from src.factors.registry import AlphaMeta def _meta(**overrides: Any) -> dict[str, Any]: base = { ...
204
6,283
Vibe-Trading
agent/tests/test_mt5_connector.py
.py
"""MetaTrader 5 connector tests (Exness-style brokers, Windows-only SDK). Mirrors ``test_sdk_connectors.py`` conventions: the real ``MetaTrader5`` package is never imported (it does not install on CI's ubuntu runner) — every test drives the connector through a ``FakeMT5`` namespace injected at the single ``_client._re...
906
37,351
Vibe-Trading
agent/tests/test_quantlib_tool.py
.py
"""Tests for the quantlib_call tool. The load-bearing tests are the three structural limits. A tool that can reach arbitrary modules, private helpers, or file writers would be a shell by another name, which is precisely what this tool exists to avoid. """ from __future__ import annotations import json import pytest...
266
10,303
Vibe-Trading
agent/tests/test_tushare_loader.py
.py
"""Tests for tushare loader symbol-type routing. Pins #310: tushare daily() only serves A-share stocks. ETF/LOF needs fund_daily(), indices need index_daily(), HK needs hk_daily(). US/crypto are unsupported and should warn+skip. """ from __future__ import annotations import os from unittest.mock import MagicMock im...
474
17,133
Vibe-Trading
agent/tests/test_skills.py
.py
"""Tests for skill loading, frontmatter parsing, and category grouping.""" from __future__ import annotations from pathlib import Path import pytest from src.agent.skills import Skill, SkillsLoader, _parse_frontmatter # --------------------------------------------------------------------------- # _parse_frontmatt...
184
7,351
Vibe-Trading
agent/tests/test_rate_limiter_memory.py
.py
"""Regression: _SlidingWindowRateLimiter must not leak memory on unique keys. The limiter keys on client IP. A burst of unique IPs (a scan, a botnet, a proxy farm) creates one deque per IP in ``_hits``. The original code used ``defaultdict(deque)``, which creates an empty deque on every lookup — even for a key that ...
109
4,206
Vibe-Trading
agent/tests/test_tushare_fallbacks.py
.py
"""Unit tests for optional Tushare fallback adapters. The Tushare client is replaced by small in-memory fakes, so these tests never touch the network or require a real token. """ from __future__ import annotations from types import SimpleNamespace from unittest.mock import patch from src.tools import tushare_fallba...
110
3,927
Vibe-Trading
agent/tests/test_mcp_client_adapter.py
.py
"""Unit tests for the MCP client adapter core.""" from __future__ import annotations import json import logging from dataclasses import dataclass from datetime import date, datetime, timezone from decimal import Decimal from enum import Enum from pathlib import Path from typing import Any from uuid import UUID impor...
782
24,852
Vibe-Trading
agent/tests/test_stock_profile_tool.py
.py
"""Tests for the get_stock_profile tool. All HTTP is mocked at :func:`get_quote_summary` as it is imported into the tool module, so no test touches a live Yahoo Finance endpoint. """ from __future__ import annotations import json from unittest.mock import patch from src.tools import stock_profile_tool as sp def _...
180
6,464
Vibe-Trading
agent/tests/test_swarm_m1_config_plumbing.py
.py
"""M1 — SWARM external MCP tools: config plumbing regression tests. Covers requirements R-03, R-05, R-09 and tests T-01, T-02, T-03 in ``docs/2026-05-25_swarm_mcp_tools_tdd.md``. M1 lands the parameter wiring *only* — no remote tool registry assembly, no boot-time loading. Those land in M2 / M3 and bring their own tes...
188
6,783
Vibe-Trading
agent/tests/test_research_papers_tool.py
.py
"""Tests for research_papers: search, read, and the paper-to-factor brief. Every test mocks ``research_papers_tool.throttled_get``, so nothing here reaches arXiv or OpenAlex. The XML and JSON fixtures are trimmed copies of real responses captured from the live endpoints (including their quirks: the LaTeX ``$1.06$`` / ...
964
42,207
Vibe-Trading
agent/tests/test_lockup_expiry_tool.py
.py
"""Tests for the Eastmoney-backed lockup-expiry (限售解禁) tool. No request ever leaves the process: the success/shape paths mock the shared client (:mod:`backtest.loaders.eastmoney_client`), and the end-to-end path mocks the frozen HTTP boundary (``throttled_get_json``) so the real client routing and this tool's parsing ...
166
6,350
Vibe-Trading
agent/tests/test_sse_ticket_and_headers.py
.py
"""VT-003 / VT-006 regression tests: SSE tickets, security headers, log redaction.""" from __future__ import annotations import logging import pytest from fastapi.testclient import TestClient import api_server from src.api import security def _remote_client() -> TestClient: """Return a TestClient that simulat...
269
9,882
Vibe-Trading
agent/tests/test_sina_loader.py
.py
"""Tests for the Sina US-equity daily OHLCV loader. All HTTP is mocked at :func:`backtest.loaders._http.throttled_get` (imported into the loader module as ``sina_loader.throttled_get``), so no test touches a live Sina endpoint. """ from __future__ import annotations from types import SimpleNamespace from unittest.mo...
225
7,305
Vibe-Trading
agent/tests/test_qveris_mcp.py
.py
"""Contract tests for issue #964 — QVeris tools exposed over MCP. The three QVeris agent tools (``qveris_search`` / ``qveris_inspect`` / ``qveris_execute``) must be registered on the FastMCP server and follow the key-gated contract of ``get_macro_series`` / ``iwencai_search``: an unconfigured install receives an actio...
132
5,254
Vibe-Trading
agent/tests/test_ths_excel_serial_dates.py
.py
"""Tonghuashun 成交时间 Excel serial floats must normalize to ISO datetime.""" from __future__ import annotations import pandas as pd from src.tools.trade_journal_parsers import parse_tonghuashun def test_parse_tonghuashun_excel_serial_datetime() -> None: # Excel serial 45321.375 = 2024-01-30 09:00:00 df = pd....
64
1,921
Vibe-Trading
agent/tests/test_agent_grounding.py
.py
"""Regression coverage for identity and numeric grounding (#887, #886).""" from __future__ import annotations import json from pathlib import Path from types import SimpleNamespace from typing import Any, Callable import pytest from src.agent.context import ContextBuilder from src.agent.grounding import ( Groun...
2,127
73,655
Vibe-Trading
agent/tests/test_get_fundamentals_tool.py
.py
"""Tests for the fundamental data tool facade and first fundamental factors.""" from __future__ import annotations import json import sys import types import numpy as np import pandas as pd import pytest from src.tools.get_fundamentals_tool import GetFundamentalsTool def _install_loader(monkeypatch: pytest.Monkey...
142
4,527
Vibe-Trading
agent/tests/test_longbridge_loader_daily_week_aliases.py
.py
"""Longbridge loader interval map must accept connector-style 1d/1w aliases.""" from __future__ import annotations from types import SimpleNamespace import pytest from backtest.loaders import longbridge as loader_mod from backtest.loaders.base import NoAvailableSourceError def test_lowercase_1d_and_1w_map_like_pr...
35
1,350
Vibe-Trading
agent/tests/test_ohlc_validation.py
.py
"""Tests for the shared OHLC invariant validator and its loader wiring.""" from __future__ import annotations import logging from pathlib import Path import pandas as pd import pytest import backtest.loaders.local_loader as local_loader from backtest.loaders.base import validate_ohlc def _frame(rows: list[tuple[f...
140
4,858
Vibe-Trading
agent/tests/test_volume_unit_consistency.py
.py
"""Empirical cross-source volume consistency guard (HKUDS/Vibe-Trading#1062). Fetches the same settled A-share trading day from every reachable loader and asserts the reported volumes agree within tolerance. This is the runtime lock the #1062 audit called for: unit drift between fallback sources (the original bug: bao...
66
2,439
Vibe-Trading
agent/tests/test_swarm_m3_boot_wiring.py
.py
"""M3 — SWARM external MCP tools: boot wiring & config resolution. Covers requirements R-09 (lazy boot discovery) and tests T-08, T-09, T-10, T-11 in ``docs/2026-05-25_swarm_mcp_tools_tdd.md``. M3 introduces the boot-time config resolver that lets operators point a swarm-only MCP allowlist at a distinct file from the ...
209
8,401
Vibe-Trading
agent/tests/test_swarm_dag_gating.py
.py
"""P0-A regression: a DAG with a failed upstream must NOT silently launch downstream tasks with empty upstream summaries. Original 5/27 incident: swarm-20260527-183056-2d91b0f2 (investment_committee preset). risk_officer correctly failed grounding (mock VaR), then portfolio_manager started 2 ms later with task_summari...
139
4,906
Vibe-Trading
agent/tests/test_web_reader_security.py
.py
"""Security tests for the web reader tool.""" from __future__ import annotations import json from types import SimpleNamespace import pytest from src.tools import web_reader_tool @pytest.mark.parametrize( "url", [ "", "file:///etc/passwd", "ftp://example.com/report", "https...
74
2,215
Vibe-Trading
agent/tests/test_grounding_recovery.py
.py
"""Bounded grounding recovery (#1081): recoverable missing evidence. When identity is unresolved or price evidence is missing, the loop must keep driving the original task through read-only tool turns (``search_symbol`` -> ``get_market_data``) instead of stopping at the three-draft cap with the "confirm and continue" ...
383
14,275
Vibe-Trading
agent/tests/test_market_screener_tool.py
.py
"""Tests for market_screener_tool: envelope shape, sorting params, validation. All HTTP is mocked at the Eastmoney client function the tool imports (:func:`get_json`), so no test touches a live endpoint. """ from __future__ import annotations import json from unittest.mock import patch from src.tools.market_screene...
165
5,547
Vibe-Trading
agent/tests/test_eastmoney_client.py
.py
"""Tests for eastmoney_client: secid resolution, kline parsing, error paths. All HTTP is mocked at :func:`backtest.loaders._http.throttled_get_json` (imported into the client module), so no test touches a live Eastmoney endpoint. """ from unittest.mock import patch import pytest from backtest.loaders import eastmon...
199
7,219
Vibe-Trading
agent/tests/test_factor_costs.py
.py
"""Tests for backtest.factor_costs. The load-bearing test is the one showing a high-turnover factor is eroded and a low-turnover one is not. A cost model that charges everyone equally, or charges nobody, would pass a suite that only checked "cost >= 0". """ import numpy as np import pandas as pd import pytest from b...
304
10,737
Vibe-Trading
agent/tests/test_mcp_server_smoke.py
.py
"""Smoke test for the MCP server entry point. Regression test for PR #85 (deadlock fix). Spawns ``vibe-trading-mcp`` as a subprocess and walks through the full JSON-RPC happy path: 1. ``initialize`` handshake. 2. ``tools/list`` returns the registered tool catalogue. 3. ``tools/call`` for ``analyze_options`` (a networ...
356
12,735
Vibe-Trading
agent/tests/test_etoro_connector.py
.py
"""Tests for the eToro Public API connector.""" from __future__ import annotations import json from typing import Any import pytest from src.live import registry from src.live.classification import ToolClass, classify_tool from src.trading import profiles, service from src.trading.connectors.etoro import sdk as eto...
930
37,026
Vibe-Trading
agent/tests/test_cli_backtest_summary.py
.py
"""CLI backtest summary: metric parsing, English labels, and no spawned server.""" from __future__ import annotations import subprocess from pathlib import Path from rich.console import Console from unittest.mock import Mock from cli._legacy import _read_metric_values _METRICS_CSV = ( "total_return,annual_retu...
129
4,173
Vibe-Trading
agent/tests/test_loop_helpers.py
.py
"""Tests for AgentLoop pure helper functions (zero LLM dependency).""" from __future__ import annotations import json import os from pathlib import Path from src.agent.loop import ( KEEP_RECENT, COLLAPSE_PRESERVE_RECENT, COLLAPSE_TEXT_MIN, MICROCOMPACT_THRESHOLD, estimate_tokens, _microcompac...
395
15,802
Vibe-Trading
agent/tests/test_swarm_retry.py
.py
"""Tests for the swarm-run retry path (MCP ``retry_run`` tool + HTTP endpoint). Retry re-launches a brand-new run with the same preset/variables as a prior ``failed`` / ``cancelled`` / stale run, leaving the original untouched. A still-``running`` run must be refused so we never fork an active run. """ from __future_...
96
3,389
Vibe-Trading
agent/tests/test_doc_reader.py
.py
"""Tests for the universal read_document tool (multi-format dispatch).""" from __future__ import annotations import json from pathlib import Path import pandas as pd import pytest from src.tools.doc_reader_tool import read_document def _call(path: Path, pages: str = "") -> dict: return json.loads(read_documen...
186
5,961
Vibe-Trading
agent/tests/test_cli_ui_redesign.py
.py
from __future__ import annotations from rich.console import Console from cli.ui.banner import print_banner from cli.ui.rail import RailRunDashboard from cli.ui.transcript import render_answer, render_elapsed_status, render_prompt_footer, render_recap def _render(renderable) -> str: console = Console(record=True...
177
5,470
Vibe-Trading
agent/tests/test_redaction_shared.py
.py
"""Shared redaction helpers promoted from the swarm worker (#142 → public). Covers ``redact_payload`` (recursive sensitive-key scrubbing), ``is_sensitive_arg`` (sink-aware key-name classification) and ``redact_tool_result`` (the single tool-result choke point), now consumed by the swarm worker, the live-action audit l...
449
15,760
Vibe-Trading
agent/tests/test_registry.py
.py
"""Tests for loader registry and fallback chain logic.""" from __future__ import annotations from unittest.mock import patch import pytest from backtest.loaders.base import DataLoaderProtocol, NoAvailableSourceError from backtest.loaders.registry import ( FALLBACK_CHAINS, LOADER_REGISTRY, VALID_SOURCES,...
372
14,918
Vibe-Trading
agent/tests/test_agent_loop_repeatable_tools.py
.py
"""Regression tests for parameter-dependent query tools in the agent loop.""" from __future__ import annotations import json from pathlib import Path from types import SimpleNamespace import pytest from src.agent.context import ContextBuilder from src.agent.loop import AgentLoop from src.agent.tools import ToolRegi...
118
3,441
Vibe-Trading
agent/tests/test_session_store_list_corrupt.py
.py
"""One corrupt session.json must not abort SessionStore.list_sessions.""" from __future__ import annotations import json from pathlib import Path from src.session.models import Session from src.session.store import SessionStore def test_list_sessions_skips_invalid_status_and_keeps_siblings(tmp_path: Path) -> None:...
45
1,407
Vibe-Trading
agent/tests/test_equity_regression.py
.py
"""Regression test: vectorized vs loop _calc_equity produce identical results.""" from __future__ import annotations import numpy as np import pandas as pd from backtest.engines.base import BaseEngine from backtest.models import Position class _StubEngine(BaseEngine): """Minimal concrete BaseEngine for testing...
118
4,033
Vibe-Trading
agent/tests/test_fred_macro_tool.py
.py
"""Tests for fred_macro_tool: availability gating, success + error envelopes. All HTTP is mocked — no test ever reaches a live FRED endpoint. The tool imports ``throttled_get_json`` from :mod:`backtest.loaders._http` into its own namespace, so we monkeypatch that name on the ``fred_macro_tool`` module. """ from __fut...
182
6,985
Vibe-Trading
agent/tests/test_alpha_bench_universe_metadata.py
.py
"""Universe loaders disclose constituent provenance and degradation.""" from __future__ import annotations import sys from types import SimpleNamespace import pandas as pd import pytest from src.tools import alpha_bench_tool as tool def _daily_frame() -> pd.DataFrame: """Return one deterministic Tushare-style...
177
5,685
Vibe-Trading
agent/tests/test_agent_loop_trace.py
.py
"""AgentLoop trace integration tests for PR #206 rebase.""" from __future__ import annotations import json from pathlib import Path from types import SimpleNamespace from typing import Any, Callable import pytest import src.agent.loop as loop_mod import src.agent.trace as trace_mod from src.agent.context import Con...
149
4,976
Vibe-Trading
agent/tests/test_auto_compact_chunked_summary.py
.py
"""Regression tests for lossless, chunked auto-compaction summaries.""" from __future__ import annotations import json from pathlib import Path from types import SimpleNamespace from typing import Any from src.agent.loop import AgentLoop, _summary_chunks from src.agent.tools import ToolRegistry from src.agent.trace ...
130
4,831
Vibe-Trading
agent/tests/test_rsshub_events_lookahead.py
.py
"""No-look-ahead guarantee for RSSHub event enrichment. Echoes the discipline of ``agent/tests/factors/test_lookahead.py``: corrupting the future must not change the present. Here, adding a future-dated event must not alter ``event_score`` on any earlier bar. """ from __future__ import annotations from typing import...
97
3,515
Vibe-Trading
agent/tests/test_shadow_scanner.py
.py
"""Focused tests for Shadow Account signal scanning.""" from __future__ import annotations from datetime import date import pandas as pd import pytest from src.shadow_account.models import ShadowProfile, ShadowRule from src.shadow_account.scanner import scan_today_signals def _profile(entry_condition: dict[str, o...
188
6,416
Vibe-Trading
agent/tests/test_shadow_account.py
.py
"""Tests for src.shadow_account (Phase 4c — M1). Fixtures are synthesized in-test via tmp_path; no binary fixtures on disk. """ from __future__ import annotations import builtins import json import types from pathlib import Path import pandas as pd import pytest from src.shadow_account import ( AttributionBrea...
2,074
76,155
Vibe-Trading
agent/tests/test_yfinance_crypto_routing.py
.py
"""Tests that yfinance-loaded crypto routes to CryptoEngine. The yfinance branch used to hand every symbol to GlobalEquityEngine, whose fee keys (slippage_us / hk_commission) never read the CryptoEngine keys (taker_rate / maker_rate / slippage), so an explicit fee config was silently ignored and two runs with differen...
50
2,033
Vibe-Trading
agent/tests/test_etf_holdings_tool.py
.py
"""Tests for etf_holdings_tool: routing, parsing, as-of honesty, degradation. Every fixture below is a trimmed copy of a real payload captured from the live endpoint, and all HTTP is mocked at the module's two transport seams (:func:`_sec_get_text` / :func:`_em_get_text`) plus the shared Eastmoney JSON helper, so no t...
1,113
49,999
Vibe-Trading
agent/tests/test_goal_store.py
.py
"""Tests for the finance research goal store MVP.""" from __future__ import annotations import hashlib from concurrent.futures import ThreadPoolExecutor from pathlib import Path import pytest from src.goal import ( AuditRow, EvidenceInput, GoalStatus, GoalStore, RiskTier, StaleGoalError, ) ...
645
21,270
Vibe-Trading
agent/tests/test_preset_honesty.py
.py
"""CI gate: a shipped preset must not promise what its node cannot reach. Swarm workers get a strict tool whitelist and a skill list. Two failure modes had shipped: ``value_investing_committee`` named three skills that were never bundled (``load_skill`` returns a soft error envelope, so the worker proceeded without it...
126
4,765
Vibe-Trading
agent/tests/test_dhan_period_reject.py
.py
"""Dhan history must reject unsupported periods instead of serving daily bars.""" from __future__ import annotations from src.trading.connectors.dhan import sdk as dhan_sdk class _FakeDhanClient: def __init__(self) -> None: self.daily_calls = 0 self.intraday_calls = 0 def historical_daily_c...
43
1,604
Vibe-Trading
agent/tests/test_web_search_tool.py
.py
"""Tests for WebSearchTool: multi-backend fallback, retry, and error handling. Covers issue #231 — a single rate-limited engine (DuckDuckGo) should no longer fail the whole search. All tests mock ``ddgs.DDGS`` so no network calls are made. """ import json import sys from contextlib import contextmanager from types imp...
199
7,007
Vibe-Trading
agent/tests/test_options_payoff.py
.py
"""Regression tests for analytic option payoff and scenario calculations.""" from __future__ import annotations import numpy as np import pytest from backtest.engines.options_portfolio import bs_price from backtest.options_payoff import ( OptionLeg, bull_call_spread, default_spot_grid, expiry_payoff,...
257
8,341
Vibe-Trading
agent/tests/test_financial_statements_yahoo_ss_suffix.py
.py
"""Regression test for _classify_market handling Yahoo .SS suffix in financial_statements_tool. Locks out a bug where _classify_market returned None for Shanghai A-share symbols using Yahoo's standard .SS suffix (e.g. "600519.SS"), rejecting valid financial statement queries. """ from src.tools.financial_statements_t...
19
840
Vibe-Trading
agent/tests/test_swarm_m5_trust_model.py
.py
"""M5 — SWARM external MCP tools: trust-model regression tests. Covers requirements R-06 and tests T-16, T-17, T-18 in ``docs/2026-05-25_swarm_mcp_tools_tdd.md``. M5 pins the contract that an external MCP caller of ``run_swarm`` cannot influence which remote MCP servers a worker reaches, no matter what they put in ``v...
444
18,031
Vibe-Trading
agent/tests/test_runtime_jobstore.py
.py
"""Tests for the durable live-runtime job store (src/live/runtime/jobstore.py, SPEC.md §7.5 #1). The store is exercised purely through its public API + the filesystem (the runtime root is redirected to a tmp dir). Focus: atomic save round-trips, a SIGKILL mid-write can never truncate the real store, a corrupt store is...
149
4,985
Vibe-Trading
agent/tests/test_fmp_loader.py
.py
"""Tests for fmp_loader: auth gating, symbol mapping, parsing, batch resilience. All HTTP is mocked at :func:`backtest.loaders._http.throttled_get_json` (imported into the loader module), so no test touches a live FMP endpoint. """ from unittest.mock import patch import pandas as pd import pytest from backtest.load...
164
6,354
Vibe-Trading
agent/tests/test_file_tool_sandbox_security.py
.py
"""Security regression tests for run_dir-based file tools.""" from __future__ import annotations import json from pathlib import Path import pytest from src.tools.backtest_tool import run_backtest from src.tools.edit_file_tool import EditFileTool from src.tools.read_file_tool import ReadFileTool from src.tools.write...
194
7,615
Vibe-Trading
agent/tests/test_backtest_runner_security.py
.py
"""Security regression tests for backtest signal_engine loading.""" from __future__ import annotations import uuid import pytest from backtest.runner import _load_module_from_file def _module_name() -> str: """Return a unique module name for import tests.""" return f"signal_engine_test_{uuid.uuid4().hex}"...
725
28,116
Vibe-Trading
agent/tests/test_ocr_integration.py
.py
"""Integration tests for the OCR pipeline. Tests the full path: synthetic scanned PDF → _read_pdf() → OCR → text output. Requires rapidocr_onnxruntime to be installed for the OCR path. """ from __future__ import annotations import json from pathlib import Path import pytest from src.config.accessor import reset_en...
126
4,345
Vibe-Trading
agent/tests/test_margin_trading_tool.py
.py
"""Tests for the margin-trading (融资融券) tool. No request leaves the process: the success path patches the shared Eastmoney client (:func:`backtest.loaders.eastmoney_client.get_json`) so the tool's own parsing/envelope logic runs against a canned datacenter payload, and the error path makes that boundary raise. """ fro...
151
5,545
Vibe-Trading
agent/tests/test_daily_count.py
.py
"""Daily order-counter serialization tests with no broker transport.""" from __future__ import annotations import os import subprocess import sys from pathlib import Path import pytest import src.live.paths as live_paths from src.live.daily_count import daily_order_lock pytestmark = pytest.mark.unit def _child_l...
56
1,540
Vibe-Trading
agent/tests/test_kimi_reasoning_content.py
.py
"""Regression tests for provider reasoning_content preservation. Invariant: ``ai_message.additional_kwargs["reasoning_content"]`` is the single source of truth. ``ChatOpenAIWithReasoning`` populates it from both the non-streaming response path and the streaming delta path. """ from __future__ import annotations impo...
744
30,866
Vibe-Trading
agent/tests/test_fund_flow_tool.py
.py
"""Tests for fund_flow_tool: envelope shape, parsing, per-symbol isolation. All HTTP is mocked at the Eastmoney client functions the tool imports (:func:`get_json` / :func:`resolve_secid`), so no test touches a live endpoint. """ from __future__ import annotations import json from unittest.mock import patch from sr...
207
7,883
Vibe-Trading
agent/tests/test_cli_channels.py
.py
"""CLI coverage for IM channel commands.""" from __future__ import annotations from pathlib import Path import pytest from cli import _legacy def test_channels_parser_accepts_status_start_stop_login_and_pairing() -> None: parser = _legacy._build_parser() status = parser.parse_args(["channels", "status", ...
115
3,696
Vibe-Trading
agent/tests/test_json_loads_guard.py
.py
"""Regression: _json_loads must not crash on corrupted JSON in database columns. Both goal/store.py and strategy_store/sqlite_store.py define _json_loads to deserialize JSON columns (theme, benchmark, assumptions, etc.). The original code called json.loads(value) without a try/except — a corrupted JSON string in the d...
53
2,049
Vibe-Trading
agent/tests/test_binance_period_map.py
.py
"""Binance history must map project-style 1H/4H tokens to ccxt timeframes.""" from __future__ import annotations from src.trading.connectors.binance import sdk as bn class _FakeEx: def __init__(self) -> None: self.calls: list[dict] = [] def fetch_ohlcv(self, symbol, timeframe="1d", limit=90): ...
43
1,620
Vibe-Trading
agent/tests/test_host_throttle_memory.py
.py
"""Regression: HostThrottle must not leak memory from stale bucket entries. The ``_last`` dict grows one entry per unique host bucket and never evicts stale entries. A batch job that queries many distinct hosts (e.g. N tickers across N providers) accumulates dead entries without bound. The fix adds a periodic sweep th...
118
3,957
Vibe-Trading
agent/tests/test_trading212_connector.py
.py
"""Tests for the read-only Trading 212 connector.""" from __future__ import annotations import pytest from src.live import registry from src.live.classification import ToolClass, classify_tool from src.trading import profiles, service from src.trading.connectors.trading212 import sdk as t212 from src.trading.connect...
252
9,073
Vibe-Trading
agent/tests/test_agent_config.py
.py
"""Unit tests for structured agent config loading.""" from __future__ import annotations import json import logging from pathlib import Path import pytest from pydantic import ValidationError from src.channels.config import load_channels_config from src.config import ( AgentConfig, MCPServerConfig, get_...
609
19,865
Vibe-Trading
agent/tests/test_block_trades_bare_code.py
.py
"""Regression test for _resolve_code handling bare 6-digit A-share symbols in block_trades_tool. Locks out a bug where _resolve_code returned None for bare 6-digit A-share codes (e.g. "600519" or "000001") because symbol.rpartition(".")[0] returned an empty string when symbol contained no dot. """ from src.tools.bloc...
20
801
Vibe-Trading
agent/tests/test_nonpositive_prices.py
.py
"""allow_nonpositive_prices: open on negative-price bars, still reject zero. Markets like European day-ahead power clear negative routinely. The default (flag off) still drops/rejects any non-positive price, so nothing changes for existing markets; when the flag is on, negative prices flow through and only an exactly-...
197
8,235
Vibe-Trading
agent/tests/test_doc_reader_security.py
.py
"""Security regression tests for document and broker-file path boundaries.""" from __future__ import annotations import json import pytest from src.tools.doc_reader_tool import read_document from src.tools.path_utils import safe_document_path, safe_user_path @pytest.fixture(autouse=True) def clear_allowed_roots(m...
49
1,480
Vibe-Trading
agent/tests/test_agent_output_discipline.py
.py
"""Output discipline: the prompt text, the gate behind it, and skill disclosure. Two defects motivate this file. The agent has been observed overwriting a value a tool returned with one it remembered, and naming instruments no tool in the session ever returned. The Output Principles answer both, and they are literal t...
814
35,021
Vibe-Trading
agent/tests/test_cli_session_id.py
.py
"""Regression tests for host session-id injection in non-interactive CLI runs. Issue #885: ``cmd_run`` registered the research-goal tools but never gave them a session, so every goal call failed validation with ``session_id is required`` while the run still reported success. The same omission affected ``cmd_continue``...
174
6,312
Vibe-Trading
agent/tests/test_market_detection.py
.py
"""Tests for runner market detection, source mapping, and code normalization. Also covers the audit-2026-05-18 B1 routing bug: composite.py previously had a truncated ``_is_china_futures`` that only inspected the exchange suffix, so a bare ``RB2410`` was misrouted to GlobalFuturesEngine. After the consolidation in ``_...
325
12,294
Vibe-Trading
agent/tests/test_cli_goal.py
.py
"""CLI tests for the finance research goal slash command.""" from __future__ import annotations from pathlib import Path from types import SimpleNamespace from src.goal import GoalStore def test_goal_command_is_registered() -> None: """The interactive slash router exposes /goal.""" from cli.commands.slash_...
147
4,810
Vibe-Trading
agent/tests/test_agent_loop_stream_retry.py
.py
"""AgentLoop single stream retry on ProviderStreamError. Mirrors the swarm worker policy: a transient mid-stream failure (connection reset, relay hiccup, 5xx) is retried exactly once; a deterministic 4xx fails the run immediately with error_code=provider_stream_error and no wasted request. Deltas from the failed attem...
194
6,689
Vibe-Trading
agent/tests/test_benchmark_excess_return_consistency.py
.py
"""Regression: excess_return must stay consistent with the corrected benchmark_return once an external benchmark's price series crosses a non-positive-prior-price bar. BaseEngine.run_backtest() overwrites the internally-computed benchmark_return with the #872-safe price relative (BenchmarkResult.total_ret), but never ...
125
4,508
Vibe-Trading
agent/tests/test_india_broker_loader.py
.py
"""India broker data-bridge loader: envelope adaptation + availability gating. The loader adapts Shoonya/Dhan ``get_historical_bars`` into the OHLCV frame. Tests inject a fake broker SDK via ``_resolve_broker`` so no real SDK/creds are needed; the loader stays unavailable (and inert) when no broker is configured. """ ...
119
4,640