Adding Tests for the User Registration Endpoint

Writing comprehensive tests is crucial for ensuring the reliability and correctness of your FastAPI application. In this section, we’ll focus on adding tests for the user registration endpoint we created in the previous section.

Testing Successful Registration

Python

def test_register_user_success(client, db_session):
    data = {"email": "[email protected]", "password": "password123"}
    response = client.post("/register", json=data)

    assert response.status_code == 200
    assert response.json().get("email") == data["email"]

    # Check if user is created in the database
    db_user = db_session.query(User).filter(User.email == data["email"]).first()
    assert db_user is not None
    assert db_user.email == data["email"]

Testing Duplicate Email Registration

Python

def test_register_user_duplicate_email(client, db_session, user):
    data = {"email": user.email, "password": "password456"}
    response = client.post("/register", json=data)

    assert response.status_code == 400
    assert "User already exists" in response.json()["detail"]

Testing Missing Required Fields

Python

def test_register_user_missing_email(client):
    data = {"password": "password123"}
    response = client.post("/register", json=data)

    assert response.status_code == 422
    assert "email" in response.json()["detail"]

def test_register_user_missing_password(client):
    data = {"email": "[email protected]"}
    response = client.post("/register", json=data)

    assert response.status_code == 422
    assert "password" in response.json()["detail"]

Testing Password Hashing

Python

def test_register_user_password_hashing(client, db_session):
    data = {"email": "[email protected]", "password": "password123"}
    response = client.post("/register", json=data)

    assert response.status_code == 200

    user = db_session.query(User).filter(User.email == data["email"]).first()
    assert user.password != data["password"]  # Password should be hashed

By writing comprehensive tests for your user registration endpoint, you can ensure its reliability, security, and performance.

Password Hashing with Passlib
Implementing User Registration and Tests

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?