From 26c1171dc1b5d684ff1074dc78d678ccff06af4b Mon Sep 17 00:00:00 2001 From: Carol Br Date: Mon, 9 Dec 2024 21:37:53 -0300 Subject: [PATCH] =?UTF-8?q?Refact:=20mensagens=20de=20erro=20e=20melhoria?= =?UTF-8?q?=20da=20legibilidade=20do=20c=C3=B3digo=20introduzindo=20consta?= =?UTF-8?q?ntes=20para=20categorias=20n=C3=A3o=20encontradas=20e=20remo?= =?UTF-8?q?=C3=A7=C3=A3o=20de=20linhas=20em=20branco?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/routers/auth.py | 1 + app/routers/category.py | 13 ++++++++++--- app/routers/customer.py | 6 ++++++ app/routers/order.py | 7 +++++++ app/routers/product.py | 5 +++++ app/tests/test_app.py | 2 ++ app/tests/test_route_auth.py | 2 ++ 7 files changed, 33 insertions(+), 3 deletions(-) diff --git a/app/routers/auth.py b/app/routers/auth.py index c4c83ef4..0e8102b9 100644 --- a/app/routers/auth.py +++ b/app/routers/auth.py @@ -10,6 +10,7 @@ router = APIRouter() + @router.post('/token', response_model=schemas.Token) def login_for_access_token(db: Session = Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()): """ diff --git a/app/routers/category.py b/app/routers/category.py index 1af37545..c11f4000 100644 --- a/app/routers/category.py +++ b/app/routers/category.py @@ -10,6 +10,9 @@ router = APIRouter() +CATEGORY_NOT_FOUND = 'Categoria não encontrada' + + @router.get('/', response_model=Dict[str, List[schemas.Category]]) def list_categories( skip: int = 0, @@ -32,6 +35,7 @@ def list_categories( categories = repository.get_categories(db, skip=skip, limit=limit) return {'categories': categories} + @router.get('/{category_id}', response_model=schemas.Category) def get_category( category_id: int, @@ -58,7 +62,7 @@ def get_category( if not db_category: logger.error(f'Categoria não encontrada para ID: {category_id}') - raise HTTPException(status_code=404, detail='Categoria não encontrada') + raise HTTPException(status_code=404, detail=CATEGORY_NOT_FOUND) category_response = schemas.Category( id=str(db_category.id), @@ -78,6 +82,7 @@ def get_category( logger.info(f'Retorno da categoria: {category_response}') return category_response + @router.post('/', response_model=schemas.Category) def create_category( category: schemas.CategoryCreate, @@ -118,6 +123,7 @@ def create_category( logger.error(f'Erro ao criar categoria: {e}') raise HTTPException(status_code=500, detail='Erro interno do servidor') + @router.put('/{category_id}', response_model=schemas.Category) def update_category( category_id: int, @@ -142,7 +148,7 @@ def update_category( """ db_category = repository.get_category(db, category_id=category_id) if db_category is None: - raise HTTPException(status_code=404, detail='Categoria não encontrada') + raise HTTPException(status_code=404, detail=CATEGORY_NOT_FOUND) db_category.name = category.name db.commit() @@ -165,6 +171,7 @@ def update_category( return category_response + @router.delete('/{category_id}', response_model=schemas.Category) def delete_category( category_id: str, @@ -192,7 +199,7 @@ def delete_category( db_category = repository.get_category(db, category_id=category_id_int) if db_category is None: - raise HTTPException(status_code=404, detail='Categoria não encontrada') + raise HTTPException(status_code=404, detail=CATEGORY_NOT_FOUND) repository.delete_category(db, db_category=db_category) return db_category diff --git a/app/routers/customer.py b/app/routers/customer.py index 5bccca9d..f26e4bd5 100644 --- a/app/routers/customer.py +++ b/app/routers/customer.py @@ -9,6 +9,7 @@ router = APIRouter() + @router.post('/admin', response_model=schemas.Customer) def create_customer(customer: schemas.CustomerCreate, db: Session = Depends(get_db)) -> schemas.Customer: """Cria um novo cliente com as informações fornecidas. @@ -32,6 +33,7 @@ def create_customer(customer: schemas.CustomerCreate, db: Session = Depends(get_ logger.info(f'Cliente criado com ID: {created_customer.id}') return created_customer + @router.get('/{customer_id}', response_model=schemas.Customer) def read_customer(customer_id: str, db: Session = Depends(get_db)) -> schemas.Customer: """Recupera um cliente pelo ID. @@ -59,6 +61,7 @@ def read_customer(customer_id: str, db: Session = Depends(get_db)) -> schemas.Cu raise HTTPException(status_code=404, detail='Cliente não encontrado') return db_customer + @router.get('/', response_model=List[schemas.Customer]) def read_customers(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)) -> List[schemas.Customer]: """Recupera uma lista de clientes com paginação. @@ -75,6 +78,7 @@ def read_customers(skip: int = 0, limit: int = 10, db: Session = Depends(get_db) customers = repository.get_customers(db, skip=skip, limit=limit) return customers + @router.post('/identify', response_model=schemas.Customer) def identify_customer(cpf: schemas.CPFIdentify, db: Session = Depends(get_db)) -> schemas.Customer: """Identifica um cliente pelo CPF. @@ -96,6 +100,7 @@ def identify_customer(cpf: schemas.CPFIdentify, db: Session = Depends(get_db)) - raise HTTPException(status_code=404, detail='Cliente não encontrado') return db_customer + @router.post('/register', response_model=schemas.Customer) def register_customer(customer: schemas.CustomerCreate, db: Session = Depends(get_db)) -> schemas.Customer: """Registra um novo cliente com as informações fornecidas. @@ -119,6 +124,7 @@ def register_customer(customer: schemas.CustomerCreate, db: Session = Depends(ge logger.info(f'Cliente registrado com ID: {created_customer.id}') return created_customer + @router.post('/anonymous', response_model=schemas.Customer) def create_anonymous_customer(db: Session = Depends(get_db)) -> schemas.Customer: """Cria um novo cliente anônimo. diff --git a/app/routers/order.py b/app/routers/order.py index 4be8db9e..a34152c6 100644 --- a/app/routers/order.py +++ b/app/routers/order.py @@ -14,6 +14,7 @@ INVALID_ORDER_ID_MSG = "Formato de ID do pedido inválido" REQUEST_NOT_FOUND_MSG = "Pedido não encontrado" + @router.post('/', response_model=schemas.OrderResponse) def create_order( order: schemas.OrderCreate, @@ -42,6 +43,7 @@ def create_order( logger.error(f'Erro ao criar o pedido: {e}', exc_info=True) raise HTTPException(status_code=500, detail=INTERNAL_SERVER_ERROR_MSG) + @router.put('/{order_id}/status', response_model=schemas.OrderResponse) def update_order_status( order_id: str, @@ -89,6 +91,7 @@ def update_order_status( logger.error(f'Erro ao atualizar o status do pedido: {e}', exc_info=True) raise HTTPException(status_code=500, detail=INTERNAL_SERVER_ERROR_MSG) + @router.get('/', response_model=Dict[str, List[schemas.OrderResponse]]) def read_orders( skip: int = 0, @@ -117,6 +120,7 @@ def read_orders( logger.error(f'Erro ao recuperar os pedidos: {e}', exc_info=True) raise HTTPException(status_code=500, detail=INTERNAL_SERVER_ERROR_MSG) + @router.get('/{order_id}', response_model=schemas.OrderCustomerView) def read_order( order_id: str, db: Session = Depends(get_db), current_user: schemas.Customer = Depends(security.get_current_user) @@ -152,6 +156,7 @@ def read_order( logger.error(f'Erro ao recuperar o pedido: {e}', exc_info=True) raise HTTPException(status_code=500, detail=INTERNAL_SERVER_ERROR_MSG) + @router.post('/checkout', response_model=schemas.OrderResponse) def fake_checkout( order: schemas.OrderCreate, @@ -180,6 +185,7 @@ def fake_checkout( logger.error(f'Erro durante o checkout fictício: {e}', exc_info=True) raise HTTPException(status_code=500, detail=INTERNAL_SERVER_ERROR_MSG) + @router.patch('/{order_id}/payment', response_model=schemas.OrderResponse) def update_order_payment_status( order_id: str, @@ -224,6 +230,7 @@ def update_order_payment_status( logger.error(f'Erro ao atualizar o status de pagamento do pedido: {e}', exc_info=True) raise HTTPException(status_code=500, detail='Erro Interno do Servidor') + @router.post('/webhook', response_model=schemas.WebhookResponse) def create_webhook( webhook: schemas.WebhookCreate, diff --git a/app/routers/product.py b/app/routers/product.py index ee932f96..3e9d23af 100644 --- a/app/routers/product.py +++ b/app/routers/product.py @@ -8,6 +8,7 @@ router = APIRouter() + @router.post('/', response_model=schemas.Product) def create_product( product: schemas.ProductCreate, @@ -47,6 +48,7 @@ def create_product( ) return product_response + @router.get('/', response_model=Dict[str, List[schemas.Product]]) def read_products( skip: int = 0, @@ -69,6 +71,7 @@ def read_products( categorized_products = repository.categorize_products(products) return categorized_products + @router.get('/{product_id}', response_model=schemas.Product) def read_product( product_id: int, @@ -101,6 +104,7 @@ def read_product( ) return product_response + @router.put('/{product_id}', response_model=schemas.Product) def update_product( product_id: int, @@ -147,6 +151,7 @@ def update_product( ) return product_response + @router.delete('/{product_id}', response_model=schemas.Product) def delete_product( product_id: int, diff --git a/app/tests/test_app.py b/app/tests/test_app.py index c7058f9c..1cf3f216 100644 --- a/app/tests/test_app.py +++ b/app/tests/test_app.py @@ -5,11 +5,13 @@ client = TestClient(app) + def test_read_root(): response = client.get('/') assert response.status_code == status.HTTP_200_OK assert response.json() == {'status': 'Operational'} + def test_redoc(): response = client.get('/redoc') assert response.status_code == status.HTTP_200_OK diff --git a/app/tests/test_route_auth.py b/app/tests/test_route_auth.py index cb4826df..be010bae 100644 --- a/app/tests/test_route_auth.py +++ b/app/tests/test_route_auth.py @@ -6,6 +6,7 @@ client = TestClient(app) + def test_auth_success(mocker): mock_user = SimpleNamespace(id=1, email='user@example.com', hashed_password='$2b$12$125as3fd45gdas5') @@ -21,6 +22,7 @@ def test_auth_success(mocker): print('Response JSON:', response.json()) assert response.json() == {'access_token': 'bearer mock_access_token', 'customer_id': mock_user.id} + def test_auth_invalid_credentials(mocker): mock_user = None mocker.patch('app.services.repository.get_user_by_email', return_value=mock_user)