Introduction to pytest

Adding comments tests

Want more?

This lesson for enrolled students only. Join the course to unlock it!

You can see the code changes implemented in this lecture below.

If you have purchased the course in a different platform, you still have access to the code changes per lecture here on Teclado. The lecture video and lecture notes remain locked.
Join course for $30

Modified files

storeapi/tests/routers/test_posts.py
--- 
+++ 
@@ -15,16 +15,24 @@
     return await create_post("Test Post", async_client)


+@pytest.fixture()
+async def created_comment(async_client: AsyncClient, created_post: dict):
+    response = await async_client.post(
+        "/comment",
+        json={"body": "Test Comment", "post_id": created_post["id"]},
+    )
+    return response.json()
+
+
 @pytest.mark.anyio
 async def test_create_post(async_client: AsyncClient):
     body = "Test Post"
-
     response = await async_client.post(
         "/post",
         json={"body": body},
     )
     assert response.status_code == 201
-    assert {"id": 0, "body": body}.items() <= response.json().items()
+    assert {"id": 0, "body": "Test Post"}.items() <= response.json().items()


 @pytest.mark.anyio
@@ -41,3 +49,51 @@
     response = await async_client.get("/post")
     assert response.status_code == 200
     assert response.json() == [created_post]
+
+
+@pytest.mark.anyio
+async def test_create_comment(
+    async_client: AsyncClient,
+    created_post: dict,
+):
+    body = "Test Comment"
+
+    response = await async_client.post(
+        "/comment",
+        json={"body": body, "post_id": created_post["id"]},
+    )
+    assert response.status_code == 201
+    assert {
+        "id": 0,
+        "body": body,
+        "post_id": created_post["id"],
+    }.items() <= response.json().items()
+
+
+@pytest.mark.anyio
+async def test_get_comments_on_post(
+    async_client: AsyncClient, created_post: dict, created_comment: dict
+):
+    response = await async_client.get(f"/post/{created_post['id']}/comment")
+    assert response.status_code == 200
+    assert response.json() == [created_comment]
+
+
+@pytest.mark.anyio
+async def test_get_post_with_comments(
+    async_client: AsyncClient, created_post: dict, created_comment: dict
+):
+    response = await async_client.get(f"/post/{created_post['id']}")
+    assert response.status_code == 200
+    assert response.json() == {
+        "post": created_post,
+        "comments": [created_comment],
+    }
+
+
+@pytest.mark.anyio
+async def test_get_missing_post_with_comments(
+    async_client: AsyncClient, created_post: dict, created_comment: dict
+):
+    response = await async_client.get("/post/2")
+    assert response.status_code == 404