56 lines
2.3 KiB
Python
56 lines
2.3 KiB
Python
import pytest
|
|
from fastapi.testclient import TestClient
|
|
|
|
from app import main, scorecard
|
|
from app.store import Store
|
|
|
|
|
|
def test_fifty_now_fifty_later_with_a_gain(tmp_path):
|
|
s = Store(str(tmp_path / "m.db"), 0) # real use: start at zero, money comes via deposits
|
|
s.add_deposit(50, "first")
|
|
s.add_deposit(50, "next week")
|
|
assert s.invested() == 100
|
|
s.q("UPDATE paper_account SET cash = cash + 20") # trading made 20
|
|
assert s.q("SELECT cash FROM paper_account")[0]["cash"] == 120
|
|
assert [d["amount"] for d in s.deposits()] == [50, 50]
|
|
|
|
|
|
def test_withdrawals_cannot_exceed_cash_and_do_not_look_like_losses(tmp_path):
|
|
s = Store(str(tmp_path / "w.db"), 100)
|
|
s.day_start_equity("paper", 100)
|
|
s.add_deposit(-40)
|
|
assert s.invested() == 60 and s.day_start_equity("paper", 60) == 60
|
|
with pytest.raises(ValueError):
|
|
s.add_deposit(-500)
|
|
assert s.invested() == 60
|
|
|
|
|
|
def test_scorecard_return_counts_deposits(tmp_path):
|
|
s = Store(str(tmp_path / "s.db"), 0)
|
|
s.add_deposit(100)
|
|
s.log_equity(1000, 100.0); s.log_equity(2000, 120.0)
|
|
r = scorecard.build(s, 0)
|
|
assert r["return_pct"] == 20.0
|
|
|
|
|
|
def test_api_money_and_deposit(monkeypatch):
|
|
c = TestClient(main.app)
|
|
main.store.clear_history()
|
|
before = c.get("/api/money").json()
|
|
assert before["invested"] == before["start_cash"] and before["gain"] == pytest.approx(0)
|
|
assert c.post("/api/deposits", json={"secret": "nope", "amount": 50}).status_code == 401
|
|
assert c.post("/api/deposits", json={"secret": "s3cret", "amount": 0}).status_code == 422
|
|
r = c.post("/api/deposits", json={"secret": "s3cret", "amount": 50, "note": "<b>x</b>"}).json()
|
|
assert r["invested"] == before["invested"] + 50
|
|
assert r["value"] == pytest.approx(before["value"] + 50) # cash really arrived
|
|
assert r["gain"] == pytest.approx(0) # a deposit is not a gain
|
|
assert c.post("/api/deposits", json={"secret": "s3cret", "amount": -1e6}).status_code == 400
|
|
main.store.clear_history()
|
|
assert c.get("/api/money").json()["deposits"] == []
|
|
|
|
|
|
def test_api_answers_are_never_cached():
|
|
c = TestClient(main.app)
|
|
for path in ("/api/state", "/api/money", "/api/scorecard", "/health"):
|
|
assert c.get(path).headers["cache-control"] == "no-store"
|