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()
@@ -7,7 +7,7 @@ from mealie.schema.openai.recipe import OpenAIInstructionEnrichment, OpenAIInstr
from mealie.schema.recipe.recipe import RecipeDraft
from mealie.schema.recipe.recipe_ingredient import RecipeIngredient
from mealie.schema.recipe.recipe_notes import RecipeNote
from mealie.schema.recipe.recipe_step import RecipeStep
from mealie.schema.recipe.recipe_step import IngredientReferences, RecipeStep, StepCooking
from mealie.services.recipe.import_workflow import (
RecipeImportWorkflow,
StepOutcome,
@@ -179,6 +179,26 @@ async def test_an_existing_heading_is_kept():
assert step.text == "Make the batter: whisk the flour and eggs."
@pytest.mark.asyncio
async def test_enrichment_does_not_replace_existing_cooking_metadata():
recipe = _recipe()
step = recipe.recipe_instructions[0]
step.ingredient_references = [
IngredientReferences(reference_id=recipe.recipe_ingredient[0].reference_id, quantity=0.5)
]
step.cooking = StepCooking(speed="spoon")
step.duration_seconds = 42
before = step.model_dump()
ctx = _ctx(
recipe,
_respond(
OpenAIInstructionEnrichment(step=1, ingredients=[2], duration="PT3M", summary="Changed", text="Changed")
),
)
await EnrichInstructionsStep().run(ctx)
assert step.model_dump() == before
@pytest.mark.asyncio
async def test_no_response_leaves_the_recipe_alone():
recipe = _recipe()
@@ -0,0 +1,52 @@
from importlib.util import module_from_spec, spec_from_file_location
from io import StringIO
from pathlib import Path
import pytest
from alembic.migration import MigrationContext
from alembic.operations import Operations
from sqlalchemy import create_engine, inspect, text
def load_migration():
path = (
Path(__file__).parents[2]
/ "mealie/alembic/versions/2026-12-01-00.00.00_e274a9d13c50_fractional_step_duration.py"
)
spec = spec_from_file_location("fractional_step_duration_migration", path)
module = module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_postgresql_upgrade_sql():
output = StringIO()
context = MigrationContext.configure(dialect_name="postgresql", opts={"as_sql": True, "output_buffer": output})
with Operations.context(context):
load_migration().upgrade()
assert "ALTER COLUMN DURATION_SECONDS TYPE FLOAT" in output.getvalue().upper()
def test_sqlite_migration_and_safe_downgrade():
engine = create_engine("sqlite://")
migration = load_migration()
with engine.begin() as connection:
connection.execute(text("CREATE TABLE recipe_instructions (id INTEGER PRIMARY KEY, duration_seconds INTEGER)"))
connection.execute(text("INSERT INTO recipe_instructions VALUES (1, 90), (2, NULL)"))
with Operations.context(MigrationContext.configure(connection)):
migration.upgrade()
assert str(inspect(connection).get_columns("recipe_instructions")[1]["type"]) == "FLOAT"
durations = connection.execute(text("SELECT duration_seconds FROM recipe_instructions ORDER BY id"))
assert durations.scalars().all() == [
90,
None,
]
connection.execute(text("UPDATE recipe_instructions SET duration_seconds = 0.5 WHERE id = 1"))
with pytest.raises(RuntimeError, match="fractional durations"):
migration.downgrade()
assert connection.scalar(text("SELECT duration_seconds FROM recipe_instructions WHERE id = 1")) == 0.5
connection.execute(text("UPDATE recipe_instructions SET duration_seconds = 90 WHERE id = 1"))
migration.downgrade()
assert str(inspect(connection).get_columns("recipe_instructions")[1]["type"]) == "INTEGER"
assert connection.scalar(text("SELECT duration_seconds FROM recipe_instructions WHERE id = 1")) == 90
engine.dispose()
@@ -5,7 +5,7 @@ from uuid import uuid4
import pytest
from pydantic import ValidationError
from sqlalchemy import Integer
from sqlalchemy import Float
from sqlalchemy.orm import Session
from mealie.db.models import _all_models # noqa: F401 - register ORM relationships without DB startup
@@ -27,7 +27,7 @@ def test_legacy_step_is_not_assigned_a_time():
assert step.text == "Bake for a while"
@pytest.mark.parametrize("seconds", [1, 90, 3661, 172801, 2147483647])
@pytest.mark.parametrize("seconds", [0.001, 0.5, 1, 1.234, 90, 3661, 172801, 2147483647])
def test_exact_duration_survives_model_and_recipe_json(seconds):
step = RecipeStep(text="Rest", durationSeconds=seconds)
# Exercise the existing create mapping, without connecting or writing to a DB.
@@ -44,7 +44,7 @@ def test_exact_duration_survives_model_and_recipe_json(seconds):
@pytest.mark.parametrize("number", ["1", "1.0", "1e0", "2147483647.0"])
def test_whole_numeric_json_spellings_are_equivalent(number):
step = RecipeStep.model_validate_json('{"text":"Rest","durationSeconds":' + number + "}")
assert type(step.duration_seconds) is int
assert type(step.duration_seconds) is float
assert step.duration_seconds == int(float(number))
@@ -54,8 +54,8 @@ def test_whole_numeric_json_spellings_are_equivalent(number):
True,
False,
-1,
1.5,
0.5,
0.0001,
1.2345,
2147483647.5,
float("inf"),
float("-inf"),
@@ -77,7 +77,7 @@ def test_duration_rejects_lossy_or_out_of_range_input(value):
def test_duration_column_is_nullable_without_a_zero_default():
column = RecipeInstruction.__table__.c.duration_seconds
assert isinstance(column.type, Integer)
assert isinstance(column.type, Float)
assert column.nullable
assert column.default is None
assert column.server_default is None
@@ -138,13 +138,13 @@ def test_existing_instruction_update_and_clear_without_database():
assert instruction.text == "Rest"
def test_api_schema_documents_optional_integer_seconds():
def test_api_schema_documents_optional_decimal_seconds():
schema = RecipeStep.model_json_schema(by_alias=True)
duration = schema["properties"]["durationSeconds"]
assert "durationSeconds" not in schema["required"]
assert duration["default"] is None
assert duration["anyOf"] == [
{"maximum": 2147483647, "minimum": 1, "type": "integer"},
{"maximum": 2147483647, "minimum": 0.001, "type": "number"},
{"type": "null"},
]
@@ -0,0 +1,47 @@
import pytest
from pydantic import ValidationError
from mealie.schema.recipe.recipe_step import IngredientReferences, RecipeStep, StepCooking
def test_legacy_step_and_explicit_zero():
step = RecipeStep(text="Mix", ingredient_references=[IngredientReferences(quantity=0)])
assert step.cooking is None
assert step.ingredient_references[0].quantity == 0
assert IngredientReferences().quantity is None
@pytest.mark.parametrize("speed", [1, 0.5, "spoon"])
def test_cooking_speeds(speed):
assert StepCooking(speed=speed).speed == speed
@pytest.mark.parametrize("quantity", [-1, float("inf"), float("nan")])
def test_invalid_quantity(quantity):
with pytest.raises(ValidationError):
IngredientReferences(quantity=quantity)
def test_nonfinite_speed_rejected():
with pytest.raises(ValidationError):
StepCooking(speed=float("inf"))
def test_unknown_cooking_settings_are_not_silently_discarded():
with pytest.raises(ValidationError):
StepCooking.model_validate({"speed": 2, "unknownSetting": True})
assert "reverse" in StepCooking.model_json_schema(by_alias=True)["properties"]
@pytest.mark.parametrize("reverse", [True, False, None])
def test_rotation_direction_round_trip(reverse):
step = RecipeStep.model_validate({"text": "Mix", "cooking": {"speed": "spoon", "reverse": reverse}})
saved = RecipeStep.model_validate_json(step.model_dump_json(by_alias=True))
assert saved.cooking.reverse is reverse
assert StepCooking().reverse is None
@pytest.mark.parametrize("reverse", ["false", "true", 0, 1, "inversa"])
def test_invalid_rotation_direction_rejected(reverse):
with pytest.raises(ValidationError):
StepCooking(reverse=reverse)
@@ -0,0 +1,50 @@
from importlib.util import module_from_spec, spec_from_file_location
from io import StringIO
from pathlib import Path
import pytest
from alembic.migration import MigrationContext
from alembic.operations import Operations
from sqlalchemy import create_engine, inspect, text
VERSIONS = Path(__file__).parents[2] / "mealie/alembic/versions"
MIGRATIONS = [
("2026-11-30-00.00.00_b742c6d50a10_add_step_ingredient_quantity.py", "recipe_ingredient_ref_link", "quantity"),
("2026-11-30-00.00.01_c981d7e62b11_add_step_cooking.py", "recipe_instructions", "cooking"),
]
def load_migration(filename):
spec = spec_from_file_location("step_metadata_migration", VERSIONS / filename)
module = module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.parametrize(("filename", "table", "column"), MIGRATIONS)
@pytest.mark.parametrize("dialect", ["sqlite", "postgresql"])
def test_additive_migration_sql(filename, table, column, dialect):
output = StringIO()
context = MigrationContext.configure(dialect_name=dialect, opts={"as_sql": True, "output_buffer": output})
with Operations.context(context):
load_migration(filename).upgrade()
sql = output.getvalue().upper()
assert f"ALTER TABLE {table.upper()} ADD COLUMN {column.upper()}" in sql
assert "NOT NULL" not in sql
assert "DEFAULT" not in sql
@pytest.mark.parametrize(("filename", "table", "column"), MIGRATIONS)
def test_sqlite_upgrade_and_downgrade_preserve_rows(filename, table, column):
engine = create_engine("sqlite://")
with engine.begin() as connection:
connection.execute(text(f"CREATE TABLE {table} (id INTEGER PRIMARY KEY, text VARCHAR)"))
connection.execute(text(f"INSERT INTO {table} (id, text) VALUES (1, 'existing')"))
migration = load_migration(filename)
with Operations.context(MigrationContext.configure(connection)):
migration.upgrade()
assert next(col for col in inspect(connection).get_columns(table) if col["name"] == column)["nullable"]
assert connection.execute(text(f"SELECT id, text, {column} FROM {table}")).one() == (1, "existing", None)
migration.downgrade()
assert connection.execute(text(f"SELECT id, text FROM {table}")).one() == (1, "existing")
engine.dispose()
+107
View File
@@ -0,0 +1,107 @@
from uuid import uuid4
import pytest
from pydantic import ValidationError
from mealie.schema.recipe.recipe import RecipeDraft
from mealie.schema.recipe.recipe_step import IngredientReferences, RecipeStep, StepCooking, StepParameter
@pytest.mark.parametrize("kind", ["remaining", "unknown", "prepared", "asNeeded", "referenceOnly"])
def test_non_numeric_allocations_never_expose_legacy_full_quantity(kind):
ref = IngredientReferences(quantity_kind=kind)
assert ref.quantity == 0
assert IngredientReferences.model_validate_json(ref.model_dump_json()).quantity_kind == kind
@pytest.mark.parametrize(
"payload",
[
{"quantityKind": "partial"},
{"quantityKind": "full", "quantity": 1},
{"quantityKind": "unknown", "quantity": 1},
{"quantityKind": "prepared", "weighing": "weigh"},
{"quantityMinimum": 10, "quantityMaximum": 2},
{"containerCount": 0},
],
)
def test_invalid_allocations_are_not_coerced(payload):
with pytest.raises(ValidationError):
IngredientReferences.model_validate(payload)
def test_optional_legacy_allocations_and_appliance_data():
step = RecipeStep(text="Hand mix", ingredient_references=[IngredientReferences()])
assert step.cooking is None
assert step.ingredient_references[0].quantity is None
assert step.ingredient_references[0].weighing is None
@pytest.mark.parametrize(
"payload",
[
{"durationRangeSeconds": {"minimum": 5, "maximum": 2}},
{"durationRangeSeconds": {"minimum": 0}},
{"durationRangeSeconds": {"minimum": 0.0001}},
{"speedRange": {"minimum": float("inf")}},
{"speedProgression": [1, float("nan")]},
{"repetitions": 1.5},
{"repetitions": True},
{"repetitionRange": {"minimum": 1.5}},
{"optional": "true"},
{"accessories": [{"name": "basket", "state": "guessed"}]},
],
)
def test_invalid_operation_settings_are_rejected(payload):
with pytest.raises(ValidationError):
StepCooking.model_validate(payload)
@pytest.mark.parametrize(
"payload",
[
{"kind": "number", "value": "2"},
{"kind": "number", "value": True},
{"kind": "boolean", "value": "false"},
{"kind": "text", "value": 2},
{"kind": "range", "value": 2},
{"kind": "range", "minimum": 5, "maximum": 2},
{"kind": "text", "minimum": 1},
],
)
def test_parameter_discriminator_is_validated(payload):
with pytest.raises(ValidationError):
StepParameter(name="setting", **payload)
def test_dependencies_are_declarative_and_cannot_form_cycles():
first, second = uuid4(), uuid4()
with pytest.raises(ValidationError, match="cycle"):
RecipeDraft(
recipe_instructions=[
RecipeStep(id=first, text="First", cooking=StepCooking(depends_on_step_ids=[second])),
RecipeStep(id=second, text="Second", cooking=StepCooking(depends_on_step_ids=[first])),
]
)
with pytest.raises(ValidationError, match="reference an instruction"):
RecipeDraft(recipe_instructions=[RecipeStep(text="Wait", cooking=StepCooking(depends_on_step_ids=[uuid4()]))])
def test_cooking_json_is_serializable_without_custom_database_encoders():
import json
from datetime import UTC, datetime
from mealie.schema.recipe.recipe_step import StepReview, StepReviewEvent
cooking = StepCooking(
depends_on_step_ids=[uuid4()],
reviews=[
StepReview(
category="operation",
history=[
StepReviewEvent(at=datetime.now(UTC), status="unresolved", content="Original content"),
],
),
],
)
assert StepCooking.model_validate(json.loads(json.dumps(cooking.model_dump()))) == cooking