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_models.py | .py | """Tests for backtest data models (Position, TradeRecord, EquitySnapshot)."""
from __future__ import annotations
import pandas as pd
import pytest
from backtest.models import EquitySnapshot, Position, TradeRecord
class TestPosition:
def test_creation(self) -> None:
pos = Position(
symbol="A... | 90 | 2,730 |
Vibe-Trading | agent/tests/test_global_futures_engine.py | .py | """Tests for GlobalFuturesEngine market rules.
Validates:
- T+0, both long and short allowed
- Equity index price-limit enforcement (7% simplified)
- Commodity futures: no price limit
- Integer contract rounding
- Per-contract commission
- Contract multiplier lookup
- Product code extraction
"""
from __... | 225 | 7,252 |
Vibe-Trading | agent/tests/test_futu_connector_period_hour_case.py | .py | """Futu connector period map must treat project-style 1H/4H as hour bars."""
from __future__ import annotations
from src.trading.connectors.futu import sdk as futu_sdk
def test_kltype_map_accepts_project_hour_tokens() -> None:
assert futu_sdk._KLTYPE_MAP["1H"] == "K_60M"
assert futu_sdk._KLTYPE_MAP["4H"] ==... | 68 | 2,393 |
Vibe-Trading | agent/tests/test_pattern_tool_double_top_abs_avg.py | .py | """Regression test for double_top_bottom pattern detection on negative price series.
Locks out a bug where double_top_bottom used `abs(v1 - v2) / avg` instead of
`abs(v1 - v2) / abs(avg)` in the peaks loop, causing false double top detections
for negative price series because division by a negative average yielded a
n... | 23 | 1,121 |
Vibe-Trading | agent/tests/test_composite_engine_fallback.py | .py | """Tests for CompositeEngine fallback when an unknown symbol is encountered."""
from __future__ import annotations
import pytest
from backtest.engines.composite import CompositeEngine
class TestCompositeEngineFallback:
"""Verify that CompositeEngine does not crash on unknown symbols."""
def test_unknown_s... | 53 | 2,294 |
Vibe-Trading | agent/tests/test_northbound_tool.py | .py | """Tests for get_northbound_flow: success + error envelopes, HTTP fully mocked.
All Eastmoney HTTP is mocked at ``src.tools.northbound_tool.get_json`` (the name
the tool imported), so no test touches a live Eastmoney endpoint.
"""
from __future__ import annotations
import json
from unittest.mock import patch
from s... | 161 | 5,947 |
Vibe-Trading | agent/tests/test_trace_writer.py | .py | """TraceWriter offload and path-safety tests."""
from __future__ import annotations
import json
import logging
import os
import stat
from pathlib import Path
import pytest
import src.agent.trace as trace_mod
from src.agent.trace import TraceWriter
def _raw_entries(trace_dir: Path) -> list[dict]:
return [
... | 310 | 10,165 |
Vibe-Trading | agent/tests/test_mandate_forex.py | .py | """Forex/CFD mandate vocabulary + lot-aware gate sizing hook (MT5 groundwork).
Covers the three Part-1 surfaces of the MT5/Exness integration:
* ``InstrumentType.FOREX`` / ``InstrumentType.CFD`` and ``AssetClass.FOREX``
exist, parse from mandate JSON under schema v1, and route through
``check_mandate`` exactly li... | 360 | 13,406 |
Vibe-Trading | agent/tests/test_slack_table_edge_columns.py | .py | """Slack markdown tables must keep empty leading/trailing columns."""
from __future__ import annotations
import re
import sys
import types
def _stub_slack_deps() -> None:
"""Install minimal stubs so slack.py imports without slack_sdk/slackify."""
def _mod(name: str) -> types.ModuleType:
mod = types... | 69 | 2,195 |
Vibe-Trading | agent/tests/test_halt.py | .py | """Tests for the live-trading kill switch (src/live/halt.py, SPEC Consent §4).
The kill switch is a pure-filesystem sentinel — independent of any LLM/agent
state — so these tests exercise it purely through the filesystem.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from src.live i... | 151 | 5,532 |
Vibe-Trading | agent/tests/test_msteams_inbound_body_limit.py | .py | """Security regression tests for the MSTeams inbound webhook body bound."""
from __future__ import annotations
import pytest
from src.channels.msteams import (
MSTEAMS_MAX_INBOUND_BODY_BYTES,
msteams_validate_content_length,
)
@pytest.mark.parametrize("raw", ["0", None])
def test_absent_or_zero_length_is_a... | 56 | 1,564 |
Vibe-Trading | agent/tests/test_readonly_default.py | .py | """Live channel OFF-by-default + read-only-default invariants (SPEC §7.4).
This gate encodes the four SPEC invariants end to end:
1. The seeded ``robinhood`` config's ``enabled_tools`` contains EXACTLY the
curated READ tool names (and never ``"*"``). This is the structural defense
that catches finding #1 (seed/... | 327 | 12,377 |
Vibe-Trading | agent/tests/test_principal_wiring.py | .py | """The Principal must actually reach a stored Session.
`Session.owner` and `_validate_api_auth` returning a Principal were both added
without anything connecting them, so every session's owner was None. A field
that is always None carries the same information as no field, which is why the
wiring needs its own tests ra... | 131 | 4,222 |
Vibe-Trading | agent/tests/test_runtime_scheduler.py | .py | """Tests for the live-runtime scheduler (src/live/runtime/scheduler.py,
SPEC.md §7.5 #1).
Two layers:
* pure decision helpers (``earliest_next_run`` / ``due_jobs`` /
``compute_sleep_ms`` / ``advance_after_fire``) — no clock, ``now_ms`` passed
in, fully deterministic.
* the async ``Scheduler`` loop — driven with ``... | 199 | 6,518 |
Vibe-Trading | agent/tests/test_report_audit_empty_table_cells.py | .py | """report_audit must keep empty table cells so values stay under the right header."""
from __future__ import annotations
from src.tools.report_audit_tool import _parse_md_tables, extract_data_points
def test_parse_md_tables_keeps_empty_mid_cell_alignment() -> None:
lines = [
"| Metric | Q1 | Q2 |",
... | 32 | 988 |
Vibe-Trading | agent/tests/test_cli_live.py | .py | """Tests for the connector-first live CLI surface + REPL intercepts (P6).
Covers SPEC.md §9 Decision 1 (CLI surface table) and Consent §2/§4:
* The ``connector`` subcommand group dispatches each verb to the right handler.
* Connector live commands trip/clear the kill switch on disk.
* Live status/mandate helpers are ... | 809 | 33,283 |
Vibe-Trading | agent/tests/test_nonpositive_returns.py | .py | """Sign-safe returns: the buy-and-hold path must not assume positive prices.
Issue #872. ``close.pct_change()`` assumes ``price[t-1] > 0``. As the divisor
approaches zero an ordinary absolute move reads as an enormous percentage move,
so the compounded benchmark explodes (+39,560% on a real power-price run); at
exactl... | 173 | 6,340 |
Vibe-Trading | agent/tests/test_finnhub_interval_reject.py | .py | """Finnhub 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 finnhub_loader as fh
def test_unsupported_interval_does_not_hit_api() -> None:
"""Runner ``1H`` must not fall through ... | 69 | 2,658 |
Vibe-Trading | agent/tests/test_base_engine.py | .py | """Tests for BaseEngine shared logic: _align, _close_position, _calc_equity.
Uses ChinaAEngine as a concrete implementation since BaseEngine is abstract.
"""
from __future__ import annotations
import json
from dataclasses import FrozenInstanceError
import numpy as np
import pandas as pd
import pytest
from backtest... | 790 | 30,853 |
Vibe-Trading | agent/tests/test_signal_alignment_perf.py | .py | """Signal alignment optimization regression tests.
Verifies:
1. Optimized _align() produces identical results to reference implementation
2. Performance target: 5000 bars x 50 symbols < 50ms (CI-safe; dev target 15-35ms)
3. End-to-end backtest equity curve unchanged (tolerance 1e-6)
"""
from __future__ import annotat... | 836 | 33,470 |
Vibe-Trading | agent/tests/test_china_a_engine.py | .py | """Tests for ChinaAEngine market rules.
Validates:
- T+1 lock: can't sell shares bought today
- No short selling
- Price limit (涨跌停) enforcement
- 100-share lot rounding
- Commission structure (min ¥5, stamp tax sell-only, transfer fee)
- Slippage
- Price limit detection helper
"""
from __future__ impor... | 274 | 9,472 |
Vibe-Trading | agent/tests/test_web_reader_privacy.py | .py | """Regression tests for read_url third-party (Jina) hardening.
Network is mocked; no live r.jina.ai calls. Asserts: HTTP errors surface
the upstream status + body for debugging; a cached snapshot is surfaced
via `cached: true`; `no_cache=True` sends the x-no-cache header while
the default path is byte-identical (no ex... | 78 | 2,344 |
Vibe-Trading | agent/tests/test_llm_provider_defaults.py | .py | """Regression coverage for current provider default model IDs."""
from __future__ import annotations
import json
from pathlib import Path
import cli
from cli.onboard import PROVIDERS as ONBOARD_PROVIDERS
from src.providers.capabilities import (
_provider_default_base_urls,
get_llm_credentials,
)
EXPECTED_P... | 180 | 7,312 |
Vibe-Trading | agent/tests/test_options_payoff_tool.py | .py | """Tests for the Agent-facing options_payoff tool envelope."""
from __future__ import annotations
import json
import pytest
from src.tools.options_payoff_tool import OptionsPayoffTool
def _spread_legs() -> list[dict[str, object]]:
"""Return a deterministic debit-spread fixture."""
return [
{"optio... | 137 | 4,349 |
Vibe-Trading | agent/tests/test_doc_reader_inverted_pages.py | .py | """Inverted PDF page ranges must raise, not silently read nothing."""
from __future__ import annotations
import pytest
from src.tools.doc_reader_tool import _parse_pages
def test_inverted_page_range_raises() -> None:
with pytest.raises(ValueError, match="inverted page range"):
_parse_pages("10-5", 20)
... | 21 | 497 |
Vibe-Trading | agent/tests/test_session_timestamp_timezone.py | .py | from datetime import datetime
from src.session.models import Attempt, Message, Session
def test_session_models_emit_timezone_aware_iso_timestamps() -> None:
session = Session()
message = Message()
attempt = Attempt()
for value in (session.created_at, session.updated_at, message.created_at, attempt.c... | 19 | 615 |
Vibe-Trading | agent/tests/test_special_token_neutralization.py | .py | """Tests for chat-template control-token neutralization (GHSA-v8fm).
External content must not be able to forge role boundaries via ChatML / Llama
special tokens. ``neutralize_special_tokens`` defangs those tokens by inserting a
zero-width space (U+200B) right after the opening delimiter char, and the shared
``with_se... | 168 | 5,749 |
Vibe-Trading | agent/tests/test_shoonya_empty_string_numeric.py | .py | """Regression: Shoonya SDK must tolerate empty-string numeric fields.
The Shoonya API frequently returns ``""`` for unset numeric fields (e.g.
``netavgprc``, ``lp``, ``prc``). A bare ``float(item.get("field", 0))`` crashes
with ``ValueError`` because the ``.get`` default only fires on a *missing* key,
not on an empty... | 176 | 6,075 |
Vibe-Trading | agent/tests/test_bench_multiple_testing.py | .py | """Tests for the multiple-testing block wired into run_bench.
`n_alphas_tested` has been carried in the bench result since it was written and
has only ever been displayed. These tests pin the correction that now uses it,
and pin that adding it changed nothing else about the result.
"""
from __future__ import annotati... | 127 | 5,212 |
Vibe-Trading | agent/tests/test_swarm_run_metadata.py | .py | """Unit tests for run-level provider/model metadata on SwarmRun.
The fields capture which LLM provider/model the swarm was launched against
so ``.swarm/runs/<id>/run.json`` carries enough context for cost audits
and post-hoc debugging. The tests assert the new fields are accepted,
default cleanly, and that legacy run.... | 343 | 11,445 |
Vibe-Trading | agent/tests/test_upload_security.py | .py | """Security regression tests for upload file type restrictions."""
from __future__ import annotations
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
import api_server
@pytest.fixture
def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
monkeypatch.setatt... | 44 | 1,056 |
Vibe-Trading | agent/tests/test_sentiment_tool.py | .py | """Tests for the sentiment analysis tool."""
import json
from unittest.mock import patch
from src.tools.sentiment_tool import (
SentimentTool,
_score_text,
_tokenize,
)
class TestTokenize:
def test_empty(self):
assert _tokenize("") == []
def test_punctuation_only(self):
assert _... | 184 | 7,305 |
Vibe-Trading | agent/tests/test_validation_cli.py | .py | from __future__ import annotations
import json
import math
from pathlib import Path
import tempfile
import pytest
from backtest import validation
def test_rejects_missing_run_dir_argument() -> None:
with pytest.raises(SystemExit, match="Usage: python -m backtest.validation <run_dir>"):
validation._pars... | 85 | 2,830 |
Vibe-Trading | agent/tests/test_spa_deep_link.py | .py | """Regression tests for the SPA deep-link middleware in ``api_server``.
The middleware intercepts browser navigation (``Accept: text/html``) to
SPA pages that share a path with an API endpoint, serving the SPA shell
instead. It must NOT intercept API-only paths even when called with a
text/html accept header — the mat... | 51 | 1,831 |
Vibe-Trading | agent/tests/test_upload_api.py | .py | """Regression tests for /upload streaming + size enforcement.
Pinned by PR #53 (fix: stream uploads while enforcing API size limit). The previous
implementation read the entire file into memory before checking MAX_UPLOAD_SIZE, so
oversized payloads could exhaust server memory before being rejected. These tests
shrink ... | 216 | 7,299 |
Vibe-Trading | agent/tests/test_playbooks_surface.py | .py | """Entry-point contracts for the scheduled-research playbook catalogue.
The templates themselves are covered by ``tests/test_research_playbooks.py``.
This module covers the three surfaces a user actually reaches them through, and
the properties that are easy to break from any of them:
* REST — ``GET /scheduled-runs/p... | 771 | 27,747 |
Vibe-Trading | agent/tests/test_eastmoney_daily_week_aliases.py | .py | """Eastmoney KLT map must accept lowercase 1d/1w like project 1D/1W tokens."""
from __future__ import annotations
from backtest.loaders.eastmoney_client import KLT_BY_INTERVAL
def test_lowercase_1d_and_1w_map_like_project_tokens() -> None:
assert KLT_BY_INTERVAL["1d"] == KLT_BY_INTERVAL["1D"] == 101
assert ... | 16 | 505 |
Vibe-Trading | agent/tests/test_rsshub_events_provider.py | .py | """Unit tests for the RSSHub event/sentiment provider (no network)."""
from __future__ import annotations
import pandas as pd
import pytest
from backtest.loaders.rsshub_events import (
DEFAULT_FEEDS,
DEFAULT_TIMEOUT_S,
EVENT_COLUMNS,
EventProviderError,
FeedSpec,
RSSHubEventProvider,
Unkn... | 271 | 9,660 |
Vibe-Trading | agent/tests/test_alpha_compare_api.py | .py | """API tests for ``POST /alpha/compare`` + its SSE stream.
Deterministic by construction — no network, no flaky background-timing:
* **validation** runs through the real ``CompareRequest`` pydantic model via
``TestClient.post`` (rejection happens before any worker spawns);
* the **worker** (``_run_compare_blocking`... | 196 | 7,270 |
Vibe-Trading | agent/tests/test_qveris_routes.py | .py | from __future__ import annotations
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
import api_server
from src.api import qveris_routes
from src.tools import qveris_tool as qt
@pytest.fixture
def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
monkeypatch.... | 152 | 4,788 |
Vibe-Trading | agent/tests/test_local_source_routing.py | .py | """Tests that an explicit local data source is honored end to end.
Covers the two halves of the bug:
1. Engine routing follows the instrument market, not the loader name
(local AAPL.US -> GlobalEquityEngine, not CryptoEngine).
2. Benchmark fetch goes through the configured source's loader instead of
unconditiona... | 185 | 6,326 |
Vibe-Trading | agent/tests/test_state_fsync.py | .py | """Durability regression: RunStateStore._write_json must fsync.
A crash between write() and the kernel flushing its page cache can leave
state.json truncated or empty. _write_json now writes in binary mode and
fsyncs the file descriptor before closing.
"""
from __future__ import annotations
import json
from pathlib ... | 40 | 1,208 |
Vibe-Trading | agent/tests/test_baostock_loader.py | .py | """Tests for baostock_loader: code format handling.
Ensures both baostock native (sh.601398) and tushare-style (601398.SH) codes work.
"""
from backtest.loaders.baostock_loader import _is_a_share
class TestIsAShareCodeFormat:
"""Verify _is_a_share accepts both baostock native and tushare-style codes."""
def... | 151 | 5,875 |
Vibe-Trading | agent/tests/test_advisory.py | .py | """Advisory interface and gate integration tests (#317).
Covers the PreTradeAdvisoryInterface contract, MockAdvisory behavior,
AdvisoryOrchestrator fail-open semantics, and LiveOrderGuardTool advisory
wiring (disabled by default, enabled with env var, observational only).
"""
from __future__ import annotations
impor... | 407 | 14,390 |
Vibe-Trading | agent/tests/test_tool_result_paging.py | .py | """Regression: an oversized tool result must be paged, and any cut declared.
A tool result is capped at ``TOOL_RESULT_LIMIT`` characters and the cut used to
be silent. For a JSON envelope it also lands mid-structure, so the model got a
broken fragment and read the records that survived as the whole answer.
Measured li... | 198 | 7,027 |
Vibe-Trading | agent/tests/test_mcp_streamable_http_integration.py | .py | """Integration tests: full-stack streamable HTTP MCP client path with FastMCP.
These tests spawn an actual FastMCP streamable HTTP server process
(agent/tests/fixtures/fake_mcp_streamable_http_server.py) and exercise the
entire path:
load_agent_config()
-> build_registry(agent_config=...)
-> M... | 138 | 5,289 |
Vibe-Trading | agent/tests/test_validation.py | .py | """Tests for backtest validation module.
Validates:
- Monte Carlo permutation test: p-value, output structure
- Bootstrap Sharpe CI: confidence interval bounds, prob_positive
- Walk-Forward analysis: window splitting, consistency metrics
- run_validation dispatcher
"""
from __future__ import annotations
impo... | 425 | 16,374 |
Vibe-Trading | agent/tests/test_swarm_status_hydration.py | .py | """Regression tests for issue #132 — swarm status visibility & long-run MCP.
Coverage map:
1. ``hydrate_run`` merges live ``tasks/*.json`` and stays side-effect-free.
2. ``get_swarm_status`` surfaces both live progress and an ``is_stale`` flag.
3. ``run_swarm`` supports ``start_only`` and never returns "error" for a
... | 882 | 32,674 |
Vibe-Trading | agent/tests/test_mt5_loader.py | .py | """MT5 backtest data loader tests (Windows-only SDK, faked here).
The real ``MetaTrader5`` package never installs on CI's ubuntu runner; the
loader lazy-imports it, so tests inject a fake module via ``sys.modules`` and
exercise symbol resolution, interval mapping, the frame contract, config
plumbing, and graceful degr... | 280 | 11,022 |
Vibe-Trading | agent/tests/test_audit_redact.py | .py | """Tests for the live-action audit ledger (src/live/audit.py, SPEC Consent §5).
Focus: every record is redacted BEFORE it touches the ledger or the SSE bus, the
ledger is append-only, and the accountability refs (mandate/consent) survive
redaction so the chain back to the authorizing user click stays intact.
"""
from... | 308 | 10,642 |
Vibe-Trading | agent/tests/test_swarm_tool_preset_matching.py | .py | """Regression coverage for SwarmTool natural-language preset routing."""
from __future__ import annotations
import json
import src.tools.swarm_tool as swarm_tool
def test_explicit_preset_name_wins_over_keyword_scoring() -> None:
prompt = (
"[Swarm Team Mode] Use the investment_committee preset to evalu... | 60 | 1,866 |
Vibe-Trading | agent/tests/test_mandate_model.py | .py | """Mandate model + read-only store: round-trip, absent→None, expiry parse."""
from __future__ import annotations
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path
import pytest
import src.live.paths as paths
from src.live.mandate.model import (
MANDATE_SCHEMA_VERSION,
A... | 194 | 7,174 |
Vibe-Trading | agent/tests/test_killswitch_blocks_orders.py | .py | """Kill switch blocks live orders at the gate (SPEC.md Consent §4, gate-level).
With a committed mandate and the HALT flag set, ``LiveOrderGuardTool.execute``
must return a refusal and make NO remote call (the mock adapter's order tool is
never invoked). Read tools are unaffected by HALT — only the gate refuses.
"""
... | 143 | 4,905 |
Vibe-Trading | agent/tests/test_get_market_data_unresolved.py | .py | """Regression test for P05 — get_market_data must not silently drop a
requested symbol that returned no data.
Pre-fix: the result dict only held winners, so a typo / wrong-suffix /
delisted / no-data code just vanished — indistinguishable from "no data",
and a loader exception lost every already-resolved symbol. Post-... | 97 | 3,351 |
Vibe-Trading | agent/tests/test_loader_retry_helpers.py | .py | """Unit tests for the shared loader retry/budget helpers.
The ccxt + okx integration tests already exercise these helpers via their
real loaders; these tests pin the helper semantics directly so future
loaders that adopt :func:`retry_with_budget` and :func:`check_budget`
inherit the same guarantees:
- Happy path runs... | 521 | 16,920 |
Vibe-Trading | agent/tests/test_progress.py | .py | """Tests for agent.progress (heartbeat + structured progress emission)."""
from __future__ import annotations
import logging
import threading
import time
import pytest
from src.agent.progress import (
HeartbeatTimer,
ProgressEvent,
_get_emitter,
_set_emitter,
emit_progress,
)
# ---------- Prog... | 187 | 6,032 |
Vibe-Trading | agent/tests/test_cli_connector_renderers.py | .py | """Regression (#735): connector CLI renderers must tolerate broker_sdk schemas.
The shared ``connector positions`` / ``connector account`` renderers were written
for the IBKR result shape (``position``/``avg_cost``/``sec_type``/``summary``).
Longbridge (and other ``broker_sdk`` connectors) return ``quantity``/``cost_p... | 153 | 5,014 |
Vibe-Trading | agent/tests/test_execution_causality.py | .py | """Causality and ordering regressions for the shared execution loop."""
from __future__ import annotations
import pandas as pd
import pytest
from backtest.engines.base import BaseEngine
from backtest.engines.china_a import ChinaAEngine
from backtest.engines.china_futures import ChinaFuturesEngine
from backtest.engin... | 226 | 7,303 |
Vibe-Trading | agent/tests/test_akshare_nona_share_interval.py | .py | """AKShare US/HK/ETF/forex must not return daily bars for intraday intervals."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import pandas as pd
import pytest
from backtest.loaders.akshare_loader import DataLoader
def _us_daily_frame() -> pd.DataFrame:
return pd.DataFrame(
... | 64 | 2,132 |
Vibe-Trading | agent/tests/test_mt5_interval_lowercase.py | .py | """MT5 loader must accept trading-convention lowercase 1h/4h/1d intervals."""
from __future__ import annotations
from backtest.loaders.mt5_loader import _INTERVAL_MAP
def test_lowercase_hour_day_aliases_match_project_tokens() -> None:
assert _INTERVAL_MAP["1h"] == "TIMEFRAME_H1"
assert _INTERVAL_MAP["1H"] =... | 15 | 533 |
Vibe-Trading | agent/tests/test_trade_journal.py | .py | """Tests for the trade journal analyzer and its broker-format parsers.
Covers ``src.tools.trade_journal_parsers`` (format detection, side/symbol
normalization, market inference, end-to-end parse) and
``src.tools.trade_journal_tool`` (FIFO pairing, profile/behavior metrics,
filtering, and the analyze_trade_journal erro... | 692 | 22,826 |
Vibe-Trading | agent/tests/test_engine_metrics_json.py | .py | """Strict JSON for BaseEngine scalar metrics stdout."""
from __future__ import annotations
import json
import pandas as pd
import backtest.engines.base as base_mod
from backtest.metrics import calc_metrics
def test_engine_scalar_metrics_stdout_is_strict_json() -> None:
"""Explosive equity sets annual_return=i... | 31 | 1,073 |
Vibe-Trading | agent/tests/test_fundamental_filter_example.py | .py | from __future__ import annotations
import importlib.util
from pathlib import Path
import pandas as pd
_AGENT_ROOT = Path(__file__).resolve().parents[1]
def _load_example_module():
path = _AGENT_ROOT / "src" / "skills" / "fundamental-filter" / "example_signal_engine.py"
spec = importlib.util.spec_from_file... | 47 | 1,502 |
Vibe-Trading | agent/tests/test_cli_parse_table_edge_columns.py | .py | """CLI transcript tables must keep empty leading/trailing columns."""
from __future__ import annotations
from cli.ui.transcript import _parse_table, _split_row
def test_split_row_keeps_empty_edge_cells() -> None:
assert _split_row("|Name|Qty||") == ["Name", "Qty", ""]
assert _split_row("||Name|Qty|") == [""... | 46 | 1,285 |
Vibe-Trading | agent/tests/test_market_data_tool.py | .py | from __future__ import annotations
import json
import pandas as pd
from src.market_data import fetch_market_data_json
from src.swarm.models import SwarmAgentSpec
from src.swarm.presets import list_presets, load_preset
from src.swarm.worker import build_worker_prompt
from src.tools import build_swarm_registry
def t... | 249 | 7,428 |
Vibe-Trading | agent/tests/test_pykrx_loader.py | .py | """Tests for pykrx_loader: symbol mapping, interval contract, normalization.
Unit-level only — no network access and no real ``pykrx`` dependency: the
normalization path is exercised through ``_normalize`` with synthetic
pykrx-shaped frames (Korean column names, date index), and ``_fetch_one`` is
driven through a fake... | 254 | 9,556 |
Vibe-Trading | agent/tests/test_swarm_retry_artifact_isolation.py | .py | """Regression tests: a retried worker attempt must not inherit stale
artifacts (report.md, or any other tool-written file) from a prior failed
attempt for the same task.
``_run_worker_with_retries`` re-invokes ``run_worker`` against the *same*
``artifact_dir`` on every attempt (``mkdir(parents=True, exist_ok=True)``,
... | 282 | 10,483 |
Vibe-Trading | agent/tests/test_tiger_period_hour_case.py | .py | """Tiger period map must treat project-style 1H/4H as hour bars, not day."""
from __future__ import annotations
from src.trading.connectors.tiger import sdk as tg
class _FakeTigerQuote:
def __init__(self) -> None:
self.calls: list[dict] = []
def get_bars(self, symbols, period=None, limit=None):
... | 37 | 1,173 |
Vibe-Trading | agent/tests/test_runtime_flatten.py | .py | """Tests for the preemptive kill-switch sweep (src/live/runtime/flatten.py).
SPEC §7.5 component 6. Verifies cancel-then-flatten ordering, the cancel-only
default when the mandate forbids flatten, the no-retry-on-error contract
(SPEC §8.5), and that every broker call is audited.
"""
from __future__ import annotations... | 209 | 7,611 |
Vibe-Trading | agent/tests/test_realized_turnover.py | .py | """Regression tests for execution-derived turnover metrics."""
from __future__ import annotations
from pathlib import Path
import pandas as pd
import pytest
from backtest.engines.base import BaseEngine
from backtest.engines.china_a import ChinaAEngine
from backtest.engines.composite import CompositeEngine
from back... | 236 | 7,581 |
Vibe-Trading | agent/tests/test_memory_gc.py | .py | """Tests for memory GC, find_relevant weighting, and RememberTool reinforce."""
from __future__ import annotations
import time
from pathlib import Path
import pytest
from src.config.accessor import reset_env_config
from src.memory.lifecycle import MemoryLifecycle
from src.memory.persistent import PersistentMemory
f... | 298 | 12,492 |
Vibe-Trading | agent/tests/test_content_filter_gemini_detection.py | .py | """Gemini content-filter detection regression tests.
Gemini surfaces content moderation via uppercase FinishReason enum values
(SAFETY, RECITATION, BLOCKLIST, ...) instead of OpenAI's lowercase
"content_filter". Google's OpenAI-compatible endpoint passes these through
unmapped, so ``_parse_response`` must recognise bo... | 84 | 3,013 |
Vibe-Trading | agent/tests/test_yahoo_client.py | .py | """Tests for yahoo_client: symbol mapping, payload parsing, crumb retry, errors.
All HTTP is mocked — no test ever reaches a live Yahoo endpoint. The client
imports ``throttled_get`` / ``throttled_get_json`` from
:mod:`backtest.loaders._http` into its own namespace, so we monkeypatch those
names on the ``yahoo_client`... | 372 | 13,996 |
Vibe-Trading | agent/tests/test_terminal_close_accounting.py | .py | """Regression tests for end-of-backtest liquidation accounting."""
from __future__ import annotations
import pandas as pd
import pytest
from backtest.engines.base import BaseEngine
from backtest.engines.china_futures import ChinaFuturesEngine
from backtest.engines.composite import CompositeEngine
from backtest.engin... | 158 | 5,233 |
Vibe-Trading | agent/tests/test_fundamental_schema.py | .py | from __future__ import annotations
import json
from pathlib import Path
import pandas as pd
import pytest
from backtest.loaders._fundamental_schema import (
DERIVED_FIELDS,
RAW_FIELDS,
SEC_CONCEPT_MAP,
list_supported_fields,
resolve_field,
)
EXPECTED_RAW_FIELDS = {
"revenue",
"cogs",
... | 115 | 3,729 |
Vibe-Trading | agent/tests/test_cli_version.py | .py | """Regression tests for issue #156 — CLI version must track pyproject.toml.
The shipped 0.1.8 wheel reported ``0.1.7`` because a hardcoded constant was
not bumped on release. ``cli/_version.py`` now derives the version from package
metadata, falling back to reading ``pyproject.toml`` directly, so there is no
constant ... | 43 | 1,591 |
Vibe-Trading | agent/tests/test_akshare_loader.py | .py | """Tests for AKShare loader symbol routing.
Pins issues #50 (ETF) and #54 (forex): the previous _fetch_one routed every
unrecognized code to stock_zh_a_hist, masking ETFs (518880.SH) and forex pairs
(EURUSD) as broken A-shares. These tests use mocks so they don't hit the
network — real-data smoke is in tests/_smoke_ak... | 177 | 6,121 |
Vibe-Trading | agent/tests/test_prediction_market_tool.py | .py | """Tests for prediction_market_tool: validation, normalization, batch isolation.
All HTTP is mocked — no test ever reaches a live Polymarket endpoint. The tool
imports ``throttled_get_json`` from :mod:`backtest.loaders._http` into its own
namespace, so we monkeypatch that name on the ``prediction_market_tool`` module.... | 1,066 | 47,993 |
Vibe-Trading | agent/tests/test_oauth_token_cache.py | .py | """Unit tests for the OAuth token cache backend (``_build_token_store``).
These guard the security-critical invariants of the live-channel token cache:
* The cache directory is created ``0700`` and ``~`` is expanded.
* Tokens survive a fresh store instance (persistence round-trip) and are read
back from disk, never... | 304 | 11,328 |
Vibe-Trading | agent/tests/test_research_playbooks.py | .py | """Tests for the scheduled-research playbook catalogue.
Covers: bundled-template invariants (schedule/timezone validity, the
missing-data rule, no tool names in any body), the markdown+frontmatter loader
and its failure modes, variable rendering, the user-directory override, and
job construction against the real job s... | 426 | 18,068 |
Vibe-Trading | agent/tests/test_error_path_redaction.py | .py | """Regression tests for P10 — user-facing errors must not leak internal
absolute filesystem paths (CWE-209 / CWE-497).
Pre-fix: an unknown preset / workspace-escape / missing run dir embedded the
full install path (OS username, .venvs/site-packages topology). Post-fix the
message keeps the actionable bits (name, Avail... | 125 | 4,811 |
Vibe-Trading | agent/tests/test_state_migration_wiring.py | .py | """Entry points run the one-time legacy-state migration (issue #904)."""
from __future__ import annotations
import pytest
from src.config import migrate
@pytest.fixture()
def record_migration(monkeypatch: pytest.MonkeyPatch) -> list[int]:
calls: list[int] = []
monkeypatch.setattr(
migrate, "migrate... | 172 | 4,643 |
Vibe-Trading | agent/tests/test_sec_edgar_client.py | .py | """Tests for sec_edgar_client: ticker->CIK mapping, CIK padding, payload parse.
All HTTP is fully mocked by patching ``throttled_get_json`` in the client
module — no test makes a real SEC request.
"""
from unittest.mock import patch
import pytest
import requests
from backtest.loaders import sec_edgar_client as sec
... | 189 | 7,117 |
Vibe-Trading | agent/tests/test_cli_hypothesis.py | .py | """Tests for the ``vibe-trading hypothesis`` CLI subcommands."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import pytest
from src.hypotheses import HypothesisRegistry
from src.hypotheses.cli_handlers import (
add_subparser,
dispatch,
)
def _make_registry(tmp_p... | 314 | 10,458 |
Vibe-Trading | agent/tests/test_mt5_connector_project_period_aliases.py | .py | """MT5 connector must map project-style 1H/4H/1D periods to hour/day bars."""
from __future__ import annotations
from src.trading.connectors.mt5.reads import _TIMEFRAME_MAP
def test_timeframe_map_accepts_project_hour_day_tokens() -> None:
assert _TIMEFRAME_MAP["1H"] == "TIMEFRAME_H1"
assert _TIMEFRAME_MAP["... | 24 | 961 |
Vibe-Trading | agent/tests/test_okx_loader_interval_case.py | .py | """OKX loader must keep lowercase 1h/4h as hour bars, not silent daily."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from backtest.loaders import okx as okx_mod
def _fetch_with_interval(interval: str) -> list[str]:
seen: list[str] = []
def fake_fetch(self, session, symb... | 41 | 1,299 |
Vibe-Trading | agent/tests/test_cashflow_analytics_tool.py | .py | """Tests for the agent-facing cashflow_performance tool envelope."""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from src.tools.cashflow_analytics_tool import CashFlowPerformanceTool
def _valuations() -> list[dict[str, object]]:
"""Return the fixture path: +10% on 100... | 238 | 7,913 |
Vibe-Trading | agent/tests/test_auth_precedence.py | .py | """GHSA-7wgj regression: API auth must check the configured key BEFORE trusting a loopback peer.
The bug: ``_validate_api_auth`` / ``require_event_stream_auth`` returned early on
``_is_local_client(request)`` *before* reading the configured API key, so a
loopback (or same-host reverse-proxy) peer was admitted with no ... | 142 | 4,796 |
Vibe-Trading | agent/tests/test_okx_bar_map.py | .py | """Tests for OKX period → bar mapping."""
from __future__ import annotations
from src.trading.connectors.okx.sdk import _BAR_MAP
def test_project_hour_tokens_map_to_hour_not_daily() -> None:
assert _BAR_MAP.get("1H") == "1H"
assert _BAR_MAP.get("4H") == "4H"
assert _BAR_MAP.get("1h") == "1H"
assert ... | 18 | 472 |
Vibe-Trading | agent/tests/test_mandate_commit_security.py | .py | """Security regressions for live mandate proposal commit boundaries."""
from __future__ import annotations
import json
import os
from pathlib import Path
import pytest
import src.live.paths as paths
from src.live.mandate.commit import CommitError, commit_mandate, save_proposal
pytestmark = pytest.mark.unit
def _... | 116 | 3,969 |
Vibe-Trading | agent/tests/test_journal_inverted_date_filter.py | .py | """Inverted journal date filters must raise, not silently empty the frame."""
from __future__ import annotations
import pandas as pd
import pytest
from src.tools.trade_journal_tool import _apply_filter
def _frame() -> pd.DataFrame:
return pd.DataFrame(
{
"datetime": pd.to_datetime(["2026-01... | 28 | 771 |
Vibe-Trading | agent/tests/test_packaging_dependencies.py | .py | """Packaging dependency regression tests."""
from __future__ import annotations
import tomllib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
def _normalized_requirement_name(requirement: str) -> str:
name = requirement.split(";", 1)[0]
for marker in ("[", "<", ">", "="):
name... | 156 | 5,063 |
Vibe-Trading | agent/tests/test_metrics_tracking_error.py | .py | """Regression: the information ratio's denominator must be reported.
``calc_metrics`` computed the annualised active-return standard deviation to
form the information ratio and then discarded it, so the 18-key return carried
no tracking error and no benchmark beta — the two numbers a benchmark-relative
mandate is writ... | 88 | 2,960 |
Vibe-Trading | agent/tests/test_classification.py | .py | """Read/write classification ladder: annotations, curated map wins, default-deny."""
from __future__ import annotations
from mcp.types import ToolAnnotations
from src.live.classification import ToolClass, classify_tool
from src.trading.connectors.ibkr.classification import IBKR_TOOL_CLASS
from src.trading.connectors... | 72 | 3,068 |
Vibe-Trading | agent/tests/test_tiingo_interval_reject.py | .py | """Tiingo must reject non-daily intervals instead of silently returning day bars."""
from __future__ import annotations
from unittest.mock import patch
from backtest.loaders import tiingo_loader as tg
def test_unsupported_interval_does_not_hit_api() -> None:
"""Runner ``1H`` must not fall through to Tiingo dai... | 49 | 1,596 |
Vibe-Trading | agent/tests/test_state_migration.py | .py | """One-time migration of code-relative state into the runtime root (issue #904)."""
from __future__ import annotations
from pathlib import Path
from src.config.migrate import migrate_legacy_state
def _seed(directory: Path, filename: str = "record.json") -> Path:
directory.mkdir(parents=True)
marker = direc... | 219 | 7,990 |
Vibe-Trading | agent/tests/test_swarm_worker_content_filter.py | .py | """Tests for content-filter skip logic in run_worker.
When the LLM returns ``content_filter_triggered=True``, the worker should
skip that iteration and continue instead of finalizing on empty/garbage
content. The worker injects a system message telling the agent to move on,
emits a ``content_filter_skipped`` event, an... | 221 | 7,598 |
Vibe-Trading | agent/tests/test_telegram_table_edge_columns.py | .py | """Telegram markdown tables must keep empty leading/trailing columns."""
from __future__ import annotations
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:
mod = types... | 82 | 2,029 |
Vibe-Trading | agent/tests/test_registry_mcp_integration.py | .py | """Integration tests for MCP tool injection into the tool registry (Phase 3)."""
from __future__ import annotations
import logging
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from src.config.schema import AgentConfig, MCPServerConfig
from src.tools import build_registry
from src.... | 294 | 11,733 |
Vibe-Trading | agent/tests/test_swarm_output_contract.py | .py | """Regression tests for P01 + P03 — swarm output contract.
A worker that produced no substantive deliverable (plan-only stub, mock
data, unparsed tool markup, raw tool envelope, or a data agent that made no
tool call and wrote no report) must NOT be reported ``completed``, and the
runtime must not fold ``timeout`` / `... | 431 | 16,392 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.