Files
smeta-web/tests/test_stove_match.py
T

108 lines
5.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
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 _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"]