feat(stove-api): expose estimate and operator controls
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
"""Boundary tests: authentication precedes body parsing; success and errors share a contract."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
import stove_api
|
||||
|
||||
|
||||
def _client():
|
||||
app = FastAPI()
|
||||
app.include_router(stove_api.secure)
|
||||
app.include_router(stove_api.public)
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_invalid_key_wins_over_invalid_body(monkeypatch):
|
||||
monkeypatch.setattr(stove_api.stove_keys, "authenticate", lambda secret, ip: {"status": "invalid_api_key"})
|
||||
response = _client().post("/api/v1/stove-estimate", content="not-json",
|
||||
headers={"Content-Type": "application/json", "X-API-Key": "wrong"})
|
||||
assert response.status_code == 401
|
||||
assert response.json()["code"] == "invalid_api_key"
|
||||
assert response.json()["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
def test_estimate_success_and_history(monkeypatch):
|
||||
calls = []
|
||||
key = {"id": 7, "limit_day": 1000, "ai_budget_rub_day": 300}
|
||||
monkeypatch.setattr(stove_api.stove_keys, "authenticate", lambda *args: {"status": "ok", "key": key})
|
||||
monkeypatch.setattr(stove_api.stove_history, "open_request", lambda **kw:
|
||||
{"admitted": True, "limit": 1000, "remaining": 999})
|
||||
monkeypatch.setattr(stove_api.stove_history, "finish_request", lambda *args, **kw: calls.append(kw))
|
||||
monkeypatch.setattr(stove_api.stove_pricing, "load", lambda parsed:
|
||||
{"valid_at": "III кв. 2026", "region": "Москва", "lines": []})
|
||||
monkeypatch.setattr(stove_api.stove_cache, "response_get", lambda key: None)
|
||||
monkeypatch.setattr(stove_api.stove_cache, "response_put", lambda *args, **kw: None)
|
||||
async def fill(prices, **kw):
|
||||
return prices
|
||||
monkeypatch.setattr(stove_api.stove_match, "fill", fill)
|
||||
response = _client().post("/api/v1/stove-estimate", json={"stove": {
|
||||
"kind": "bath", "bricks": {"ceramic": 1, "fireclay": 0}, "region": "Москва"}},
|
||||
headers={"X-API-Key": "test"})
|
||||
assert response.status_code == 200, response.text
|
||||
body = response.json()
|
||||
assert body["total"] is None
|
||||
assert body["missing_data"] == ["расценка на кладку банной печи: в базах нет", "ведомость материалов"]
|
||||
assert body["request_id"] == response.headers["X-Request-Id"]
|
||||
assert response.headers["Infosmeta-RateLimit-Remaining"] == "999"
|
||||
assert calls and calls[0]["http_status"] == 200
|
||||
|
||||
|
||||
def test_invalid_request_reports_field_path(monkeypatch):
|
||||
key = {"id": 7, "limit_day": 1000, "ai_budget_rub_day": 300}
|
||||
monkeypatch.setattr(stove_api.stove_keys, "authenticate", lambda *args: {"status": "ok", "key": key})
|
||||
monkeypatch.setattr(stove_api.stove_history, "open_request", lambda **kw:
|
||||
{"admitted": True, "limit": 1000, "remaining": 999})
|
||||
monkeypatch.setattr(stove_api.stove_history, "finish_request", lambda *args, **kw: None)
|
||||
response = _client().post("/api/v1/stove-estimate", json={"stove": {"kind": "bath"}},
|
||||
headers={"X-API-Key": "test"})
|
||||
assert response.status_code == 400
|
||||
assert response.json()["code"] == "invalid_request"
|
||||
assert "stove.bricks" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_protocol_and_schema_are_public():
|
||||
client = _client()
|
||||
assert client.get("/api/v1/stove-estimate/protocol").status_code == 200
|
||||
schema = client.get("/api/v1/stove-estimate/openapi.json").json()
|
||||
assert "stove" in schema["paths"]["/api/v1/stove-estimate"]["post"]["requestBody"]["content"]["application/json"]["schema"]["properties"]
|
||||
assert client.get("/api/v1/stove-estimate").json()["code"] == "method_not_allowed"
|
||||
@@ -257,3 +257,11 @@ def test_no_bill_is_named_and_bricks_alone_are_materials():
|
||||
assert out["missing_data"] == ["ведомость материалов"]
|
||||
assert out["materials"] == {"min": 4420, "max": 4420, "min_way": 0, "max_way": 0}
|
||||
assert out["total"]["min"] == 4420 + 1106
|
||||
|
||||
|
||||
def test_works_only_are_a_valid_partial_total_when_material_prices_are_missing():
|
||||
out = _checked(_run(lines=[dict(UNMATCHED)], notes=[]))
|
||||
assert out["works"] is not None
|
||||
assert out["materials"] is None
|
||||
assert out["total"] == out["works"]
|
||||
assert out["missing"] == [UNMATCHED["name"]]
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""AI matcher accepts only supplied codes and keeps provider failures out of the cache."""
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
import stove_match
|
||||
|
||||
|
||||
def _prices():
|
||||
return {"region": "Москва", "zone": None, "valid_at": "III кв. 2026",
|
||||
"lines": [{"name": "Глина шамотная", "qty": 0.5, "unit": "т", "code": None}]}
|
||||
|
||||
|
||||
def _candidate():
|
||||
return {"code": "17.4.05.01-0051", "name": "Глина огнеупорная шамотная", "unit": "кг", "price_calc": 26.08}
|
||||
|
||||
|
||||
def test_match_uses_only_candidate_code_and_writes_cache(monkeypatch):
|
||||
saved = []
|
||||
monkeypatch.setattr(stove_match.stove_cache, "match_get", lambda key: None)
|
||||
monkeypatch.setattr(stove_match.stove_cache, "match_put", lambda key, **kw: saved.append(kw))
|
||||
monkeypatch.setattr(stove_match, "_candidates", lambda *args: [_candidate()])
|
||||
monkeypatch.setattr(stove_match, "_profile_chain", lambda: [SimpleNamespace(name="glm", model="mock")])
|
||||
monkeypatch.setattr(stove_match, "_reserve", lambda *args: 42)
|
||||
monkeypatch.setattr(stove_match.db, "settle_llm_usage_stub", lambda *args, **kw: None)
|
||||
monkeypatch.setattr(stove_match.stove_history, "add_ai_cost", lambda *args, **kw: None)
|
||||
monkeypatch.setattr(stove_match.gateway, "_price", lambda *args: {"price_rub": 1.0})
|
||||
async def stream(*args):
|
||||
yield {"delta": '[{"index":0,"code":"17.4.05.01-0051"}]'}
|
||||
yield {"usage": {"input_tokens": 50, "output_tokens": 10}}
|
||||
monkeypatch.setattr(stove_match.gateway, "_provider_stream", stream)
|
||||
result = asyncio.run(stove_match.fill(_prices(), key_id=1, budget=300, deadline=__import__('time').monotonic()+10, request_id="rid"))
|
||||
assert result["lines"][0]["code"] == "17.4.05.01-0051"
|
||||
assert result["lines"][0]["price"] == 26.08
|
||||
assert saved[0]["code"] == "17.4.05.01-0051"
|
||||
|
||||
|
||||
def test_out_of_list_code_is_missing_and_not_cached(monkeypatch):
|
||||
saved = []
|
||||
monkeypatch.setattr(stove_match.stove_cache, "match_get", lambda key: None)
|
||||
monkeypatch.setattr(stove_match.stove_cache, "match_put", lambda key, **kw: saved.append(kw))
|
||||
monkeypatch.setattr(stove_match, "_candidates", lambda *args: [_candidate()])
|
||||
monkeypatch.setattr(stove_match, "_profile_chain", lambda: [SimpleNamespace(name="glm", model="mock")])
|
||||
monkeypatch.setattr(stove_match, "_reserve", lambda *args: 42)
|
||||
monkeypatch.setattr(stove_match.db, "settle_llm_usage_stub", lambda *args, **kw: None)
|
||||
monkeypatch.setattr(stove_match.stove_history, "add_ai_cost", lambda *args, **kw: None)
|
||||
monkeypatch.setattr(stove_match.gateway, "_price", lambda *args: {"price_rub": 1.0})
|
||||
async def stream(*args):
|
||||
yield {"delta": '[{"index":0,"code":"invented"}]'}
|
||||
yield {"usage": {"input_tokens": 50, "output_tokens": 10}}
|
||||
monkeypatch.setattr(stove_match.gateway, "_provider_stream", stream)
|
||||
result = asyncio.run(stove_match.fill(_prices(), key_id=1, budget=300, deadline=__import__('time').monotonic()+10, request_id="rid"))
|
||||
assert result["lines"][0]["code"] is None
|
||||
assert saved == []
|
||||
Reference in New Issue
Block a user