munch-ease-backend/tests/test_recipes_parse_from_url_v2.py

80 lines
2.7 KiB
Python

import unittest
from fastapi.testclient import TestClient
import main
from db import connect, create
from scripts.migration_to_households import run_migration
class TestRecipesParseFromUrlV2(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.conn = await connect(":memory:")
await create(self.conn)
await run_migration(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
async def fake_scrape(url: str):
assert url == "https://example.com/recipe"
return {"@type": "Recipe", "name": "Example"}
async def fake_scrape_none(url: str):
return None
# Success case
orig = scraping.scrape_recipe_ldata
scraping.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()
assert body.get("@type") == "Recipe"
assert body.get("name") == "Example"
finally:
scraping.scrape_recipe_ldata = orig
# Not found case
scraping.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 == 404, r2.text
pb = r2.json()
assert pb.get("status") == 404
finally:
scraping.scrape_recipe_ldata = orig