feat(recipe): add step quantities and appliance settings
Release Drafter / auto_label (push) Skipped
Release Drafter / draft_release (push) Canceled after 0s
CodeQL / Analyze (javascript-typescript) (push) Canceled after 0s
CodeQL / Analyze (python) (push) Canceled after 0s
Backend Lint and Test / tests (sqlite) (push) Canceled after 0s
Backend Lint and Test / tests (postgres) (push) Canceled after 0s
Docker Nightly Production / Backend Server Tests (push) Canceled after 0s
Frontend Lint and Test / lint (push) Canceled after 0s
Docker Nightly Production / Frontend Tests (push) Canceled after 0s
Build Package / Build frontend and wheel (push) Canceled after 0s
Docker Nightly Production / Build Package (push) Canceled after 0s
Docker Nightly Production / Build E2E Image Cache (push) Canceled after 0s
Docker Nightly Production / Build Tagged Release (push) Canceled after 0s
Docker Nightly Production / Notify Discord (push) Canceled after 0s

This commit is contained in:
jfmcarreira committed 2026-12-01 13:05:50 +00:00
1 parent 1dd63a070b
commit 8dad430650
51 files changed
+2775 -77

No files matched your search

@@ -64,8 +64,16 @@ def create_populated_recipe(api_client: TestClient, user: TestUser) -> dict:
"title": "Prep Work",
"summary": "Season the meat",
"text": "Season the **beef**.",
"ingredientReferences": [{"referenceId": reference_id}],
"ingredientReferences": [{"referenceId": reference_id, "quantity": 0.5}],
"noteReferences": [{"referenceId": note_reference_id}],
"durationSeconds": 180,
"cooking": {
"appliance": "thermomix",
"temperatureCelsius": 120,
"speed": "spoon",
"reverse": True,
"mode": "steaming",
},
}
],
}
@@ -91,6 +99,67 @@ def camel_case_export(api_client: TestClient, user: TestUser, slug: str) -> str:
EXPORTS: list[Callable[[TestClient, TestUser, str], str]] = [snake_case_export, camel_case_export]
def test_duplicate_remaps_ingredient_links_and_preserves_step_metadata(api_client: TestClient, unique_user: TestUser):
original = create_populated_recipe(api_client, unique_user)
response = api_client.post(
api_routes.recipes_slug_duplicate(original["slug"]), json={"name": random_string()}, headers=unique_user.token
)
assert response.status_code == 201, response.text
duplicate = response.json()
original_step = original["recipeInstructions"][0]
step = duplicate["recipeInstructions"][0]
assert duplicate["recipeIngredient"][0]["referenceId"] != original["recipeIngredient"][0]["referenceId"]
assert step["ingredientReferences"][0]["referenceId"] == duplicate["recipeIngredient"][0]["referenceId"]
assert step["ingredientReferences"][0]["quantity"] == 0.5
assert step["cooking"] == original_step["cooking"]
assert step["durationSeconds"] == 180
@pytest.mark.parametrize("reverse", [True, False, None])
def test_update_rotation_direction(api_client: TestClient, unique_user: TestUser, reverse: bool | None):
recipe = create_populated_recipe(api_client, unique_user)
recipe["recipeInstructions"][0]["cooking"]["reverse"] = reverse
response = api_client.put(api_routes.recipes_slug(recipe["slug"]), json=recipe, headers=unique_user.token)
assert response.status_code == 200, response.text
saved = api_client.get(api_routes.recipes_slug(recipe["slug"]), headers=unique_user.token).json()
assert saved["recipeInstructions"][0]["cooking"]["reverse"] is reverse
assert saved["recipeInstructions"][0]["cooking"]["speed"] == "spoon"
def test_update_and_clear_existing_step_metadata(api_client: TestClient, unique_user: TestUser):
recipe = create_populated_recipe(api_client, unique_user)
step = recipe["recipeInstructions"][0]
step["ingredientReferences"][0]["quantity"] = 1.25
step["cooking"]["speed"] = 1
response = api_client.put(api_routes.recipes_slug(recipe["slug"]), json=recipe, headers=unique_user.token)
assert response.status_code == 200, response.text
saved = api_client.get(api_routes.recipes_slug(recipe["slug"]), headers=unique_user.token).json()
assert saved["recipeInstructions"][0]["ingredientReferences"][0]["quantity"] == 1.25
assert saved["recipeInstructions"][0]["cooking"]["speed"] == 1
saved["recipeInstructions"][0]["ingredientReferences"][0]["quantity"] = None
saved["recipeInstructions"][0]["cooking"] = None
response = api_client.put(api_routes.recipes_slug(recipe["slug"]), json=saved, headers=unique_user.token)
assert response.status_code == 200, response.text
cleared = api_client.get(api_routes.recipes_slug(recipe["slug"]), headers=unique_user.token).json()
assert cleared["recipeInstructions"][0]["ingredientReferences"][0]["quantity"] is None
assert cleared["recipeInstructions"][0]["cooking"] is None
def test_shopping_list_uses_recipe_quantity_not_step_portion(
api_client: TestClient, unique_user: TestUser, shopping_lists
):
recipe = create_populated_recipe(api_client, unique_user)
shopping_list = shopping_lists[0]
response = api_client.post(
api_routes.households_shopping_lists_item_id_recipe_recipe_id(shopping_list.id, recipe["id"]),
headers=unique_user.token,
)
assert response.status_code == 200, response.text
result = api_client.get(api_routes.households_shopping_lists_item_id(shopping_list.id), headers=unique_user.token)
assert result.status_code == 200
assert result.json()["listItems"][0]["quantity"] == 2
def paste(
api_client: TestClient, user: TestUser, data: str, include_tags: bool = True, include_categories: bool = True
) -> Response:
@@ -135,6 +204,9 @@ def test_paste_mealie_export_keeps_contents(
step = imported["recipeInstructions"][0]
assert (step["title"], step["summary"], step["text"]) == ("Prep Work", "Season the meat", "Season the **beef**.")
assert [ref["referenceId"] for ref in step["ingredientReferences"]] == [ingredient["referenceId"]]
assert step["ingredientReferences"][0]["quantity"] == 0.5
assert step["durationSeconds"] == 180
assert step["cooking"] == original["recipeInstructions"][0]["cooking"]
# the recipe the export came from is untouched
still_there = api_client.get(api_routes.recipes_slug(original["slug"]), headers=unique_user.token)
@@ -29,13 +29,13 @@ def test_duration_persists_edits_clears_and_exports_for_zip_import(api_client, u
assert [step["durationSeconds"] for step in reloaded["recipeInstructions"]] == [None, None, 3661]
# Fresh GET crosses the request-scoped session boundary, rather than reading a mock ORM object.
reloaded["recipeInstructions"][2]["durationSeconds"] = 42
reloaded["recipeInstructions"][2]["durationSeconds"] = 0.5
assert api_client.put(route, json=reloaded, headers=unique_user.token).status_code == 200
reloaded = api_client.get(route, headers=unique_user.token).json()
assert reloaded["recipeInstructions"][2]["durationSeconds"] == 42
assert reloaded["recipeInstructions"][2]["durationSeconds"] == 0.5
exported = TemplateService(temp=tmp_path).render(RecipeDraft.model_validate(reloaded), "raw")
imported = json.loads(exported.read_text())
assert [step["durationSeconds"] for step in imported["recipeInstructions"]] == [None, None, 42]
assert [step["durationSeconds"] for step in imported["recipeInstructions"]] == [None, None, 0.5]
imported["id"] = str(uuid4())
imported["name"] = imported["slug"] = f"duration-import-{uuid4()}"
for step in imported["recipeInstructions"]:
@@ -49,7 +49,7 @@ def test_duration_persists_edits_clears_and_exports_for_zip_import(api_client, u
assert response.status_code == 201
restored = api_client.get(api_routes.recipes_slug(imported["slug"]), headers=unique_user.token)
assert restored.status_code == 200
assert [step["durationSeconds"] for step in restored.json()["recipeInstructions"]] == [None, None, 42]
assert [step["durationSeconds"] for step in restored.json()["recipeInstructions"]] == [None, None, 0.5]
reloaded["recipeInstructions"][2]["durationSeconds"] = clear_value
assert api_client.put(route, json=reloaded, headers=unique_user.token).status_code == 200
@@ -67,11 +67,11 @@ def test_api_persists_whole_numeric_spellings(api_client, unique_user, random_re
response = api_client.put(route, content=body, headers={**unique_user.token, "Content-Type": "application/json"})
assert response.status_code == 200
restored = api_client.get(route, headers=unique_user.token).json()["recipeInstructions"][0]
assert type(restored["durationSeconds"]) is int
assert type(restored["durationSeconds"]) is float
assert restored["durationSeconds"] == int(float(number))
@pytest.mark.parametrize("value", [True, False, "90", -1, 1.5, 2147483647.5, "", " ", 2147483648])
@pytest.mark.parametrize("value", [True, False, "90", -1, 0.0001, 1.2345, 2147483647.5, "", " ", 2147483648])
def test_api_rejects_invalid_duration_without_saving(api_client, unique_user, random_recipe, value):
route = api_routes.recipes_slug(random_recipe.slug)
before = api_client.get(route, headers=unique_user.token).json()
@@ -0,0 +1,199 @@
import json
from uuid import uuid4
from mealie.schema.recipe.recipe_step import IngredientReferences, StepCooking
from tests.utils import api_routes
def operation_recipe(api_client, unique_user):
slug = api_client.post(api_routes.recipes, json={"name": f"Operations {uuid4()}"}, headers=unique_user.token).json()
route = api_routes.recipes_slug(slug)
recipe = api_client.get(route, headers=unique_user.token).json()
ref_id, step_id = str(uuid4()), str(uuid4())
recipe["recipeIngredient"] = [{"referenceId": ref_id, "quantity": 100, "note": "flour"}]
recipe["recipeInstructions"] = [
{
"id": step_id,
"text": "Mix and check consistency",
"durationSeconds": 0.5,
"ingredientReferences": [
{
"referenceId": ref_id,
"quantityKind": "partial",
"quantity": 20,
"weighing": "weigh",
"role": "addition",
"destination": "bowl",
"quantityMinimum": 19,
"quantityMaximum": 21,
"approximate": True,
"containerCount": 2,
"sourceText": "two portions",
}
],
"cooking": {
"appliance": "mixer",
"applianceInstance": "left",
"actionType": "machine",
"timerType": "machine",
"durationKind": "range",
"temperatureCelsius": 37.5,
"speed": 1.5,
"reverse": False,
"mode": "pulse",
"durationRangeSeconds": {"minimum": 0.5, "maximum": 2.5},
"durationCondition": "Until combined",
"speedKind": "progression",
"speedRange": {"minimum": 1, "maximum": 5},
"speedProgression": [1, 3, 5],
"accessories": [
{"name": name, "state": state}
for name, state in [
("steamer", "installed"),
("basket", "removed"),
("whisk", "unknown"),
("lid", "closed"),
]
],
"modeParameters": [
{"name": "thickness", "kind": "text", "value": "coarse"},
{"name": "doneness", "kind": "text", "value": "medium soft"},
{"name": "pulses", "kind": "number", "value": 3},
{"name": "cover", "kind": "boolean", "value": False},
{"name": "pulseRange", "kind": "range", "minimum": 2, "maximum": 4},
],
"optional": True,
"condition": "If too coarse",
"requiresConfirmation": True,
"repetitions": 3,
"repetitionRange": {"minimum": 2, "maximum": 4},
"reviews": [
{
"category": "ingredient",
"source": "add some flour",
"reason": "Ambiguous portion",
"candidateIngredientIds": [ref_id],
}
],
},
},
{
"text": "Reuse mixture",
"ingredientReferences": [{"referenceId": ref_id, "quantityKind": "prepared"}],
"cooking": {"actionType": "manual", "dependsOnStepIds": [step_id]},
},
]
response = api_client.put(route, json=recipe, headers=unique_user.token)
assert response.status_code == 200, response.text
saved = api_client.get(route, headers=unique_user.token).json()
desired = StepCooking.model_validate(recipe["recipeInstructions"][0]["cooking"]).model_dump(
mode="json", by_alias=True
)
actual = saved["recipeInstructions"][0]["cooking"]
assert {key: value for key, value in actual.items() if key != "reviews"} == {
key: value for key, value in desired.items() if key != "reviews"
}
desired_reference = IngredientReferences.model_validate(
recipe["recipeInstructions"][0]["ingredientReferences"][0]
).model_dump(mode="json", by_alias=True)
assert {
key: value
for key, value in saved["recipeInstructions"][0]["ingredientReferences"][0].items()
if key != "allocationId"
} == {key: value for key, value in desired_reference.items() if key != "allocationId"}
return saved
def test_full_operations_round_trip_edit_duplicate_and_export(api_client, unique_user):
recipe = operation_recipe(api_client, unique_user)
step = recipe["recipeInstructions"][0]
assert step["durationSeconds"] == 0.5
assert step["ingredientReferences"][0]["weighing"] == "weigh"
assert step["cooking"]["modeParameters"][3]["value"] is False
allocation_id = step["ingredientReferences"][0]["allocationId"]
review = step["cooking"]["reviews"][0]
assert review["history"] and review["status"] == "unresolved"
review["resolution"], review["status"] = "Confirmed portion and manual check", "resolved"
route = api_routes.recipes_slug(recipe["slug"])
assert api_client.put(route, json=recipe, headers=unique_user.token).status_code == 200
saved = api_client.get(route, headers=unique_user.token).json()
assert saved["recipeInstructions"][0]["ingredientReferences"][0]["allocationId"] == allocation_id
assert saved["recipeInstructions"][0]["cooking"]["reviews"][0]["approvedContent"]
assert saved["recipeInstructions"][0]["id"] == step["id"]
# Reordering never renumbers instruction/allocation identities or loses dependencies.
saved["recipeInstructions"].reverse()
assert api_client.put(route, json=saved, headers=unique_user.token).status_code == 200
reordered = api_client.get(route, headers=unique_user.token).json()
assert reordered["recipeInstructions"][1]["id"] == step["id"]
assert reordered["recipeInstructions"][1]["ingredientReferences"][0]["allocationId"] == allocation_id
saved["recipeInstructions"].reverse()
assert api_client.put(route, json=saved, headers=unique_user.token).status_code == 200
duplicated = api_client.post(
api_routes.recipes_slug_duplicate(recipe["slug"]), json={"name": f"Copy {uuid4()}"}, headers=unique_user.token
)
assert duplicated.status_code == 201, duplicated.text
copy = duplicated.json()
copied_step = copy["recipeInstructions"][0]
assert copied_step["id"] != step["id"]
assert copied_step["ingredientReferences"][0]["allocationId"] != allocation_id
assert copy["recipeInstructions"][1]["cooking"]["dependsOnStepIds"] == [copied_step["id"]]
assert copied_step["cooking"]["reviews"][0]["candidateIngredientIds"] == [
copy["recipeIngredient"][0]["referenceId"]
]
assert copied_step["cooking"]["modeParameters"] == step["cooking"]["modeParameters"]
response = api_client.post(
api_routes.recipes_create_html_or_json,
json={"data": json.dumps(saved), "include_tags": True, "include_categories": True},
headers=unique_user.token,
)
assert response.status_code == 201, response.text
imported = api_client.get(api_routes.recipes_slug(response.json()), headers=unique_user.token).json()
assert imported["recipeInstructions"][0]["cooking"]["modeParameters"] == step["cooking"]["modeParameters"]
assert imported["recipeInstructions"][0]["ingredientReferences"][0]["quantityKind"] == "partial"
assert imported["recipeInstructions"][1]["cooking"]["dependsOnStepIds"] == [imported["recipeInstructions"][0]["id"]]
def test_changed_native_content_reopens_review_without_erasing_history(api_client, unique_user):
recipe = operation_recipe(api_client, unique_user)
route = api_routes.recipes_slug(recipe["slug"])
review = recipe["recipeInstructions"][0]["cooking"]["reviews"][0]
review.update(status="resolved", resolution="Checked")
assert api_client.put(route, json=recipe, headers=unique_user.token).status_code == 200
saved = api_client.get(route, headers=unique_user.token).json()
history = saved["recipeInstructions"][0]["cooking"]["reviews"][0]["history"]
saved["recipeInstructions"][0]["cooking"]["speed"] = 2
assert api_client.put(route, json=saved, headers=unique_user.token).status_code == 200
changed = api_client.get(route, headers=unique_user.token).json()
review = changed["recipeInstructions"][0]["cooking"]["reviews"][0]
assert review["status"] == "unresolved"
assert review["history"][: len(history)] == history
assert review["source"] == "add some flour"
changed["recipeInstructions"][0]["cooking"] = None
assert api_client.put(route, json=changed, headers=unique_user.token).status_code == 200
assert api_client.get(route, headers=unique_user.token).json()["recipeInstructions"][0]["cooking"]["reviews"]
def test_all_allocation_kinds_survive_readback(api_client, unique_user):
recipe = operation_recipe(api_client, unique_user)
reference_id = recipe["recipeIngredient"][0]["referenceId"]
kinds = ["full", "partial", "remaining", "unknown", "prepared", "asNeeded", "referenceOnly"]
recipe["recipeInstructions"] = [
{
"text": kind,
"ingredientReferences": [
{"referenceId": reference_id, "quantityKind": kind, "quantity": 0 if kind == "partial" else None}
],
}
for kind in kinds
]
route = api_routes.recipes_slug(recipe["slug"])
response = api_client.put(route, json=recipe, headers=unique_user.token)
assert response.status_code == 200, response.text
saved = api_client.get(route, headers=unique_user.token).json()
refs = [step["ingredientReferences"][0] for step in saved["recipeInstructions"]]
assert [ref["quantityKind"] for ref in refs] == kinds
assert [ref["quantity"] for ref in refs] == [None, 0, 0, 0, 0, 0, 0]
assert saved["recipeIngredient"][0]["quantity"] == 100
assert all(ref["weighing"] is None for ref in refs)
@@ -0,0 +1,104 @@
"""Upgrade a populated, pre-feature database using the actual Alembic chain."""
from pathlib import Path
from types import SimpleNamespace
from uuid import uuid4
from alembic import command
from alembic.config import Config
from sqlalchemy import MetaData, create_engine, inspect, select, text
from sqlalchemy.engine import make_url
from mealie.core import config as app_config
from mealie.core.config import get_app_settings
def test_upgrade_existing_database_preserves_legacy_recipes(tmp_path, monkeypatch):
settings = get_app_settings()
admin_engine = create_engine(settings.DB_URL)
database = f"guided_migration_{uuid4().hex}"
if admin_engine.dialect.name == "postgresql":
with admin_engine.connect().execution_options(isolation_level="AUTOCOMMIT") as connection:
connection.execute(text(f'CREATE DATABASE "{database}"'))
url = make_url(settings.DB_URL).set(database=database)
else:
url = make_url(f"sqlite:///{tmp_path / 'legacy.db'}")
engine = create_engine(url)
monkeypatch.setattr(
app_config,
"get_app_settings",
lambda: SimpleNamespace(DB_URL=url.render_as_string(hide_password=False), DEFAULT_HOUSEHOLD="Test"),
)
config = Config(str(Path(__file__).parents[3] / "mealie/alembic/alembic.ini"))
try:
command.upgrade(config, "c981d7e62b11")
metadata = MetaData()
metadata.reflect(engine)
with engine.begin() as connection:
instruction_id, reference_id = str(uuid4()), str(uuid4())
connection.execute(
metadata.tables["recipe_instructions"].insert(),
{
"id": instruction_id,
"text": "Legacy instruction",
"duration_seconds": 90,
"cooking": {"appliance": "mixer", "speed": 2, "reverse": True},
},
)
connection.execute(
metadata.tables["recipe_ingredient_ref_link"].insert(),
{
"instruction_id": instruction_id,
"reference_id": reference_id,
"quantity": 12,
},
)
with engine.connect() as connection:
before = {
name: sorted([tuple(row) for row in connection.execute(select(table))], key=repr)
for name, table in metadata.tables.items()
if name != "alembic_version"
}
assert before["recipe_instructions"]
command.upgrade(config, "head")
with engine.connect() as connection:
for name, table in metadata.tables.items():
if name == "alembic_version":
continue
assert sorted([tuple(row) for row in connection.execute(select(table))], key=repr) == before[name], name
assert (
connection.scalar(
text("SELECT COUNT(*) FROM recipe_ingredient_ref_link WHERE quantity_kind IS NOT NULL")
)
== 0
)
columns = {column["name"]: column for column in inspect(engine).get_columns("recipe_ingredient_ref_link")}
for name in (
"allocation_id",
"quantity_kind",
"weighing",
"role",
"destination",
"quantity_minimum",
"quantity_maximum",
"approximate",
"container_count",
"source_text",
):
assert columns[name]["nullable"]
with engine.begin() as connection:
connection.execute(text("UPDATE recipe_instructions SET duration_seconds = 0.5"))
assert connection.scalar(text("SELECT MIN(duration_seconds) FROM recipe_instructions")) == 0.5
connection.execute(text("UPDATE recipe_instructions SET duration_seconds = 90"))
command.downgrade(config, "c981d7e62b11")
with engine.connect() as connection:
for name, table in metadata.tables.items():
if name != "alembic_version":
assert sorted([tuple(row) for row in connection.execute(select(table))], key=repr) == before[name]
command.upgrade(config, "head")
finally:
engine.dispose()
if admin_engine.dialect.name == "postgresql":
with admin_engine.connect().execution_options(isolation_level="AUTOCOMMIT") as connection:
connection.execute(text(f'DROP DATABASE "{database}"'))
admin_engine.dispose()