In addition to testing post creation, it’s essential to write tests for other post-related operations, such as retrieving, updating, and deleting posts. These tests help ensure the correctness and reliability of your social media API.
Testing Post Retrieval
To test post retrieval, we’ll make a GET request to the /posts/{post_id}
endpoint and assert that the correct post is returned.
Example:
Python
def test_get_post(client, db_session, post):
response = client.get(f"/posts/{post.id}")
assert response.status_code == 200
assert response.json() == {
"id": post.id,
"content": post.content,
"user_id": post.user_id
}
In this example, we use a fixture named post
to create a test post before the test runs.
Testing Post Update
To test post updates, we’ll make a PUT request to the /posts/{post_id}
endpoint with updated data and assert that the post is successfully updated.
Example:
Python
def test_update_post(client, db_session, post):
new_content = "Updated content"
data = {"content": new_content}
response = client.put(f"/posts/{post.id}", json=data)
assert response.status_code == 200
post = db_session.query(Post).filter(Post.id == post.id).first()
assert post.content == new_content
Testing Post Deletion
To test post deletion, we’ll make a DELETE request to the /posts/{post_id}
endpoint and assert that the post is successfully deleted.
Example:
Python
def test_delete_post(client, db_session, post):
response = client.delete(f"/posts/{post.id}")
assert response.status_code == 200
post = db_session.query(Post).filter(Post.id == post.id).first()
assert post is None