"""End-to-end tests with news and LLM mocked out (no network, no API keys needed).""" import pytest from fastapi.testclient import TestClient from app import main, sentiment from app.sentiment import Verdict client = TestClient(main.app) def alert(symbol="ASML", action="buy", price=700.0, secret="s3cret"): return client.post("/webhook", json={"secret": secret, "symbol": symbol, "action": action, "price": price, "reason": "test"}) @pytest.fixture(autouse=True) def reset(monkeypatch): main.store.q("DELETE FROM paper_positions") main.store.q("DELETE FROM daily_equity") main.store.q("UPDATE paper_account SET cash = start_cash") main.state["kill_switch"] = False sentiment._cache.clear() monkeypatch.setattr(main.sentiment, "analyze", lambda q, **k: Verdict("bullish", 0.8, "Strong earnings.", ["h1"])) def test_wrong_secret_rejected(): assert alert(secret="nope").status_code == 401 def test_bullish_buy_full_size_then_sell_with_pnl(): r = alert().json() assert r["decision"] == "executed" and "full size" in r["reason"] assert r["order"]["qty"] == pytest.approx(1000 / 700, rel=1e-3) # 10% of 10,000 r = alert(action="sell", price=770).json() assert r["decision"] == "executed" and r["order"]["pnl"] > 0 def _cap(monkeypatch, eur): from dataclasses import replace from app import risk monkeypatch.setattr(risk, "settings", replace(risk.settings, max_order_eur=eur)) def test_order_cap_50_eur(monkeypatch): _cap(monkeypatch, 50) r = alert().json() # bullish: full size, but capped at €50 assert r["order"]["qty"] * 700 == pytest.approx(50, rel=1e-3) def test_order_cap_scales_with_news(monkeypatch): _cap(monkeypatch, 50) monkeypatch.setattr(main.sentiment, "analyze", lambda q, **k: Verdict("neutral", 0.5, "", [])) r = alert().json() # neutral: 75% of the €50 cap assert r["order"]["qty"] * 700 == pytest.approx(37.5, rel=1e-3) def test_alpaca_cap_converted_to_usd(monkeypatch): from dataclasses import replace from app import risk monkeypatch.setattr(risk, "settings", replace(risk.settings, max_order_eur=50, eur_usd_rate=1.1)) class FakeAlpaca: name = "alpaca" def equity(self): return 100000 def positions(self): return [] def has_position(self, s): return False d = risk.check_buy(FakeAlpaca(), "BTC/USD", Verdict("bullish", 0.9, "", []), 100000, False) assert d.allowed and d.amount == pytest.approx(55.0) def test_strong_bearish_news_vetoes_buy(monkeypatch): monkeypatch.setattr(main.sentiment, "analyze", lambda q, **k: Verdict("bearish", 0.9, "Profit warning.", ["h"])) r = alert().json() assert r["decision"] == "blocked" and "bearish" in r["reason"] def test_mild_bearish_halves_size(monkeypatch): monkeypatch.setattr(main.sentiment, "analyze", lambda q, **k: Verdict("bearish", 0.4, "Meh.", [])) r = alert().json() assert r["order"]["qty"] == pytest.approx(500 / 700, rel=1e-3) def test_filter_failure_blocks_buys_but_not_sells(monkeypatch): alert() # open a position while news is fine monkeypatch.setattr(main.sentiment, "analyze", lambda q, **k: Verdict("unavailable", 0, "down", [])) assert alert(symbol="ADYEN").json()["decision"] == "blocked" assert alert(action="sell").json()["decision"] == "executed" def test_no_double_buy_and_sell_without_position_ignored(): alert() assert alert().json()["decision"] == "blocked" assert alert(symbol="INGA", action="sell").json()["decision"] == "ignored" def test_kill_switch(): assert client.post("/api/kill", json={"secret": "s3cret", "on": True}).status_code == 200 assert alert().json()["decision"] == "blocked" def test_max_open_positions(): for s in ["ASML", "ADYEN", "INGA", "BTCUSD"]: assert alert(symbol=s, price=100).json()["decision"] == "executed" assert alert(symbol="ETHUSD", price=100).json()["reason"].startswith("max 4") def test_daily_loss_limit(): alert(price=100) main.store.q("UPDATE daily_equity SET start_equity = 11000") # pretend we're down ~9% today r = alert(symbol="ADYEN").json() assert r["decision"] == "blocked" and "daily loss" in r["reason"] def test_unknown_symbol_ignored(): assert alert(symbol="DOGE").json()["decision"] == "ignored" def test_llm_output_validation(): v = sentiment.parse({"sentiment": "Bullish", "confidence": 3, "summary": "x"}, []) assert v.sentiment == "bullish" and v.confidence == 1.0 with pytest.raises(ValueError): sentiment.parse({"sentiment": "to the moon"}, []) def test_missing_key_means_unavailable(monkeypatch): monkeypatch.undo() assert sentiment.analyze("ASML").sentiment == "unavailable" def test_dashboard_and_state(): alert() assert "Yote-In-Vest" in client.get("/").text s = client.get("/api/state").json() assert s["live_trading"] is False and s["events"][0]["decision"] == "executed" class FakeAlpaca: """Stands in for Alpaca so US-stock routing can be tested offline.""" name = "alpaca" def __init__(self, is_open): self.is_open, self.orders, self.held = is_open, [], set() def market_open(self): return self.is_open def equity(self): return 10000 def positions(self): return [] def has_position(self, s): return s in self.held def buy_notional(self, symbol, amount, price, asset_class="stock"): self.orders.append((symbol, amount, asset_class)); self.held.add(symbol) return {"broker": "alpaca", "symbol": symbol, "asset_class": asset_class} def close(self, symbol, price): self.held.discard(symbol); return {"broker": "alpaca", "side": "sell"} def test_us_stock_routes_to_alpaca_when_open(monkeypatch): fake = FakeAlpaca(is_open=True) monkeypatch.setattr(main, "alpaca", fake) r = alert(symbol="NVDA", price=180).json() assert r["decision"] == "executed" and fake.orders[0][0] == "NVDA" and fake.orders[0][2] == "stock" assert alert(symbol="NVDA", action="sell", price=190).json()["decision"] == "executed" def test_us_stock_skipped_when_market_closed(monkeypatch): monkeypatch.setattr(main, "alpaca", FakeAlpaca(is_open=False)) r = alert(symbol="SPY", price=600).json() assert r["decision"] == "blocked" and "market closed" in r["reason"] def test_crypto_trades_while_stock_market_closed(monkeypatch): fake = FakeAlpaca(is_open=False) monkeypatch.setattr(main, "alpaca", fake) assert alert(symbol="BTCUSD", price=67000).json()["decision"] == "executed" assert fake.orders[0][2] == "crypto"