fix: fix missing images / keep recipes.image in sync with the images on disk (#8276)
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
0314e875b4
commit
30ba9a6540
13 files changed
+324
-24
No files matched your search
+107
@@ -0,0 +1,107 @@
|
||||
"""backfill recipe image column from disk
|
||||
|
||||
Revision ID: 4b91d3a7c0e2
|
||||
Revises: f2191b69db2e
|
||||
Create Date: 2026-09-03 16:12:44.183921
|
||||
|
||||
`recipes.image` is a cache key, but the frontend now reads its presence as the answer to
|
||||
"does this recipe have a picture?". That made rows which had drifted out of sync with the
|
||||
files on disk suddenly visible: a recipe with an image but no key renders the placeholder
|
||||
and never requests the file, and a recipe with a key but no image asks the media route for
|
||||
a 404 on every render. This reconciles the column with what is actually on disk, once.
|
||||
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import orm, text
|
||||
|
||||
from alembic import op
|
||||
from mealie.core.config import get_app_dirs
|
||||
from mealie.core.root_logger import get_logger
|
||||
from mealie.pkgs import cache
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "4b91d3a7c0e2"
|
||||
down_revision: str | None = "f2191b69db2e"
|
||||
branch_labels: str | tuple[str, ...] | None = None
|
||||
depends_on: str | tuple[str, ...] | None = None
|
||||
|
||||
NO_IMAGE = "no image"
|
||||
"""Legacy placeholder the scraper wrote when it had no image. Truthy, so it reads as "has one"."""
|
||||
|
||||
|
||||
def _directory_name(recipe_id: Any) -> str:
|
||||
"""The name `Recipe.directory_from_id` gave this recipe's folder.
|
||||
|
||||
Raw SQL bypasses the `GUID` type decorator, so the id arrives in whichever spelling the
|
||||
database stores: a `UUID` from Postgres, but the undashed CHAR(32) from SQLite. The
|
||||
directories are named with `str(uuid)`, the dashed form, so without this the SQLite
|
||||
spelling matches nothing on disk and the backfill silently restores nothing.
|
||||
"""
|
||||
try:
|
||||
return str(uuid.UUID(str(recipe_id)))
|
||||
except ValueError:
|
||||
return str(recipe_id)
|
||||
|
||||
|
||||
def _image_on_disk(recipe_data_dir: Path, recipe_id: Any) -> bool:
|
||||
# Mirrors Recipe.image_dir_from_id, which can't be used here because it creates the
|
||||
# directories it looks in. original.webp is the one file the minifier always writes.
|
||||
return recipe_data_dir.joinpath(_directory_name(recipe_id), "images", "original.webp").is_file()
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
logger = get_logger()
|
||||
recipe_data_dir = get_app_dirs().RECIPE_DATA_DIR
|
||||
|
||||
session = orm.Session(bind=op.get_bind())
|
||||
|
||||
rows = session.execute(text("SELECT id, image FROM recipes")).fetchall()
|
||||
on_disk = {str(row[0]): _image_on_disk(recipe_data_dir, row[0]) for row in rows}
|
||||
|
||||
# An unmounted or misconfigured data volume is indistinguishable from "no recipe has an
|
||||
# image", and clearing on that reading would drop every reference in the database. The
|
||||
# repairing half is safe either way, so only the clearing half is held back.
|
||||
claiming_image = [row for row in rows if row[1] and row[1] != NO_IMAGE]
|
||||
skip_clearing = bool(claiming_image) and not any(on_disk.values())
|
||||
if skip_clearing:
|
||||
logger.warning(
|
||||
"Skipping the clearing half of the recipe image backfill: %s recipes reference an image "
|
||||
"but no image files were found under %s. If the recipe data volume was not mounted, "
|
||||
"nothing was cleared.",
|
||||
len(claiming_image),
|
||||
recipe_data_dir,
|
||||
)
|
||||
|
||||
restored = cleared = 0
|
||||
for recipe_id, image in rows:
|
||||
has_image = on_disk[str(recipe_id)]
|
||||
|
||||
if has_image and (not image or image == NO_IMAGE):
|
||||
session.execute(
|
||||
text("UPDATE recipes SET image = :image WHERE id = :id"),
|
||||
{"image": cache.new_key(4), "id": recipe_id},
|
||||
)
|
||||
restored += 1
|
||||
|
||||
elif not has_image and image and not skip_clearing:
|
||||
session.execute(text("UPDATE recipes SET image = NULL WHERE id = :id"), {"id": recipe_id})
|
||||
cleared += 1
|
||||
|
||||
session.commit()
|
||||
logger.info(
|
||||
"Recipe image backfill checked %s recipes: %s image references restored, %s cleared",
|
||||
len(rows),
|
||||
restored,
|
||||
cleared,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# The old values were cache keys carrying no meaning beyond "set" or "unset", and every
|
||||
# row this touched was one that disagreed with the disk. There is nothing to restore.
|
||||
pass
|
||||
@@ -1,7 +1,6 @@
|
||||
import re as re
|
||||
from collections.abc import Iterable, Sequence
|
||||
from datetime import UTC, datetime
|
||||
from random import randint
|
||||
from typing import Self
|
||||
from uuid import UUID
|
||||
|
||||
@@ -17,6 +16,7 @@ from mealie.db.models.recipe.tag import Tag
|
||||
from mealie.db.models.recipe.tool import Tool
|
||||
from mealie.db.models.users.user_to_recipe import UserToRecipe
|
||||
from mealie.db.models.users.users import User
|
||||
from mealie.pkgs import cache
|
||||
from mealie.schema.cookbook.cookbook import ReadCookBook
|
||||
from mealie.schema.recipe import Recipe
|
||||
from mealie.schema.recipe.recipe import RecipePagination, RecipeSummary, create_recipe_slug
|
||||
@@ -147,9 +147,9 @@ class RepositoryRecipes(RecipeSuggestionMixin, HouseholdRepositoryGeneric[Recipe
|
||||
|
||||
return results
|
||||
|
||||
def update_image(self, slug: str, _: str | None = None) -> int:
|
||||
def update_image(self, slug: str, _: str | None = None) -> str:
|
||||
entry: RecipeModel = self._query_one(match_value=slug)
|
||||
entry.image = randint(0, 255)
|
||||
entry.image = cache.new_key()
|
||||
self.session.commit()
|
||||
|
||||
return entry.image
|
||||
|
||||
@@ -761,7 +761,7 @@ class RecipeController(BaseRecipeController):
|
||||
data_service = RecipeDataService(recipe.id)
|
||||
|
||||
try:
|
||||
await data_service.scrape_image(url.url)
|
||||
image_path = await data_service.scrape_image(url.url)
|
||||
except NotAnImageError as e:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
@@ -773,6 +773,14 @@ class RecipeController(BaseRecipeController):
|
||||
detail=ErrorResponse.respond("Url is not from an allowed domain"),
|
||||
) from e
|
||||
|
||||
# A failed download must not leave the recipe claiming an image, or every render
|
||||
# asks the media route for a file that isn't there.
|
||||
if image_path is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=ErrorResponse.respond("Image could not be downloaded"),
|
||||
)
|
||||
|
||||
recipe.image = cache.cache_key.new_key()
|
||||
self.service.update_one(recipe.slug, recipe)
|
||||
return UpdateImageResponse(image=recipe.image)
|
||||
|
||||
@@ -25,7 +25,7 @@ from mealie.services.scraper import cleaner
|
||||
from .._base_service import BaseService
|
||||
from .utils.database_helpers import DatabaseMigrationHelpers
|
||||
from .utils.migration_alias import MigrationAlias
|
||||
from .utils.migration_helpers import import_image
|
||||
from .utils.migration_helpers import import_image, scrape_image
|
||||
|
||||
|
||||
class BaseMigrator(BaseService):
|
||||
@@ -201,7 +201,12 @@ class BaseMigrator(BaseService):
|
||||
exception: str | Exception = ""
|
||||
status = False
|
||||
try:
|
||||
recipe = self.recipe_service.create_one(recipe)
|
||||
# Whatever the source called `image` is an archive path or a remote URL, never a
|
||||
# Mealie cache key - and the migrators still read it off `validated_recipes` to
|
||||
# locate the file, so it is dropped from the persisted copy only. The key is
|
||||
# recorded by `import_image`/`scrape_image` once a file actually lands, so a
|
||||
# recipe never claims an image the media route cannot serve.
|
||||
recipe = self.recipe_service.create_one(recipe.model_copy(update={"image": None}))
|
||||
status = True
|
||||
|
||||
except Exception as inst:
|
||||
@@ -272,8 +277,20 @@ class BaseMigrator(BaseService):
|
||||
recipe = cleaner.clean(recipe_dict, self.translator, url=recipe_dict.get("org_url", None))
|
||||
return recipe
|
||||
|
||||
def _record_image(self, slug: str) -> None:
|
||||
"""Stamps the recipe's image cache key, marking it as having a picture."""
|
||||
try:
|
||||
self.db.recipes.update_image(slug)
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to record image for {slug}: {e}")
|
||||
|
||||
def import_image(self, slug: str, src: str | Path, recipe_id: UUID4, extraction_root: Path | None = None):
|
||||
try:
|
||||
import_image(src, recipe_id, extraction_root=extraction_root)
|
||||
if import_image(src, recipe_id, extraction_root=extraction_root) is not None:
|
||||
self._record_image(slug)
|
||||
except UnidentifiedImageError as e:
|
||||
self.logger.error(f"Failed to import image for {slug}: {e}")
|
||||
|
||||
async def scrape_image(self, slug: str, image_url: str, recipe_id: UUID4) -> None:
|
||||
if await scrape_image(image_url, recipe_id) is not None:
|
||||
self._record_image(slug)
|
||||
@@ -10,7 +10,7 @@ from mealie.services.migrations.utils.migration_alias import MigrationAlias
|
||||
from mealie.services.scraper import cleaner
|
||||
|
||||
from ._migration_base import BaseMigrator
|
||||
from .utils.migration_helpers import scrape_image, split_by_line_break, split_by_semicolon
|
||||
from .utils.migration_helpers import split_by_line_break, split_by_semicolon
|
||||
|
||||
nutrition_map = {
|
||||
"carbohydrate": "carbohydrateContent",
|
||||
@@ -139,6 +139,6 @@ class MyRecipeBoxMigrator(BaseMigrator):
|
||||
continue
|
||||
|
||||
try:
|
||||
asyncio.run(scrape_image(recipe_image_url, recipe_id))
|
||||
asyncio.run(self.scrape_image(slug, recipe_image_url, recipe_id))
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to download image for {slug}: {e}")
|
||||
@@ -12,7 +12,7 @@ from mealie.services.scraper import cleaner
|
||||
|
||||
from ._migration_base import BaseMigrator
|
||||
from .utils.migration_alias import MigrationAlias
|
||||
from .utils.migration_helpers import scrape_image, split_by_comma
|
||||
from .utils.migration_helpers import split_by_comma
|
||||
|
||||
|
||||
def plantoeat_recipes(file: Path):
|
||||
@@ -171,6 +171,6 @@ class PlanToEatMigrator(BaseMigrator):
|
||||
continue
|
||||
|
||||
try:
|
||||
asyncio.run(scrape_image(recipe_image_urls[slug], recipe_id))
|
||||
asyncio.run(self.scrape_image(slug, recipe_image_urls[slug], recipe_id))
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to download image for {slug}: {e}")
|
||||
@@ -120,9 +120,11 @@ def safe_local_path(candidate: str | Path, root: Path) -> Path | None:
|
||||
return None
|
||||
|
||||
|
||||
def import_image(src: str | Path, recipe_id: UUID4, extraction_root: Path | None = None):
|
||||
def import_image(src: str | Path, recipe_id: UUID4, extraction_root: Path | None = None) -> Path | None:
|
||||
"""Import a local image file into the recipe image directory.
|
||||
|
||||
Returns the path the image was written to, or `None` if there was nothing to import.
|
||||
|
||||
May raise an UnidentifiedImageError if the file is not a recognised format.
|
||||
|
||||
If extraction_root is provided, the src path must be contained within it.
|
||||
@@ -138,30 +140,32 @@ def import_image(src: str | Path, recipe_id: UUID4, extraction_root: Path | None
|
||||
root_logger.get_logger().warning(
|
||||
"Rejected image path outside extraction root: %s (root: %s)", src, extraction_root
|
||||
)
|
||||
return
|
||||
return None
|
||||
|
||||
if not src.exists():
|
||||
return
|
||||
return None
|
||||
|
||||
data_service = RecipeDataService(recipe_id=recipe_id)
|
||||
data_service.write_image(src, src.suffix)
|
||||
return data_service.write_image(src, src.suffix)
|
||||
|
||||
|
||||
async def scrape_image(image_url: str, recipe_id: UUID4):
|
||||
async def scrape_image(image_url: str, recipe_id: UUID4) -> Path | None:
|
||||
"""Read the successful migrations attribute and for each scrape the image
|
||||
appropriately into the image directory. Minification is done in mass
|
||||
after the migration occurs.
|
||||
|
||||
Returns the path the image was written to, or `None` if nothing was downloaded.
|
||||
"""
|
||||
|
||||
if not isinstance(image_url, str):
|
||||
return
|
||||
return None
|
||||
|
||||
data_service = RecipeDataService(recipe_id=recipe_id)
|
||||
|
||||
try:
|
||||
await data_service.scrape_image(image_url)
|
||||
return await data_service.scrape_image(image_url)
|
||||
except UnidentifiedImageError:
|
||||
return
|
||||
return None
|
||||
|
||||
|
||||
def parse_iso8601_duration(time: str | None) -> str:
|
||||
|
||||
@@ -116,7 +116,13 @@ class RecipeDataService(BaseService):
|
||||
image_path = image_dir.joinpath(img_type.value)
|
||||
image_path.unlink(missing_ok=True)
|
||||
|
||||
async def scrape_image(self, image_url: str | dict[str, str] | list[str]) -> None:
|
||||
async def scrape_image(self, image_url: str | dict[str, str] | list[str]) -> Path | None:
|
||||
"""Downloads the image at `image_url` into the recipe's image directory.
|
||||
|
||||
Returns the path the image was written to, or `None` if nothing could be
|
||||
downloaded. Callers must not record a cache key for a recipe unless a path
|
||||
comes back, or the recipe claims an image the media route cannot serve.
|
||||
"""
|
||||
self.logger.info(f"Image URL: {image_url}")
|
||||
|
||||
image_url_str = ""
|
||||
@@ -164,5 +170,7 @@ class RecipeDataService(BaseService):
|
||||
raise NotAnImageError(f"Content-Type {content_type} is not an image")
|
||||
|
||||
self.logger.debug(f"File Name Suffix {file_path.suffix}")
|
||||
self.write_image(r.content, file_path.suffix)
|
||||
image_path = self.write_image(r.content, file_path.suffix)
|
||||
file_path.unlink(missing_ok=True)
|
||||
|
||||
return image_path
|
||||
@@ -450,6 +450,20 @@ class RecipeService(RecipeServiceBase):
|
||||
|
||||
return recipe
|
||||
|
||||
@staticmethod
|
||||
def _preserve_omitted_image(recipe: Recipe, update_data: Recipe) -> Recipe:
|
||||
"""Keeps the stored image when the payload doesn't mention it.
|
||||
|
||||
Updates are a full overwrite, so a client that round-trips a recipe without echoing
|
||||
`image` back would otherwise clear it. The image files stay on disk, leaving a recipe
|
||||
that has a picture but no longer says so - which reads to the frontend as "no image".
|
||||
The image is owned by the `/{slug}/image` endpoints; an update only carries it along.
|
||||
"""
|
||||
if "image" not in update_data.model_fields_set:
|
||||
update_data.image = recipe.image
|
||||
|
||||
return update_data
|
||||
|
||||
def _remove_non_existent_ingredient_references(self, update_data: Recipe) -> Recipe:
|
||||
"""Removes the references of ingredients from steps that no longer exist."""
|
||||
|
||||
@@ -493,6 +507,7 @@ class RecipeService(RecipeServiceBase):
|
||||
def update_one(self, slug_or_id: str | UUID, update_data: Recipe) -> Recipe:
|
||||
recipe = self._pre_update_check(slug_or_id, update_data)
|
||||
|
||||
update_data = self._preserve_omitted_image(recipe, update_data)
|
||||
update_data = self._remove_non_existent_ingredient_references(update_data)
|
||||
update_data = self._resolve_ingredient_sub_recipes(update_data)
|
||||
|
||||
|
||||
@@ -83,6 +83,8 @@ async def finalize_scraped_recipe(
|
||||
|
||||
recipe_data_service = RecipeDataService(recipe.id)
|
||||
|
||||
image_written = False
|
||||
|
||||
try:
|
||||
if isinstance(recipe.image, list):
|
||||
recipe.image = recipe.image[0] if recipe.image else None
|
||||
@@ -91,16 +93,20 @@ async def finalize_scraped_recipe(
|
||||
if recipe.image and recipe.image != NO_IMAGE:
|
||||
if on_progress:
|
||||
await on_progress(translator.t("recipe.create-progress.downloading-image"))
|
||||
await recipe_data_service.scrape_image(recipe.image) # type: ignore
|
||||
image_written = await recipe_data_service.scrape_image(recipe.image) is not None # type: ignore
|
||||
|
||||
if recipe.name is None:
|
||||
recipe.name = "Untitled"
|
||||
|
||||
recipe.slug = create_recipe_slug(recipe.name)
|
||||
recipe.image = cache.new_key(4)
|
||||
except Exception as e:
|
||||
recipe_data_service.logger.exception(f"Error Scraping Image: {e}")
|
||||
recipe.image = NO_IMAGE
|
||||
image_written = False
|
||||
|
||||
# `image` is the cache key the frontend uses to decide whether to request an image at
|
||||
# all, so it must stay empty unless a file actually landed on disk. Stamping a key for
|
||||
# a recipe with no image is what makes every render ask for a file that 404s.
|
||||
recipe.image = cache.new_key(4) if image_written else None
|
||||
|
||||
if recipe.name is None or recipe.name == "":
|
||||
recipe.name = f"No Recipe Name Found - {uuid4()!s}"
|
||||
|
||||
@@ -5,6 +5,7 @@ from slugify import slugify
|
||||
|
||||
from mealie.schema.recipe.recipe import Recipe
|
||||
from tests import data
|
||||
from tests.utils import api_routes
|
||||
from tests.utils.factories import random_string
|
||||
from tests.utils.fixture_schemas import TestUser
|
||||
|
||||
@@ -150,3 +151,62 @@ def test_recipe_image_upload(api_client: TestClient, unique_user: TestUser, reci
|
||||
response = api_client.get(f"/api/recipes/{recipe_ingredient_only.slug}", headers=unique_user.token)
|
||||
recipe_respons = response.json()
|
||||
assert recipe_respons["image"] == image_version
|
||||
|
||||
|
||||
def test_recipe_update_without_image_field_keeps_image(
|
||||
api_client: TestClient, unique_user: TestUser, recipe_ingredient_only: Recipe
|
||||
):
|
||||
"""An update that doesn't mention `image` must leave the stored value alone.
|
||||
|
||||
Updates are a full overwrite, so a client that round-trips a recipe without echoing the
|
||||
field back used to clear it. The image files stay on disk regardless, which left recipes
|
||||
that have a picture but no longer say so - and once the frontend started trusting the
|
||||
column, those pictures vanished from the UI (mealie-recipes/mealie#8271).
|
||||
"""
|
||||
slug = recipe_ingredient_only.slug
|
||||
|
||||
response = api_client.put(
|
||||
api_routes.recipes_slug_image(slug),
|
||||
data={"extension": "jpg"},
|
||||
files={"image": data.images_test_image_1.read_bytes()},
|
||||
headers=unique_user.token,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
image_version = response.json()["image"]
|
||||
assert image_version
|
||||
|
||||
recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json()
|
||||
del recipe["image"]
|
||||
|
||||
response = api_client.put(api_routes.recipes_slug(slug), json=recipe, headers=unique_user.token)
|
||||
assert response.status_code == 200
|
||||
|
||||
recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json()
|
||||
assert recipe["image"] == image_version
|
||||
|
||||
# The file was there the whole time; the column is what used to drift away from it.
|
||||
assert api_client.get(f"/api/media/recipes/{recipe['id']}/images/original.webp").status_code == 200
|
||||
|
||||
|
||||
def test_recipe_update_can_still_clear_image(
|
||||
api_client: TestClient, unique_user: TestUser, recipe_ingredient_only: Recipe
|
||||
):
|
||||
"""Preserving an omitted image must not make the field unwritable."""
|
||||
slug = recipe_ingredient_only.slug
|
||||
|
||||
response = api_client.put(
|
||||
api_routes.recipes_slug_image(slug),
|
||||
data={"extension": "jpg"},
|
||||
files={"image": data.images_test_image_1.read_bytes()},
|
||||
headers=unique_user.token,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json()
|
||||
recipe["image"] = None
|
||||
|
||||
response = api_client.put(api_routes.recipes_slug(slug), json=recipe, headers=unique_user.token)
|
||||
assert response.status_code == 200
|
||||
|
||||
recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json()
|
||||
assert recipe["image"] is None
|
||||
@@ -1,7 +1,10 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from mealie.lang.providers import get_locale_provider
|
||||
from mealie.schema.recipe.recipe import Recipe
|
||||
from mealie.services.recipe.recipe_data_service import RecipeDataService
|
||||
from mealie.services.scraper import scraper
|
||||
from mealie.services.scraper.recipe_scraper import RecipeScraper
|
||||
from mealie.services.scraper.scraped_extras import ScrapedExtras
|
||||
@@ -38,3 +41,37 @@ async def test_create_from_html_truncates_long_slug(monkeypatch):
|
||||
assert recipe.name == long_name
|
||||
# ...but the slug is truncated to a filesystem-safe length.
|
||||
assert 0 < len(recipe.slug) <= 250
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("scraped_image", "download_result", "expect_key"),
|
||||
[
|
||||
pytest.param("https://example.com/img.jpg", Path("/images/original.webp"), True, id="image-downloaded"),
|
||||
pytest.param("https://example.com/img.jpg", None, False, id="download-failed"),
|
||||
pytest.param("no image", None, False, id="placeholder-url"),
|
||||
pytest.param(None, None, False, id="no-image-url"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_finalize_only_stamps_a_cache_key_when_an_image_landed(
|
||||
monkeypatch, scraped_image, download_result, expect_key
|
||||
):
|
||||
"""`recipe.image` must stay empty unless a file actually reached the disk.
|
||||
|
||||
The frontend reads the presence of this cache key as "this recipe has a picture" and
|
||||
skips the request entirely when it is empty. Stamping a key regardless of whether the
|
||||
download succeeded is what left recipes asking the media route for a file that 404s on
|
||||
every single render (mealie-recipes/mealie#8271, GH #4804).
|
||||
"""
|
||||
|
||||
async def fake_scrape_image(self, image_url):
|
||||
return download_result
|
||||
|
||||
monkeypatch.setattr(RecipeDataService, "scrape_image", fake_scrape_image)
|
||||
|
||||
recipe = await scraper.finalize_scraped_recipe(
|
||||
Recipe(name="Test Recipe", image=scraped_image),
|
||||
get_locale_provider(),
|
||||
)
|
||||
|
||||
assert bool(recipe.image) is expect_key
|
||||
@@ -0,0 +1,38 @@
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from tests.utils.alembic_reader import ALEMBIC_MIGRATIONS, import_file
|
||||
|
||||
|
||||
def _migration():
|
||||
path = next(ALEMBIC_MIGRATIONS.glob("*4b91d3a7c0e2*.py"))
|
||||
return import_file("backfill_recipe_image_column", path)
|
||||
|
||||
|
||||
def test_image_on_disk_finds_every_id_spelling(tmp_path: Path) -> None:
|
||||
"""The backfill reads recipe ids with raw SQL, which bypasses the GUID type decorator.
|
||||
|
||||
Postgres hands back a UUID, SQLite the undashed CHAR(32) it stores, and the directories
|
||||
on disk are named with the dashed form either way. Every spelling has to find the file,
|
||||
or the backfill silently restores nothing on whichever database it gets wrong.
|
||||
"""
|
||||
migration = _migration()
|
||||
recipe_id = uuid.uuid4()
|
||||
|
||||
image = tmp_path.joinpath(str(recipe_id), "images", "original.webp")
|
||||
image.parent.mkdir(parents=True)
|
||||
image.touch()
|
||||
|
||||
assert migration._image_on_disk(tmp_path, recipe_id), "postgres returns a UUID"
|
||||
assert migration._image_on_disk(tmp_path, str(recipe_id)), "dashed string"
|
||||
assert migration._image_on_disk(tmp_path, recipe_id.hex), "sqlite returns CHAR(32)"
|
||||
|
||||
|
||||
def test_image_on_disk_is_false_without_a_file(tmp_path: Path) -> None:
|
||||
migration = _migration()
|
||||
recipe_id = uuid.uuid4()
|
||||
|
||||
tmp_path.joinpath(str(recipe_id), "images").mkdir(parents=True)
|
||||
|
||||
assert not migration._image_on_disk(tmp_path, recipe_id)
|
||||
assert not migration._image_on_disk(tmp_path, recipe_id.hex)
|
||||
Reference in new issue
Block a user