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_india_equity_engine.py | .py | """Tests for IndiaEquityEngine (NSE / BSE delivery) market rules.
Validates:
- No short selling by default; allow_short opt-in
- T+1: can't sell shares bought the same bar
- Configurable circuit band blocks buys at upper / sells at lower limit
- 1-share lots
- India delivery cost stack (STT bilateral, stamp ... | 178 | 6,940 |
Vibe-Trading | agent/tests/test_channel_media_roots.py | .py | """Inbound IM media must be saved where the agent's read tools can open it (#465)."""
from __future__ import annotations
from pathlib import Path
def test_media_dir_lives_under_uploads_root(tmp_path, monkeypatch):
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)
from src.... | 28 | 962 |
Vibe-Trading | agent/tests/test_yfinance_lowercase_4h_1w.py | .py | """yfinance interval map must not leave lowercase 4h/1w as invalid Yahoo tokens."""
from __future__ import annotations
from backtest.loaders.yfinance_loader import _to_yfinance_interval
def test_lowercase_4h_maps_like_4H() -> None:
"""``4h`` used to fall through to ``.lower()`` and become invalid ``4h``."""
... | 23 | 769 |
Vibe-Trading | agent/tests/test_sec_filings_tool.py | .py | """Tests for get_sec_filings: success + error envelopes, HTTP fully mocked.
The SEC client functions (``cik_for`` / ``get_submissions`` /
``get_company_facts``) are patched on the tool module, so no test reaches a
live ``sec.gov`` endpoint.
"""
from __future__ import annotations
import json
from unittest.mock import... | 151 | 5,529 |
Vibe-Trading | agent/tests/test_yfinance_lowercase_4h_resample.py | .py | """yfinance loader must resample to 4-hour bars for lowercase ``4h`` too.
``_to_yfinance_interval`` already treats ``4h``/``4H`` the same when picking
the Yahoo interval to download (see test_yfinance_lowercase_4h_1w.py), but
``_normalize_frame``'s resample trigger was a case-sensitive ``== "4H"``
check. A request for... | 54 | 1,824 |
Vibe-Trading | agent/tests/test_ibkr_mcp_seed.py | .py | """IBKR official MCP read-only probe wiring.
The IBKR endpoint exposes tool names only after OAuth, so the seed uses a
read-only ``mcp.read`` wildcard probe. These tests keep that narrow exception
from becoming an ungated live-broker wildcard.
"""
from __future__ import annotations
from typing import Any
import pyt... | 92 | 3,070 |
Vibe-Trading | agent/tests/test_governance.py | .py | """Tests for src/governance/ (run manifest + hash-chained ledger).
Focus: manifest hashing is deterministic over composition and sensitive to
every composition dimension (system prompt / skills / tools / package
versions / extra) while being INSENSITIVE to run_id/timestamp; the ledger's
tamper detection is proven with... | 775 | 29,608 |
Vibe-Trading | agent/tests/test_vnpy_export.py | .py | """Tests for the vnpy-export skill — SKILL.md integrity and template validity."""
from __future__ import annotations
import ast
from pathlib import Path
import pytest
SKILL_DIR = Path(__file__).parent.parent / "src" / "skills" / "vnpy-export"
SKILL_MD = SKILL_DIR / "SKILL.md"
TEMPLATE_PY = SKILL_DIR / "scripts" / "... | 141 | 5,585 |
Vibe-Trading | agent/tests/test_autopilot_tool.py | .py | """Tests for Research Autopilot bridge tools."""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from src.hypotheses import HypothesisRegistry
from src.tools import build_registry
from src.tools.autopilot_tool import (
GenerateBacktestConfigTool,
RunResearchAutopilotToo... | 175 | 6,678 |
Vibe-Trading | agent/tests/test_provider_diagnostics.py | .py | """Provider capability and diagnostic regression tests."""
from __future__ import annotations
import json
import os
from unittest.mock import patch
from src.providers.capabilities import get_provider_capabilities
from src.providers.llm import build_llm, provider_diagnostics
def test_provider_diagnostics_redacts_se... | 276 | 10,335 |
Vibe-Trading | agent/tests/test_trading_connections.py | .py | """Tests for connector-first trading profile operations."""
from __future__ import annotations
import json
from types import SimpleNamespace
import pytest
from src.trading import profiles, service
from src.tools import build_registry
from src.tools.trading_connector_tool import TradingPlaceOrderTool, TradingSelectC... | 186 | 7,249 |
Vibe-Trading | agent/tests/test_memory_lifecycle.py | .py | """Tests for memory lifecycle: quality scoring, decay, and reinforcement."""
from __future__ import annotations
from pathlib import Path
import pytest
from src.config.accessor import reset_env_config
from src.memory.lifecycle import (
MemoryLifecycle,
compute_importance,
is_decay_enabled,
is_gc_enab... | 348 | 14,437 |
Vibe-Trading | agent/tests/test_alphavantage_loader.py | .py | """Tests for alphavantage_loader: availability, payload parsing, error paths.
All HTTP is mocked at :func:`backtest.loaders._http.throttled_get_json` (imported
into the loader module), so no test touches a live Alpha Vantage endpoint.
"""
from unittest.mock import patch
import pandas as pd
import pytest
from backte... | 193 | 8,210 |
Vibe-Trading | agent/tests/test_mcp_regression.py | .py | """Regression tests: existing MCP server mode and no-config behavior.
These tests guard against regressions introduced by the MCP client integration:
1. no-config regression — build_registry() with no agent_config must behave
identically to before this roadmap: local tools only, no exceptions.
2. MCP server mode ... | 298 | 10,079 |
Vibe-Trading | agent/tests/test_block_trades_tool.py | .py | """Tests for the get_block_trades tool.
All HTTP is mocked at :func:`backtest.loaders.eastmoney_client.get_json` as it is
imported into the tool module, so no test touches a live Eastmoney endpoint.
"""
from __future__ import annotations
import json
from unittest.mock import patch
from src.tools import block_trades... | 124 | 4,643 |
Vibe-Trading | agent/tests/test_mcp_specs_cache.py | .py | """Unit tests for MCP tool discovery specs cache.
Tests verify that :func:`build_mcp_tool_wrappers` caches tool specs to
avoid redundant ``list_tools`` RPC calls across Swarm workers.
"""
from __future__ import annotations
import threading
from concurrent.futures import ThreadPoolExecutor
from unittest.mock import M... | 423 | 16,727 |
Vibe-Trading | agent/tests/test_redaction.py | .py | """G1 evidence: anchored redaction — no over-redaction, idempotent, None-safe.
Covers ``redact_internal_paths`` (path-boundary aware root scrubbing) and
``redact_text`` (pattern scrubbing for free-form text surfaces).
"""
from __future__ import annotations
import os
import tempfile
from pathlib import Path
import p... | 197 | 7,397 |
Vibe-Trading | agent/tests/test_qveris_tool.py | .py | from __future__ import annotations
import json
import stat
import threading
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import pytest
from src.tools import qveris_tool as qt
@pytest.fixture(autouse=True)
def qveris_config_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
mon... | 414 | 13,019 |
Vibe-Trading | agent/tests/test_longbridge_runtime.py | .py | """Tests for Longbridge transport-neutral connector runtime status.
Task 3: extends the live-trading runtime to surface Longbridge broker_sdk
profiles through the profile registry (not a hard-coded broker list), adds a
read-only idempotent ``POST /live/connectors/{profile_id}/verify`` endpoint,
and a bounded 15-second... | 1,020 | 36,824 |
Vibe-Trading | agent/tests/test_okx_loader_bounded.py | .py | """Regression tests for the OKX loader — session-based, dual-endpoint,
proxy-aware, with bounded retry and wall-clock budget.
The loader now uses a ``requests.Session`` (with optional proxy) and tries
both ``/market/history-candles`` and ``/market/candles`` endpoints.
Tests mock the session or the helper that creates ... | 216 | 7,574 |
Vibe-Trading | agent/tests/test_china_futures_engine.py | .py | """Tests for ChinaFuturesEngine market rules.
Validates:
- T+0: can close same-day positions (unlike A-shares)
- Both long and short allowed
- Price limit enforcement (varies by product)
- Integer contract rounding
- Commission (fixed per-lot and per-notional)
- Contract multiplier lookup
- Margin rate l... | 318 | 11,142 |
Vibe-Trading | agent/tests/test_risk_parity.py | .py | """Tests for risk parity optimizer."""
from __future__ import annotations
import numpy as np
import pandas as pd
import pytest
from backtest.optimizers.risk_parity import RiskParityOptimizer
class TestRiskParityCalcWeights:
"""Unit tests for the core weight calculation."""
def test_equal_vol_gives_equal_w... | 120 | 4,385 |
Vibe-Trading | agent/tests/test_qveris_loader.py | .py | """Tests for qveris_loader: config gating, mocked HTTP fetches, and registry safety.
All QVeris calls are mocked by replacing ``requests.Session`` inside the loader
module. No test reaches the live QVeris API or a signed full-content URL.
"""
from __future__ import annotations
import json
from typing import Any
imp... | 503 | 18,758 |
Vibe-Trading | agent/tests/test_path_safety.py | .py | """Tests for path safety helpers in src.tools.path_utils."""
from __future__ import annotations
from pathlib import Path
import pytest
from src.tools.path_utils import safe_document_path, safe_path, safe_run_dir, safe_run_id, safe_user_path
# -----------------------------------------------------------------------... | 194 | 7,868 |
Vibe-Trading | agent/tests/test_futu_loader.py | .py | """Tests for FutuLoader — all Futu API calls are mocked.
futu-api is not installed in CI, so we stub ``sys.modules['futu']`` before
importing the loader. Every external call goes through the stub.
"""
from __future__ import annotations
import sys
from unittest.mock import MagicMock
import pandas as pd
import pytes... | 333 | 11,579 |
Vibe-Trading | agent/tests/test_longbridge_loader.py | .py | """Contract tests for the optional Longbridge historical-data loader."""
from __future__ import annotations
import datetime as dt
import json
from types import SimpleNamespace
import pandas as pd
import pytest
from backtest.loaders import longbridge as loader_mod
from backtest.loaders.base import NoAvailableSourceE... | 411 | 14,880 |
Vibe-Trading | agent/tests/test_sdm_governance_wiring.py | .py | """The model-governance fields must be reachable through the SDM tools.
`ModelRecord` existed as a tested store schema while the three agent-facing SDM
tools exposed none of it, so an agent registering a factor could not record an
owner, a validator or a limitation even though the columns were there. A
governance fiel... | 190 | 6,278 |
Vibe-Trading | agent/tests/test_financial_statements_tool.py | .py | """Tests for financial_statements_tool: envelope shape, dispatch, isolation.
All HTTP is mocked at the functions the tool imports. A-share/HK route through
Eastmoney ``get_json`` / ``resolve_secid``; US routes through SEC EDGAR
``cik_for`` / ``get_company_facts``. No test touches a live endpoint.
"""
from __future__ ... | 362 | 13,347 |
Vibe-Trading | agent/tests/test_correlation.py | .py | """Tests for backtest/correlation.py"""
import numpy as np
import pandas as pd
import pytest
from backtest.correlation import (
_normalize_symbol,
_rolling_correlation_matrix,
infer_market,
)
class TestInferMarket:
def test_crypto_usdt(self):
assert infer_market("BTC-USDT") == "crypto"
... | 279 | 12,085 |
Vibe-Trading | agent/tests/test_institutional_holdings_tool.py | .py | """Tests for get_institutional_holdings: 13F parsing, unit detection, envelopes.
Every SEC round trip is mocked at :func:`institutional_holdings_tool._sec_get`,
the single choke point through which the tool reaches the network, so no test
touches ``sec.gov`` or ``efts.sec.gov``. The XML fixtures are trimmed copies of
... | 1,740 | 83,292 |
Vibe-Trading | agent/tests/test_context_attribution_layers.py | .py | """Tests for the post-backtest attribution layers in system prompt."""
from __future__ import annotations
import builtins
import pytest
from backtest.loaders.registry import VALID_SOURCES
from src.agent.context import ContextBuilder
@pytest.mark.unit
class TestAttributionLayersPresence:
"""Verify all 4 attrib... | 135 | 5,260 |
Vibe-Trading | agent/tests/test_trade_journal_fifo_str_datetime.py | .py | """Regression test for pair_trades_fifo handling string datetime columns in trade_journal_tool.
Locks out a bug where pair_trades_fifo raised TypeError: unsupported operand type(s)
for -: 'str' and 'str' when df["datetime"] contained string timestamps instead of Timestamps.
"""
import pandas as pd
from src.tools.trad... | 39 | 1,301 |
Vibe-Trading | agent/tests/test_report_audit_tool.py | .py | """Tests for the ``report_audit`` agent tool.
Covers the markdown data-point extraction (tables + ``label: value`` lines,
Chinese units), sampling (clamp + reproducibility), the verdict logic across
single/two-source cases (incl. the split-source WARN and the single-source
FAIL that the original upstream logic mishand... | 303 | 11,248 |
Vibe-Trading | agent/tests/test_shoonya_interval_map.py | .py | """Shoonya period map must not silently collapse 4h/1H/1w/1M to daily."""
from __future__ import annotations
from src.trading.connectors.shoonya import sdk as sh
class _FakeApi:
def __init__(self) -> None:
self.daily_calls: list[dict] = []
self.time_calls: list[dict] = []
def get_daily_pric... | 74 | 2,480 |
Vibe-Trading | agent/tests/test_futu_loader_interval_case.py | .py | """Futu loader interval map must accept connector-style hour/day aliases."""
from __future__ import annotations
from backtest.loaders.futu import _INTERVAL_MAP, _to_futu_ktype
def test_lowercase_hour_aliases_match_project_tokens() -> None:
assert _INTERVAL_MAP["1h"] == _INTERVAL_MAP["1H"] == "K_60M"
assert ... | 27 | 829 |
Vibe-Trading | agent/tests/test_risk_xray.py | .py | """Tests for the portfolio risk x-ray core and its agent tool."""
from __future__ import annotations
import json
import numpy as np
import pandas as pd
import pytest
from backtest.risk_xray import (
_drawdown,
average_invested_weights,
compute_risk_xray,
render_risk_xray_markdown,
write_risk_xra... | 394 | 14,875 |
Vibe-Trading | agent/tests/test_api_infrastructure.py | .py | """Regression tests for the extracted API infrastructure modules."""
from __future__ import annotations
import os
import pytest
import api_server
from src.api import _compat, security, models, helpers, state
# ============================================================================
# Re-export identity tests
#... | 356 | 13,159 |
Vibe-Trading | agent/tests/test_ocr_engine.py | .py | """Tests for the pluggable OCR engine factory.
Cloud OCR uploads document pages to a third party, so cloud engines
must only ever be reachable through an explicit VIBE_TRADING_OCR_ENGINE
choice — never via "auto" fallback.
"""
from __future__ import annotations
import numpy as np
import pytest
from src.config.acces... | 461 | 18,711 |
Vibe-Trading | agent/tests/test_grounding_nan_volume.py | .py | """Regression: format_grounding_block must not crash on NaN/inf volume or close.
Loaders can return NaN for missing OHLCV fields (e.g. volume on a
non-trading day, close on a halted stock). The original code called
``int(row['volume'])`` unconditionally — ``int(float('nan'))`` raises
``ValueError: cannot convert float... | 126 | 4,577 |
Vibe-Trading | agent/tests/test_cli_data.py | .py | from __future__ import annotations
import pytest
from cli import _legacy
def test_data_parser_accepts_status_mode_and_usage() -> None:
parser = _legacy._build_parser()
status = parser.parse_args(["data", "status"])
assert status.command == "data"
assert status.data_command == "status"
free = p... | 45 | 1,098 |
Vibe-Trading | agent/tests/test_stooq_interval_reject.py | .py | """Stooq must reject non-daily intervals instead of silently returning day bars."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from backtest.loaders import stooq_loader as sq
def test_unsupported_interval_does_not_hit_api() -> None:
"""Runner ``1H`` must not fall through to S... | 44 | 1,385 |
Vibe-Trading | agent/tests/test_chat_response_metadata.py | .py | from pathlib import Path
from types import MethodType, SimpleNamespace
import src.providers.chat as chat_module
from src.agent.loop import AgentLoop
from src.config.accessor import reset_env_config
from src.providers.chat import ChatLLM, LLMResponse
def test_parse_response_keeps_provider_reported_model() -> None:
... | 76 | 2,262 |
Vibe-Trading | agent/tests/test_mcp_sse_integration.py | .py | """Integration tests: full-stack SSE MCP client path with a real FastMCP server.
These tests spawn an actual FastMCP SSE server process
(agent/tests/fixtures/fake_mcp_sse_server.py) and exercise the entire path:
load_agent_config()
-> build_registry(agent_config=...)
-> MCPServerAdapter
... | 104 | 3,761 |
Vibe-Trading | agent/tests/test_tap_forward.py | .py | """Direct unit tests for ``src.trading.tap_forward``.
The connector tests (test_alpaca_tap_routing.py) mock ``tap_forward.forward``
wholesale, so this file exercises the module itself with ``urllib`` mocked:
the fail-closed error paths, the 202 → poll → decision loop, and the
poll-URL exfiltration guard (the agent key... | 247 | 9,511 |
Vibe-Trading | agent/tests/test_yfinance_crypto.py | .py | """Tests for yfinance loader crypto support: symbol conversion and market registration."""
from __future__ import annotations
import pandas as pd
import pytest
from backtest.loaders.yfinance_loader import DataLoader, _to_yfinance_symbol
# ---------------------------------------------------------------------------
... | 148 | 5,035 |
Vibe-Trading | agent/tests/test_dragon_tiger_tool.py | .py | """Tests for the dragon-tiger (龙虎榜) tool.
No request leaves the process: the HTTP boundary
(:func:`backtest.loaders.eastmoney_client.throttled_get_json`) is mocked so the
real client + tool parsing runs offline.
"""
from __future__ import annotations
import json
from typing import Any
from unittest.mock import patch... | 180 | 6,376 |
Vibe-Trading | agent/tests/test_tushare_fundamentals_provider.py | .py | from __future__ import annotations
import sys
from types import SimpleNamespace
import pandas as pd
import pytest
from backtest.loaders.tushare_fundamentals import (
SchemaValidationError,
TushareFundamentalProvider,
UnknownTableError,
enrich_price_frames_with_fundamentals,
)
class _FakeTushareApi:... | 377 | 13,826 |
Vibe-Trading | agent/tests/test_background_tools.py | .py | """Regression tests for background command lifecycle reporting."""
from __future__ import annotations
import json
import os
import shlex
import sys
import threading
import time
from pathlib import Path
from unittest.mock import MagicMock
import pytest
from src.tools import background_tools
from src.tools.background... | 348 | 10,731 |
Vibe-Trading | agent/tests/test_feishu_parse_md_table_edge_columns.py | .py | """Feishu markdown tables must keep empty leading/trailing columns."""
from __future__ import annotations
from src.channels.feishu import FeishuChannel
def test_parse_md_table_keeps_trailing_empty_header_column() -> None:
table = "|Name|Qty||\n|---|---|---|\n|a|1|note|\n|b|2|other|\n"
parsed = FeishuChannel... | 28 | 1,022 |
Vibe-Trading | agent/tests/test_cli_runtime.py | .py | """Tests for the live-runtime CLI surface + discoverability (parcel R7).
Covers SPEC.md §7.5 (persistent runner control) + §9 Decision 1 (CLI surface
table) + the §9 audit discoverability fix:
* ``connector start`` / ``connector stop`` dispatch to their handlers and
relay to the R6 surface endpoints (``POST /live/r... | 516 | 20,094 |
Vibe-Trading | agent/tests/test_crypto_engine.py | .py | """Tests for CryptoEngine market rules.
Validates:
- 24/7 execution (no direction/time restrictions)
- Fractional position sizing
- Maker/Taker fee separation
- Funding fee settlement (every 8 hours)
- Forced liquidation (maintenance margin check)
- Tiered maintenance margin rates
"""
from __future__ impo... | 1,254 | 46,245 |
Vibe-Trading | agent/tests/test_image_vision_tool.py | .py | """Tests for image_vision_tool: path safety, input validation, LLM plumbing.
The LLM call is mocked; the only real I/O is a tiny PNG written to tmp_path.
"""
from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from src.tools.image_vision_... | 76 | 2,527 |
Vibe-Trading | agent/tests/test_alpaca_timeframe_map.py | .py | """Tests for Alpaca period → timeframe mapping."""
from __future__ import annotations
from src.trading.connectors.alpaca.sdk import _rest_timeframe
def test_project_hour_tokens_map_to_hour_not_day() -> None:
assert _rest_timeframe("1H") == "1Hour"
assert _rest_timeframe("4H") == "4Hour"
assert _rest_tim... | 18 | 533 |
Vibe-Trading | agent/tests/test_consent_commit.py | .py | """Consent backend: propose -> select -> commit state machine + invariants.
Covers (live-trading SPEC, Consent §1/§3, Mandate §2):
* PROPOSE -> SELECT -> COMMIT happy path, then the mandate loads back.
* commit-is-the-only-write: an AST + registry scan proves no agent tool / tool
registry path reaches ``commit_mand... | 563 | 21,317 |
Vibe-Trading | agent/tests/test_data_routing_sources_subset.py | .py | """Guard test: data-routing SKILL.md can never drift from the loader registry.
The ``data-routing`` skill is the single ROUTER and its Source Overview table
enumerates the registered backtest data sources by name. This test parses those
names straight from the markdown and asserts they form a strict **subset** of
``ba... | 157 | 6,368 |
Vibe-Trading | agent/tests/test_goal_api.py | .py | """API regressions for research goal status and defaults."""
from __future__ import annotations
from pathlib import Path
from fastapi.testclient import TestClient
import api_server
def _client(tmp_path: Path, monkeypatch) -> TestClient:
monkeypatch.setenv("VIBE_TRADING_GOAL_DB_PATH", str(tmp_path / "goals.db"... | 139 | 4,902 |
Vibe-Trading | agent/tests/test_ibkr_local.py | .py | """Unit tests for the local IBKR TWS / IB Gateway bridge."""
from __future__ import annotations
import json
import sys
import types
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from src.trading.connectors.ibkr import local
from src.tools.trading_connector_tool import TradingPositi... | 542 | 19,623 |
Vibe-Trading | agent/tests/test_tiingo_loader.py | .py | """Tests for the Tiingo US-equity OHLCV loader.
All HTTP is mocked at :func:`backtest.loaders._http.throttled_get_json` (imported
into the loader module as ``throttled_get_json``), so no test touches a live
Tiingo endpoint.
"""
from __future__ import annotations
from unittest.mock import patch
import pandas as pd
i... | 203 | 6,963 |
Vibe-Trading | agent/tests/test_hypothesis_registry.py | .py | """Tests for the durable hypothesis registry MVP."""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from src.hypotheses import HypothesisRegistry, default_hypotheses_path
from src.tools.hypothesis_tool import (
CreateHypothesisTool,
LinkBacktestTool,
SearchHypothes... | 204 | 6,851 |
Vibe-Trading | agent/tests/test_bash_tool.py | .py | """Safety regression tests for host shell execution."""
from __future__ import annotations
import json
from unittest.mock import MagicMock
import pytest
from src.tools import bash_tool
from src.tools.bash_tool import BashTool
@pytest.mark.parametrize(
"command",
[
'taskkill /F /IM python.exe 2>nul... | 67 | 1,879 |
Vibe-Trading | agent/tests/test_sector_tool.py | .py | """Tests for sector_tool: envelope shape, parsing, mode dispatch, validation.
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 ... | 195 | 6,928 |
Vibe-Trading | agent/tests/test_agent_loop_terminal_state.py | .py | """Regression tests for AgentLoop terminal-state result dict (issue #114).
Before the fix, AgentLoop.run() returned a dict missing the `reason` field
on the cancelled and max-iter-failed branches even though state.json on
disk recorded a useful reason. SessionService then surfaced
'Execution failed: unknown' to the ch... | 396 | 13,848 |
Vibe-Trading | agent/tests/test_tool_timeout.py | .py | """Tool timeout/liveness regression tests."""
from __future__ import annotations
import json
import time
from types import SimpleNamespace
from typing import Any
from src.agent import loop as loop_mod
from src.agent.loop import AgentLoop
class _SlowRegistry:
class _Tool:
is_readonly = True
def get... | 100 | 3,094 |
Vibe-Trading | agent/tests/test_alpha_bench_forward_returns.py | .py | """Regression tests for alpha-bench forward-return missing-data handling."""
from __future__ import annotations
import pandas as pd
from src.tools.alpha_bench_tool import _compute_forward_returns
def test_forward_returns_preserve_missing_close_boundaries() -> None:
close = pd.DataFrame(
{"AAA": [100.0,... | 19 | 504 |
Vibe-Trading | agent/tests/test_yfinance_interval_map.py | .py | """Tests for yfinance interval mapping (month vs minute case)."""
from __future__ import annotations
from backtest.loaders.yfinance_loader import _to_yfinance_interval
def test_month_token_maps_to_1mo_not_1m() -> None:
assert _to_yfinance_interval("1M") == "1mo"
assert _to_yfinance_interval("1m") == "1m"
... | 21 | 599 |
Vibe-Trading | agent/tests/test_scheduled_research_executor.py | .py | """Tests for the scheduled research executor."""
from __future__ import annotations
import asyncio
from datetime import datetime, timezone
from pathlib import Path
from zoneinfo import ZoneInfo
import pytest
from src.scheduled_research.executor import (
ScheduledResearchExecutor,
is_due,
next_due,
sc... | 741 | 26,635 |
Vibe-Trading | agent/tests/test_turnover_aware_optimizer.py | .py | """Tests for the turnover-aware optimizer."""
from __future__ import annotations
import numpy as np
import pandas as pd
import pytest
from backtest.optimizers.turnover_aware import TurnoverAwareOptimizer, optimize
def _sample_data(n_days: int = 200, n_assets: int = 4, seed: int = 0):
"""Return (ret, pos, dates... | 301 | 12,181 |
Vibe-Trading | agent/tests/test_session_search.py | .py | """Tests for SessionSearchIndex: SQLite FTS5 cross-session search."""
from __future__ import annotations
import time
from pathlib import Path
import pytest
from src.session.search import SessionSearchIndex, SearchMatch
@pytest.fixture()
def index(tmp_path: Path) -> SessionSearchIndex:
"""Create an ephemeral S... | 223 | 8,813 |
Vibe-Trading | agent/tests/test_session_service_mcp.py | .py | """SessionService regressions for remote MCP startup paths."""
from __future__ import annotations
import asyncio
import time
from pathlib import Path
from src.session.events import EventBus
from src.session.models import Attempt
from src.session.service import SessionService
from src.session.store import SessionStor... | 72 | 2,768 |
Vibe-Trading | agent/tests/test_tool_registry_security.py | .py | """Security regression tests for default tool exposure."""
from __future__ import annotations
import pytest
from src.tools import build_registry
def test_shell_tools_absent_from_default_registry(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("VIBE_TRADING_ENABLE_SHELL_TOOLS", raising=False)
... | 28 | 873 |
Vibe-Trading | agent/tests/test_alpaca_tap_routing.py | .py | """Tests for the opt-in TAP routing of Alpaca order placement.
When TAP is enabled, ``alpaca.sdk.place_order`` must route the order through the
TAP proxy (``tap_forward.forward``) instead of the broker SDK, map the upstream
response into the standard envelope, and fail closed on a denied/timed-out
order. When TAP is d... | 452 | 19,306 |
Vibe-Trading | agent/tests/test_agent_goal_context.py | .py | """AgentLoop regressions for active research goal context."""
from __future__ import annotations
from pathlib import Path
from typing import Any, Callable
from src.agent.loop import AgentLoop
from src.goal import GoalStore
class _AnswerResponse:
def __init__(self, content: str = "done", total_tokens: int = 0) ... | 170 | 5,985 |
Vibe-Trading | agent/tests/test_chat_llm_streaming.py | .py | """ChatLLM streaming liveness and error semantics."""
from __future__ import annotations
import os
from typing import Any
from unittest.mock import patch
import pytest
from src.providers.chat import ChatLLM, ProviderStreamError
class _FakeChunk:
def __init__(
self,
*,
content: str = ""... | 350 | 12,320 |
Vibe-Trading | agent/tests/test_swarm_route_contracts.py | .py | """Public swarm REST and SSE contract regressions."""
from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
import pytest
from fastapi.testclient import TestClient
import api_server
import src.api.swarm_routes as swarm_routes
from src.swarm.models import RunStatus, SwarmEvent... | 139 | 4,207 |
Vibe-Trading | agent/tests/test_etoro_live_actions.py | .py | """Live action gate tests for eToro-specific writes."""
from __future__ import annotations
from contextlib import contextmanager, nullcontext
import pytest
from src.live import sdk_order_gate as gate
from src.live.enforcement import OrderIntent
from src.live.mandate.model import AssetClass, ConsentMeta, HardCaps, I... | 343 | 11,176 |
Vibe-Trading | agent/tests/test_security_scanner.py | .py | """Tests for prompt-injection warning envelopes on external content."""
from __future__ import annotations
import json
import sys
import types
from pathlib import Path
import pytest
from src.security.scanner import scan_prompt_injection, with_security_warnings
from src.tools.doc_reader_tool import read_document
fro... | 208 | 6,756 |
Vibe-Trading | agent/tests/test_taiwan_stock_data_tool.py | .py | from __future__ import annotations
import json
import sqlite3
from datetime import date, timedelta
from pathlib import Path
import pytest
from src.config.limits import TOOL_RESULT_LIMIT
from src.tools.taiwan_stock_data_tool import (
MAX_QUERY_STOCKS,
MAX_RESULT_ROWS,
RESPONSE_CHAR_BUDGET,
TaiwanStock... | 831 | 20,120 |
Vibe-Trading | agent/tests/test_alpha_bench_cache.py | .py | """Tests for the HMAC-authenticated universe-panel pickle cache (VT-010).
The sidecar next to each ``<name>.pkl`` is a *keyed* HMAC-SHA256 tag, not a bare
digest. These tests pin the security property that matters: a local attacker who
can rewrite the pickle but does not hold the secret cannot forge a matching
sidecar... | 86 | 2,847 |
Vibe-Trading | agent/tests/test_tushare_daily_alias_1d.py | .py | """Tushare daily fetch must accept lowercase 1d instead of falling into minutes."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import pandas as pd
from backtest.loaders.tushare import DataLoader
def _daily_frame() -> pd.DataFrame:
idx = pd.to_datetime(["2024-01-02"])
ret... | 56 | 1,800 |
Vibe-Trading | agent/tests/test_factor_operators.py | .py | """Equivalence tests for optimized factor operators.
Tests verify that the fast paths (bottleneck / numpy stride) produce
identical results to the original pandas rolling().apply() fallback.
"""
from __future__ import annotations
import importlib
import os
import sys
import warnings
import numpy as np
import pandas... | 299 | 10,351 |
Vibe-Trading | agent/tests/test_dotenv_observability.py | .py | """Regression test for P08 (R1) — .env resolution must be observable.
A stale / shadowed .env silently won the config for the whole process with
zero diagnostic, costing hours. _ensure_dotenv now emits one behavior-
preserving INFO line naming the resolved slot via a redacted symbolic
label (or "none") plus the resolv... | 119 | 5,017 |
Vibe-Trading | agent/tests/test_parse_period_inverted.py | .py | """Regression: inverted period strings must raise ValueError."""
from __future__ import annotations
import pytest
from src.tools.alpha_bench_tool import _parse_period
def test_parse_period_rejects_inverted_year_range() -> None:
with pytest.raises(ValueError, match="start_date"):
_parse_period("2024-202... | 23 | 702 |
Vibe-Trading | agent/tests/test_skill_writer_tools.py | .py | """Tests for skill writer tools: SaveSkillTool, PatchSkillTool, DeleteSkillTool, SkillFileTool."""
from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import patch
import pytest
from src.tools.skill_writer_tool import (
SaveSkillTool,
PatchSkillTool,
DeleteSkillToo... | 306 | 11,654 |
Vibe-Trading | agent/tests/test_cli_setup_dev.py | .py | """Unit tests for the cross-platform `vibe-trading setup` and
`vibe-trading dev` commands.
These tests cover the entrypoint and platform-aware build-command
selection. They do not actually invoke ``npm`` (we mock ``shutil.which``
and ``subprocess.run``), so they run in any environment.
"""
from __future__ import anno... | 282 | 12,650 |
Vibe-Trading | agent/tests/test_institutional_commands.py | .py | """Tests for the institutional research workflow slash commands.
Covers the four things that can silently break:
1. Registration — all six commands reach ``SLASH_COMMANDS``, without
duplicating or displacing anything already there, and idempotently.
2. Aliases — never shadow an existing command, never steal a key ... | 553 | 22,986 |
Vibe-Trading | agent/tests/test_session_reply_runtime_metadata.py | .py | from __future__ import annotations
import asyncio
from pathlib import Path
from src.session.events import EventBus
from src.session.models import Attempt, Session
from src.session.service import SessionService
from src.session.store import SessionStore
class _DummyIndex:
def index_session(self, session_id: str,... | 64 | 2,319 |
Vibe-Trading | agent/tests/test_metrics_inf_zero_equity.py | .py | """Regression: metrics and validation must not produce inf from zero equity.
pct_change() divides by the previous value. When an equity curve hits
zero (a blown-up account, a liquidation event), pct_change() produces
inf or -inf. fillna(0.0) only handles NaN, not inf, so the inf
propagates into std(), mean(), and ever... | 141 | 5,702 |
Vibe-Trading | agent/tests/test_mcp_new_tools.py | .py | """MCP exposure of the institutional-research & alternative-data tools.
Covers the four tools that reach the MCP surface by mirroring their own JSON
Schema (``get_institutional_holdings`` / ``etf_holdings`` /
``prediction_market`` / ``research_papers``) and the red-line regression that
guards *which* tools the MCP ser... | 355 | 12,823 |
Vibe-Trading | agent/tests/test_ccxt_loader_bounded.py | .py | """Regression tests for P12-b — the ccxt loader must fail fast instead of
hanging on a transient disconnect.
Pre-fix: `_fetch_one` called `exchange.fetch_ohlcv` with no per-call timeout,
no retry, and no wall-clock budget, so a flaky connection hung
`get_market_data` for 10+ minutes. Post-fix: bounded retry on the tra... | 145 | 5,200 |
Vibe-Trading | agent/tests/test_korea_backtest_smoke.py | .py | """End-to-end smoke test: backtest runs on Korean (KRX) symbols.
Drives ``KoreaEquityEngine`` so strategies can run on KOSPI/KOSDAQ data with
the Korea cost stack. This test feeds KRX-shaped bars through a fake loader +
trivial long signal and asserts:
1. The backtest completes and emits metrics + a run card.
2. ... | 148 | 5,449 |
Vibe-Trading | agent/tests/test_load_skill_paging.py | .py | """Regression: an oversized skill must be reachable, and the cut must be stated.
Skill documents are the implementation for much of this product — the bond
maths, the implied-vol solver, the impact models, the China market structure.
A tool result is capped at ``TOOL_RESULT_LIMIT`` characters and 31 of the 88
bundled ... | 110 | 3,962 |
Vibe-Trading | agent/tests/test_memory_orphan_recovery.py | .py | """Recovery of memory entries orphaned by the missing-suffix write bug."""
from pathlib import Path
import pytest
from src.memory.hierarchy import MemoryHierarchy
_ENTRY = "---\nname: alpha-note\ndescription: d\nmetadata:\n type: project\n---\n\nbody\n"
def test_extensionless_entry_is_recovered_and_becomes_visible(... | 56 | 1,988 |
Vibe-Trading | agent/tests/test_shareholder_count_tool.py | .py | """Tests for get_shareholder_count: success + error envelopes, HTTP mocked.
The Eastmoney datacenter call is mocked at ``get_json`` (imported into the tool
module), so no test reaches a live endpoint.
"""
from __future__ import annotations
import json
from unittest.mock import patch
from src.tools import shareholde... | 105 | 3,448 |
Vibe-Trading | agent/tests/test_runtime_triggers.py | .py | """Tests for live-runtime triggers (src/live/runtime/triggers.py, SPEC §7.5 c4).
The decision core is pure — it takes ``now_ms`` as an argument and reads no
clock — so every market-session / interval / event case is pinned to a fixed
epoch-millisecond instant and asserted deterministically.
"""
from __future__ import... | 228 | 8,591 |
Vibe-Trading | agent/tests/test_loader_volume_units.py | .py | """Pin the volume-unit declarations of equity loaders (HKUDS/Vibe-Trading#1062).
Every A-share source declares board lots (1 lot = 100 shares) — baostock's
native single-share volume is normalized at its loader boundary; the
tencent/eastmoney loaders are market-dependent (A-share lots vs HK shares).
These pins lock th... | 55 | 2,442 |
Vibe-Trading | agent/tests/test_telegram_split_fence_hang.py | .py | """Regression: telegram markdown split must not hang on long fenced bodies."""
from __future__ import annotations
import signal
import sys
import types
def _stub_telegram_deps() -> None:
"""Install minimal stubs so telegram.py imports without python-telegram-bot."""
def _mod(name: str) -> types.ModuleType:... | 114 | 3,239 |
Vibe-Trading | agent/tests/test_runtime_reconcile.py | .py | """Tests for crash recovery + position reconciliation (SPEC §7.5 component 5).
Drives each delta class with fabricated broker snapshots (no live broker), and
asserts the load-bearing invariants:
* classification (matched / unknown_fill / orphan_order / mid_order_ambiguous),
* ``is_safe`` / ``requires_halt`` derive co... | 352 | 13,076 |
Vibe-Trading | agent/tests/test_load_equity_aliases.py | .py | """Regression: equity.csv may use nav/value instead of equity."""
from __future__ import annotations
from pathlib import Path
import pandas as pd
import pytest
from backtest.validation import _load_equity
def test_load_equity_accepts_nav_column(tmp_path: Path) -> None:
arts = tmp_path / "artifacts"
arts.m... | 49 | 1,489 |
Vibe-Trading | agent/tests/test_split_message_nonpositive.py | .py | """Regression: split_message must not hang on non-positive max_len."""
from __future__ import annotations
from src.channels.utils import split_message
def test_split_message_nonpositive_max_len_returns_unsplit() -> None:
content = "hello world"
assert split_message(content, max_len=0) == [content]
asser... | 56 | 2,482 |
Vibe-Trading | agent/tests/test_swarm_token_tracking.py | .py | """Tests for real-token propagation from LangChain through to swarm totals.
The swarm's ``total_input_tokens`` / ``total_output_tokens`` used to be
character-count guesses (``len(json.dumps(messages)) // 4``) — wrong by
20-50% for English prompts and dramatically wrong for CJK / Thai /
emoji-heavy traffic. LangChain a... | 169 | 6,744 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.