unittest
e pytest
unittest
pytest
testes_backend/
│
├── app/
│ ├── __init__.py
│ ├── calculadora.py # Funções de backend simples
│ ├── auth.py # Simulação de autenticação
│
├── tests/
│ ├── __init__.py
│ ├── test_calculadora_unittest.py # Testes com unittest
│ ├── test_auth_pytest.py # Testes com pytest
│
├── requirements.txt
├── README.md
mkdir testes_backend
cd testes_backend
python -m venv venv
source venv/bin/activate # Linux/Mac
.\venv\Scripts\activate # Windows
pytest
:pip install pytest
requirements.txt
:pytest
app/calculadora.py
def somar(a, b):
return a + b
def subtrair(a, b):
return a - b
def multiplicar(a, b):
return a * b
def dividir(a, b):
if b == 0:
raise ValueError("Divisão por zero não permitida.")
return a / b
app/auth.py
def login(username, password):
if username == "admin" and password == "1234":
return True
else:
return False
unittest
tests/test_calculadora_unittest.py
import unittest
from app import calculadora
class TestCalculadora(unittest.TestCase):
def test_somar(self):
self.assertEqual(calculadora.somar(2, 3), 5)
def test_subtrair(self):
self.assertEqual(calculadora.subtrair(10, 4), 6)
def test_multiplicar(self):
self.assertEqual(calculadora.multiplicar(3, 7), 21)
def test_dividir(self):
self.assertEqual(calculadora.dividir(10, 2), 5)
def test_dividir_por_zero(self):
with self.assertRaises(ValueError):
calculadora.dividir(10, 0)
if __name__ == '__main__':
unittest.main()
pytest
tests/test_auth_pytest.py
import pytest
from app import auth
def test_login_correto():
assert auth.login("admin", "1234") == True
def test_login_incorreto():
assert auth.login("admin", "wrong") == False
def test_login_usuario_inexistente():
assert auth.login("user", "1234") == False
python -m unittest discover tests
pytest tests/
pip install pytest-cov
pytest --cov=app tests/
---------- coverage: platform linux, python 3.11 ----------
Name Stmts Miss Cover
---------------------------------------
app/auth.py 6 0 100%
app/calculadora.py 9 0 100%
---------------------------------------
TOTAL 15 0 100%
# Projeto: Testes Backend com Python
Este projeto demonstra o uso de `unittest` e `pytest` para testes unitários de funções backend.
## Estrutura
- `app/` contém funções de negócio
- `tests/` contém testes automatizados
## Como executar
- Instalar dependências:
- Rodar testes com unittest:
- Rodar testes com pytest:
- Gerar relatório de cobertura:
testes_backend/
│
├── app/
│ ├── __init__.py
│ ├── calculadora.py
│ ├── auth.py
│ ├── api.py # NOVO: Código da API FastAPI
│
├── tests/
│ ├── __init__.py
│ ├── test_calculadora_unittest.py
│ ├── test_auth_pytest.py
│ ├── test_api_endpoints.py # NOVO: Testes dos endpoints
│
├── requirements.txt
├── README.md
requirements.txt
fastapi
e httpx
:pytest
fastapi
uvicorn
httpx
pytest-cov
pip install -r requirements.txt
from fastapi import FastAPI, HTTPException
from app import calculadora, auth
app = FastAPI()
@app.get("/")
def root():
return {"message": "API de Testes Backend"}
# Endpoints da Calculadora
@app.get("/soma")
def somar(a: float, b: float):
return {"resultado": calculadora.somar(a, b)}
@app.get("/subtrai")
def subtrair(a: float, b: float):
return {"resultado": calculadora.subtrair(a, b)}
@app.get("/multiplica")
def multiplicar(a: float, b: float):
return {"resultado": calculadora.multiplicar(a, b)}
@app.get("/divide")
def dividir(a: float, b: float):
try:
resultado = calculadora.dividir(a, b)
return {"resultado": resultado}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
# Endpoint de Login
@app.post("/login")
def login(username: str, password: str):
if auth.login(username, password):
return {"login": "sucesso"}
else:
raise HTTPException(status_code=401, detail="Credenciais inválidas")
uvicorn app.api:app --reload
from fastapi.testclient import TestClient
from app.api import app
client = TestClient(app)
def test_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "API de Testes Backend"}
def test_soma():
response = client.get("/soma?a=2&b=3")
assert response.status_code == 200
assert response.json() == {"resultado": 5}
def test_subtrair():
response = client.get("/subtrai?a=10&b=4")
assert response.status_code == 200
assert response.json() == {"resultado": 6}
def test_multiplicar():
response = client.get("/multiplica?a=5&b=2")
assert response.status_code == 200
assert response.json() == {"resultado": 10}
def test_dividir_sucesso():
response = client.get("/divide?a=8&b=2")
assert response.status_code == 200
assert response.json() == {"resultado": 4}
def test_dividir_por_zero():
response = client.get("/divide?a=8&b=0")
assert response.status_code == 400
assert response.json()["detail"] == "Divisão por zero não permitida."
def test_login_sucesso():
response = client.post("/login?username=admin&password=1234")
assert response.status_code == 200
assert response.json() == {"login": "sucesso"}
def test_login_falha():
response = client.post("/login?username=admin&password=wrong")
assert response.status_code == 401
assert response.json()["detail"] == "Credenciais inválidas"
pytest tests/test_api_endpoints.py
pytest tests/
pytest --cov=app tests/
api.py
(a API FastAPI).unittest
pytest
tests/
├── api/
│ └── test_auth.py
├── models/
│ └── test_user.py
└── utils/
└── test_helpers.py