Skip to content

Commit

Permalink
Merge pull request #77 from software-architecture-fiap/bugfix/video
Browse files Browse the repository at this point in the history
Refactoração de código
  • Loading branch information
carolinebrasil authored Dec 14, 2024
2 parents 4059611 + 26c1171 commit e973f2b
Show file tree
Hide file tree
Showing 7 changed files with 33 additions and 3 deletions.
1 change: 1 addition & 0 deletions app/routers/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()):
"""
Expand Down
13 changes: 10 additions & 3 deletions app/routers/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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),
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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()
Expand All @@ -165,6 +171,7 @@ def update_category(

return category_response


@router.delete('/{category_id}', response_model=schemas.Category)
def delete_category(
category_id: str,
Expand Down Expand Up @@ -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
6 changes: 6 additions & 0 deletions app/routers/customer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand All @@ -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.
Expand All @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions app/routers/order.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
5 changes: 5 additions & 0 deletions app/routers/product.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

router = APIRouter()


@router.post('/', response_model=schemas.Product)
def create_product(
product: schemas.ProductCreate,
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -101,6 +104,7 @@ def read_product(
)
return product_response


@router.put('/{product_id}', response_model=schemas.Product)
def update_product(
product_id: int,
Expand Down Expand Up @@ -147,6 +151,7 @@ def update_product(
)
return product_response


@router.delete('/{product_id}', response_model=schemas.Product)
def delete_product(
product_id: int,
Expand Down
2 changes: 2 additions & 0 deletions app/tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions app/tests/test_route_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

client = TestClient(app)


def test_auth_success(mocker):
mock_user = SimpleNamespace(id=1, email='[email protected]', hashed_password='$2b$12$125as3fd45gdas5')

Expand All @@ -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)
Expand Down

0 comments on commit e973f2b

Please sign in to comment.