Skip to content

Commit

Permalink
- add pytest in project
Browse files Browse the repository at this point in the history
  • Loading branch information
jprogram committed Jul 15, 2024
1 parent 2758066 commit 342ff09
Show file tree
Hide file tree
Showing 8 changed files with 98 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ on:
push:
branches:
- main
- develop
pull_request:
branches:
- main
Expand Down Expand Up @@ -34,6 +35,10 @@ jobs:
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run Tests
working-directory: ./backend
run: pytest --disable-warnings

build-frontend:
name: Build Frontend
runs-on: ubuntu-latest
Expand Down
2 changes: 1 addition & 1 deletion backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from config import Config
from utils.mongo import init_mongo
from flask_jwt_extended import JWTManager
from backend.log_config import setup_logging
from log_config import setup_logging

def create_app():
app = Flask(__name__)
Expand Down
5 changes: 3 additions & 2 deletions backend/controllers/auth_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from flask_jwt_extended import jwt_required, get_jwt_identity, create_access_token, create_refresh_token
from services.auth_service import create_user, authenticate_user, generate_qr_code, enable_2fa, is_2fa_enabled
from services.rabbitmq import send_message
from backend.log_config import setup_logging
from log_config import setup_logging
from utils.mongo import mongo

logger = setup_logging()
Expand All @@ -17,10 +17,11 @@ def register_user():
logger.debug(f"Registering user {username} with email: {email}")

sucess, secret = create_user(db, username, email, password)
logger.debug(f"teste {sucess} secret: {secret}")

if sucess:
# Envia mensagem para a fila RabbitMQ
send_message('user_registered', {'username': username, 'email': email})
#send_message('user_registered', {'username': username, 'email': email})

# Gera QR Code
qr_code = generate_qr_code(secret, email)
Expand Down
27 changes: 27 additions & 0 deletions backend/log_config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import logging
import os
from logging.handlers import RotatingFileHandler

def setup_logging():
# Configuração do logger
if not os.path.exists('./logs'):
os.makedirs('./logs')

# Configuração do logger
logger = logging.getLogger('jreport')
logger.setLevel(logging.DEBUG)
Expand All @@ -24,3 +29,25 @@ def setup_logging():
logger.addHandler(file_handler)

return logger

def setup_test_logging():
# Configuração do logger
if not os.path.exists('./logs'):
os.makedirs('./logs')

# Configuração do logger para testes
logger = logging.getLogger('test')
logger.setLevel(logging.DEBUG)

# Formato do log
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# Handler para o arquivo de log (com rotação)
file_handler = RotatingFileHandler('./logs/tests.log', maxBytes=10000000, backupCount=5)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)

# Adicionar handlers ao logger
logger.addHandler(file_handler)

return logger
3 changes: 2 additions & 1 deletion backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ Flask-JWT-Extended==4.6.0
pyotp==2.9.0
qrcode==7.4.2
pypng==0.20220715.0
pika==1.3.2
pika==1.3.2
pytest==8.2.2
2 changes: 1 addition & 1 deletion backend/services/auth_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from flask_jwt_extended import create_access_token, create_refresh_token
from flask import current_app
from io import BytesIO
from backend.log_config import setup_logging
from log_config import setup_logging

logger = setup_logging()

Expand Down
17 changes: 17 additions & 0 deletions backend/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import sys
import os
import pytest

# Adiciona o diretório 'backend' ao caminho de importação do Python
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from log_config import setup_test_logging

@pytest.fixture(autouse=True)
def log_tests(request):
# Configuração do logger
logger = setup_test_logging()

logger.info(f"Starting test: {request.node.name}")
yield
logger.info(f"Finished test: {request.node.name}")
42 changes: 42 additions & 0 deletions backend/tests/test_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import pytest
import logging
from app import create_app

# Usar o logger de teste configurado
logger = logging.getLogger('test')

@pytest.fixture
def app():
app = create_app()
app.config.update({
"TESTING": True,
})
return app

@pytest.fixture
def client(app):
return app.test_client()

def test_register_route(client):
logger.info("Testing register route")

response = client.post('/api/register', json={
'username': 'newuser',
'password': 'Newpassword33@',
'email': '[email protected]'
})

assert response.status_code == 200, f"Expected status code 200 but got {response.status_code}"
logger.info("Register route test passed")


def test_login_route(client):
logger.info("Testing login route")

response = client.post('/api/login', json={
'email': '[email protected]',
'password': 'Newpassword33@'
})

assert response.status_code == 200, f"Expected status code 200 but got {response.status_code}"
logger.info("Login route test passed")

0 comments on commit 342ff09

Please sign in to comment.