diet-guard/diet_guard/tests/test_foodbank.py
Krzysztof kuhy Rudnicki 3e51e614b1 Split the last seven Python files; extend the redirect guard to all five paths
Ninth batch of the 250-line sweep. Every Python file in the repo is now under
cap (over-cap count 25 -> 18; the 18 remaining are all Dart).

  _foodbank.py             365 -> 210  (+ _foodbank_search, _foodbank_rebuild)
  test_averages.py         351 -> 222  (+ test_averages_report.py)
  _estimator.py            325 -> 137  (+ _estimator_off.py)
  _budget.py               323 -> 227  (+ _budget_biometrics, _budget_derived)
  test_foodbank.py         311 -> 117  (+ test_foodbank_rebuild.py)
  _averages.py             298 -> 174  (+ _averages_periods, _averages_report)
  test_budget_history.py   288 -> 162  (+ test_budget_history_io.py)

The split boundaries are constrained by which module owns each conftest-patched
state path, not by line count. BUDGET_FILE stays in _budget, FOOD_BANK_FILE in
_foodbank: the derived/search/rebuild halves reach the file only through their
parent's private helpers. Two of the new modules had copied FOOD_BANK_FILE into
their headers as an incidental import, which is exactly the leak the guard is
for -- both cleaned.

test_state_redirect.py now covers all five redirected paths (FOOD_LOG_FILE,
BUDGET_FILE, BUDGET_HISTORY_FILE, FOOD_BANK_FILE, MANUAL_BANK_FILE) rather
than just the food log, in both directions: only the owning module may name
each constant, and each redirect demonstrably moves a real write off the live
path.

Two rewires fail-closed rather than silently: `_budget.budget_weight` and
`_estimator.requests` were module-attribute references no import rewrite
touches, and both raised AttributeError immediately. The latter appeared only
after ruff removed the now-unused `requests` import from _estimator -- the
import was load-bearing solely as a patch target.

Verified: 707 Python tests / 100% branch coverage, 5 layout-fits tests under
xvfb, check_patch_targets 0, pre-commit clean, ~/.local/share/diet_guard
byte-identical.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RA9ynjqXPnexRQnR5oAuCC
2026-08-15 20:37:05 +02:00

116 lines
3.9 KiB
Python

"""Tests for _foodbank.py — the local corpus of previously logged foods.
The food-bank file is redirected into ``tmp_path`` by the autouse conftest
fixture, so every read/write here is isolated from real user data.
"""
from __future__ import annotations
import json
from diet_guard import _foodbank
from diet_guard._estimator import Nutrition
from diet_guard._foodbank import remember_food
from diet_guard._foodbank_search import lookup_food, search_foods
_NUT = Nutrition(
kcal=250,
protein_g=12,
carbs_g=30,
fat_g=10,
grams=200,
source="manual",
)
def _write_raw(bank: object) -> None:
"""Write an arbitrary object as the bank file (for defensive-read tests)."""
_foodbank.FOOD_BANK_FILE.write_text(json.dumps(bank), encoding="utf-8")
class TestRememberAndLookup:
"""Round-tripping foods through the bank."""
def test_blank_description_ignored(self) -> None:
"""A blank name is not stored."""
remember_food(" ", _NUT)
assert lookup_food(" ") is None
def test_roundtrip_case_insensitive(self) -> None:
"""A remembered food is found regardless of case."""
remember_food("Big Mac", _NUT)
found = lookup_food("big mac")
assert found is not None
assert found.kcal == 250
assert found.source == "food bank"
def test_lookup_miss(self) -> None:
"""An unknown food looks up to None."""
assert lookup_food("nope") is None
def test_recording_twice_bumps_count(self) -> None:
"""Re-logging a food increments its use count (raises its ranking)."""
remember_food("oats", _NUT)
remember_food("oats", _NUT)
bank = json.loads(_foodbank.FOOD_BANK_FILE.read_text(encoding="utf-8"))
assert bank["oats"]["count"] == 2
class TestReadDefensive:
"""The bank read tolerates a missing or corrupt file."""
def test_missing_file(self) -> None:
"""No file yet -> empty results."""
assert search_foods("anything") == []
def test_corrupt_json(self) -> None:
"""Unparsable content -> empty bank."""
_foodbank.FOOD_BANK_FILE.write_text("not json", encoding="utf-8")
assert search_foods("x") == []
def test_top_level_not_dict(self) -> None:
"""A non-object top level -> empty bank."""
_write_raw([1, 2, 3])
assert search_foods("x") == []
def test_non_dict_records_filtered(self) -> None:
"""Records that are not objects are dropped on read."""
_write_raw({"good": {"desc": "good", "kcal": 5, "count": 1}, "bad": 123})
names = [name for name, _ in search_foods("")]
assert names == ["good"]
class TestSearch:
"""Ranked autocomplete search."""
def test_empty_query_ranks_by_count(self) -> None:
"""An empty query returns all foods, most-logged first."""
remember_food("rare", _NUT)
remember_food("common", _NUT)
remember_food("common", _NUT)
names = [name for name, _ in search_foods("")]
assert names[0] == "common"
def test_substring_match(self) -> None:
"""A substring of a stored name matches it."""
remember_food("chicken breast", _NUT)
names = [name for name, _ in search_foods("breast")]
assert "chicken breast" in names
def test_typo_within_threshold(self) -> None:
"""A close typo still matches via the fuzzy scorer."""
remember_food("chicken", _NUT)
names = [name for name, _ in search_foods("chiken")]
assert "chicken" in names
def test_below_threshold_filtered(self) -> None:
"""A wildly different query returns nothing."""
remember_food("chicken", _NUT)
assert search_foods("xylophone") == []
def test_display_name_falls_back_to_key(self) -> None:
"""A record with no usable desc displays under its key."""
_write_raw({"applekey": {"kcal": 50, "count": 1}})
names = [name for name, _ in search_foods("")]
assert names == ["applekey"]