Skip to content

Commit

Permalink
fix(topic): refactor and test init method of TopicForm
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentporte committed Aug 12, 2024
1 parent 134496b commit ac133dd
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
8 changes: 2 additions & 6 deletions lacommunaute/forum_conversation/forms.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import F
from django.forms import CharField, CheckboxSelectMultiple, HiddenInput, ModelMultipleChoiceField
from machina.apps.forum_conversation.forms import PostForm as AbstractPostForm, TopicForm as AbstractTopicForm
Expand Down Expand Up @@ -54,11 +53,8 @@ class TopicForm(CreateUpdatePostMixin, AbstractTopicForm):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
try:
if hasattr(self.instance, "topic"):
self.fields["tags"].initial = self.instance.topic.tags.all()
except ObjectDoesNotExist:
pass
if self.instance.pk:
self.fields["tags"].initial = self.instance.topic.tags.all()

def save(self):
post = super().save()
Expand Down
21 changes: 21 additions & 0 deletions lacommunaute/forum_conversation/tests/tests_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from lacommunaute.forum_conversation.forms import PostForm
from lacommunaute.forum_conversation.models import Topic
from lacommunaute.users.factories import UserFactory
from taggit.models import Tag


faker = Faker(settings.LANGUAGE_CODE)
Expand Down Expand Up @@ -204,6 +205,26 @@ def test_update_authenticated_topic_as_superuser(self, db, client, public_forum)
assert topic.first_post.updates_count == 1
assert topic.first_post.updated_by == superuser

def test_init_tags_when_creating_topic(self, db, client, public_forum):
response = client.get(get_create_topic_url(public_forum))
assert response.status_code == 200
assert response.context_data["post_form"].fields["tags"].initial is None

def test_init_tags_when_updating_topic(self, db, client, public_forum):
topic = TopicFactory(forum=public_forum, with_post=True)
client.force_login(topic.poster)
response = client.get(get_update_topic_url(topic))
assert response.status_code == 200
assert set(response.context_data["post_form"].fields["tags"].initial) == set(Tag.objects.none())

def test_init_tags_when_updating_tagged_topic(self, db, client, public_forum):
topic = TopicFactory(forum=public_forum, with_post=True, with_tags=[faker.word() for _ in range(2)])
client.force_login(topic.poster)

response = client.get(get_update_topic_url(topic))
assert response.status_code == 200
assert set(response.context_data["post_form"].fields["tags"].initial) == set(Tag.objects.all())


class TestPostForm:
def test_reply_as_anonymous(self, db, client, public_forum):
Expand Down

0 comments on commit ac133dd

Please sign in to comment.