munch-ease-backend/tests/test_recipes_parse_from_url_v2.py

83 lines
2.8 KiB
Python
Raw Permalink Normal View History

import unittest
from fastapi.testclient import TestClient
import main
from db import connect, create
class TestRecipesParseFromUrlV2(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.conn = await connect(":memory:")
await create(self.conn)
async def override_get_db():
try:
yield self.conn
finally:
pass
main.app.dependency_overrides[main.get_db] = override_get_db
self.client = TestClient(main.app)
# Register user and create household
r = self.client.post(
"/api/v1/auth/register",
json={"email": "parse@test.com", "password": "pw", "displayName": "Parse"},
)
assert r.status_code == 200, r.text
token = r.json()["accessToken"]
self.headers = {"Authorization": f"Bearer {token}"}
r = self.client.post("/api/v1/households", headers=self.headers, json={"name": "H"})
assert r.status_code == 200, r.text
self.slug = r.json()["slug"]
async def asyncTearDown(self):
await self.conn.close()
main.app.dependency_overrides.clear()
def test_parse_from_url_success_and_not_found(self):
# Monkeypatch scraper to avoid network
import recipes.scraping as scraping
2025-11-04 07:31:13 +00:00
async def fake_scrape(url: str, log=None, dump_dir=None):
assert url == "https://example.com/recipe"
2025-11-01 12:36:46 +00:00
return {"@type": "Recipe", "name": "Example", "recipeIngredient": ["2 eggs"]}
2025-11-04 07:31:13 +00:00
async def fake_scrape_none(url: str, log=None, dump_dir=None):
return None
# Success case
2025-11-01 12:36:46 +00:00
import recipes as recipes_pkg
2025-11-02 06:51:10 +00:00
2025-11-01 12:36:46 +00:00
orig = recipes_pkg._scrape_recipe_ldata
recipes_pkg._scrape_recipe_ldata = fake_scrape
try:
r = self.client.post(
f"/api/v1/households/{self.slug}/recipes/parse-from-url",
headers=self.headers,
json={"url": "https://example.com/recipe"},
)
assert r.status_code == 200, r.text
body = r.json()
2025-11-01 12:36:46 +00:00
# Returns the same shape as create (RecipeCreate)
assert "id" not in body
assert body.get("name") == "Example"
2025-11-01 12:36:46 +00:00
assert "createdBy" not in body
finally:
2025-11-01 12:36:46 +00:00
recipes_pkg._scrape_recipe_ldata = orig
# Unprocessable (parse failure) case
2025-11-01 12:36:46 +00:00
recipes_pkg._scrape_recipe_ldata = fake_scrape_none
try:
r2 = self.client.post(
f"/api/v1/households/{self.slug}/recipes/parse-from-url",
headers=self.headers,
json={"url": "https://example.com/missing"},
)
assert r2.status_code == 422, r2.text
pb = r2.json()
assert pb.get("status") == 422
finally:
2025-11-01 12:36:46 +00:00
recipes_pkg._scrape_recipe_ldata = orig