DEV Community

Fiyinfoluwa Ojo
Fiyinfoluwa Ojo

Posted on

Unit & Integration Testing: Proving Your Code Works with Pytest

Why Write Tests?

Manual testing means opening Postman every time
you make a change. Automated tests run in seconds
and catch bugs before they reach production.

Unit Tests vs Integration Tests

Unit tests -> test individual functions/logic in isolation
Integration tests -> test full endpoints with real HTTP requests

My 3 Unit Tests

1. Reject negative price

def test_price_validation_rejects_negative():
    with pytest.raises(ValidationError):
        ItemDTO(name="Test", price=-10)
Enter fullscreen mode Exit fullscreen mode

2. Reject zero price

def test_price_validation_rejects_zero():
    with pytest.raises(ValidationError):
        ItemDTO(name="Test", price=0)
Enter fullscreen mode Exit fullscreen mode

3. Accept positive price

def test_price_validation_accepts_positive():
    item = ItemDTO(name="Test", price=99.99)
    assert item.price == 99.99
Enter fullscreen mode Exit fullscreen mode

My Integration Tests

Signup success

def test_signup_success():
    email = f"testuser{int(time.time())}@example.com"
    response = client.post("/auth/signup", json={
        "email": email,
        "password": "testpassword123"
    })
    assert response.status_code == 201
    assert response.json()["email"] == email

Enter fullscreen mode Exit fullscreen mode

Duplicate email returns 400

def test_signup_duplicate_email():
    # signup twice with same email
    assert response.status_code == 400
Enter fullscreen mode Exit fullscreen mode

Login returns token

def test_login_success():
    assert "access_token" in response.json()
Enter fullscreen mode Exit fullscreen mode

Protected route without token returns 401

def test_protected_without_token():
    response = client.get("/protected")
    assert response.status_code == 401
Enter fullscreen mode Exit fullscreen mode

The Results

passed test

8 passed, 0 failed. ✅

Lessons Learned

Tests are not extra work, they're insurance.
Every test you write is a bug you'll never
have to debug manually in production.

Day 21 done. 9 more to go.

GDGoCBowen30dayChallenge

Top comments (0)