Files
smeta-web/tests/test_stove_match.py
T

145 lines
7.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""AI matcher accepts only supplied codes and keeps provider failures out of the cache."""
import asyncio
import os
import sys
import time
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
import stove_pricing
import stove_contract as c
def test_explicit_non_thinking_mode_reaches_anthropic_provider():
body = {"messages": [{"role": "user", "content": "Верни JSON"}],
"max_tokens": 2000, "thinking": {"type": "disabled"}}
payload = stove_match.gateway._to_provider(body, "deepseek-flash", 4096)
assert payload["thinking"] == {"type": "disabled"}
assert "thinking" not in stove_match.gateway._to_provider(
{"messages": body["messages"]}, "glm-5.3", 4096)
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 == []
def test_site_fireclay_mortar_is_not_discarded_as_brick(monkeypatch):
monkeypatch.setattr(stove_pricing.fgis_ref, "find_resource_price", lambda **kw: {
"status": "ok", "region": "Москва", "results": []})
request = c.StoveRequest.model_validate({"stove": {
"kind": "bath", "bricks": {"ceramic": 244, "fireclay": 76}, "region": "Москва",
"materials": [
{"name": "Мертель / шамотная глина", "qty": 23, "unit": "кг"},
{"name": "Кирпич красный полнотелый", "qty": 257, "unit": "шт"},
{"name": "Кирпичный бой для засыпки", "qty": 10, "unit": "кг"},
]}})
priced = stove_pricing.load(request)
assert [line["name"] for line in priced["lines"]] == [
"кирпич керамический", "кирпич шамотный", "Мертель / шамотная глина",
"Кирпичный бой для засыпки"]
assert priced["brick_lines_skipped"] == ["Кирпич красный полнотелый"]
def test_match_reuses_price_search_for_site_material(monkeypatch):
calls = []
candidate = {"code": "08.1.02.12-0061", "name": "Дверка печная 250×205", "unit": "шт",
"price_current": 1234}
def search(**kw):
calls.append(kw["query"])
return {"status": "ok", "region": "Москва", "results":
[candidate] if kw["query"] == "Дверка топочная 250×205" else []}
monkeypatch.setattr(stove_pricing.fgis_ref, "find_resource_price", search)
monkeypatch.setattr(stove_match.stove_cache, "match_get", lambda key: None)
monkeypatch.setattr(stove_match.stove_cache, "match_put", lambda *args, **kw: None)
async def choose(batch, *args):
assert len(batch) == 1 and batch[0]["line"]["name"] == "Дверка топочная 250×205"
return [candidate["code"]]
monkeypatch.setattr(stove_match, "_ask", choose)
request = c.StoveRequest.model_validate({"stove": {
"kind": "bath", "bricks": {"ceramic": 244, "fireclay": 76}, "region": "Москва",
"materials": [{"name": "Дверка топочная 250×205", "qty": 1, "unit": "шт"}]}})
priced = stove_pricing.load(request)
result = asyncio.run(stove_match.fill(
priced, key_id=1, budget=300, deadline=__import__('time').monotonic()+10, request_id="rid"))
assert calls.count("Дверка топочная 250×205") == 1
assert result["lines"][2]["code"] == candidate["code"]
def test_match_prefers_deepseek_without_thinking_and_keeps_glm_fallback(monkeypatch):
glm = SimpleNamespace(name="glm", model="glm-5.3", uses_api_token=True)
deepseek = SimpleNamespace(name="deepseek", model="deepseek-flash", uses_api_token=True)
monkeypatch.setattr(stove_match.agent_provider, "provider_chain", lambda user: [glm, deepseek])
monkeypatch.setattr(stove_match.provider_health, "should_include", lambda name: True)
monkeypatch.setattr(stove_match.zaika_quota, "snapshot", lambda: {"known": False})
assert [p.name for p in stove_match._profile_chain()] == ["deepseek", "glm"]
calls = []
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)
async def call(profile, body, timeout):
calls.append((profile.name, body.get("thinking")))
if profile.name == "deepseek":
raise stove_match.gateway.ProviderError(503, "temporary")
return '[{"index":0,"code":null}]', {}
monkeypatch.setattr(stove_match, "_call", call)
batch = [{"index": 0, "line": {"name": "Бетон B20", "unit": "м3"},
"candidates": [{"code": "x", "name": "Балки из бетона B20", "unit": "м3"}]}]
picked = asyncio.run(stove_match._ask(batch, 1, 300, time.monotonic()+10, "rid"))
assert picked == [None]
assert calls == [("deepseek", {"type": "disabled"}), ("glm", None)]