munch-ease-backend/tests/test_recipes_household_v2.py
2025-11-01 15:34:01 +11:00

84 lines
2.8 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 TestRecipesHouseholdV2(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 a user and create two households
r = self.client.post(
"/api/v1/auth/register",
json={"email": "r@test.com", "password": "pw", "displayName": "R"},
)
assert r.status_code == 200, r.text
self.token = r.json()["accessToken"]
self.headers = {"Authorization": f"Bearer {self.token}"}
r = self.client.post("/api/v1/households", headers=self.headers, json={"name": "H1"})
assert r.status_code == 200, r.text
self.h1 = r.json()["slug"]
r = self.client.post("/api/v1/households", headers=self.headers, json={"name": "H2"})
assert r.status_code == 200, r.text
self.h2 = r.json()["slug"]
async def asyncTearDown(self):
await self.conn.close()
main.app.dependency_overrides.clear()
def test_create_and_list_scoped_recipes(self):
# Create a recipe in H1
recipe = {
"id": -1,
"name": "Soup",
"link": "https://example.com/soup",
"serves": 2,
"imageUrls": [],
"ingredients": [
{
"id": 0,
"line": "1 Apple",
"name": "Apple",
"unit": "Items",
"quantity": 1,
"preparation": "",
"product": None,
}
],
}
r = self.client.post(
f"/api/v1/households/{self.h1}/recipes", headers=self.headers, json=recipe
)
assert r.status_code == 200, r.text
rid = r.json()["id"]
# List H1 should include
r = self.client.get(f"/api/v1/households/{self.h1}/recipes", headers=self.headers)
assert r.status_code == 200
items = r.json()["items"]
assert any(it["id"] == rid for it in items)
# List H2 should not include
r = self.client.get(f"/api/v1/households/{self.h2}/recipes", headers=self.headers)
assert r.status_code == 200
items2 = r.json()["items"]
assert not any(it["id"] == rid for it in items2)
# Get in H2 by id should 404
r = self.client.get(f"/api/v1/households/{self.h2}/recipes/{rid}", headers=self.headers)
assert r.status_code == 404