Pytest: Testes Python
Pytest é uma das melhores ferramentas de teste para Python, oferecendo recursos avançados e sintaxe limpa.
Teste Básico
# test_calculator.py
def test_add():
assert add(2, 3) == 5
def test_multiply():
assert multiply(2, 3) == 6Fixtures
# conftest.py
import pytest
@pytest.fixture
def sample_user():
return User(name="John", email="john@example.com")
def test_user_creation(sample_user):
assert sample_user.name == "John"Parametrização
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(2, 3, 5),
(10, 20, 30),
])
def test_add(a, b, expected):
assert add(a, b) == expectedMocks
from unittest.mock import patch
@patch('requests.get')
def test_fetch_data(mock_get):
mock_get.return_value.json.return_value = {'data': 'test'}
result = fetch_data()
assert result == {'data': 'test'}
1 comment