68 lines
2.2 KiB
Python
68 lines
2.2 KiB
Python
import os
|
|
import sys
|
|
|
|
# BD en memoria para tests, antes de importar la app.
|
|
os.environ["DATABASE_URL"] = "sqlite://"
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
|
|
|
import off # noqa: E402
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
from main import app # noqa: E402
|
|
|
|
client = TestClient(app)
|
|
|
|
|
|
def test_health():
|
|
assert client.get("/health").json() == {"status": "ok"}
|
|
|
|
|
|
def test_add_and_search_food():
|
|
r = client.post("/foods", json={"name": "Mi salsa", "kcalPer100g": 120})
|
|
assert r.status_code == 200
|
|
assert r.json()["kcalPer100g"] == 120
|
|
res = client.get("/foods", params={"q": "salsa"}).json()
|
|
assert any(f["name"] == "Mi salsa" for f in res)
|
|
|
|
|
|
def test_search_imports_from_off(monkeypatch):
|
|
monkeypatch.setattr(
|
|
off, "search",
|
|
lambda q, limit=12: [{"name": "Cosa OFF", "kcal_100g": 90, "off_id": "111", "barcode": "111"}],
|
|
)
|
|
res = client.get("/foods", params={"q": "cosarara"}).json()
|
|
assert any(f["name"] == "Cosa OFF" for f in res)
|
|
|
|
|
|
def test_food_upsert_by_id_no_duplicates():
|
|
r1 = client.post("/foods", json={"id": "fixed-1", "name": "Salsa X", "kcalPer100g": 100})
|
|
assert r1.json()["id"] == "fixed-1"
|
|
client.post("/foods", json={"id": "fixed-1", "name": "Salsa X v2", "kcalPer100g": 110})
|
|
res = client.get("/foods", params={"q": "salsa x"}).json()
|
|
matches = [f for f in res if f["id"] == "fixed-1"]
|
|
assert len(matches) == 1
|
|
assert matches[0]["kcalPer100g"] == 110 # actualizado, no duplicado
|
|
|
|
|
|
def test_food_rejects_malformed_portion():
|
|
r = client.post("/foods", json={
|
|
"name": "Mala", "kcalPer100g": 50, "portions": [{"name": "taza"}] # falta grams
|
|
})
|
|
assert r.status_code == 422 # pydantic valida la forma
|
|
|
|
|
|
def test_get_missing_recipe_is_404():
|
|
assert client.get("/recipes/nope").status_code == 404
|
|
|
|
|
|
def test_publish_and_get_recipe():
|
|
r = client.post("/recipes", json={
|
|
"name": "Ensalada",
|
|
"servings": 2,
|
|
"items": [{"food": {"name": "Lechuga", "kcalPer100g": 15}, "grams": 100}],
|
|
})
|
|
assert r.status_code == 200
|
|
rid = r.json()["id"]
|
|
got = client.get(f"/recipes/{rid}").json()
|
|
assert got["name"] == "Ensalada"
|
|
assert got["servings"] == 2
|