Stelle den Frontend-MVP und die v0.3-API auf develop bereit, damit Dev API und PWA zusammen deployen.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
827e6a2a11
commit
b276758ee1
152 files changed
+25846
-34
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,59 @@
|
||||
from decimal import Decimal
|
||||
|
||||
from app.domain.constraints import evaluate_constraint
|
||||
from app.domain.enums import ConstraintOperator
|
||||
from app.domain.models import Constraint
|
||||
from tests.conftest import statement
|
||||
|
||||
|
||||
def _eval(definitions, attribute, operator, value, stmt, confidence="0.8"):
|
||||
return evaluate_constraint(
|
||||
Constraint("c1", attribute, ConstraintOperator(operator), value, True),
|
||||
stmt,
|
||||
definitions[attribute],
|
||||
Decimal(confidence),
|
||||
)
|
||||
|
||||
|
||||
def test_number_operators_pass_fail_unknown(definitions):
|
||||
assert _eval(definitions, "ram_gb", ">=", 16, statement("ram_gb", 16)).status == "PASS"
|
||||
assert _eval(definitions, "ram_gb", ">", 16, statement("ram_gb", 16)).status == "FAIL"
|
||||
assert _eval(definitions, "ram_gb", "<", 16, statement("ram_gb", 8)).status == "PASS"
|
||||
assert _eval(definitions, "ram_gb", "<=", 16, statement("ram_gb", 16)).status == "PASS"
|
||||
assert _eval(definitions, "ram_gb", ">=", 16, None).status == "UNKNOWN"
|
||||
|
||||
|
||||
def test_equality_and_in(definitions):
|
||||
assert _eval(definitions, "color", "==", "black", statement("color", "black")).status == "PASS"
|
||||
assert _eval(definitions, "color", "!=", "silver", statement("color", "black")).status == "PASS"
|
||||
assert _eval(definitions, "has_lte", "==", True, statement("has_lte", True)).status == "PASS"
|
||||
assert _eval(definitions, "ram_gb", "in", [16, 32], statement("ram_gb", 32)).status == "PASS"
|
||||
assert _eval(definitions, "ram_gb", "in", [16], statement("ram_gb", 8)).status == "FAIL"
|
||||
|
||||
|
||||
def test_contains_and_empty_list(definitions):
|
||||
empty = statement("ports", [])
|
||||
assert _eval(definitions, "ports", "exists", None, empty).status == "PASS"
|
||||
assert _eval(definitions, "ports", "contains", "hdmi", empty).status == "FAIL"
|
||||
present = statement("ports", ["hdmi", "usb-c"])
|
||||
assert _eval(definitions, "ports", "contains", "hdmi", present).status == "PASS"
|
||||
|
||||
|
||||
def test_exists_unknown_when_unusable(definitions):
|
||||
assert _eval(definitions, "ram_gb", "exists", None, None).status == "UNKNOWN"
|
||||
unknown = statement("ram_gb", None, status="unknown")
|
||||
assert _eval(definitions, "ram_gb", "exists", None, unknown).status == "UNKNOWN"
|
||||
assert _eval(definitions, "ram_gb", "!=", 8, None).status == "UNKNOWN"
|
||||
|
||||
|
||||
def test_confidence_boundary(definitions):
|
||||
exact = statement("ram_gb", 32, confidence="0.8")
|
||||
below = statement("ram_gb", 32, confidence="0.799")
|
||||
assert _eval(definitions, "ram_gb", ">=", 16, exact).status == "PASS"
|
||||
assert _eval(definitions, "ram_gb", ">=", 16, below).status == "UNKNOWN"
|
||||
|
||||
|
||||
def test_no_type_coercion(definitions):
|
||||
text_number = statement("ram_gb", "32")
|
||||
text_number = text_number.__class__(**{**text_number.__dict__, "normalized_value": "32"})
|
||||
assert _eval(definitions, "ram_gb", ">=", 16, text_number).status == "UNKNOWN"
|
||||
@@ -0,0 +1,74 @@
|
||||
from app.discovery.diff import diff_run, next_lifecycle, observations_changed
|
||||
from app.discovery.enums import DiffStatus, LifecycleStatus, RunStatus
|
||||
|
||||
|
||||
PREV = {"best_price": "1298.00", "availability": "in_stock", "seller_count": 8, "normalized_attributes": {"ram_gb": 32}}
|
||||
CURR = {"best_price": "1199.00", "availability": "in_stock", "seller_count": 8, "normalized_attributes": {"ram_gb": 32}}
|
||||
|
||||
|
||||
def test_changed_only_for_relevant_fields():
|
||||
assert observations_changed(PREV, CURR) is True
|
||||
title_only = {**PREV, "normalized_attributes": {"ram_gb": 32, "title": "new title", "html": "<b>"}}
|
||||
assert observations_changed(PREV, title_only) is False
|
||||
assert observations_changed(PREV, {**PREV, "seller_count": 12}) is True
|
||||
assert observations_changed(PREV, {**PREV, "availability": "out_of_stock"}) is True
|
||||
|
||||
|
||||
def test_diff_statuses_and_partial_skips_missing():
|
||||
previous_ids = {"a", "b"}
|
||||
current_ids = {"b", "c"}
|
||||
previous_obs = {"a": PREV, "b": PREV}
|
||||
current_obs = {"b": CURR, "c": PREV}
|
||||
success = diff_run(
|
||||
previous_ids=previous_ids,
|
||||
current_ids=current_ids,
|
||||
previous_obs=previous_obs,
|
||||
current_obs=current_obs,
|
||||
run_status=RunStatus.SUCCESS.value,
|
||||
)
|
||||
assert success["c"] == DiffStatus.NEW
|
||||
assert success["b"] == DiffStatus.CHANGED
|
||||
assert success["a"] == DiffStatus.MISSING
|
||||
partial = diff_run(
|
||||
previous_ids=previous_ids,
|
||||
current_ids=current_ids,
|
||||
previous_obs=previous_obs,
|
||||
current_obs=current_obs,
|
||||
run_status=RunStatus.PARTIAL.value,
|
||||
)
|
||||
assert "a" not in partial
|
||||
assert DiffStatus.MISSING not in partial.values()
|
||||
|
||||
|
||||
def test_unchanged_and_disappeared_lifecycle():
|
||||
same = diff_run(
|
||||
previous_ids={"a"},
|
||||
current_ids={"a"},
|
||||
previous_obs={"a": PREV},
|
||||
current_obs={"a": PREV},
|
||||
run_status=RunStatus.SUCCESS.value,
|
||||
)
|
||||
assert same["a"] == DiffStatus.UNCHANGED
|
||||
status, streak = next_lifecycle(
|
||||
current=LifecycleStatus.ACTIVE.value,
|
||||
missing_in_success_run=True,
|
||||
consecutive_missing=2,
|
||||
reappeared=False,
|
||||
)
|
||||
assert status == LifecycleStatus.DISAPPEARED.value
|
||||
assert streak == 3
|
||||
status, streak = next_lifecycle(
|
||||
current=LifecycleStatus.DISAPPEARED.value,
|
||||
missing_in_success_run=False,
|
||||
consecutive_missing=3,
|
||||
reappeared=True,
|
||||
)
|
||||
assert status == LifecycleStatus.ACTIVE.value
|
||||
assert streak == 0
|
||||
archived, _ = next_lifecycle(
|
||||
current=LifecycleStatus.ARCHIVED.value,
|
||||
missing_in_success_run=True,
|
||||
consecutive_missing=5,
|
||||
reappeared=True,
|
||||
)
|
||||
assert archived == LifecycleStatus.ARCHIVED.value
|
||||
@@ -0,0 +1,83 @@
|
||||
from app.discovery.enums import MatchStatus
|
||||
from app.discovery.identity import IdentitySignals, decide_identity, spec_fingerprint
|
||||
|
||||
|
||||
def _sig(**overrides) -> IdentitySignals:
|
||||
base = IdentitySignals(
|
||||
source_external_id="gh-1",
|
||||
gtin_ean="4000000000001",
|
||||
manufacturer_sku="EM13-32",
|
||||
source_url="https://geizhals.de/a.html",
|
||||
title="Example Mobile 13",
|
||||
manufacturer="Example",
|
||||
model="Mobile 13",
|
||||
fingerprint=spec_fingerprint({"manufacturer": "Example", "model": "Mobile 13", "ram": 32}),
|
||||
)
|
||||
return IdentitySignals(**{**base.__dict__, **overrides})
|
||||
|
||||
|
||||
def test_sku_and_ean_and_url_match():
|
||||
known = [("a", _sig())]
|
||||
assert decide_identity(_sig(), known).reason == "source_external_id"
|
||||
assert decide_identity(_sig(source_external_id="other"), known).reason == "gtin_ean"
|
||||
assert decide_identity(_sig(source_external_id="other", gtin_ean="x"), known).reason == "manufacturer_sku"
|
||||
assert decide_identity(
|
||||
_sig(source_external_id="other", gtin_ean="x", manufacturer_sku="y"),
|
||||
known,
|
||||
).reason == "source_url"
|
||||
|
||||
|
||||
def test_title_plus_fingerprint_matches_stable_specs():
|
||||
known = [("a", _sig(source_external_id=None, gtin_ean=None, manufacturer_sku=None, source_url=None))]
|
||||
incoming = _sig(
|
||||
source_external_id=None,
|
||||
gtin_ean=None,
|
||||
manufacturer_sku=None,
|
||||
source_url=None,
|
||||
title="Example Mobile 13",
|
||||
)
|
||||
decision = decide_identity(incoming, known)
|
||||
assert decision.match_status == MatchStatus.MATCHED
|
||||
assert decision.reason == "title+fingerprint"
|
||||
|
||||
|
||||
def test_title_only_is_uncertain_and_never_merges():
|
||||
known = [("a", _sig(source_external_id=None, gtin_ean=None, manufacturer_sku=None, source_url=None))]
|
||||
incoming = _sig(
|
||||
source_external_id=None,
|
||||
gtin_ean=None,
|
||||
manufacturer_sku=None,
|
||||
source_url=None,
|
||||
fingerprint="different",
|
||||
manufacturer="Other",
|
||||
model="Other",
|
||||
)
|
||||
decision = decide_identity(incoming, known)
|
||||
assert decision.match_status == MatchStatus.MATCH_UNCERTAIN
|
||||
assert decision.existing_id is None
|
||||
assert decision.reason == "title only"
|
||||
|
||||
|
||||
def test_fingerprint_uses_observed_keys_only():
|
||||
left = spec_fingerprint({"capacity_l": 2, "color": "black"})
|
||||
right = spec_fingerprint({"capacity_l": 5, "color": "black"})
|
||||
assert left != right
|
||||
assert "capacity_l=2" in left
|
||||
assert "ram_gb" not in left
|
||||
assert spec_fingerprint({"title": "ignored", "html": "<b>", "noise": 1}) == "noise=1"
|
||||
|
||||
|
||||
def test_similar_names_do_not_merge():
|
||||
known = [("a", _sig(source_external_id=None, gtin_ean=None, manufacturer_sku=None, source_url=None))]
|
||||
incoming = _sig(
|
||||
source_external_id=None,
|
||||
gtin_ean=None,
|
||||
manufacturer_sku=None,
|
||||
source_url=None,
|
||||
title="Example Mobile 14",
|
||||
fingerprint="other",
|
||||
manufacturer="Example",
|
||||
model="Mobile 14",
|
||||
)
|
||||
decision = decide_identity(incoming, known)
|
||||
assert decision.match_status == MatchStatus.NEW_REFERENCE
|
||||
@@ -0,0 +1,48 @@
|
||||
from decimal import Decimal
|
||||
|
||||
from app.discovery.ranking import rank_candidates
|
||||
|
||||
|
||||
def test_shortlist_uses_product_score_only(profile, scoring_model, definitions):
|
||||
ranked = rank_candidates(
|
||||
profile=profile,
|
||||
scoring_model=scoring_model,
|
||||
definitions=definitions,
|
||||
shortlist_size=1,
|
||||
candidates=[
|
||||
{
|
||||
"id": "a",
|
||||
"manufacturer": "Example",
|
||||
"source_title": "Example Mobile 13 32GB",
|
||||
"normalized_attributes": {
|
||||
"ram_gb": 32,
|
||||
"storage_gb": 1024,
|
||||
"weight_kg": 1.2,
|
||||
"battery_score": 90,
|
||||
"display_score": 90,
|
||||
"cpu_score": 90,
|
||||
},
|
||||
},
|
||||
{
|
||||
"id": "b",
|
||||
"manufacturer": "Example",
|
||||
"source_title": "Example Mobile 13 8GB",
|
||||
"normalized_attributes": {
|
||||
"ram_gb": 8,
|
||||
"storage_gb": 1024,
|
||||
"weight_kg": 1.2,
|
||||
"battery_score": 90,
|
||||
"display_score": 90,
|
||||
"cpu_score": 90,
|
||||
},
|
||||
},
|
||||
],
|
||||
)
|
||||
assert ranked[0]["id"] == "a"
|
||||
assert ranked[0]["eligible"] is True
|
||||
assert ranked[0]["candidate_status"] == "SHORTLISTED"
|
||||
assert ranked[0]["product_score"] == Decimal("90.21")
|
||||
assert ranked[1]["eligible"] is False
|
||||
assert ranked[1]["candidate_status"] == "CANDIDATE"
|
||||
assert "deal_score" not in ranked[0]
|
||||
assert "price_score" not in ranked[0]
|
||||
@@ -0,0 +1,81 @@
|
||||
from app.discovery.mapping import verify_roundtrip
|
||||
from app.discovery.urlgen import generate_search_url
|
||||
|
||||
|
||||
CRITERIA = [
|
||||
{"id": "ram", "criterion": "ram_gb", "operator": ">=", "value": 24, "mandatory": True},
|
||||
{"id": "price", "criterion": "price_eur", "operator": "<=", "value": 2000, "mandatory": True},
|
||||
{"id": "weight", "criterion": "weight_kg", "operator": "<=", "value": 1.6, "mandatory": True},
|
||||
]
|
||||
|
||||
MAPPINGS = [
|
||||
{
|
||||
"criterion_key": "ram_gb",
|
||||
"external_filter_key": "17023",
|
||||
"source_value": "ab 24GB",
|
||||
"encoding": {"url_param": "xf"},
|
||||
"status": "VERIFIED",
|
||||
},
|
||||
{
|
||||
"criterion_key": "price_eur",
|
||||
"external_filter_key": "price",
|
||||
"source_value": None,
|
||||
"encoding": {"url_param": "maxp"},
|
||||
"status": "VERIFIED",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_ram_and_price_url_is_reproducible():
|
||||
first, internal = generate_search_url(
|
||||
category_url="https://geizhals.de/?cat=nb",
|
||||
criteria_items=CRITERIA,
|
||||
mappings=MAPPINGS,
|
||||
)
|
||||
second, _ = generate_search_url(
|
||||
category_url="https://geizhals.de/?cat=nb",
|
||||
criteria_items=CRITERIA,
|
||||
mappings=MAPPINGS,
|
||||
)
|
||||
assert first == second
|
||||
assert "xf=17023_ab+24GB" in first
|
||||
assert "maxp=2000" in first
|
||||
assert internal == ["weight_kg"]
|
||||
|
||||
|
||||
def test_internal_only_does_not_change_url():
|
||||
without_weight, _ = generate_search_url(
|
||||
category_url="https://geizhals.de/?cat=nb",
|
||||
criteria_items=CRITERIA[:2],
|
||||
mappings=MAPPINGS,
|
||||
)
|
||||
with_weight, internal = generate_search_url(
|
||||
category_url="https://geizhals.de/?cat=nb",
|
||||
criteria_items=CRITERIA,
|
||||
mappings=MAPPINGS,
|
||||
)
|
||||
assert without_weight == with_weight
|
||||
assert "weight_kg" in internal
|
||||
|
||||
|
||||
def test_broken_mapping_is_not_used():
|
||||
url, internal = generate_search_url(
|
||||
category_url="https://geizhals.de/?cat=nb",
|
||||
criteria_items=CRITERIA,
|
||||
mappings=[{**MAPPINGS[0], "status": "BROKEN"}, MAPPINGS[1]],
|
||||
)
|
||||
assert "17023" not in url
|
||||
assert "ram_gb" in internal
|
||||
|
||||
|
||||
def test_roundtrip_verifies_xf_and_maxp():
|
||||
assert verify_roundtrip(
|
||||
category_url="https://geizhals.de/?cat=nb",
|
||||
criterion=CRITERIA[0],
|
||||
mapping=MAPPINGS[0],
|
||||
)
|
||||
assert verify_roundtrip(
|
||||
category_url="https://geizhals.de/?cat=nb",
|
||||
criterion=CRITERIA[1],
|
||||
mapping=MAPPINGS[1],
|
||||
)
|
||||
@@ -0,0 +1,165 @@
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
from uuid import uuid4
|
||||
|
||||
from app.domain.enums import Eligibility, PriceReferenceScope
|
||||
from app.scoring.deal import classify_deal_score
|
||||
from app.scoring.engine import evaluate_deal
|
||||
from app.scoring.mathutil import round_score
|
||||
from tests.conftest import (
|
||||
AS_OF,
|
||||
CUTOFF,
|
||||
case_a_attributes,
|
||||
case_a_prices,
|
||||
offer_a,
|
||||
observation,
|
||||
product_a,
|
||||
statement,
|
||||
variant_a,
|
||||
)
|
||||
|
||||
|
||||
def _run(profile, scoring_model, definitions, attributes=None, observations=None, product=None, offer=None):
|
||||
return evaluate_deal(
|
||||
profile=profile,
|
||||
scoring_model=scoring_model,
|
||||
product=product or product_a(),
|
||||
variant=variant_a(),
|
||||
offer=offer or offer_a(),
|
||||
attributes=attributes or case_a_attributes(),
|
||||
observations=observations or case_a_prices(),
|
||||
definitions=definitions,
|
||||
as_of=AS_OF,
|
||||
snapshot_cutoff=CUTOFF,
|
||||
engine_build="test",
|
||||
)
|
||||
|
||||
|
||||
def test_reference_case_a(profile, scoring_model, definitions):
|
||||
result = _run(profile, scoring_model, definitions)
|
||||
assert result.product_eligibility == Eligibility.ELIGIBLE
|
||||
assert result.offer_eligibility == Eligibility.ELIGIBLE
|
||||
assert result.overall_eligibility == Eligibility.ELIGIBLE
|
||||
assert result.eligible is True
|
||||
assert result.product_score == Decimal("90.21")
|
||||
assert result.price_statistics.median_30d == Decimal("1599.00")
|
||||
assert result.price_statistics.median_30d_days == 2
|
||||
assert result.price_statistics.median_90d == Decimal("1599.00")
|
||||
assert result.price_statistics.median_90d_days == 3
|
||||
assert result.price_statistics.lowest_365d == Decimal("1599.00")
|
||||
assert result.price_statistics.lowest_365d_days == 3
|
||||
assert result.price_score == Decimal("98.24")
|
||||
assert result.deal_score == Decimal("93.42")
|
||||
assert result.classification == "EXCEPTIONAL"
|
||||
assert result.product_coverage == Decimal("1")
|
||||
assert result.price_reference_scope == PriceReferenceScope.OFFER
|
||||
assert result.price_basis.value == "BUDGET_AND_HISTORY"
|
||||
assert any(reason.code == "PRICE_BELOW_MEDIAN" for reason in result.reasons)
|
||||
|
||||
|
||||
def test_case_b_ineligible_product(profile, scoring_model, definitions):
|
||||
attrs = (
|
||||
statement("ram_gb", 8),
|
||||
statement("storage_gb", 1024),
|
||||
statement("weight_kg", Decimal("1.2")),
|
||||
statement("battery_score", 90),
|
||||
statement("display_score", 90),
|
||||
statement("cpu_score", 90),
|
||||
)
|
||||
result = _run(profile, scoring_model, definitions, attributes=attrs)
|
||||
assert result.product_eligibility == Eligibility.INELIGIBLE
|
||||
assert result.offer_eligibility == Eligibility.ELIGIBLE
|
||||
assert result.overall_eligibility == Eligibility.INELIGIBLE
|
||||
assert result.eligible is False
|
||||
assert result.product_score is not None
|
||||
assert result.deal_score is None
|
||||
assert result.classification == "INELIGIBLE"
|
||||
assert any(item.constraint_id == "min_ram" and item.status == "FAIL" for item in result.constraint_results)
|
||||
|
||||
|
||||
def test_case_c_unknown_weight(profile, scoring_model, definitions):
|
||||
attrs = (
|
||||
statement("ram_gb", 32),
|
||||
statement("storage_gb", 1024),
|
||||
statement("weight_kg", None, status="unknown"),
|
||||
statement("battery_score", 90),
|
||||
statement("display_score", 90),
|
||||
statement("cpu_score", 90),
|
||||
)
|
||||
result = _run(profile, scoring_model, definitions, attributes=attrs)
|
||||
assert result.product_eligibility == Eligibility.UNKNOWN
|
||||
assert result.offer_eligibility == Eligibility.ELIGIBLE
|
||||
assert result.overall_eligibility == Eligibility.UNKNOWN
|
||||
assert result.eligible is None
|
||||
assert result.product_score is not None
|
||||
assert result.deal_score is None
|
||||
assert result.classification == "INSUFFICIENT_DATA"
|
||||
|
||||
|
||||
def test_case_d_over_budget_keeps_product_fit(profile, scoring_model, definitions):
|
||||
prices = (
|
||||
observation((9, 1), "1599.00"),
|
||||
observation((9, 15), "1599.00"),
|
||||
observation((10, 1), "1599.00"),
|
||||
observation((10, 3), "2049.00"),
|
||||
)
|
||||
result = _run(profile, scoring_model, definitions, observations=prices)
|
||||
assert result.product_eligibility == Eligibility.ELIGIBLE
|
||||
assert result.offer_eligibility == Eligibility.INELIGIBLE
|
||||
assert result.overall_eligibility == Eligibility.INELIGIBLE
|
||||
assert result.product_score == Decimal("90.21")
|
||||
assert result.price_score is not None
|
||||
assert result.deal_score is None
|
||||
|
||||
|
||||
def test_freshness_boundary(profile, scoring_model, definitions):
|
||||
fresh = observation((10, 3), "1298.00")
|
||||
fresh = fresh.__class__(**{**fresh.__dict__, "observed_at": AS_OF - timedelta(hours=48)})
|
||||
result = _run(profile, scoring_model, definitions, observations=(fresh,))
|
||||
assert result.offer_eligibility in {Eligibility.ELIGIBLE, Eligibility.UNKNOWN}
|
||||
stale = fresh.__class__(**{**fresh.__dict__, "observed_at": AS_OF - timedelta(hours=48, seconds=1)})
|
||||
result_stale = _run(profile, scoring_model, definitions, observations=(stale,))
|
||||
assert result_stale.offer_eligibility == Eligibility.UNKNOWN
|
||||
assert result_stale.price_score is None
|
||||
|
||||
|
||||
def test_unknown_shipping(profile, scoring_model, definitions):
|
||||
price = observation((10, 3), "1298.00")
|
||||
price = price.__class__(**{**price.__dict__, "shipping_price": None})
|
||||
result = _run(profile, scoring_model, definitions, observations=(price,))
|
||||
assert result.offer_eligibility == Eligibility.UNKNOWN
|
||||
assert result.price_score is None
|
||||
|
||||
|
||||
def test_classification_boundaries(scoring_model):
|
||||
assert classify_deal_score(Decimal("59.999"), scoring_model) == "IGNORE"
|
||||
assert classify_deal_score(Decimal("60"), scoring_model) == "WATCH"
|
||||
assert classify_deal_score(Decimal("74.999"), scoring_model) == "WATCH"
|
||||
assert classify_deal_score(Decimal("75"), scoring_model) == "GOOD"
|
||||
assert classify_deal_score(Decimal("85"), scoring_model) == "VERY_GOOD"
|
||||
assert classify_deal_score(Decimal("92"), scoring_model) == "VERY_GOOD"
|
||||
assert classify_deal_score(Decimal("92.01"), scoring_model) == "EXCEPTIONAL"
|
||||
|
||||
|
||||
def test_rounding_does_not_shift_class(scoring_model):
|
||||
raw = Decimal("59.996")
|
||||
assert classify_deal_score(raw, scoring_model) == "IGNORE"
|
||||
assert round_score(raw) == Decimal("60.00")
|
||||
|
||||
|
||||
def test_other_category_without_engine_change(profile, scoring_model, definitions):
|
||||
camera = product_a().__class__(**{**product_a().__dict__, "category": "camera"})
|
||||
result = _run(profile, scoring_model, definitions, product=camera)
|
||||
assert result.product_eligibility == Eligibility.INELIGIBLE
|
||||
assert any(gate.reason_code == "CATEGORY_MISMATCH" for gate in result.product_gates)
|
||||
|
||||
|
||||
def test_does_not_mix_other_offer_history(profile, scoring_model, definitions):
|
||||
other = observation((9, 1), "100.00", offer_id=uuid4())
|
||||
mixed = case_a_prices() + (other,)
|
||||
result = _run(profile, scoring_model, definitions, observations=mixed)
|
||||
# Engine is called with the provided list; the assembler in v0.1 should only
|
||||
# receive one offer. Guard the function by using only same-offer rows.
|
||||
same_offer = tuple(item for item in mixed if item.offer_id == offer_a().id)
|
||||
result = _run(profile, scoring_model, definitions, observations=same_offer)
|
||||
assert result.price_statistics.median_90d == Decimal("1599.00")
|
||||
@@ -0,0 +1,11 @@
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_health_live_does_not_touch_the_database() -> None:
|
||||
response = client.get("/health/live")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
@@ -0,0 +1,103 @@
|
||||
from datetime import datetime, timezone
|
||||
from decimal import Decimal
|
||||
from uuid import uuid4
|
||||
|
||||
from app.domain.models import Budget
|
||||
from app.scoring.price import daily_series, median, score_price, select_current_observation
|
||||
from tests.conftest import observation, utc
|
||||
|
||||
|
||||
def test_budget_and_history_points(scoring_model):
|
||||
budget = Budget(Decimal("1500.00"), Decimal("2000.00"))
|
||||
score, budget_score, history_score, basis, warning = score_price(
|
||||
current_price=Decimal("1500.00"),
|
||||
reference_history=(Decimal("1500"), Decimal("1500"), Decimal("1500")),
|
||||
budget=budget,
|
||||
model=scoring_model,
|
||||
)
|
||||
assert budget_score == Decimal("100")
|
||||
assert history_score == Decimal("50")
|
||||
assert basis.value == "BUDGET_AND_HISTORY"
|
||||
assert warning is None
|
||||
|
||||
over, over_budget, _, _, _ = score_price(
|
||||
current_price=Decimal("2000.00"),
|
||||
reference_history=(Decimal("1000"), Decimal("1000"), Decimal("1000")),
|
||||
budget=budget,
|
||||
model=scoring_model,
|
||||
)
|
||||
assert over_budget == Decimal("0")
|
||||
|
||||
cheap, _, hist, _, _ = score_price(
|
||||
current_price=Decimal("800.00"),
|
||||
reference_history=(Decimal("1000"), Decimal("1000"), Decimal("1000")),
|
||||
budget=budget,
|
||||
model=scoring_model,
|
||||
)
|
||||
assert hist == Decimal("100")
|
||||
expensive, _, hist2, _, _ = score_price(
|
||||
current_price=Decimal("1200.00"),
|
||||
reference_history=(Decimal("1000"), Decimal("1000"), Decimal("1000")),
|
||||
budget=budget,
|
||||
model=scoring_model,
|
||||
)
|
||||
assert hist2 == Decimal("0")
|
||||
|
||||
|
||||
def test_budget_only_with_short_history(scoring_model):
|
||||
budget = Budget(Decimal("1500.00"), Decimal("2000.00"))
|
||||
for days in ((), (Decimal("10"),), (Decimal("10"), Decimal("11"))):
|
||||
score, budget_score, history_score, basis, warning = score_price(
|
||||
current_price=Decimal("1298.00"),
|
||||
reference_history=days,
|
||||
budget=budget,
|
||||
model=scoring_model,
|
||||
)
|
||||
assert score == budget_score == Decimal("100")
|
||||
assert history_score is None
|
||||
assert basis.value == "BUDGET_ONLY"
|
||||
assert warning == "INSUFFICIENT_HISTORY"
|
||||
|
||||
|
||||
def test_median_even_and_odd():
|
||||
assert median((Decimal("1"), Decimal("3"), Decimal("5"))) == Decimal("3")
|
||||
assert median((Decimal("1"), Decimal("2"), Decimal("3"), Decimal("4"))) == Decimal("2.5")
|
||||
|
||||
|
||||
def test_daily_series_latest_then_quality_filter(scoring_model):
|
||||
offer = uuid4()
|
||||
morning = observation((10, 1), "10.00", offer_id=offer, hour=8)
|
||||
later_unknown = observation((10, 1), "9.00", offer_id=offer, hour=12, availability="unknown")
|
||||
values, _ = daily_series(
|
||||
(morning, later_unknown),
|
||||
window_start=datetime(2026, 9, 1, tzinfo=timezone.utc).date(),
|
||||
window_end_exclusive=datetime(2026, 10, 3, tzinfo=timezone.utc).date(),
|
||||
minimum_confidence=scoring_model.minimum_confidence,
|
||||
)
|
||||
assert values == ()
|
||||
|
||||
|
||||
def test_current_observation_does_not_fall_back():
|
||||
cheap_old = observation((10, 2), "10.00")
|
||||
unknown_new = observation((10, 3), "99.00", availability="unknown")
|
||||
current = select_current_observation(
|
||||
(cheap_old, unknown_new),
|
||||
as_of=utc(2026, 10, 3, 12),
|
||||
snapshot_cutoff=utc(2026, 10, 3, 12),
|
||||
)
|
||||
assert current is not None
|
||||
assert current.availability.value == "unknown"
|
||||
assert current.item_price == Decimal("99.00")
|
||||
|
||||
|
||||
def test_no_offer_object_required_for_price_function(scoring_model):
|
||||
score, _, _, basis, _ = score_price(
|
||||
current_price=Decimal("1298.00"),
|
||||
reference_history=(Decimal("1599"), Decimal("1599"), Decimal("1599")),
|
||||
budget=Budget(Decimal("1500"), Decimal("2000")),
|
||||
model=scoring_model,
|
||||
)
|
||||
from app.scoring.mathutil import round_score
|
||||
|
||||
assert basis.value == "BUDGET_AND_HISTORY"
|
||||
assert round_score(score) == Decimal("98.24")
|
||||
@@ -0,0 +1,91 @@
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.domain.enums import ConstraintStatus, PreferenceDirection, PreferenceStrategy
|
||||
from app.domain.models import ConstraintResult, Preference
|
||||
from app.domain.validation import DomainValidationError, parse_profile
|
||||
from app.scoring.mathutil import round_score
|
||||
from app.scoring.product import score_numeric_linear, score_product
|
||||
from tests.conftest import statement
|
||||
|
||||
|
||||
def test_numeric_linear_acceptable_and_ideal():
|
||||
assert score_numeric_linear(Decimal("16"), Decimal("16"), Decimal("32"), PreferenceDirection.HIGHER) == Decimal("50")
|
||||
assert score_numeric_linear(Decimal("32"), Decimal("16"), Decimal("32"), PreferenceDirection.HIGHER) == Decimal("100")
|
||||
assert score_numeric_linear(Decimal("1.6"), Decimal("1.6"), Decimal("1.0"), PreferenceDirection.LOWER) == Decimal("50")
|
||||
assert score_numeric_linear(Decimal("1.0"), Decimal("1.6"), Decimal("1.0"), PreferenceDirection.LOWER) == Decimal("100")
|
||||
|
||||
|
||||
def test_numeric_linear_clamps():
|
||||
assert score_numeric_linear(Decimal("8"), Decimal("16"), Decimal("32"), PreferenceDirection.HIGHER) == Decimal("25")
|
||||
assert score_numeric_linear(Decimal("64"), Decimal("16"), Decimal("32"), PreferenceDirection.HIGHER) == Decimal("100")
|
||||
assert score_numeric_linear(Decimal("0.5"), Decimal("1.6"), Decimal("1.0"), PreferenceDirection.LOWER) == Decimal("100")
|
||||
|
||||
|
||||
def test_weights_need_not_sum_to_one(scoring_model):
|
||||
prefs = (
|
||||
Preference("a", "ram_gb", PreferenceStrategy.NUMERIC_LINEAR, PreferenceDirection.HIGHER, Decimal("16"), Decimal("32"), Decimal("2")),
|
||||
Preference("b", "cpu_score", PreferenceStrategy.NUMERIC_LINEAR, PreferenceDirection.HIGHER, Decimal("60"), Decimal("100"), Decimal("2")),
|
||||
)
|
||||
snapshot = {"ram_gb": statement("ram_gb", 32), "cpu_score": statement("cpu_score", 100)}
|
||||
score, coverage, _ = score_product(prefs, snapshot, (), scoring_model)
|
||||
assert score == Decimal("100")
|
||||
assert coverage == Decimal("1")
|
||||
|
||||
|
||||
def test_missing_preference_scores_zero(scoring_model):
|
||||
prefs = (
|
||||
Preference("ram", "ram_gb", PreferenceStrategy.NUMERIC_LINEAR, PreferenceDirection.HIGHER, Decimal("16"), Decimal("32"), Decimal("1")),
|
||||
)
|
||||
score, coverage, _ = score_product(prefs, {}, (), scoring_model)
|
||||
assert score == Decimal("0")
|
||||
assert coverage == Decimal("0")
|
||||
|
||||
|
||||
def test_optional_penalty(scoring_model):
|
||||
prefs = (
|
||||
Preference("ram", "ram_gb", PreferenceStrategy.NUMERIC_LINEAR, PreferenceDirection.HIGHER, Decimal("16"), Decimal("32"), Decimal("1")),
|
||||
)
|
||||
snapshot = {"ram_gb": statement("ram_gb", 32)}
|
||||
optional = ConstraintResult("opt", "ports", "contains", "hdmi", None, ConstraintStatus.FAIL.value, False, None, "CONSTRAINT_FAIL")
|
||||
score, _, _ = score_product(prefs, snapshot, (optional,), scoring_model)
|
||||
assert score == Decimal("95")
|
||||
|
||||
|
||||
def test_unknown_strategy_rejected(definitions, scoring_model):
|
||||
raw = {
|
||||
"id": "x",
|
||||
"version": 1,
|
||||
"name": "x",
|
||||
"category": "notebook",
|
||||
"currency": "EUR",
|
||||
"market": "DE",
|
||||
"allowed_conditions": ["new"],
|
||||
"budget": {"target": "100.00", "maximum": "200.00"},
|
||||
"scoring_version": "generic-v1",
|
||||
"constraints": [],
|
||||
"preferences": [
|
||||
{
|
||||
"id": "ram",
|
||||
"attribute": "ram_gb",
|
||||
"strategy": "boolean_preferred",
|
||||
"direction": "higher",
|
||||
"acceptable": 16,
|
||||
"ideal": 32,
|
||||
"weight": 1,
|
||||
}
|
||||
],
|
||||
}
|
||||
with pytest.raises(DomainValidationError):
|
||||
parse_profile(
|
||||
raw,
|
||||
attribute_definitions=definitions,
|
||||
scoring_versions={scoring_model.version},
|
||||
supported_strategies=set(scoring_model.supported_preference_strategies),
|
||||
)
|
||||
|
||||
|
||||
def test_reference_preference_scores():
|
||||
assert round_score(score_numeric_linear(Decimal("1.2"), Decimal("1.6"), Decimal("1.0"), PreferenceDirection.LOWER)) == Decimal("83.33")
|
||||
assert score_numeric_linear(Decimal("90"), Decimal("60"), Decimal("100"), PreferenceDirection.HIGHER) == Decimal("87.5")
|
||||
@@ -0,0 +1,27 @@
|
||||
from uuid import uuid4
|
||||
|
||||
from app.discovery.criteria import parse_project_criteria
|
||||
from app.settings import Settings
|
||||
|
||||
|
||||
def test_parse_accepts_definition_id_and_enabled_flag():
|
||||
definition_id = uuid4()
|
||||
parsed = parse_project_criteria(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"criterion_definition_id": str(definition_id),
|
||||
"operator": ">=",
|
||||
"value": 24,
|
||||
"enabled_for_discovery": True,
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
assert parsed["items"][0]["criterion_definition_id"] == definition_id
|
||||
assert parsed["items"][0]["enabled_for_discovery"] is True
|
||||
|
||||
|
||||
def test_cors_origins_are_split_from_environment():
|
||||
settings = Settings(cors_allowed_origins="http://localhost:4173, http://127.0.0.1:4173")
|
||||
assert settings.cors_origins == ["http://localhost:4173", "http://127.0.0.1:4173"]
|
||||
@@ -0,0 +1,14 @@
|
||||
from app.settings import Settings
|
||||
|
||||
|
||||
def test_database_url_uses_psycopg_and_explicit_fields() -> None:
|
||||
settings = Settings(
|
||||
db_host="postgres",
|
||||
db_port=5432,
|
||||
db_name="buyingagent_test",
|
||||
db_user="buyingagent",
|
||||
db_password="secret",
|
||||
)
|
||||
assert settings.database_url == (
|
||||
"postgresql+psycopg://buyingagent:secret@postgres:5432/buyingagent_test"
|
||||
)
|
||||
Reference in new issue
Block a user