munch-ease-backend/tests/test_ingredients_parse_api_v2.py

87 lines
2.9 KiB
Python
Raw Normal View History

2025-11-01 12:05:16 +00:00
import unittest
from fastapi.testclient import TestClient
import main
from db import connect, create
2025-11-01 12:36:46 +00:00
from scripts.migration_to_households import run_migration
2025-11-01 12:05:16 +00:00
class TestIngredientsParseApiV2(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.conn = await connect(":memory:")
await create(self.conn)
2025-11-01 12:36:46 +00:00
await run_migration(self.conn)
2025-11-01 12:05:16 +00:00
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)
2025-11-01 12:36:46 +00:00
# Register user and create household
r = self.client.post(
"/api/v1/auth/register",
json={"email": "ing@test.com", "password": "pw", "displayName": "Ing"},
)
assert r.status_code == 200, r.text
token = r.json()["accessToken"]
self.headers = {"Authorization": f"Bearer {token}"}
r2 = self.client.post("/api/v1/households", headers=self.headers, json={"name": "H"})
assert r2.status_code == 200, r2.text
self.slug = r2.json()["slug"]
2025-11-01 12:05:16 +00:00
async def asyncTearDown(self):
await self.conn.close()
main.app.dependency_overrides.clear()
def test_parse_multiple_ingredients(self):
2025-11-01 12:36:46 +00:00
lines = [
"14oz milk powder",
"2 cups flour",
"1 tsp salt",
"egg", # defaults to 1 Items
]
parsed = []
for line in lines:
r = self.client.get(
f"/api/v1/households/{self.slug}/ingredients/parse",
params={"line": line},
headers=self.headers,
)
assert r.status_code == 200, r.text
parsed.append(r.json())
2025-11-01 12:05:16 +00:00
# Basic shape checks
2025-11-01 12:36:46 +00:00
for item in parsed:
2025-11-01 12:05:16 +00:00
assert "name" in item and isinstance(item["name"], str)
assert "line" in item and isinstance(item["line"], str)
assert "quantity" in item
assert "unit" in item and isinstance(item["unit"], str)
# Quantity should be a positive number
assert float(item["quantity"]) > 0
# The original sentence should round-trip into line
assert len(item["line"]) >= len(item["name"]) >= 1
# Spot checks for unit/quantity normalization
# 14oz milk powder
2025-11-01 12:36:46 +00:00
oz, cups, tsp, egg = parsed
2025-11-01 12:05:16 +00:00
assert float(oz["quantity"]) == 14.0
assert oz["unit"] == "Ounce"
assert "milk" in oz["name"].lower()
assert float(cups["quantity"]) == 2.0
assert cups["unit"] == "Cup"
assert cups["name"].lower() == "flour"
assert float(tsp["quantity"]) == 1.0
assert tsp["unit"] == "Teaspoon"
assert tsp["name"].lower() == "salt"
assert float(egg["quantity"]) == 1.0
assert egg["unit"] == "Items"
assert egg["name"].lower() == "egg"