Files
smeta-web/tests/test_norm_finder.py
T

186 lines
9.6 KiB
Python

"""Source-backed norm search and price preview."""
import pytest
import importlib
from fastapi.testclient import TestClient
def test_search_rejects_empty_query_and_uses_existing_fsnb(monkeypatch):
import fsnb_ref
import norm_finder
seen = []
def find(*, query, base, limit):
seen.append((query, base, limit))
return {"status": "ok", "works": [{"code": "10-08-002-02", "name": "Извещатель",
"unit": "шт.", "base": "ГЭСН-2022", "base_type": "ГЭСНм"}]}
monkeypatch.setattr(fsnb_ref, "find_works", find)
with pytest.raises(ValueError):
norm_finder.search(" ", "2022", 12)
found = norm_finder.search("извещатель", "2022", 12)
assert found["items"][0]["code"] == "10-08-002-02"
assert found["items"][0]["match_reason"].startswith("Совпали слова")
assert seen == [("извещатель", "2022", 12)]
def test_search_falls_back_to_subject_term_and_ranks_relevant_work(monkeypatch):
import fsnb_ref
import norm_finder
def find(*, query, base, limit):
if query == "устройство стяжки пола":
return {"status": "not_found"}
assert query == "стяжки"
return {"status": "ok", "works": [
{"code": "06-12-001-04", "name": "Заполнение откосов со стяжкой",
"section_path": "Элеваторы", "base": "ГЭСН-2022", "base_type": "ГЭСН", "unit": "м3"},
{"code": "11-01-011-02", "name": "Устройство стяжек пола",
"section_path": "Полы", "base": "ГЭСН-2022", "base_type": "ГЭСН", "unit": "100 м2"},
]}
monkeypatch.setattr(fsnb_ref, "find_works", find)
monkeypatch.setattr(fsnb_ref, "count_works", lambda word: {"стяжки": 30, "пола": 200}.get(word, 1000))
rows = norm_finder.search("устройство стяжки пола", "2022", 12)["items"]
assert rows[0]["code"] == "11-01-011-02"
def test_detail_requires_exact_base_type_and_code(monkeypatch):
import fsnb_ref
import norm_finder
def composition(*, query, base, limit):
return {"status": "ok", "results": [
{"base": "ГЭСН-2022", "base_type": "ГЭСН", "code": query,
"name": "Другая норма", "unit": "м2", "resources": []},
{"base": "ГЭСН-2022", "base_type": "ГЭСНм", "code": query,
"name": "Извещатель", "unit": "шт.", "resources": [{"code": "1-100-40", "quantity": 1}],
"provenance": {"decree": "Приказ"}},
]}
monkeypatch.setattr(fsnb_ref, "find_gesn_composition", composition)
item = norm_finder.detail("2022", "ГЭСНм", "10-08-002-02")
assert item["name"] == "Извещатель"
assert item["provenance"]["decree"] == "Приказ"
assert item["current_price_supported"] is True
with pytest.raises(ValueError):
norm_finder.detail("2022", "ГЭСНр", "10-08-002-02")
def test_calculation_refuses_unpriced_norm_instead_of_fabricating_total(monkeypatch):
import norm_finder
monkeypatch.setattr(norm_finder, "detail", lambda *args: {
"base": "ГЭСН-2022", "base_type": "ГЭСНм", "code": "10-08-002-02",
"name": "Извещатель", "unit": "шт.", "resources": [
{"code": "91.01.01-001", "name": "Машина", "unit": "маш.-ч", "quantity": 1}],
})
with pytest.raises(ValueError, match="не поддерживается"):
norm_finder.calculate("2022", "ГЭСНм", "10-08-002-02", 100, "шт.",
"Хабаровский край (1 зона)", "4 квартал 2026")
def test_gesn_quantity_uses_base_unit_and_engine_resource_key(monkeypatch):
import norm_finder
import engine_prices
import estimate_contract as ec
monkeypatch.setattr(norm_finder, "detail", lambda *args: {
"base": "ГЭСН-2022", "base_type": "ГЭСН", "code": "11-01-049-01",
"name": "Порог", "unit": "100 м", "resources": [
{"code": "1-100-40", "name": "Рабочий", "unit": "чел.-ч", "quantity": 1}],
})
monkeypatch.setattr(engine_prices, "resolve", lambda meta: {"status": "ok", "entry": {}})
monkeypatch.setattr(engine_prices, "load_lookup", lambda entry: object())
seen = []
def fake_calc(draft, resources, prices, basis):
seen.append((draft.positions[0].qty, sorted(resources)))
return {"status": "ok", "ok": False, "grand_total": 10.0,
"missing": [{"reason": "НР/СП"}], "unpriced": []}
monkeypatch.setattr(ec, "build_and_calc", fake_calc)
result = norm_finder.calculate("2022", "ГЭСН", "11-01-049-01", 50, "м",
"Хабаровский край (1 зона)", "4 квартал 2026")
assert seen == [(0.5, ["11-01-049-01"])]
assert result["total"] is None and result["accounted"] == 10.0
@pytest.fixture()
def api(tmp_path, monkeypatch):
monkeypatch.setenv("DB_PATH", str(tmp_path / "finder.db"))
monkeypatch.setenv("SESSION_SECRET", "finder-test-secret")
import auth
import db
import main
for module in (db, auth, main):
importlib.reload(module)
db.init_db()
db.create_user("finder@x", auth.hash_password("Passw0rd!ok"))
db.admin_verify_user("finder@x")
headers = {"Authorization": "Bearer " + auth._make_token("finder@x"), "X-Tab-Id": "tab"}
return TestClient(main.app), headers, db
@pytest.mark.parametrize("method,path", [
("get", "/api/norm-finder/catalog"),
("get", "/api/norm-finder/search?q=извещатель&base=2022"),
("get", "/api/norm-finder/detail?base=2022&base_type=ГЭСНм&code=10-08-002-02"),
("get", "/api/norm-finder/prices?subject_id=264"),
("post", "/api/norm-finder/calculate"),
("get", "/api/norm-finder/quotes/1"),
("post", "/api/norm-finder/quotes/1"),
])
def test_finder_requires_login(api, method, path):
client, _, _ = api
assert getattr(client, method)(path).status_code == 401
def test_finder_api_search_detail_and_catalog(api, monkeypatch):
import norm_finder
client, headers, _ = api
monkeypatch.setattr(norm_finder, "catalog", lambda: [{"base": "ГЭСН-2022", "base_type": "ГЭСНм", "count": 100}])
monkeypatch.setattr(norm_finder, "search", lambda q, b, limit: {"status": "ok", "items": [
{"base": "ГЭСН-2022", "base_type": "ГЭСНм", "code": "10-08-002-02", "name": "Извещатель", "unit": "шт."}]})
monkeypatch.setattr(norm_finder, "detail", lambda b, t, c: {"base": "ГЭСН-2022", "base_type": t,
"code": c, "name": "Извещатель", "unit": "шт.", "resources": [], "provenance": {"decree": "Приказ"}})
assert client.get("/api/norm-finder/catalog", headers=headers).json()["bases"][0]["count"] == 100
found = client.get("/api/norm-finder/search?q=извещатель&base=2022", headers=headers)
assert found.status_code == 200 and found.json()["items"][0]["code"] == "10-08-002-02"
detail = client.get("/api/norm-finder/detail?base=2022&base_type=ГЭСНм&code=10-08-002-02", headers=headers)
assert detail.status_code == 200 and detail.json()["provenance"]["decree"] == "Приказ"
def test_finder_quote_is_saved_and_revised_in_place(api, monkeypatch):
import norm_finder
import engine_prices
client, headers, db = api
monkeypatch.setattr(engine_prices, "basis_options", lambda sid: [
{"zone_id": 118, "name": "Хабаровский край (1 зона)",
"periods": [{"period_id": 428, "name": "4 квартал 2026"}]}] if sid == 264 else [])
monkeypatch.setattr(norm_finder, "calculate", lambda b, t, c, q, u, z, p: {
"status": "ok", "complete": False, "accounted": q * 100,
"base": "ГЭСН-2022", "base_type": t, "code": c, "quantity": q,
"unit": u, "zone": z, "period": p, "missing": [{"reason": "НР/СП"}]})
body = {"base": "2022", "base_type": "ГЭСНм", "code": "10-08-002-02",
"quantity": 100, "unit": "шт.", "subject_id": 264, "zone_id": 118, "period_id": 428}
assert client.post("/api/norm-finder/calculate", json={**body, "period_id": 999}, headers=headers).status_code == 400
created = client.post("/api/norm-finder/calculate", json=body, headers=headers)
assert created.status_code == 200, created.text
quote = created.json()
assert quote["result"]["accounted"] == 10000
assert db.get_history("finder@x", "tab")[-1]["role"] == "norm_quote"
url = f"/api/norm-finder/quotes/{quote['id']}"
import auth
db.create_user("other@x", auth.hash_password("Passw0rd!ok"))
db.admin_verify_user("other@x")
other = {"Authorization": "Bearer " + auth._make_token("other@x"), "X-Tab-Id": "tab"}
assert client.get(url, headers=other).status_code == 404
assert client.post(url, json={**body, "revision": 0}, headers=other).status_code == 404
assert client.get(url, headers=headers).json()["result"]["accounted"] == 10000
updated = client.post(url, json={**body, "quantity": 75, "revision": quote["revision"]}, headers=headers)
assert updated.status_code == 200 and updated.json()["id"] == quote["id"]
assert updated.json()["result"]["accounted"] == 7500
assert client.post(url, json={**body, "quantity": 50, "revision": quote["revision"]}, headers=headers).status_code == 409
def test_finder_page_is_reachable_from_site(api):
client, _, _ = api
page = client.get("/podbor")
assert page.status_code == 200
assert "Подбор норм" in page.text
assert 'src="/static/norm-finder.js"' in page.text
assert "/podbor" in client.get("/").text