Updates dos testes unitarios com autenticacao
This commit is contained in:
parent
6ffc5c9ef6
commit
27a71ae761
@ -10,6 +10,6 @@ invoice_bp = Blueprint("invoices", __name__)
|
||||
@invoice_bp.route("/", methods=["GET"])
|
||||
@token_required # Protege a rota
|
||||
@swag_from(invoice_get_doc)
|
||||
def get_invoices():
|
||||
def get_invoices(self):
|
||||
invoices = Invoice.query.all() # select * from Invoice
|
||||
return jsonify([{"id": i.id, "amount": i.amount, "user_id": i.user_id} for i in invoices])
|
||||
|
||||
@ -11,16 +11,16 @@ user_bp = Blueprint("users", __name__)
|
||||
@user_bp.route("/", methods=["GET"])
|
||||
@swag_from(user_get_doc)
|
||||
@token_required # Protege a rota
|
||||
def get_users(user):
|
||||
def get_users(self):
|
||||
users = User.query.all() # select * from User
|
||||
return jsonify([{"id": u.id, "name": u.name, "email": u.email} for u in users])
|
||||
|
||||
@user_bp.route("/", methods=["POST"])
|
||||
@swag_from(user_post_doc)
|
||||
@token_required # Protege a rota
|
||||
def create_user():
|
||||
def create_user(self):
|
||||
data = request.get_json()
|
||||
|
||||
print(data)
|
||||
name = data.get("name")
|
||||
email = data.get("email")
|
||||
password = data.get("password")
|
||||
@ -46,6 +46,7 @@ def create_user():
|
||||
@swag_from(login_post_doc)
|
||||
def login_user():
|
||||
data = request.get_json()
|
||||
print(data)
|
||||
|
||||
email = data.get("email")
|
||||
password = data.get("password")
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
import pytest
|
||||
from app import create_app
|
||||
from app.database import db
|
||||
from app.models.user import User
|
||||
from werkzeug.security import generate_password_hash
|
||||
|
||||
@pytest.fixture
|
||||
def app():
|
||||
@ -13,7 +15,18 @@ def app():
|
||||
})
|
||||
|
||||
with app.app_context():
|
||||
db.create_all() # Criar tabelas no banco de testes
|
||||
db.create_all() # Cria as tabelas no banco de testes
|
||||
|
||||
# Cria o usuário admin fixo, garantindo que esteja disponível para o client
|
||||
if not User.query.filter_by(email="admin@email.com").first():
|
||||
admin_user = User(
|
||||
name="admin",
|
||||
email="admin@email.com",
|
||||
password=generate_password_hash("senha123", method="pbkdf2:sha256")
|
||||
)
|
||||
db.session.add(admin_user)
|
||||
db.session.commit()
|
||||
|
||||
yield app # Executa os testes
|
||||
db.session.remove()
|
||||
db.drop_all() # Limpa o banco após os testes
|
||||
|
||||
@ -7,15 +7,17 @@ from app.database import db
|
||||
# Configurar Faker para usar dados do Brasil
|
||||
faker = Faker("pt_BR")
|
||||
|
||||
|
||||
class UserFactory(factory.alchemy.SQLAlchemyModelFactory):
|
||||
class Meta:
|
||||
model = User
|
||||
sqlalchemy_session = db.session
|
||||
sqlalchemy_session_persistence = "commit"
|
||||
|
||||
id = factory.Sequence(lambda n: n + 1)
|
||||
id = factory.Sequence(lambda n: n + (2 if User.query.filter_by(id=1).first() is not None else 1))
|
||||
name = factory.LazyAttribute(lambda _: faker.name()) # Nome em pt_BR
|
||||
email = factory.LazyAttribute(lambda _: faker.email()) # Email realista em pt_BR
|
||||
password = factory.LazyAttribute(lambda _: faker.password()) # Email realista em pt_BR
|
||||
|
||||
class InvoiceFactory(factory.alchemy.SQLAlchemyModelFactory):
|
||||
class Meta:
|
||||
@ -25,4 +27,11 @@ class InvoiceFactory(factory.alchemy.SQLAlchemyModelFactory):
|
||||
|
||||
id = factory.Sequence(lambda n: n + 1)
|
||||
amount = factory.Faker("pydecimal", left_digits=4, right_digits=2, positive=True, locale="pt_BR")
|
||||
user = factory.SubFactory(UserFactory) # Relacionamento com um usuário
|
||||
|
||||
@factory.lazy_attribute
|
||||
def user_id(self):
|
||||
existing_user = User.query.first()
|
||||
if not existing_user:
|
||||
existing_user = UserFactory() # Cria um usuário se não existir
|
||||
return existing_user.id
|
||||
|
||||
|
||||
@ -1,11 +1,15 @@
|
||||
from tests.factories import InvoiceFactory
|
||||
from tests.utils import get_auth_token
|
||||
|
||||
def test_get_invoices(client, db_session):
|
||||
"""Testa a listagem de faturas"""
|
||||
token = get_auth_token(client)
|
||||
InvoiceFactory.create_batch(2) # Cria 2 faturas fictícias
|
||||
db_session.commit()
|
||||
|
||||
response = client.get("/invoices/")
|
||||
response = client.get("/invoices/", headers={"Authorization": f"Bearer {token}"})
|
||||
print(response)
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()
|
||||
assert len(data) == 2
|
||||
|
||||
|
||||
@ -1,18 +1,30 @@
|
||||
from tests.factories import UserFactory
|
||||
from tests.utils import get_auth_token
|
||||
|
||||
def test_create_user(client):
|
||||
"""Testa a criação de um usuário via API"""
|
||||
response = client.post("/users/", json={"name": "Teste", "email": "teste@email.com"})
|
||||
assert response.status_code == 201
|
||||
token = get_auth_token(client) # Obtém o token JWT do usuário admin
|
||||
response = client.post(
|
||||
"/users/",
|
||||
json={"name": "Teste", "email": "teste@email.com", "password": "senha123"},
|
||||
headers={"Authorization": f"Bearer {token}"} # Corrige o formato do token
|
||||
)
|
||||
|
||||
assert response.status_code == 201 # Verifica se o usuário foi criado com sucesso
|
||||
data = response.get_json()
|
||||
assert data["message"] == "Usuário criado com sucesso!"
|
||||
print("Usuário criado com dados: ", data)
|
||||
# assert data["name"] == "Teste"
|
||||
# assert data["email"] == "teste@email.com"
|
||||
|
||||
|
||||
def test_get_users(client, db_session):
|
||||
"""Testa a listagem de usuários"""
|
||||
token = get_auth_token(client)
|
||||
|
||||
UserFactory.create_batch(3) # Cria 3 usuários fictícios
|
||||
db_session.commit()
|
||||
|
||||
response = client.get("/users/")
|
||||
response = client.get("/users/", headers={"Authorization": f"Bearer {token}"})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()
|
||||
assert len(data) == 3
|
||||
assert len(data) == 4 # 3 criados + 1 admin
|
||||
|
||||
9
tests/utils.py
Normal file
9
tests/utils.py
Normal file
@ -0,0 +1,9 @@
|
||||
def get_auth_token(client):
|
||||
"""Retorna um token JWT para o usuário admin, assumindo que ele já existe."""
|
||||
response = client.post(
|
||||
"/users/login",
|
||||
json={"email": "admin@email.com", "password": "senha123"}
|
||||
)
|
||||
print("Login response:", response.status_code, response.get_data(as_text=True))
|
||||
assert response.status_code == 200 # Verifica se o login está funcionando
|
||||
return response.get_json()["token"]
|
||||
Loading…
Reference in New Issue
Block a user