From 24be05b9c387f6f85dc2965049130580981018b9 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Sun, 23 Aug 2026 08:00:54 +0200 Subject: [PATCH] feat: mirror the catering parser and slot spread in Dart, gated by one fixture The phone is getting its own Kuchnia Wikinga importer so the feature works with the PC switched off. That turns a risk `_kuchnia_spread.py` called "theoretical" into a live one: two implementations must now agree exactly on which dishes are dropped, which slot each lands on, and the JSON a banked record encodes to. Disagreement means each device re-adds what the other dropped, and since `add_manual_entry` restamps `t` unconditionally, the whole curated bank republishes to every peer on every refresh. A slot mismatch is worse -- a checkpoint one device offers and the other does not can never be satisfied. So the port lands with its gate rather than after it. One shared fixture, `tests/fixtures/kuchnia_day.json`, is asserted by both `pytest` and `flutter test`: same input, same expected dishes, drops, slots, bank keys and records. Two suites written independently from the same prose is not a gate. The fixture is five real dishes (a scrubbed 2026-08-22 capture) plus synthetic meals that each pin one drop or fallback path -- a per-100 g mix-up, an absurd portion, a stringly-typed number, a non-dict entry, a missing `nutrition`, a missing `mealPriority`, and a twin-dish pair. Without those, "the same meals are dropped" is a vacuous assertion against an all-happy-path capture. Both halves were mutation-checked: flipping an expected slot, drop count or record value fails each suite, and flipping `435.0` to `435` fails the byte-identity test while the value comparison still passes, which is why both exist. Three traps the port had to survive, each caught before it shipped: - `_ENERGY_TOLERANCE` is **0.35**. The prose said "~1%", which describes how closely the captured day agreed, not the threshold; porting 0.01 would drop dishes the PC keeps. That paragraph now says so. - `jsonEncode(435)` emits `435` where Python emits `435.0`, so every Dart macro is forced to `double` and a canonical-encoding test pins it. - Dart's `List.sort` is unstable where Python's `sorted` is stable, so the Dart comparator carries the payload index as a final tiebreak. The real dishes live in their own file rather than as a literal in the generator: transcribing them by hand corrupted three of the five, and the error was invisible until the generated fixture was diffed against the capture. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01QQpCiPaSbyRpwsLkH3dgsX --- app/lib/models/kuchnia_dish.dart | 82 ++++++ app/lib/services/kuchnia_parse.dart | 134 +++++++++ app/lib/services/kuchnia_spread.dart | 85 ++++++ app/pubspec.yaml | 2 +- app/test/kuchnia_parity_test.dart | 207 +++++++++++++ diet_guard/_kuchnia_parse.py | 8 + diet_guard/_kuchnia_spread.py | 18 +- diet_guard/tests/test_kuchnia_parity.py | 147 +++++++++ docs/kuchnia-wikinga.md | 38 ++- scripts/build_kuchnia_fixture.py | 192 ++++++++++++ tests/fixtures/kuchnia_day.json | 377 ++++++++++++++++++++++++ tests/fixtures/kuchnia_real_meals.json | 87 ++++++ 12 files changed, 1365 insertions(+), 12 deletions(-) create mode 100644 app/lib/models/kuchnia_dish.dart create mode 100644 app/lib/services/kuchnia_parse.dart create mode 100644 app/lib/services/kuchnia_spread.dart create mode 100644 app/test/kuchnia_parity_test.dart create mode 100644 diet_guard/tests/test_kuchnia_parity.py create mode 100755 scripts/build_kuchnia_fixture.py create mode 100644 tests/fixtures/kuchnia_day.json create mode 100644 tests/fixtures/kuchnia_real_meals.json diff --git a/app/lib/models/kuchnia_dish.dart b/app/lib/models/kuchnia_dish.dart new file mode 100644 index 0000000..9afe894 --- /dev/null +++ b/app/lib/models/kuchnia_dish.dart @@ -0,0 +1,82 @@ +/// One delivered catering dish, with its portion macros. +/// +/// The Dart mirror of `diet_guard/_kuchnia_parse.py`'s `Dish`. Every macro is +/// the total *for this portion*, not per 100 g -- the same convention +/// [Nutrition] uses. +/// +/// KEEP IN SYNC WITH `diet_guard/_kuchnia_parse.py`. Both sides are gated by +/// `tests/fixtures/kuchnia_day.json`; see `kuchnia_parity_test.dart`. +library; + +/// A dish the caterer delivered on a given day. +class KuchniaDish { + /// Creates a dish from its already-validated fields. + const KuchniaDish({ + required this.name, + required this.kcal, + required this.proteinG, + required this.carbsG, + required this.fatG, + required this.grams, + required this.priority, + required this.slotLabel, + }); + + /// The dish itself (`menuMealName`), e.g. "Kaszotto grzybowe...". + /// + /// Not `mealName`, which is the slot label ("Kolacja") and would collapse + /// every Monday dinner onto one food-bank entry. + final String name; + + /// Calories for this portion. + final double kcal; + + /// Protein in grams, for this portion. + final double proteinG; + + /// Carbohydrate in grams, for this portion. + final double carbsG; + + /// Fat in grams, for this portion. + final double fatG; + + /// The portion weight in grams (`nutrition.weight`). + final double grams; + + /// The caterer's own eating order, 1..N. + /// + /// Falls back to the dish's 1-based position in the payload when + /// `mealPriority` is missing. + final int priority; + + /// The caterer's slot label ("Śniadanie", "Obiad", ...), for display only. + final String slotLabel; + + /// The curated-bank record for this dish. + /// + /// Mirrors `_kuchnia_import.dish_to_record`. `count` is 0: the bank's count + /// ranks foods by how often they were *eaten*, and a delivered dish has not + /// been eaten yet. + /// + /// Every macro is forced to `double` before it reaches `jsonEncode`. + /// `jsonEncode(435)` emits `435` where Python emits `435.0`, and a + /// byte-different record for the same dish makes every refresh look like a + /// change -- which republishes the whole curated bank to every peer. + Map toBankRecord() => { + 'desc': name, + 'kcal': kcal.toDouble(), + 'protein_g': proteinG.toDouble(), + 'carbs_g': carbsG.toDouble(), + 'fat_g': fatG.toDouble(), + 'grams': grams.toDouble(), + 'count': 0, + }; + + /// The curated bank's key for this dish. + /// + /// Python uses `str.casefold()` and this uses `String.toLowerCase()`. They + /// agree across the whole Polish alphabet and diverge only on `ß`, + /// ligatures and final sigma; rekeying to unify them would strand every + /// existing entry, so the agreement is pinned by test instead. + String get bankKey => name.trim().toLowerCase(); +} diff --git a/app/lib/services/kuchnia_parse.dart b/app/lib/services/kuchnia_parse.dart new file mode 100644 index 0000000..ee8830d --- /dev/null +++ b/app/lib/services/kuchnia_parse.dart @@ -0,0 +1,134 @@ +/// Turns the catering panel's menu payload into [KuchniaDish] records. +/// +/// The Dart mirror of `diet_guard/_kuchnia_parse.py`. The shape that matters: +/// +/// ```json +/// {"deliveryMenuMeal": [ +/// {"mealName": "Śniadanie", +/// "menuMealName": "Marchewkowe pancakes, ...", +/// "mealPriority": 1, +/// "nutrition": {"weight": 270.0, "calories": 435.0, "protein": 25.86, +/// "carbohydrate": 54.64, "fat": 12.01}}, +/// ...]} +/// ``` +/// +/// **Macros are per portion and `weight` is that portion in grams.** Verified +/// arithmetically rather than assumed. Had they been per-100 g, every imported +/// meal would have been silently wrong by a factor of several -- which is why +/// [parseMenu] drops a dish whose numbers do not hold together instead of +/// importing a plausible-looking lie. +/// +/// KEEP IN SYNC WITH `diet_guard/_kuchnia_parse.py`. If the two sides disagree +/// about which dishes pass, each re-adds what the other dropped and the +/// curated bank republishes to every peer on every refresh. Gated by +/// `tests/fixtures/kuchnia_day.json`. +library; + +import 'package:diet_guard_app/models/kuchnia_dish.dart'; + +/// Atwater factors. Used only as a sanity check on the *units*, never to +/// recompute a value the panel already states. +const double _kcalPerGProtein = 4; +const double _kcalPerGCarb = 4; +const double _kcalPerGFat = 9; + +/// How far the macro-derived energy may drift from the stated calories before +/// the dish is treated as unusable. +/// +/// Generous by design: the panel rounds, and fibre and polyols carry energy +/// these three factors ignore. A per-100 g mix-up misses by a factor of 2-5, +/// nowhere near this band. +/// +/// **This is 0.35, not the "~1%" some prose says** -- that figure describes how +/// closely the captured day happened to agree, not the threshold. Porting 0.01 +/// here would drop dishes the PC keeps. +const double kuchniaEnergyTolerance = 0.35; + +/// A portion outside this range is not a meal. Guards against a unit change +/// (kg for g) rather than against unusual food. +const double _minGrams = 1; +const double _maxGrams = 5000; + +/// Coerces a stored field to `double`, defaulting to 0. +/// +/// Mirrors `diet_guard/_coerce.as_float` exactly, and the exactness is +/// load-bearing: bools and **strings** both yield 0. A payload with +/// `"calories": "435"` must be *dropped* by both devices, so this must not +/// reach for `double.tryParse` -- that would keep a dish the PC discards. +double asDouble(Object? value) { + if (value is bool) return 0; + if (value is num) return value.toDouble(); + return 0; +} + +/// Returns true when the macros roughly account for the stated calories. +/// +/// A *unit* check, not a nutrition check: it catches a payload whose macros +/// and calories are quoted on different bases (per portion vs per 100 g), +/// which is the one failure mode that would corrupt every import without +/// looking wrong. +bool energyIsConsistent(double kcal, double protein, double carbs, double fat) { + if (kcal <= 0) return false; + final derived = + _kcalPerGProtein * protein + _kcalPerGCarb * carbs + _kcalPerGFat * fat; + return (derived - kcal).abs() <= kuchniaEnergyTolerance * kcal; +} + +/// Builds one dish, or null when the entry is unusable. +/// +/// [fallbackPriority] is the 1-based payload position, used when +/// `mealPriority` is missing. +KuchniaDish? parseMeal(Object? meal, int fallbackPriority) { + if (meal is! Map) return null; + final nutrition = meal['nutrition']; + if (nutrition is! Map) return null; + + // `menuMealName` is the dish; `mealName` is the slot label ("Kolacja"), + // which would collapse every Monday dinner onto one bank entry. + final rawName = meal['menuMealName']; + final name = rawName is String ? rawName.trim() : ''; + if (name.isEmpty) return null; + + final kcal = asDouble(nutrition['calories']); + final protein = asDouble(nutrition['protein']); + final carbs = asDouble(nutrition['carbohydrate']); + final fat = asDouble(nutrition['fat']); + final grams = asDouble(nutrition['weight']); + + if (grams < _minGrams || grams > _maxGrams) return null; + if (!energyIsConsistent(kcal, protein, carbs, fat)) return null; + + // Python rejects bools here (they are an int subclass); Dart's `is int` is + // already false for a bool, so the check is naturally equivalent. + final rawPriority = meal['mealPriority']; + final priority = rawPriority is int ? rawPriority : fallbackPriority; + + final rawLabel = meal['mealName']; + return KuchniaDish( + name: name, + kcal: kcal, + proteinG: protein, + carbsG: carbs, + fatG: fat, + grams: grams, + priority: priority, + slotLabel: rawLabel is String ? rawLabel.trim() : '', + ); +} + +/// Extracts the day's dishes from a `menus/delivery/{id}/new` response. +/// +/// Unusable entries are skipped rather than thrown on: a single malformed dish +/// must not cost the user the other four. Returns the dishes in payload order; +/// `kuchnia_spread.dart` sorts them by priority. +List parseMenu(Object? payload) { + if (payload is! Map) return const []; + final meals = payload['deliveryMenuMeal']; + if (meals is! List) return const []; + final dishes = []; + for (var index = 0; index < meals.length; index++) { + final dish = parseMeal(meals[index], index + 1); + if (dish != null) dishes.add(dish); + } + return dishes; +} diff --git a/app/lib/services/kuchnia_spread.dart b/app/lib/services/kuchnia_spread.dart new file mode 100644 index 0000000..226c3ae --- /dev/null +++ b/app/lib/services/kuchnia_spread.dart @@ -0,0 +1,85 @@ +/// Assigns catering dishes to meal slots, in the provider's own order. +/// +/// The Dart mirror of `diet_guard/_kuchnia_spread.py`. +/// +/// The panel returns each dish with a `mealPriority` (1..N: Śniadanie, II +/// śniadanie, Obiad, Podwieczorek, Kolacja) -- the order the catering intends +/// them to be eaten in. That beats inferring an order from the dish names, and +/// it beats spreading them arithmetically. +/// +/// Counts rarely match: a 5-meal plan against the default 4 slots means two +/// dishes share the first slot. The mapping is `i * S ~/ N`, which is +/// monotonic non-decreasing, keeps the first dish on the first slot and the +/// last on the last, and doubles up the earliest slots rather than dropping +/// anything. +/// +/// **Integer `~/` only, never `round()`.** Repo convention for slot arithmetic +/// (`docs/meal-schedule.md`): Python's `round` is banker's and Dart's is +/// half-away-from-zero, so a float path silently desyncs the two devices -- +/// and a slot one device offers while the other does not is a checkpoint that +/// can never be satisfied, i.e. a permanent lock. `index`, `span` and `count` +/// are all `int`, so `~/` matches Python's `//` exactly (`~/` on doubles +/// truncates toward zero where `//` floors). +/// +/// KEEP IN SYNC WITH `diet_guard/_kuchnia_spread.py`, gated by +/// `tests/fixtures/kuchnia_day.json`. +library; + +import 'package:diet_guard_app/models/kuchnia_dish.dart'; + +/// A dish paired with the meal-slot hour it was assigned to. +class SlottedDish { + /// Pairs [dish] with the [slot] hour it should be logged against. + const SlottedDish({required this.dish, required this.slot}); + + /// The dish itself. + final KuchniaDish dish; + + /// The slot hour, e.g. `12` for the 12:00 checkpoint. + final int slot; +} + +/// Pairs each dish with a slot hour, following the provider's meal order. +/// +/// Returns an empty list when either input is empty -- a day with no delivery +/// and a schedule with no slots are both "nothing to assign", not errors. +List assignSlots(List dishes, List slots) { + if (dishes.isEmpty || slots.isEmpty) return const []; + + // Ties fall back to name so the result is deterministic; a bank import that + // reshuffled between runs would look like a change and re-stamp every + // record. + // + // The payload index is the final tiebreak because `List.sort` is *not* + // stable in Dart while Python's `sorted` is: two dishes sharing both + // priority and name would otherwise be free to swap here and not on the PC. + // With the index in the comparator the ordering is total, so both languages + // agree without relying on either sort's stability. + final indexed = <(int, KuchniaDish)>[ + for (var i = 0; i < dishes.length; i++) (i, dishes[i]), + ]; + indexed.sort((a, b) { + final byPriority = a.$2.priority.compareTo(b.$2.priority); + if (byPriority != 0) return byPriority; + final byName = a.$2.name.compareTo(b.$2.name); + if (byName != 0) return byName; + return a.$1.compareTo(b.$1); + }); + + final count = indexed.length; + final span = slots.length; + return [ + for (var index = 0; index < count; index++) + SlottedDish( + dish: indexed[index].$2, + slot: slots[index * span ~/ count], + ), + ]; +} + +/// Returns [dishes] ordered by the provider's own meal priority. +/// +/// So the dish offered for the slot being filled is the one the catering +/// actually intends for it, rather than whatever order the payload arrived in. +List dishesInSlotOrder(List dishes, List slots) => + [for (final item in assignSlots(dishes, slots)) item.dish]; diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 77fcbbe..c492b25 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -2,7 +2,7 @@ name: diet_guard_app description: "Companion phone app for diet_guard: log meals on the go." publish_to: 'none' -version: 1.0.57+1 +version: 1.0.58+1 environment: sdk: ^3.12.2 diff --git a/app/test/kuchnia_parity_test.dart b/app/test/kuchnia_parity_test.dart new file mode 100644 index 0000000..40c07b8 --- /dev/null +++ b/app/test/kuchnia_parity_test.dart @@ -0,0 +1,207 @@ +/// The Dart half of the cross-language catering parity gate. +/// +/// `diet_guard/tests/test_kuchnia_parity.py` asserts the *same* expectations +/// against the *same* `tests/fixtures/kuchnia_day.json`. Two independently +/// written suites from the same prose is not a gate -- one shared input with +/// one shared expected result is, because a divergence has to surface as a +/// failure on one side rather than as two self-consistent implementations. +/// +/// What the parity protects, per `docs/kuchnia-wikinga.md`: +/// +/// * **Slot assignment.** A slot one device offers while the other does not is +/// a checkpoint that can never be satisfied -- a permanent lock. +/// * **Which dishes are dropped.** If the two sides disagree, each re-adds +/// what the other dropped, `add_manual_entry` restamps `t` unconditionally, +/// and the curated bank republishes to every peer on every refresh. +/// * **Bank keys and record values**, including their JSON *types*. +/// +/// `dart:io` is fine here: the repo invariant only scans `lib/`, and +/// `flutter test` runs on the VM. +library; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:diet_guard_app/models/kuchnia_dish.dart'; +import 'package:diet_guard_app/services/kuchnia_parse.dart'; +import 'package:diet_guard_app/services/kuchnia_spread.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// The repo root, found by walking up from the package directory. +/// +/// Mirrors `repo_invariants_test.dart`'s approach so the test works whatever +/// working directory `flutter test` picks. +Directory get _repoRoot { + var dir = Directory.current; + while (!File('${dir.path}/pubspec.yaml').existsSync()) { + final parent = dir.parent; + if (parent.path == dir.path) { + fail('could not locate app/ from ${Directory.current.path}'); + } + dir = parent; + } + // `dir` is app/; the fixture is shared, so it lives at the repo root. + return dir.parent; +} + +File get _fixtureFile => + File('${_repoRoot.path}/tests/fixtures/kuchnia_day.json'); + +void main() { + late Map fixture; + late Map expected; + late List dishes; + + setUpAll(() { + fixture = + jsonDecode(_fixtureFile.readAsStringSync()) as Map; + expected = fixture['expected'] as Map; + dishes = parseMenu(fixture['payload']); + }); + + test('the shared fixture is present', () { + // Asserted explicitly so a relocation fails with a clear reason rather + // than as a confusing cast error inside another test. + expect( + _fixtureFile.existsSync(), + isTrue, + reason: 'shared parity fixture missing at ${_fixtureFile.path}. It is ' + 'read by both flutter test and pytest; regenerate with ' + 'scripts/build_kuchnia_fixture.py.', + ); + }); + + test('parsed dishes match the shared expectation', () { + final actual = [ + for (final dish in dishes) + { + 'name': dish.name, + 'kcal': dish.kcal, + 'protein_g': dish.proteinG, + 'carbs_g': dish.carbsG, + 'fat_g': dish.fatG, + 'grams': dish.grams, + 'priority': dish.priority, + 'slot_label': dish.slotLabel, + }, + ]; + expect(actual, equals(expected['dishes'])); + }); + + test('the same meals are dropped on both sides', () { + // Vacuous against a clean capture, which is why the fixture carries a + // per-100 g mix-up, an absurd portion, a stringly-typed number, a non-map + // entry and a meal with no nutrition at all. + final total = (fixture['payload'] as Map)['deliveryMenuMeal'] as List; + expect(total.length - dishes.length, equals(expected['dropped_count'])); + expect(expected['dropped_count'], greaterThan(0)); + }); + + test('slot assignment matches for every configured schedule', () { + final slotCases = expected['slots'] as Map; + for (final entry in slotCases.entries) { + var key = entry.key; + var subject = dishes; + if (key.startsWith('first_three_')) { + subject = dishes.take(3).toList(); + key = key.substring('first_three_'.length); + } + final hours = [for (final part in key.split(',')) int.parse(part)]; + final actual = [ + for (final item in assignSlots(subject, hours)) item.slot, + ]; + expect( + actual, + equals(entry.value), + reason: 'slot assignment diverged for ${entry.key}', + ); + } + }); + + test('slot ordering is total, so the twin-dish pair cannot reshuffle', () { + // Dart's List.sort is not stable and Python's sorted is, so two dishes + // sharing both priority and name are what force the comparator to be + // total. Run repeatedly: an unstable sort need not misbehave every time. + for (var attempt = 0; attempt < 5; attempt++) { + final ordered = assignSlots(parseMenu(fixture['payload']), const [ + 8, + 12, + 16, + 20, + ]); + expect( + [for (final item in ordered) item.dish.name], + equals(expected['slot_order']), + ); + } + }); + + test('bank keys match', () { + expect( + [for (final dish in dishes) dish.bankKey], + equals(expected['bank_keys']), + ); + }); + + test('bank records match by value', () { + // Numeric comparison, not string: `270 == 270.0` must be true here exactly + // as it is in Python's `_matches`, or every phone refresh rewrites the + // whole curated bank. + expect( + [for (final dish in dishes) dish.toBankRecord()], + equals(expected['bank_records']), + ); + }); + + test('bank records encode byte-identically to the Python ones', () { + // The real divergence risk is int-vs-double at the JSON boundary: + // jsonEncode(435) emits `435` where Python emits `435.0`. Comparing the + // encoded text (canonical key order on both sides) is what catches it; + // the value comparison above would not. + final expectedRecords = expected['bank_records'] as List; + for (var i = 0; i < dishes.length; i++) { + final actual = dishes[i].toBankRecord(); + final wanted = (expectedRecords[i] as Map).cast(); + final sortedKeys = actual.keys.toList()..sort(); + String canonical(Map record) => jsonEncode({ + for (final key in sortedKeys) key: record[key], + }); + expect( + canonical(actual), + equals(canonical(wanted)), + reason: 'record ${i + 1} (${dishes[i].name}) encodes differently to ' + 'the Python-banked record; check int vs double.', + ); + } + }); + + test('macros bank as doubles and count as an int', () { + for (final dish in dishes) { + final record = dish.toBankRecord(); + for (final key in ['kcal', 'protein_g', 'carbs_g', 'fat_g', 'grams']) { + expect( + record[key], + isA(), + reason: '$key must bank as a double, or its JSON loses the ".0"', + ); + } + expect(record['count'], isA()); + } + }); + + test('a stringly-typed number is coerced to 0, never parsed', () { + // Pins the `as_float` contract. `double.tryParse` here would keep a dish + // the PC drops, and then each device re-adds what the other removed. + expect(asDouble('435'), equals(0.0)); + expect(asDouble(true), equals(0.0)); + expect(asDouble(null), equals(0.0)); + expect(asDouble(435), equals(435.0)); + expect(asDouble(435.5), equals(435.5)); + }); + + test('the energy tolerance is 0.35, not the "~1%" in the prose', () { + // Porting 0.01 would drop dishes the PC keeps, and each side would re-add + // what the other dropped -- the republish flood. + expect(kuchniaEnergyTolerance, equals(0.35)); + }); +} diff --git a/diet_guard/_kuchnia_parse.py b/diet_guard/_kuchnia_parse.py index 6ebeaa5..0aa9ec1 100644 --- a/diet_guard/_kuchnia_parse.py +++ b/diet_guard/_kuchnia_parse.py @@ -18,6 +18,14 @@ sums to 2055 kcal against the plan's declared 2000. Had they been per-100 g, every imported meal would have been silently wrong by a factor of several -- which is why :func:`parse_menu` drops a dish whose numbers do not hold together instead of importing a plausible-looking lie. + +That ~1% is how closely the *captured day* happened to agree, **not** the +threshold: :data:`_ENERGY_TOLERANCE` is 0.35. The distinction matters now that +``app/lib/services/kuchnia_parse.dart`` mirrors this check on the phone -- a +port that copied "1%" from this paragraph would drop dishes the PC keeps, and +then each device re-adds what the other dropped, restamping and republishing +the whole curated bank on every refresh. Both sides are gated by +``tests/fixtures/kuchnia_day.json``. """ from __future__ import annotations diff --git a/diet_guard/_kuchnia_spread.py b/diet_guard/_kuchnia_spread.py index 25f40df..0b10ccc 100644 --- a/diet_guard/_kuchnia_spread.py +++ b/diet_guard/_kuchnia_spread.py @@ -14,10 +14,20 @@ last, and doubles up the earliest slots rather than dropping anything. Integer ``//`` only, never ``round()``. That is repo convention for slot arithmetic (``docs/meal-schedule.md``): Python's banker's rounding and Dart's half-away-from-zero disagree on ``.5``, and a slot one device offers while the -other does not is a checkpoint that can never be satisfied. The parity risk is -theoretical *here* -- the phone has no importer and so no mirror of this code -(see the plan's §8) -- but the rule is cheap to keep and expensive to -rediscover. +other does not is a checkpoint that can never be satisfied. + +**The mirror now exists**: ``app/lib/services/kuchnia_spread.dart`` runs this +same mapping on the phone, which fetches the catering menu itself rather than +waiting for the PC to bank it. The parity risk stopped being theoretical the +day that landed, so the two implementations are gated by one shared fixture, +``tests/fixtures/kuchnia_day.json``, asserted by +``diet_guard/tests/test_kuchnia_parity.py`` *and* +``app/test/kuchnia_parity_test.dart`` -- same input, same expected slots. + +One Dart-only hazard has no Python counterpart and is easy to reintroduce: +``List.sort`` is not stable while :func:`sorted` is, so the Dart comparator +carries the payload index as a final tiebreak. Without it two dishes sharing +both a priority and a name could order differently on the two devices. """ from __future__ import annotations diff --git a/diet_guard/tests/test_kuchnia_parity.py b/diet_guard/tests/test_kuchnia_parity.py new file mode 100644 index 0000000..e34346a --- /dev/null +++ b/diet_guard/tests/test_kuchnia_parity.py @@ -0,0 +1,147 @@ +"""The Python half of the cross-language catering parity gate. + +``app/test/kuchnia_parity_test.dart`` asserts the *same* expectations against +the *same* ``tests/fixtures/kuchnia_day.json``. Two independently written +suites from the same prose is not a gate -- one shared input with one shared +expected result is, because a divergence has to show up as a failure on one +side rather than as two self-consistent implementations. + +What the parity actually protects, per ``docs/kuchnia-wikinga.md``: + +* **Slot assignment.** A slot one device offers while the other does not is a + checkpoint that can never be satisfied -- a permanent lock. +* **Which dishes are dropped.** If the two sides disagree, each re-adds what + the other dropped, ``add_manual_entry`` restamps ``t`` unconditionally, and + the curated bank republishes to every peer on every refresh. +* **Bank keys and record values.** Divergence there is the same flood by a + different route. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from diet_guard._kuchnia_import import dish_to_record +from diet_guard._kuchnia_parse import Dish, parse_menu +from diet_guard._kuchnia_spread import assign_slots + +FIXTURE = Path(__file__).resolve().parents[2] / "tests/fixtures/kuchnia_day.json" + + +@pytest.fixture(name="fixture") +def _fixture() -> dict[str, Any]: + """The shared payload/expected pair, read from the committed JSON. + + Typed ``Any`` deliberately: this is decoded JSON whose nested shape is the + fixture's own contract, and every read below is an assertion about that + shape. Threading precise types through would restate the fixture's schema + in the type system without making a divergence any more visible. + """ + with FIXTURE.open(encoding="utf-8") as handle: + data: dict[str, Any] = json.load(handle) + return data + + +@pytest.fixture(name="dishes") +def _dishes(fixture: dict[str, Any]) -> list[Dish]: + """The dishes the parser extracts from the shared payload.""" + return parse_menu(fixture["payload"]) + + +def _slots_for(key: str) -> tuple[int, ...]: + """Turn a fixture slot key such as ``"8,12,16,20"`` into slot hours.""" + return tuple(int(part) for part in key.split(",")) + + +def test_fixture_is_present() -> None: + """The fixture is shared with ``flutter test``; a move breaks both silently. + + Asserted explicitly so a relocation fails here with a clear reason rather + than as a confusing KeyError inside another test. + """ + assert FIXTURE.is_file(), f"shared parity fixture missing at {FIXTURE}" + + +def test_parsed_dishes_match_expected( + fixture: dict[str, Any], dishes: list[Dish] +) -> None: + """Every kept dish matches the shared expectation field for field.""" + expected = fixture["expected"]["dishes"] + actual = [ + { + "name": dish.name, + "kcal": dish.kcal, + "protein_g": dish.protein_g, + "carbs_g": dish.carbs_g, + "fat_g": dish.fat_g, + "grams": dish.grams, + "priority": dish.priority, + "slot_label": dish.slot_label, + } + for dish in dishes + ] + assert actual == expected + + +def test_dropped_count_matches(fixture: dict[str, Any], dishes: list[Dish]) -> None: + """The same meals are refused on both sides. + + A vacuous assertion against a clean capture, which is why the fixture + carries a per-100 g mix-up, an absurd portion, a stringly-typed number, a + non-dict entry and a meal with no nutrition at all. + """ + total = len(fixture["payload"]["deliveryMenuMeal"]) + assert total - len(dishes) == fixture["expected"]["dropped_count"] + assert fixture["expected"]["dropped_count"] > 0 + + +def test_slot_assignment_matches(fixture: dict[str, Any], dishes: list[Dish]) -> None: + """``i * S // N`` lands each dish on the slot the Dart side also picks.""" + for key, expected in fixture["expected"]["slots"].items(): + subject = dishes[:3] if key.startswith("first_three_") else dishes + hours = _slots_for(key.removeprefix("first_three_")) + actual = [item.slot for item in assign_slots(subject, hours)] + assert actual == expected, f"slot assignment diverged for {key}" + + +def test_slot_order_matches(fixture: dict[str, Any], dishes: list[Dish]) -> None: + """Ordering is total, so the twin-dish pair cannot reshuffle between runs. + + Python's ``sorted`` is stable and Dart's ``List.sort`` is not, so two + dishes sharing both priority and name are the case that forces both + comparators to be total. + """ + ordered = assign_slots(dishes, (8, 12, 16, 20)) + assert [item.dish.name for item in ordered] == fixture["expected"]["slot_order"] + + +def test_bank_keys_match(fixture: dict[str, Any], dishes: list[Dish]) -> None: + """Both devices key the curated bank identically for these dish names.""" + keys = [dish.name.strip().casefold() for dish in dishes] + assert keys == fixture["expected"]["bank_keys"] + + +def test_bank_records_match(fixture: dict[str, Any], dishes: list[Dish]) -> None: + """A banked record is value-identical to the one Dart would write.""" + records = [dish_to_record(dish) for dish in dishes] + assert records == fixture["expected"]["bank_records"] + + +def test_bank_record_numbers_are_floats(dishes: list[Dish]) -> None: + """Macros bank as floats, so Dart must ``.toDouble()`` before encoding. + + ``jsonEncode(435)`` emits ``435`` where Python emits ``435.0``. Left + unpinned, an int-typed Dart macro produces a byte-different record for the + same dish, every refresh sees a change, and the curated bank republishes to + every peer -- the same flood a tolerance mismatch causes. + """ + for record in (dish_to_record(dish) for dish in dishes): + for key in ("kcal", "protein_g", "carbs_g", "fat_g", "grams"): + assert isinstance(record[key], float), f"{key} must bank as a float" + # ``count`` is the exception: an int on both sides. + assert isinstance(record["count"], int) + assert not isinstance(record["count"], bool) diff --git a/docs/kuchnia-wikinga.md b/docs/kuchnia-wikinga.md index f383169..e551874 100644 --- a/docs/kuchnia-wikinga.md +++ b/docs/kuchnia-wikinga.md @@ -146,13 +146,37 @@ news: it must not talk over the prompt telling the user which slots to fill. - **`requests` is lazy-imported.** The gate's not-due tick imports the CLI and must not pay ~78ms for an HTTP stack it never touches. Call sites reach through `sys.modules[__name__]` so `patch.object` still wins. -- **The phone needs no importer.** It receives the curated bank and the log - through existing sync, and `FoodBankRecord.fromJson`/`toJson` enumerate a - fixed key set — a provenance field written by the PC would be silently - dropped on every round-trip, producing an endless re-add/re-strip ping-pong. - Verified rather than assumed: `app/test/kuchnia_bank_interop_test.dart` - round-trips a verbatim capture of a real imported bank through the Dart - model, diacritics and `t` stamp included. +- **The phone has its own importer, and the two must agree exactly.** It no + longer merely receives the curated bank: it fetches, parses and banks the + day's dishes itself, so the feature works with the PC switched off. That + makes three things load-bearing across two languages — which dishes are + *dropped*, which *slot* each lands on, and the exact JSON a banked record + encodes to. A disagreement on any of them means each device re-adds what the + other dropped; `add_manual_entry` restamps `t` unconditionally, so the whole + curated bank republishes to every peer on every refresh. A slot mismatch is + worse: a checkpoint one device offers and the other does not can never be + satisfied. + + Gated by **one shared fixture**, `tests/fixtures/kuchnia_day.json`, asserted + by `diet_guard/tests/test_kuchnia_parity.py` *and* + `app/test/kuchnia_parity_test.dart`. Two suites written independently from + the same prose is not a gate; one input with one expected result is. + Regenerate it with `scripts/build_kuchnia_fixture.py`, and re-read the diff + before committing — the script blesses whatever Python currently does. + + Three traps the fixture pins, each of which passed review once: + `_ENERGY_TOLERANCE` is **0.35**, not the ~1% the prose above quotes for the + captured day; `jsonEncode(435)` emits `435` where Python emits `435.0`, so + every Dart macro is forced to `double`; and Dart's `List.sort` is unstable + where Python's `sorted` is stable, so the Dart comparator carries the payload + index as a final tiebreak. + +- **Bank records still round-trip losslessly through the Dart model.** + `FoodBankRecord.fromJson`/`toJson` enumerate a fixed key set — a provenance + field written by the PC would be silently dropped on every round-trip, + producing an endless re-add/re-strip ping-pong. + `app/test/kuchnia_bank_interop_test.dart` round-trips a verbatim capture of a + real imported bank through the Dart model, diacritics and `t` stamp included. - **The two devices normalize bank keys with different primitives** — Python `str.casefold()`, Dart `String.toLowerCase()`. They agree across the entire Polish alphabet and on every real dish name seen so far, and diverge only on diff --git a/scripts/build_kuchnia_fixture.py b/scripts/build_kuchnia_fixture.py new file mode 100755 index 0000000..1d97057 --- /dev/null +++ b/scripts/build_kuchnia_fixture.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +"""Regenerate the shared cross-language catering parity fixture. + +The fixture (``tests/fixtures/kuchnia_day.json``) is read by *both* +``diet_guard/tests/test_kuchnia_parity.py`` and +``app/test/kuchnia_parity_test.dart``. Two independently written suites from +the same prose is not a gate; one shared input with one shared expected result +is. + +``expected`` is generated from the Python implementation, which is the +reference the Dart port must reproduce. That means regenerating after a +behaviour change will happily bless the new behaviour -- so only run this when +the change is intended, and re-read the diff before committing it. + +The five real dishes live in ``tests/fixtures/kuchnia_real_meals.json``: a +scrubbed capture of the live panel on 2026-08-22, where the fields the parser +reads are verbatim, opaque ids are replaced with synthetic ones, and +image/allergen/review metadata is dropped. Every other meal is synthetic and +pins exactly one drop or fallback path. + +Run it from the repo root, where the editable install puts ``diet_guard`` on +the path -- the same assumption the test suite makes. Both forms work: + + python3 scripts/build_kuchnia_fixture.py + python3 -m scripts.build_kuchnia_fixture +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from diet_guard._kuchnia_import import dish_to_record +from diet_guard._kuchnia_parse import Dish, parse_menu +from diet_guard._kuchnia_spread import assign_slots + +FIXTURE = Path(__file__).resolve().parent.parent / "tests/fixtures/kuchnia_day.json" + +#: The real, scrubbed dishes, kept as a sidecar data file rather than a literal +#: here: transcribing them by hand silently corrupted three of the five (wrong +#: macros, truncated names) and the mistake was invisible in review. +#: +#: Diacritics are deliberately preserved. The two devices normalize bank keys +#: with different primitives (Python ``str.casefold()``, Dart +#: ``String.toLowerCase()``) and this is what pins their agreement across the +#: Polish alphabet. +REAL_MEALS_FILE = FIXTURE.parent / "kuchnia_real_meals.json" + + +def _real_meals() -> list[dict[str, object]]: + """Load the scrubbed capture of the live panel on 2026-08-22.""" + with REAL_MEALS_FILE.open(encoding="utf-8") as handle: + return json.load(handle) + + +def _nutrition( + weight: float, kcal: object, protein: float, carbs: float, fat: float +) -> dict[str, object]: + """Build a minimal ``nutrition`` block for a synthetic meal.""" + return { + "weight": weight, + "calories": kcal, + "protein": protein, + "carbohydrate": carbs, + "fat": fat, + } + + +#: One synthetic meal per parser branch. Without these, "dropped dishes" is a +#: vacuous assertion -- a real capture is all happy path. +_SYNTHETIC_MEALS: list[object] = [ + # Macros quoted per 100 g against a per-portion kcal: the one failure mode + # that would silently skew every logged meal by a factor of several. + { + "mealName": "Obiad", + "menuMealName": "Per-100g mix-up, dropped", + "mealPriority": 6, + "nutrition": _nutrition(400.0, 900.0, 5.0, 6.0, 2.0), + }, + # Portion outside the sane gram band (kg mistaken for g). + { + "mealName": "Kolacja", + "menuMealName": "Absurd portion, dropped", + "mealPriority": 7, + "nutrition": _nutrition(9000.0, 500.0, 30.0, 60.0, 15.0), + }, + # No mealPriority -> falls back to 1-based payload position. + { + "mealName": "Przekąska", + "menuMealName": "No priority, kept", + "nutrition": _nutrition(120.0, 300.0, 10.0, 40.0, 8.0), + }, + # A numeric field delivered as a JSON string. ``as_float`` rejects strings + # (0.0), so the energy check fails and the dish drops. Pins the coercion + # contract: Dart must NOT `double.tryParse` its way to a different answer. + { + "mealName": "Obiad", + "menuMealName": "Stringly typed, dropped", + "mealPriority": 8, + "nutrition": _nutrition(200.0, "435", 25.0, 50.0, 12.0), + }, + # Not a dict at all. + "not-a-meal", + # ``nutrition`` absent entirely. + { + "mealName": "Obiad", + "menuMealName": "No nutrition, dropped", + "mealPriority": 9, + }, + # Two dishes sharing BOTH priority and name. Python's ``sorted`` is stable + # and Dart's ``List.sort`` is not, so this pair is what forces both sides to + # make the comparator total. + { + "mealName": "Obiad", + "menuMealName": "Twin dish", + "mealPriority": 5, + "nutrition": _nutrition(300.0, 400.0, 25.0, 45.0, 12.0), + }, + { + "mealName": "Obiad", + "menuMealName": "Twin dish", + "mealPriority": 5, + "nutrition": _nutrition(300.0, 400.0, 25.0, 45.0, 12.0), + }, +] + + +def _dish_json(dish: Dish) -> dict[str, object]: + """Serialize a ``Dish`` field-for-field for the expected block.""" + return { + "name": dish.name, + "kcal": dish.kcal, + "protein_g": dish.protein_g, + "carbs_g": dish.carbs_g, + "fat_g": dish.fat_g, + "grams": dish.grams, + "priority": dish.priority, + "slot_label": dish.slot_label, + } + + +def build() -> dict[str, object]: + """Return the whole fixture: the payload and its expected results.""" + payload = { + "deliveryMenuMeal": [*_real_meals(), *_SYNTHETIC_MEALS], + "menuVisible": True, + "showNutrition": True, + } + dishes = parse_menu(payload) + default_slots = (8, 12, 16, 20) + return { + "_comment": ( + "Shared parity fixture for the Kuchnia Wikinga catering import. " + "Read by BOTH diet_guard/tests/test_kuchnia_parity.py and " + "app/test/kuchnia_parity_test.dart -- same input, same expected " + "result. Regenerate with scripts/build_kuchnia_fixture.py." + ), + "payload": payload, + "expected": { + "dishes": [_dish_json(dish) for dish in dishes], + "dropped_count": len(payload["deliveryMenuMeal"]) - len(dishes), + "slots": { + "8,12,16,20": [s.slot for s in assign_slots(dishes, default_slots)], + "8,12,16,20,22": [ + s.slot for s in assign_slots(dishes, (8, 12, 16, 20, 22)) + ], + # The other direction: fewer dishes than slots. + "first_three_8,12,16,20": [ + s.slot for s in assign_slots(dishes[:3], default_slots) + ], + }, + "slot_order": [s.dish.name for s in assign_slots(dishes, default_slots)], + "bank_keys": [dish.name.strip().casefold() for dish in dishes], + "bank_records": [dish_to_record(dish) for dish in dishes], + }, + } + + +def main() -> None: + """Write the fixture to disk. + + Deliberately silent: ``T201`` bans ``print`` here, and the script's output + is the file itself -- ``git diff`` is how you check what changed. + """ + FIXTURE.parent.mkdir(parents=True, exist_ok=True) + with FIXTURE.open("w", encoding="utf-8") as handle: + json.dump(build(), handle, ensure_ascii=False, indent=2, sort_keys=True) + handle.write("\n") + + +if __name__ == "__main__": + main() diff --git a/tests/fixtures/kuchnia_day.json b/tests/fixtures/kuchnia_day.json new file mode 100644 index 0000000..c0ca23e --- /dev/null +++ b/tests/fixtures/kuchnia_day.json @@ -0,0 +1,377 @@ +{ + "_comment": "Shared parity fixture for the Kuchnia Wikinga catering import. Read by BOTH diet_guard/tests/test_kuchnia_parity.py and app/test/kuchnia_parity_test.dart -- same input, same expected result. Regenerate with scripts/build_kuchnia_fixture.py.", + "expected": { + "bank_keys": [ + "marchewkowe pancakes, twarożek cynamonowy, sos truskawkowy", + "hummus paprykowy, mini wafle kukurydziane, warzywa", + "makaron farfalle z indykiem w sosie z batatów z suszonymi pomidorami, ser włoski", + "fit ciasto, jak twix white", + "kaszotto grzybowe z pieczonym kurczakiem i serem włoskim", + "no priority, kept", + "twin dish", + "twin dish" + ], + "bank_records": [ + { + "carbs_g": 54.64, + "count": 0, + "desc": "Marchewkowe pancakes, twarożek cynamonowy, sos truskawkowy", + "fat_g": 12.01, + "grams": 270.0, + "kcal": 435.0, + "protein_g": 25.86 + }, + { + "carbs_g": 41.67, + "count": 0, + "desc": "Hummus paprykowy, mini wafle kukurydziane, warzywa", + "fat_g": 17.26, + "grams": 205.0, + "kcal": 367.0, + "protein_g": 10.86 + }, + { + "carbs_g": 53.23, + "count": 0, + "desc": "Makaron farfalle z indykiem w sosie z batatów z suszonymi pomidorami, ser włoski", + "fat_g": 23.21, + "grams": 465.0, + "kcal": 594.0, + "protein_g": 42.47 + }, + { + "carbs_g": 25.18, + "count": 0, + "desc": "Fit ciasto, jak twix white", + "fat_g": 17.36, + "grams": 90.0, + "kcal": 268.0, + "protein_g": 5.85 + }, + { + "carbs_g": 35.56, + "count": 0, + "desc": "Kaszotto grzybowe z pieczonym kurczakiem i serem włoskim", + "fat_g": 13.02, + "grams": 318.0, + "kcal": 391.0, + "protein_g": 32.51 + }, + { + "carbs_g": 40.0, + "count": 0, + "desc": "No priority, kept", + "fat_g": 8.0, + "grams": 120.0, + "kcal": 300.0, + "protein_g": 10.0 + }, + { + "carbs_g": 45.0, + "count": 0, + "desc": "Twin dish", + "fat_g": 12.0, + "grams": 300.0, + "kcal": 400.0, + "protein_g": 25.0 + }, + { + "carbs_g": 45.0, + "count": 0, + "desc": "Twin dish", + "fat_g": 12.0, + "grams": 300.0, + "kcal": 400.0, + "protein_g": 25.0 + } + ], + "dishes": [ + { + "carbs_g": 54.64, + "fat_g": 12.01, + "grams": 270.0, + "kcal": 435.0, + "name": "Marchewkowe pancakes, twarożek cynamonowy, sos truskawkowy", + "priority": 1, + "protein_g": 25.86, + "slot_label": "Śniadanie" + }, + { + "carbs_g": 41.67, + "fat_g": 17.26, + "grams": 205.0, + "kcal": 367.0, + "name": "Hummus paprykowy, mini wafle kukurydziane, warzywa", + "priority": 2, + "protein_g": 10.86, + "slot_label": "II śniadanie" + }, + { + "carbs_g": 53.23, + "fat_g": 23.21, + "grams": 465.0, + "kcal": 594.0, + "name": "Makaron farfalle z indykiem w sosie z batatów z suszonymi pomidorami, ser włoski", + "priority": 3, + "protein_g": 42.47, + "slot_label": "Obiad" + }, + { + "carbs_g": 25.18, + "fat_g": 17.36, + "grams": 90.0, + "kcal": 268.0, + "name": "Fit ciasto, jak twix white", + "priority": 4, + "protein_g": 5.85, + "slot_label": "Podwieczorek" + }, + { + "carbs_g": 35.56, + "fat_g": 13.02, + "grams": 318.0, + "kcal": 391.0, + "name": "Kaszotto grzybowe z pieczonym kurczakiem i serem włoskim", + "priority": 5, + "protein_g": 32.51, + "slot_label": "Kolacja" + }, + { + "carbs_g": 40.0, + "fat_g": 8.0, + "grams": 120.0, + "kcal": 300.0, + "name": "No priority, kept", + "priority": 8, + "protein_g": 10.0, + "slot_label": "Przekąska" + }, + { + "carbs_g": 45.0, + "fat_g": 12.0, + "grams": 300.0, + "kcal": 400.0, + "name": "Twin dish", + "priority": 5, + "protein_g": 25.0, + "slot_label": "Obiad" + }, + { + "carbs_g": 45.0, + "fat_g": 12.0, + "grams": 300.0, + "kcal": 400.0, + "name": "Twin dish", + "priority": 5, + "protein_g": 25.0, + "slot_label": "Obiad" + } + ], + "dropped_count": 5, + "slot_order": [ + "Marchewkowe pancakes, twarożek cynamonowy, sos truskawkowy", + "Hummus paprykowy, mini wafle kukurydziane, warzywa", + "Makaron farfalle z indykiem w sosie z batatów z suszonymi pomidorami, ser włoski", + "Fit ciasto, jak twix white", + "Kaszotto grzybowe z pieczonym kurczakiem i serem włoskim", + "Twin dish", + "Twin dish", + "No priority, kept" + ], + "slots": { + "8,12,16,20": [ + 8, + 8, + 12, + 12, + 16, + 16, + 20, + 20 + ], + "8,12,16,20,22": [ + 8, + 8, + 12, + 12, + 16, + 20, + 20, + 22 + ], + "first_three_8,12,16,20": [ + 8, + 12, + 16 + ] + } + }, + "payload": { + "deliveryMenuMeal": [ + { + "deliveryMealId": 1001, + "mealName": "Śniadanie", + "mealPriority": 1, + "menuMealName": "Marchewkowe pancakes, twarożek cynamonowy, sos truskawkowy", + "nutrition": { + "calories": 435.0, + "carbohydrate": 54.64, + "dietaryFiber": 2.03, + "fat": 12.01, + "protein": 25.86, + "salt": 0.52, + "saturatedFattyAcids": 1.92, + "sugar": 22.4, + "weight": 270.0 + } + }, + { + "deliveryMealId": 1002, + "mealName": "II śniadanie", + "mealPriority": 2, + "menuMealName": "Hummus paprykowy, mini wafle kukurydziane, warzywa", + "nutrition": { + "calories": 367.0, + "carbohydrate": 41.67, + "dietaryFiber": 9.18, + "fat": 17.26, + "protein": 10.86, + "salt": 1.27, + "saturatedFattyAcids": 1.59, + "sugar": 3.77, + "weight": 205.0 + } + }, + { + "deliveryMealId": 1003, + "mealName": "Obiad", + "mealPriority": 3, + "menuMealName": "Makaron farfalle z indykiem w sosie z batatów z suszonymi pomidorami, ser włoski", + "nutrition": { + "calories": 594.0, + "carbohydrate": 53.23, + "dietaryFiber": 3.83, + "fat": 23.21, + "protein": 42.47, + "salt": 1.08, + "saturatedFattyAcids": 7.03, + "sugar": 4.88, + "weight": 465.0 + } + }, + { + "deliveryMealId": 1004, + "mealName": "Podwieczorek", + "mealPriority": 4, + "menuMealName": "Fit ciasto, jak twix white", + "nutrition": { + "calories": 268.0, + "carbohydrate": 25.18, + "dietaryFiber": 0.36, + "fat": 17.36, + "protein": 5.85, + "salt": 0.15, + "saturatedFattyAcids": 10.76, + "sugar": 8.3, + "weight": 90.0 + } + }, + { + "deliveryMealId": 1005, + "mealName": "Kolacja", + "mealPriority": 5, + "menuMealName": "Kaszotto grzybowe z pieczonym kurczakiem i serem włoskim", + "nutrition": { + "calories": 391.0, + "carbohydrate": 35.56, + "dietaryFiber": 3.69, + "fat": 13.02, + "protein": 32.51, + "salt": 1.3, + "saturatedFattyAcids": 6.53, + "sugar": 1.99, + "weight": 318.0 + } + }, + { + "mealName": "Obiad", + "mealPriority": 6, + "menuMealName": "Per-100g mix-up, dropped", + "nutrition": { + "calories": 900.0, + "carbohydrate": 6.0, + "fat": 2.0, + "protein": 5.0, + "weight": 400.0 + } + }, + { + "mealName": "Kolacja", + "mealPriority": 7, + "menuMealName": "Absurd portion, dropped", + "nutrition": { + "calories": 500.0, + "carbohydrate": 60.0, + "fat": 15.0, + "protein": 30.0, + "weight": 9000.0 + } + }, + { + "mealName": "Przekąska", + "menuMealName": "No priority, kept", + "nutrition": { + "calories": 300.0, + "carbohydrate": 40.0, + "fat": 8.0, + "protein": 10.0, + "weight": 120.0 + } + }, + { + "mealName": "Obiad", + "mealPriority": 8, + "menuMealName": "Stringly typed, dropped", + "nutrition": { + "calories": "435", + "carbohydrate": 50.0, + "fat": 12.0, + "protein": 25.0, + "weight": 200.0 + } + }, + "not-a-meal", + { + "mealName": "Obiad", + "mealPriority": 9, + "menuMealName": "No nutrition, dropped" + }, + { + "mealName": "Obiad", + "mealPriority": 5, + "menuMealName": "Twin dish", + "nutrition": { + "calories": 400.0, + "carbohydrate": 45.0, + "fat": 12.0, + "protein": 25.0, + "weight": 300.0 + } + }, + { + "mealName": "Obiad", + "mealPriority": 5, + "menuMealName": "Twin dish", + "nutrition": { + "calories": 400.0, + "carbohydrate": 45.0, + "fat": 12.0, + "protein": 25.0, + "weight": 300.0 + } + } + ], + "menuVisible": true, + "showNutrition": true + } +} diff --git a/tests/fixtures/kuchnia_real_meals.json b/tests/fixtures/kuchnia_real_meals.json new file mode 100644 index 0000000..0a18189 --- /dev/null +++ b/tests/fixtures/kuchnia_real_meals.json @@ -0,0 +1,87 @@ +[ + { + "deliveryMealId": 1001, + "mealName": "Śniadanie", + "mealPriority": 1, + "menuMealName": "Marchewkowe pancakes, twarożek cynamonowy, sos truskawkowy", + "nutrition": { + "calories": 435.0, + "carbohydrate": 54.64, + "dietaryFiber": 2.03, + "fat": 12.01, + "protein": 25.86, + "salt": 0.52, + "saturatedFattyAcids": 1.92, + "sugar": 22.4, + "weight": 270.0 + } + }, + { + "deliveryMealId": 1002, + "mealName": "II śniadanie", + "mealPriority": 2, + "menuMealName": "Hummus paprykowy, mini wafle kukurydziane, warzywa", + "nutrition": { + "calories": 367.0, + "carbohydrate": 41.67, + "dietaryFiber": 9.18, + "fat": 17.26, + "protein": 10.86, + "salt": 1.27, + "saturatedFattyAcids": 1.59, + "sugar": 3.77, + "weight": 205.0 + } + }, + { + "deliveryMealId": 1003, + "mealName": "Obiad", + "mealPriority": 3, + "menuMealName": "Makaron farfalle z indykiem w sosie z batatów z suszonymi pomidorami, ser włoski", + "nutrition": { + "calories": 594.0, + "carbohydrate": 53.23, + "dietaryFiber": 3.83, + "fat": 23.21, + "protein": 42.47, + "salt": 1.08, + "saturatedFattyAcids": 7.03, + "sugar": 4.88, + "weight": 465.0 + } + }, + { + "deliveryMealId": 1004, + "mealName": "Podwieczorek", + "mealPriority": 4, + "menuMealName": "Fit ciasto, jak twix white", + "nutrition": { + "calories": 268.0, + "carbohydrate": 25.18, + "dietaryFiber": 0.36, + "fat": 17.36, + "protein": 5.85, + "salt": 0.15, + "saturatedFattyAcids": 10.76, + "sugar": 8.3, + "weight": 90.0 + } + }, + { + "deliveryMealId": 1005, + "mealName": "Kolacja", + "mealPriority": 5, + "menuMealName": "Kaszotto grzybowe z pieczonym kurczakiem i serem włoskim", + "nutrition": { + "calories": 391.0, + "carbohydrate": 35.56, + "dietaryFiber": 3.69, + "fat": 13.02, + "protein": 32.51, + "salt": 1.3, + "saturatedFattyAcids": 6.53, + "sugar": 1.99, + "weight": 318.0 + } + } +]