Skip to content

Commit

Permalink
Completed unit test for post comment model
Browse files Browse the repository at this point in the history
  • Loading branch information
riadelimemmedov committed Mar 31, 2024
1 parent 0d0b9d6 commit 13a8378
Show file tree
Hide file tree
Showing 6 changed files with 197 additions and 5 deletions.
20 changes: 20 additions & 0 deletions backend/apps/posts/migrations/0007_alter_category_name.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 5.0.1 on 2024-03-28 07:53

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("posts", "0006_alter_post_categories"),
]

operations = [
migrations.AlterField(
model_name="category",
name="name",
field=models.CharField(
max_length=100, null=True, unique=True, verbose_name="Category name"
),
),
]
20 changes: 20 additions & 0 deletions backend/apps/posts/migrations/0008_alter_post_title.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 5.0.1 on 2024-03-28 18:01

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("posts", "0007_alter_category_name"),
]

operations = [
migrations.AlterField(
model_name="post",
name="title",
field=models.CharField(
max_length=250, null=True, unique=True, verbose_name="Post title"
),
),
]
1 change: 1 addition & 0 deletions backend/config/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
register(factories.TransactionFactory)
register(factories.CategoryFactory)
register(factories.PostFactory)
register(factories.CommentFactory)


# !api_client
Expand Down
10 changes: 10 additions & 0 deletions backend/config/tests/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,13 @@ def likes(self, create, extracted, **kwargs):
return
if extracted:
self.likes.add(extracted)


# !CommentFactory
class CommentFactory(factory.django.DjangoModelFactory):
class Meta:
model = Comment

post = factory.SubFactory(PostFactory)
author = factory.SubFactory(UserFactory)
body = factory.LazyAttribute(lambda _: "\n\n".join(faker.paragraphs(nb=5)))
68 changes: 68 additions & 0 deletions backend/config/tests/posts/comment/test_comment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import pytest
from django.contrib.auth import get_user_model

from apps.posts.models import Comment

# * If you don't declare pytestmark our test class model don't accsess to database table
pytestmark = pytest.mark.django_db

# User
User = get_user_model()


# !TestPostComment
class TestPostComment:
def test_comment_factory_creation(
self, comment_factory, post_factory, user_factory
):
"""
Test the creation of a Comment object using the CommentFactory.
Args:
comment_factory: A fixture that provides a CommentFactory instance.
post_factory: A fixture that provides a PostFactory instance.
user_factory: A fixture that provides a UserFactory instance.
Returns:
None
Raises:
AssertionError: If any of the assertions fail.
"""
obj = comment_factory(post=post_factory(), author=user_factory())
assert isinstance(obj, Comment)
assert obj.post is not None
assert obj.author is not None
assert obj.body is not None

def test_str_method(self, comment_factory):
"""
Test the __str__ method of the Comment model.
Args:
comment_factory: A fixture that provides a CommentFactory instance.
Returns:
None
Raises:
AssertionError: If the string representation does not match the expected format.
"""
obj = comment_factory()
assert obj.__str__() == f"{obj.body[:20]} by {obj.author.username}"

def test_comment_body(self, comment_factory):
"""
Test the body attribute of the Comment model.
Args:
comment_factory: A fixture that provides a CommentFactory instance.
Returns:
None
Raises:
AssertionError: If the body attribute does not contain at least one paragraph.
"""
body = comment_factory().body.split("\n\n")
assert len(body) >= 1
83 changes: 78 additions & 5 deletions backend/config/tests/posts/post/test_post_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,14 @@ def post_response(self, api_client, get_user, post_factory, category_factory):
if user.is_authenticated:
payload = {
"post_photo_url": SimpleUploadedFile("test.jpg", b"xxxxxxxx"),
"title": "Male",
"title": "Python",
"body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua",
"categories": [category_factory().id],
}
response = api_client().post(
self.endpoint, payload, format="multipart", headers=headers
)
yield payload, response, user
yield payload, response

def test_return_all_posts(self, post_factory, api_client):
"""
Expand All @@ -124,7 +124,7 @@ def test_return_all_posts(self, post_factory, api_client):
assert response.status_code == status.HTTP_200_OK
assert len(json.loads(response.content)) == 4

def test_return_single_post(self, post_response, api_client):
def test_return_single_post(self, post_response, get_user, api_client):
"""
Test the endpoint to return a single post.
Expand All @@ -133,7 +133,9 @@ def test_return_single_post(self, post_response, api_client):
api_client (APIClient): The API client used to make the request.
"""
payload, response, user = post_response
payload, response = post_response
user, headers = get_user
user = self.get_user_object(user.data["id"])
response = api_client().get(
f"{self.endpoint}{response.data['slug']}/", format="json"
)
Expand All @@ -149,7 +151,7 @@ def test_create_post(self, post_response, api_client):
api_client (APIClient): The API client used to make the request.
"""
payload, response, user = post_response
payload, response = post_response
assert response.status_code == status.HTTP_201_CREATED
assert (
response.data["id"]
Expand All @@ -161,3 +163,74 @@ def test_create_post(self, post_response, api_client):
and response.data["created"]
and response.data["modified"]
) is not None

def test_update_post_fields(self, post_response, get_user, api_client):
"""
Test updating post fields via the API.
Args:
post_response: A fixture that provides the initial post data and response.
get_user: A fixture that provides the authenticated user and headers.
api_client: A fixture that provides the API client.
Returns:
None
Raises:
AssertionError: If any of the assertions fail.
"""
payload, response = post_response
user, headers = get_user
title = "Kotlin"
body = "Why we need to use kotlin"
post_photo_url = SimpleUploadedFile("test.jpg", b"xxxxxxxx")
payload["title"] = title
payload["body"] = body
payload["post_photo_url"] = post_photo_url
response = api_client().put(
f"{self.endpoint}{response.data['slug']}/",
payload,
format="multipart",
headers=headers,
)
assert response.status_code == status.HTTP_200_OK
assert response.data["title"] == title
assert response.data["body"] == body
assert response.data["post_photo_url"] != post_photo_url.name

def test_update_post_field(self, post_response, get_user, api_client):
"""
Test the endpoint to update a post.
Args:
post_response (tuple): A tuple containing the payload, response, and user.
api_client (APIClient): The API client used to make the request.
"""
payload, response = post_response
user, headers = get_user
title = "Typescript"
response = api_client().patch(
f"{self.endpoint}{response.data['slug']}/",
{"title": title},
format="json",
headers=headers,
)
assert response.status_code == status.HTTP_200_OK
assert response.data["title"] == title

def test_delete_post(self, post_response, get_user, api_client):
"""
Test the endpoint to delete a post.
Args:
post_response (tuple): A tuple containing the payload, response, and user.
api_client (APIClient): The API client used to make the request.
"""
payload, response = post_response
user, headers = get_user
response = api_client().delete(
f"{self.endpoint}{response.data['slug']}/", headers=headers, format="json"
)
assert response.status_code == status.HTTP_204_NO_CONTENT

0 comments on commit 13a8378

Please sign in to comment.