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

@@ -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