Writing Post Creation Tests

In this section, we’ll focus on writing tests for the post creation endpoint in our social media API. We’ll cover scenarios like creating valid posts, handling invalid data, and testing database interactions.

Testing Valid Post Creation

To test valid post creation, we’ll make a POST request to the /posts endpoint with valid data and assert that the response status code is 201 (Created) and the created post is returned.

Example:

Python

def test_create_post(client, db_session):
    data = {"content": "This is a test post", "user_id": 1}
    response = client.post("/posts", json=data)
    assert response.status_code == 201

    post = db_session.query(Post).filter(Post.content == data["content"]).first()
    assert post is not None
    assert post.user_id == data["user_id"]

Testing Invalid Post Data

To test invalid post data, we’ll make a POST request with missing or invalid fields and assert that the response status code is 422 (Unprocessable Entity) and an appropriate error message is returned.

Example:

Python

def test_create_post_missing_content(client):
    data = {"user_id": 1}
    response = client.post("/posts", json=data)
    assert response.status_code == 422
    assert "content" in response.json()["detail"]

def test_create_post_invalid_user_id(client):
    data = {"content": "This is a test post", "user_id": "invalid"}
    response = client.post("/posts", json=data)
    assert response.status_code == 422
    assert "user_id" in response.json()["detail"]

Testing Database Interactions

To ensure that the post is correctly stored in the database, we’ll query the database for the created post and verify its properties.

Example:

Python

def test_create_post_database_interaction(client, db_session):
    data = {"content": "This is a test post", "user_id": 1}
    response = client.post("/posts", json=data)
    assert response.status_code == 201

    post = db_session.query(Post).filter(Post.id == response.json()["id"]).first()
    assert post is not None
    assert post.content == data["content"]
    assert post.user_id == data["user_id"]

By writing comprehensive tests for your post creation endpoint, you can ensure that it functions correctly and meets your requirements.

Adding Post Tests
Starting FastAPI Tests

Get industry recognized certification – Contact us

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