Writing Comment Tests

In addition to testing post-related operations, it’s essential to write tests for comment-related functionalities. These tests help ensure that your social media API’s commenting system works as expected.

Testing Comment Creation

To test comment creation, we’ll make a POST request to the /posts/{post_id}/comments endpoint and assert that the comment is successfully created and associated with the correct post.

Example:

Python

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

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

Testing Comment Retrieval

To test comment retrieval, we’ll make a GET request to the /posts/{post_id}/comments endpoint and assert that the correct comments are returned for the specified post.

Example:

Python

def test_get_comments(client, db_session, post, comments):
    response = client.get(f"/posts/{post.id}/comments")
    assert response.status_code == 200
    assert len(response.json()) == len(comments)
    for comment in response.json():
        assert comment["post_id"] == post.id

Testing Comment Deletion

To test comment deletion, we’ll make a DELETE request to the /posts/{post_id}/comments/{comment_id} endpoint and assert that the comment is successfully deleted.

Example:

Python

def test_delete_comment(client, db_session, comment):
    response = client.delete(f"/posts/{comment.post_id}/comments/{comment.id}")
    assert response.status_code == 200

    comment = db_session.query(Comment).filter(Comment.id == comment.id).first()
    assert comment is None

Additional Considerations

  • Pagination: If your API supports pagination for comments, test how pagination works and ensure that the correct number of comments are returned.
  • Nested Comments: If your API allows nested comments, test how nested comments are created, retrieved, and deleted.
  • Error Handling: Test how your API handles errors like trying to create or delete a comment on a non-existent post.

By writing comprehensive tests for comment-related operations, you can ensure that your social media API’s commenting system functions correctly and provides a seamless user experience.

Organizing API Files with APIRouter
Adding Post Tests

Get industry recognized certification – Contact us

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