import unittest from fastapi.testclient import TestClient import main from db import connect, create from scripts.migration_to_households import run_migration class TestShoppingRequestIngredientDedupeV2(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 a household r = self.client.post( "/api/v1/auth/register", json={"email": "ing2@test.com", "password": "pw", "displayName": "Ing2"}, ) 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"] # Resolve household id async with self.conn.execute("SELECT id FROM Household WHERE slug = ?", (self.slug,)) as c: row = await c.fetchone() assert row is not None self.hid = int(row[0]) # Seed one ingredient in household await self.conn.execute( "INSERT INTO Ingredient (name, line, unit, quantity, recipe_id, meal_id, household_id) VALUES ('Eggs', '12 eggs', 'dozen', 1, NULL, NULL, ?)", (self.hid,), ) async with self.conn.execute("SELECT last_insert_rowid()") as c: row = await c.fetchone() assert row is not None self.eggs_id = int(row[0]) await self.conn.commit() async def asyncTearDown(self): await self.conn.close() main.app.dependency_overrides.clear() def test_request_same_ingredient_twice_deduped(self): # First request r1 = self.client.post( f"/api/v1/households/{self.slug}/shopping/current/ingredients", headers=self.headers, json={"ingredientId": self.eggs_id}, ) assert r1.status_code == 200, r1.text item1 = r1.json() # Second request for same ingredient should not create a duplicate; return same item r2 = self.client.post( f"/api/v1/households/{self.slug}/shopping/current/ingredients", headers=self.headers, json={"ingredientId": self.eggs_id}, ) assert r2.status_code == 200, r2.text item2 = r2.json() assert item1["id"] == item2["id"], "Should return existing request item" # Outstanding list should contain exactly one instance for the ingredient r = self.client.get( f"/api/v1/households/{self.slug}/shopping/current", headers=self.headers ) assert r.status_code == 200, r.text cur = r.json() outstanding = [i for i in cur["outstandingItems"] if i.get("ingredientId") == self.eggs_id] assert len(outstanding) == 1, outstanding