From 70f4567bf5a97d7014064bae2b0454e04cd6f7e1 Mon Sep 17 00:00:00 2001 From: Raphael Odini Date: Fri, 29 Dec 2023 09:48:21 +0100 Subject: [PATCH] feat: add endpoint to retrieve product by code (#106) * Add endpoint /products/code/ * Update tests --- app/api.py | 17 ++++++++++++++++- tests/test_api.py | 13 +++++++++---- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/app/api.py b/app/api.py index 2414b70a..a27b2770 100644 --- a/app/api.py +++ b/app/api.py @@ -274,12 +274,27 @@ def get_user_proofs( return crud.get_user_proofs(db, user=current_user) +@app.get( + "/api/v1/products/code/{product_code}", + response_model=schemas.ProductBase, + tags=["Products"], +) +def get_product_by_code(product_code: str, db: Session = Depends(get_db)): + db_product = crud.get_product_by_code(db, code=product_code) + if not db_product: + raise HTTPException( + status_code=404, + detail=f"Product with code {product_code} not found", + ) + return db_product + + @app.get( "/api/v1/products/{product_id}", response_model=schemas.ProductBase, tags=["Products"], ) -def get_product(product_id: int, db: Session = Depends(get_db)): +def get_product_by_id(product_id: int, db: Session = Depends(get_db)): db_product = crud.get_product_by_id(db, id=product_id) if not db_product: raise HTTPException( diff --git a/tests/test_api.py b/tests/test_api.py index 09dfc678..c01d41c1 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -92,7 +92,6 @@ def test_create_price(user, db=override_get_db()): assert response.status_code == 201 assert response.json()["product_code"] == PRICE_1.product_code assert "id" not in response.json() - assert "owner" not in response.json() db_prices = crud.get_prices(next(db)) assert len(db_prices) == 1 # assert db_prices[0]["owner"] == user.user_id @@ -238,7 +237,7 @@ def test_get_prices(): response = client.get("/api/v1/prices") assert response.status_code == 200 assert len(response.json()["items"]) == 3 - for price_field in ["product_id", "location_id", "proof_id"]: + for price_field in ["owner", "product_id", "location_id", "proof_id"]: assert price_field in response.json()["items"][0] for price_relationship in ["product", "location"]: assert price_relationship in response.json()["items"][0] @@ -325,12 +324,18 @@ def test_get_proofs(user): def test_get_product(product): - # product exists + # by id: product exists response = client.get(f"/api/v1/products/{product.id}") assert response.status_code == 200 - # product does not exist + # by id: product does not exist response = client.get(f"/api/v1/products/{product.id+1}") assert response.status_code == 404 + # by code: product exists + response = client.get(f"/api/v1/products/code/{product.code}") + assert response.status_code == 200 + # by code: product does not exist + response = client.get(f"/api/v1/products/code/{product.code+'X'}") + assert response.status_code == 404 def test_get_location(location):