id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
18,100
test_threads_lists_mark_as_read.py
rafalp_Misago/misago/threads/tests/test_threads_lists_mark_as_read.py
from django.urls import reverse from ...conf.test import override_dynamic_settings from ...readtracker.models import ReadCategory, ReadThread from ...test import assert_contains @override_dynamic_settings(index_view="categories") def test_site_threads_list_mark_as_read_redirects_guests(db, client): response = client.post(reverse("misago:threads"), {"mark_as_read": "true"}) assert response.status_code == 302 assert response["location"] == reverse("misago:threads") def test_category_threads_list_mark_as_read_redirects_guests(default_category, client): response = client.post( default_category.get_absolute_url(), {"mark_as_read": "true"} ) assert response.status_code == 302 assert response["location"] == default_category.get_absolute_url() @override_dynamic_settings(index_view="categories") def test_site_threads_list_mark_as_read_displays_confirmation_page_to_users( user_client, ): response = user_client.post(reverse("misago:threads"), {"mark_as_read": "true"}) assert_contains(response, "Mark as read | Threads") assert_contains( response, "Are you sure you want to mark all threads and categories as read?" ) def test_category_threads_list_mark_as_read_displays_confirmation_page_to_users( default_category, user_client ): response = user_client.post( default_category.get_absolute_url(), {"mark_as_read": "true"} ) assert_contains(response, f"Mark as read | {default_category}") assert_contains( response, "Are you sure you want to mark all threads in this category as read?" ) def test_private_threads_list_mark_as_read_displays_confirmation_page_to_users( user_client, ): response = user_client.post( reverse("misago:private-threads"), {"mark_as_read": "true"} ) assert_contains(response, f"Mark as read | Private threads") assert_contains( response, "Are you sure you want to mark all private threads as read?" ) @override_dynamic_settings(index_view="categories") def test_site_threads_list_mark_as_read_marks_all_categories_as_read( user_client, user, default_category, child_category, thread, other_thread ): ReadThread.objects.create( user=user, category=default_category, thread=thread, read_time=thread.last_post_on, ) ReadThread.objects.create( user=user, category=child_category, thread=other_thread, read_time=other_thread.last_post_on, ) response = user_client.post( reverse("misago:threads"), {"mark_as_read": "true", "confirm": "true"}, ) assert response.status_code == 302 assert response["location"] == reverse("misago:threads") ReadCategory.objects.get( user=user, category=default_category, ) ReadCategory.objects.get( user=user, category=child_category, ) assert not ReadThread.objects.exists() @override_dynamic_settings(index_view="categories") def test_site_threads_list_mark_as_read_marks_all_categories_as_read_in_htmx( user_client, user, default_category, child_category, thread, other_thread ): ReadThread.objects.create( user=user, category=default_category, thread=thread, read_time=thread.last_post_on, ) ReadThread.objects.create( user=user, category=child_category, thread=other_thread, read_time=other_thread.last_post_on, ) response = user_client.post( reverse("misago:threads"), {"mark_as_read": "true", "confirm": "true"}, headers={"hx-request": "true"}, ) assert_contains(response, thread.title) assert_contains(response, other_thread.title) ReadCategory.objects.get( user=user, category=default_category, ) ReadCategory.objects.get( user=user, category=child_category, ) assert not ReadThread.objects.exists() def test_category_threads_list_mark_as_read_marks_category_as_read( default_category, user_client, user, thread ): ReadThread.objects.create( user=user, category=default_category, thread=thread, read_time=thread.last_post_on, ) response = user_client.post( default_category.get_absolute_url(), {"mark_as_read": "true", "confirm": "true"}, ) assert response.status_code == 302 assert response["location"] == default_category.get_absolute_url() ReadCategory.objects.get( user=user, category=default_category, ) assert not ReadThread.objects.exists() def test_category_threads_list_mark_as_read_marks_category_as_read_in_htmx( default_category, user_client, user, thread ): ReadThread.objects.create( user=user, category=default_category, thread=thread, read_time=thread.last_post_on, ) response = user_client.post( default_category.get_absolute_url(), {"mark_as_read": "true", "confirm": "true"}, headers={"hx-request": "true"}, ) assert_contains(response, thread.title) ReadCategory.objects.get( user=user, category=default_category, ) assert not ReadThread.objects.exists() def test_category_threads_list_mark_as_read_marks_child_category_as_read( default_category, child_category, user_client, user, thread ): ReadThread.objects.create( user=user, category=child_category, thread=thread, read_time=thread.last_post_on, ) response = user_client.post( default_category.get_absolute_url(), {"mark_as_read": "true", "confirm": "true"}, ) assert response.status_code == 302 assert response["location"] == default_category.get_absolute_url() ReadCategory.objects.get( user=user, category=default_category, ) ReadCategory.objects.get( user=user, category=child_category, ) assert not ReadThread.objects.exists() def test_category_threads_list_mark_as_read_doesnt_mark_child_category_as_read_if_listing_is_disabled( default_category, child_category, user_client, user, thread, other_thread ): default_category.list_children_threads = False default_category.save() ReadThread.objects.create( user=user, category=default_category, thread=thread, read_time=thread.last_post_on, ) ReadThread.objects.create( user=user, category=child_category, thread=other_thread, read_time=other_thread.last_post_on, ) response = user_client.post( default_category.get_absolute_url(), {"mark_as_read": "true", "confirm": "true"} ) assert response.status_code == 302 assert response["location"] == default_category.get_absolute_url() ReadCategory.objects.get( user=user, category=default_category, ) assert not ReadCategory.objects.filter(user=user, category=child_category).exists() assert ReadThread.objects.filter(category=child_category).exists() def test_private_threads_list_mark_as_read_marks_private_threads_as_read( user_client, user, private_threads_category, user_private_thread ): ReadThread.objects.create( user=user, category=private_threads_category, thread=user_private_thread, read_time=user_private_thread.last_post_on, ) response = user_client.post( reverse("misago:private-threads"), {"mark_as_read": "true", "confirm": "true"} ) assert response.status_code == 302 assert response["location"] == reverse("misago:private-threads") ReadCategory.objects.get( user=user, category=private_threads_category, ) assert not ReadThread.objects.exists() def test_private_threads_list_mark_as_read_marks_private_threads_as_read_in_htmx( user_client, user, private_threads_category, user_private_thread ): ReadThread.objects.create( user=user, category=private_threads_category, thread=user_private_thread, read_time=user_private_thread.last_post_on, ) response = user_client.post( reverse("misago:private-threads"), {"mark_as_read": "true", "confirm": "true"}, headers={"hx-request": "true"}, ) assert_contains(response, user_private_thread.title) ReadCategory.objects.get( user=user, category=private_threads_category, ) assert not ReadThread.objects.exists() def test_private_threads_list_mark_as_read_clears_user_unread_private_threads_count( user_client, user ): user.unread_private_threads = 120 user.save() response = user_client.post( reverse("misago:private-threads"), {"mark_as_read": "true", "confirm": "true"} ) assert response.status_code == 302 assert response["location"] == reverse("misago:private-threads") user.refresh_from_db() assert user.unread_private_threads == 0
9,008
Python
.py
250
29.912
102
0.682487
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,101
test_threads_filters.py
rafalp_Misago/misago/threads/tests/test_threads_filters.py
from datetime import timedelta from unittest.mock import Mock from django.utils import timezone from ...readtracker.models import ReadCategory, ReadThread from ..filters import ( MyThreadsFilter, UnapprovedThreadsFilter, UnreadThreadsFilter, ) from ..models import Thread from ..test import post_thread def test_filter_as_choice_method_returns_active_filter_choice(anonymous_user): filter = MyThreadsFilter(Mock(user=anonymous_user)) choice = filter.as_choice("/base/url/", True) assert choice.name == filter.name assert choice.url == filter.url assert choice.absolute_url == f"/base/url/{filter.url}/" assert choice.active assert choice.filter is filter def test_filter_as_choice_method_returns_inactive_filter_choice(anonymous_user): filter = MyThreadsFilter(Mock(user=anonymous_user)) choice = filter.as_choice("/base/url/", False) assert choice.name == filter.name assert choice.url == filter.url assert choice.absolute_url == f"/base/url/{filter.url}/" assert not choice.active assert choice.filter is filter def test_unread_threads_filter_returns_never_read_thread( dynamic_settings, user, default_category ): queryset = Thread.objects.all() thread = post_thread(default_category) filter = UnreadThreadsFilter(Mock(settings=dynamic_settings, user=user)) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [thread] def test_unread_threads_filter_excludes_never_read_thread_older_than_user( dynamic_settings, user, default_category ): queryset = Thread.objects.all() post_thread( default_category, started_on=timezone.now() - timedelta(minutes=5), ) filter = UnreadThreadsFilter(Mock(settings=dynamic_settings, user=user)) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [] def test_unread_threads_filter_excludes_old_never_read_thread( dynamic_settings, user, default_category ): queryset = Thread.objects.all() post_thread( default_category, started_on=timezone.now().replace(year=2010), ) filter = UnreadThreadsFilter(Mock(settings=dynamic_settings, user=user)) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [] def test_unread_threads_filter_excludes_read_thread( dynamic_settings, user, default_category ): user.joined_on -= timedelta(minutes=60) user.save() queryset = Thread.objects.all() thread = post_thread( default_category, started_on=timezone.now() - timedelta(minutes=30), ) ReadThread.objects.create( user=user, category=default_category, thread=thread, read_time=timezone.now(), ) filter = UnreadThreadsFilter(Mock(settings=dynamic_settings, user=user)) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [] def test_unread_threads_filter_excludes_thread_in_read_category( dynamic_settings, user, default_category ): user.joined_on -= timedelta(minutes=60) user.save() queryset = Thread.objects.all() post_thread( default_category, started_on=timezone.now() - timedelta(minutes=30), ) ReadCategory.objects.create( user=user, category=default_category, read_time=timezone.now(), ) filter = UnreadThreadsFilter(Mock(settings=dynamic_settings, user=user)) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [] def test_unread_threads_filter_shows_read_thread_with_unread_replies( dynamic_settings, user, default_category ): user.joined_on -= timedelta(minutes=60) user.save() queryset = Thread.objects.all() thread = post_thread( default_category, started_on=timezone.now() - timedelta(minutes=10), ) ReadThread.objects.create( user=user, category=default_category, thread=thread, read_time=timezone.now() - timedelta(minutes=30), ) filter = UnreadThreadsFilter(Mock(settings=dynamic_settings, user=user)) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [thread] def test_unread_threads_filter_shows_unread_thread_in_read_category( dynamic_settings, user, default_category ): user.joined_on -= timedelta(minutes=60) user.save() queryset = Thread.objects.all() thread = post_thread( default_category, started_on=timezone.now(), ) ReadCategory.objects.create( user=user, category=default_category, read_time=timezone.now() - timedelta(minutes=30), ) filter = UnreadThreadsFilter(Mock(settings=dynamic_settings, user=user)) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [thread] def test_unread_threads_filter_shows_read_thread_in_read_category_with_unread_replies( dynamic_settings, user, default_category ): user.joined_on -= timedelta(minutes=60) user.save() queryset = Thread.objects.all() thread = post_thread( default_category, started_on=timezone.now() - timedelta(minutes=10), ) ReadCategory.objects.create( user=user, category=default_category, read_time=timezone.now() - timedelta(minutes=40), ) ReadThread.objects.create( user=user, category=default_category, thread=thread, read_time=timezone.now() - timedelta(minutes=20), ) filter = UnreadThreadsFilter(Mock(settings=dynamic_settings, user=user)) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [thread] def test_my_threads_filter_returns_user_started_thread(user, default_category): queryset = Thread.objects.all() thread = post_thread(default_category, poster=user) filter = MyThreadsFilter(Mock(user=user)) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [thread] def test_my_threads_filter_excludes_other_users_threads( user, other_user, default_category ): queryset = Thread.objects.all() post_thread(default_category, poster=other_user) filter = MyThreadsFilter(Mock(user=user)) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [] def test_my_threads_filter_excludes_anonymous_users_threads(user, default_category): queryset = Thread.objects.all() post_thread(default_category, poster="Anon") filter = MyThreadsFilter(Mock(user=user)) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [] def test_my_threads_filter_returns_empty_queryset_if_user_is_anonymous( anonymous_user, user, default_category ): queryset = Thread.objects.all() post_thread(default_category, poster=user) filter = MyThreadsFilter(Mock(user=anonymous_user)) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [] def test_unapproved_threads_filter_returns_unapproved_thread(default_category): queryset = Thread.objects.all() thread = post_thread(default_category, is_unapproved=True) filter = UnapprovedThreadsFilter(Mock()) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [thread] def test_unapproved_threads_filter_returns_thread_with_unapproved_posts( default_category, ): queryset = Thread.objects.all() thread = post_thread(default_category) thread.has_unapproved_posts = True thread.save() filter = UnapprovedThreadsFilter(Mock()) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == [thread] def test_unapproved_threads_filter_excludes_threads_without_unapproved_status( default_category, ): queryset = Thread.objects.all() thread = post_thread(default_category) thread.is_unapproved = False thread.has_unapproved_posts = False thread.save() filter = UnapprovedThreadsFilter(Mock()) choice = filter.as_choice("/base/url/", False) filtered_queryset = choice.filter(queryset) assert list(filtered_queryset) == []
8,906
Python
.py
225
34.257778
86
0.71593
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,102
test_attachments_middleware.py
rafalp_Misago/misago/threads/tests/test_attachments_middleware.py
from unittest.mock import Mock import pytest from rest_framework import serializers from .. import test from ...conf.test import override_dynamic_settings from ..api.postingendpoint import PostingEndpoint from ..api.postingendpoint.attachments import ( AttachmentsMiddleware, validate_attachments_count, ) from ..models import Attachment, AttachmentType @pytest.fixture def context(default_category, dynamic_settings, user, user_acl): thread = test.post_thread(category=default_category) post = thread.first_post post.update_fields = [] return { "category": default_category, "thread": thread, "post": post, "settings": dynamic_settings, "user": user, "user_acl": user_acl, } def create_attachment(*, post=None, user=None): return Attachment.objects.create( secret=Attachment.generate_new_secret(), filetype=AttachmentType.objects.order_by("id").last(), post=post, size=1000, uploader=user if user else None, uploader_name=user.username if user else "testuser", uploader_slug=user.slug if user else "testuser", filename="testfile_%s.zip" % (Attachment.objects.count() + 1), ) def test_middleware_is_used_if_user_has_permission_to_upload_attachments(context): context["user_acl"]["max_attachment_size"] = 1024 middleware = AttachmentsMiddleware(**context) assert middleware.use_this_middleware() def test_middleware_is_not_used_if_user_has_no_permission_to_upload_attachments( context, ): context["user_acl"]["max_attachment_size"] = 0 middleware = AttachmentsMiddleware(**context) assert not middleware.use_this_middleware() def test_middleware_handles_no_data(context): middleware = AttachmentsMiddleware( request=Mock(data={}), mode=PostingEndpoint.START, **context ) serializer = middleware.get_serializer() assert serializer.is_valid() def test_middleware_handles_empty_data(context): middleware = AttachmentsMiddleware( request=Mock(data={"attachments": []}), mode=PostingEndpoint.START, **context ) serializer = middleware.get_serializer() assert serializer.is_valid() def test_data_validation_fails_if_attachments_data_is_not_iterable(context): middleware = AttachmentsMiddleware( request=Mock(data={"attachments": "none"}), mode=PostingEndpoint.START, **context ) serializer = middleware.get_serializer() assert not serializer.is_valid() def test_data_validation_fails_if_attachments_data_has_non_int_values(context): middleware = AttachmentsMiddleware( request=Mock(data={"attachments": [1, "b"]}), mode=PostingEndpoint.START, **context ) serializer = middleware.get_serializer() assert not serializer.is_valid() @override_dynamic_settings(post_attachments_limit=2) def test_data_validation_fails_if_attachments_data_is_longer_than_allowed(context): middleware = AttachmentsMiddleware( request=Mock(data={"attachments": range(5)}), mode=PostingEndpoint.START, **context ) serializer = middleware.get_serializer() assert not serializer.is_valid() def test_middleware_adds_attachment_to_new_post(context): new_attachment = create_attachment(user=context["user"]) middleware = AttachmentsMiddleware( request=Mock(data={"attachments": [new_attachment.id]}), mode=PostingEndpoint.START, **context ) serializer = middleware.get_serializer() serializer.is_valid() middleware.save(serializer) new_attachment.refresh_from_db() assert new_attachment.post == context["post"] def test_middleware_adds_attachment_to_attachments_cache(context): new_attachment = create_attachment(user=context["user"]) middleware = AttachmentsMiddleware( request=Mock(data={"attachments": [new_attachment.id]}), mode=PostingEndpoint.START, **context ) serializer = middleware.get_serializer() serializer.is_valid() middleware.save(serializer) attachments_cache = context["post"].attachments_cache assert len(attachments_cache) == 1 assert attachments_cache[0]["id"] == new_attachment.id def test_middleware_adds_attachment_to_existing_post(context): new_attachment = create_attachment(user=context["user"]) middleware = AttachmentsMiddleware( request=Mock(data={"attachments": [new_attachment.id]}), mode=PostingEndpoint.EDIT, **context ) serializer = middleware.get_serializer() serializer.is_valid() middleware.save(serializer) new_attachment.refresh_from_db() assert new_attachment.post == context["post"] def test_middleware_adds_attachment_to_post_with_existing_attachment(context): old_attachment = create_attachment(post=context["post"]) new_attachment = create_attachment(user=context["user"]) middleware = AttachmentsMiddleware( request=Mock(data={"attachments": [old_attachment.id, new_attachment.id]}), mode=PostingEndpoint.EDIT, **context ) serializer = middleware.get_serializer() serializer.is_valid() middleware.save(serializer) new_attachment.refresh_from_db() assert new_attachment.post == context["post"] old_attachment.refresh_from_db() assert old_attachment.post == context["post"] def test_middleware_adds_attachment_to_existing_attachments_cache(context): old_attachment = create_attachment(post=context["post"]) new_attachment = create_attachment(user=context["user"]) middleware = AttachmentsMiddleware( request=Mock(data={"attachments": [old_attachment.id, new_attachment.id]}), mode=PostingEndpoint.EDIT, **context ) serializer = middleware.get_serializer() serializer.is_valid() middleware.save(serializer) attachments_cache = context["post"].attachments_cache assert len(attachments_cache) == 2 assert attachments_cache[0]["id"] == new_attachment.id assert attachments_cache[1]["id"] == old_attachment.id def test_other_user_attachment_cant_be_added_to_post(context): attachment = create_attachment() middleware = AttachmentsMiddleware( request=Mock(data={"attachments": [attachment.id]}), mode=PostingEndpoint.EDIT, **context ) serializer = middleware.get_serializer() serializer.is_valid() middleware.save(serializer) attachment.refresh_from_db() assert not attachment.post def test_other_post_attachment_cant_be_added_to_new_post(context, default_category): post = test.post_thread(category=default_category).first_post attachment = create_attachment(post=post, user=context["user"]) middleware = AttachmentsMiddleware( request=Mock(data={"attachments": [attachment.id]}), mode=PostingEndpoint.EDIT, **context ) serializer = middleware.get_serializer() serializer.is_valid() middleware.save(serializer) attachment.refresh_from_db() assert attachment.post == post def test_middleware_removes_attachment_from_post(context): attachment = create_attachment(post=context["post"], user=context["user"]) middleware = AttachmentsMiddleware( request=Mock(data={"attachments": []}), mode=PostingEndpoint.EDIT, **context ) serializer = middleware.get_serializer() serializer.is_valid() middleware.save(serializer) context["post"].refresh_from_db() assert not context["post"].attachment_set.exists() def test_middleware_removes_attachment_from_attachments_cache(context): attachment = create_attachment(post=context["post"], user=context["user"]) middleware = AttachmentsMiddleware( request=Mock(data={"attachments": []}), mode=PostingEndpoint.EDIT, **context ) serializer = middleware.get_serializer() serializer.is_valid() middleware.save(serializer) assert not context["post"].attachments_cache def test_middleware_deletes_attachment_removed_from_post(context): attachment = create_attachment(post=context["post"], user=context["user"]) middleware = AttachmentsMiddleware( request=Mock(data={"attachments": []}), mode=PostingEndpoint.EDIT, **context ) serializer = middleware.get_serializer() serializer.is_valid() middleware.save(serializer) with pytest.raises(Attachment.DoesNotExist): attachment.refresh_from_db() def test_middleware_blocks_user_from_removing_other_user_attachment_without_permission( context, ): attachment = create_attachment(post=context["post"]) middleware = AttachmentsMiddleware( request=Mock(data={"attachments": []}), mode=PostingEndpoint.EDIT, **context ) serializer = middleware.get_serializer() assert not serializer.is_valid() middleware.save(serializer) attachment.refresh_from_db() assert attachment.post == context["post"] def test_middleware_allows_user_with_permission_to_remove_other_user_attachment( context, ): context["user_acl"]["can_delete_other_users_attachments"] = True attachment = create_attachment(post=context["post"]) middleware = AttachmentsMiddleware( request=Mock(data={"attachments": []}), mode=PostingEndpoint.EDIT, **context ) serializer = middleware.get_serializer() serializer.is_valid() middleware.save(serializer) context["post"].refresh_from_db() assert not context["post"].attachment_set.exists() def test_attachments_count_validator_allows_attachments_within_limit(): settings = Mock(post_attachments_limit=5) validate_attachments_count(range(5), settings) def test_attachments_count_validator_raises_validation_error_on_too_many_attachmes(): settings = Mock(post_attachments_limit=2) with pytest.raises(serializers.ValidationError): validate_attachments_count(range(5), settings)
9,916
Python
.py
235
36.638298
87
0.722592
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,103
test_thread_postmove_api.py
rafalp_Misago/misago/threads/tests/test_thread_postmove_api.py
import json from django.urls import reverse from .. import test from ...categories.models import Category from ...conf.test import override_dynamic_settings from ...users.test import AuthenticatedUserTestCase from ..models import Thread from ..test import patch_category_acl, patch_other_category_acl class ThreadPostMoveApiTestCase(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.get(slug="first-category") self.thread = test.post_thread(category=self.category) self.api_link = reverse( "misago:api:thread-post-move", kwargs={"thread_pk": self.thread.pk} ) Category(name="Other category", slug="other-category").insert_at( self.category, position="last-child", save=True ) self.other_category = Category.objects.get(slug="other-category") def test_anonymous_user(self): """you need to authenticate to move posts""" self.logout_user() response = self.client.post( self.api_link, json.dumps({}), content_type="application/json" ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This action is not available to guests."} ) @patch_category_acl({"can_move_posts": True}) def test_invalid_data(self): """api handles post that is invalid type""" response = self.client.post( self.api_link, "[]", content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Invalid data. Expected a dictionary, but got list."}, ) response = self.client.post( self.api_link, "123", content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Invalid data. Expected a dictionary, but got int."}, ) response = self.client.post( self.api_link, '"string"', content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Invalid data. Expected a dictionary, but got str."}, ) response = self.client.post( self.api_link, "malformed", content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)"}, ) @patch_category_acl({"can_move_posts": False}) def test_no_permission(self): """api validates permission to move""" response = self.client.post( self.api_link, json.dumps({}), content_type="application/json" ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't move posts from this thread."} ) @patch_category_acl({"can_move_posts": True}) def test_move_no_new_thread_url(self): """api validates if new thread url was given""" response = self.client.post(self.api_link) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"detail": "Enter link to new thread."}) @patch_category_acl({"can_move_posts": True}) def test_invalid_new_thread_url(self): """api validates new thread url""" response = self.client.post( self.api_link, {"new_thread": self.user.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "This is not a valid thread link."} ) @patch_category_acl({"can_move_posts": True}) def test_current_new_thread_url(self): """api validates if new thread url points to current thread""" response = self.client.post( self.api_link, {"new_thread": self.thread.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Thread to move posts to is same as current one."}, ) @patch_other_category_acl({"can_see": False}) @patch_category_acl({"can_move_posts": True}) def test_other_thread_exists(self): """api validates if other thread exists""" other_thread = test.post_thread(self.other_category) response = self.client.post( self.api_link, {"new_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "detail": ( "The thread you have entered link to doesn't exist " "or you don't have permission to see it." ) }, ) @patch_other_category_acl({"can_browse": False}) @patch_category_acl({"can_move_posts": True}) def test_other_thread_is_invisible(self): """api validates if other thread is visible""" other_thread = test.post_thread(self.other_category) response = self.client.post( self.api_link, {"new_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "detail": ( "The thread you have entered link to doesn't exist " "or you don't have permission to see it." ) }, ) @patch_other_category_acl({"can_reply_threads": False}) @patch_category_acl({"can_move_posts": True}) def test_other_thread_isnt_replyable(self): """api validates if other thread can be replied""" other_thread = test.post_thread(self.other_category) response = self.client.post( self.api_link, {"new_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You can't move posts to threads you can't reply."}, ) @patch_category_acl({"can_move_posts": True}) def test_empty_data(self): """api handles empty data""" test.post_thread(self.category) response = self.client.post(self.api_link) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"detail": "Enter link to new thread."}) @patch_category_acl({"can_move_posts": True}) def test_empty_posts_data_json(self): """api handles empty json data""" other_thread = test.post_thread(self.category) response = self.client.post( self.api_link, json.dumps({"new_thread": other_thread.get_absolute_url()}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You have to specify at least one post to move."}, ) @patch_category_acl({"can_move_posts": True}) def test_empty_posts_data_form(self): """api handles empty form data""" other_thread = test.post_thread(self.category) response = self.client.post( self.api_link, {"new_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You have to specify at least one post to move."}, ) @patch_category_acl({"can_move_posts": True}) def test_no_posts_ids(self): """api rejects no posts ids""" other_thread = test.post_thread(self.category) response = self.client.post( self.api_link, json.dumps({"new_thread": other_thread.get_absolute_url(), "posts": []}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You have to specify at least one post to move."}, ) @patch_category_acl({"can_move_posts": True}) def test_invalid_posts_data(self): """api handles invalid data""" other_thread = test.post_thread(self.category) response = self.client.post( self.api_link, json.dumps( {"new_thread": other_thread.get_absolute_url(), "posts": "string"} ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": 'Expected a list of items but got type "str".'} ) @patch_category_acl({"can_move_posts": True}) def test_invalid_posts_ids(self): """api handles invalid post id""" other_thread = test.post_thread(self.category) response = self.client.post( self.api_link, json.dumps( { "new_thread": other_thread.get_absolute_url(), "posts": [1, 2, "string"], } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "One or more post ids received were invalid."} ) @override_dynamic_settings(posts_per_page=5, posts_per_page_orphans=3) @patch_category_acl({"can_move_posts": True}) def test_move_limit(self): """api rejects more posts than move limit""" other_thread = test.post_thread(self.category) response = self.client.post( self.api_link, json.dumps( {"new_thread": other_thread.get_absolute_url(), "posts": list(range(9))} ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "No more than 8 posts can be moved at a single time."}, ) @patch_category_acl({"can_move_posts": True}) def test_move_invisible(self): """api validates posts visibility""" other_thread = test.post_thread(self.category) response = self.client.post( self.api_link, json.dumps( { "new_thread": other_thread.get_absolute_url(), "posts": [test.reply_thread(self.thread, is_unapproved=True).pk], } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "One or more posts to move could not be found."} ) @patch_category_acl({"can_move_posts": True}) def test_move_other_thread_posts(self): """api recjects attempt to move other thread's post""" other_thread = test.post_thread(self.category) response = self.client.post( self.api_link, json.dumps( { "new_thread": other_thread.get_absolute_url(), "posts": [test.reply_thread(other_thread, is_hidden=True).pk], } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "One or more posts to move could not be found."} ) @patch_category_acl({"can_move_posts": True}) def test_move_event(self): """api rejects events move""" other_thread = test.post_thread(self.category) response = self.client.post( self.api_link, json.dumps( { "new_thread": other_thread.get_absolute_url(), "posts": [test.reply_thread(self.thread, is_event=True).pk], } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"detail": "Events can't be moved."}) @patch_category_acl({"can_move_posts": True}) def test_move_first_post(self): """api rejects first post move""" other_thread = test.post_thread(self.category) response = self.client.post( self.api_link, json.dumps( { "new_thread": other_thread.get_absolute_url(), "posts": [self.thread.first_post_id], } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Thread's first post can only be moved together with thread."}, ) @patch_category_acl({"can_move_posts": True}) def test_move_hidden_posts(self): """api recjects attempt to move urneadable hidden post""" other_thread = test.post_thread(self.category) response = self.client.post( self.api_link, json.dumps( { "new_thread": other_thread.get_absolute_url(), "posts": [test.reply_thread(self.thread, is_hidden=True).pk], } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You can't move posts the content you can't see."}, ) @patch_category_acl({"can_move_posts": True, "can_close_threads": False}) def test_move_posts_closed_thread_no_permission(self): """api recjects attempt to move posts from closed thread""" other_thread = test.post_thread(self.category) self.thread.is_closed = True self.thread.save() response = self.client.post( self.api_link, json.dumps( { "new_thread": other_thread.get_absolute_url(), "posts": [test.reply_thread(self.thread).pk], } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "This thread is closed. You can't move posts in it."}, ) @patch_other_category_acl({"can_reply_threads": True, "can_close_threads": False}) @patch_category_acl({"can_move_posts": True}) def test_move_posts_closed_category_no_permission(self): """api recjects attempt to move posts from closed thread""" other_thread = test.post_thread(self.other_category) self.category.is_closed = True self.category.save() response = self.client.post( self.api_link, json.dumps( { "new_thread": other_thread.get_absolute_url(), "posts": [test.reply_thread(self.thread).pk], } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "This category is closed. You can't move posts in it."}, ) @patch_other_category_acl({"can_reply_threads": True}) @patch_category_acl({"can_move_posts": True}) def test_move_posts(self): """api moves posts to other thread""" other_thread = test.post_thread(self.other_category) posts = ( test.reply_thread(self.thread).pk, test.reply_thread(self.thread).pk, test.reply_thread(self.thread).pk, test.reply_thread(self.thread).pk, ) self.thread.refresh_from_db() self.assertEqual(self.thread.replies, 4) response = self.client.post( self.api_link, json.dumps({"new_thread": other_thread.get_absolute_url(), "posts": posts}), content_type="application/json", ) self.assertEqual(response.status_code, 200) # replies were moved self.thread.refresh_from_db() self.assertEqual(self.thread.replies, 0) other_thread = Thread.objects.get(pk=other_thread.pk) self.assertEqual(other_thread.post_set.filter(pk__in=posts).count(), 4) self.assertEqual(other_thread.replies, 4) @patch_other_category_acl({"can_reply_threads": True}) @patch_category_acl({"can_move_posts": True}) def test_move_best_answer(self): """api moves best answer to other thread""" other_thread = test.post_thread(self.other_category) best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.synchronize() self.thread.save() self.thread.refresh_from_db() self.assertEqual(self.thread.best_answer, best_answer) self.assertEqual(self.thread.replies, 1) response = self.client.post( self.api_link, json.dumps( { "new_thread": other_thread.get_absolute_url(), "posts": [best_answer.pk], } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) # best_answer was moved and unmarked self.thread.refresh_from_db() self.assertEqual(self.thread.replies, 0) self.assertIsNone(self.thread.best_answer) other_thread = Thread.objects.get(pk=other_thread.pk) self.assertEqual(other_thread.replies, 1) self.assertIsNone(other_thread.best_answer) @patch_other_category_acl({"can_reply_threads": True}) @patch_category_acl({"can_move_posts": True}) def test_move_posts_reads(self): """api moves posts reads together with posts""" other_thread = test.post_thread(self.other_category) posts = (test.reply_thread(self.thread), test.reply_thread(self.thread)) self.thread.refresh_from_db() self.assertEqual(self.thread.replies, 2) poststracker.save_read(self.user, self.thread.first_post) for post in posts: poststracker.save_read(self.user, post) response = self.client.post( self.api_link, json.dumps( { "new_thread": other_thread.get_absolute_url(), "posts": [p.pk for p in posts], } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) other_thread = Thread.objects.get(pk=other_thread.pk) # postreads were removed postreads = self.user.postread_set.order_by("id") postreads_threads = list(postreads.values_list("thread_id", flat=True)) self.assertEqual(postreads_threads, [self.thread.pk]) postreads_categories = list(postreads.values_list("category_id", flat=True)) self.assertEqual(postreads_categories, [self.category.pk])
19,475
Python
.py
465
31.32043
88
0.585234
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,104
test_paginator.py
rafalp_Misago/misago/threads/tests/test_paginator.py
from itertools import product from django.test import TestCase from ..paginator import PostsPaginator class PostsPaginatorTests(TestCase): def test_paginator(self): """pages share first and last items with each other""" items = [i + 1 for i in range(30)] paginator = PostsPaginator(items, 5) self.assertEqual( self.get_paginator_items_list(paginator), [ [1, 2, 3, 4, 5], [5, 6, 7, 8, 9], [9, 10, 11, 12, 13], [13, 14, 15, 16, 17], [17, 18, 19, 20, 21], [21, 22, 23, 24, 25], [25, 26, 27, 28, 29], [29, 30], ], ) def test_paginator_orphans(self): """paginator handles orphans""" items = [i + 1 for i in range(16)] paginator = PostsPaginator(items, 8, 6) self.assertEqual( self.get_paginator_items_list(paginator), [[1, 2, 3, 4, 5, 6, 7, 8], [8, 9, 10, 11, 12, 13, 14, 15, 16]], ) paginator = PostsPaginator(items, 4, 4) self.assertEqual( self.get_paginator_items_list(paginator), [[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13, 14, 15, 16]], ) paginator = PostsPaginator(items, 5, 3) self.assertEqual( self.get_paginator_items_list(paginator), [[1, 2, 3, 4, 5], [5, 6, 7, 8, 9], [9, 10, 11, 12, 13, 14, 15, 16]], ) paginator = PostsPaginator(items, 6, 2) self.assertEqual( self.get_paginator_items_list(paginator), [[1, 2, 3, 4, 5, 6], [6, 7, 8, 9, 10, 11], [11, 12, 13, 14, 15, 16]], ) paginator = PostsPaginator(items, 7, 1) self.assertEqual( self.get_paginator_items_list(paginator), [[1, 2, 3, 4, 5, 6, 7], [7, 8, 9, 10, 11, 12, 13], [13, 14, 15, 16]], ) paginator = PostsPaginator(items, 7, 3) self.assertEqual( self.get_paginator_items_list(paginator), [[1, 2, 3, 4, 5, 6, 7], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]], ) paginator = PostsPaginator(items, 10, 6) self.assertEqual(self.get_paginator_items_list(paginator), [items]) def test_paginator_overlap(self): """test for #732 - assert that page contants don't overlap too much""" num_items = 16 items = [i + 1 for i in range(num_items)] for per_page, orphans in product(range(num_items), range(num_items)): paginator = PostsPaginator(items, per_page + 2, orphans) pages = self.get_paginator_items_list(paginator) for p, page in enumerate(pages): for c, compared in enumerate(pages): if p == c: continue common_part = set(page) & set(compared) self.assertTrue( len(common_part) < 2, "invalid page %s: %s" % (max(p, c) + 1, sorted(list(common_part))), ) def get_paginator_items_list(self, paginator): items_list = [] for page in paginator.page_range: items_list.append(paginator.page(page).object_list) return items_list
3,343
Python
.py
78
30.923077
86
0.51016
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,105
test_anonymize_data.py
rafalp_Misago/misago/threads/tests/test_anonymize_data.py
from unittest.mock import patch from django.test import RequestFactory from django.urls import reverse from .. import test from ...cache.versions import get_cache_versions from ...categories.models import Category from ...conf.dynamicsettings import DynamicSettings from ...users.test import AuthenticatedUserTestCase, create_test_user from ..api.postendpoints.patch_post import patch_is_liked from ..models import Post from ..participants import ( add_participant, change_owner, make_participants_aware, remove_participant, set_owner, ) class AnonymizeEventsTests(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.factory = RequestFactory() category = Category.objects.get(slug="first-category") self.thread = test.post_thread(category) def get_request(self, user=None): request = self.factory.get("/customer/details") request.user = user or self.user request.user_ip = "127.0.0.1" request.cache_versions = get_cache_versions() request.settings = DynamicSettings(request.cache_versions) request.include_frontend_context = False request.frontend_context = {} return request def test_anonymize_changed_owner_event(self): """changed owner event is anonymized by user.anonymize_data""" user = create_test_user("Other_User", "otheruser@example.com") request = self.get_request() set_owner(self.thread, self.user) make_participants_aware(self.user, self.thread) change_owner(request, self.thread, user) user.anonymize_data(anonymous_username="Deleted") event = Post.objects.get(event_type="changed_owner") self.assertEqual( event.event_context, { "user": { "id": None, "username": user.username, "url": reverse("misago:index"), } }, ) @patch("misago.threads.participants.notify_on_new_private_thread") def test_anonymize_added_participant_event(self, notify_on_new_private_thread_mock): """added participant event is anonymized by user.anonymize_data""" user = create_test_user("Other_User", "otheruser@example.com") request = self.get_request() set_owner(self.thread, self.user) make_participants_aware(self.user, self.thread) add_participant(request, self.thread, user) user.anonymize_data(anonymous_username="Deleted") event = Post.objects.get(event_type="added_participant") self.assertEqual( event.event_context, { "user": { "id": None, "username": user.username, "url": reverse("misago:index"), } }, ) @patch("misago.threads.participants.notify_on_new_private_thread") def test_anonymize_owner_left_event(self, notify_on_new_private_thread_mock): """owner left event is anonymized by user.anonymize_data""" user = create_test_user("Other_User", "otheruser@example.com") request = self.get_request(user) set_owner(self.thread, user) make_participants_aware(user, self.thread) add_participant(request, self.thread, self.user) make_participants_aware(user, self.thread) remove_participant(request, self.thread, user) user.anonymize_data(anonymous_username="Deleted") event = Post.objects.get(event_type="owner_left") self.assertEqual( event.event_context, { "user": { "id": None, "username": user.username, "url": reverse("misago:index"), } }, ) @patch("misago.threads.participants.notify_on_new_private_thread") def test_anonymize_removed_owner_event(self, notify_on_new_private_thread_mock): """removed owner event is anonymized by user.anonymize_data""" user = create_test_user("Other_User", "otheruser@example.com") request = self.get_request() set_owner(self.thread, user) make_participants_aware(user, self.thread) add_participant(request, self.thread, self.user) make_participants_aware(user, self.thread) remove_participant(request, self.thread, user) user.anonymize_data(anonymous_username="Deleted") event = Post.objects.get(event_type="removed_owner") self.assertEqual( event.event_context, { "user": { "id": None, "username": user.username, "url": reverse("misago:index"), } }, ) def test_anonymize_participant_left_event(self): """participant left event is anonymized by user.anonymize_data""" user = create_test_user("Other_User", "otheruser@example.com") request = self.get_request(user) set_owner(self.thread, self.user) make_participants_aware(user, self.thread) add_participant(request, self.thread, user) make_participants_aware(user, self.thread) remove_participant(request, self.thread, user) user.anonymize_data(anonymous_username="Deleted") event = Post.objects.get(event_type="participant_left") self.assertEqual( event.event_context, { "user": { "id": None, "username": user.username, "url": reverse("misago:index"), } }, ) @patch("misago.threads.participants.notify_on_new_private_thread") def test_anonymize_removed_participant_event( self, notify_on_new_private_thread_mock ): """removed participant event is anonymized by user.anonymize_data""" user = create_test_user("Other_User", "otheruser@example.com") request = self.get_request() set_owner(self.thread, self.user) make_participants_aware(self.user, self.thread) add_participant(request, self.thread, user) make_participants_aware(self.user, self.thread) remove_participant(request, self.thread, user) user.anonymize_data(anonymous_username="Deleted") event = Post.objects.get(event_type="removed_participant") self.assertEqual( event.event_context, { "user": { "id": None, "username": user.username, "url": reverse("misago:index"), } }, ) class AnonymizeLikesTests(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.factory = RequestFactory() def get_request(self, user=None): request = self.factory.get("/customer/details") request.user = user or self.user request.user_ip = "127.0.0.1" return request def test_anonymize_user_likes(self): """post's last like is anonymized by user.anonymize_data""" category = Category.objects.get(slug="first-category") thread = test.post_thread(category) post = test.reply_thread(thread) post.acl = {"can_like": True} user = create_test_user("Other_User", "otheruser@example.com") patch_is_liked(self.get_request(self.user), post, 1) patch_is_liked(self.get_request(user), post, 1) user.anonymize_data(anonymous_username="Deleted") last_likes = Post.objects.get(pk=post.pk).last_likes self.assertEqual( last_likes, [ {"id": None, "username": user.username}, {"id": self.user.id, "username": self.user.username}, ], ) class AnonymizePostsTests(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.factory = RequestFactory() def get_request(self, user=None): request = self.factory.get("/customer/details") request.user = user or self.user request.user_ip = "127.0.0.1" return request def test_anonymize_user_posts(self): """post is anonymized by user.anonymize_data""" category = Category.objects.get(slug="first-category") thread = test.post_thread(category) user = create_test_user("Other_User", "otheruser@example.com") post = test.reply_thread(thread, poster=user) user.anonymize_data(anonymous_username="Deleted") anonymized_post = Post.objects.get(pk=post.pk) self.assertTrue(anonymized_post.is_valid)
8,758
Python
.py
205
32.517073
88
0.616561
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,106
test_posts_moderation.py
rafalp_Misago/misago/threads/tests/test_posts_moderation.py
from .. import moderation, test from ...categories.models import Category from ...users.test import AuthenticatedUserTestCase from ..models import Post, Thread class PostsModerationTests(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.all_categories()[:1][0] self.thread = test.post_thread(self.category) self.post = test.reply_thread(self.thread) def reload_thread(self): self.thread = Thread.objects.get(pk=self.thread.pk) def reload_post(self): self.post = Post.objects.get(pk=self.post.pk) def test_hide_original_post(self): """hide_post fails for first post in thread""" with self.assertRaises(moderation.ModerationError): moderation.hide_post(self.user, self.thread.first_post) def test_protect_post(self): """protect_post protects post""" self.assertFalse(self.post.is_protected) self.assertTrue(moderation.protect_post(self.user, self.post)) self.reload_post() self.assertTrue(self.post.is_protected) def test_protect_protected_post(self): """protect_post fails to protect protected post gracefully""" self.post.is_protected = True self.assertFalse(moderation.protect_post(self.user, self.post)) def test_unprotect_post(self): """unprotect_post releases post protection""" self.post.is_protected = True self.assertTrue(moderation.unprotect_post(self.user, self.post)) self.reload_post() self.assertFalse(self.post.is_protected) def test_unprotect_protected_post(self): """unprotect_post fails to unprotect unprotected post gracefully""" self.assertFalse(moderation.unprotect_post(self.user, self.post)) def test_hide_post(self): """hide_post hides post""" self.assertFalse(self.post.is_hidden) self.assertTrue(moderation.hide_post(self.user, self.post)) self.reload_post() self.assertTrue(self.post.is_hidden) self.assertEqual(self.post.hidden_by, self.user) self.assertEqual(self.post.hidden_by_name, self.user.username) self.assertEqual(self.post.hidden_by_slug, self.user.slug) self.assertIsNotNone(self.post.hidden_on) def test_hide_hidden_post(self): """hide_post fails to hide hidden post gracefully""" self.post.is_hidden = True self.assertFalse(moderation.hide_post(self.user, self.post)) def test_unhide_original_post(self): """unhide_post fails for first post in thread""" with self.assertRaises(moderation.ModerationError): moderation.unhide_post(self.user, self.thread.first_post) def test_unhide_post(self): """unhide_post reveals post""" self.post.is_hidden = True self.assertTrue(self.post.is_hidden) self.assertTrue(moderation.unhide_post(self.user, self.post)) self.reload_post() self.assertFalse(self.post.is_hidden) def test_unhide_visible_post(self): """unhide_post fails to reveal visible post gracefully""" self.assertFalse(moderation.unhide_post(self.user, self.post)) def test_delete_original_post(self): """delete_post fails for first post in thread""" with self.assertRaises(moderation.ModerationError): moderation.delete_post(self.user, self.thread.first_post) def test_delete_post(self): """delete_post deletes thread post""" self.assertTrue(moderation.delete_post(self.user, self.post)) with self.assertRaises(Post.DoesNotExist): self.reload_post() self.thread.synchronize() self.assertEqual(self.thread.replies, 0)
3,746
Python
.py
76
41.092105
75
0.689334
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,107
test_attachments_proxy.py
rafalp_Misago/misago/threads/tests/test_attachments_proxy.py
import pytest from django.urls import reverse from ...acl.models import Role from ...acl.test import patch_user_acl from ...conf import settings from ...conf.test import override_dynamic_settings from ..models import Attachment, AttachmentType @pytest.fixture def attachment_type(db): return AttachmentType.objects.order_by("id").first() @pytest.fixture def attachment(attachment_type, post, user): return Attachment.objects.create( secret="secret", filetype=attachment_type, post=post, uploader=user, uploader_name=user.username, uploader_slug=user.slug, filename="test.txt", file="test.txt", size=1000, ) @pytest.fixture def image(post, user): return Attachment.objects.create( secret="secret", filetype=AttachmentType.objects.get(mimetypes="image/png"), post=post, uploader=user, uploader_name=user.username, uploader_slug=user.slug, filename="test.png", image="test.png", size=1000, ) @pytest.fixture def image_with_thumbnail(post, user): return Attachment.objects.create( secret="secret", filetype=AttachmentType.objects.get(mimetypes="image/png"), post=post, uploader=user, uploader_name=user.username, uploader_slug=user.slug, filename="test.png", image="test.png", thumbnail="test-thumbnail.png", size=1000, ) @pytest.fixture def other_users_attachment(attachment, other_user): attachment.uploader = other_user attachment.save() return attachment @pytest.fixture def orphaned_attachment(attachment): attachment.post = None attachment.save() return attachment @pytest.fixture def other_users_orphaned_attachment(other_users_attachment): other_users_attachment.post = None other_users_attachment.save() return other_users_attachment def assert_403(response): assert response.status_code == 302 assert response["location"].endswith(settings.MISAGO_ATTACHMENT_403_IMAGE) def assert_404(response): assert response.status_code == 302 assert response["location"].endswith(settings.MISAGO_ATTACHMENT_404_IMAGE) def test_proxy_redirects_client_to_attachment_file(client, attachment): response = client.get(attachment.get_absolute_url()) assert response.status_code == 302 assert response["location"].endswith("test.txt") def test_proxy_redirects_client_to_attachment_image(client, image): response = client.get(image.get_absolute_url()) assert response.status_code == 302 assert response["location"].endswith("test.png") def test_proxy_redirects_client_to_attachment_thumbnail(client, image_with_thumbnail): response = client.get(image_with_thumbnail.get_thumbnail_url()) assert response.status_code == 302 assert response["location"].endswith("test-thumbnail.png") def test_proxy_redirects_to_404_image_for_nonexistant_attachment(db, client): response = client.get( reverse("misago:attachment", kwargs={"pk": 1, "secret": "secret"}) ) assert_404(response) def test_proxy_redirects_to_404_image_for_url_with_invalid_attachment_secret( client, attachment ): response = client.get( reverse("misago:attachment", kwargs={"pk": attachment.id, "secret": "invalid"}) ) assert_404(response) @patch_user_acl({"can_download_other_users_attachments": False}) def test_proxy_redirects_to_403_image_for_user_without_permission_to_see_attachment( user_client, other_users_attachment ): response = user_client.get(other_users_attachment.get_absolute_url()) assert_403(response) def test_thumbnail_proxy_redirects_to_404_for_non_image_attachment(client, attachment): response = client.get( reverse( "misago:attachment-thumbnail", kwargs={"pk": attachment.pk, "secret": attachment.secret}, ) ) assert_404(response) def test_thumbnail_proxy_redirects_to_regular_image_for_image_without_thumbnail( client, image ): response = client.get( reverse( "misago:attachment-thumbnail", kwargs={"pk": image.pk, "secret": image.secret}, ) ) assert response.status_code == 302 assert response["location"].endswith("test.png") def test_thumbnail_proxy_redirects_to_thumbnail_image(client, image_with_thumbnail): response = client.get( reverse( "misago:attachment-thumbnail", kwargs={ "pk": image_with_thumbnail.pk, "secret": image_with_thumbnail.secret, }, ) ) assert response.status_code == 302 assert response["location"].endswith("test-thumbnail.png") def test_proxy_blocks_user_from_their_orphaned_attachment( user_client, orphaned_attachment ): response = user_client.get(orphaned_attachment.get_absolute_url()) assert_404(response) def test_proxy_redirects_user_to_their_orphaned_attachment_if_link_has_shva_key( user_client, orphaned_attachment ): response = user_client.get("%s?shva=1" % orphaned_attachment.get_absolute_url()) assert response.status_code == 302 assert response["location"].endswith("test.txt") def test_proxy_blocks_user_from_other_users_orphaned_attachment( user_client, other_users_orphaned_attachment ): response = user_client.get(other_users_orphaned_attachment.get_absolute_url()) assert_404(response) def test_proxy_blocks_user_from_other_users_orphaned_attachment_if_link_has_shva_key( user_client, other_users_orphaned_attachment ): response = user_client.get( "%s?shva=1" % other_users_orphaned_attachment.get_absolute_url() ) assert_404(response) def test_proxy_redirects_admin_to_other_users_orphaned_attachment( admin_client, orphaned_attachment ): response = admin_client.get("%s?shva=1" % orphaned_attachment.get_absolute_url()) assert response.status_code == 302 assert response["location"].endswith("test.txt") def test_proxy_blocks_user_from_attachment_with_disabled_type( user_client, attachment, attachment_type ): attachment_type.status = AttachmentType.DISABLED attachment_type.save() response = user_client.get(attachment.get_absolute_url()) assert_403(response) @pytest.fixture def role(db): return Role.objects.create(name="Test") @pytest.fixture def limited_attachment_type(attachment_type, role): attachment_type.limit_downloads_to.add(role) return attachment_type def test_proxy_blocks_user_without_role_from_attachment_with_limited_type( user_client, attachment, limited_attachment_type ): response = user_client.get(attachment.get_absolute_url()) assert_403(response) def test_proxy_allows_user_with_role_to_download_attachment_with_limited_type( user, user_client, role, attachment, limited_attachment_type ): user.roles.add(role) response = user_client.get(attachment.get_absolute_url()) assert response.status_code == 302 assert response["location"].endswith("test.txt") def test_proxy_allows_admin_without_role_to_download_attachment_with_limited_type( admin_client, attachment, limited_attachment_type ): response = admin_client.get(attachment.get_absolute_url()) assert response.status_code == 302 assert response["location"].endswith("test.txt") @override_dynamic_settings(attachment_403_image="custom-403-image.png") @patch_user_acl({"can_download_other_users_attachments": False}) def test_proxy_uses_custom_permission_denied_image_if_one_is_set( user_client, other_users_attachment ): response = user_client.get(other_users_attachment.get_absolute_url()) assert response.status_code == 302 assert response["location"].endswith("custom-403-image.png") @override_dynamic_settings(attachment_404_image="custom-404-image.png") def test_proxy_uses_custom_not_found_image_if_one_is_set(db, client): response = client.get( reverse("misago:attachment", kwargs={"pk": 1, "secret": "secret"}) ) assert response.status_code == 302 assert response["location"].endswith("custom-404-image.png")
8,186
Python
.py
208
34.163462
87
0.722264
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,108
test_thread_postdelete_api.py
rafalp_Misago/misago/threads/tests/test_thread_postdelete_api.py
from datetime import timedelta from django.urls import reverse from django.utils import timezone from .. import test from ..models import Post, Thread from ..test import patch_category_acl from .test_threads_api import ThreadsApiTestCase class PostDeleteApiTests(ThreadsApiTestCase): def setUp(self): super().setUp() self.post = test.reply_thread(self.thread, poster=self.user) self.api_link = reverse( "misago:api:thread-post-detail", kwargs={"thread_pk": self.thread.pk, "pk": self.post.pk}, ) def test_delete_anonymous(self): """api validates if deleting user is authenticated""" self.logout_user() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This action is not available to guests."} ) @patch_category_acl({"can_hide_posts": 1, "can_hide_own_posts": 1}) def test_no_permission(self): """api validates permission to delete post""" response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't delete posts in this category."} ) @patch_category_acl( {"can_hide_posts": 1, "can_hide_own_posts": 2, "post_edit_time": 0} ) def test_delete_other_user_post_no_permission(self): """api valdiates if user can delete other users posts""" self.post.poster = None self.post.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't delete other users posts in this category."}, ) @patch_category_acl( {"can_hide_posts": 1, "can_hide_own_posts": 2, "post_edit_time": 0} ) def test_delete_protected_post_no_permission(self): """api validates if user can delete protected post""" self.post.is_protected = True self.post.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This post is protected. You can't delete it."} ) @patch_category_acl( {"can_hide_posts": 1, "can_hide_own_posts": 2, "post_edit_time": 1} ) def test_delete_protected_post_after_edit_time(self): """api validates if user can delete delete post after edit time""" self.post.posted_on = timezone.now() - timedelta(minutes=10) self.post.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't delete posts that are older than 1 minute."}, ) @patch_category_acl( { "can_hide_posts": 0, "can_hide_own_posts": 2, "post_edit_time": 0, "can_close_threads": False, } ) def test_delete_post_closed_thread_no_permission(self): """api valdiates if user can delete posts in closed threads""" self.thread.is_closed = True self.thread.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This thread is closed. You can't delete posts in it."}, ) @patch_category_acl( { "can_hide_posts": 0, "can_hide_own_posts": 2, "post_edit_time": 0, "can_close_threads": False, } ) def test_delete_post_closed_category_no_permission(self): """api valdiates if user can delete posts in closed categories""" self.category.is_closed = True self.category.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This category is closed. You can't delete posts in it."}, ) @patch_category_acl({"can_hide_posts": 2, "can_hide_own_posts": 2}) def test_delete_first_post(self): """api disallows first post deletion""" api_link = reverse( "misago:api:thread-post-detail", kwargs={"thread_pk": self.thread.pk, "pk": self.thread.first_post_id}, ) response = self.client.delete(api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "Thread's first post can only be deleted together with thread."}, ) @patch_category_acl({"can_hide_posts": 2, "can_hide_own_posts": 2}) def test_delete_best_answer(self): """api disallows best answer deletion""" self.thread.set_best_answer(self.user, self.post) self.thread.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't delete this post because its marked as best answer."}, ) @patch_category_acl( {"can_hide_posts": 0, "can_hide_own_posts": 2, "post_edit_time": 0} ) def test_delete_owned_post(self): """api deletes owned thread post""" response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 200) self.thread = Thread.objects.get(pk=self.thread.pk) self.assertNotEqual(self.thread.last_post_id, self.post.pk) with self.assertRaises(Post.DoesNotExist): self.thread.post_set.get(pk=self.post.pk) @patch_category_acl({"can_hide_posts": 2, "can_hide_own_posts": 0}) def test_delete_post(self): """api deletes thread post""" response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 200) self.thread = Thread.objects.get(pk=self.thread.pk) self.assertNotEqual(self.thread.last_post_id, self.post.pk) with self.assertRaises(Post.DoesNotExist): self.thread.post_set.get(pk=self.post.pk) class EventDeleteApiTests(ThreadsApiTestCase): def setUp(self): super().setUp() self.event = test.reply_thread(self.thread, poster=self.user, is_event=True) self.api_link = reverse( "misago:api:thread-post-detail", kwargs={"thread_pk": self.thread.pk, "pk": self.event.pk}, ) def test_delete_anonymous(self): """api validates if deleting user is authenticated""" self.logout_user() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This action is not available to guests."} ) @patch_category_acl( {"can_hide_posts": 2, "can_hide_own_posts": 0, "can_hide_events": 0} ) def test_no_permission(self): """api validates permission to delete event""" response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't delete events in this category."} ) @patch_category_acl( { "can_hide_posts": 2, "can_hide_own_posts": 0, "can_hide_events": 2, "can_close_threads": False, } ) def test_delete_event_closed_thread_no_permission(self): """api valdiates if user can delete events in closed threads""" self.thread.is_closed = True self.thread.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This thread is closed. You can't delete events in it."}, ) @patch_category_acl( {"can_hide_posts": 2, "can_hide_events": 2, "can_close_threads": False} ) def test_delete_event_closed_category_no_permission(self): """api valdiates if user can delete events in closed categories""" self.category.is_closed = True self.category.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This category is closed. You can't delete events in it."}, ) @patch_category_acl({"can_hide_posts": 0, "can_hide_events": 2}) def test_delete_event(self): """api differs posts from events""" response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 200) self.thread = Thread.objects.get(pk=self.thread.pk) self.assertNotEqual(self.thread.last_post_id, self.event.pk) with self.assertRaises(Post.DoesNotExist): self.thread.post_set.get(pk=self.event.pk)
9,157
Python
.py
215
33.706977
88
0.621306
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,109
test_mergeconflict.py
rafalp_Misago/misago/threads/tests/test_mergeconflict.py
from django.test import TestCase from rest_framework.exceptions import ValidationError from .. import test from ...categories.models import Category from ...users.test import create_test_user from ..mergeconflict import MergeConflict class MergeConflictTests(TestCase): def setUp(self): self.category = Category.objects.get(slug="first-category") self.user = create_test_user("User", "user@example.com") def create_plain_thread(self): return test.post_thread(self.category) def create_poll_thread(self): thread = test.post_thread(self.category) test.post_poll(thread, self.user) return thread def create_best_answer_thread(self): thread = test.post_thread(self.category) best_answer = test.reply_thread(thread) thread.set_best_answer(self.user, best_answer) thread.synchronize() thread.save() return thread def test_plain_threads_no_conflicts(self): """threads without items of interest don't conflict""" threads = [self.create_plain_thread() for i in range(10)] merge_conflict = MergeConflict(threads=threads) self.assertFalse(merge_conflict.is_merge_conflict()) self.assertEqual(merge_conflict.get_conflicting_fields(), []) merge_conflict.is_valid(raise_exception=True) self.assertEqual(merge_conflict.get_resolution(), {}) def test_one_best_answer_one_plain(self): """thread with best answer and plain thread don't conflict""" threads = [self.create_best_answer_thread(), self.create_plain_thread()] merge_conflict = MergeConflict(threads=threads) self.assertFalse(merge_conflict.is_merge_conflict()) self.assertEqual(merge_conflict.get_conflicting_fields(), []) merge_conflict.is_valid(raise_exception=True) self.assertEqual(merge_conflict.get_resolution(), {"best_answer": threads[0]}) def test_one_poll_one_plain(self): """thread with poll and plain thread don't conflict""" threads = [self.create_poll_thread(), self.create_plain_thread()] merge_conflict = MergeConflict(threads=threads) self.assertFalse(merge_conflict.is_merge_conflict()) self.assertEqual(merge_conflict.get_conflicting_fields(), []) merge_conflict.is_valid(raise_exception=True) self.assertEqual(merge_conflict.get_resolution(), {"poll": threads[0].poll}) def test_one_best_answer_one_poll(self): """thread with best answer and thread with poll don't conflict""" threads = [self.create_poll_thread(), self.create_best_answer_thread()] merge_conflict = MergeConflict(threads=threads) self.assertFalse(merge_conflict.is_merge_conflict()) def test_one_best_answer_one_poll_one_plain(self): """thread with best answer, thread with poll and plain thread don't conflict""" threads = [ self.create_plain_thread(), self.create_poll_thread(), self.create_best_answer_thread(), ] merge_conflict = MergeConflict(threads=threads) self.assertFalse(merge_conflict.is_merge_conflict()) def test_three_best_answers_one_poll_two_plain_conflict(self): """ three threads with best answer, thread with poll and two plain threads conflict """ best_answers = [self.create_best_answer_thread() for i in range(3)] polls = [self.create_poll_thread()] threads = ( [self.create_plain_thread(), self.create_plain_thread()] + best_answers + polls ) merge_conflict = MergeConflict(threads=threads) self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual(merge_conflict.get_conflicting_fields(), ["best_answer"]) # without choice, conflict lists resolutions try: merge_conflict.is_valid(raise_exception=True) self.fail("merge_conflict.is_valid() should raise ValidationError") except ValidationError as e: self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual(merge_conflict.get_conflicting_fields(), ["best_answer"]) self.assertEqual( e.detail, { "best_answers": [["0", "Unmark all best answers"]] + [[str(thread.id), thread.title] for thread in best_answers] }, ) # conflict validates choice try: merge_conflict = MergeConflict({"best_answer": threads[0].id}, threads) merge_conflict.is_valid(raise_exception=True) self.fail("merge_conflict.is_valid() should raise ValidationError") except ValidationError as e: self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual(e.detail, {"best_answer": ["Invalid choice."]}) # conflict returns selected resolution merge_conflict = MergeConflict({"best_answer": best_answers[0].id}, threads) self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual(merge_conflict.get_conflicting_fields(), ["best_answer"]) merge_conflict.is_valid(raise_exception=True) self.assertEqual( merge_conflict.get_resolution(), {"best_answer": best_answers[0], "poll": polls[0].poll}, ) # conflict returns no-choice resolution merge_conflict = MergeConflict({"best_answer": 0}, threads) self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual(merge_conflict.get_conflicting_fields(), ["best_answer"]) merge_conflict.is_valid(raise_exception=True) self.assertEqual( merge_conflict.get_resolution(), {"best_answer": None, "poll": polls[0].poll}, ) def test_one_best_answer_three_polls_two_plain_conflict(self): """ one thread with best answer, three threads with poll and two plain threads conflict """ best_answers = [self.create_best_answer_thread()] polls = [self.create_poll_thread() for i in range(3)] threads = ( [self.create_plain_thread(), self.create_plain_thread()] + best_answers + polls ) merge_conflict = MergeConflict(threads=threads) self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual(merge_conflict.get_conflicting_fields(), ["poll"]) # without choice, conflict lists resolutions try: merge_conflict.is_valid(raise_exception=True) self.fail("merge_conflict.is_valid() should raise ValidationError") except ValidationError as e: self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual(merge_conflict.get_conflicting_fields(), ["poll"]) self.assertEqual( e.detail, { "polls": [["0", "Delete all polls"]] + [ [ str(thread.poll.id), "%s (%s)" % (thread.poll.question, thread.title), ] for thread in polls ] }, ) # conflict validates choice try: merge_conflict = MergeConflict({"poll": threads[0].id}, threads) merge_conflict.is_valid(raise_exception=True) self.fail("merge_conflict.is_valid() should raise ValidationError") except ValidationError as e: self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual(e.detail, {"poll": ["Invalid choice."]}) # conflict returns selected resolution merge_conflict = MergeConflict({"poll": polls[0].poll.id}, threads) self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual(merge_conflict.get_conflicting_fields(), ["poll"]) merge_conflict.is_valid(raise_exception=True) self.assertEqual( merge_conflict.get_resolution(), {"best_answer": best_answers[0], "poll": polls[0].poll}, ) # conflict returns no-choice resolution merge_conflict = MergeConflict({"poll": 0}, threads) self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual(merge_conflict.get_conflicting_fields(), ["poll"]) merge_conflict.is_valid(raise_exception=True) self.assertEqual( merge_conflict.get_resolution(), {"best_answer": best_answers[0], "poll": None}, ) def test_three_best_answers_three_polls_two_plain_conflict(self): """multiple conflict is handled""" best_answers = [self.create_best_answer_thread() for i in range(3)] polls = [self.create_poll_thread() for i in range(3)] threads = ( [self.create_plain_thread(), self.create_plain_thread()] + best_answers + polls ) merge_conflict = MergeConflict(threads=threads) self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual( merge_conflict.get_conflicting_fields(), ["best_answer", "poll"] ) # without choice, conflict lists all resolutions try: merge_conflict.is_valid(raise_exception=True) self.fail("merge_conflict.is_valid() should raise ValidationError") except ValidationError as e: self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual( merge_conflict.get_conflicting_fields(), ["best_answer", "poll"] ) self.assertEqual( e.detail, { "best_answers": [["0", "Unmark all best answers"]] + [[str(thread.id), thread.title] for thread in best_answers], "polls": [["0", "Delete all polls"]] + [ [ str(thread.poll.id), "%s (%s)" % (thread.poll.question, thread.title), ] for thread in polls ], }, ) # conflict validates all choices if single choice was given try: merge_conflict = MergeConflict({"best_answer": threads[0].id}, threads) merge_conflict.is_valid(raise_exception=True) self.fail("merge_conflict.is_valid() should raise ValidationError") except ValidationError as e: self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual( e.detail, {"best_answer": ["Invalid choice."], "poll": ["Invalid choice."]}, ) try: merge_conflict = MergeConflict({"poll": threads[0].id}, threads) merge_conflict.is_valid(raise_exception=True) self.fail("merge_conflict.is_valid() should raise ValidationError") except ValidationError as e: self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual( e.detail, {"best_answer": ["Invalid choice."], "poll": ["Invalid choice."]}, ) # conflict validates all choices if all choices were given try: merge_conflict = MergeConflict( {"best_answer": threads[0].id, "poll": threads[0].id}, threads ) merge_conflict.is_valid(raise_exception=True) self.fail("merge_conflict.is_valid() should raise ValidationError") except ValidationError as e: self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual( e.detail, {"best_answer": ["Invalid choice."], "poll": ["Invalid choice."]}, ) # conflict returns selected resolutions valid_choices = {"best_answer": best_answers[0].id, "poll": polls[0].poll.id} merge_conflict = MergeConflict(valid_choices, threads) self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual( merge_conflict.get_conflicting_fields(), ["best_answer", "poll"] ) merge_conflict.is_valid(raise_exception=True) self.assertEqual( merge_conflict.get_resolution(), {"best_answer": best_answers[0], "poll": polls[0].poll}, ) # conflict returns no-choice resolution merge_conflict = MergeConflict({"best_answer": 0, "poll": 0}, threads) self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual( merge_conflict.get_conflicting_fields(), ["best_answer", "poll"] ) merge_conflict.is_valid(raise_exception=True) self.assertEqual( merge_conflict.get_resolution(), {"best_answer": None, "poll": None} ) # conflict allows mixing no-choice with choice merge_conflict = MergeConflict( {"best_answer": best_answers[0].id, "poll": 0}, threads ) self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual( merge_conflict.get_conflicting_fields(), ["best_answer", "poll"] ) merge_conflict.is_valid(raise_exception=True) self.assertEqual( merge_conflict.get_resolution(), {"best_answer": best_answers[0], "poll": None}, ) merge_conflict = MergeConflict( {"best_answer": 0, "poll": polls[0].poll.id}, threads ) self.assertTrue(merge_conflict.is_merge_conflict()) self.assertEqual( merge_conflict.get_conflicting_fields(), ["best_answer", "poll"] ) merge_conflict.is_valid(raise_exception=True) self.assertEqual( merge_conflict.get_resolution(), {"best_answer": None, "poll": polls[0].poll}, )
14,037
Python
.py
295
36.237288
87
0.606231
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,110
test_thread_postbulkpatch_api.py
rafalp_Misago/misago/threads/tests/test_thread_postbulkpatch_api.py
import json from django.urls import reverse from .. import test from ...categories.models import Category from ...conf.test import override_dynamic_settings from ...users.test import AuthenticatedUserTestCase from ..models import Post, Thread from ..test import patch_category_acl class ThreadPostBulkPatchApiTestCase(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.get(slug="first-category") self.thread = test.post_thread(category=self.category) self.posts = [ test.reply_thread(self.thread, poster=self.user), test.reply_thread(self.thread), test.reply_thread(self.thread, poster=self.user), ] self.ids = [p.id for p in self.posts] self.api_link = reverse( "misago:api:thread-post-list", kwargs={"thread_pk": self.thread.pk} ) def patch(self, api_link, ops): return self.client.patch( api_link, json.dumps(ops), content_type="application/json" ) class BulkPatchSerializerTests(ThreadPostBulkPatchApiTestCase): def test_invalid_input_type(self): """api rejects invalid input type""" response = self.patch(self.api_link, [1, 2, 3]) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] }, ) def test_missing_input_keys(self): """api rejects input with missing keys""" response = self.patch(self.api_link, {}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"ids": ["This field is required."], "ops": ["This field is required."]}, ) def test_empty_input_keys(self): """api rejects input with empty keys""" response = self.patch(self.api_link, {"ids": [], "ops": []}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "ids": ["Ensure this field has at least 1 elements."], "ops": ["Ensure this field has at least 1 elements."], }, ) def test_invalid_input_keys(self): """api rejects input with invalid keys""" response = self.patch(self.api_link, {"ids": ["a"], "ops": [1]}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "ids": {"0": ["A valid integer is required."]}, "ops": {"0": ['Expected a dictionary of items but got type "int".']}, }, ) def test_too_small_id(self): """api rejects input with implausiple id""" response = self.patch(self.api_link, {"ids": [0], "ops": [{}]}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"ids": {"0": ["Ensure this value is greater than or equal to 1."]}}, ) @override_dynamic_settings(posts_per_page=4, posts_per_page_orphans=3) def test_too_large_input(self): """api rejects too large input""" response = self.patch( self.api_link, {"ids": [i + 1 for i in range(8)], "ops": [{} for i in range(200)]}, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "ids": ["No more than 7 posts can be updated at a single time."], "ops": ["Ensure this field has no more than 10 elements."], }, ) def test_posts_not_found(self): """api fails to find posts""" posts = [ test.reply_thread(self.thread, is_hidden=True), test.reply_thread(self.thread, is_unapproved=True), ] response = self.patch( self.api_link, {"ids": [p.id for p in posts], "ops": [{}]} ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "One or more posts to update could not be found."}, ) def test_ops_invalid(self): """api validates descriptions""" response = self.patch(self.api_link, {"ids": self.ids[:1], "ops": [{}]}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), [{"id": self.ids[0], "detail": ["undefined op"]}] ) def test_anonymous_user(self): """anonymous users can't use bulk actions""" self.logout_user() response = self.patch(self.api_link, {"ids": self.ids[:1], "ops": [{}]}) self.assertEqual(response.status_code, 403) def test_events(self): """cant use bulk actions for events""" for post in self.posts: post.is_event = True post.save() response = self.patch(self.api_link, {"ids": self.ids, "ops": [{}]}) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "One or more posts to update could not be found."}, ) class PostsAddAclApiTests(ThreadPostBulkPatchApiTestCase): def test_add_acl_true(self): """api adds posts acls to response""" response = self.patch( self.api_link, {"ids": self.ids, "ops": [{"op": "add", "path": "acl", "value": True}]}, ) self.assertEqual(response.status_code, 200) response_json = response.json() for i, post in enumerate(self.posts): self.assertEqual(response_json[i]["id"], post.id) self.assertTrue(response_json[i]["acl"]) class BulkPostProtectApiTests(ThreadPostBulkPatchApiTestCase): @patch_category_acl({"can_protect_posts": True, "can_edit_posts": 2}) def test_protect_post(self): """api makes it possible to protect posts""" response = self.patch( self.api_link, { "ids": self.ids, "ops": [{"op": "replace", "path": "is-protected", "value": True}], }, ) self.assertEqual(response.status_code, 200) response_json = response.json() for i, post in enumerate(self.posts): self.assertEqual(response_json[i]["id"], post.id) self.assertTrue(response_json[i]["is_protected"]) for post in Post.objects.filter(id__in=self.ids): self.assertTrue(post.is_protected) @patch_category_acl({"can_protect_posts": False}) def test_protect_post_no_permission(self): """api validates permission to protect posts and returns errors""" response = self.patch( self.api_link, { "ids": self.ids, "ops": [{"op": "replace", "path": "is-protected", "value": True}], }, ) self.assertEqual(response.status_code, 400) response_json = response.json() for i, post in enumerate(self.posts): self.assertEqual(response_json[i]["id"], post.id) self.assertEqual( response_json[i]["detail"], ["You can't protect posts in this category."], ) for post in Post.objects.filter(id__in=self.ids): self.assertFalse(post.is_protected) class BulkPostsApproveApiTests(ThreadPostBulkPatchApiTestCase): @patch_category_acl({"can_approve_content": True}) def test_approve_post(self): """api resyncs thread and categories on posts approval""" for post in self.posts: post.is_unapproved = True post.save() self.thread.synchronize() self.thread.save() self.assertNotIn(self.thread.last_post_id, self.ids) response = self.patch( self.api_link, { "ids": self.ids, "ops": [{"op": "replace", "path": "is-unapproved", "value": False}], }, ) self.assertEqual(response.status_code, 200) response_json = response.json() for i, post in enumerate(self.posts): self.assertEqual(response_json[i]["id"], post.id) self.assertFalse(response_json[i]["is_unapproved"]) for post in Post.objects.filter(id__in=self.ids): self.assertFalse(post.is_unapproved) thread = Thread.objects.get(pk=self.thread.pk) self.assertIn(thread.last_post_id, self.ids) category = Category.objects.get(pk=self.category.pk) self.assertEqual(category.posts, 4)
8,732
Python
.py
207
32.033816
85
0.578643
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,111
test_updatepostschecksums.py
rafalp_Misago/misago/threads/tests/test_updatepostschecksums.py
from io import StringIO from django.core.management import call_command from django.test import TestCase from .. import test from ...categories.models import Category from ..management.commands import updatepostschecksums from ..models import Post class UpdatePostsChecksumsTests(TestCase): def test_no_posts_to_update(self): """command works when there are no posts""" command = updatepostschecksums.Command() out = StringIO() call_command(command, stdout=out) command_output = out.getvalue().strip() self.assertEqual(command_output, "No posts were found") def test_posts_update(self): """command updates posts checksums""" category = Category.objects.all_categories()[:1][0] threads = [test.post_thread(category) for _ in range(5)] for _, thread in enumerate(threads): [test.reply_thread(thread) for _ in range(3)] thread.save() Post.objects.update(parsed="Hello world!") for post in Post.objects.all(): self.assertFalse(post.is_valid) command = updatepostschecksums.Command() out = StringIO() call_command(command, stdout=out) command_output = out.getvalue().splitlines()[-1].strip() self.assertEqual(command_output, "Updated 20 posts checksums") for post in Post.objects.all(): self.assertTrue(post.is_valid)
1,426
Python
.py
32
36.90625
70
0.677046
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,112
test_thread_model.py
rafalp_Misago/misago/threads/tests/test_thread_model.py
from datetime import timedelta from django.test import TestCase from django.utils import timezone from .. import test from ...categories.models import Category from ...users.test import create_test_user from ..models import Poll, Post, Thread, ThreadParticipant class ThreadModelTests(TestCase): def setUp(self): datetime = timezone.now() self.category = Category.objects.all_categories()[:1][0] self.thread = Thread( category=self.category, started_on=datetime, starter_name="Tester", starter_slug="tester", last_post_on=datetime, last_poster_name="Tester", last_poster_slug="tester", ) self.thread.set_title("Test thread") self.thread.save() Post.objects.create( category=self.category, thread=self.thread, poster_name="Tester", original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=datetime, updated_on=datetime, ) self.thread.synchronize() self.thread.save() def test_synchronize(self): """synchronize method updates thread data to reflect its contents""" user = create_test_user("User", "user@example.com") self.assertEqual(self.thread.replies, 0) datetime = timezone.now() + timedelta(5) post = Post.objects.create( category=self.category, thread=self.thread, poster=user, poster_name=user.username, original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=datetime, updated_on=datetime, ) # first sync call, updates last thread self.thread.synchronize() self.assertEqual(self.thread.last_post, post) self.assertEqual(self.thread.last_post_on, post.posted_on) self.assertEqual(self.thread.last_poster, user) self.assertEqual(self.thread.last_poster_name, user.username) self.assertEqual(self.thread.last_poster_slug, user.slug) self.assertFalse(self.thread.has_reported_posts) self.assertFalse(self.thread.has_unapproved_posts) self.assertFalse(self.thread.has_hidden_posts) self.assertEqual(self.thread.replies, 1) # add unapproved post unapproved_post = Post.objects.create( category=self.category, thread=self.thread, poster=user, poster_name=user.username, original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=datetime + timedelta(5), updated_on=datetime + timedelta(5), is_unapproved=True, ) self.thread.synchronize() self.assertEqual(self.thread.last_post, post) self.assertEqual(self.thread.last_post_on, post.posted_on) self.assertEqual(self.thread.last_poster, user) self.assertEqual(self.thread.last_poster_name, user.username) self.assertEqual(self.thread.last_poster_slug, user.slug) self.assertFalse(self.thread.has_reported_posts) self.assertTrue(self.thread.has_unapproved_posts) self.assertFalse(self.thread.has_hidden_posts) self.assertEqual(self.thread.replies, 1) # add hidden post hidden_post = Post.objects.create( category=self.category, thread=self.thread, poster=user, poster_name=user.username, original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=datetime + timedelta(10), updated_on=datetime + timedelta(10), is_hidden=True, ) self.thread.synchronize() self.assertEqual(self.thread.last_post, hidden_post) self.assertEqual(self.thread.last_post_on, hidden_post.posted_on) self.assertEqual(self.thread.last_poster, user) self.assertEqual(self.thread.last_poster_name, user.username) self.assertEqual(self.thread.last_poster_slug, user.slug) self.assertFalse(self.thread.has_reported_posts) self.assertTrue(self.thread.has_unapproved_posts) self.assertTrue(self.thread.has_hidden_posts) self.assertEqual(self.thread.replies, 2) # unhide post hidden_post.is_hidden = False hidden_post.save() # last post changed to unhidden one self.thread.synchronize() self.assertEqual(self.thread.last_post, hidden_post) self.assertEqual(self.thread.last_post_on, hidden_post.posted_on) self.assertEqual(self.thread.last_poster, user) self.assertEqual(self.thread.last_poster_name, user.username) self.assertEqual(self.thread.last_poster_slug, user.slug) self.assertFalse(self.thread.has_reported_posts) self.assertTrue(self.thread.has_unapproved_posts) self.assertFalse(self.thread.has_hidden_posts) self.assertEqual(self.thread.replies, 2) # unmoderate post unapproved_post.is_unapproved = False unapproved_post.save() # last post not changed, but flags and count did self.thread.synchronize() self.assertEqual(self.thread.last_post, hidden_post) self.assertEqual(self.thread.last_post_on, hidden_post.posted_on) self.assertEqual(self.thread.last_poster, user) self.assertEqual(self.thread.last_poster_name, user.username) self.assertEqual(self.thread.last_poster_slug, user.slug) self.assertFalse(self.thread.has_reported_posts) self.assertFalse(self.thread.has_unapproved_posts) self.assertFalse(self.thread.has_hidden_posts) self.assertEqual(self.thread.replies, 3) # add event post event = Post.objects.create( category=self.category, thread=self.thread, poster=user, poster_name=user.username, original="-", parsed="-", checksum="nope", posted_on=datetime + timedelta(10), updated_on=datetime + timedelta(10), is_event=True, ) self.thread.synchronize() self.assertEqual(self.thread.last_post, event) self.assertEqual(self.thread.last_post_on, event.posted_on) self.assertEqual(self.thread.last_poster, user) self.assertEqual(self.thread.last_poster_name, user.username) self.assertEqual(self.thread.last_poster_slug, user.slug) self.assertTrue(self.thread.last_post_is_event) self.assertTrue(self.thread.has_events) self.assertFalse(self.thread.has_reported_posts) self.assertFalse(self.thread.has_unapproved_posts) self.assertFalse(self.thread.has_hidden_posts) # events don't count to reply count self.assertEqual(self.thread.replies, 3) # create another post to provoke other has_events resolution path Post.objects.create( category=self.category, thread=self.thread, poster=user, poster_name=user.username, original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=datetime, updated_on=datetime, ) self.thread.synchronize() self.assertFalse(self.thread.last_post_is_event) self.assertTrue(self.thread.has_events) # remove event event.delete() self.thread.synchronize() self.assertFalse(self.thread.last_post_is_event) self.assertFalse(self.thread.has_events) # has poll flag self.assertFalse(self.thread.has_poll) Poll.objects.create( thread=self.thread, category=self.category, poster_name="test", poster_slug="test", choices=[], ) self.thread.synchronize() self.assertTrue(self.thread.has_poll) def test_set_first_post(self): """set_first_post sets first post and poster data on thread""" user = create_test_user("User", "user@example.com") datetime = timezone.now() + timedelta(5) post = Post.objects.create( category=self.category, thread=self.thread, poster=user, poster_name=user.username, original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=datetime, updated_on=datetime, ) self.thread.set_first_post(post) self.assertEqual(self.thread.first_post, post) self.assertEqual(self.thread.started_on, post.posted_on) self.assertEqual(self.thread.starter, user) self.assertEqual(self.thread.starter_name, user.username) self.assertEqual(self.thread.starter_slug, user.slug) def test_set_last_post(self): """set_last_post sets first post and poster data on thread""" user = create_test_user("User", "user@example.com") datetime = timezone.now() + timedelta(5) post = Post.objects.create( category=self.category, thread=self.thread, poster=user, poster_name=user.username, original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=datetime, updated_on=datetime, ) self.thread.set_last_post(post) self.assertEqual(self.thread.last_post, post) self.assertEqual(self.thread.last_post_on, post.posted_on) self.assertEqual(self.thread.last_poster, user) self.assertEqual(self.thread.last_poster_name, user.username) self.assertEqual(self.thread.last_poster_slug, user.slug) def test_set_best_answer(self): """set_best_answer sets best answer and setter data on thread""" user = create_test_user("User", "user@example.com") best_answer = Post.objects.create( category=self.category, thread=self.thread, poster=user, poster_name=user.username, original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=timezone.now(), updated_on=timezone.now(), is_protected=True, ) self.thread.synchronize() self.thread.save() self.thread.set_best_answer(user, best_answer) self.thread.save() self.assertEqual(self.thread.best_answer, best_answer) self.assertTrue(self.thread.has_best_answer) self.assertTrue(self.thread.best_answer_is_protected) self.assertTrue(self.thread.best_answer_marked_on) self.assertEqual(self.thread.best_answer_marked_by, user) self.assertEqual(self.thread.best_answer_marked_by_name, user.username) self.assertEqual(self.thread.best_answer_marked_by_slug, user.slug) # clear best answer self.thread.clear_best_answer() self.assertIsNone(self.thread.best_answer) self.assertFalse(self.thread.has_best_answer) self.assertFalse(self.thread.best_answer_is_protected) self.assertIsNone(self.thread.best_answer_marked_on) self.assertIsNone(self.thread.best_answer_marked_by) self.assertIsNone(self.thread.best_answer_marked_by_name) self.assertIsNone(self.thread.best_answer_marked_by_slug) def test_set_invalid_best_answer(self): """set_best_answer implements some assertions for data integrity""" user = create_test_user("User", "user@example.com") other_thread = test.post_thread(self.category) with self.assertRaises(ValueError): self.thread.set_best_answer(user, other_thread.first_post) with self.assertRaises(ValueError): self.thread.set_best_answer(user, self.thread.first_post) with self.assertRaises(ValueError): reply = test.reply_thread(self.thread, is_hidden=True) self.thread.set_best_answer(user, reply) with self.assertRaises(ValueError): reply = test.reply_thread(self.thread, is_unapproved=True) self.thread.set_best_answer(user, reply) def test_move(self): """move(new_category) moves thread to other category""" root_category = Category.objects.root_category() Category(name="New Category", slug="new-category").insert_at( root_category, position="last-child", save=True ) new_category = Category.objects.get(slug="new-category") self.thread.move(new_category) self.assertEqual(self.thread.category, new_category) for post in self.thread.post_set.all(): self.assertEqual(post.category_id, new_category.id) def test_merge(self): """merge(other_thread) moves other thread content to this thread""" with self.assertRaises(ValueError): self.thread.merge(self.thread) datetime = timezone.now() + timedelta(5) other_thread = Thread( category=self.category, started_on=datetime, starter_name="Tester", starter_slug="tester", last_post_on=datetime, last_poster_name="Tester", last_poster_slug="tester", ) other_thread.set_title("Other thread") other_thread.save() post = Post.objects.create( category=self.category, thread=other_thread, poster_name="Admin", original="Hello! I am other message!", parsed="<p>Hello! I am other message!</p>", checksum="nope", posted_on=datetime, updated_on=datetime, ) other_thread.first_post = post other_thread.last_post = post other_thread.save() self.thread.merge(other_thread) self.thread.synchronize() self.assertEqual(self.thread.replies, 1) self.assertEqual(self.thread.last_post, post) self.assertEqual(self.thread.last_post_on, post.posted_on) self.assertEqual(self.thread.last_poster_name, "Admin") self.assertEqual(self.thread.last_poster_slug, "admin") def test_delete_private_thread(self): """ private thread gets deleted automatically when there are no participants left in it """ user = create_test_user("User", "user@example.com") other_user = create_test_user("Other_User", "otheruser@example.com") ThreadParticipant.objects.add_participants(self.thread, [user, other_user]) self.assertEqual(self.thread.participants.count(), 2) user.delete(anonymous_username="Deleted") Thread.objects.get(id=self.thread.id) other_user.delete(anonymous_username="Deleted") with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(id=self.thread.id) def test_thread_participants_ids_property_returns_list_of_participants_users_ids( thread, user, other_user ): ThreadParticipant.objects.create(thread=thread, user=user, is_owner=False) ThreadParticipant.objects.create(thread=thread, user=other_user, is_owner=True) participants_ids = list(thread.participants_ids) assert participants_ids == [other_user.id, user.id]
15,738
Python
.py
351
34.652422
83
0.639141
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,113
test_get_thread_url.py
rafalp_Misago/misago/threads/tests/test_get_thread_url.py
from django.urls import reverse from ..models import Thread from ..threadurl import get_thread_url def test_get_thread_url_returns_thread_url(django_assert_num_queries, thread): with django_assert_num_queries(0): url = get_thread_url(thread) assert url == reverse( "misago:thread", kwargs={"id": thread.id, "slug": thread.slug} ) def test_get_thread_url_returns_thread_url_using_category_arg( django_assert_num_queries, thread, default_category ): thread_without_related = Thread.objects.get(id=thread.id) with django_assert_num_queries(0): url = get_thread_url(thread_without_related, default_category) assert url == reverse( "misago:thread", kwargs={"id": thread.id, "slug": thread.slug} ) def test_get_thread_url_returns_private_thread_url( django_assert_num_queries, private_thread ): with django_assert_num_queries(0): url = get_thread_url(private_thread) assert url == reverse( "misago:private-thread", kwargs={"id": private_thread.id, "slug": private_thread.slug}, ) def test_get_thread_url_returns_private_thread_url_using_category( django_assert_num_queries, private_thread, private_threads_category ): thread_without_related = Thread.objects.get(id=private_thread.id) with django_assert_num_queries(0): url = get_thread_url(thread_without_related, private_threads_category) assert url == reverse( "misago:private-thread", kwargs={"id": private_thread.id, "slug": private_thread.slug}, )
1,558
Python
.py
37
36.756757
78
0.704907
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,114
test_threads_lists_moderation.py
rafalp_Misago/misago/threads/tests/test_threads_lists_moderation.py
from django.urls import reverse from ...conf.test import override_dynamic_settings from ...permissions.models import Moderator from ...test import assert_contains, assert_not_contains from ..test import post_thread MODERATION_FORM_HTML = '<form id="threads-moderation" method="post">' MODERATION_FIXED_HTML = '<div class="fixed-moderation">' DISABLED_CHECKBOX_HTML = '<input type="checkbox" disabled />' @override_dynamic_settings(index_view="categories") def test_site_threads_list_shows_noscript_moderation_form_to_moderators( default_category, moderator_client ): response = moderator_client.get(reverse("misago:threads")) assert_contains(response, MODERATION_FORM_HTML) def test_category_threads_list_shows_noscript_moderation_form_to_moderators( default_category, moderator_client ): response = moderator_client.get(default_category.get_absolute_url()) assert_contains(response, MODERATION_FORM_HTML) @override_dynamic_settings(index_view="categories") def test_site_threads_list_shows_fixed_moderation_form_to_moderators( default_category, moderator_client ): response = moderator_client.get(reverse("misago:threads")) assert_contains(response, MODERATION_FIXED_HTML) def test_category_threads_list_shows_fixed_moderation_form_to_moderators( default_category, moderator_client ): response = moderator_client.get(default_category.get_absolute_url()) assert_contains(response, MODERATION_FIXED_HTML) @override_dynamic_settings(index_view="categories") def test_site_threads_list_doesnt_show_moderation_to_users( default_category, user_client ): response = user_client.get(reverse("misago:threads")) assert_not_contains(response, MODERATION_FORM_HTML) assert_not_contains(response, MODERATION_FIXED_HTML) def test_category_threads_list_doesnt_show_moderation_to_users( default_category, user_client ): response = user_client.get(default_category.get_absolute_url()) assert_not_contains(response, MODERATION_FORM_HTML) assert_not_contains(response, MODERATION_FIXED_HTML) @override_dynamic_settings(index_view="categories") def test_site_threads_list_doesnt_show_moderation_to_guests( default_category, user_client ): response = user_client.get(reverse("misago:threads")) assert_not_contains(response, MODERATION_FORM_HTML) assert_not_contains(response, MODERATION_FIXED_HTML) def test_category_threads_list_doesnt_show_moderation_to_guests( default_category, user_client ): response = user_client.get(default_category.get_absolute_url()) assert_not_contains(response, MODERATION_FORM_HTML) assert_not_contains(response, MODERATION_FIXED_HTML) def test_category_threads_list_doesnt_show_moderation_to_other_category_moderators( default_category, child_category, user, user_client ): Moderator.objects.create( categories=[default_category.id], user=user, is_global=False, ) response = user_client.get(child_category.get_absolute_url()) assert_not_contains(response, MODERATION_FORM_HTML) assert_not_contains(response, MODERATION_FIXED_HTML) @override_dynamic_settings(index_view="categories") def test_site_threads_list_shows_threads_checkboxes_to_global_moderators( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.get(reverse("misago:threads")) assert_contains(response, thread.title) assert_contains(response, "threads-list-item-col-checkbox") assert_not_contains(response, DISABLED_CHECKBOX_HTML) def test_category_threads_shows_threads_checkboxes_to_global_moderators( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.get(default_category.get_absolute_url()) assert_contains(response, thread.title) assert_contains(response, "threads-list-item-col-checkbox") assert_not_contains(response, DISABLED_CHECKBOX_HTML) @override_dynamic_settings(index_view="categories") def test_site_threads_list_shows_threads_checkboxes_to_category_moderators( default_category, user, user_client ): Moderator.objects.create( categories=[default_category.id], user=user, is_global=False, ) thread = post_thread(default_category, "Moderate Thread") response = user_client.get(reverse("misago:threads")) assert_contains(response, thread.title) assert_contains(response, "threads-list-item-col-checkbox") assert_not_contains(response, DISABLED_CHECKBOX_HTML) def test_category_threads_shows_threads_checkboxes_to_category_moderators( default_category, user, user_client ): Moderator.objects.create( categories=[default_category.id], user=user, is_global=False, ) thread = post_thread(default_category, "Moderate Thread") response = user_client.get(default_category.get_absolute_url()) assert_contains(response, thread.title) assert_contains(response, "threads-list-item-col-checkbox") assert_not_contains(response, DISABLED_CHECKBOX_HTML) @override_dynamic_settings(index_view="categories") def test_site_threads_list_shows_disabled_threads_checkboxes_to_other_category_moderators( default_category, child_category, user, user_client ): Moderator.objects.create( categories=[default_category.id], user=user, is_global=False, ) thread = post_thread(child_category, "Moderate Thread") response = user_client.get(reverse("misago:threads")) assert_contains(response, thread.title) assert_contains(response, "threads-list-item-col-checkbox") assert_contains(response, DISABLED_CHECKBOX_HTML) def test_category_threads_shows_disabled_threads_checkboxes_to_other_category_moderators( default_category, child_category, user, user_client ): Moderator.objects.create( categories=[default_category.id], user=user, is_global=False, ) thread = post_thread(child_category, "Moderate Thread") response = user_client.get(default_category.get_absolute_url()) assert_contains(response, thread.title) assert_contains(response, "threads-list-item-col-checkbox") assert_contains(response, DISABLED_CHECKBOX_HTML) @override_dynamic_settings(index_view="categories") def test_site_threads_list_executes_single_stage_moderation_action( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( reverse("misago:threads"), {"moderation": "close", "threads": [thread.id]}, ) assert response.status_code == 302 assert response["location"] == reverse("misago:threads") thread.refresh_from_db() assert thread.is_closed def test_category_threads_executes_single_stage_moderation_action( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": [thread.id]}, ) assert response.status_code == 302 assert response["location"] == default_category.get_absolute_url() thread.refresh_from_db() assert thread.is_closed @override_dynamic_settings(index_view="categories") def test_site_threads_list_executes_single_stage_moderation_action_in_htmx( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( reverse("misago:threads"), {"moderation": "close", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains(response, thread.title) assert_contains(response, "thread-flags") assert_contains(response, "thread-flag-closed") thread.refresh_from_db() assert thread.is_closed def test_category_threads_executes_single_stage_moderation_action_in_htmx( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains(response, thread.title) assert_contains(response, "thread-flags") assert_contains(response, "thread-flag-closed") thread.refresh_from_db() assert thread.is_closed @override_dynamic_settings(index_view="categories") def test_site_threads_list_executes_multi_stage_moderation_action( default_category, child_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( reverse("misago:threads"), {"moderation": "move", "threads": [thread.id]}, ) assert_contains(response, "Move threads") response = moderator_client.post( reverse("misago:threads"), { "moderation": "move", "threads": [thread.id], "moderation-category": child_category.id, "confirm": "move", }, ) assert response.status_code == 302 assert response["location"] == reverse("misago:threads") thread.refresh_from_db() assert thread.category == child_category def test_category_threads_executes_multi_stage_moderation_action( default_category, child_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "move", "threads": [thread.id]}, ) assert_contains(response, "Move threads") response = moderator_client.post( default_category.get_absolute_url(), { "moderation": "move", "threads": [thread.id], "moderation-category": child_category.id, "confirm": "move", }, ) assert response.status_code == 302 assert response["location"] == default_category.get_absolute_url() thread.refresh_from_db() assert thread.category == child_category @override_dynamic_settings(index_view="categories") def test_site_threads_list_executes_multi_stage_moderation_action_in_htmx( default_category, child_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( reverse("misago:threads"), {"moderation": "move", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains(response, "Move threads") response = moderator_client.post( reverse("misago:threads"), { "moderation": "move", "threads": [thread.id], "moderation-category": child_category.id, "confirm": "move", }, headers={"hx-request": "true"}, ) assert_contains(response, thread.title) thread.refresh_from_db() assert thread.category == child_category def test_category_threads_executes_multi_stage_moderation_action_in_htmx( default_category, child_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "move", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains(response, "Move threads") response = moderator_client.post( default_category.get_absolute_url(), { "moderation": "move", "threads": [thread.id], "moderation-category": child_category.id, "confirm": "move", }, headers={"hx-request": "true"}, ) assert_contains(response, thread.title) thread.refresh_from_db() assert thread.category == child_category @override_dynamic_settings(index_view="categories") def test_site_threads_list_moderation_returns_error_for_user( default_category, user_client ): thread = post_thread(default_category, "Moderate Thread") response = user_client.post( reverse("misago:threads"), {"moderation": "close", "threads": [thread.id]}, ) assert_contains(response, "Invalid moderation action.") thread.refresh_from_db() assert not thread.is_closed def test_category_threads_list_moderation_returns_error_for_user( default_category, user_client ): thread = post_thread(default_category, "Moderate Thread") response = user_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": [thread.id]}, ) assert_contains(response, "Invalid moderation action.") thread.refresh_from_db() assert not thread.is_closed @override_dynamic_settings(index_view="categories") def test_site_threads_list_moderation_returns_error_for_user_in_htmx( default_category, user_client ): thread = post_thread(default_category, "Moderate Thread") response = user_client.post( reverse("misago:threads"), {"moderation": "close", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains(response, "Invalid moderation action.") thread.refresh_from_db() assert not thread.is_closed def test_category_threads_list_moderation_returns_error_for_user_in_htmx( default_category, user_client ): thread = post_thread(default_category, "Moderate Thread") response = user_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains(response, "Invalid moderation action.") thread.refresh_from_db() assert not thread.is_closed @override_dynamic_settings(index_view="categories") def test_site_threads_list_moderation_returns_error_for_guest(default_category, client): thread = post_thread(default_category, "Moderate Thread") response = client.post( reverse("misago:threads"), {"moderation": "close", "threads": [thread.id]}, ) assert_contains(response, "Invalid moderation action.") thread.refresh_from_db() assert not thread.is_closed def test_category_threads_list_moderation_returns_error_for_guest( default_category, client ): thread = post_thread(default_category, "Moderate Thread") response = client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": [thread.id]}, ) assert_contains(response, "Invalid moderation action.") thread.refresh_from_db() assert not thread.is_closed @override_dynamic_settings(index_view="categories") def test_site_threads_list_moderation_returns_error_for_guest_in_htmx( default_category, client ): thread = post_thread(default_category, "Moderate Thread") response = client.post( reverse("misago:threads"), {"moderation": "close", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains(response, "Invalid moderation action.") thread.refresh_from_db() assert not thread.is_closed def test_category_threads_list_moderation_returns_error_for_guest_in_htmx( default_category, client ): thread = post_thread(default_category, "Moderate Thread") response = client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains(response, "Invalid moderation action.") thread.refresh_from_db() assert not thread.is_closed @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_invalid_moderation_action( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( reverse("misago:threads"), {"moderation": "invalid", "threads": [thread.id]}, ) assert_contains(response, "Invalid moderation action.") def test_category_threads_returns_error_for_invalid_moderation_action( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "invalid", "threads": [thread.id]}, ) assert_contains(response, "Invalid moderation action.") @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_invalid_moderation_action_in_htmx( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( reverse("misago:threads"), {"moderation": "invalid", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains(response, "Invalid moderation action.") def test_category_threads_returns_error_for_invalid_moderation_action_in_htmx( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "invalid", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains(response, "Invalid moderation action.") @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_empty_moderation_action( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( reverse("misago:threads"), {"moderation": "", "threads": [thread.id]}, ) assert_contains(response, "Invalid moderation action.") def test_category_threads_returns_error_for_empty_moderation_action( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "", "threads": [thread.id]}, ) assert_contains(response, "Invalid moderation action.") @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_empty_moderation_action_in_htmx( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( reverse("misago:threads"), {"moderation": "", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains(response, "Invalid moderation action.") def test_category_threads_returns_error_for_empty_moderation_action_in_htmx( default_category, moderator_client ): thread = post_thread(default_category, "Moderate Thread") response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains(response, "Invalid moderation action.") @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_empty_threads_selection( default_category, moderator_client ): response = moderator_client.post( reverse("misago:threads"), {"moderation": "close", "threads": []}, ) assert_contains(response, "No valid threads selected.") def test_category_threads_returns_error_for_empty_threads_selection( default_category, moderator_client ): response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": []}, ) assert_contains(response, "No valid threads selected.") @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_empty_threads_selection_in_htmx( default_category, moderator_client ): response = moderator_client.post( reverse("misago:threads"), {"moderation": "close", "threads": []}, headers={"hx-request": "true"}, ) assert_contains(response, "No valid threads selected.") def test_category_threads_returns_error_for_empty_threads_selection_in_htmx( default_category, moderator_client ): response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": []}, headers={"hx-request": "true"}, ) assert_contains(response, "No valid threads selected.") @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_invalid_threads_selection( default_category, moderator_client ): response = moderator_client.post( reverse("misago:threads"), {"moderation": "close", "threads": "invalid"}, ) assert_contains(response, "No valid threads selected.") def test_category_threads_returns_error_for_invalid_threads_selection( default_category, moderator_client ): response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": "invalid"}, ) assert_contains(response, "No valid threads selected.") @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_invalid_threads_selection_in_htmx( default_category, moderator_client ): response = moderator_client.post( reverse("misago:threads"), {"moderation": "close", "threads": "invalid"}, headers={"hx-request": "true"}, ) assert_contains(response, "No valid threads selected.") def test_category_threads_returns_error_for_invalid_threads_selection_in_htmx( default_category, moderator_client ): response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": "invalid"}, headers={"hx-request": "true"}, ) assert_contains(response, "No valid threads selected.") @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_invalid_threads_ids_in_selection( default_category, moderator_client ): response = moderator_client.post( reverse("misago:threads"), {"moderation": "close", "threads": ["invalid"]}, ) assert_contains(response, "No valid threads selected.") def test_category_threads_returns_error_for_invalid_threads_ids_in_selection( default_category, moderator_client ): response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": ["invalid"]}, ) assert_contains(response, "No valid threads selected.") @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_invalid_threads_ids_in_selection_in_htmx( default_category, moderator_client ): response = moderator_client.post( reverse("misago:threads"), {"moderation": "close", "threads": ["invalid"]}, headers={"hx-request": "true"}, ) assert_contains(response, "No valid threads selected.") def test_category_threads_returns_error_for_invalid_threads_ids_in_selection_in_htmx( default_category, moderator_client ): response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": ["invalid"]}, headers={"hx-request": "true"}, ) assert_contains(response, "No valid threads selected.") @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_not_existing_threads_ids_in_selection( default_category, moderator_client ): response = moderator_client.post( reverse("misago:threads"), {"moderation": "close", "threads": [42]}, ) assert_contains(response, "No valid threads selected.") def test_category_threads_returns_error_for_not_existing_threads_ids_in_selection( default_category, moderator_client ): response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": [42]}, ) assert_contains(response, "No valid threads selected.") @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_not_existing_threads_ids_in_selection_in_htmx( default_category, moderator_client ): response = moderator_client.post( reverse("misago:threads"), {"moderation": "close", "threads": [42]}, headers={"hx-request": "true"}, ) assert_contains(response, "No valid threads selected.") def test_category_threads_returns_error_for_not_existing_threads_ids_in_selection_in_htmx( default_category, moderator_client ): response = moderator_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": [42]}, headers={"hx-request": "true"}, ) assert_contains(response, "No valid threads selected.") @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_thread_in_selection_user_cant_moderate( default_category, child_category, user, user_client ): Moderator.objects.create( categories=[default_category.id], user=user, is_global=False, ) thread = post_thread(child_category, "Moderated Thread") response = user_client.post( reverse("misago:threads"), {"moderation": "close", "threads": [thread.id]}, ) assert_contains( response, "Can&#x27;t moderate the &quot;Moderated Thread&quot; thread", ) thread.refresh_from_db() assert not thread.is_closed @override_dynamic_settings(index_view="categories") def test_category_threads_list_returns_error_for_thread_in_selection_user_cant_moderate( default_category, child_category, user, user_client ): Moderator.objects.create( categories=[default_category.id], user=user, is_global=False, ) thread = post_thread(child_category, "Moderated Thread") response = user_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": [thread.id]}, ) assert_contains( response, "Can&#x27;t moderate the &quot;Moderated Thread&quot; thread", ) thread.refresh_from_db() assert not thread.is_closed @override_dynamic_settings(index_view="categories") def test_site_threads_list_returns_error_for_thread_in_selection_user_cant_moderate_in_htmx( default_category, child_category, user, user_client ): Moderator.objects.create( categories=[default_category.id], user=user, is_global=False, ) thread = post_thread(child_category, "Moderated Thread") response = user_client.post( reverse("misago:threads"), {"moderation": "close", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains( response, "Can&#x27;t moderate the &quot;Moderated Thread&quot; thread", ) thread.refresh_from_db() assert not thread.is_closed @override_dynamic_settings(index_view="categories") def test_category_threads_list_returns_error_for_thread_in_selection_user_cant_moderate_in_htmx( default_category, child_category, user, user_client ): Moderator.objects.create( categories=[default_category.id], user=user, is_global=False, ) thread = post_thread(child_category, "Moderated Thread") response = user_client.post( default_category.get_absolute_url(), {"moderation": "close", "threads": [thread.id]}, headers={"hx-request": "true"}, ) assert_contains( response, "Can&#x27;t moderate the &quot;Moderated Thread&quot; thread", ) thread.refresh_from_db() assert not thread.is_closed
27,822
Python
.py
684
35.209064
96
0.706258
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,115
test_search.py
rafalp_Misago/misago/threads/tests/test_search.py
from django.urls import reverse from .. import test from ...categories.models import Category from ...users.test import AuthenticatedUserTestCase def index_post(post): if post.id == post.thread.first_post_id: post.set_search_document(post.thread.title) else: post.set_search_document() post.save(update_fields=["search_document"]) post.update_search_vector() post.save(update_fields=["search_vector"]) class SearchApiTests(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.get(slug="first-category") self.api_link = reverse("misago:api:search") def test_no_query(self): """api handles no search query""" response = self.client.get(self.api_link) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertIn("threads", [p["id"] for p in reponse_json]) for provider in reponse_json: if provider["id"] == "threads": self.assertEqual(provider["results"]["results"], []) def test_empty_query(self): """api handles empty search query""" response = self.client.get("%s?q=" % self.api_link) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertIn("threads", [p["id"] for p in reponse_json]) for provider in reponse_json: if provider["id"] == "threads": self.assertEqual(provider["results"]["results"], []) def test_short_query(self): """api handles short search query""" thread = test.post_thread(self.category) post = test.reply_thread(thread, message="Lorem ipsum dolor.") index_post(post) response = self.client.get("%s?q=ip" % self.api_link) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertIn("threads", [p["id"] for p in reponse_json]) for provider in reponse_json: if provider["id"] == "threads": self.assertEqual(provider["results"]["results"], []) def test_wrong_query(self): """api handles query miss""" thread = test.post_thread(self.category) post = test.reply_thread(thread, message="Lorem ipsum dolor.") index_post(post) response = self.client.get("%s?q=elit" % self.api_link) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertIn("threads", [p["id"] for p in reponse_json]) for provider in reponse_json: if provider["id"] == "threads": self.assertEqual(provider["results"]["results"], []) def test_hidden_post(self): """hidden posts are extempt from search""" thread = test.post_thread(self.category) post = test.reply_thread(thread, message="Lorem ipsum dolor.", is_hidden=True) index_post(post) response = self.client.get("%s?q=ipsum" % self.api_link) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertIn("threads", [p["id"] for p in reponse_json]) for provider in reponse_json: if provider["id"] == "threads": self.assertEqual(provider["results"]["results"], []) def test_unapproved_post(self): """unapproves posts are extempt from search""" thread = test.post_thread(self.category) post = test.reply_thread( thread, message="Lorem ipsum dolor.", is_unapproved=True ) index_post(post) response = self.client.get("%s?q=ipsum" % self.api_link) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertIn("threads", [p["id"] for p in reponse_json]) for provider in reponse_json: if provider["id"] == "threads": self.assertEqual(provider["results"]["results"], []) def test_query(self): """api handles search query""" thread = test.post_thread(self.category) post = test.reply_thread(thread, message="Lorem ipsum dolor.") index_post(post) response = self.client.get("%s?q=ipsum" % self.api_link) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertIn("threads", [p["id"] for p in reponse_json]) for provider in reponse_json: if provider["id"] == "threads": results = provider["results"]["results"] self.assertEqual(len(results), 1) self.assertEqual(results[0]["id"], post.id) def test_thread_title_search(self): """api searches threads by title""" thread = test.post_thread(self.category, title="Atmosphere of mars") index_post(thread.first_post) post = test.reply_thread(thread, message="Lorem ipsum dolor.") index_post(post) response = self.client.get("%s?q=mars atmosphere" % self.api_link) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertIn("threads", [p["id"] for p in reponse_json]) for provider in reponse_json: if provider["id"] == "threads": results = provider["results"]["results"] self.assertEqual(len(results), 1) self.assertEqual(results[0]["id"], thread.first_post_id) def test_complex_query(self): """api handles complex query that uses fulltext search facilities""" thread = test.post_thread(self.category) post = test.reply_thread(thread, message="Atmosphere of Mars") index_post(post) response = self.client.get("%s?q=Mars atmosphere" % self.api_link) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertIn("threads", [p["id"] for p in reponse_json]) for provider in reponse_json: if provider["id"] == "threads": results = provider["results"]["results"] self.assertEqual(len(results), 1) self.assertEqual(results[0]["id"], post.id) def test_filtered_query(self): """search filters are used by search system""" thread = test.post_thread(self.category) post = test.reply_thread( thread, message="You just do MMM in 4th minute and its pwnt" ) index_post(post) response = self.client.get("%s?q=MMM" % self.api_link) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertIn("threads", [p["id"] for p in reponse_json]) for provider in reponse_json: if provider["id"] == "threads": results = provider["results"]["results"] self.assertEqual(len(results), 1) self.assertEqual(results[0]["id"], post.id) response = self.client.get("%s?q=Marines Medics" % self.api_link) self.assertEqual(response.status_code, 200) for provider in reponse_json: if provider["id"] == "threads": results = provider["results"]["results"] self.assertEqual(len(results), 1) self.assertEqual(results[0]["id"], post.id) class SearchProviderApiTests(SearchApiTests): def setUp(self): super().setUp() self.api_link = reverse( "misago:api:search", kwargs={"search_provider": "threads"} ) def test_post_search_filters_hook_is_used_by_threads_search( db, user_client, mocker, thread ): def search_filter(search): return search.replace("apple phone", "iphone") mocker.patch( "misago.threads.filtersearch.hooks.post_search_filters", [search_filter] ) post = test.reply_thread(thread, message="Lorem ipsum iphone dolor met.") index_post(post) response = user_client.get("/api/search/?q=apple phone") reponse_json = response.json() assert "threads" in [p["id"] for p in reponse_json] for provider in reponse_json: if provider["id"] == "threads": results = provider["results"]["results"] assert len(results) == 1 assert results[0]["id"] == post.id
8,322
Python
.py
175
37.897143
86
0.61684
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,116
test_thread_postedits_api.py
rafalp_Misago/misago/threads/tests/test_thread_postedits_api.py
from django.urls import reverse from .. import test from ..test import patch_category_acl from .test_threads_api import ThreadsApiTestCase class ThreadPostEditsApiTestCase(ThreadsApiTestCase): def setUp(self): super().setUp() self.post = test.reply_thread(self.thread, poster=self.user) self.api_link = reverse( "misago:api:thread-post-edits", kwargs={"thread_pk": self.thread.pk, "pk": self.post.pk}, ) def mock_edit_record(self): edits_record = [ self.post.edits_record.create( category=self.category, thread=self.thread, editor=self.user, editor_name=self.user.username, editor_slug=self.user.slug, edited_from="Original body", edited_to="First Edit", ), self.post.edits_record.create( category=self.category, thread=self.thread, editor_name="Deleted", editor_slug="deleted", edited_from="First Edit", edited_to="Second Edit", ), self.post.edits_record.create( category=self.category, thread=self.thread, editor=self.user, editor_name=self.user.username, editor_slug=self.user.slug, edited_from="Second Edit", edited_to="Last Edit", ), ] self.post.original = "Last Edit" self.post.parsed = "<p>Last Edit</p>" self.post.save() return edits_record class ThreadPostGetEditTests(ThreadPostEditsApiTestCase): def test_no_edits(self): """api returns 403 if post has no edits record""" response = self.client.get(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This post has no changes history."} ) self.logout_user() response = self.client.get(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This post has no changes history."} ) def test_empty_edit_id(self): """api handles empty edit in querystring""" response = self.client.get("%s?edit=" % self.api_link) self.assertEqual(response.status_code, 404) def test_invalid_edit_id(self): """api handles invalid edit in querystring""" response = self.client.get("%s?edit=dsa67d8sa68" % self.api_link) self.assertEqual(response.status_code, 404) def test_nonexistant_edit_id(self): """api handles nonexistant edit in querystring""" response = self.client.get("%s?edit=1321" % self.api_link) self.assertEqual(response.status_code, 404) def test_get_last_edit(self): """api returns last edit record""" edits = self.mock_edit_record() response = self.client.get(self.api_link) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["id"], edits[-1].id) self.assertIsNone(response_json["next"]) self.assertEqual(response_json["previous"], edits[1].id) def test_get_middle_edit(self): """api returns middle edit record""" edits = self.mock_edit_record() response = self.client.get("%s?edit=%s" % (self.api_link, edits[1].id)) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["id"], edits[1].id) self.assertEqual(response_json["next"], edits[-1].id) self.assertEqual(response_json["previous"], edits[0].id) def test_get_first_edit(self): """api returns middle edit record""" edits = self.mock_edit_record() response = self.client.get("%s?edit=%s" % (self.api_link, edits[0].id)) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["id"], edits[0].id) self.assertEqual(response_json["next"], edits[1].id) self.assertIsNone(response_json["previous"]) class ThreadPostPostEditTests(ThreadPostEditsApiTestCase): def setUp(self): super().setUp() self.edits = self.mock_edit_record() @patch_category_acl({"can_edit_posts": 2}) def test_empty_edit_id(self): """api handles empty edit in querystring""" response = self.client.post("%s?edit=" % self.api_link) self.assertEqual(response.status_code, 404) @patch_category_acl({"can_edit_posts": 2}) def test_invalid_edit_id(self): """api handles invalid edit in querystring""" response = self.client.post("%s?edit=dsa67d8sa68" % self.api_link) self.assertEqual(response.status_code, 404) @patch_category_acl({"can_edit_posts": 2}) def test_nonexistant_edit_id(self): """api handles nonexistant edit in querystring""" response = self.client.post("%s?edit=1321" % self.api_link) self.assertEqual(response.status_code, 404) def test_anonymous(self): """only signed in users can rever ports""" self.logout_user() response = self.client.post("%s?edit=%s" % (self.api_link, self.edits[0].id)) self.assertEqual(response.status_code, 403) @patch_category_acl({"can_edit_posts": 0}) def test_no_permission(self): """api validates permission to revert post""" response = self.client.post("%s?edit=1321" % self.api_link) self.assertEqual(response.status_code, 403) @patch_category_acl({"can_edit_posts": 2}) def test_revert_post(self): """api reverts post to version from before specified edit""" response = self.client.post("%s?edit=%s" % (self.api_link, self.edits[0].id)) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["edits"], 1) self.assertEqual(response_json["content"], "<p>Original body</p>") self.assertEqual(self.post.edits_record.count(), 4) edit = self.post.edits_record.first() self.assertEqual(edit.edited_from, self.post.original) self.assertEqual(edit.edited_to, "Original body")
6,413
Python
.py
139
36.42446
85
0.622614
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,117
test_utils.py
rafalp_Misago/misago/threads/tests/test_utils.py
from django.test import TestCase from .. import test from ...categories.models import Category from ..utils import add_categories_to_items, get_thread_id_from_url class AddCategoriesToItemsTests(TestCase): def setUp(self): """ Create categories tree for test cases: First category (created by migration) Category A + Category B + Subcategory C + Subcategory D Category E + Subcategory F """ super().setUp() self.root = Category.objects.root_category() Category( name="Category A", slug="category-a", css_class="showing-category-a" ).insert_at(self.root, position="last-child", save=True) Category( name="Category E", slug="category-e", css_class="showing-category-e" ).insert_at(self.root, position="last-child", save=True) self.root = Category.objects.root_category() self.category_a = Category.objects.get(slug="category-a") Category( name="Category B", slug="category-b", css_class="showing-category-b" ).insert_at(self.category_a, position="last-child", save=True) self.category_b = Category.objects.get(slug="category-b") Category( name="Category C", slug="category-c", css_class="showing-category-c" ).insert_at(self.category_b, position="last-child", save=True) Category( name="Category D", slug="category-d", css_class="showing-category-d" ).insert_at(self.category_b, position="last-child", save=True) self.category_c = Category.objects.get(slug="category-c") self.category_d = Category.objects.get(slug="category-d") self.category_e = Category.objects.get(slug="category-e") Category( name="Category F", slug="category-f", css_class="showing-category-f" ).insert_at(self.category_e, position="last-child", save=True) Category.objects.partial_rebuild(self.root.tree_id) self.root = Category.objects.root_category() self.category_a = Category.objects.get(slug="category-a") self.category_b = Category.objects.get(slug="category-b") self.category_c = Category.objects.get(slug="category-c") self.category_d = Category.objects.get(slug="category-d") self.category_e = Category.objects.get(slug="category-e") self.category_f = Category.objects.get(slug="category-f") self.categories = list(Category.objects.all_categories(include_root=True)) def test_root_thread_from_root(self): """thread in root category is handled""" thread = test.post_thread(category=self.root) add_categories_to_items(self.root, self.categories, [thread]) self.assertEqual(thread.category, self.root) def test_root_thread_from_elsewhere(self): """thread in root category is handled""" thread = test.post_thread(category=self.root) add_categories_to_items(self.category_e, self.categories, [thread]) self.assertEqual(thread.category, self.root) def test_direct_child_thread_from_parent(self): """thread in direct child category is handled""" thread = test.post_thread(category=self.category_e) add_categories_to_items(self.root, self.categories, [thread]) self.assertEqual(thread.category, self.category_e) def test_direct_child_thread_from_elsewhere(self): """thread in direct child category is handled""" thread = test.post_thread(category=self.category_e) add_categories_to_items(self.category_b, self.categories, [thread]) self.assertEqual(thread.category, self.category_e) def test_child_thread_from_root(self): """thread in child category is handled""" thread = test.post_thread(category=self.category_d) add_categories_to_items(self.root, self.categories, [thread]) self.assertEqual(thread.category, self.category_d) def test_child_thread_from_parent(self): """thread in child category is handled""" thread = test.post_thread(category=self.category_d) add_categories_to_items(self.category_a, self.categories, [thread]) self.assertEqual(thread.category, self.category_d) def test_child_thread_from_category(self): """thread in child category is handled""" thread = test.post_thread(category=self.category_d) add_categories_to_items(self.category_d, self.categories, [thread]) self.assertEqual(thread.category, self.category_d) def test_child_thread_from_elsewhere(self): """thread in child category is handled""" thread = test.post_thread(category=self.category_d) add_categories_to_items(self.category_f, self.categories, [thread]) self.assertEqual(thread.category, self.category_d) class MockRequest: def __init__(self, scheme, host, wsgialias=""): self.scheme = scheme self.host = host self.path_info = "/api/threads/123/merge/" self.path = "%s%s" % (wsgialias.rstrip("/"), self.path_info) def get_host(self): return self.host def is_secure(self): return self.scheme == "https" class GetThreadIdFromUrlTests(TestCase): def test_get_thread_id_from_valid_urls(self): """get_thread_id_from_url extracts thread pk from valid urls""" TEST_CASES = [ { # perfect match "request": MockRequest("https", "testforum.com", "/discuss/"), "url": "https://testforum.com/discuss/t/test-thread/123/", "pk": 123, }, { # we don't validate scheme in case site recently moved to https # but user still has old url's saved somewhere "request": MockRequest("http", "testforum.com", "/discuss/"), "url": "http://testforum.com/discuss/t/test-thread/432/post/12321/", "pk": 432, }, { # extract thread id from other thread urls "request": MockRequest("https", "testforum.com", "/discuss/"), "url": "http://testforum.com/discuss/t/test-thread/432/post/12321/", "pk": 432, }, { # extract thread id from thread page url "request": MockRequest("http", "testforum.com", "/discuss/"), "url": "http://testforum.com/discuss/t/test-thread/432/123/", "pk": 432, }, { # extract thread id from thread last post url with relative schema "request": MockRequest("http", "testforum.com", "/discuss/"), "url": "//testforum.com/discuss/t/test-thread/18/last/", "pk": 18, }, { # extract thread id from url that lacks scheme "request": MockRequest("http", "testforum.com", ""), "url": "testforum.com/t/test-thread/12/last/", "pk": 12, }, { # extract thread id from schemaless thread last post url "request": MockRequest("http", "testforum.com", "/discuss/"), "url": "testforum.com/discuss/t/test-thread/18/last/", "pk": 18, }, { # extract thread id from url that lacks scheme and hostname "request": MockRequest("http", "testforum.com", ""), "url": "/t/test-thread/13/", "pk": 13, }, { # extract thread id from url that has port name "request": MockRequest("http", "127.0.0.1:8000", ""), "url": "https://127.0.0.1:8000/t/test-thread/13/", "pk": 13, }, { # extract thread id from url that isn't trimmed "request": MockRequest("http", "127.0.0.1:8000", ""), "url": " /t/test-thread/13/ ", "pk": 13, }, ] for case in TEST_CASES: pk = get_thread_id_from_url(case["request"], case["url"]) self.assertEqual( pk, case["pk"], "get_thread_id_from_url for %(url)s should return %(pk)s" % case, ) def test_get_thread_id_from_invalid_urls(self): TEST_CASES = [ { # lacking wsgi alias "request": MockRequest("https", "testforum.com"), "url": "http://testforum.com/discuss/t/test-thread-123/", }, { # invalid wsgi alias "request": MockRequest("https", "testforum.com", "/discuss/"), "url": "http://testforum.com/forum/t/test-thread-123/", }, { # invalid hostname "request": MockRequest("http", "misago-project.org", "/discuss/"), "url": "https://testforum.com/discuss/t/test-thread-432/post/12321/", }, { # old thread url "request": MockRequest("http", "testforum.com"), "url": "https://testforum.com/thread/test-123/", }, { # dashed thread url "request": MockRequest("http", "testforum.com"), "url": "https://testforum.com/t/test-thread-123/", }, { # non-thread url "request": MockRequest("http", "testforum.com"), "url": "https://testforum.com/user/user-123/", }, { # rubbish url "request": MockRequest("http", "testforum.com"), "url": "asdsadsasadsaSA&das8as*S(A*sa", }, { # blank url "request": MockRequest("http", "testforum.com"), "url": "/", }, { # empty url "request": MockRequest("http", "testforum.com"), "url": "", }, ] for case in TEST_CASES: pk = get_thread_id_from_url(case["request"], case["url"]) self.assertIsNone( pk, "get_thread_id_from_url for %s should fail" % case["url"] )
10,460
Python
.py
227
33.9163
85
0.560495
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,118
test_threads_list_read_category.py
rafalp_Misago/misago/threads/tests/test_threads_list_read_category.py
from datetime import timedelta from django.utils import timezone from ...readtracker.models import ReadCategory, ReadThread from ..test import post_thread def test_unread_category_without_unread_threads_is_marked_read( default_category, user, user_client ): user.joined_on -= timedelta(minutes=60) user.save() threads = ( post_thread( default_category, started_on=timezone.now() - timedelta(minutes=40), ), post_thread( default_category, started_on=timezone.now() - timedelta(minutes=20), ), ) for thread in threads: ReadThread.objects.create( user=user, category=default_category, thread=thread, read_time=thread.last_post_on, ) default_category.synchronize() default_category.save() response = user_client.get(default_category.get_absolute_url()) assert response.status_code == 200 assert not ReadThread.objects.exists() ReadCategory.objects.get(user=user, category=default_category) def test_unread_category_read_entry_without_unread_threads_is_marked_read( default_category, user, user_client ): user.joined_on -= timedelta(minutes=60) user.save() post_thread( default_category, started_on=timezone.now() - timedelta(minutes=40), ) read_category = ReadCategory.objects.create( user=user, category=default_category, read_time=timezone.now() - timedelta(minutes=30), ) read_thread = post_thread( default_category, started_on=timezone.now() - timedelta(minutes=20), ) ReadThread.objects.create( user=user, category=default_category, thread=read_thread, read_time=read_thread.last_post_on, ) default_category.synchronize() default_category.save() response = user_client.get(default_category.get_absolute_url()) assert response.status_code == 200 assert not ReadThread.objects.exists() new_read_category = ReadCategory.objects.get(user=user, category=default_category) assert new_read_category.id == read_category.id assert new_read_category.read_time > read_category.read_time def test_unread_category_with_unread_thread_is_not_marked_read( default_category, user, user_client ): user.joined_on -= timedelta(minutes=60) user.save() read_thread = post_thread( default_category, started_on=timezone.now() - timedelta(minutes=40), ) ReadThread.objects.create( user=user, category=default_category, thread=read_thread, read_time=read_thread.last_post_on, ) post_thread( default_category, started_on=timezone.now() - timedelta(minutes=20), ) default_category.synchronize() default_category.save() response = user_client.get(default_category.get_absolute_url()) assert response.status_code == 200 assert ReadThread.objects.exists() assert not ReadCategory.objects.exists()
3,075
Python
.py
89
27.842697
86
0.679851
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,119
test_thread_postmerge_api.py
rafalp_Misago/misago/threads/tests/test_thread_postmerge_api.py
import json from django.urls import reverse from .. import test from ...categories.models import Category from ...conf.test import override_dynamic_settings from ...users.test import AuthenticatedUserTestCase from ..models import Post from ..test import patch_category_acl class ThreadPostMergeApiTestCase(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.get(slug="first-category") self.thread = test.post_thread(category=self.category) self.post = test.reply_thread(self.thread, poster=self.user) self.api_link = reverse( "misago:api:thread-post-merge", kwargs={"thread_pk": self.thread.pk} ) def test_anonymous_user(self): """you need to authenticate to merge posts""" self.logout_user() response = self.client.post( self.api_link, json.dumps({}), content_type="application/json" ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This action is not available to guests."} ) @patch_category_acl({"can_merge_posts": False}) def test_no_permission(self): """api validates permission to merge""" response = self.client.post( self.api_link, json.dumps({}), content_type="application/json" ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't merge posts in this thread."} ) @patch_category_acl({"can_merge_posts": True}) def test_empty_data_json(self): """api handles empty json data""" response = self.client.post( self.api_link, json.dumps({}), content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You have to select at least two posts to merge."}, ) @patch_category_acl({"can_merge_posts": True}) def test_empty_data_form(self): """api handles empty form data""" response = self.client.post(self.api_link, {}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You have to select at least two posts to merge."}, ) @patch_category_acl({"can_merge_posts": True}) def test_invalid_data(self): """api handles post that is invalid type""" response = self.client.post( self.api_link, "[]", content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Invalid data. Expected a dictionary, but got list."}, ) response = self.client.post( self.api_link, "123", content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Invalid data. Expected a dictionary, but got int."}, ) response = self.client.post( self.api_link, '"string"', content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Invalid data. Expected a dictionary, but got str."}, ) response = self.client.post( self.api_link, "malformed", content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)"}, ) @patch_category_acl({"can_merge_posts": True}) def test_no_posts_ids(self): """api rejects no posts ids""" response = self.client.post( self.api_link, json.dumps({"posts": []}), content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You have to select at least two posts to merge."}, ) @patch_category_acl({"can_merge_posts": True}) def test_invalid_posts_data(self): """api handles invalid data""" response = self.client.post( self.api_link, json.dumps({"posts": "string"}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": 'Expected a list of items but got type "str".'} ) @patch_category_acl({"can_merge_posts": True}) def test_invalid_posts_ids(self): """api handles invalid post id""" response = self.client.post( self.api_link, json.dumps({"posts": [1, 2, "string"]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "One or more post ids received were invalid."} ) @patch_category_acl({"can_merge_posts": True}) def test_one_post_id(self): """api rejects one post id""" response = self.client.post( self.api_link, json.dumps({"posts": [1]}), content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You have to select at least two posts to merge."}, ) @override_dynamic_settings(posts_per_page=5, posts_per_page_orphans=3) @patch_category_acl({"can_merge_posts": True}) def test_merge_limit(self): """api rejects more posts than merge limit""" response = self.client.post( self.api_link, json.dumps({"posts": list(range(9))}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "No more than 8 posts can be merged at a single time."}, ) @patch_category_acl({"can_merge_posts": True}) def test_merge_event(self): """api recjects events""" event = test.reply_thread(self.thread, is_event=True, poster=self.user) response = self.client.post( self.api_link, json.dumps({"posts": [self.post.pk, event.pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"detail": "Events can't be merged."}) @patch_category_acl({"can_merge_posts": True}) def test_merge_notfound_pk(self): """api recjects nonexistant pk's""" response = self.client.post( self.api_link, json.dumps({"posts": [self.post.pk, self.post.pk * 1000]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "One or more posts to merge could not be found."}, ) @patch_category_acl({"can_merge_posts": True}) def test_merge_cross_threads(self): """api recjects attempt to merge with post made in other thread""" other_thread = test.post_thread(category=self.category) other_post = test.reply_thread(other_thread, poster=self.user) response = self.client.post( self.api_link, json.dumps({"posts": [self.post.pk, other_post.pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "One or more posts to merge could not be found."}, ) @patch_category_acl({"can_merge_posts": True}) def test_merge_authenticated_with_guest_post(self): """api recjects attempt to merge with post made by deleted user""" other_post = test.reply_thread(self.thread) response = self.client.post( self.api_link, json.dumps({"posts": [self.post.pk, other_post.pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Posts made by different users can't be merged."}, ) @patch_category_acl({"can_merge_posts": True}) def test_merge_guest_with_authenticated_post(self): """api recjects attempt to merge with post made by deleted user""" other_post = test.reply_thread(self.thread) response = self.client.post( self.api_link, json.dumps({"posts": [other_post.pk, self.post.pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Posts made by different users can't be merged."}, ) @patch_category_acl({"can_merge_posts": True}) def test_merge_guest_posts_different_usernames(self): """api recjects attempt to merge posts made by different guests""" response = self.client.post( self.api_link, json.dumps( { "posts": [ test.reply_thread(self.thread, poster="Bob").pk, test.reply_thread(self.thread, poster="Miku").pk, ] } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Posts made by different users can't be merged."}, ) @patch_category_acl({"can_merge_posts": True, "can_hide_posts": 1}) def test_merge_different_visibility(self): """api recjects attempt to merge posts with different visibility""" response = self.client.post( self.api_link, json.dumps( { "posts": [ test.reply_thread( self.thread, poster=self.user, is_hidden=True ).pk, test.reply_thread( self.thread, poster=self.user, is_hidden=False ).pk, ] } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Posts with different visibility can't be merged."}, ) @patch_category_acl({"can_merge_posts": True, "can_approve_content": True}) def test_merge_different_approval(self): """api recjects attempt to merge posts with different approval""" response = self.client.post( self.api_link, json.dumps( { "posts": [ test.reply_thread( self.thread, poster=self.user, is_unapproved=True ).pk, test.reply_thread( self.thread, poster=self.user, is_unapproved=False ).pk, ] } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Posts with different visibility can't be merged."}, ) @patch_category_acl({"can_merge_posts": True, "can_close_threads": False}) def test_closed_thread_no_permission(self): """api validates permission to merge in closed thread""" self.thread.is_closed = True self.thread.save() posts = [ test.reply_thread(self.thread, poster=self.user).pk, test.reply_thread(self.thread, poster=self.user).pk, ] response = self.client.post( self.api_link, json.dumps({"posts": posts}), content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "This thread is closed. You can't merge posts in it."}, ) @patch_category_acl({"can_merge_posts": True, "can_close_threads": True}) def test_closed_thread(self): """api validates permission to merge in closed thread""" self.thread.is_closed = True self.thread.save() posts = [ test.reply_thread(self.thread, poster=self.user).pk, test.reply_thread(self.thread, poster=self.user).pk, ] response = self.client.post( self.api_link, json.dumps({"posts": posts}), content_type="application/json" ) self.assertEqual(response.status_code, 200) @patch_category_acl({"can_merge_posts": True, "can_close_threads": False}) def test_closed_category_no_permission(self): """api validates permission to merge in closed category""" self.category.is_closed = True self.category.save() posts = [ test.reply_thread(self.thread, poster=self.user).pk, test.reply_thread(self.thread, poster=self.user).pk, ] response = self.client.post( self.api_link, json.dumps({"posts": posts}), content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "This category is closed. You can't merge posts in it."}, ) @patch_category_acl({"can_merge_posts": True, "can_close_threads": True}) def test_closed_category(self): """api validates permission to merge in closed category""" self.category.is_closed = True self.category.save() posts = [ test.reply_thread(self.thread, poster=self.user).pk, test.reply_thread(self.thread, poster=self.user).pk, ] response = self.client.post( self.api_link, json.dumps({"posts": posts}), content_type="application/json" ) self.assertEqual(response.status_code, 200) @patch_category_acl({"can_merge_posts": True}) def test_merge_best_answer_first_post(self): """api recjects attempt to merge best_answer with first post""" self.thread.first_post.poster = self.user self.thread.first_post.save() self.post.poster = self.user self.post.save() self.thread.set_best_answer(self.user, self.post) self.thread.save() response = self.client.post( self.api_link, json.dumps({"posts": [self.thread.first_post.pk, self.post.pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "detail": ( "Post marked as best answer can't be " "merged with thread's first post." ) }, ) @patch_category_acl({"can_merge_posts": True}) def test_merge_posts(self): """api merges two posts""" post_a = test.reply_thread(self.thread, poster=self.user, message="Battęry") post_b = test.reply_thread(self.thread, poster=self.user, message="Hórse") thread_replies = self.thread.replies response = self.client.post( self.api_link, json.dumps({"posts": [post_a.pk, post_b.pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 200) self.thread.refresh_from_db() self.assertEqual(self.thread.replies, thread_replies - 1) with self.assertRaises(Post.DoesNotExist): Post.objects.get(pk=post_b.pk) merged_post = Post.objects.get(pk=post_a.pk) self.assertEqual(merged_post.parsed, "%s\n%s" % (post_a.parsed, post_b.parsed)) @patch_category_acl({"can_merge_posts": True}) def test_merge_guest_posts(self): """api recjects attempt to merge posts made by same guest""" response = self.client.post( self.api_link, json.dumps( { "posts": [ test.reply_thread(self.thread, poster="Bob").pk, test.reply_thread(self.thread, poster="Bob").pk, ] } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) @patch_category_acl({"can_merge_posts": True, "can_hide_posts": 1}) def test_merge_hidden_posts(self): """api merges two hidden posts""" response = self.client.post( self.api_link, json.dumps( { "posts": [ test.reply_thread( self.thread, poster=self.user, is_hidden=True ).pk, test.reply_thread( self.thread, poster=self.user, is_hidden=True ).pk, ] } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) @patch_category_acl({"can_merge_posts": True, "can_approve_content": True}) def test_merge_unapproved_posts(self): """api merges two unapproved posts""" response = self.client.post( self.api_link, json.dumps( { "posts": [ test.reply_thread( self.thread, poster=self.user, is_unapproved=True ).pk, test.reply_thread( self.thread, poster=self.user, is_unapproved=True ).pk, ] } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) @patch_category_acl({"can_merge_posts": True, "can_hide_threads": True}) def test_merge_with_hidden_thread(self): """api excludes thread's first post from visibility checks""" self.thread.first_post.is_hidden = True self.thread.first_post.poster = self.user self.thread.first_post.save() post_visible = test.reply_thread(self.thread, poster=self.user, is_hidden=False) response = self.client.post( self.api_link, json.dumps({"posts": [self.thread.first_post.pk, post_visible.pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 200) @patch_category_acl({"can_merge_posts": True}) def test_merge_protected(self): """api preserves protected status after merge""" response = self.client.post( self.api_link, json.dumps( { "posts": [ test.reply_thread( self.thread, poster="Bob", is_protected=True ).pk, test.reply_thread( self.thread, poster="Bob", is_protected=False ).pk, ] } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) merged_post = self.thread.post_set.order_by("-id")[0] self.assertTrue(merged_post.is_protected) @patch_category_acl({"can_merge_posts": True}) def test_merge_best_answer(self): """api merges best answer with other post""" best_answer = test.reply_thread(self.thread, poster="Bob") self.thread.set_best_answer(self.user, best_answer) self.thread.save() response = self.client.post( self.api_link, json.dumps( { "posts": [ best_answer.pk, test.reply_thread(self.thread, poster="Bob").pk, ] } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) self.thread.refresh_from_db() self.assertEqual(self.thread.best_answer, best_answer) @patch_category_acl({"can_merge_posts": True}) def test_merge_best_answer_in(self): """api merges best answer into other post""" other_post = test.reply_thread(self.thread, poster="Bob") best_answer = test.reply_thread(self.thread, poster="Bob") self.thread.set_best_answer(self.user, best_answer) self.thread.save() response = self.client.post( self.api_link, json.dumps({"posts": [best_answer.pk, other_post.pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 200) self.thread.refresh_from_db() self.assertEqual(self.thread.best_answer, other_post) @patch_category_acl({"can_merge_posts": True}) def test_merge_best_answer_in_protected(self): """api merges best answer into protected post""" best_answer = test.reply_thread(self.thread, poster="Bob") self.thread.set_best_answer(self.user, best_answer) self.thread.save() response = self.client.post( self.api_link, json.dumps( { "posts": [ best_answer.pk, test.reply_thread( self.thread, poster="Bob", is_protected=True ).pk, ] } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) self.thread.refresh_from_db() self.assertEqual(self.thread.best_answer, best_answer) self.thread.best_answer.refresh_from_db() self.assertTrue(self.thread.best_answer.is_protected) self.assertTrue(self.thread.best_answer_is_protected) @patch_category_acl({"can_merge_posts": True}) def test_merge_remove_reads(self): """two posts merge removes read tracker from post""" post_a = test.reply_thread(self.thread, poster=self.user, message="Battęry") post_b = test.reply_thread(self.thread, poster=self.user, message="Hórse") poststracker.save_read(self.user, post_a) poststracker.save_read(self.user, post_b) response = self.client.post( self.api_link, json.dumps({"posts": [post_a.pk, post_b.pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 200) # both post's were removed from readtracker self.assertEqual(self.user.postread_set.count(), 0)
23,286
Python
.py
557
30.308797
88
0.567076
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,120
test_participants.py
rafalp_Misago/misago/threads/tests/test_participants.py
from django.test import TestCase from django.utils import timezone from ...categories.models import Category from ...users.test import create_test_user from ..models import Post, Thread, ThreadParticipant from ..participants import ( add_participants, has_participants, make_participants_aware, set_owner, set_users_unread_private_threads_sync, ) class ParticipantsTests(TestCase): def setUp(self): datetime = timezone.now() self.category = Category.objects.all_categories()[:1][0] self.thread = Thread( category=self.category, started_on=datetime, starter_name="Tester", starter_slug="tester", last_post_on=datetime, last_poster_name="Tester", last_poster_slug="tester", ) self.thread.set_title("Test thread") self.thread.save() post = Post.objects.create( category=self.category, thread=self.thread, poster_name="Tester", original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=datetime, updated_on=datetime, ) self.thread.first_post = post self.thread.last_post = post self.thread.save() def test_has_participants(self): """has_participants returns true if thread has participants""" users = [ create_test_user("User", "user@example.com"), create_test_user("Other_User", "otheruser@example.com"), ] self.assertFalse(has_participants(self.thread)) ThreadParticipant.objects.add_participants(self.thread, users) self.assertTrue(has_participants(self.thread)) self.thread.threadparticipant_set.all().delete() self.assertFalse(has_participants(self.thread)) def test_make_threads_participants_aware(self): """ make_participants_aware sets participants_list and participant annotations on list of threads """ user = create_test_user("User", "user@example.com") other_user = create_test_user("Other_User", "otheruser@example.com") self.assertFalse(hasattr(self.thread, "participants_list")) self.assertFalse(hasattr(self.thread, "participant")) make_participants_aware(user, [self.thread]) self.assertFalse(hasattr(self.thread, "participants_list")) self.assertTrue(hasattr(self.thread, "participant")) self.assertIsNone(self.thread.participant) ThreadParticipant.objects.set_owner(self.thread, user) ThreadParticipant.objects.add_participants(self.thread, [other_user]) make_participants_aware(user, [self.thread]) self.assertFalse(hasattr(self.thread, "participants_list")) self.assertEqual(self.thread.participant.user, user) def test_make_thread_participants_aware(self): """ make_participants_aware sets participants_list and participant annotations on thread model """ user = create_test_user("User", "user@example.com") other_user = create_test_user("Other_User", "otheruser@example.com") self.assertFalse(hasattr(self.thread, "participants_list")) self.assertFalse(hasattr(self.thread, "participant")) make_participants_aware(user, self.thread) self.assertTrue(hasattr(self.thread, "participants_list")) self.assertTrue(hasattr(self.thread, "participant")) self.assertEqual(self.thread.participants_list, []) self.assertIsNone(self.thread.participant) ThreadParticipant.objects.set_owner(self.thread, user) ThreadParticipant.objects.add_participants(self.thread, [other_user]) make_participants_aware(user, self.thread) self.assertEqual(self.thread.participant.user, user) for participant in self.thread.participants_list: if participant.user == user: break else: self.fail("thread.participants_list didn't contain user") def test_set_owner(self): """set_owner sets user as thread owner""" user = create_test_user("User", "user@example.com") set_owner(self.thread, user) owner = self.thread.threadparticipant_set.get(is_owner=True) self.assertEqual(user, owner.user) def test_set_users_unread_private_threads_sync(self): """ set_users_unread_private_threads_sync sets sync_unread_private_threads flag on users provided to true """ users = [ create_test_user("User", "user@example.com"), create_test_user("Other_User", "otheruser@example.com"), ] set_users_unread_private_threads_sync(users=users) for user in users: user.refresh_from_db() assert user.sync_unread_private_threads def test_set_participants_unread_private_threads_sync(self): """ set_users_unread_private_threads_sync sets sync_unread_private_threads flag on participants provided to true """ users = [ create_test_user("User", "user@example.com"), create_test_user("Other_User", "otheruser@example.com"), ] participants = [ThreadParticipant(user=u) for u in users] set_users_unread_private_threads_sync(participants=participants) for user in users: user.refresh_from_db() assert user.sync_unread_private_threads def test_set_participants_users_unread_private_threads_sync(self): """ set_users_unread_private_threads_sync sets sync_unread_private_threads flag on users and participants provided to true """ users = [create_test_user("User", "user@example.com")] participants = [ThreadParticipant(user=u) for u in users] users.append(create_test_user("Other_User", "otheruser@example.com")) set_users_unread_private_threads_sync(users=users, participants=participants) for user in users: user.refresh_from_db() assert user.sync_unread_private_threads def test_set_users_unread_private_threads_sync_exclude_user(self): """exclude_user kwarg works""" users = [ create_test_user("User", "user@example.com"), create_test_user("Other_User", "otheruser@example.com"), ] set_users_unread_private_threads_sync(users=users, exclude_user=users[0]) [i.refresh_from_db() for i in users] assert users[0].sync_unread_private_threads is False assert users[1].sync_unread_private_threads def test_set_users_unread_private_threads_sync_noop(self): """excluding only user is noop""" user = create_test_user("User", "user@example.com") with self.assertNumQueries(0): set_users_unread_private_threads_sync(users=[user], exclude_user=user) user.refresh_from_db() assert user.sync_unread_private_threads is False def test_add_participants_triggers_notify_on_new_private_thread( mocker, user, other_user, private_thread ): notify_on_new_private_thread_mock = mocker.patch( "misago.threads.participants.notify_on_new_private_thread" ) add_participants(user, private_thread, [user, other_user]) notify_on_new_private_thread_mock.delay.assert_called_once_with( user.id, private_thread.id, [other_user.id] )
7,531
Python
.py
164
36.810976
85
0.659336
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,121
test_privatethreads.py
rafalp_Misago/misago/threads/tests/test_privatethreads.py
from ...categories.models import Category from ...users.test import AuthenticatedUserTestCase class PrivateThreadsTestCase(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.private_threads()
257
Python
.py
6
38.166667
58
0.7751
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,122
test_thread_reply_api.py
rafalp_Misago/misago/threads/tests/test_thread_reply_api.py
from unittest.mock import patch from django.urls import reverse from .. import test from ...acl.test import patch_user_acl from ...categories.models import Category from ...users.test import AuthenticatedUserTestCase from ..models import Thread from ..test import patch_category_acl class ReplyThreadTests(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.get(slug="first-category") self.thread = test.post_thread(category=self.category) self.api_link = reverse( "misago:api:thread-post-list", kwargs={"thread_pk": self.thread.pk} ) def test_cant_reply_thread_as_guest(self): """user has to be authenticated to be able to post reply""" self.logout_user() response = self.client.post(self.api_link) self.assertEqual(response.status_code, 403) def test_thread_visibility(self): """thread's visibility is validated""" with patch_category_acl({"can_see": 0}): response = self.client.post(self.api_link) self.assertEqual(response.status_code, 404) with patch_category_acl({"can_browse": 0}): response = self.client.post(self.api_link) self.assertEqual(response.status_code, 404) with patch_category_acl({"can_see_all_threads": 0}): response = self.client.post(self.api_link) self.assertEqual(response.status_code, 404) @patch_category_acl({"can_reply_threads": False}) def test_cant_reply_thread(self): """permission to reply thread is validated""" response = self.client.post(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't reply to threads in this category."} ) @patch_category_acl({"can_reply_threads": True, "can_close_threads": False}) def test_closed_category_no_permission(self): """permssion to reply in closed category is validated""" self.category.is_closed = True self.category.save() response = self.client.post(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This category is closed. You can't reply to threads in it."}, ) @patch_category_acl({"can_reply_threads": True, "can_close_threads": True}) def test_closed_category(self): """permssion to reply in closed category is validated""" self.category.is_closed = True self.category.save() response = self.client.post(self.api_link) self.assertEqual(response.status_code, 400) @patch_category_acl({"can_reply_threads": True, "can_close_threads": False}) def test_closed_thread_no_permission(self): """permssion to reply in closed thread is validated""" self.thread.is_closed = True self.thread.save() response = self.client.post(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't reply to closed threads in this category."}, ) @patch_category_acl({"can_reply_threads": True, "can_close_threads": True}) def test_closed_thread(self): """permssion to reply in closed thread is validated""" self.thread.is_closed = True self.thread.save() response = self.client.post(self.api_link) self.assertEqual(response.status_code, 400) @patch_category_acl({"can_reply_threads": True}) def test_empty_data(self): """no data sent handling has no showstoppers""" response = self.client.post(self.api_link, data={}) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"post": ["You have to enter a message."]}) @patch_category_acl({"can_reply_threads": True}) def test_invalid_data(self): """api errors for invalid request data""" response = self.client.post( self.api_link, "false", content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "non_field_errors": [ "Invalid data. Expected a dictionary, but got bool." ] }, ) @patch_category_acl({"can_reply_threads": True}) def test_post_is_validated(self): """post is validated""" response = self.client.post(self.api_link, data={"post": "a"}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "post": [ "Posted message should be at least 5 characters long (it has 1)." ] }, ) @patch_category_acl({"can_reply_threads": True}) @patch( "misago.threads.api.postingendpoint.notifications.notify_on_new_thread_reply" ) def test_can_reply_thread(self, notify_on_new_thread_reply_mock): """endpoint creates new reply""" response = self.client.post( self.api_link, data={"post": "This is test response!"} ) self.assertEqual(response.status_code, 200) thread = Thread.objects.get(pk=self.thread.pk) response = self.client.get(self.thread.get_absolute_url()) self.assertContains(response, "<p>This is test response!</p>") # api increased user's posts counts self.reload_user() self.assertEqual(self.user.threads, 0) self.assertEqual(self.user.posts, 1) self.assertEqual(self.user.audittrail_set.count(), 1) post = self.user.post_set.all()[:1][0] self.assertEqual(post.category_id, self.category.pk) self.assertEqual(post.original, "This is test response!") self.assertEqual(post.poster_id, self.user.id) self.assertEqual(post.poster_name, self.user.username) self.assertEqual(thread.last_post_id, post.id) self.assertEqual(thread.last_poster_id, self.user.id) self.assertEqual(thread.last_poster_name, self.user.username) self.assertEqual(thread.last_poster_slug, self.user.slug) category = Category.objects.get(pk=self.category.pk) self.assertEqual(category.last_thread_id, thread.id) self.assertEqual(category.last_thread_title, thread.title) self.assertEqual(category.last_thread_slug, thread.slug) self.assertEqual(category.last_poster_id, self.user.id) self.assertEqual(category.last_poster_name, self.user.username) self.assertEqual(category.last_poster_slug, self.user.slug) @patch_category_acl({"can_reply_threads": True}) @patch( "misago.threads.api.postingendpoint.notifications.notify_on_new_thread_reply" ) def test_post_unicode(self, notify_on_new_thread_reply_mock): """unicode characters can be posted""" response = self.client.post( self.api_link, data={"post": "Chrzążczyżewoszyce, powiat Łękółody."} ) self.assertEqual(response.status_code, 200) @patch_category_acl({"can_reply_threads": True}) @patch( "misago.threads.api.postingendpoint.notifications.notify_on_new_thread_reply" ) def test_category_moderation_queue(self, notify_on_new_thread_reply_mock): """reply thread in category that requires approval""" self.category.require_replies_approval = True self.category.save() response = self.client.post( self.api_link, data={"post": "Lorem ipsum dolor met!"} ) self.assertEqual(response.status_code, 200) thread = Thread.objects.get(pk=self.thread.pk) self.assertFalse(thread.is_unapproved) self.assertTrue(thread.has_unapproved_posts) self.assertEqual(thread.replies, self.thread.replies) post = self.user.post_set.all()[:1][0] self.assertTrue(post.is_unapproved) category = Category.objects.get(slug="first-category") self.assertEqual(category.threads, self.category.threads) self.assertEqual(category.posts, self.category.posts) @patch_category_acl({"can_reply_threads": True}) @patch_user_acl({"can_approve_content": True}) @patch( "misago.threads.api.postingendpoint.notifications.notify_on_new_thread_reply" ) def test_category_moderation_queue_bypass(self, notify_on_new_thread_reply_mock): """bypass moderation queue due to user's acl""" self.category.require_replies_approval = True self.category.save() response = self.client.post( self.api_link, data={"post": "Lorem ipsum dolor met!"} ) self.assertEqual(response.status_code, 200) thread = Thread.objects.get(pk=self.thread.pk) self.assertFalse(thread.is_unapproved) self.assertFalse(thread.has_unapproved_posts) self.assertEqual(thread.replies, self.thread.replies + 1) post = self.user.post_set.all()[:1][0] self.assertFalse(post.is_unapproved) category = Category.objects.get(slug="first-category") self.assertEqual(category.threads, self.category.threads) self.assertEqual(category.posts, self.category.posts + 1) @patch_category_acl({"can_reply_threads": True, "require_replies_approval": True}) @patch( "misago.threads.api.postingendpoint.notifications.notify_on_new_thread_reply" ) def test_user_moderation_queue(self, notify_on_new_thread_reply_mock): """reply thread by user that requires approval""" response = self.client.post( self.api_link, data={"post": "Lorem ipsum dolor met!"} ) self.assertEqual(response.status_code, 200) thread = Thread.objects.get(pk=self.thread.pk) self.assertFalse(thread.is_unapproved) self.assertTrue(thread.has_unapproved_posts) self.assertEqual(thread.replies, self.thread.replies) post = self.user.post_set.all()[:1][0] self.assertTrue(post.is_unapproved) category = Category.objects.get(slug="first-category") self.assertEqual(category.threads, self.category.threads) self.assertEqual(category.posts, self.category.posts) @patch_category_acl({"can_reply_threads": True, "require_replies_approval": True}) @patch_user_acl({"can_approve_content": True}) @patch( "misago.threads.api.postingendpoint.notifications.notify_on_new_thread_reply" ) def test_user_moderation_queue_bypass(self, notify_on_new_thread_reply_mock): """bypass moderation queue due to user's acl""" response = self.client.post( self.api_link, data={"post": "Lorem ipsum dolor met!"} ) self.assertEqual(response.status_code, 200) thread = Thread.objects.get(pk=self.thread.pk) self.assertFalse(thread.is_unapproved) self.assertFalse(thread.has_unapproved_posts) self.assertEqual(thread.replies, self.thread.replies + 1) post = self.user.post_set.all()[:1][0] self.assertFalse(post.is_unapproved) category = Category.objects.get(slug="first-category") self.assertEqual(category.threads, self.category.threads) self.assertEqual(category.posts, self.category.posts + 1) @patch_category_acl( { "can_reply_threads": True, "require_threads_approval": True, "require_edits_approval": True, } ) @patch( "misago.threads.api.postingendpoint.notifications.notify_on_new_thread_reply" ) def test_omit_other_moderation_queues(self, notify_on_new_thread_reply_mock): """other queues are omitted""" self.category.require_threads_approval = True self.category.require_edits_approval = True self.category.save() response = self.client.post( self.api_link, data={"post": "Lorem ipsum dolor met!"} ) self.assertEqual(response.status_code, 200) thread = Thread.objects.get(pk=self.thread.pk) self.assertFalse(thread.is_unapproved) self.assertFalse(thread.has_unapproved_posts) self.assertEqual(thread.replies, self.thread.replies + 1) post = self.user.post_set.all()[:1][0] self.assertFalse(post.is_unapproved) category = Category.objects.get(slug="first-category") self.assertEqual(category.threads, self.category.threads) self.assertEqual(category.posts, self.category.posts + 1)
12,664
Python
.py
264
39.106061
87
0.657669
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,123
test_private_threads_list_read_category.py
rafalp_Misago/misago/threads/tests/test_private_threads_list_read_category.py
from datetime import timedelta from django.urls import reverse from django.utils import timezone from ...readtracker.models import ReadCategory, ReadThread from ..models import Thread, ThreadParticipant from ..test import post_thread def make_user_participant(user): for thread in Thread.objects.all(): ThreadParticipant.objects.create(user=user, thread=thread) def test_private_threads_list_without_unread_threads_is_marked_read( private_threads_category, user, user_client ): user.joined_on -= timedelta(minutes=60) user.save() threads = ( post_thread( private_threads_category, started_on=timezone.now() - timedelta(minutes=40), ), post_thread( private_threads_category, started_on=timezone.now() - timedelta(minutes=20), ), ) for thread in threads: ReadThread.objects.create( user=user, category=private_threads_category, thread=thread, read_time=thread.last_post_on, ) private_threads_category.synchronize() private_threads_category.save() make_user_participant(user) response = user_client.get(reverse("misago:private-threads")) assert response.status_code == 200 assert not ReadThread.objects.exists() ReadCategory.objects.get(user=user, category=private_threads_category) def test_private_threads_list_without_unread_threads_clears_user_unread_threads_count( private_threads_category, user, user_client ): user.joined_on -= timedelta(minutes=60) user.unread_private_threads = 50 user.save() threads = ( post_thread( private_threads_category, started_on=timezone.now() - timedelta(minutes=40), ), post_thread( private_threads_category, started_on=timezone.now() - timedelta(minutes=20), ), ) for thread in threads: ReadThread.objects.create( user=user, category=private_threads_category, thread=thread, read_time=thread.last_post_on, ) private_threads_category.synchronize() private_threads_category.save() make_user_participant(user) response = user_client.get(reverse("misago:private-threads")) assert response.status_code == 200 user.refresh_from_db() assert user.unread_private_threads == 0 def test_private_threads_list_read_entry_without_unread_threads_is_marked_read( private_threads_category, user, user_client ): user.joined_on -= timedelta(minutes=60) user.save() post_thread( private_threads_category, started_on=timezone.now() - timedelta(minutes=40), ) read_category = ReadCategory.objects.create( user=user, category=private_threads_category, read_time=timezone.now() - timedelta(minutes=30), ) read_thread = post_thread( private_threads_category, started_on=timezone.now() - timedelta(minutes=20), ) ReadThread.objects.create( user=user, category=private_threads_category, thread=read_thread, read_time=read_thread.last_post_on, ) private_threads_category.synchronize() private_threads_category.save() make_user_participant(user) response = user_client.get(reverse("misago:private-threads")) assert response.status_code == 200 assert not ReadThread.objects.exists() new_read_category = ReadCategory.objects.get( user=user, category=private_threads_category ) assert new_read_category.id == read_category.id assert new_read_category.read_time > read_category.read_time def test_private_threads_list_with_unread_thread_is_not_marked_read( private_threads_category, user, user_client ): user.joined_on -= timedelta(minutes=60) user.save() read_thread = post_thread( private_threads_category, started_on=timezone.now() - timedelta(minutes=40), ) ReadThread.objects.create( user=user, category=private_threads_category, thread=read_thread, read_time=read_thread.last_post_on, ) post_thread( private_threads_category, started_on=timezone.now() - timedelta(minutes=20), ) private_threads_category.synchronize() private_threads_category.save() make_user_participant(user) response = user_client.get(reverse("misago:private-threads")) assert response.status_code == 200 assert ReadThread.objects.exists() assert not ReadCategory.objects.exists()
4,616
Python
.py
129
28.914729
86
0.684211
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,124
test_thread_start_api.py
rafalp_Misago/misago/threads/tests/test_thread_start_api.py
from django.urls import reverse from ...acl.test import patch_user_acl from ...categories.models import Category from ...users.test import AuthenticatedUserTestCase from ..test import patch_category_acl class StartThreadTests(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.get(slug="first-category") self.api_link = reverse("misago:api:thread-list") def test_cant_start_thread_as_guest(self): """user has to be authenticated to be able to post thread""" self.logout_user() response = self.client.post(self.api_link) self.assertEqual(response.status_code, 403) @patch_category_acl({"can_see": False}) def test_cant_see(self): """has no permission to see selected category""" response = self.client.post(self.api_link, {"category": self.category.pk}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "category": ["Selected category is invalid."], "post": ["You have to enter a message."], "title": ["You have to enter a thread title."], }, ) @patch_category_acl({"can_browse": False}) def test_cant_browse(self): """has no permission to browse selected category""" response = self.client.post(self.api_link, {"category": self.category.pk}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "category": ["Selected category is invalid."], "post": ["You have to enter a message."], "title": ["You have to enter a thread title."], }, ) @patch_category_acl({"can_start_threads": False}) def test_cant_start_thread(self): """permission to start thread in category is validated""" response = self.client.post(self.api_link, {"category": self.category.pk}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "category": [ "You don't have permission to start new threads in this category." ], "post": ["You have to enter a message."], "title": ["You have to enter a thread title."], }, ) @patch_category_acl({"can_start_threads": True, "can_close_threads": False}) def test_cant_start_thread_in_locked_category(self): """can't post in closed category""" self.category.is_closed = True self.category.save() response = self.client.post(self.api_link, {"category": self.category.pk}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "category": [ "This category is closed. You can't start new threads in it." ], "post": ["You have to enter a message."], "title": ["You have to enter a thread title."], }, ) def test_cant_start_thread_in_invalid_category(self): """can't post in invalid category""" response = self.client.post( self.api_link, {"category": self.category.pk * 100000} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "category": [ "Selected category doesn't exist or " "you don't have permission to browse it." ], "post": ["You have to enter a message."], "title": ["You have to enter a thread title."], }, ) @patch_category_acl({"can_start_threads": True}) def test_empty_data(self): """no data sent handling has no showstoppers""" response = self.client.post(self.api_link, data={}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "category": ["You have to select category to post thread in."], "title": ["You have to enter a thread title."], "post": ["You have to enter a message."], }, ) @patch_category_acl({"can_start_threads": True}) def test_invalid_data(self): """api errors for invalid request data""" response = self.client.post( self.api_link, "false", content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "non_field_errors": [ "Invalid data. Expected a dictionary, but got bool." ] }, ) @patch_category_acl({"can_start_threads": True}) def test_title_is_validated(self): """title is validated""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "------", "post": "Lorem ipsum dolor met, sit amet elit!", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"title": ["Thread title should contain alpha-numeric characters."]}, ) @patch_category_acl({"can_start_threads": True}) def test_post_is_validated(self): """post is validated""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Lorem ipsum dolor met", "post": "a", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "post": [ "Posted message should be at least 5 characters long (it has 1)." ] }, ) @patch_category_acl({"can_start_threads": True}) def test_can_start_thread(self): """endpoint creates new thread""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] response_json = response.json() self.assertEqual(response_json["url"], thread.get_absolute_url()) response = self.client.get(thread.get_absolute_url()) self.assertContains(response, self.category.name) self.assertContains(response, thread.title) self.assertContains(response, "<p>Lorem ipsum dolor met!</p>") # api increased user's threads and posts counts self.reload_user() self.assertEqual(self.user.threads, 1) self.assertEqual(self.user.posts, 1) self.assertEqual(self.user.audittrail_set.count(), 1) self.assertEqual(thread.category_id, self.category.pk) self.assertEqual(thread.title, "Hello, I am test thread!") self.assertEqual(thread.starter_id, self.user.id) self.assertEqual(thread.starter_name, self.user.username) self.assertEqual(thread.starter_slug, self.user.slug) self.assertEqual(thread.last_poster_id, self.user.id) self.assertEqual(thread.last_poster_name, self.user.username) self.assertEqual(thread.last_poster_slug, self.user.slug) post = self.user.post_set.all()[:1][0] self.assertEqual(post.category_id, self.category.pk) self.assertEqual(post.original, "Lorem ipsum dolor met!") self.assertEqual(post.poster_id, self.user.id) self.assertEqual(post.poster_name, self.user.username) category = Category.objects.get(pk=self.category.pk) self.assertEqual(category.threads, 1) self.assertEqual(category.posts, 1) self.assertEqual(category.last_thread_id, thread.id) self.assertEqual(category.last_thread_title, thread.title) self.assertEqual(category.last_thread_slug, thread.slug) self.assertEqual(category.last_poster_id, self.user.id) self.assertEqual(category.last_poster_name, self.user.username) self.assertEqual(category.last_poster_slug, self.user.slug) @patch_category_acl({"can_start_threads": True, "can_close_threads": False}) def test_start_closed_thread_no_permission(self): """permission is checked before thread is closed""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", "close": True, }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertFalse(thread.is_closed) @patch_category_acl({"can_start_threads": True, "can_close_threads": True}) def test_start_closed_thread(self): """can post closed thread""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", "close": True, }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertTrue(thread.is_closed) @patch_category_acl({"can_start_threads": True, "can_pin_threads": 1}) def test_start_unpinned_thread(self): """can post unpinned thread""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", "pin": 0, }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertEqual(thread.weight, 0) @patch_category_acl({"can_start_threads": True, "can_pin_threads": 1}) def test_start_locally_pinned_thread(self): """can post locally pinned thread""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", "pin": 1, }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertEqual(thread.weight, 1) @patch_category_acl({"can_start_threads": True, "can_pin_threads": 2}) def test_start_globally_pinned_thread(self): """can post globally pinned thread""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", "pin": 2, }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertEqual(thread.weight, 2) @patch_category_acl({"can_start_threads": True, "can_pin_threads": 1}) def test_start_globally_pinned_thread_no_permission(self): """cant post globally pinned thread without permission""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", "pin": 2, }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertEqual(thread.weight, 0) @patch_category_acl({"can_start_threads": True, "can_pin_threads": 0}) def test_start_locally_pinned_thread_no_permission(self): """cant post locally pinned thread without permission""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", "pin": 1, }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertEqual(thread.weight, 0) @patch_category_acl({"can_start_threads": True, "can_hide_threads": 1}) def test_start_hidden_thread(self): """can post hidden thread""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", "hide": 1, }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertTrue(thread.is_hidden) category = Category.objects.get(pk=self.category.pk) self.assertNotEqual(category.last_thread_id, thread.id) @patch_category_acl({"can_start_threads": True, "can_hide_threads": 0}) def test_start_hidden_thread_no_permission(self): """cant post hidden thread without permission""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", "hide": 1, }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertFalse(thread.is_hidden) @patch_category_acl({"can_start_threads": True}) def test_post_unicode(self): """unicode characters can be posted""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Brzęczyżczykiewicz", "post": "Chrzążczyżewoszyce, powiat Łękółody.", }, ) self.assertEqual(response.status_code, 200) @patch_category_acl({"can_start_threads": True}) def test_category_moderation_queue(self): """start unapproved thread in category that requires approval""" self.category.require_threads_approval = True self.category.save() response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertTrue(thread.is_unapproved) self.assertTrue(thread.has_unapproved_posts) post = self.user.post_set.all()[:1][0] self.assertTrue(post.is_unapproved) category = Category.objects.get(slug="first-category") self.assertEqual(category.threads, self.category.threads) self.assertEqual(category.posts, self.category.posts) self.assertFalse(category.last_thread_id == thread.id) @patch_category_acl({"can_start_threads": True}) @patch_user_acl({"can_approve_content": True}) def test_category_moderation_queue_bypass(self): """bypass moderation queue due to user's acl""" self.category.require_threads_approval = True self.category.save() response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertFalse(thread.is_unapproved) self.assertFalse(thread.has_unapproved_posts) post = self.user.post_set.all()[:1][0] self.assertFalse(post.is_unapproved) category = Category.objects.get(slug="first-category") self.assertEqual(category.threads, self.category.threads + 1) self.assertEqual(category.posts, self.category.posts + 1) self.assertEqual(category.last_thread_id, thread.id) @patch_category_acl({"can_start_threads": True, "require_threads_approval": True}) def test_user_moderation_queue(self): """start unapproved thread in category that requires approval""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertTrue(thread.is_unapproved) self.assertTrue(thread.has_unapproved_posts) post = self.user.post_set.all()[:1][0] self.assertTrue(post.is_unapproved) category = Category.objects.get(slug="first-category") self.assertEqual(category.threads, self.category.threads) self.assertEqual(category.posts, self.category.posts) self.assertFalse(category.last_thread_id == thread.id) @patch_category_acl({"can_start_threads": True, "require_threads_approval": True}) @patch_user_acl({"can_approve_content": True}) def test_user_moderation_queue_bypass(self): """bypass moderation queue due to user's acl""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertFalse(thread.is_unapproved) self.assertFalse(thread.has_unapproved_posts) post = self.user.post_set.all()[:1][0] self.assertFalse(post.is_unapproved) category = Category.objects.get(slug="first-category") self.assertEqual(category.threads, self.category.threads + 1) self.assertEqual(category.posts, self.category.posts + 1) self.assertEqual(category.last_thread_id, thread.id) @patch_category_acl( { "can_start_threads": True, "require_replies_approval": True, "require_edits_approval": True, } ) def test_omit_other_moderation_queues(self): """other queues are omitted""" self.category.require_replies_approval = True self.category.require_edits_approval = True self.category.save() response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] self.assertFalse(thread.is_unapproved) self.assertFalse(thread.has_unapproved_posts) post = self.user.post_set.all()[:1][0] self.assertFalse(post.is_unapproved) category = Category.objects.get(slug="first-category") self.assertEqual(category.threads, self.category.threads + 1) self.assertEqual(category.posts, self.category.posts + 1) self.assertEqual(category.last_thread_id, thread.id)
20,087
Python
.py
469
31.842217
86
0.579179
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,125
test_thread_postlikes_api.py
rafalp_Misago/misago/threads/tests/test_thread_postlikes_api.py
from django.urls import reverse from .. import test from ..serializers import PostLikeSerializer from ..test import patch_category_acl from .test_threads_api import ThreadsApiTestCase class ThreadPostLikesApiTestCase(ThreadsApiTestCase): def setUp(self): super().setUp() self.post = test.reply_thread(self.thread, poster=self.user) self.api_link = reverse( "misago:api:thread-post-likes", kwargs={"thread_pk": self.thread.pk, "pk": self.post.pk}, ) @patch_category_acl({"can_see_posts_likes": 0}) def test_no_permission(self): """api errors if user has no permission to see likes""" response = self.client.get(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't see who liked this post."} ) @patch_category_acl({"can_see_posts_likes": 1}) def test_no_permission_to_list(self): """api errors if user has no permission to see likes, but can see likes count""" response = self.client.get(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't see who liked this post."} ) @patch_category_acl({"can_see_posts_likes": 2}) def test_no_likes(self): """api returns empty list if post has no likes""" response = self.client.get(self.api_link) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), []) @patch_category_acl({"can_see_posts_likes": 2}) def test_likes(self): """api returns list of likes""" like = test.like_post(self.post, self.user) other_like = test.like_post(self.post, self.user) response = self.client.get(self.api_link) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), [ PostLikeSerializer( { "id": other_like.id, "liked_on": other_like.liked_on, "liker_id": other_like.liker_id, "liker_name": other_like.liker_name, "liker_slug": other_like.liker_slug, "liker__avatars": self.user.avatars, } ).data, PostLikeSerializer( { "id": like.id, "liked_on": like.liked_on, "liker_id": like.liker_id, "liker_name": like.liker_name, "liker_slug": like.liker_slug, "liker__avatars": self.user.avatars, } ).data, ], ) # api has no showstoppers for likes by deleted users like.liker = None like.save() other_like.liker = None other_like.save() response = self.client.get(self.api_link) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), [ PostLikeSerializer( { "id": other_like.id, "liked_on": other_like.liked_on, "liker_id": other_like.liker_id, "liker_name": other_like.liker_name, "liker_slug": other_like.liker_slug, "liker__avatars": None, } ).data, PostLikeSerializer( { "id": like.id, "liked_on": like.liked_on, "liker_id": like.liker_id, "liker_name": like.liker_name, "liker_slug": like.liker_slug, "liker__avatars": None, } ).data, ], )
4,057
Python
.py
99
26.79798
88
0.507224
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,126
test_redirects_views.py
rafalp_Misago/misago/threads/tests/test_redirects_views.py
from django.urls import reverse from django.utils import timezone from ...readtracker.models import ReadCategory from ...readtracker.tracker import mark_thread_read from ...test import assert_contains from ..test import reply_thread def test_thread_last_post_redirect_view_returns_redirect(client, thread): reply = reply_thread(thread) response = client.get( reverse( "misago:thread-last-post", kwargs={"id": thread.id, "slug": thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:thread", kwargs={"id": thread.id, "slug": thread.slug}, ) + f"#post-{reply.id}" ) def test_private_thread_last_post_redirect_view_returns_redirect( user_client, user_private_thread ): reply = reply_thread(user_private_thread) response = user_client.get( reverse( "misago:private-thread-last-post", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) + f"#post-{reply.id}" ) def test_thread_unread_post_redirect_view_returns_redirect_to_last_post_for_anonymous_user( client, thread ): reply_thread(thread, posted_on=timezone.now()) reply = reply_thread(thread, posted_on=timezone.now()) response = client.get( reverse( "misago:thread-unread-post", kwargs={"id": thread.id, "slug": thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:thread", kwargs={"id": thread.id, "slug": thread.slug}, ) + f"#post-{reply.id}" ) def test_thread_unread_post_redirect_view_returns_redirect_to_first_unread_post_for_user( user, user_client, thread ): mark_thread_read(user, thread, thread.first_post.posted_on) reply = reply_thread(thread, posted_on=timezone.now()) reply_thread(thread, posted_on=timezone.now()) response = user_client.get( reverse( "misago:thread-unread-post", kwargs={"id": thread.id, "slug": thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:thread", kwargs={"id": thread.id, "slug": thread.slug}, ) + f"#post-{reply.id}" ) def test_thread_unread_post_redirect_view_returns_redirect_to_last_post_for_read_thread( user, user_client, thread ): reply_thread(thread, posted_on=timezone.now()) reply = reply_thread(thread, posted_on=timezone.now()) mark_thread_read(user, thread, timezone.now()) response = user_client.get( reverse( "misago:thread-unread-post", kwargs={"id": thread.id, "slug": thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:thread", kwargs={"id": thread.id, "slug": thread.slug}, ) + f"#post-{reply.id}" ) def test_thread_unread_post_redirect_view_returns_redirect_to_last_post_for_read_category( user, user_client, thread ): reply_thread(thread, posted_on=timezone.now()) reply = reply_thread(thread, posted_on=timezone.now()) ReadCategory.objects.create( user=user, category=thread.category, read_time=timezone.now(), ) response = user_client.get( reverse( "misago:thread-unread-post", kwargs={"id": thread.id, "slug": thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:thread", kwargs={"id": thread.id, "slug": thread.slug}, ) + f"#post-{reply.id}" ) def test_private_thread_unread_post_redirect_view_returns_error_404_for_anonymous_client( client, user_private_thread ): response = client.get( reverse( "misago:private-thread-unread-post", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) ) assert response.status_code == 403 def test_private_thread_unread_post_redirect_view_returns_redirect_to_first_unread_post_for_user( user, user_client, user_private_thread ): mark_thread_read( user, user_private_thread, user_private_thread.first_post.posted_on ) reply = reply_thread(user_private_thread, posted_on=timezone.now()) reply_thread(user_private_thread, posted_on=timezone.now()) response = user_client.get( reverse( "misago:private-thread-unread-post", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) + f"#post-{reply.id}" ) def test_private_thread_unread_post_redirect_view_returns_redirect_to_last_post_for_read_thread( user, user_client, user_private_thread ): reply_thread(user_private_thread, posted_on=timezone.now()) reply = reply_thread(user_private_thread, posted_on=timezone.now()) mark_thread_read(user, user_private_thread, timezone.now()) response = user_client.get( reverse( "misago:private-thread-unread-post", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) + f"#post-{reply.id}" ) def test_private_thread_unread_post_redirect_view_returns_redirect_to_last_post_for_read_category( user, user_client, user_private_thread ): reply_thread(user_private_thread, posted_on=timezone.now()) reply = reply_thread(user_private_thread, posted_on=timezone.now()) ReadCategory.objects.create( user=user, category=user_private_thread.category, read_time=timezone.now(), ) response = user_client.get( reverse( "misago:private-thread-unread-post", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) + f"#post-{reply.id}" ) def test_thread_solution_redirect_view_returns_redirect_to_solution_post( client, thread ): solution = reply_thread(thread) reply_thread(thread) thread.best_answer = solution thread.save() response = client.get( reverse( "misago:thread-solution-post", kwargs={"id": thread.id, "slug": thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:thread", kwargs={"id": thread.id, "slug": thread.slug}, ) + f"#post-{solution.id}" ) def test_thread_solution_redirect_view_returns_redirect_to_last_post_in_unsolved_thread( client, thread ): reply_thread(thread) reply = reply_thread(thread) response = client.get( reverse( "misago:thread-solution-post", kwargs={"id": thread.id, "slug": thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:thread", kwargs={"id": thread.id, "slug": thread.slug}, ) + f"#post-{reply.id}" ) def test_thread_unapproved_redirect_view_returns_error_for_anonymous_user( client, thread ): response = client.get( reverse( "misago:thread-unapproved-post", kwargs={"id": thread.id, "slug": thread.slug}, ) ) assert_contains( response, "You must be a moderator to view unapproved posts.", status_code=403, ) def test_thread_unapproved_redirect_view_returns_error_for_user_without_moderator_permission( user_client, thread ): response = user_client.get( reverse( "misago:thread-unapproved-post", kwargs={"id": thread.id, "slug": thread.slug}, ) ) assert_contains( response, "You must be a moderator to view unapproved posts.", status_code=403, ) def test_thread_unapproved_redirect_view_redirects_moderator_to_last_post_if_no_unapproved_posts_exist( moderator_client, thread ): reply = reply_thread(thread) response = moderator_client.get( reverse( "misago:thread-unapproved-post", kwargs={"id": thread.id, "slug": thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:thread", kwargs={"id": thread.id, "slug": thread.slug}, ) + f"#post-{reply.id}" ) def test_thread_unapproved_redirect_view_redirects_moderator_to_unapproved_post( moderator_client, thread ): unapproved = reply_thread(thread, is_unapproved=True) reply_thread(thread) response = moderator_client.get( reverse( "misago:thread-unapproved-post", kwargs={"id": thread.id, "slug": thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:thread", kwargs={"id": thread.id, "slug": thread.slug}, ) + f"#post-{unapproved.id}" ) def test_private_thread_unapproved_redirect_view_returns_error_for_user_without_moderator_permission( user_client, user_private_thread ): response = user_client.get( reverse( "misago:private-thread-unapproved-post", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) ) assert_contains( response, "You must be a moderator to view unapproved posts.", status_code=403, ) def test_private_thread_unapproved_redirect_view_redirects_moderator_to_last_post_if_no_unapproved_posts_exist( moderator_client, user_private_thread ): reply = reply_thread(user_private_thread) response = moderator_client.get( reverse( "misago:private-thread-unapproved-post", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) + f"#post-{reply.id}" ) def test_private_thread_unapproved_redirect_view_redirects_moderator_to_unapproved_post( moderator_client, user_private_thread ): unapproved = reply_thread(user_private_thread, is_unapproved=True) reply_thread(user_private_thread) response = moderator_client.get( reverse( "misago:private-thread-unapproved-post", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) ) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) + f"#post-{unapproved.id}" ) def test_post_redirect_view_returns_404_for_not_existing_post_id(client, thread): reply = reply_thread(thread) response = client.get(reverse("misago:post", kwargs={"id": reply.id + 10})) assert response.status_code == 404 def test_post_redirect_view_returns_error_404_if_user_cant_see_private_thread( user_client, private_thread ): reply = reply_thread(private_thread) response = user_client.get(reverse("misago:post", kwargs={"id": reply.id})) assert response.status_code == 404 def test_post_redirect_view_returns_redirect_to_thread_post(client, thread): reply = reply_thread(thread) response = client.get(reverse("misago:post", kwargs={"id": reply.id})) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:thread", kwargs={"id": thread.id, "slug": thread.slug}, ) + f"#post-{reply.id}" ) def test_post_redirect_view_returns_redirect_to_private_thread_post( user_client, user_private_thread ): reply = reply_thread(user_private_thread) response = user_client.get(reverse("misago:post", kwargs={"id": reply.id})) assert response.status_code == 302 assert ( response["location"] == reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) + f"#post-{reply.id}" )
13,599
Python
.py
406
26.133005
111
0.619676
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,127
test_synchronizethreads.py
rafalp_Misago/misago/threads/tests/test_synchronizethreads.py
from io import StringIO from django.core.management import call_command from django.test import TestCase from .. import test from ...categories.models import Category from ..management.commands import synchronizethreads class SynchronizeThreadsTests(TestCase): def test_no_threads_sync(self): """command works when there are no threads""" command = synchronizethreads.Command() out = StringIO() call_command(command, stdout=out) command_output = out.getvalue().strip() self.assertEqual(command_output, "No threads were found") def test_threads_sync(self): """command synchronizes threads""" category = Category.objects.all_categories()[:1][0] threads = [test.post_thread(category) for _ in range(10)] for i, thread in enumerate(threads): [test.reply_thread(thread) for _ in range(i)] thread.replies = 0 thread.save() command = synchronizethreads.Command() out = StringIO() call_command(command, stdout=out) for i, thread in enumerate(threads): db_thread = category.thread_set.get(id=thread.id) self.assertEqual(db_thread.replies, i) command_output = out.getvalue().splitlines()[-1].strip() self.assertEqual(command_output, "Synchronized 10 threads")
1,358
Python
.py
30
37.333333
67
0.674772
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,128
test_post_model.py
rafalp_Misago/misago/threads/tests/test_post_model.py
from datetime import timedelta from django.test import TestCase from django.utils import timezone from ...categories.models import Category from ...users.test import create_test_user from ..checksums import update_post_checksum from ..models import Post, Thread class PostModelTests(TestCase): def setUp(self): self.user = create_test_user("User", "user@example.com") datetime = timezone.now() self.category = Category.objects.all_categories()[:1][0] self.thread = Thread( category=self.category, started_on=datetime, starter_name="Tester", starter_slug="tester", last_post_on=datetime, last_poster_name="Tester", last_poster_slug="tester", ) self.thread.set_title("Test thread") self.thread.save() self.post = Post.objects.create( category=self.category, thread=self.thread, poster=self.user, poster_name=self.user.username, original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=datetime, updated_on=datetime, ) update_post_checksum(self.post) self.post.save(update_fields=["checksum"]) self.thread.first_post = self.post self.thread.last_post = self.post self.thread.save() def test_merge_invalid(self): """see if attempts for invalid merges fail""" # can't merge with itself with self.assertRaises(ValueError): self.post.merge(self.post) other_user = create_test_user("Other_User", "otheruser@example.com") other_thread = Thread.objects.create( category=self.category, started_on=timezone.now(), starter_name="Tester", starter_slug="tester", last_post_on=timezone.now(), last_poster_name="Tester", last_poster_slug="tester", ) # can't merge with other users posts with self.assertRaises(ValueError): self.post.merge( Post.objects.create( category=self.category, thread=self.thread, poster=other_user, poster_name=other_user.username, original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=timezone.now() + timedelta(minutes=5), updated_on=timezone.now() + timedelta(minutes=5), ) ) # can't merge across threads with self.assertRaises(ValueError): self.post.merge( Post.objects.create( category=self.category, thread=other_thread, poster=self.user, poster_name=self.user.username, original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=timezone.now() + timedelta(minutes=5), updated_on=timezone.now() + timedelta(minutes=5), ) ) # can't merge with events with self.assertRaises(ValueError): self.post.merge( Post.objects.create( category=self.category, thread=self.thread, poster=self.user, poster_name=self.user.username, original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=timezone.now() + timedelta(minutes=5), updated_on=timezone.now() + timedelta(minutes=5), is_event=True, ) ) def test_merge(self): """merge method merges two posts into one""" other_post = Post.objects.create( category=self.category, thread=self.thread, poster=self.user, poster_name=self.user.username, original="I am other message!", parsed="<p>I am other message!</p>", checksum="nope", posted_on=timezone.now() + timedelta(minutes=5), updated_on=timezone.now() + timedelta(minutes=5), ) other_post.merge(self.post) self.assertIn(other_post.original, self.post.original) self.assertIn(other_post.parsed, self.post.parsed) self.assertTrue(self.post.is_valid) def test_merge_best_answer(self): """merge method merges best answer into post""" best_answer = Post.objects.create( category=self.category, thread=self.thread, poster=self.user, poster_name=self.user.username, original="I am other message!", parsed="<p>I am other message!</p>", checksum="nope", posted_on=timezone.now() + timedelta(minutes=5), updated_on=timezone.now() + timedelta(minutes=5), ) self.thread.set_best_answer(self.user, best_answer) self.thread.save() best_answer.merge(self.post) self.assertEqual(self.thread.best_answer, self.post) def test_merge_in_best_answer(self): """merge method merges post into best answert""" best_answer = Post.objects.create( category=self.category, thread=self.thread, poster=self.user, poster_name=self.user.username, original="I am other message!", parsed="<p>I am other message!</p>", checksum="nope", posted_on=timezone.now() + timedelta(minutes=5), updated_on=timezone.now() + timedelta(minutes=5), ) other_post = Post.objects.create( category=self.category, thread=self.thread, poster=self.user, poster_name=self.user.username, original="I am other message!", parsed="<p>I am other message!</p>", checksum="nope", posted_on=timezone.now() + timedelta(minutes=5), updated_on=timezone.now() + timedelta(minutes=5), ) self.thread.set_best_answer(self.user, best_answer) self.thread.save() other_post.merge(best_answer) self.assertEqual(self.thread.best_answer, best_answer) def test_move(self): """move method moves post to other thread""" new_thread = Thread.objects.create( category=self.category, started_on=timezone.now(), starter_name="Tester", starter_slug="tester", last_post_on=timezone.now(), last_poster_name="Tester", last_poster_slug="tester", ) self.post.move(new_thread) self.assertEqual(self.post.thread, new_thread)
7,152
Python
.py
175
28.342857
76
0.557571
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,129
test_threads_lists_views.py
rafalp_Misago/misago/threads/tests/test_threads_lists_views.py
from unittest.mock import patch from django.urls import reverse from ...categories.models import Category from ...conf.test import override_dynamic_settings from ...pagination.cursor import EmptyPageError from ...permissions.enums import CategoryPermission from ...permissions.models import CategoryGroupPermission from ...test import assert_contains, assert_not_contains from ..models import ThreadParticipant from ..test import post_thread @override_dynamic_settings(index_view="categories") def test_site_threads_list_renders_empty_to_guests(db, client): response = client.get(reverse("misago:threads")) assert_contains(response, "No threads have been started yet") @override_dynamic_settings(index_view="categories") def test_site_threads_list_renders_empty_to_users(user_client): response = user_client.get(reverse("misago:threads")) assert_contains(response, "No threads have been started yet") @override_dynamic_settings(index_view="categories") def test_site_threads_list_renders_empty_to_moderators(moderator_client): response = moderator_client.get(reverse("misago:threads")) assert_contains(response, "No threads have been started yet") def test_category_threads_list_renders_empty_to_guests(default_category, client): response = client.get(default_category.get_absolute_url()) assert_contains(response, default_category.name) assert_contains(response, "No threads have been started in this category yet") def test_category_threads_list_renders_empty_to_users(default_category, user_client): response = user_client.get(default_category.get_absolute_url()) assert_contains(response, default_category.name) assert_contains(response, "No threads have been started in this category yet") def test_category_threads_list_renders_empty_to_moderators( default_category, moderator_client ): response = moderator_client.get(default_category.get_absolute_url()) assert_contains(response, default_category.name) assert_contains(response, "No threads have been started in this category yet") def test_child_category_threads_list_renders_empty_to_guests(child_category, client): response = client.get(child_category.get_absolute_url()) assert_contains(response, child_category.name) assert_contains(response, "No threads have been started in this category yet") def test_child_category_threads_list_renders_empty_to_users( child_category, user_client ): response = user_client.get(child_category.get_absolute_url()) assert_contains(response, child_category.name) assert_contains(response, "No threads have been started in this category yet") def test_child_category_threads_list_renders_empty_to_moderators( child_category, moderator_client ): response = moderator_client.get(child_category.get_absolute_url()) assert_contains(response, child_category.name) assert_contains(response, "No threads have been started in this category yet") def test_hidden_category_threads_list_renders_error_to_guests(hidden_category, client): response = client.get(hidden_category.get_absolute_url()) assert response.status_code == 404 def test_hidden_category_threads_list_renders_error_to_users( hidden_category, user_client ): response = user_client.get(hidden_category.get_absolute_url()) assert response.status_code == 404 def test_private_threads_list_shows_permission_error_to_guests(db, client): response = client.get(reverse("misago:private-threads")) assert_contains( response, "You must be signed in to use private threads.", status_code=403 ) def test_private_threads_list_renders_empty_to_users(user_client): response = user_client.get(reverse("misago:private-threads")) assert_contains(response, "Private threads") assert_contains(response, "You aren't participating in any private threads") def test_private_threads_list_shows_permission_error_to_users_without_permission( user_client, members_group ): members_group.can_use_private_threads = False members_group.save() response = user_client.get(reverse("misago:private-threads")) assert_contains(response, "You can&#x27;t use private threads.", status_code=403) def test_private_threads_list_renders_empty_to_moderators(moderator_client): response = moderator_client.get(reverse("misago:private-threads")) assert_contains(response, "Private threads") assert_contains(response, "You aren't participating in any private threads") @override_dynamic_settings(index_view="categories") def test_threads_list_displays_thread_to_user(default_category, user, user_client): post_thread(default_category, title="Test Thread") response = user_client.get(reverse("misago:threads")) assert_contains(response, "Test Thread") @override_dynamic_settings(index_view="categories") def test_threads_list_displays_thread_to_anonymous_user(default_category, client): post_thread(default_category, title="Test Thread") response = client.get(reverse("misago:threads")) assert_contains(response, "Test Thread") def test_category_threads_list_displays_thread_to_user( default_category, user, user_client ): post_thread(default_category, title="Test Thread") response = user_client.get(default_category.get_absolute_url()) assert_contains(response, "Test Thread") def test_category_threads_list_displays_thread_to_anonymous_user( default_category, client ): post_thread(default_category, title="Test Thread") response = client.get(default_category.get_absolute_url()) assert_contains(response, "Test Thread") def test_category_threads_list_displays_user_thread_to_user( default_category, user_client, other_user ): post_thread(default_category, title="Test Thread", poster=other_user) response = user_client.get(default_category.get_absolute_url()) assert_contains(response, "Test Thread") def test_category_threads_list_displays_user_thread_to_anonymous_user( default_category, client, other_user ): post_thread(default_category, title="Test Thread", poster=other_user) response = client.get(default_category.get_absolute_url()) assert_contains(response, "Test Thread") def test_category_threads_list_includes_child_category_thread( default_category, user, user_client, other_user ): default_category.list_children_threads = True default_category.save() child_category = Category(name="Child Category", slug="child-category") child_category.insert_at(default_category, position="last-child", save=True) post_thread(child_category, title="Test Thread", poster=other_user) CategoryGroupPermission.objects.create( category=child_category, group=user.group, permission=CategoryPermission.SEE, ) CategoryGroupPermission.objects.create( category=child_category, group=user.group, permission=CategoryPermission.BROWSE, ) response = user_client.get(default_category.get_absolute_url()) assert_contains(response, "Test Thread") def test_category_threads_list_excludes_child_category_thread_if_list_children_threads_is_false( default_category, user, user_client, other_user ): default_category.list_children_threads = False default_category.save() child_category = Category(name="Child Category", slug="child-category") child_category.insert_at(default_category, position="last-child", save=True) post_thread(child_category, title="Test Thread", poster=other_user) CategoryGroupPermission.objects.create( category=child_category, group=user.group, permission=CategoryPermission.SEE, ) CategoryGroupPermission.objects.create( category=child_category, group=user.group, permission=CategoryPermission.BROWSE, ) response = user_client.get(default_category.get_absolute_url()) assert_contains(response, "No threads have been started in this category yet") def test_private_threads_list_displays_private_thread( private_threads_category, user, user_client ): thread = post_thread(private_threads_category, title="Test Private Thread") ThreadParticipant.objects.create(thread=thread, user=user) response = user_client.get(reverse("misago:private-threads")) assert_contains(response, "Test Private Thread") def test_private_threads_list_displays_user_private_thread( private_threads_category, user, user_client, other_user ): thread = post_thread( private_threads_category, title="Test Private Thread", poster=other_user ) ThreadParticipant.objects.create(thread=thread, user=user) response = user_client.get(reverse("misago:private-threads")) assert_contains(response, "Test Private Thread") @override_dynamic_settings(index_view="categories") def test_threads_list_displays_empty_in_htmx_request(db, user_client): response = user_client.get( reverse("misago:threads"), headers={"hx-request": "true"}, ) assert_not_contains(response, "<h1>") @override_dynamic_settings(index_view="categories") def test_threads_list_displays_thread_in_htmx_request(default_category, user_client): post_thread(default_category, title="Test Thread") response = user_client.get( reverse("misago:threads"), headers={"hx-request": "true"}, ) assert_not_contains(response, "<h1>") assert_contains(response, "Test Thread") def test_category_threads_list_displays_empty_in_htmx_request( default_category, user_client ): response = user_client.get( default_category.get_absolute_url(), headers={"hx-request": "true"}, ) assert_not_contains(response, "<h1>") def test_category_threads_list_displays_thread_in_htmx_request( default_category, user_client ): post_thread(default_category, title="Test Thread") response = user_client.get( default_category.get_absolute_url(), headers={"hx-request": "true"}, ) assert_not_contains(response, "<h1>") assert_contains(response, "Test Thread") def test_private__threads_list_displays_empty_in_htmx_request(db, user_client): response = user_client.get( reverse("misago:private-threads"), headers={"hx-request": "true"}, ) assert_not_contains(response, "<h1>") def test_private_threads_list_displays_thread_in_htmx_request( user, private_threads_category, user_client ): thread = post_thread(private_threads_category, title="Test Thread") ThreadParticipant.objects.create(thread=thread, user=user) response = user_client.get( reverse("misago:private-threads"), headers={"hx-request": "true"}, ) assert_not_contains(response, "<h1>") assert_contains(response, "Test Thread") @override_dynamic_settings(index_view="categories") def test_threads_list_displays_thread_with_animation_in_htmx_request( default_category, user_client ): post_thread(default_category, title="Test Thread") response = user_client.get( reverse("misago:threads") + "?animate_new=0", headers={"hx-request": "true"}, ) assert_not_contains(response, "<h1>") assert_contains(response, "Test Thread") assert_contains(response, "threads-list-item-animate") @override_dynamic_settings(index_view="categories") def test_threads_list_displays_thread_without_animation_in_htmx_request( default_category, user_client ): thread = post_thread(default_category, title="Test Thread") response = user_client.get( reverse("misago:threads") + f"?animate_new={thread.last_post_id + 1}", headers={"hx-request": "true"}, ) assert_not_contains(response, "<h1>") assert_contains(response, "Test Thread") assert_not_contains(response, "threads-list-item-animate") @override_dynamic_settings(index_view="categories") def test_threads_list_displays_thread_without_animation_without_htmx( default_category, user_client ): post_thread(default_category, title="Test Thread") response = user_client.get( reverse("misago:threads") + "?animate_new=0", ) assert_contains(response, "<h1>") assert_contains(response, "Test Thread") assert_not_contains(response, "threads-list-item-animate") def test_category_threads_list_displays_thread_with_animation_in_htmx_request( default_category, user_client ): post_thread(default_category, title="Test Thread") response = user_client.get( default_category.get_absolute_url() + "?animate_new=0", headers={"hx-request": "true"}, ) assert_not_contains(response, "<h1>") assert_contains(response, "Test Thread") assert_contains(response, "threads-list-item-animate") def test_category_threads_list_displays_thread_without_animation_in_htmx_request( default_category, user_client ): thread = post_thread(default_category, title="Test Thread") response = user_client.get( default_category.get_absolute_url() + f"?animate_new={thread.last_post_id + 1}", headers={"hx-request": "true"}, ) assert_not_contains(response, "<h1>") assert_contains(response, "Test Thread") assert_not_contains(response, "threads-list-item-animate") def test_category_threads_list_displays_thread_without_animation_without_htmx( default_category, user_client ): post_thread(default_category, title="Test Thread") response = user_client.get( default_category.get_absolute_url() + "?animate_new=0", ) assert_contains(response, "<h1>") assert_contains(response, "Test Thread") assert_not_contains(response, "threads-list-item-animate") def test_private_threads_list_displays_thread_with_animation_in_htmx_request( private_threads_category, user_client, user ): thread = post_thread(private_threads_category, title="Test Thread") ThreadParticipant.objects.create(thread=thread, user=user) response = user_client.get( reverse("misago:private-threads") + "?animate_new=0", headers={"hx-request": "true"}, ) assert_not_contains(response, "<h1>") assert_contains(response, "Test Thread") assert_contains(response, "threads-list-item-animate") def test_private_threads_list_displays_thread_without_animation_in_htmx_request( private_threads_category, user_client, user ): thread = post_thread(private_threads_category, title="Test Thread") ThreadParticipant.objects.create(thread=thread, user=user) response = user_client.get( reverse("misago:private-threads") + f"?animate_new={thread.last_post_id + 1}", headers={"hx-request": "true"}, ) assert_not_contains(response, "<h1>") assert_contains(response, "Test Thread") assert_not_contains(response, "threads-list-item-animate") def test_private_threads_list_displays_thread_without_animation_without_htmx( private_threads_category, user_client, user ): thread = post_thread(private_threads_category, title="Test Thread") ThreadParticipant.objects.create(thread=thread, user=user) response = user_client.get( reverse("misago:private-threads") + "?animate_new=0", ) assert_contains(response, "<h1>") assert_contains(response, "Test Thread") assert_not_contains(response, "threads-list-item-animate") @override_dynamic_settings(index_view="categories") def test_threads_list_raises_404_error_if_filter_is_invalid( default_category, user, user_client ): post_thread(default_category, title="User Thread", poster=user) response = user_client.get(reverse("misago:threads", kwargs={"filter": "invalid"})) assert response.status_code == 404 @override_dynamic_settings(index_view="categories") def test_threads_list_filters_threads(default_category, user, user_client): visible_thread = post_thread(default_category, title="User Thread", poster=user) hidden_thread = post_thread(default_category, title="Hidden Thread") response = user_client.get(reverse("misago:threads", kwargs={"filter": "my"})) assert_contains(response, visible_thread.title) assert_not_contains(response, hidden_thread.title) @override_dynamic_settings(index_view="threads") def test_index_threads_list_filters_threads(default_category, user, user_client): visible_thread = post_thread(default_category, title="User Thread", poster=user) hidden_thread = post_thread(default_category, title="Hidden Thread") response = user_client.get(reverse("misago:threads", kwargs={"filter": "my"})) assert_contains(response, visible_thread.title) assert_not_contains(response, hidden_thread.title) @override_dynamic_settings(index_view="categories") def test_threads_list_builds_valid_filters_urls(user_client): response = user_client.get(reverse("misago:threads")) assert_contains(response, reverse("misago:threads", kwargs={"filter": "my"})) @override_dynamic_settings(index_view="threads") def test_index_threads_list_builds_valid_filters_urls(user_client): response = user_client.get(reverse("misago:index")) assert_contains(response, reverse("misago:threads", kwargs={"filter": "my"})) def test_category_threads_list_raises_404_error_if_filter_is_invalid( default_category, user, user_client ): post_thread(default_category, title="User Thread", poster=user) response = user_client.get( reverse( "misago:category", kwargs={ "id": default_category.id, "slug": default_category.slug, "filter": "invalid", }, ) ) assert response.status_code == 404 def test_category_threads_list_filters_threads(default_category, user, user_client): visible_thread = post_thread(default_category, title="User Thread", poster=user) hidden_thread = post_thread(default_category, title="Other Thread") response = user_client.get( reverse( "misago:category", kwargs={ "id": default_category.id, "slug": default_category.slug, "filter": "my", }, ) ) assert_contains(response, visible_thread.title) assert_not_contains(response, hidden_thread.title) def test_private_threads_list_raises_404_error_if_filter_is_invalid( private_threads_category, user, user_client ): thread = post_thread(private_threads_category, title="User Thread", poster=user) ThreadParticipant.objects.create(thread=thread, user=user) response = user_client.get( reverse("misago:private-threads", kwargs={"filter": "invalid"}) ) assert response.status_code == 404 def test_private_threads_list_filters_threads( private_threads_category, user, user_client ): visible_thread = post_thread( private_threads_category, title="User Thread", poster=user ) hidden_thread = post_thread(private_threads_category, title="Other Thread") ThreadParticipant.objects.create(thread=visible_thread, user=user) ThreadParticipant.objects.create(thread=hidden_thread, user=user) response = user_client.get( reverse("misago:private-threads", kwargs={"filter": "my"}) ) assert_contains(response, visible_thread.title) assert_not_contains(response, hidden_thread.title) @override_dynamic_settings(index_view="categories") @patch("misago.threads.views.list.paginate_queryset", side_effect=EmptyPageError(10)) def test_site_threads_list_redirects_to_last_page_for_invalid_cursor( mock_pagination, db, client ): response = client.get(reverse("misago:threads")) assert response.status_code == 302 assert response["location"] == reverse("misago:threads") + "?cursor=10" mock_pagination.assert_called_once() @patch("misago.threads.views.list.paginate_queryset", side_effect=EmptyPageError(10)) def test_category_threads_list_redirects_to_last_page_for_invalid_cursor( mock_pagination, default_category, client ): response = client.get(default_category.get_absolute_url()) assert response.status_code == 302 assert response["location"] == default_category.get_absolute_url() + "?cursor=10" mock_pagination.assert_called_once() @patch("misago.threads.views.list.paginate_queryset", side_effect=EmptyPageError(10)) def test_private_threads_list_redirects_to_last_page_for_invalid_cursor( mock_pagination, user_client ): response = user_client.get(reverse("misago:private-threads")) assert response.status_code == 302 assert response["location"] == reverse("misago:private-threads") + "?cursor=10" mock_pagination.assert_called_once() def test_category_threads_list_returns_404_for_top_level_vanilla_category_without_children( default_category, client ): default_category.is_vanilla = True default_category.list_children_threads = False default_category.save() response = client.get(default_category.get_absolute_url()) assert response.status_code == 404 def test_category_threads_list_returns_404_for_top_level_vanilla_category_with_invisible_children( default_category, child_category, client ): default_category.is_vanilla = True default_category.list_children_threads = False default_category.save() CategoryGroupPermission.objects.filter(category=child_category).delete() response = client.get(default_category.get_absolute_url()) assert response.status_code == 404 def test_category_threads_list_renders_for_top_level_vanilla_category_with_children( default_category, child_category, client ): default_category.is_vanilla = True default_category.list_children_threads = False default_category.save() response = client.get(default_category.get_absolute_url()) assert response.status_code == 200 def test_category_threads_list_renders_for_nested_vanilla_category_without_children( child_category, client ): child_category.is_vanilla = True child_category.list_children_threads = False child_category.save() response = client.get(child_category.get_absolute_url()) assert response.status_code == 200 @override_dynamic_settings(index_view="categories") def test_site_threads_list_renders_unread_thread(user, user_client, default_category): user.joined_on = user.joined_on.replace(year=2012) user.save() unread_thread = post_thread(default_category, title="Unread Thread") response = user_client.get(reverse("misago:threads")) assert_contains(response, "Has unread posts") assert_contains(response, unread_thread.title) def test_category_threads_list_renders_unread_thread( user, user_client, default_category ): user.joined_on = user.joined_on.replace(year=2012) user.save() unread_thread = post_thread(default_category, title="Unread Thread") response = user_client.get(default_category.get_absolute_url()) assert_contains(response, "Has unread posts") assert_contains(response, unread_thread.title) def test_private_threads_list_renders_unread_thread( user, user_client, private_threads_category ): user.joined_on = user.joined_on.replace(year=2012) user.save() unread_thread = post_thread(private_threads_category, title="Unread Thread") ThreadParticipant.objects.create(thread=unread_thread, user=user) response = user_client.get(reverse("misago:private-threads")) assert_contains(response, "Has unread posts") assert_contains(response, unread_thread.title)
23,457
Python
.py
490
42.946939
98
0.739784
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,130
test_privatethread_reply_api.py
rafalp_Misago/misago/threads/tests/test_privatethread_reply_api.py
from unittest.mock import patch from .. import test from ...users.test import create_test_user from ..models import ThreadParticipant from .test_privatethreads import PrivateThreadsTestCase class PrivateThreadReplyApiTestCase(PrivateThreadsTestCase): def setUp(self): super().setUp() self.thread = test.post_thread(self.category, poster=self.user) self.api_link = self.thread.get_posts_api_url() self.other_user = create_test_user("Other_User", "otheruser@example.com") @patch( "misago.threads.api.postingendpoint.notifications.notify_on_new_thread_reply" ) def test_reply_private_thread(self, notify_on_new_thread_reply_mock): """api sets other private thread participants sync thread flag""" ThreadParticipant.objects.set_owner(self.thread, self.user) ThreadParticipant.objects.add_participants(self.thread, [self.other_user]) response = self.client.post( self.api_link, data={"post": "This is test response!"} ) self.assertEqual(response.status_code, 200) # don't count private thread replies self.reload_user() self.assertEqual(self.user.threads, 0) self.assertEqual(self.user.posts, 0) self.assertEqual(self.user.audittrail_set.count(), 1) # valid user was flagged to sync self.user.refresh_from_db() self.assertFalse(self.user.sync_unread_private_threads) self.other_user.refresh_from_db() self.assertTrue(self.other_user.sync_unread_private_threads)
1,564
Python
.py
32
41.40625
85
0.706114
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,131
test_new_reply_notification.py
rafalp_Misago/misago/threads/tests/test_new_reply_notification.py
from django.urls import reverse from ..models import ThreadParticipant def test_notify_about_new_reply_task_is_triggered_by_new_thread_reply( notify_on_new_thread_reply_mock, user_client, thread ): response = user_client.post( reverse("misago:api:thread-post-list", kwargs={"thread_pk": thread.pk}), data={ "post": "Lorem ipsum dolor met", }, ) assert response.status_code == 200 data = response.json() notify_on_new_thread_reply_mock.delay.assert_called_once_with(data["id"]) def test_notify_about_new_reply_task_is_triggered_by_new_private_thread_reply( notify_on_new_thread_reply_mock, user, user_client, private_thread, ): ThreadParticipant.objects.create(thread=private_thread, user=user) response = user_client.post( reverse( "misago:api:private-thread-post-list", kwargs={"thread_pk": private_thread.pk}, ), data={ "post": "Lorem ipsum dolor met", }, ) assert response.status_code == 200 data = response.json() notify_on_new_thread_reply_mock.delay.assert_called_once_with(data["id"]) def test_notify_about_new_reply_task_is_not_triggered_on_new_thread_start( notify_on_new_thread_reply_mock, user_client, default_category ): response = user_client.post( reverse("misago:api:thread-list"), data={ "category": default_category.pk, "title": "Test thread", "post": "Lorem ipsum dolor met", }, ) assert response.status_code == 200 notify_on_new_thread_reply_mock.delay.assert_not_called() def test_notify_about_new_reply_task_is_not_triggered_on_new_private_thread_start( notify_on_new_private_thread_mock, notify_on_new_thread_reply_mock, other_user, user_client, ): response = user_client.post( reverse("misago:api:private-thread-list"), data={ "to": [other_user.username], "title": "Test thread", "post": "Lorem ipsum dolor met", }, ) assert response.status_code == 200 notify_on_new_thread_reply_mock.delay.assert_not_called() def test_notify_about_new_reply_task_is_not_triggered_on_thread_reply_edit( notify_on_new_thread_reply_mock, user_client, thread, user_reply, ): response = user_client.put( reverse( "misago:api:thread-post-detail", kwargs={"thread_pk": thread.id, "pk": user_reply.id}, ), json={ "post": "Edited reply", }, ) assert response.status_code == 200 notify_on_new_thread_reply_mock.delay.assert_not_called() def test_notify_about_new_reply_task_is_not_triggered_on_private_thread_reply_edit( notify_on_new_thread_reply_mock, user, user_client, private_thread, private_thread_user_reply, ): ThreadParticipant.objects.create(thread=private_thread, user=user) response = user_client.put( reverse( "misago:api:private-thread-post-detail", kwargs={"thread_pk": private_thread.id, "pk": private_thread_user_reply.id}, ), json={ "post": "Edited reply", }, ) assert response.status_code == 200 notify_on_new_thread_reply_mock.delay.assert_not_called()
3,346
Python
.py
98
27.27551
88
0.643278
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,132
test_privatethread_start_api.py
rafalp_Misago/misago/threads/tests/test_privatethread_start_api.py
from unittest.mock import patch from django.contrib.auth import get_user_model from django.urls import reverse from ...acl.test import patch_user_acl from ...categories.models import Category from ...conf.test import override_dynamic_settings from ...users.test import AuthenticatedUserTestCase, create_test_user from ..models import ThreadParticipant from ..test import other_user_cant_use_private_threads User = get_user_model() class StartPrivateThreadTests(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.private_threads() self.api_link = reverse("misago:api:private-thread-list") self.other_user = create_test_user("Other_User", "otheruser@example.com") def test_cant_start_thread_as_guest(self): """user has to be authenticated to be able to post private thread""" self.logout_user() response = self.client.post(self.api_link) self.assertEqual(response.status_code, 403) @patch_user_acl({"can_use_private_threads": False}) def test_cant_use_private_threads(self): """has no permission to use private threads""" response = self.client.post(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual(response.json(), {"detail": "You can't use private threads."}) @patch_user_acl({"can_start_private_threads": False}) def test_cant_start_private_thread(self): """permission to start private thread is validated""" response = self.client.post(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't start private threads."} ) def test_empty_data(self): """no data sent handling has no showstoppers""" response = self.client.post(self.api_link, data={}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "to": ["This field is required."], "title": ["You have to enter a thread title."], "post": ["You have to enter a message."], }, ) def test_title_is_validated(self): """title is validated""" response = self.client.post( self.api_link, data={ "to": [self.other_user.username], "title": "------", "post": "Lorem ipsum dolor met, sit amet elit!", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"title": ["Thread title should contain alpha-numeric characters."]}, ) def test_post_is_validated(self): """post is validated""" response = self.client.post( self.api_link, data={ "to": [self.other_user.username], "title": "Lorem ipsum dolor met", "post": "a", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "post": [ "Posted message should be at least 5 characters long (it has 1)." ] }, ) def test_cant_invite_self(self): """api validates that you cant invite yourself to private thread""" response = self.client.post( self.api_link, data={ "to": [self.user.username], "title": "Lorem ipsum dolor met", "post": "Lorem ipsum dolor.", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "to": [ "You can't include yourself on the list " "of users to invite to new thread." ] }, ) def test_cant_invite_nonexisting(self): """api validates that you cant invite nonexisting user to thread""" response = self.client.post( self.api_link, data={ "to": ["Ab", "Cd"], "title": "Lorem ipsum dolor met", "post": "Lorem ipsum dolor.", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"to": ["One or more users could not be found: ab, cd"]} ) def test_cant_invite_too_many(self): """api validates that you cant invite too many users to thread""" response = self.client.post( self.api_link, data={ "to": ["Username%s" % i for i in range(50)], "title": "Lorem ipsum dolor met", "post": "Lorem ipsum dolor.", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "to": [ "You can't add more than 3 users to private thread " "(you've added 50)." ] }, ) @patch_user_acl(other_user_cant_use_private_threads) def test_cant_invite_no_permission(self): """api validates invited user permission to private thread""" response = self.client.post( self.api_link, data={ "to": [self.other_user.username], "title": "Lorem ipsum dolor met", "post": "Lorem ipsum dolor.", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"to": ["Other_User can't participate in private threads."]}, ) def test_cant_invite_blocking(self): """api validates that you cant invite blocking user to thread""" self.other_user.blocks.add(self.user) response = self.client.post( self.api_link, data={ "to": [self.other_user.username], "title": "Lorem ipsum dolor met", "post": "Lorem ipsum dolor.", }, ) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"to": ["Other_User is blocking you."]}) @patch_user_acl({"can_add_everyone_to_private_threads": 1}) def test_cant_invite_blocking_override(self): """api validates that you cant invite blocking user to thread""" self.other_user.blocks.add(self.user) response = self.client.post( self.api_link, data={ "to": [self.other_user.username], "title": "-----", "post": "Lorem ipsum dolor.", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"title": ["Thread title should contain alpha-numeric characters."]}, ) def test_cant_invite_followers_only(self): """api validates that you cant invite followers-only user to thread""" user_constant = User.LIMIT_INVITES_TO_FOLLOWED self.other_user.limits_private_thread_invites_to = user_constant self.other_user.save() response = self.client.post( self.api_link, data={ "to": [self.other_user.username], "title": "Lorem ipsum dolor met", "post": "Lorem ipsum dolor.", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "to": [ "Other_User limits invitations to private threads to followed users." ] }, ) # allow us to bypass following check with patch_user_acl({"can_add_everyone_to_private_threads": 1}): response = self.client.post( self.api_link, data={ "to": [self.other_user.username], "title": "-----", "post": "Lorem ipsum dolor.", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"title": ["Thread title should contain alpha-numeric characters."]}, ) # make user follow us self.other_user.follows.add(self.user) response = self.client.post( self.api_link, data={ "to": [self.other_user.username], "title": "-----", "post": "Lorem ipsum dolor.", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"title": ["Thread title should contain alpha-numeric characters."]}, ) def test_cant_invite_anyone(self): """api validates that you cant invite nobody user to thread""" user_constant = User.LIMIT_INVITES_TO_NOBODY self.other_user.limits_private_thread_invites_to = user_constant self.other_user.save() response = self.client.post( self.api_link, data={ "to": [self.other_user.username], "title": "Lorem ipsum dolor met", "post": "Lorem ipsum dolor.", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"to": ["Other_User has disabled invitations to private threads."]}, ) # allow us to bypass user preference check with patch_user_acl({"can_add_everyone_to_private_threads": 1}): response = self.client.post( self.api_link, data={ "to": [self.other_user.username], "title": "-----", "post": "Lorem ipsum dolor.", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"title": ["Thread title should contain alpha-numeric characters."]}, ) @override_dynamic_settings(forum_address="http://test.com/") @patch("misago.threads.participants.notify_on_new_private_thread") def test_can_start_thread(self, notify_on_new_private_thread_mock): """endpoint creates new thread""" response = self.client.post( self.api_link, data={ "to": [self.other_user.username], "title": "Hello, I am test thread!", "post": "Lorem ipsum dolor met!", }, ) self.assertEqual(response.status_code, 200) thread = self.user.thread_set.all()[:1][0] response_json = response.json() self.assertEqual(response_json["url"], thread.get_absolute_url()) response = self.client.get(thread.get_absolute_url()) self.assertContains(response, self.category.name) self.assertContains(response, thread.title) self.assertContains(response, "<p>Lorem ipsum dolor met!</p>") # don't count private threads self.reload_user() self.assertEqual(self.user.threads, 0) self.assertEqual(self.user.posts, 0) self.assertEqual(thread.category_id, self.category.pk) self.assertEqual(thread.title, "Hello, I am test thread!") self.assertEqual(thread.starter_id, self.user.id) self.assertEqual(thread.starter_name, self.user.username) self.assertEqual(thread.starter_slug, self.user.slug) self.assertEqual(thread.last_poster_id, self.user.id) self.assertEqual(thread.last_poster_name, self.user.username) self.assertEqual(thread.last_poster_slug, self.user.slug) post = self.user.post_set.all()[:1][0] self.assertEqual(post.category_id, self.category.pk) self.assertEqual(post.original, "Lorem ipsum dolor met!") self.assertEqual(post.poster_id, self.user.id) self.assertEqual(post.poster_name, self.user.username) self.assertEqual(self.user.audittrail_set.count(), 1) # thread has two participants self.assertEqual(thread.participants.count(), 2) # we are thread owner ThreadParticipant.objects.get(thread=thread, user=self.user, is_owner=True) # other user was added to thread ThreadParticipant.objects.get( thread=thread, user=self.other_user, is_owner=False ) # other user has sync_unread_private_threads flag self.other_user.refresh_from_db() self.assertTrue(self.other_user.sync_unread_private_threads) # notification about new private thread was triggered notify_on_new_private_thread_mock.delay.assert_called_once_with( self.user.id, thread.id, [self.other_user.id], ) @patch("misago.threads.participants.notify_on_new_private_thread") def test_post_unicode(self, notify_on_new_private_thread_mock): """unicode characters can be posted""" response = self.client.post( self.api_link, data={ "to": [self.other_user.username], "title": "Brzęczyżczykiewicz", "post": "Chrzążczyżewoszyce, powiat Łękółody.", }, ) self.assertEqual(response.status_code, 200)
13,621
Python
.py
333
29.42042
89
0.562665
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,133
test_treesmap.py
rafalp_Misago/misago/threads/tests/test_treesmap.py
from django.test import TestCase from ...categories.models import Category from ..threadtypes.treesmap import TreesMap THREAD_TYPE = "misago.threads.threadtypes.thread.Thread" class TreesMapTests(TestCase): def test_load_types(self): """TreesMap().load_types() loads types modules""" trees_map = TreesMap(None) types = trees_map.load_types([THREAD_TYPE]) self.assertEqual(len(types), 1, "expected to load only one thread type") self.assertIn("root_category", types, "invalid thread type was loaded") def test_load_trees(self): """TreesMap().load_trees() loads trees ids""" trees_map = TreesMap(None) types = trees_map.load_types([THREAD_TYPE]) trees = trees_map.load_trees(types) tree_id = Category.objects.get(special_role="root_category").tree_id self.assertEqual(len(trees), 1, "expected to load only one tree") self.assertEqual( trees[tree_id].root_name, "root_category", "invalid tree was loaded" ) def test_get_roots(self): """TreesMap().get_roots() returns roots to trees dict""" trees_map = TreesMap(None) types = trees_map.load_types([THREAD_TYPE]) trees = trees_map.load_trees(types) roots = trees_map.get_roots(trees) tree_id = Category.objects.get(special_role="root_category").tree_id self.assertEqual(len(roots), 1, "expected to load only one root") self.assertIn("root_category", roots, "invalid root was loaded") self.assertEqual(roots["root_category"], tree_id, "invalid tree_id was loaded") def test_load(self): """TreesMap().load() populates trees map""" trees_map = TreesMap([THREAD_TYPE]) self.assertFalse( trees_map.is_loaded, "trees map should be not loaded by default" ) trees_map.load() self.assertTrue( trees_map.is_loaded, "trees map should be loaded after call to load()" ) self.assertEqual(len(trees_map.types), 1, "expected to load one type") self.assertEqual(len(trees_map.trees), 1, "expected to load one tree") self.assertEqual(len(trees_map.roots), 1, "expected to load one root") tree_id = Category.objects.get(special_role="root_category").tree_id self.assertIn( "root_category", trees_map.types, "invalid thread type was loaded" ) self.assertEqual( trees_map.trees[tree_id].root_name, "root_category", "invalid tree was loaded", ) self.assertIn("root_category", trees_map.roots, "invalid root was loaded") def test_get_type_for_tree_id(self): """TreesMap().get_type_for_tree_id() returns type for valid id""" trees_map = TreesMap([THREAD_TYPE]) trees_map.load() tree_id = Category.objects.get(special_role="root_category").tree_id thread_type = trees_map.get_type_for_tree_id(tree_id) self.assertEqual( thread_type.root_name, "root_category", "returned invalid thread type for given tree id", ) try: trees_map.get_type_for_tree_id(tree_id + 1000) self.fail("invalid tree id should cause KeyError being raised") except KeyError as e: self.assertIn( "tree id has no type defined", str(e), "invalid exception message as given", ) def test_get_tree_id_for_root(self): """TreesMap().get_tree_id_for_root() returns tree id for valid type name""" trees_map = TreesMap([THREAD_TYPE]) trees_map.load() in_db_tree_id = Category.objects.get(special_role="root_category").tree_id tree_id = trees_map.get_tree_id_for_root("root_category") self.assertEqual( tree_id, in_db_tree_id, "root name didn't match one in database" ) try: trees_map.get_tree_id_for_root("hurr_durr") self.fail("invalid root name should cause KeyError being raised") except KeyError as e: self.assertIn( '"hurr_durr" root has no tree defined', str(e), "invalid exception message as given", )
4,310
Python
.py
92
36.913043
87
0.619275
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,134
test_thread_pollcreate_api.py
rafalp_Misago/misago/threads/tests/test_thread_pollcreate_api.py
from django.urls import reverse from ...acl.test import patch_user_acl from ..models import Poll, Thread from ..serializers.poll import MAX_POLL_OPTIONS from ..test import patch_category_acl from .test_thread_poll_api import ThreadPollApiTestCase class ThreadPollCreateTests(ThreadPollApiTestCase): def test_anonymous(self): """api requires you to sign in to create poll""" self.logout_user() response = self.post(self.api_link) self.assertEqual(response.status_code, 403) def test_invalid_thread_id(self): """api validates that thread id is integer""" api_link = reverse( "misago:api:thread-poll-list", kwargs={"thread_pk": "kjha6dsa687sa"} ) response = self.post(api_link) self.assertEqual(response.status_code, 404) def test_nonexistant_thread_id(self): """api validates that thread exists""" api_link = reverse( "misago:api:thread-poll-list", kwargs={"thread_pk": self.thread.pk + 1} ) response = self.post(api_link) self.assertEqual(response.status_code, 404) @patch_user_acl({"can_start_polls": 0}) def test_no_permission(self): """api validates that user has permission to start poll in thread""" response = self.post(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual(response.json(), {"detail": "You can't start polls."}) @patch_user_acl({"can_start_polls": 1}) @patch_category_acl({"can_close_threads": False}) def test_closed_thread_no_permission(self): """api validates that user has permission to start poll in closed thread""" self.thread.is_closed = True self.thread.save() response = self.post(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This thread is closed. You can't start polls in it."}, ) @patch_user_acl({"can_start_polls": 1}) @patch_category_acl({"can_close_threads": True}) def test_closed_thread(self): """api validates that user has permission to start poll in closed thread""" self.thread.is_closed = True self.thread.save() response = self.post(self.api_link) self.assertEqual(response.status_code, 400) @patch_user_acl({"can_start_polls": 1}) @patch_category_acl({"can_close_threads": False}) def test_closed_category_no_permission(self): """api validates that user has permission to start poll in closed category""" self.category.is_closed = True self.category.save() response = self.post(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This category is closed. You can't start polls in it."}, ) @patch_user_acl({"can_start_polls": 1}) @patch_category_acl({"can_close_threads": True}) def test_closed_category(self): """api validates that user has permission to start poll in closed category""" self.category.is_closed = True self.category.save() response = self.post(self.api_link) self.assertEqual(response.status_code, 400) @patch_user_acl({"can_start_polls": 1}) def test_other_user_thread_no_permission(self): """ api validates that user has permission to start poll in other user's thread """ self.thread.starter = None self.thread.save() response = self.post(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't start polls in other users threads."} ) @patch_user_acl({"can_start_polls": 2}) def test_other_user_thread(self): """ api validates that user has permission to start poll in other user's thread """ self.thread.starter = None self.thread.save() response = self.post(self.api_link) self.assertEqual(response.status_code, 400) def test_no_permission_poll_exists(self): """api validates that user can't start second poll in thread""" self.thread.poll = Poll.objects.create( thread=self.thread, category=self.category, poster_name="Test", poster_slug="test", length=30, question="Test", choices=[{"hash": "t3st"}], allowed_choices=1, ) response = self.post(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "There's already a poll in this thread."} ) def test_empty_data(self): """api handles empty request data""" response = self.post(self.api_link) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual(len(response_json), 4) def test_length_validation(self): """api validates poll's length""" response = self.post(self.api_link, data={"length": -1}) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["length"], ["Ensure this value is greater than or equal to 0."], ) response = self.post(self.api_link, data={"length": 200}) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["length"], ["Ensure this value is less than or equal to 180."] ) def test_question_validation(self): """api validates question length""" response = self.post(self.api_link, data={"question": "abcd" * 255}) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["question"], ["Ensure this field has no more than 255 characters."], ) def test_validate_choice_length(self): """api validates single choice length""" response = self.post( self.api_link, data={"choices": [{"hash": "qwertyuiopas", "label": ""}]} ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["choices"], ["One or more poll choices are invalid."] ) response = self.post( self.api_link, data={"choices": [{"hash": "qwertyuiopas", "label": "abcd" * 255}]}, ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["choices"], ["One or more poll choices are invalid."] ) def test_validate_two_choices(self): """api validates that there are at least two choices in poll""" response = self.post(self.api_link, data={"choices": [{"label": "Choice"}]}) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["choices"], ["You need to add at least two choices to a poll."], ) def test_validate_max_choices(self): """api validates that there are no more choices in poll than allowed number""" response = self.post( self.api_link, data={"choices": [{"label": "Choice"}] * (MAX_POLL_OPTIONS + 1)}, ) self.assertEqual(response.status_code, 400) error_formats = (MAX_POLL_OPTIONS, MAX_POLL_OPTIONS + 1) response_json = response.json() self.assertEqual( response_json["choices"], [ "You can't add more than %s options to a single poll (added %s)." % error_formats ], ) def test_allowed_choices_validation(self): """api validates allowed choices number""" response = self.post(self.api_link, data={"allowed_choices": 0}) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["allowed_choices"], ["Ensure this value is greater than or equal to 1."], ) response = self.post( self.api_link, data={ "length": 0, "question": "Lorem ipsum", "allowed_choices": 3, "choices": [{"label": "Choice"}, {"label": "Choice"}], }, ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["non_field_errors"], ["Number of allowed choices can't be greater than number of all choices."], ) def test_poll_created(self): """api creates public poll if provided with valid data""" response = self.post( self.api_link, data={ "length": 40, "question": "Select two best colors", "allowed_choices": 2, "allow_revotes": True, "is_public": True, "choices": [{"label": "\nRed "}, {"label": "Green"}, {"label": "Blue"}], }, ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["poster_name"], self.user.username) self.assertEqual(response_json["length"], 40) self.assertEqual(response_json["question"], "Select two best colors") self.assertEqual(response_json["allowed_choices"], 2) self.assertTrue(response_json["allow_revotes"]) self.assertEqual(response_json["votes"], 0) self.assertTrue(response_json["is_public"]) self.assertEqual(len(response_json["choices"]), 3) self.assertEqual(len({c["hash"] for c in response_json["choices"]}), 3) self.assertEqual( [c["label"] for c in response_json["choices"]], ["Red", "Green", "Blue"] ) thread = Thread.objects.get(pk=self.thread.pk) self.assertTrue(thread.has_poll) poll = thread.poll self.assertEqual(poll.category_id, self.category.id) self.assertEqual(poll.thread_id, self.thread.id) self.assertEqual(poll.poster_id, self.user.id) self.assertEqual(poll.poster_name, self.user.username) self.assertEqual(poll.poster_slug, self.user.slug) self.assertEqual(poll.length, 40) self.assertEqual(poll.question, "Select two best colors") self.assertEqual(poll.allowed_choices, 2) self.assertTrue(poll.allow_revotes) self.assertEqual(poll.votes, 0) self.assertTrue(poll.is_public) self.assertEqual(len(poll.choices), 3) self.assertEqual(len({c["hash"] for c in poll.choices}), 3) self.assertEqual(self.user.audittrail_set.count(), 1)
11,084
Python
.py
252
34.392857
88
0.610632
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,135
test_clearattachments.py
rafalp_Misago/misago/threads/tests/test_clearattachments.py
from datetime import timedelta from io import StringIO import pytest from django.core import management from django.utils import timezone from ...conf.test import override_dynamic_settings from ..management.commands import clearattachments from ..models import Attachment, AttachmentType @pytest.fixture def attachment_type(db): return AttachmentType.objects.order_by("id").last() def create_attachment(attachment_type, uploaded_on, post=None): return Attachment.objects.create( secret=Attachment.generate_new_secret(), post=post, filetype=attachment_type, size=1000, uploaded_on=uploaded_on, uploader_name="User", uploader_slug="user", filename="testfile_%s.zip" % (Attachment.objects.count() + 1), ) def call_command(): command = clearattachments.Command() out = StringIO() management.call_command(command, stdout=out) return out.getvalue().strip().splitlines()[-1].strip() def test_command_works_if_there_are_no_attachments(db): command_output = call_command() assert command_output == "No unused attachments were cleared" @override_dynamic_settings(unused_attachments_lifetime=2) def test_recent_attachment_is_not_cleared(attachment_type): attachment = create_attachment(attachment_type, timezone.now()) command_output = call_command() assert command_output == "No unused attachments were cleared" @override_dynamic_settings(unused_attachments_lifetime=2) def test_old_used_attachment_is_not_cleared(attachment_type, post): uploaded_on = timezone.now() - timedelta(hours=3) attachment = create_attachment(attachment_type, uploaded_on, post) command_output = call_command() assert command_output == "No unused attachments were cleared" @override_dynamic_settings(unused_attachments_lifetime=2) def test_old_unused_attachment_is_cleared(attachment_type): uploaded_on = timezone.now() - timedelta(hours=3) attachment = create_attachment(attachment_type, uploaded_on) command_output = call_command() assert command_output == "Cleared 1 attachments" with pytest.raises(Attachment.DoesNotExist): attachment.refresh_from_db()
2,197
Python
.py
49
40.285714
70
0.752582
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,136
test_threads_moderation.py
rafalp_Misago/misago/threads/tests/test_threads_moderation.py
from .. import moderation, test from ...categories.models import Category from ...users.test import AuthenticatedUserTestCase from ..models import Thread class MockRequest: def __init__(self, user): self.user = user self.user_ip = "123.14.15.222" class ThreadsModerationTests(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.request = MockRequest(self.user) self.category = Category.objects.all_categories()[:1][0] self.thread = test.post_thread(self.category) def reload_thread(self): self.thread = Thread.objects.get(pk=self.thread.pk) def test_change_thread_title(self): """change_thread_title changes thread's title and slug""" self.assertTrue( moderation.change_thread_title( self.request, self.thread, "New title is here!" ) ) self.reload_thread() self.assertEqual(self.thread.title, "New title is here!") self.assertEqual(self.thread.slug, "new-title-is-here") event = self.thread.last_post self.assertTrue(event.is_event) self.assertEqual(event.event_type, "changed_title") def test_pin_globally_thread(self): """pin_thread_globally makes thread pinned globally""" self.assertEqual(self.thread.weight, 0) self.assertTrue(moderation.pin_thread_globally(self.request, self.thread)) self.reload_thread() self.assertEqual(self.thread.weight, 2) event = self.thread.last_post self.assertTrue(event.is_event) self.assertEqual(event.event_type, "pinned_globally") def test_pin_globally_invalid_thread(self): """ pin_thread_globally returns false for already globally pinned thread """ self.thread.weight = 2 self.assertFalse(moderation.pin_thread_globally(self.request, self.thread)) self.assertEqual(self.thread.weight, 2) def test_pin_thread_locally(self): """pin_thread_locally makes thread pinned locally""" self.assertEqual(self.thread.weight, 0) self.assertTrue(moderation.pin_thread_locally(self.request, self.thread)) self.reload_thread() self.assertEqual(self.thread.weight, 1) event = self.thread.last_post self.assertTrue(event.is_event) self.assertEqual(event.event_type, "pinned_locally") def test_pin_invalid_thread(self): """pin_thread_locally returns false for already locally pinned thread""" self.thread.weight = 1 self.assertFalse(moderation.pin_thread_locally(self.request, self.thread)) self.assertEqual(self.thread.weight, 1) def test_unpin_globally_pinned_thread(self): """unpin_thread unpins globally pinned thread""" moderation.pin_thread_globally(self.request, self.thread) self.assertEqual(self.thread.weight, 2) self.assertTrue(moderation.unpin_thread(self.request, self.thread)) self.reload_thread() self.assertEqual(self.thread.weight, 0) event = self.thread.last_post self.assertTrue(event.is_event) self.assertEqual(event.event_type, "unpinned") def test_unpin_locally_pinned_thread(self): """unpin_thread unpins locally pinned thread""" moderation.pin_thread_locally(self.request, self.thread) self.assertEqual(self.thread.weight, 1) self.assertTrue(moderation.unpin_thread(self.request, self.thread)) self.reload_thread() self.assertEqual(self.thread.weight, 0) event = self.thread.last_post self.assertTrue(event.is_event) self.assertEqual(event.event_type, "unpinned") def test_unpin_weightless_thread(self): """unpin_thread returns false for already weightless thread""" self.assertFalse(moderation.unpin_thread(self.request, self.thread)) self.assertEqual(self.thread.weight, 0) def test_approve_thread(self): """approve_thread approves unapproved thread""" self.thread = test.post_thread(self.category, is_unapproved=True) self.assertTrue(self.thread.is_unapproved) self.assertTrue(self.thread.first_post.is_unapproved) self.assertTrue(moderation.approve_thread(self.request, self.thread)) self.reload_thread() self.assertFalse(self.thread.is_unapproved) self.assertFalse(self.thread.first_post.is_unapproved) event = self.thread.last_post self.assertTrue(event.is_event) self.assertEqual(event.event_type, "approved") def test_move_thread(self): """moves_thread moves unapproved thread to other category""" root_category = Category.objects.root_category() Category(name="New Category", slug="new-category").insert_at( root_category, position="last-child", save=True ) new_category = Category.objects.get(slug="new-category") self.assertEqual(self.thread.category, self.category) self.assertTrue(moderation.move_thread(self.request, self.thread, new_category)) self.reload_thread() self.assertEqual(self.thread.category, new_category) event = self.thread.last_post self.assertTrue(event.is_event) self.assertEqual(event.event_type, "moved") def test_move_thread_to_same_category(self): """moves_thread does not move thread to same category it is in""" self.assertEqual(self.thread.category, self.category) self.assertFalse( moderation.move_thread(self.request, self.thread, self.category) ) self.reload_thread() self.assertEqual(self.thread.category, self.category) def test_close_thread(self): """close_thread closes thread""" self.assertFalse(self.thread.is_closed) self.assertTrue(moderation.close_thread(self.request, self.thread)) self.reload_thread() self.assertTrue(self.thread.is_closed) event = self.thread.last_post self.assertTrue(event.is_event) self.assertEqual(event.event_type, "closed") def test_close_invalid_thread(self): """close_thread fails gracefully for opened thread""" moderation.close_thread(self.request, self.thread) self.reload_thread() self.assertTrue(self.thread.is_closed) self.assertFalse(moderation.close_thread(self.request, self.thread)) def test_open_thread(self): """open_thread closes thread""" moderation.close_thread(self.request, self.thread) self.reload_thread() self.assertTrue(self.thread.is_closed) self.assertTrue(moderation.open_thread(self.request, self.thread)) self.reload_thread() self.assertFalse(self.thread.is_closed) event = self.thread.last_post self.assertTrue(event.is_event) self.assertEqual(event.event_type, "opened") def test_open_invalid_thread(self): """open_thread fails gracefully for opened thread""" self.assertFalse(self.thread.is_closed) self.assertFalse(moderation.open_thread(self.request, self.thread)) def test_hide_thread(self): """hide_thread hides thread""" self.assertFalse(self.thread.is_hidden) self.assertTrue(moderation.hide_thread(self.request, self.thread)) self.reload_thread() self.assertTrue(self.thread.is_hidden) event = self.thread.last_post self.assertTrue(event.is_event) self.assertEqual(event.event_type, "hid") def test_hide_hidden_thread(self): """hide_thread fails gracefully for hidden thread""" self.thread.is_hidden = True self.assertFalse(moderation.hide_thread(self.request, self.thread)) def test_unhide_thread(self): """unhide_thread unhides thread""" moderation.hide_thread(self.request, self.thread) self.reload_thread() self.assertTrue(self.thread.is_hidden) self.assertTrue(moderation.unhide_thread(self.request, self.thread)) self.reload_thread() self.assertFalse(self.thread.is_hidden) event = self.thread.last_post self.assertTrue(event.is_event) self.assertEqual(event.event_type, "unhid") def test_unhide_visible_thread(self): """unhide_thread fails gracefully for visible thread""" self.assertFalse(moderation.unhide_thread(self.request, self.thread)) def test_delete_thread(self): """delete_thread deletes thread""" self.assertTrue(moderation.delete_thread(self.request, self.thread)) with self.assertRaises(Thread.DoesNotExist): self.reload_thread()
8,713
Python
.py
179
39.916201
88
0.683757
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,137
test_validators.py
rafalp_Misago/misago/threads/tests/test_validators.py
from unittest.mock import Mock from django.core.exceptions import ValidationError from django.test import TestCase from ..validators import validate_post_length, validate_thread_title class ValidatePostLengthTests(TestCase): def test_valid_post_length_passes_validation(self): """valid post passes validation""" settings = Mock(post_length_min=1, post_length_max=50) validate_post_length(settings, "Lorem ipsum dolor met sit amet elit.") def test_for_empty_post_validation_error_is_raised(self): """empty post is rejected""" settings = Mock(post_length_min=3) with self.assertRaises(ValidationError): validate_post_length(settings, "") def test_for_too_short_post_validation_error_is_raised(self): """too short post is rejected""" settings = Mock(post_length_min=3) with self.assertRaises(ValidationError): validate_post_length(settings, "a") def test_for_too_long_post_validation_error_is_raised(self): """too long post is rejected""" settings = Mock(post_length_min=1, post_length_max=2) with self.assertRaises(ValidationError): validate_post_length(settings, "abc") class ValidateThreadTitleTests(TestCase): def test_valid_thread_titles_pass_validation(self): """validate_thread_title is ok with valid titles""" settings = Mock(thread_title_length_min=1, thread_title_length_max=50) VALID_TITLES = ["Lorem ipsum dolor met", "123 456 789 112", "Ugabugagagagagaga"] for title in VALID_TITLES: validate_thread_title(settings, title) def test_for_empty_thread_title_validation_error_is_raised(self): """empty title is rejected""" settings = Mock(thread_title_length_min=3) with self.assertRaises(ValidationError): validate_thread_title(settings, "") def test_for_too_short_thread_title_validation_error_is_raised(self): """too short title is rejected""" settings = Mock(thread_title_length_min=3) with self.assertRaises(ValidationError): validate_thread_title(settings, "a") def test_for_too_long_thread_title_validation_error_is_raised(self): """too long title is rejected""" settings = Mock(thread_title_length_min=1, thread_title_length_max=2) with self.assertRaises(ValidationError): validate_thread_title(settings, "abc") def test_for_unsluggable_thread_title_valdiation_error_is_raised(self): """unsluggable title is rejected""" settings = Mock(thread_title_length_min=1, thread_title_length_max=9) with self.assertRaises(ValidationError): validate_thread_title(settings, "-#%^&-")
2,758
Python
.py
51
45.803922
88
0.691679
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,138
test_floodprotection.py
rafalp_Misago/misago/threads/tests/test_floodprotection.py
from unittest.mock import patch from django.urls import reverse from .. import test from ...acl.test import patch_user_acl from ...categories.models import Category from ...users.test import AuthenticatedUserTestCase class FloodProtectionTests(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.get(slug="first-category") self.thread = test.post_thread(category=self.category) self.post_link = reverse( "misago:api:thread-post-list", kwargs={"thread_pk": self.thread.pk} ) @patch( "misago.threads.api.postingendpoint.notifications.notify_on_new_thread_reply" ) def test_flood_has_no_showstoppers(self, notify_on_new_thread_reply_mock): """endpoint handles posting interruption""" response = self.client.post( self.post_link, data={"post": "This is test response!"} ) self.assertEqual(response.status_code, 200) response = self.client.post( self.post_link, data={"post": "This is test response!"} ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't post message so quickly after previous one."}, ) @patch_user_acl({"can_omit_flood_protection": True}) @patch( "misago.threads.api.postingendpoint.notifications.notify_on_new_thread_reply" ) def test_user_with_permission_omits_flood_protection( self, notify_on_new_thread_reply_mock ): response = self.client.post( self.post_link, data={"post": "This is test response!"} ) self.assertEqual(response.status_code, 200) response = self.client.post( self.post_link, data={"post": "This is test response!"} ) self.assertEqual(response.status_code, 200)
1,903
Python
.py
46
33.543478
85
0.657282
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,139
test_thread_postpatch_api.py
rafalp_Misago/misago/threads/tests/test_thread_postpatch_api.py
import json from datetime import timedelta from django.urls import reverse from django.utils import timezone from .. import test from ...categories.models import Category from ...users.test import AuthenticatedUserTestCase from ..models import Post from ..test import patch_category_acl class ThreadPostPatchApiTestCase(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.get(slug="first-category") self.thread = test.post_thread(category=self.category) self.post = test.reply_thread(self.thread, poster=self.user) self.api_link = reverse( "misago:api:thread-post-detail", kwargs={"thread_pk": self.thread.pk, "pk": self.post.pk}, ) def patch(self, api_link, ops): return self.client.patch( api_link, json.dumps(ops), content_type="application/json" ) class PostAddAclApiTests(ThreadPostPatchApiTestCase): def test_add_acl_true(self): """api adds current event's acl to response""" response = self.patch( self.api_link, [{"op": "add", "path": "acl", "value": True}] ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertTrue(response_json["acl"]) def test_add_acl_false(self): """ if value is false, api won't add acl to the response, but will set empty key """ response = self.patch( self.api_link, [{"op": "add", "path": "acl", "value": False}] ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertIsNone(response_json["acl"]) class PostProtectApiTests(ThreadPostPatchApiTestCase): @patch_category_acl({"can_edit_posts": 2, "can_protect_posts": True}) def test_protect_post(self): """api makes it possible to protect post""" response = self.patch( self.api_link, [{"op": "replace", "path": "is-protected", "value": True}] ) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertTrue(reponse_json["is_protected"]) self.post.refresh_from_db() self.assertTrue(self.post.is_protected) @patch_category_acl({"can_edit_posts": 2, "can_protect_posts": True}) def test_unprotect_post(self): """api makes it possible to unprotect protected post""" self.post.is_protected = True self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-protected", "value": False}] ) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertFalse(reponse_json["is_protected"]) self.post.refresh_from_db() self.assertFalse(self.post.is_protected) @patch_category_acl({"can_edit_posts": 2, "can_protect_posts": True}) def test_protect_best_answer(self): """api makes it possible to protect post""" self.thread.set_best_answer(self.user, self.post) self.thread.save() self.assertFalse(self.thread.best_answer_is_protected) response = self.patch( self.api_link, [{"op": "replace", "path": "is-protected", "value": True}] ) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertTrue(reponse_json["is_protected"]) self.post.refresh_from_db() self.assertTrue(self.post.is_protected) self.thread.refresh_from_db() self.assertTrue(self.thread.best_answer_is_protected) @patch_category_acl({"can_edit_posts": 2, "can_protect_posts": True}) def test_unprotect_best_answer(self): """api makes it possible to unprotect protected post""" self.post.is_protected = True self.post.save() self.thread.set_best_answer(self.user, self.post) self.thread.save() self.assertTrue(self.thread.best_answer_is_protected) response = self.patch( self.api_link, [{"op": "replace", "path": "is-protected", "value": False}] ) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertFalse(reponse_json["is_protected"]) self.post.refresh_from_db() self.assertFalse(self.post.is_protected) self.thread.refresh_from_db() self.assertFalse(self.thread.best_answer_is_protected) @patch_category_acl({"can_edit_posts": 2, "can_protect_posts": False}) def test_protect_post_no_permission(self): """api validates permission to protect post""" response = self.patch( self.api_link, [{"op": "replace", "path": "is-protected", "value": True}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "You can't protect posts in this category." ) self.post.refresh_from_db() self.assertFalse(self.post.is_protected) @patch_category_acl({"can_edit_posts": 2, "can_protect_posts": False}) def test_unprotect_post_no_permission(self): """api validates permission to unprotect post""" self.post.is_protected = True self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-protected", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "You can't protect posts in this category." ) self.post.refresh_from_db() self.assertTrue(self.post.is_protected) @patch_category_acl({"can_edit_posts": 0, "can_protect_posts": True}) def test_protect_post_not_editable(self): """api validates if we can edit post we want to protect""" response = self.patch( self.api_link, [{"op": "replace", "path": "is-protected", "value": True}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "You can't protect posts you can't edit." ) self.post.refresh_from_db() self.assertFalse(self.post.is_protected) @patch_category_acl({"can_edit_posts": 0, "can_protect_posts": True}) def test_unprotect_post_not_editable(self): """api validates if we can edit post we want to protect""" self.post.is_protected = True self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-protected", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "You can't protect posts you can't edit." ) self.post.refresh_from_db() self.assertTrue(self.post.is_protected) class PostApproveApiTests(ThreadPostPatchApiTestCase): @patch_category_acl({"can_approve_content": True}) def test_approve_post(self): """api makes it possible to approve post""" self.post.is_unapproved = True self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-unapproved", "value": False}] ) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertFalse(reponse_json["is_unapproved"]) self.post.refresh_from_db() self.assertFalse(self.post.is_unapproved) @patch_category_acl({"can_approve_content": True}) def test_unapprove_post(self): """unapproving posts is not supported by api""" response = self.patch( self.api_link, [{"op": "replace", "path": "is-unapproved", "value": True}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "Content approval can't be reversed." ) self.post.refresh_from_db() self.assertFalse(self.post.is_unapproved) @patch_category_acl({"can_approve_content": False}) def test_approve_post_no_permission(self): """api validates approval permission""" self.post.is_unapproved = True self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-unapproved", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "You can't approve posts in this category." ) self.post.refresh_from_db() self.assertTrue(self.post.is_unapproved) @patch_category_acl({"can_approve_content": True, "can_close_threads": False}) def test_approve_post_closed_thread_no_permission(self): """api validates approval permission in closed threads""" self.post.is_unapproved = True self.post.save() self.thread.is_closed = True self.thread.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-unapproved", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "This thread is closed. You can't approve posts in it.", ) self.post.refresh_from_db() self.assertTrue(self.post.is_unapproved) @patch_category_acl({"can_approve_content": True, "can_close_threads": False}) def test_approve_post_closed_category_no_permission(self): """api validates approval permission in closed categories""" self.post.is_unapproved = True self.post.save() self.category.is_closed = True self.category.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-unapproved", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "This category is closed. You can't approve posts in it.", ) self.post.refresh_from_db() self.assertTrue(self.post.is_unapproved) @patch_category_acl({"can_approve_content": True}) def test_approve_first_post(self): """api approve first post fails""" self.post.is_unapproved = True self.post.save() self.thread.set_first_post(self.post) self.thread.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-unapproved", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "Thread's first post can only be approved together with thread.", ) self.post.refresh_from_db() self.assertTrue(self.post.is_unapproved) @patch_category_acl({"can_approve_content": True}) def test_approve_hidden_post(self): """api approve hidden post fails""" self.post.is_unapproved = True self.post.is_hidden = True self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-unapproved", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "You can't approve posts the content you can't see.", ) self.post.refresh_from_db() self.assertTrue(self.post.is_unapproved) class PostHideApiTests(ThreadPostPatchApiTestCase): @patch_category_acl({"can_hide_posts": 1}) def test_hide_post(self): """api makes it possible to hide post""" response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertTrue(reponse_json["is_hidden"]) self.post.refresh_from_db() self.assertTrue(self.post.is_hidden) @patch_category_acl({"can_hide_posts": 1}) def test_hide_own_post(self): """api makes it possible to hide owned post""" response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertTrue(reponse_json["is_hidden"]) self.post.refresh_from_db() self.assertTrue(self.post.is_hidden) @patch_category_acl({"can_hide_posts": 0}) def test_hide_post_no_permission(self): """api hide post with no permission fails""" response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "You can't hide posts in this category." ) self.post.refresh_from_db() self.assertFalse(self.post.is_hidden) @patch_category_acl({"can_hide_own_posts": 1, "can_protect_posts": False}) def test_hide_own_protected_post(self): """api validates if we are trying to hide protected post""" self.post.is_protected = True self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "This post is protected. You can't hide it." ) self.post.refresh_from_db() self.assertFalse(self.post.is_hidden) @patch_category_acl({"can_hide_own_posts": True}) def test_hide_other_user_post(self): """api validates post ownership when hiding""" self.post.poster = None self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "You can't hide other users posts in this category.", ) self.post.refresh_from_db() self.assertFalse(self.post.is_hidden) @patch_category_acl({"post_edit_time": 1, "can_hide_own_posts": True}) def test_hide_own_post_after_edit_time(self): """api validates if we are trying to hide post after edit time""" self.post.posted_on = timezone.now() - timedelta(minutes=10) self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "You can't hide posts that are older than 1 minute.", ) self.post.refresh_from_db() self.assertFalse(self.post.is_hidden) @patch_category_acl({"can_close_threads": False, "can_hide_own_posts": True}) def test_hide_post_in_closed_thread(self): """api validates if we are trying to hide post in closed thread""" self.thread.is_closed = True self.thread.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "This thread is closed. You can't hide posts in it.", ) self.post.refresh_from_db() self.assertFalse(self.post.is_hidden) @patch_category_acl({"can_close_threads": False, "can_hide_own_posts": True}) def test_hide_post_in_closed_category(self): """api validates if we are trying to hide post in closed category""" self.category.is_closed = True self.category.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "This category is closed. You can't hide posts in it.", ) self.post.refresh_from_db() self.assertFalse(self.post.is_hidden) @patch_category_acl({"can_hide_posts": 1}) def test_hide_first_post(self): """api hide first post fails""" self.thread.set_first_post(self.post) self.thread.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "Thread's first post can only be hidden using the hide thread option.", ) @patch_category_acl({"can_hide_posts": 1}) def test_hide_best_answer(self): """api hide first post fails""" self.thread.set_best_answer(self.user, self.post) self.thread.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "id": self.post.id, "detail": [ "You can't hide this post because its marked as best answer." ], }, ) class PostUnhideApiTests(ThreadPostPatchApiTestCase): @patch_category_acl({"can_hide_posts": 1}) def test_show_post(self): """api makes it possible to unhide post""" self.post.is_hidden = True self.post.save() self.post.refresh_from_db() self.assertTrue(self.post.is_hidden) response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": False}] ) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertFalse(reponse_json["is_hidden"]) self.post.refresh_from_db() self.assertFalse(self.post.is_hidden) @patch_category_acl({"can_hide_own_posts": 1}) def test_show_own_post(self): """api makes it possible to unhide owned post""" self.post.is_hidden = True self.post.save() self.post.refresh_from_db() self.assertTrue(self.post.is_hidden) response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": False}] ) self.assertEqual(response.status_code, 200) reponse_json = response.json() self.assertFalse(reponse_json["is_hidden"]) self.post.refresh_from_db() self.assertFalse(self.post.is_hidden) @patch_category_acl({"can_hide_posts": 0}) def test_show_post_no_permission(self): """api unhide post with no permission fails""" self.post.is_hidden = True self.post.save() self.post.refresh_from_db() self.assertTrue(self.post.is_hidden) response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "You can't reveal posts in this category." ) self.post.refresh_from_db() self.assertTrue(self.post.is_hidden) @patch_category_acl({"can_protect_posts": 0, "can_hide_own_posts": 1}) def test_show_own_protected_post(self): """api validates if we are trying to reveal protected post""" self.post.is_hidden = True self.post.save() self.post.is_protected = True self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "This post is protected. You can't reveal it." ) self.post.refresh_from_db() self.assertTrue(self.post.is_hidden) @patch_category_acl({"can_hide_own_posts": 1}) def test_show_other_user_post(self): """api validates post ownership when revealing""" self.post.is_hidden = True self.post.poster = None self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "You can't reveal other users posts in this category.", ) self.post.refresh_from_db() self.assertTrue(self.post.is_hidden) @patch_category_acl({"post_edit_time": 1, "can_hide_own_posts": 1}) def test_show_own_post_after_edit_time(self): """api validates if we are trying to reveal post after edit time""" self.post.is_hidden = True self.post.posted_on = timezone.now() - timedelta(minutes=10) self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "You can't reveal posts that are older than 1 minute.", ) self.post.refresh_from_db() self.assertTrue(self.post.is_hidden) @patch_category_acl({"can_close_threads": False, "can_hide_own_posts": 1}) def test_show_post_in_closed_thread(self): """api validates if we are trying to reveal post in closed thread""" self.thread.is_closed = True self.thread.save() self.post.is_hidden = True self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "This thread is closed. You can't reveal posts in it.", ) self.post.refresh_from_db() self.assertTrue(self.post.is_hidden) @patch_category_acl({"can_close_threads": False, "can_hide_own_posts": 1}) def test_show_post_in_closed_category(self): """api validates if we are trying to reveal post in closed category""" self.category.is_closed = True self.category.save() self.post.is_hidden = True self.post.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "This category is closed. You can't reveal posts in it.", ) self.post.refresh_from_db() self.assertTrue(self.post.is_hidden) @patch_category_acl({"can_hide_posts": 1}) def test_show_first_post(self): """api unhide first post fails""" self.thread.set_first_post(self.post) self.thread.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "Thread's first post can only be revealed using the reveal thread option.", ) class PostLikeApiTests(ThreadPostPatchApiTestCase): @patch_category_acl({"can_see_posts_likes": 0}) def test_like_no_see_permission(self): """api validates user's permission to see posts likes""" response = self.patch( self.api_link, [{"op": "replace", "path": "is-liked", "value": True}] ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"id": self.post.id, "detail": ["You can't like posts in this category."]}, ) @patch_category_acl({"can_like_posts": False}) def test_like_no_like_permission(self): """api validates user's permission to see posts likes""" response = self.patch( self.api_link, [{"op": "replace", "path": "is-liked", "value": True}] ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"id": self.post.id, "detail": ["You can't like posts in this category."]}, ) def test_like_post(self): """api adds user like to post""" response = self.patch( self.api_link, [{"op": "replace", "path": "is-liked", "value": True}] ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["likes"], 1) self.assertEqual(response_json["is_liked"], True) self.assertEqual( response_json["last_likes"], [{"id": self.user.id, "username": self.user.username}], ) post = Post.objects.get(pk=self.post.pk) self.assertEqual(post.likes, response_json["likes"]) self.assertEqual(post.last_likes, response_json["last_likes"]) def test_like_liked_post(self): """api adds user like to post""" test.like_post(self.post, username="Myo") test.like_post(self.post, username="Mugi") test.like_post(self.post, username="Bob") test.like_post(self.post, username="Miku") response = self.patch( self.api_link, [{"op": "replace", "path": "is-liked", "value": True}] ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["likes"], 5) self.assertEqual(response_json["is_liked"], True) self.assertEqual( response_json["last_likes"], [ {"id": self.user.id, "username": self.user.username}, {"id": None, "username": "Miku"}, {"id": None, "username": "Bob"}, {"id": None, "username": "Mugi"}, ], ) post = Post.objects.get(pk=self.post.pk) self.assertEqual(post.likes, response_json["likes"]) self.assertEqual(post.last_likes, response_json["last_likes"]) def test_unlike_post(self): """api removes user like from post""" test.like_post(self.post, self.user) response = self.patch( self.api_link, [{"op": "replace", "path": "is-liked", "value": False}] ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["likes"], 0) self.assertEqual(response_json["is_liked"], False) self.assertEqual(response_json["last_likes"], []) post = Post.objects.get(pk=self.post.pk) self.assertEqual(post.likes, response_json["likes"]) self.assertEqual(post.last_likes, response_json["last_likes"]) def test_like_post_no_change(self): """api does no state change if we are linking liked post""" test.like_post(self.post, self.user) response = self.patch( self.api_link, [{"op": "replace", "path": "is-liked", "value": True}] ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["likes"], 1) self.assertEqual(response_json["is_liked"], True) self.assertEqual( response_json["last_likes"], [{"id": self.user.id, "username": self.user.username}], ) post = Post.objects.get(pk=self.post.pk) self.assertEqual(post.likes, response_json["likes"]) self.assertEqual(post.last_likes, response_json["last_likes"]) def test_unlike_post_no_change(self): """api does no state change if we are unlinking unliked post""" response = self.patch( self.api_link, [{"op": "replace", "path": "is-liked", "value": False}] ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["likes"], 0) self.assertEqual(response_json["is_liked"], False) self.assertEqual(response_json["last_likes"], []) class ThreadEventPatchApiTestCase(ThreadPostPatchApiTestCase): def setUp(self): super().setUp() self.event = test.reply_thread(self.thread, poster=self.user, is_event=True) self.api_link = reverse( "misago:api:thread-post-detail", kwargs={"thread_pk": self.thread.pk, "pk": self.event.pk}, ) def refresh_event(self): self.event = self.thread.post_set.get(pk=self.event.pk) class EventAnonPatchApiTests(ThreadEventPatchApiTestCase): def test_anonymous_user(self): """anonymous users can't change event state""" self.logout_user() response = self.patch( self.api_link, [{"op": "add", "path": "acl", "value": True}] ) self.assertEqual(response.status_code, 403) class EventAddAclApiTests(ThreadEventPatchApiTestCase): def test_add_acl_true(self): """api adds current event's acl to response""" response = self.patch( self.api_link, [{"op": "add", "path": "acl", "value": True}] ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertTrue(response_json["acl"]) def test_add_acl_false(self): """ if value is false, api won't add acl to the response, but will set empty key """ response = self.patch( self.api_link, [{"op": "add", "path": "acl", "value": False}] ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertIsNone(response_json["acl"]) response = self.patch( self.api_link, [{"op": "add", "path": "acl", "value": True}] ) self.assertEqual(response.status_code, 200) class EventHideApiTests(ThreadEventPatchApiTestCase): @patch_category_acl({"can_hide_events": 1}) def test_hide_event(self): """api makes it possible to hide event""" response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 200) self.event.refresh_from_db() self.assertTrue(self.event.is_hidden) @patch_category_acl({"can_hide_events": 1}) def test_show_event(self): """api makes it possible to unhide event""" self.event.is_hidden = True self.event.save() self.event.refresh_from_db() self.assertTrue(self.event.is_hidden) response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": False}] ) self.assertEqual(response.status_code, 200) self.event.refresh_from_db() self.assertFalse(self.event.is_hidden) @patch_category_acl({"can_hide_events": 0}) def test_hide_event_no_permission(self): """api hide event with no permission fails""" response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "You can't hide events in this category." ) self.event.refresh_from_db() self.assertFalse(self.event.is_hidden) @patch_category_acl({"can_close_threads": False, "can_hide_events": 1}) def test_hide_event_closed_thread_no_permission(self): """api hide event in closed thread with no permission fails""" self.thread.is_closed = True self.thread.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "This thread is closed. You can't hide events in it.", ) self.event.refresh_from_db() self.assertFalse(self.event.is_hidden) @patch_category_acl({"can_close_threads": False, "can_hide_events": 1}) def test_hide_event_closed_category_no_permission(self): """api hide event in closed category with no permission fails""" self.category.is_closed = True self.category.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": True}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "This category is closed. You can't hide events in it.", ) self.event.refresh_from_db() self.assertFalse(self.event.is_hidden) @patch_category_acl({"can_hide_events": 0}) def test_show_event_no_permission(self): """api unhide event with no permission fails""" self.event.is_hidden = True self.event.save() self.event.refresh_from_db() self.assertTrue(self.event.is_hidden) response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": False}] ) self.assertEqual(response.status_code, 404) @patch_category_acl({"can_close_threads": False, "can_hide_events": 1}) def test_show_event_closed_thread_no_permission(self): """api show event in closed thread with no permission fails""" self.event.is_hidden = True self.event.save() self.thread.is_closed = True self.thread.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "This thread is closed. You can't reveal events in it.", ) self.event.refresh_from_db() self.assertTrue(self.event.is_hidden) @patch_category_acl({"can_close_threads": False, "can_hide_events": 1}) def test_show_event_closed_category_no_permission(self): """api show event in closed category with no permission fails""" self.event.is_hidden = True self.event.save() self.category.is_closed = True self.category.save() response = self.patch( self.api_link, [{"op": "replace", "path": "is-hidden", "value": False}] ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["detail"][0], "This category is closed. You can't reveal events in it.", ) self.event.refresh_from_db() self.assertTrue(self.event.is_hidden)
36,287
Python
.py
827
34.631197
87
0.60786
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,140
test_validate_post.py
rafalp_Misago/misago/threads/tests/test_validate_post.py
from django.core.exceptions import ValidationError from django.urls import reverse from ...categories.models import Category from ...users.test import AuthenticatedUserTestCase class ValidatePostTests(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.get(slug="first-category") self.api_link = reverse("misago:api:thread-list") def test_title_validation(self): """validate_post tests title""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Check our l33t CaSiNo!", "post": "Lorem ipsum dolor met!", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"non_field_errors": ["Don't discuss gambling!"]} ) # clean title passes validation response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Check our l33t place!", "post": "Lorem ipsum dolor met!", }, ) self.assertEqual(response.status_code, 200) def test_post_validation(self): """validate_post tests post content""" response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Lorem ipsum dolor met!", "post": "Check our l33t CaSiNo!", }, ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"non_field_errors": ["Don't discuss gambling!"]} ) # clean post passes validation response = self.client.post( self.api_link, data={ "category": self.category.pk, "title": "Lorem ipsum dolor met!", "post": "Check our l33t place!", }, ) self.assertEqual(response.status_code, 200) def test_empty_input(self): """validate_post handles empty input""" response = self.client.post(self.api_link, data={"category": self.category.pk}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "title": ["You have to enter a thread title."], "post": ["You have to enter a message."], }, ) response = self.client.post( self.api_link, data={"category": self.category.pk, "title": "", "post": ""} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "title": ["This field may not be blank."], "post": ["This field may not be blank."], }, ) def test_post_validators_hook_is_used_by_posting_api(db, user_client, mocker, thread): def validator(context, data): raise ValidationError("ERROR FROM PLUGIN") mocker.patch("misago.threads.validators.hooks.post_validators", [validator]) response = user_client.post( f"/api/threads/{thread.id}/posts/", {"post": "Lorem ipsum dolor met"} ) assert response.status_code == 400 assert response.json() == {"non_field_errors": ["ERROR FROM PLUGIN"]}
3,427
Python
.py
88
28.363636
87
0.564079
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,141
test_watch_replied_thread.py
rafalp_Misago/misago/threads/tests/test_watch_replied_thread.py
from django.urls import reverse from ...notifications.models import WatchedThread from ...notifications.threads import ThreadNotifications from ..models import ThreadParticipant def test_replied_thread_is_watched_by_user_with_option_enabled( notify_on_new_thread_reply_mock, user, user_client, thread ): user.watch_replied_threads = ThreadNotifications.SITE_ONLY user.save() response = user_client.post( reverse("misago:api:thread-post-list", kwargs={"thread_pk": thread.pk}), data={ "post": "Lorem ipsum dolor met", }, ) assert response.status_code == 200 WatchedThread.objects.get( user=user, category_id=thread.category_id, thread=thread, send_emails=False, ) def test_replied_thread_is_not_watched_by_user_with_option_disabled( notify_on_new_thread_reply_mock, user, user_client, thread ): user.watch_replied_threads = ThreadNotifications.NONE user.save() response = user_client.post( reverse("misago:api:thread-post-list", kwargs={"thread_pk": thread.pk}), data={ "post": "Lorem ipsum dolor met", }, ) assert response.status_code == 200 assert not WatchedThread.objects.exists() def test_replied_private_thread_is_watched_by_user_with_option_enabled( notify_on_new_thread_reply_mock, user, user_client, private_thread ): user.watch_replied_threads = ThreadNotifications.SITE_ONLY user.save() ThreadParticipant.objects.create(thread=private_thread, user=user) response = user_client.post( reverse( "misago:api:private-thread-post-list", kwargs={"thread_pk": private_thread.pk}, ), data={ "post": "Lorem ipsum dolor met", }, ) assert response.status_code == 200 WatchedThread.objects.get( user=user, category_id=private_thread.category_id, thread=private_thread, send_emails=False, ) def test_replied_private_thread_is_not_watched_by_user_with_option_disabled( notify_on_new_thread_reply_mock, user, user_client, private_thread ): user.watch_replied_threads = ThreadNotifications.NONE user.save() ThreadParticipant.objects.create(thread=private_thread, user=user) response = user_client.post( reverse( "misago:api:private-thread-post-list", kwargs={"thread_pk": private_thread.pk}, ), data={ "post": "Lorem ipsum dolor met", }, ) assert response.status_code == 200 assert not WatchedThread.objects.exists()
2,631
Python
.py
74
28.864865
80
0.672319
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,142
test_floodprotection_middleware.py
rafalp_Misago/misago/threads/tests/test_floodprotection_middleware.py
from datetime import timedelta import pytest from django.utils import timezone from ...conf.test import override_dynamic_settings from ..api.postingendpoint import PostingEndpoint, PostingInterrupt from ..api.postingendpoint.floodprotection import FloodProtectionMiddleware from ..test import post_thread default_acl = {"can_omit_flood_protection": False} can_omit_flood_acl = {"can_omit_flood_protection": True} def test_middleware_lets_users_first_post_through(dynamic_settings, user): user.update_fields = [] middleware = FloodProtectionMiddleware( settings=dynamic_settings, user=user, user_acl=default_acl ) middleware.interrupt_posting(None) def test_middleware_updates_users_last_post_datetime(dynamic_settings, user): user.update_fields = [] middleware = FloodProtectionMiddleware( settings=dynamic_settings, user=user, user_acl=default_acl ) middleware.interrupt_posting(None) assert user.last_posted_on assert "last_posted_on" in user.update_fields def test_middleware_interrupts_posting_because_previous_post_was_posted_too_recently( dynamic_settings, user ): user.last_posted_on = timezone.now() user.update_fields = [] middleware = FloodProtectionMiddleware( mode=PostingEndpoint.START, settings=dynamic_settings, user=user, user_acl=default_acl, ) assert middleware.use_this_middleware() with pytest.raises(PostingInterrupt): middleware.interrupt_posting(None) def test_middleware_lets_users_next_post_through_if_previous_post_is_not_recent( dynamic_settings, user ): user.last_posted_on = timezone.now() - timedelta(seconds=10) user.update_fields = [] middleware = FloodProtectionMiddleware( mode=PostingEndpoint.START, settings=dynamic_settings, user=user, user_acl=default_acl, ) assert middleware.use_this_middleware() middleware.interrupt_posting(None) def test_middleware_is_not_used_if_user_has_permission_to_omit_flood_protection( dynamic_settings, user ): user.last_posted_on = timezone.now() user.update_fields = [] middleware = FloodProtectionMiddleware( mode=PostingEndpoint.START, settings=dynamic_settings, user=user, user_acl=can_omit_flood_acl, ) assert not middleware.use_this_middleware() def test_middleware_is_not_used_if_user_edits_post(dynamic_settings, user): middleware = FloodProtectionMiddleware( mode=PostingEndpoint.EDIT, settings=dynamic_settings, user=user, user_acl=can_omit_flood_acl, ) assert not middleware.use_this_middleware() @override_dynamic_settings(hourly_post_limit=3) def test_middleware_interrupts_posting_if_hourly_limit_was_met( default_category, dynamic_settings, user ): user.update_fields = [] for _ in range(3): post_thread(default_category, poster=user) middleware = FloodProtectionMiddleware( mode=PostingEndpoint.START, settings=dynamic_settings, user=user, user_acl=default_acl, ) assert middleware.use_this_middleware() with pytest.raises(PostingInterrupt): middleware.interrupt_posting(None) @override_dynamic_settings(hourly_post_limit=0) def test_old_posts_dont_count_to_hourly_limit(default_category, dynamic_settings, user): user.update_fields = [] for _ in range(3): post_thread( default_category, poster=user, started_on=timezone.now() - timedelta(hours=1), ) middleware = FloodProtectionMiddleware( mode=PostingEndpoint.START, settings=dynamic_settings, user=user, user_acl=default_acl, ) middleware.interrupt_posting(None) @override_dynamic_settings(hourly_post_limit=0) def test_middleware_lets_post_through_if_hourly_limit_was_disabled( default_category, dynamic_settings, user ): user.update_fields = [] for _ in range(3): post_thread(default_category, poster=user) middleware = FloodProtectionMiddleware( mode=PostingEndpoint.START, settings=dynamic_settings, user=user, user_acl=default_acl, ) middleware.interrupt_posting(None) @override_dynamic_settings(daily_post_limit=3) def test_middleware_interrupts_posting_if_daily_limit_was_met( default_category, dynamic_settings, user ): user.update_fields = [] for _ in range(3): post_thread(default_category, poster=user) middleware = FloodProtectionMiddleware( mode=PostingEndpoint.START, settings=dynamic_settings, user=user, user_acl=default_acl, ) assert middleware.use_this_middleware() with pytest.raises(PostingInterrupt): middleware.interrupt_posting(None) @override_dynamic_settings(daily_post_limit=0) def test_old_posts_dont_count_to_daily_limit(default_category, dynamic_settings, user): user.update_fields = [] for _ in range(3): post_thread( default_category, poster=user, started_on=timezone.now() - timedelta(days=1) ) middleware = FloodProtectionMiddleware( mode=PostingEndpoint.START, settings=dynamic_settings, user=user, user_acl=default_acl, ) middleware.interrupt_posting(None) @override_dynamic_settings(daily_post_limit=0) def test_middleware_lets_post_through_if_daily_limit_was_disabled( default_category, dynamic_settings, user ): user.update_fields = [] for _ in range(3): post_thread(default_category, poster=user) middleware = FloodProtectionMiddleware( mode=PostingEndpoint.START, settings=dynamic_settings, user=user, user_acl=default_acl, ) middleware.interrupt_posting(None)
5,832
Python
.py
160
30.49375
88
0.716545
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,143
test_private_thread_replies_view.py
rafalp_Misago/misago/threads/tests/test_private_thread_replies_view.py
from django.urls import reverse from ...test import assert_contains, assert_not_contains from ..models import ThreadParticipant def test_private_thread_replies_view_shows_error_on_missing_permission( user, user_client, user_private_thread ): user.group.can_use_private_threads = False user.group.save() response = user_client.get( reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) ) assert_not_contains(response, user_private_thread.title, status_code=403) assert_not_contains( response, user_private_thread.first_post.parsed, status_code=403, ) def test_private_thread_replies_view_shows_error_to_anonymous_user( client, user_private_thread ): response = client.get( reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) ) assert_not_contains(response, user_private_thread.title, status_code=403) assert_not_contains( response, user_private_thread.first_post.parsed, status_code=403, ) def test_private_thread_replies_view_shows_error_to_user_who_is_not_thread_participant( user, user_client, user_private_thread ): ThreadParticipant.objects.filter(user=user).delete() response = user_client.get( reverse( "misago:private-thread", kwargs={ "id": user_private_thread.id, "slug": user_private_thread.slug, }, ) ) assert_not_contains(response, user_private_thread.title, status_code=404) assert_not_contains( response, user_private_thread.first_post.parsed, status_code=404, ) def test_private_thread_replies_view_shows_thread_to_user( user_client, user_private_thread ): response = user_client.get( reverse( "misago:private-thread", kwargs={ "id": user_private_thread.id, "slug": user_private_thread.slug, }, ) ) assert_contains(response, user_private_thread.title) assert_contains(response, user_private_thread.first_post.parsed) def test_private_thread_replies_view_shows_other_users_thread_to_user( user_client, other_user_private_thread ): response = user_client.get( reverse( "misago:private-thread", kwargs={ "id": other_user_private_thread.id, "slug": other_user_private_thread.slug, }, ) ) assert_contains(response, other_user_private_thread.title) assert_contains(response, other_user_private_thread.first_post.parsed) def test_private_thread_replies_view_shows_thread_to_user_in_htmx( user_client, user_private_thread ): response = user_client.get( reverse( "misago:private-thread", kwargs={ "id": user_private_thread.id, "slug": user_private_thread.slug, }, ), headers={"hx-request": "true"}, ) assert_contains(response, user_private_thread.title) assert_contains(response, user_private_thread.first_post.parsed) def test_private_thread_replies_view_shows_other_users_thread_to_user_in_htmx( user_client, other_user_private_thread ): response = user_client.get( reverse( "misago:private-thread", kwargs={ "id": other_user_private_thread.id, "slug": other_user_private_thread.slug, }, ), headers={"hx-request": "true"}, ) assert_contains(response, other_user_private_thread.title) assert_contains(response, other_user_private_thread.first_post.parsed) def test_private_thread_replies_view_redirects_if_slug_is_invalid( user_client, user_private_thread ): response = user_client.get( reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": "invalid"}, ), ) assert response.status_code == 301 assert response["location"] == reverse( "misago:private-thread", kwargs={ "id": user_private_thread.id, "slug": user_private_thread.slug, }, ) def test_private_thread_replies_view_ignores_invalid_slug_in_htmx( user_client, user_private_thread ): response = user_client.get( reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": "invalid"}, ), headers={"hx-request": "true"}, ) assert_contains(response, user_private_thread.title) assert_contains(response, user_private_thread.first_post.parsed) def test_private_thread_replies_view_redirects_to_last_page_if_page_number_is_too_large( user_client, user_private_thread ): response = user_client.get( reverse( "misago:private-thread", kwargs={ "id": user_private_thread.id, "slug": user_private_thread.slug, "page": 1000, }, ), ) assert response.status_code == 302 assert response["location"] == reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ) def test_private_thread_replies_view_shows_last_page_if_page_number_is_too_large_in_htmx( user_client, user_private_thread ): response = user_client.get( reverse( "misago:private-thread", kwargs={ "id": user_private_thread.id, "slug": user_private_thread.slug, "page": 1000, }, ), headers={"hx-request": "true"}, ) assert_contains(response, user_private_thread.title) assert_contains(response, user_private_thread.first_post.parsed) def test_private_thread_replies_view_shows_error_if_regular_thread_is_accessed( user_client, thread ): response = user_client.get( reverse( "misago:private-thread", kwargs={"id": thread.id, "slug": thread.slug}, ), ) assert_not_contains(response, thread.title, status_code=404) assert_not_contains(response, thread.first_post.parsed, status_code=404)
6,387
Python
.py
186
26.419355
89
0.626012
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,144
test_privatethreads_api.py
rafalp_Misago/misago/threads/tests/test_privatethreads_api.py
from django.urls import reverse from .. import test from ...acl.test import patch_user_acl from ..models import Thread, ThreadParticipant from ..test import patch_private_threads_acl from .test_privatethreads import PrivateThreadsTestCase class PrivateThreadsListApiTests(PrivateThreadsTestCase): def setUp(self): super().setUp() self.api_link = reverse("misago:api:private-thread-list") def test_unauthenticated(self): """api requires user to sign in and be able to access it""" self.logout_user() response = self.client.get(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You have to sign in to use private threads."} ) @patch_user_acl({"can_use_private_threads": False}) def test_no_permission(self): """api requires user to have permission to be able to access it""" response = self.client.get(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual(response.json(), {"detail": "You can't use private threads."}) @patch_user_acl({"can_use_private_threads": True}) def test_empty_list(self): """api has no showstoppers on returning empty list""" response = self.client.get(self.api_link) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(len(response_json["results"]), 0) @patch_user_acl({"can_use_private_threads": True}) def test_thread_visibility(self): """only participated threads are returned by private threads api""" visible = test.post_thread(category=self.category, poster=self.user) reported = test.post_thread(category=self.category, poster=self.user) # hidden thread test.post_thread(category=self.category, poster=self.user) ThreadParticipant.objects.add_participants(visible, [self.user]) reported.has_reported_posts = True reported.save() response = self.client.get(self.api_link) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(len(response_json["results"]), 1) self.assertEqual(response_json["results"][0]["id"], visible.id) # threads with reported posts will also show to moderators with patch_user_acl({"can_moderate_private_threads": True}): response = self.client.get(self.api_link) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(len(response_json["results"]), 2) self.assertEqual(response_json["results"][0]["id"], reported.id) self.assertEqual(response_json["results"][1]["id"], visible.id) class PrivateThreadRetrieveApiTests(PrivateThreadsTestCase): def setUp(self): super().setUp() self.thread = test.post_thread(self.category, poster=self.user) self.api_link = self.thread.get_api_url() def test_anonymous(self): """anonymous user can't see private thread""" self.logout_user() response = self.client.get(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You have to sign in to use private threads."} ) @patch_user_acl({"can_use_private_threads": False}) def test_no_permission(self): """user needs to have permission to see private thread""" response = self.client.get(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual(response.json(), {"detail": "You can't use private threads."}) @patch_user_acl({"can_use_private_threads": True}) def test_no_participant(self): """user cant see thread he isn't part of""" response = self.client.get(self.api_link) self.assertEqual(response.status_code, 404) @patch_user_acl( {"can_use_private_threads": True, "can_moderate_private_threads": True} ) def test_mod_not_reported(self): """moderator can't see private thread that has no reports""" response = self.client.get(self.api_link) self.assertEqual(response.status_code, 404) @patch_user_acl( {"can_use_private_threads": True, "can_moderate_private_threads": False} ) def test_reported_not_mod(self): """non-mod can't see private thread that has reported posts""" self.thread.has_reported_posts = True self.thread.save() response = self.client.get(self.api_link) self.assertEqual(response.status_code, 404) @patch_user_acl({"can_use_private_threads": True}) def test_can_see_owner(self): """user can see thread he is owner of""" ThreadParticipant.objects.set_owner(self.thread, self.user) response = self.client.get(self.api_link) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["title"], self.thread.title) self.assertEqual( response_json["participants"], [ { "id": self.user.id, "username": self.user.username, "avatars": self.user.avatars, "url": self.user.get_absolute_url(), "is_owner": True, } ], ) @patch_user_acl({"can_use_private_threads": True}) def test_can_see_participant(self): """user can see thread he is participant of""" ThreadParticipant.objects.add_participants(self.thread, [self.user]) response = self.client.get(self.api_link) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["title"], self.thread.title) self.assertEqual( response_json["participants"], [ { "id": self.user.id, "username": self.user.username, "avatars": self.user.avatars, "url": self.user.get_absolute_url(), "is_owner": False, } ], ) @patch_user_acl( {"can_use_private_threads": True, "can_moderate_private_threads": True} ) def test_mod_can_see_reported(self): """moderator can see private thread that has reports""" self.thread.has_reported_posts = True self.thread.save() response = self.client.get(self.api_link) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["title"], self.thread.title) self.assertEqual(response_json["participants"], []) class PrivateThreadDeleteApiTests(PrivateThreadsTestCase): def setUp(self): super().setUp() self.thread = test.post_thread(self.category, poster=self.user) self.api_link = self.thread.get_api_url() ThreadParticipant.objects.add_participants(self.thread, [self.user]) @patch_private_threads_acl({"can_hide_threads": 0}) def test_hide_thread_no_permission(self): """api tests permission to delete threads""" response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json()["detail"], "You can't delete threads in this category." ) @patch_private_threads_acl({"can_hide_threads": 1}) def test_delete_thread_no_permission(self): """api tests permission to delete threads""" response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json()["detail"], "You can't delete threads in this category." ) @patch_private_threads_acl({"can_hide_threads": 2}) def test_delete_thread(self): """DELETE to API link with permission deletes thread""" response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 200) with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk)
8,305
Python
.py
175
38.131429
87
0.641929
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,145
test_threads_lists_subcategories.py
rafalp_Misago/misago/threads/tests/test_threads_lists_subcategories.py
from django.urls import reverse from ...categories.enums import CategoryChildrenComponent from ...categories.models import Category from ...conf.test import override_dynamic_settings from ...permissions.enums import CategoryPermission from ...test import assert_contains, assert_not_contains from ...testutils import grant_category_group_permissions @override_dynamic_settings( index_view="categories", threads_list_categories_component=CategoryChildrenComponent.DISABLED, ) def test_threads_list_renders_no_subcategories_component(default_category, client): response = client.get(reverse("misago:threads")) assert_not_contains(response, "list-group-category") @override_dynamic_settings( index_view="categories", threads_list_categories_component=CategoryChildrenComponent.FULL, ) def test_threads_list_renders_full_subcategories_component(default_category, client): response = client.get(reverse("misago:threads")) assert_contains(response, default_category.name) assert_contains(response, "list-group-category") @override_dynamic_settings( index_view="categories", threads_list_categories_component=CategoryChildrenComponent.DROPDOWN, ) def test_threads_list_renders_dropdown_subcategories_component( default_category, client, guests_group ): default_category.children_categories_component = CategoryChildrenComponent.DROPDOWN default_category.save() child_category = Category(name="Child Category", slug="child-category") child_category.insert_at(default_category, position="last-child", save=True) grant_category_group_permissions( child_category, guests_group, CategoryPermission.SEE, ) response = client.get(default_category.get_absolute_url()) assert_contains(response, child_category.name) assert_contains(response, "dropdown-category") def test_category_threads_list_renders_full_subcategories_component( default_category, client, guests_group ): default_category.children_categories_component = CategoryChildrenComponent.FULL default_category.save() child_category = Category(name="Child Category", slug="child-category") child_category.insert_at(default_category, position="last-child", save=True) grant_category_group_permissions( child_category, guests_group, CategoryPermission.SEE, ) response = client.get(default_category.get_absolute_url()) assert_contains(response, child_category.name) assert_contains(response, "list-group-category") def test_category_threads_list_renders_dropdown_subcategories_component( default_category, client, guests_group ): default_category.children_categories_component = CategoryChildrenComponent.DROPDOWN default_category.save() child_category = Category(name="Child Category", slug="child-category") child_category.insert_at(default_category, position="last-child", save=True) grant_category_group_permissions( child_category, guests_group, CategoryPermission.SEE, ) response = client.get(default_category.get_absolute_url()) assert_contains(response, child_category.name) assert_contains(response, "dropdown-category")
3,226
Python
.py
71
40.830986
87
0.774801
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,146
test_attachments_api.py
rafalp_Misago/misago/threads/tests/test_attachments_api.py
import os from django.urls import reverse from PIL import Image from ...acl.models import Role from ...acl.test import patch_user_acl from ...conf import settings from ...users.test import AuthenticatedUserTestCase from ..models import Attachment, AttachmentType TESTFILES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "testfiles") TEST_DOCUMENT_PATH = os.path.join(TESTFILES_DIR, "document.pdf") TEST_LARGEPNG_PATH = os.path.join(TESTFILES_DIR, "large.png") TEST_SMALLJPG_PATH = os.path.join(TESTFILES_DIR, "small.jpg") TEST_ANIMATEDGIF_PATH = os.path.join(TESTFILES_DIR, "animated.gif") TEST_CORRUPTEDIMG_PATH = os.path.join(TESTFILES_DIR, "corrupted.gif") class AttachmentsApiTestCase(AuthenticatedUserTestCase): def setUp(self): super().setUp() AttachmentType.objects.all().delete() self.api_link = reverse("misago:api:attachment-list") def test_anonymous(self): """user has to be authenticated to be able to upload files""" self.logout_user() response = self.client.post(self.api_link) self.assertEqual(response.status_code, 403) @patch_user_acl({"max_attachment_size": 0}) def test_no_permission(self): """user needs permission to upload files""" response = self.client.post(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You don't have permission to upload new files."}, ) def test_no_file_uploaded(self): """no file uploaded scenario is handled""" response = self.client.post(self.api_link) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"detail": "No file has been uploaded."}) def test_invalid_extension(self): """uploaded file's extension is rejected as invalid""" AttachmentType.objects.create( name="Test extension", extensions="jpg,jpeg", mimetypes=None ) with open(TEST_DOCUMENT_PATH, "rb") as upload: response = self.client.post(self.api_link, data={"upload": upload}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You can't upload files of this type."} ) def test_invalid_mime(self): """uploaded file's mimetype is rejected as invalid""" AttachmentType.objects.create( name="Test extension", extensions="png", mimetypes="loremipsum" ) with open(TEST_DOCUMENT_PATH, "rb") as upload: response = self.client.post(self.api_link, data={"upload": upload}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You can't upload files of this type."} ) def test_no_perm_to_type(self): """user needs permission to upload files of this type""" attachment_type = AttachmentType.objects.create( name="Test extension", extensions="png", mimetypes="application/pdf" ) user_roles = (r.pk for r in self.user.get_roles()) attachment_type.limit_uploads_to.set(Role.objects.exclude(id__in=user_roles)) with open(TEST_DOCUMENT_PATH, "rb") as upload: response = self.client.post(self.api_link, data={"upload": upload}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You can't upload files of this type."} ) def test_type_is_locked(self): """new uploads for this filetype are locked""" AttachmentType.objects.create( name="Test extension", extensions="png", mimetypes="application/pdf", status=AttachmentType.LOCKED, ) with open(TEST_DOCUMENT_PATH, "rb") as upload: response = self.client.post(self.api_link, data={"upload": upload}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You can't upload files of this type."} ) def test_type_is_disabled(self): """new uploads for this filetype are disabled""" AttachmentType.objects.create( name="Test extension", extensions="png", mimetypes="application/pdf", status=AttachmentType.DISABLED, ) with open(TEST_DOCUMENT_PATH, "rb") as upload: response = self.client.post(self.api_link, data={"upload": upload}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You can't upload files of this type."} ) @patch_user_acl({"max_attachment_size": 100}) def test_upload_too_big_for_user(self): """too big uploads are rejected""" AttachmentType.objects.create( name="Test extension", extensions="png", mimetypes="image/png" ) with open(TEST_LARGEPNG_PATH, "rb") as upload: response = self.client.post(self.api_link, data={"upload": upload}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "detail": ( "You can't upload files larger than 100.0\xa0KB " "(your file has 253.9\xa0KB)." ) }, ) def test_corrupted_image_upload(self): """corrupted image upload is handled""" AttachmentType.objects.create(name="Test extension", extensions="gif") with open(TEST_CORRUPTEDIMG_PATH, "rb") as upload: response = self.client.post(self.api_link, data={"upload": upload}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Uploaded image is unsupported or invalid."} ) def test_document_upload(self): """successful upload creates orphan attachment""" AttachmentType.objects.create( name="Test extension", extensions="pdf", mimetypes="application/pdf" ) with open(TEST_DOCUMENT_PATH, "rb") as upload: response = self.client.post(self.api_link, data={"upload": upload}) self.assertEqual(response.status_code, 200) response_json = response.json() attachment = Attachment.objects.get(id=response_json["id"]) self.assertEqual(attachment.filename, "document.pdf") self.assertTrue(attachment.is_file) self.assertFalse(attachment.is_image) self.assertIsNotNone(attachment.file) self.assertTrue(not attachment.image) self.assertTrue(not attachment.thumbnail) self.assertTrue(str(attachment.file).endswith("document.pdf")) self.assertIsNone(response_json["post"]) self.assertEqual(response_json["uploader_name"], self.user.username) self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url()) self.assertIsNone(response_json["url"]["thumb"]) self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url()) self.assertEqual(self.user.audittrail_set.count(), 1) # files associated with attachment are deleted on its deletion file_path = attachment.file.path self.assertTrue(os.path.exists(file_path)) attachment.delete() self.assertFalse(os.path.exists(file_path)) def test_small_image_upload(self): """successful small image upload creates orphan attachment without thumbnail""" AttachmentType.objects.create( name="Test extension", extensions="jpeg,jpg", mimetypes="image/jpeg" ) with open(TEST_SMALLJPG_PATH, "rb") as upload: response = self.client.post(self.api_link, data={"upload": upload}) self.assertEqual(response.status_code, 200) response_json = response.json() attachment = Attachment.objects.get(id=response_json["id"]) self.assertEqual(attachment.filename, "small.jpg") self.assertFalse(attachment.is_file) self.assertTrue(attachment.is_image) self.assertTrue(not attachment.file) self.assertIsNotNone(attachment.image) self.assertTrue(not attachment.thumbnail) self.assertTrue(str(attachment.image).endswith("small.jpg")) self.assertIsNone(response_json["post"]) self.assertEqual(response_json["uploader_name"], self.user.username) self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url()) self.assertIsNone(response_json["url"]["thumb"]) self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url()) self.assertEqual(self.user.audittrail_set.count(), 1) @patch_user_acl({"max_attachment_size": 10 * 1024}) def test_large_image_upload(self): """successful large image upload creates orphan attachment with thumbnail""" AttachmentType.objects.create( name="Test extension", extensions="png", mimetypes="image/png" ) with open(TEST_LARGEPNG_PATH, "rb") as upload: response = self.client.post(self.api_link, data={"upload": upload}) self.assertEqual(response.status_code, 200) response_json = response.json() attachment = Attachment.objects.get(id=response_json["id"]) self.assertEqual(attachment.filename, "large.png") self.assertFalse(attachment.is_file) self.assertTrue(attachment.is_image) self.assertTrue(not attachment.file) self.assertIsNotNone(attachment.image) self.assertIsNotNone(attachment.thumbnail) self.assertTrue(str(attachment.image).endswith("large.png")) self.assertTrue(str(attachment.thumbnail).endswith("large.png")) self.assertIsNone(response_json["post"]) self.assertEqual(response_json["uploader_name"], self.user.username) self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url()) self.assertEqual(response_json["url"]["thumb"], attachment.get_thumbnail_url()) self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url()) self.assertEqual(self.user.audittrail_set.count(), 1) # thumbnail was scaled down thumbnail = Image.open(attachment.thumbnail.path) self.assertEqual( thumbnail.size[0], settings.MISAGO_ATTACHMENT_IMAGE_SIZE_LIMIT[0] ) self.assertLess( thumbnail.size[1], settings.MISAGO_ATTACHMENT_IMAGE_SIZE_LIMIT[1] ) # files associated with attachment are deleted on its deletion image_path = attachment.image.path thumbnail_path = attachment.thumbnail.path self.assertTrue(os.path.exists(image_path)) self.assertTrue(os.path.exists(thumbnail_path)) attachment.delete() self.assertFalse(os.path.exists(image_path)) self.assertFalse(os.path.exists(thumbnail_path)) def test_animated_image_upload(self): """successful gif upload creates orphan attachment with thumbnail""" AttachmentType.objects.create( name="Test extension", extensions="gif", mimetypes="image/gif" ) with open(TEST_ANIMATEDGIF_PATH, "rb") as upload: response = self.client.post(self.api_link, data={"upload": upload}) self.assertEqual(response.status_code, 200) response_json = response.json() attachment = Attachment.objects.get(id=response_json["id"]) self.assertEqual(attachment.filename, "animated.gif") self.assertFalse(attachment.is_file) self.assertTrue(attachment.is_image) self.assertTrue(not attachment.file) self.assertIsNotNone(attachment.image) self.assertIsNotNone(attachment.thumbnail) self.assertTrue(str(attachment.image).endswith("animated.gif")) self.assertTrue(str(attachment.thumbnail).endswith("animated.gif")) self.assertIsNone(response_json["post"]) self.assertEqual(response_json["uploader_name"], self.user.username) self.assertEqual(response_json["url"]["index"], attachment.get_absolute_url()) self.assertEqual(response_json["url"]["thumb"], attachment.get_thumbnail_url()) self.assertEqual(response_json["url"]["uploader"], self.user.get_absolute_url()) self.assertEqual(self.user.audittrail_set.count(), 1)
12,624
Python
.py
244
41.885246
88
0.653378
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,147
test_threads_merge_api.py
rafalp_Misago/misago/threads/tests/test_threads_merge_api.py
import json from unittest.mock import patch import pytest from django.urls import reverse from .. import test from ...acl import useracl from ...acl.objectacl import add_acl_to_obj from ...categories.models import Category from ...conf.dynamicsettings import DynamicSettings from ...conf.test import override_dynamic_settings from ...conftest import get_cache_versions from ...notifications.models import Notification from ..models import Poll, PollVote, Post, Thread from ..serializers import ThreadsListSerializer from ..test import patch_category_acl, patch_other_category_acl from .test_threads_api import ThreadsApiTestCase cache_versions = get_cache_versions() class ThreadsMergeApiTests(ThreadsApiTestCase): def setUp(self): super().setUp() self.api_link = reverse("misago:api:thread-merge") Category(name="Other Category", slug="other-category").insert_at( self.category, position="last-child", save=True ) self.other_category = Category.objects.get(slug="other-category") def test_merge_no_threads(self): """api validates if we are trying to merge no threads""" response = self.client.post(self.api_link, content_type="application/json") self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You have to select at least two threads to merge."}, ) def test_merge_empty_threads(self): """api validates if we are trying to empty threads list""" response = self.client.post( self.api_link, json.dumps({"threads": []}), content_type="application/json" ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You have to select at least two threads to merge."}, ) def test_merge_invalid_threads(self): """api validates if we are trying to merge invalid thread ids""" response = self.client.post( self.api_link, json.dumps({"threads": "abcd"}), content_type="application/json", ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": 'Expected a list of items but got type "str".'} ) response = self.client.post( self.api_link, json.dumps({"threads": ["a", "-", "c"]}), content_type="application/json", ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": ["One or more thread ids received were invalid."]}, ) def test_merge_single_thread(self): """api validates if we are trying to merge single thread""" response = self.client.post( self.api_link, json.dumps({"threads": [self.thread.id]}), content_type="application/json", ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You have to select at least two threads to merge."}, ) def test_merge_with_nonexisting_thread(self): """api validates if we are trying to merge with invalid thread""" response = self.client.post( self.api_link, json.dumps({"threads": [self.thread.id, self.thread.id + 1000]}), content_type="application/json", ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "One or more threads to merge could not be found."}, ) def test_merge_with_invisible_thread(self): """api validates if we are trying to merge with inaccesible thread""" unaccesible_thread = test.post_thread(category=self.other_category) response = self.client.post( self.api_link, json.dumps({"threads": [self.thread.id, unaccesible_thread.id]}), content_type="application/json", ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "One or more threads to merge could not be found."}, ) def test_merge_no_permission(self): """api validates permission to merge threads""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "category": self.category.id, "title": "Lorem ipsum dolor", "threads": [self.thread.id, thread.id], } ), content_type="application/json", ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), [ { "id": thread.pk, "title": thread.title, "errors": ["You can't merge threads in this category."], }, { "id": self.thread.pk, "title": self.thread.title, "errors": ["You can't merge threads in this category."], }, ], ) @patch_other_category_acl() @patch_category_acl({"can_merge_threads": True, "can_close_threads": False}) def test_thread_category_is_closed(self): """api validates if thread's category is open""" other_thread = test.post_thread(self.category) self.category.is_closed = True self.category.save() response = self.client.post( self.api_link, json.dumps( { "category": self.other_category.id, "title": "Lorem ipsum dolor", "threads": [self.thread.id, other_thread.id], } ), content_type="application/json", ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), [ { "id": other_thread.id, "title": other_thread.title, "errors": [ "This category is closed. You can't merge it's threads." ], }, { "id": self.thread.id, "title": self.thread.title, "errors": [ "This category is closed. You can't merge it's threads." ], }, ], ) @patch_other_category_acl() @patch_category_acl({"can_merge_threads": True, "can_close_threads": False}) def test_thread_is_closed(self): """api validates if thread is open""" other_thread = test.post_thread(self.category) other_thread.is_closed = True other_thread.save() response = self.client.post( self.api_link, json.dumps( { "category": self.other_category.id, "title": "Lorem ipsum dolor", "threads": [self.thread.id, other_thread.id], } ), content_type="application/json", ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), [ { "id": other_thread.id, "title": other_thread.title, "errors": [ "This thread is closed. You can't merge it with other threads." ], } ], ) @override_dynamic_settings(threads_per_page=4) @patch_category_acl({"can_merge_threads": True}) def test_merge_too_many_threads(self): """api rejects too many threads to merge""" threads = [] for _ in range(5): threads.append(test.post_thread(category=self.category).pk) response = self.client.post( self.api_link, json.dumps({"threads": threads}), content_type="application/json", ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "No more than 4 threads can be merged at a single time."}, ) @patch_category_acl({"can_merge_threads": True}) def test_merge_no_final_thread(self): """api rejects merge because no data to merge threads was specified""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps({"threads": [self.thread.id, thread.id]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "title": ["This field is required."], "category": ["This field is required."], }, ) @patch_category_acl({"can_merge_threads": True}) def test_merge_invalid_final_title(self): """api rejects merge because final thread title was invalid""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "$$$", "category": self.category.id, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "title": [ "Thread title should be at least 5 characters long (it has 3)." ] }, ) @patch_category_acl({"can_merge_threads": True}) def test_merge_invalid_category(self): """api rejects merge because final category was invalid""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "Valid thread title", "category": self.other_category.id, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"category": ["Requested category could not be found."]} ) @patch_category_acl({"can_merge_threads": True, "can_start_threads": False}) def test_merge_unallowed_start_thread(self): """api rejects merge because category isn't allowing starting threads""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "Valid thread title", "category": self.category.id, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"category": ["You can't create new threads in selected category."]}, ) @patch_category_acl({"can_merge_threads": True}) def test_merge_invalid_weight(self): """api rejects merge because final weight was invalid""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "Valid thread title", "category": self.category.id, "weight": 4, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"weight": ["Ensure this value is less than or equal to 2."]}, ) @patch_category_acl({"can_merge_threads": True}) def test_merge_unallowed_global_weight(self): """api rejects merge because global weight was unallowed""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "Valid thread title", "category": self.category.id, "weight": 2, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "weight": [ "You don't have permission to pin threads globally " "in this category." ] }, ) @patch_category_acl({"can_merge_threads": True}) def test_merge_unallowed_local_weight(self): """api rejects merge because local weight was unallowed""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "Valid thread title", "category": self.category.id, "weight": 1, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"weight": ["You don't have permission to pin threads in this category."]}, ) @patch_category_acl({"can_merge_threads": True, "can_pin_threads": 1}) def test_merge_allowed_local_weight(self): """api allows local weight""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "$$$", "category": self.category.id, "weight": 1, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "title": [ "Thread title should be at least 5 characters long (it has 3)." ] }, ) @patch_category_acl({"can_merge_threads": True, "can_pin_threads": 2}) def test_merge_allowed_global_weight(self): """api allows global weight""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "$$$", "category": self.category.id, "weight": 2, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "title": [ "Thread title should be at least 5 characters long (it has 3)." ] }, ) @patch_category_acl({"can_merge_threads": True, "can_close_threads": False}) def test_merge_unallowed_close(self): """api rejects merge because closing thread was unallowed""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "Valid thread title", "category": self.category.id, "is_closed": True, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "is_closed": [ "You don't have permission to close threads in this category." ] }, ) @patch_category_acl({"can_merge_threads": True, "can_close_threads": True}) def test_merge_with_close(self): """api allows for closing thread""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "$$$", "category": self.category.id, "weight": 0, "is_closed": True, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "title": [ "Thread title should be at least 5 characters long (it has 3)." ] }, ) @patch_category_acl({"can_merge_threads": True, "can_hide_threads": 0}) def test_merge_unallowed_hidden(self): """api rejects merge because hidden thread was unallowed""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "Valid thread title", "category": self.category.id, "is_hidden": True, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "is_hidden": [ "You don't have permission to hide threads in this category." ] }, ) @patch_category_acl({"can_merge_threads": True, "can_hide_threads": 1}) def test_merge_with_hide(self): """api allows for hiding thread""" thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "$$$", "category": self.category.id, "weight": 0, "is_hidden": True, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "title": [ "Thread title should be at least 5 characters long (it has 3)." ] }, ) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.api.threadendpoints.merge.delete_duplicate_watched_threads") def test_merge(self, delete_duplicate_watched_threads_mock): """api performs basic merge""" posts_ids = [p.id for p in Post.objects.all()] thread = test.post_thread(category=self.category) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "Merged thread!", "category": self.category.id, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) # is response json with new thread? response_json = response.json() new_thread = Thread.objects.get(pk=response_json["id"]) new_thread.is_read = False new_thread.subscription = None user_acl = useracl.get_user_acl(self.user, cache_versions) add_acl_to_obj(user_acl, new_thread.category) add_acl_to_obj(user_acl, new_thread) self.assertEqual( response_json, ThreadsListSerializer( new_thread, context={"settings": DynamicSettings(cache_versions)} ).data, ) # did posts move to new thread? for post in Post.objects.filter(id__in=posts_ids): self.assertEqual(post.thread_id, new_thread.id) # are old threads gone? self.assertEqual([t.pk for t in Thread.objects.all()], [new_thread.pk]) @patch_category_acl( { "can_merge_threads": True, "can_close_threads": True, "can_hide_threads": 1, "can_pin_threads": 2, } ) @patch("misago.threads.api.threadendpoints.merge.delete_duplicate_watched_threads") def test_merge_kitchensink(self, delete_duplicate_watched_threads_mock): """api performs merge""" posts_ids = [p.id for p in Post.objects.all()] thread = test.post_thread(category=self.category) poststracker.save_read(self.user, self.thread.first_post) poststracker.save_read(self.user, thread.first_post) self.user.subscription_set.create( thread=self.thread, category=self.thread.category, last_read_on=self.thread.last_post_on, send_email=False, ) self.user.subscription_set.create( thread=thread, category=thread.category, last_read_on=thread.last_post_on, send_email=False, ) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, thread.id], "title": "Merged thread!", "category": self.category.id, "is_closed": 1, "is_hidden": 1, "weight": 2, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) # is response json with new thread? response_json = response.json() new_thread = Thread.objects.get(pk=response_json["id"]) new_thread.is_read = False new_thread.subscription = None self.assertEqual(new_thread.weight, 2) self.assertTrue(new_thread.is_closed) self.assertTrue(new_thread.is_hidden) user_acl = useracl.get_user_acl(self.user, cache_versions) add_acl_to_obj(user_acl, new_thread.category) add_acl_to_obj(user_acl, new_thread) self.assertEqual( response_json, ThreadsListSerializer( new_thread, context={"settings": DynamicSettings(cache_versions)} ).data, ) # did posts move to new thread? for post in Post.objects.filter(id__in=posts_ids): self.assertEqual(post.thread_id, new_thread.id) # are old threads gone? self.assertEqual([t.pk for t in Thread.objects.all()], [new_thread.pk]) # posts reads are kept postreads = self.user.postread_set.filter(post__is_event=False).order_by("id") self.assertEqual( list(postreads.values_list("post_id", flat=True)), [self.thread.first_post_id, thread.first_post_id], ) self.assertEqual(postreads.filter(thread=new_thread).count(), 2) self.assertEqual(postreads.filter(category=self.category).count(), 2) # subscriptions are kept self.assertEqual(self.user.subscription_set.count(), 1) self.user.subscription_set.get(thread=new_thread) self.user.subscription_set.get(category=self.category) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.api.threadendpoints.merge.delete_duplicate_watched_threads") def test_merge_threads_merged_best_answer( self, delete_duplicate_watched_threads_mock ): """api merges two threads successfully, moving best answer to old thread""" other_thread = test.post_thread(self.category) best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.save() response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, other_thread.id], "title": "Merged thread!", "category": self.category.id, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) # best answer is set on new thread new_thread = Thread.objects.get(pk=response.json()["id"]) self.assertEqual(new_thread.best_answer_id, best_answer.id) @patch_category_acl({"can_merge_threads": True}) def test_merge_threads_merge_conflict_best_answer(self): """api errors on merge conflict, returning list of available best answers""" best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.save() other_thread = test.post_thread(self.category) other_best_answer = test.reply_thread(other_thread) other_thread.set_best_answer(self.user, other_best_answer) other_thread.save() response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, other_thread.id], "title": "Merged thread!", "category": self.category.id, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "best_answers": [ ["0", "Unmark all best answers"], [str(self.thread.id), self.thread.title], [str(other_thread.id), other_thread.title], ] }, ) # best answers were untouched self.assertEqual(self.thread.post_set.count(), 2) self.assertEqual(other_thread.post_set.count(), 2) self.assertEqual( Thread.objects.get(pk=self.thread.pk).best_answer_id, best_answer.id ) self.assertEqual( Thread.objects.get(pk=other_thread.pk).best_answer_id, other_best_answer.id ) @patch_category_acl({"can_merge_threads": True}) def test_threads_merge_conflict_best_answer_invalid_resolution(self): """api errors on invalid merge conflict resolution""" best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.save() other_thread = test.post_thread(self.category) other_best_answer = test.reply_thread(other_thread) other_thread.set_best_answer(self.user, other_best_answer) other_thread.save() response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, other_thread.id], "title": "Merged thread!", "category": self.category.id, "best_answer": other_thread.id + 10, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"best_answer": ["Invalid choice."]}) # best answers were untouched self.assertEqual(self.thread.post_set.count(), 2) self.assertEqual(other_thread.post_set.count(), 2) self.assertEqual( Thread.objects.get(pk=self.thread.pk).best_answer_id, best_answer.id ) self.assertEqual( Thread.objects.get(pk=other_thread.pk).best_answer_id, other_best_answer.id ) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.api.threadendpoints.merge.delete_duplicate_watched_threads") def test_threads_merge_conflict_unmark_all_best_answers( self, delete_duplicate_watched_threads_mock ): """api unmarks all best answers when unmark all choice is selected""" best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.save() other_thread = test.post_thread(self.category) other_best_answer = test.reply_thread(other_thread) other_thread.set_best_answer(self.user, other_best_answer) other_thread.save() response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, other_thread.id], "title": "Merged thread!", "category": self.category.id, "best_answer": 0, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) # best answer is not set on new thread new_thread = Thread.objects.get(pk=response.json()["id"]) self.assertFalse(new_thread.has_best_answer) self.assertIsNone(new_thread.best_answer_id) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.api.threadendpoints.merge.delete_duplicate_watched_threads") def test_threads_merge_conflict_keep_first_best_answer( self, delete_duplicate_watched_threads_mock ): """api unmarks other best answer on merge""" best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.save() other_thread = test.post_thread(self.category) other_best_answer = test.reply_thread(other_thread) other_thread.set_best_answer(self.user, other_best_answer) other_thread.save() response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, other_thread.id], "title": "Merged thread!", "category": self.category.id, "best_answer": self.thread.pk, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) # selected best answer is set on new thread new_thread = Thread.objects.get(pk=response.json()["id"]) self.assertEqual(new_thread.best_answer_id, best_answer.id) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.api.threadendpoints.merge.delete_duplicate_watched_threads") def test_threads_merge_conflict_keep_other_best_answer( self, delete_duplicate_watched_threads_mock ): """api unmarks first best answer on merge""" best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.save() other_thread = test.post_thread(self.category) other_best_answer = test.reply_thread(other_thread) other_thread.set_best_answer(self.user, other_best_answer) other_thread.save() response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, other_thread.id], "title": "Merged thread!", "category": self.category.id, "best_answer": other_thread.pk, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) # selected best answer is set on new thread new_thread = Thread.objects.get(pk=response.json()["id"]) self.assertEqual(new_thread.best_answer_id, other_best_answer.id) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.api.threadendpoints.merge.delete_duplicate_watched_threads") def test_merge_threads_kept_poll(self, delete_duplicate_watched_threads_mock): """api merges two threads successfully, keeping poll from other thread""" other_thread = test.post_thread(self.category) poll = test.post_poll(other_thread, self.user) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, other_thread.id], "title": "Merged thread!", "category": self.category.id, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) new_thread = Thread.objects.get(pk=response.json()["id"]) # poll and its votes were kept self.assertEqual(Poll.objects.filter(pk=poll.pk, thread=new_thread).count(), 1) self.assertEqual( PollVote.objects.filter(poll=poll, thread=new_thread).count(), 4 ) self.assertEqual(Poll.objects.count(), 1) self.assertEqual(PollVote.objects.count(), 4) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.api.threadendpoints.merge.delete_duplicate_watched_threads") def test_merge_threads_moved_poll(self, delete_duplicate_watched_threads_mock): """api merges two threads successfully, moving poll from old thread""" other_thread = test.post_thread(self.category) poll = test.post_poll(self.thread, self.user) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, other_thread.id], "title": "Merged thread!", "category": self.category.id, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) new_thread = Thread.objects.get(pk=response.json()["id"]) # poll and its votes were kept self.assertEqual(Poll.objects.filter(pk=poll.pk, thread=new_thread).count(), 1) self.assertEqual( PollVote.objects.filter(poll=poll, thread=new_thread).count(), 4 ) self.assertEqual(Poll.objects.count(), 1) self.assertEqual(PollVote.objects.count(), 4) @patch_category_acl({"can_merge_threads": True}) def test_threads_merge_conflict_poll(self): """api errors on merge conflict, returning list of available polls""" other_thread = test.post_thread(self.category) poll = test.post_poll(self.thread, self.user) other_poll = test.post_poll(other_thread, self.user) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, other_thread.id], "title": "Merged thread!", "category": self.category.id, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "polls": [ ["0", "Delete all polls"], [ str(other_poll.pk), "%s (%s)" % (other_poll.question, other_poll.thread.title), ], [str(poll.pk), "%s (%s)" % (poll.question, poll.thread.title)], ] }, ) # polls and votes were untouched self.assertEqual(Poll.objects.count(), 2) self.assertEqual(PollVote.objects.count(), 8) @patch_category_acl({"can_merge_threads": True}) def test_threads_merge_conflict_poll_invalid_resolution(self): """api errors on invalid merge conflict resolution""" other_thread = test.post_thread(self.category) test.post_poll(self.thread, self.user) test.post_poll(other_thread, self.user) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, other_thread.id], "title": "Merged thread!", "category": self.category.id, "poll": other_thread.poll.id + 10, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"poll": ["Invalid choice."]}) # polls and votes were untouched self.assertEqual(Poll.objects.count(), 2) self.assertEqual(PollVote.objects.count(), 8) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.api.threadendpoints.merge.delete_duplicate_watched_threads") def test_threads_merge_conflict_delete_all_polls( self, delete_duplicate_watched_threads_mock ): """api deletes all polls when delete all choice is selected""" other_thread = test.post_thread(self.category) test.post_poll(self.thread, self.user) test.post_poll(other_thread, self.user) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, other_thread.id], "title": "Merged thread!", "category": self.category.id, "poll": 0, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) # polls and votes are gone self.assertEqual(Poll.objects.count(), 0) self.assertEqual(PollVote.objects.count(), 0) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.api.threadendpoints.merge.delete_duplicate_watched_threads") def test_threads_merge_conflict_keep_first_poll( self, delete_duplicate_watched_threads_mock ): """api deletes other poll on merge""" other_thread = test.post_thread(self.category) poll = test.post_poll(self.thread, self.user) other_poll = test.post_poll(other_thread, self.user) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, other_thread.id], "title": "Merged thread!", "category": self.category.id, "poll": poll.pk, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) # other poll and its votes are gone self.assertEqual(Poll.objects.count(), 1) self.assertEqual(PollVote.objects.count(), 4) Poll.objects.get(pk=poll.pk) with self.assertRaises(Poll.DoesNotExist): Poll.objects.get(pk=other_poll.pk) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.api.threadendpoints.merge.delete_duplicate_watched_threads") def test_threads_merge_conflict_keep_other_poll( self, delete_duplicate_watched_threads_mock ): """api deletes first poll on merge""" other_thread = test.post_thread(self.category) poll = test.post_poll(self.thread, self.user) other_poll = test.post_poll(other_thread, self.user) response = self.client.post( self.api_link, json.dumps( { "threads": [self.thread.id, other_thread.id], "title": "Merged thread!", "category": self.category.id, "poll": other_poll.pk, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) # other poll and its votes are gone self.assertEqual(Poll.objects.count(), 1) self.assertEqual(PollVote.objects.count(), 4) Poll.objects.get(pk=other_poll.pk) with self.assertRaises(Poll.DoesNotExist): Poll.objects.get(pk=poll.pk) @pytest.fixture def delete_duplicate_watched_threads_mock(mocker): return mocker.patch( "misago.threads.api.threadendpoints.merge.delete_duplicate_watched_threads" ) @patch_category_acl({"can_merge_threads": True}) def test_threads_merge_api_merges_notifications( delete_duplicate_watched_threads_mock, user, user_client, thread, other_thread, ): notification = Notification.objects.create( user=user, verb="TEST", category=other_thread.category, thread=other_thread, thread_title=other_thread.title, post=other_thread.first_post, ) response = user_client.post( reverse("misago:api:thread-merge"), json={ "threads": [thread.id, other_thread.id], "title": "Merged thread", "category": thread.category.id, }, ) assert response.status_code == 200 new_thread = Thread.objects.get(pk=response.json()["id"]) notification.refresh_from_db() assert notification.category_id == new_thread.category_id assert notification.thread_id == new_thread.id assert notification.thread_title == "Merged thread" @patch_category_acl({"can_merge_threads": True}) def test_threads_merge_api_merges_watched_threads( delete_duplicate_watched_threads_mock, user, user_client, thread, other_thread, watched_thread_factory, ): watched_thread = watched_thread_factory(user, thread, send_emails=True) response = user_client.post( reverse("misago:api:thread-merge"), json={ "threads": [thread.id, other_thread.id], "title": "Merged thread", "category": thread.category.id, }, ) assert response.status_code == 200 new_thread = Thread.objects.get(pk=response.json()["id"]) watched_thread.refresh_from_db() assert watched_thread.category_id == new_thread.category_id assert watched_thread.thread_id == new_thread.id delete_duplicate_watched_threads_mock.delay.assert_called_once_with(new_thread.id)
43,041
Python
.py
1,066
28.56379
87
0.558626
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,148
test_threadparticipant_model.py
rafalp_Misago/misago/threads/tests/test_threadparticipant_model.py
from django.test import TestCase from django.utils import timezone from ...categories.models import Category from ...users.test import create_test_user from ..models import Post, Thread, ThreadParticipant class ThreadParticipantTests(TestCase): def setUp(self): datetime = timezone.now() self.category = Category.objects.all_categories()[:1][0] self.thread = Thread( category=self.category, started_on=datetime, starter_name="Tester", starter_slug="tester", last_post_on=datetime, last_poster_name="Tester", last_poster_slug="tester", ) self.thread.set_title("Test thread") self.thread.save() post = Post.objects.create( category=self.category, thread=self.thread, poster_name="Tester", original="Hello! I am test message!", parsed="<p>Hello! I am test message!</p>", checksum="nope", posted_on=datetime, updated_on=datetime, ) self.thread.first_post = post self.thread.last_post = post self.thread.save() def test_set_owner(self): """set_owner makes user thread owner""" user = create_test_user("User", "user@example.com") other_user = create_test_user("User2", "user2@example.com") ThreadParticipant.objects.set_owner(self.thread, user) self.assertEqual(self.thread.participants.count(), 1) participant = ThreadParticipant.objects.get(thread=self.thread, user=user) self.assertTrue(participant.is_owner) self.assertEqual(user, participant.user) # threads can't have more than one owner ThreadParticipant.objects.set_owner(self.thread, other_user) self.assertEqual(self.thread.participants.count(), 2) participant = ThreadParticipant.objects.get(thread=self.thread, user=user) self.assertFalse(participant.is_owner) self.assertEqual(ThreadParticipant.objects.filter(is_owner=True).count(), 1) def test_add_participants(self): """add_participant adds participant to thread""" users = [ create_test_user("User", "user@example.com"), create_test_user("User2", "user2@example.com"), ] ThreadParticipant.objects.add_participants(self.thread, users) self.assertEqual(self.thread.participants.count(), 2) for user in users: participant = ThreadParticipant.objects.get(thread=self.thread, user=user) self.assertFalse(participant.is_owner) def test_remove_participant(self): """remove_participant deletes participant from thread""" user = create_test_user("User", "user@example.com") other_user = create_test_user("User2", "user2@example.com") ThreadParticipant.objects.add_participants(self.thread, [user]) ThreadParticipant.objects.add_participants(self.thread, [other_user]) self.assertEqual(self.thread.participants.count(), 2) ThreadParticipant.objects.remove_participant(self.thread, user) self.assertEqual(self.thread.participants.count(), 1) with self.assertRaises(ThreadParticipant.DoesNotExist): ThreadParticipant.objects.get(thread=self.thread, user=user)
3,355
Python
.py
70
38.414286
86
0.662175
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,149
test_thread_polldelete_api.py
rafalp_Misago/misago/threads/tests/test_thread_polldelete_api.py
from datetime import timedelta from django.urls import reverse from django.utils import timezone from ...acl.test import patch_user_acl from ..models import Poll, PollVote, Thread from ..test import patch_category_acl from .test_thread_poll_api import ThreadPollApiTestCase class ThreadPollDeleteTests(ThreadPollApiTestCase): def setUp(self): super().setUp() self.mock_poll() def test_anonymous(self): """api requires you to sign in to delete poll""" self.logout_user() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) def test_invalid_thread_id(self): """api validates that thread id is integer""" api_link = reverse( "misago:api:thread-poll-detail", kwargs={"thread_pk": "kjha6dsa687sa", "pk": self.poll.pk}, ) response = self.client.delete(api_link) self.assertEqual(response.status_code, 404) def test_nonexistant_thread_id(self): """api validates that thread exists""" api_link = reverse( "misago:api:thread-poll-detail", kwargs={"thread_pk": self.thread.pk + 1, "pk": self.poll.pk}, ) response = self.client.delete(api_link) self.assertEqual(response.status_code, 404) def test_invalid_poll_id(self): """api validates that poll id is integer""" api_link = reverse( "misago:api:thread-poll-detail", kwargs={"thread_pk": self.thread.pk, "pk": "sad98as7d97sa98"}, ) response = self.client.delete(api_link) self.assertEqual(response.status_code, 404) def test_nonexistant_poll_id(self): """api validates that poll exists""" api_link = reverse( "misago:api:thread-poll-detail", kwargs={"thread_pk": self.thread.pk, "pk": self.poll.pk + 123}, ) response = self.client.delete(api_link) self.assertEqual(response.status_code, 404) @patch_user_acl({"can_delete_polls": 0}) def test_no_permission(self): """api validates that user has permission to delete poll in thread""" response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual(response.json(), {"detail": "You can't delete polls."}) @patch_user_acl({"can_delete_polls": 1, "poll_edit_time": 5}) def test_no_permission_timeout(self): """api validates that user's window to delete poll in thread has closed""" self.poll.posted_on = timezone.now() - timedelta(minutes=15) self.poll.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't delete polls that are older than 5 minutes."}, ) @patch_user_acl({"can_delete_polls": 1}) def test_no_permission_poll_closed(self): """api validates that user's window to delete poll in thread has closed""" self.poll.posted_on = timezone.now() - timedelta(days=15) self.poll.length = 5 self.poll.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This poll is over. You can't delete it."} ) @patch_user_acl({"can_delete_polls": 1}) def test_no_permission_other_user_poll(self): """api validates that user has permission to delete other user poll in thread""" self.poll.poster = None self.poll.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't delete other users polls in this category."}, ) @patch_user_acl({"can_delete_polls": 1}) @patch_category_acl({"can_close_threads": False}) def test_no_permission_closed_thread(self): """api validates that user has permission to delete poll in closed thread""" self.thread.is_closed = True self.thread.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This thread is closed. You can't delete polls in it."}, ) @patch_user_acl({"can_delete_polls": 1}) @patch_category_acl({"can_close_threads": True}) def test_closed_thread(self): """api validates that user has permission to delete poll in closed thread""" self.thread.is_closed = True self.thread.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 200) @patch_user_acl({"can_delete_polls": 1}) @patch_category_acl({"can_close_threads": False}) def test_no_permission_closed_category(self): """api validates that user has permission to delete poll in closed category""" self.category.is_closed = True self.category.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This category is closed. You can't delete polls in it."}, ) @patch_user_acl({"can_delete_polls": 1}) @patch_category_acl({"can_close_threads": True}) def test_closed_category(self): """api validates that user has permission to delete poll in closed category""" self.category.is_closed = True self.category.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 200) @patch_user_acl({"can_delete_polls": 1, "poll_edit_time": 5}) def test_poll_delete(self): """api deletes poll and associated votes""" response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), {"can_start_poll": True}) self.assertEqual(Poll.objects.count(), 0) self.assertEqual(PollVote.objects.count(), 0) # api set poll flag on thread to False thread = Thread.objects.get(pk=self.thread.pk) self.assertFalse(thread.has_poll) @patch_user_acl({"can_delete_polls": 2, "poll_edit_time": 5}) def test_other_user_poll_delete(self): """api deletes other user's poll and associated votes, even if its over""" self.poll.poster = None self.poll.posted_on = timezone.now() - timedelta(days=15) self.poll.length = 5 self.poll.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), {"can_start_poll": True}) self.assertEqual(Poll.objects.count(), 0) self.assertEqual(PollVote.objects.count(), 0) # api set poll flag on thread to False thread = Thread.objects.get(pk=self.thread.pk) self.assertFalse(thread.has_poll)
7,141
Python
.py
153
38.183007
88
0.644317
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,150
test_private_thread_replies_mark_read.py
rafalp_Misago/misago/threads/tests/test_private_thread_replies_mark_read.py
from django.urls import reverse from ...conf.test import override_dynamic_settings from ...notifications.users import notify_user from ...readtracker.models import ReadCategory, ReadThread from ...test import assert_contains from ..test import reply_thread def test_private_thread_replies_view_marks_category_as_read_for_user( user_client, user, private_threads_category, user_private_thread ): private_threads_category.last_post_on = user_private_thread.last_post_on private_threads_category.save() response = user_client.get( reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ), ) assert_contains(response, user_private_thread.title) assert not ReadThread.objects.exists() ReadCategory.objects.get( user=user, category=private_threads_category, read_time=private_threads_category.last_post_on, ) def test_private_thread_replies_view_marks_thread_as_read_for_user( user_client, user, private_threads_category, user_private_thread, other_user_private_thread, ): private_threads_category.last_post_on = other_user_private_thread.last_post_on private_threads_category.save() response = user_client.get( reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ), ) assert_contains(response, user_private_thread.title) assert not ReadCategory.objects.exists() ReadThread.objects.get( user=user, category=private_threads_category, thread=user_private_thread, read_time=user_private_thread.last_post_on, ) @override_dynamic_settings(posts_per_page=5, posts_per_page_orphans=0) def test_private_thread_replies_view_marks_unread_thread_posts_on_page_as_read_for_user( user_client, user, private_threads_category, user_private_thread ): posts = [reply_thread(user_private_thread) for _ in range(5)] user_private_thread.synchronize() user_private_thread.save() private_threads_category.synchronize() private_threads_category.save() response = user_client.get( reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ), ) assert_contains(response, user_private_thread.title) assert not ReadCategory.objects.exists() ReadThread.objects.get( user=user, category=private_threads_category, thread=user_private_thread, read_time=posts[-2].posted_on, ) def test_private_thread_replies_view_updates_user_watched_thread_read_time( user_client, user, private_threads_category, user_private_thread, other_user_private_thread, watched_thread_factory, ): watched_thread = watched_thread_factory(user, user_private_thread, False) watched_thread.read_time = watched_thread.read_time.replace(year=2010) watched_thread.save() private_threads_category.last_post_on = other_user_private_thread.last_post_on private_threads_category.save() response = user_client.get( reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ), ) assert_contains(response, user_private_thread.title) watched_thread.refresh_from_db() assert watched_thread.read_time == user_private_thread.last_post_on def test_private_thread_replies_view_marks_displayed_posts_notifications_as_read( user_client, user, private_threads_category, user_private_thread, ): notification = notify_user( user, "test", category=private_threads_category, thread=user_private_thread, post=user_private_thread.first_post, ) user.unread_notifications = 5 user.save() response = user_client.get( reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ), ) assert_contains(response, user_private_thread.title) user.refresh_from_db() assert user.unread_notifications == 4 notification.refresh_from_db() assert notification.is_read def test_private_thread_replies_view_decreases_user_unread_threads_count_on_thread_read( user_client, user, private_threads_category, user_private_thread, other_user_private_thread, ): user.unread_private_threads = 5 user.save() private_threads_category.last_post_on = other_user_private_thread.last_post_on private_threads_category.save() response = user_client.get( reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ), ) assert_contains(response, user_private_thread.title) user.refresh_from_db() assert user.unread_private_threads == 4 @override_dynamic_settings(posts_per_page=5, posts_per_page_orphans=0) def test_private_thread_replies_view_doesnt_update_user_unread_threads_count_on_thread_page_read( user_client, user, private_threads_category, user_private_thread ): user.unread_private_threads = 5 user.save() [reply_thread(user_private_thread) for _ in range(5)] private_threads_category.synchronize() private_threads_category.save() response = user_client.get( reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ), ) assert_contains(response, user_private_thread.title) user.refresh_from_db() assert user.unread_private_threads == 5 def test_private_thread_replies_view_clears_user_unread_threads_count_on_category_read( user_client, user, private_threads_category, user_private_thread ): user.unread_private_threads = 5 user.save() private_threads_category.last_post_on = user_private_thread.last_post_on private_threads_category.save() response = user_client.get( reverse( "misago:private-thread", kwargs={"id": user_private_thread.id, "slug": user_private_thread.slug}, ), ) assert_contains(response, user_private_thread.title) user.refresh_from_db() assert user.unread_private_threads == 0
6,422
Python
.py
172
31.162791
97
0.696521
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,151
test_thread_postsplit_api.py
rafalp_Misago/misago/threads/tests/test_thread_postsplit_api.py
import json from django.urls import reverse from .. import test from ...categories.models import Category from ...conf.test import override_dynamic_settings from ...users.test import AuthenticatedUserTestCase from ..models import Post from ..test import patch_category_acl, patch_other_category_acl class ThreadPostSplitApiTestCase(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.get(slug="first-category") self.thread = test.post_thread(category=self.category) self.posts = [ test.reply_thread(self.thread).pk, test.reply_thread(self.thread).pk, ] self.api_link = reverse( "misago:api:thread-post-split", kwargs={"thread_pk": self.thread.pk} ) Category(name="Other category", slug="other-category").insert_at( self.category, position="last-child", save=True ) self.other_category = Category.objects.get(slug="other-category") def test_anonymous_user(self): """you need to authenticate to split posts""" self.logout_user() response = self.client.post( self.api_link, json.dumps({}), content_type="application/json" ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This action is not available to guests."} ) @patch_category_acl({"can_move_posts": False}) def test_no_permission(self): """api validates permission to split""" response = self.client.post( self.api_link, json.dumps({}), content_type="application/json" ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't split posts from this thread."} ) @patch_category_acl({"can_move_posts": True}) def test_empty_data(self): """api handles empty data""" response = self.client.post(self.api_link) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You have to specify at least one post to split."}, ) @patch_category_acl({"can_move_posts": True}) def test_invalid_data(self): """api handles post that is invalid type""" response = self.client.post( self.api_link, "[]", content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] }, ) response = self.client.post( self.api_link, "123", content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"non_field_errors": ["Invalid data. Expected a dictionary, but got int."]}, ) response = self.client.post( self.api_link, '"string"', content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"non_field_errors": ["Invalid data. Expected a dictionary, but got str."]}, ) response = self.client.post( self.api_link, "malformed", content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)"}, ) @patch_category_acl({"can_move_posts": True}) def test_no_posts_ids(self): """api rejects no posts ids""" response = self.client.post( self.api_link, json.dumps({}), content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You have to specify at least one post to split."}, ) @patch_category_acl({"can_move_posts": True}) def test_empty_posts_ids(self): """api rejects empty posts ids list""" response = self.client.post( self.api_link, json.dumps({"posts": []}), content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You have to specify at least one post to split."}, ) @patch_category_acl({"can_move_posts": True}) def test_invalid_posts_data(self): """api handles invalid data""" response = self.client.post( self.api_link, json.dumps({"posts": "string"}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": 'Expected a list of items but got type "str".'} ) @patch_category_acl({"can_move_posts": True}) def test_invalid_posts_ids(self): """api handles invalid post id""" response = self.client.post( self.api_link, json.dumps({"posts": [1, 2, "string"]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "One or more post ids received were invalid."} ) @override_dynamic_settings(posts_per_page=5, posts_per_page_orphans=3) @patch_category_acl({"can_move_posts": True}) def test_split_limit(self): """api rejects more posts than split limit""" response = self.client.post( self.api_link, json.dumps({"posts": list(range(9))}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "No more than 8 posts can be split at a single time."}, ) @patch_category_acl({"can_move_posts": True}) def test_split_invisible(self): """api validates posts visibility""" response = self.client.post( self.api_link, json.dumps( {"posts": [test.reply_thread(self.thread, is_unapproved=True).pk]} ), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "One or more posts to split could not be found."}, ) @patch_category_acl({"can_move_posts": True}) def test_split_event(self): """api rejects events split""" response = self.client.post( self.api_link, json.dumps({"posts": [test.reply_thread(self.thread, is_event=True).pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"detail": "Events can't be split."}) @patch_category_acl({"can_move_posts": True}) def test_split_first_post(self): """api rejects first post split""" response = self.client.post( self.api_link, json.dumps({"posts": [self.thread.first_post_id]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Thread's first post can't be split."} ) @patch_category_acl({"can_move_posts": True}) def test_split_hidden_posts(self): """api recjects attempt to split urneadable hidden post""" response = self.client.post( self.api_link, json.dumps({"posts": [test.reply_thread(self.thread, is_hidden=True).pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You can't split posts the content you can't see."}, ) @patch_category_acl({"can_move_posts": True, "can_close_threads": False}) def test_split_posts_closed_thread_no_permission(self): """api recjects attempt to split posts from closed thread""" self.thread.is_closed = True self.thread.save() response = self.client.post( self.api_link, json.dumps({"posts": [test.reply_thread(self.thread).pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "This thread is closed. You can't split posts in it."}, ) @patch_category_acl({"can_move_posts": True, "can_close_threads": False}) def test_split_posts_closed_category_no_permission(self): """api recjects attempt to split posts from closed thread""" self.category.is_closed = True self.category.save() response = self.client.post( self.api_link, json.dumps({"posts": [test.reply_thread(self.thread).pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "This category is closed. You can't split posts in it."}, ) @patch_category_acl({"can_move_posts": True}) def test_split_other_thread_posts(self): """api recjects attempt to split other thread's post""" other_thread = test.post_thread(self.category) response = self.client.post( self.api_link, json.dumps({"posts": [test.reply_thread(other_thread, is_hidden=True).pk]}), content_type="application/json", ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "One or more posts to split could not be found."}, ) @patch_category_acl({"can_move_posts": True}) def test_split_empty_new_thread_data(self): """api handles empty form data""" response = self.client.post( self.api_link, json.dumps({"posts": self.posts}), content_type="application/json", ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json, { "title": ["This field is required."], "category": ["This field is required."], }, ) @patch_category_acl({"can_move_posts": True}) def test_split_invalid_final_title(self): """api rejects split because final thread title was invalid""" response = self.client.post( self.api_link, json.dumps( {"posts": self.posts, "title": "$$$", "category": self.category.id} ), content_type="application/json", ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json, { "title": [ "Thread title should be at least 5 characters long (it has 3)." ] }, ) @patch_other_category_acl({"can_see": False}) @patch_category_acl({"can_move_posts": True}) def test_split_invalid_category(self): """api rejects split because final category was invalid""" response = self.client.post( self.api_link, json.dumps( { "posts": self.posts, "title": "Valid thread title", "category": self.other_category.id, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json, {"category": ["Requested category could not be found."]} ) @patch_category_acl({"can_move_posts": True, "can_start_threads": False}) def test_split_unallowed_start_thread(self): """api rejects split because category isn't allowing starting threads""" response = self.client.post( self.api_link, json.dumps( { "posts": self.posts, "title": "Valid thread title", "category": self.category.id, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json, {"category": ["You can't create new threads in selected category."]}, ) @patch_category_acl({"can_move_posts": True}) def test_split_invalid_weight(self): """api rejects split because final weight was invalid""" response = self.client.post( self.api_link, json.dumps( { "posts": self.posts, "title": "Valid thread title", "category": self.category.id, "weight": 4, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json, {"weight": ["Ensure this value is less than or equal to 2."]} ) @patch_category_acl({"can_move_posts": True}) def test_split_unallowed_global_weight(self): """api rejects split because global weight was unallowed""" response = self.client.post( self.api_link, json.dumps( { "posts": self.posts, "title": "Valid thread title", "category": self.category.id, "weight": 2, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json, { "weight": [ "You don't have permission to pin threads " "globally in this category." ] }, ) @patch_category_acl({"can_move_posts": True, "can_pin_threads": 0}) def test_split_unallowed_local_weight(self): """api rejects split because local weight was unallowed""" response = self.client.post( self.api_link, json.dumps( { "posts": self.posts, "title": "Valid thread title", "category": self.category.id, "weight": 1, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json, {"weight": ["You don't have permission to pin threads in this category."]}, ) @patch_category_acl({"can_move_posts": True, "can_pin_threads": 1}) def test_split_allowed_local_weight(self): """api allows local weight""" response = self.client.post( self.api_link, json.dumps( { "posts": self.posts, "title": "$$$", "category": self.category.id, "weight": 1, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json, { "title": [ "Thread title should be at least 5 characters long (it has 3)." ] }, ) @patch_category_acl({"can_move_posts": True, "can_pin_threads": 2}) def test_split_allowed_global_weight(self): """api allows global weight""" response = self.client.post( self.api_link, json.dumps( { "posts": self.posts, "title": "$$$", "category": self.category.id, "weight": 2, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json, { "title": [ "Thread title should be at least 5 characters long (it has 3)." ] }, ) @patch_category_acl({"can_move_posts": True, "can_close_threads": False}) def test_split_unallowed_close(self): """api rejects split because closing thread was unallowed""" response = self.client.post( self.api_link, json.dumps( { "posts": self.posts, "title": "Valid thread title", "category": self.category.id, "is_closed": True, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json, { "is_closed": [ "You don't have permission to close threads in this category." ] }, ) @patch_category_acl({"can_move_posts": True, "can_close_threads": True}) def test_split_with_close(self): """api allows for closing thread""" response = self.client.post( self.api_link, json.dumps( { "posts": self.posts, "title": "$$$", "category": self.category.id, "weight": 0, "is_closed": True, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json, { "title": [ "Thread title should be at least 5 characters long (it has 3)." ] }, ) @patch_category_acl({"can_move_posts": True, "can_hide_threads": 0}) def test_split_unallowed_hidden(self): """api rejects split because hidden thread was unallowed""" response = self.client.post( self.api_link, json.dumps( { "posts": self.posts, "title": "Valid thread title", "category": self.category.id, "is_hidden": True, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json, { "is_hidden": [ "You don't have permission to hide threads in this category." ] }, ) @patch_category_acl({"can_move_posts": True, "can_hide_threads": 1}) def test_split_with_hide(self): """api allows for hiding thread""" response = self.client.post( self.api_link, json.dumps( { "posts": self.posts, "title": "$$$", "category": self.category.id, "weight": 0, "is_hidden": True, } ), content_type="application/json", ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json, { "title": [ "Thread title should be at least 5 characters long (it has 3)." ] }, ) @patch_category_acl({"can_move_posts": True}) def test_split(self): """api splits posts to new thread""" self.thread.refresh_from_db() self.assertEqual(self.thread.replies, 2) response = self.client.post( self.api_link, json.dumps( { "posts": self.posts, "title": "Split thread.", "category": self.category.id, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) # thread was created split_thread = self.category.thread_set.get(slug="split-thread") self.assertEqual(split_thread.replies, 1) # posts were removed from old thread self.thread.refresh_from_db() self.assertEqual(self.thread.replies, 0) # posts were moved to new thread self.assertEqual(split_thread.post_set.filter(pk__in=self.posts).count(), 2) @patch_category_acl({"can_move_posts": True}) def test_split_best_answer(self): """api splits best answer to new thread""" best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.synchronize() self.thread.save() self.thread.refresh_from_db() self.assertEqual(self.thread.best_answer, best_answer) self.assertEqual(self.thread.replies, 3) response = self.client.post( self.api_link, json.dumps( { "posts": [best_answer.pk], "title": "Split thread.", "category": self.category.id, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) # best_answer was moved and unmarked self.thread.refresh_from_db() self.assertEqual(self.thread.replies, 2) self.assertIsNone(self.thread.best_answer) split_thread = self.category.thread_set.get(slug="split-thread") self.assertEqual(split_thread.replies, 0) self.assertIsNone(split_thread.best_answer) @patch_other_category_acl( { "can_start_threads": True, "can_close_threads": True, "can_hide_threads": True, "can_pin_threads": 2, } ) @patch_category_acl({"can_move_posts": True}) def test_split_kitchensink(self): """api splits posts with kitchensink""" self.thread.refresh_from_db() self.assertEqual(self.thread.replies, 2) poststracker.save_read(self.user, self.thread.first_post) for post in self.posts: poststracker.save_read( self.user, Post.objects.select_related().get(pk=post) ) response = self.client.post( self.api_link, json.dumps( { "posts": self.posts, "title": "Split thread", "category": self.other_category.id, "weight": 2, "is_closed": 1, "is_hidden": 1, } ), content_type="application/json", ) self.assertEqual(response.status_code, 200) # thread was created split_thread = self.other_category.thread_set.get(slug="split-thread") self.assertEqual(split_thread.replies, 1) self.assertEqual(split_thread.weight, 2) self.assertTrue(split_thread.is_closed) self.assertTrue(split_thread.is_hidden) # posts were removed from old thread self.thread.refresh_from_db() self.assertEqual(self.thread.replies, 0) # posts were moved to new thread self.assertEqual(split_thread.post_set.filter(pk__in=self.posts).count(), 2) # postreads were removed postreads = self.user.postread_set.filter(post__is_event=False).order_by("id") postreads_threads = list(postreads.values_list("thread_id", flat=True)) self.assertEqual(postreads_threads, [self.thread.pk]) postreads_categories = list(postreads.values_list("category_id", flat=True)) self.assertEqual(postreads_categories, [self.category.pk])
24,920
Python
.py
646
27.037152
88
0.545913
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,152
test_thread_replies_mark_read.py
rafalp_Misago/misago/threads/tests/test_thread_replies_mark_read.py
from django.urls import reverse from ...conf.test import override_dynamic_settings from ...notifications.users import notify_user from ...readtracker.models import ReadCategory, ReadThread from ...test import assert_contains from ..test import reply_thread def test_thread_replies_view_doesnt_mark_unread_threads_for_guest(client, thread): response = client.get( reverse("misago:thread", kwargs={"id": thread.id, "slug": thread.slug}), ) assert_contains(response, thread.title) assert not ReadCategory.objects.exists() assert not ReadThread.objects.exists() def test_thread_replies_view_marks_category_as_read_for_user( user_client, user, default_category, thread ): default_category.last_post_on = thread.last_post_on default_category.save() response = user_client.get( reverse("misago:thread", kwargs={"id": thread.id, "slug": thread.slug}), ) assert_contains(response, thread.title) assert not ReadThread.objects.exists() ReadCategory.objects.get( user=user, category=default_category, read_time=default_category.last_post_on, ) def test_thread_replies_view_marks_thread_as_read_for_user( user_client, user, default_category, thread, other_thread ): default_category.last_post_on = other_thread.last_post_on default_category.save() response = user_client.get( reverse("misago:thread", kwargs={"id": thread.id, "slug": thread.slug}), ) assert_contains(response, thread.title) assert not ReadCategory.objects.exists() ReadThread.objects.get( user=user, category=default_category, thread=thread, read_time=thread.last_post_on, ) @override_dynamic_settings(posts_per_page=5, posts_per_page_orphans=0) def test_thread_replies_view_marks_unread_thread_posts_on_page_as_read_for_user( user_client, user, default_category, thread ): posts = [reply_thread(thread) for _ in range(5)] thread.synchronize() thread.save() default_category.synchronize() default_category.save() response = user_client.get( reverse("misago:thread", kwargs={"id": thread.id, "slug": thread.slug}), ) assert_contains(response, thread.title) assert not ReadCategory.objects.exists() ReadThread.objects.get( user=user, category=default_category, thread=thread, read_time=posts[-2].posted_on, ) def test_thread_replies_view_updates_user_watched_thread_read_time( user_client, user, default_category, thread, other_thread, watched_thread_factory, ): watched_thread = watched_thread_factory(user, thread, False) watched_thread.read_time = watched_thread.read_time.replace(year=2010) watched_thread.save() default_category.last_post_on = other_thread.last_post_on default_category.save() response = user_client.get( reverse("misago:thread", kwargs={"id": thread.id, "slug": thread.slug}), ) assert_contains(response, thread.title) watched_thread.refresh_from_db() assert watched_thread.read_time == thread.last_post_on def test_thread_replies_view_marks_displayed_posts_notifications_as_read( user_client, user, default_category, thread, ): notification = notify_user( user, "test", category=default_category, thread=thread, post=thread.first_post, ) user.unread_notifications = 5 user.save() response = user_client.get( reverse( "misago:thread", kwargs={"id": thread.id, "slug": thread.slug}, ), ) assert_contains(response, thread.title) user.refresh_from_db() assert user.unread_notifications == 4 notification.refresh_from_db() assert notification.is_read
3,823
Python
.py
109
29.477064
82
0.696065
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,153
test_privatethread_patch_api.py
rafalp_Misago/misago/threads/tests/test_privatethread_patch_api.py
import json from unittest.mock import patch from .. import test from ...acl.test import patch_user_acl from ...users.test import create_test_user from ..models import Thread, ThreadParticipant from ..test import other_user_cant_use_private_threads from .test_privatethreads import PrivateThreadsTestCase class PrivateThreadPatchApiTestCase(PrivateThreadsTestCase): def setUp(self): super().setUp() self.thread = test.post_thread(self.category, poster=self.user) self.api_link = self.thread.get_api_url() self.other_user = create_test_user("Other_User", "otheruser@example.com") def patch(self, api_link, ops): return self.client.patch( api_link, json.dumps(ops), content_type="application/json" ) class PrivateThreadAddParticipantApiTests(PrivateThreadPatchApiTestCase): def test_add_participant_not_owner(self): """non-owner can't add participant""" ThreadParticipant.objects.add_participants(self.thread, [self.user]) response = self.patch( self.api_link, [{"op": "add", "path": "participants", "value": self.user.username}], ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "id": self.thread.pk, "detail": [ "You have to be thread owner to add new participants to it." ], }, ) def test_add_empty_username(self): """path validates username""" ThreadParticipant.objects.set_owner(self.thread, self.user) response = self.patch( self.api_link, [{"op": "add", "path": "participants", "value": ""}] ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "id": self.thread.pk, "detail": ["You have to enter new participant's username."], }, ) def test_add_nonexistant_user(self): """can't user two times""" ThreadParticipant.objects.set_owner(self.thread, self.user) response = self.patch( self.api_link, [{"op": "add", "path": "participants", "value": "InvalidUser"}], ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"id": self.thread.pk, "detail": ["No user with this name exists."]}, ) def test_add_already_participant(self): """can't add user that is already participant""" ThreadParticipant.objects.set_owner(self.thread, self.user) response = self.patch( self.api_link, [{"op": "add", "path": "participants", "value": self.user.username}], ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "id": self.thread.pk, "detail": ["This user is already thread participant."], }, ) def test_add_blocking_user(self): """can't add user that is blocking us""" ThreadParticipant.objects.set_owner(self.thread, self.user) self.other_user.blocks.add(self.user) response = self.patch( self.api_link, [{"op": "add", "path": "participants", "value": self.other_user.username}], ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"id": self.thread.pk, "detail": ["Other_User is blocking you."]}, ) @patch_user_acl(other_user_cant_use_private_threads) def test_add_no_perm_user(self): """can't add user that has no permission to use private threads""" ThreadParticipant.objects.set_owner(self.thread, self.user) response = self.patch( self.api_link, [{"op": "add", "path": "participants", "value": self.other_user.username}], ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "id": self.thread.pk, "detail": ["Other_User can't participate in private threads."], }, ) @patch_user_acl({"max_private_thread_participants": 3}) def test_add_too_many_users(self): """can't add user that is already participant""" ThreadParticipant.objects.set_owner(self.thread, self.user) for i in range(3): user = create_test_user("User%s" % i, "user%s@example.com" % i) ThreadParticipant.objects.add_participants(self.thread, [user]) response = self.patch( self.api_link, [{"op": "add", "path": "participants", "value": self.other_user.username}], ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "id": self.thread.pk, "detail": ["You can't add any more new users to this thread."], }, ) def test_add_user_closed_thread(self): """adding user to closed thread fails for non-moderator""" ThreadParticipant.objects.set_owner(self.thread, self.user) self.thread.is_closed = True self.thread.save() response = self.patch( self.api_link, [{"op": "add", "path": "participants", "value": self.other_user.username}], ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "id": self.thread.pk, "detail": ["Only moderators can add participants to closed threads."], }, ) @patch("misago.threads.participants.notify_on_new_private_thread") def test_add_user(self, notify_on_new_private_thread_mock): """ adding user to thread add user to thread as participant, sets event and notifies them """ ThreadParticipant.objects.set_owner(self.thread, self.user) self.patch( self.api_link, [{"op": "add", "path": "participants", "value": self.other_user.username}], ) # event was set on thread event = self.thread.post_set.order_by("id").last() self.assertTrue(event.is_event) self.assertTrue(event.event_type, "added_participant") # notification about new private thread was triggered notify_on_new_private_thread_mock.delay.assert_called_once_with( self.user.id, self.thread.id, [self.other_user.id] ) @patch_user_acl({"can_moderate_private_threads": True}) @patch("misago.threads.participants.notify_on_new_private_thread") def test_add_user_to_other_user_thread_moderator( self, notify_on_new_private_thread_mock ): """moderators can add users to other users threads""" ThreadParticipant.objects.set_owner(self.thread, self.other_user) self.thread.has_reported_posts = True self.thread.save() self.patch( self.api_link, [{"op": "add", "path": "participants", "value": self.user.username}], ) # event was set on thread event = self.thread.post_set.order_by("id").last() self.assertTrue(event.is_event) self.assertTrue(event.event_type, "entered_thread") # notification about new private thread was triggered notify_on_new_private_thread_mock.delay.assert_not_called() @patch_user_acl({"can_moderate_private_threads": True}) @patch("misago.threads.participants.notify_on_new_private_thread") def test_add_user_to_closed_moderator(self, notify_on_new_private_thread_mock): """moderators can add users to closed threads""" ThreadParticipant.objects.set_owner(self.thread, self.user) self.thread.is_closed = True self.thread.save() self.patch( self.api_link, [{"op": "add", "path": "participants", "value": self.other_user.username}], ) # event was set on thread event = self.thread.post_set.order_by("id").last() self.assertTrue(event.is_event) self.assertTrue(event.event_type, "added_participant") # notification about new private thread was triggered notify_on_new_private_thread_mock.delay.assert_called_once_with( self.user.id, self.thread.id, [self.other_user.id] ) class PrivateThreadRemoveParticipantApiTests(PrivateThreadPatchApiTestCase): def test_remove_empty(self): """api handles empty user id""" ThreadParticipant.objects.set_owner(self.thread, self.user) response = self.patch( self.api_link, [{"op": "remove", "path": "participants", "value": ""}] ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"id": self.thread.pk, "detail": ["A valid integer is required."]}, ) def test_remove_invalid(self): """api validates user id type""" ThreadParticipant.objects.set_owner(self.thread, self.user) response = self.patch( self.api_link, [{"op": "remove", "path": "participants", "value": "string"}] ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"id": self.thread.pk, "detail": ["A valid integer is required."]}, ) def test_remove_nonexistant(self): """removed user has to be participant""" ThreadParticipant.objects.set_owner(self.thread, self.user) response = self.patch( self.api_link, [{"op": "remove", "path": "participants", "value": self.other_user.pk}], ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"id": self.thread.pk, "detail": ["Participant doesn't exist."]}, ) def test_remove_not_owner(self): """api validates if user trying to remove other user is an owner""" ThreadParticipant.objects.set_owner(self.thread, self.other_user) ThreadParticipant.objects.add_participants(self.thread, [self.user]) response = self.patch( self.api_link, [{"op": "remove", "path": "participants", "value": self.other_user.pk}], ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "id": self.thread.pk, "detail": [ "You have to be thread owner to remove participants from it." ], }, ) def test_owner_remove_user_closed_thread(self): """api disallows owner to remove other user from closed thread""" ThreadParticipant.objects.set_owner(self.thread, self.user) ThreadParticipant.objects.add_participants(self.thread, [self.other_user]) self.thread.is_closed = True self.thread.save() response = self.patch( self.api_link, [{"op": "remove", "path": "participants", "value": self.other_user.pk}], ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "id": self.thread.pk, "detail": [ "Only moderators can remove participants from closed threads." ], }, ) def test_user_leave_thread(self): """api allows user to remove themself from thread""" ThreadParticipant.objects.set_owner(self.thread, self.other_user) ThreadParticipant.objects.add_participants(self.thread, [self.user]) self.user.subscription_set.create(category=self.category, thread=self.thread) response = self.patch( self.api_link, [{"op": "remove", "path": "participants", "value": self.user.pk}], ) self.assertEqual(response.status_code, 200) self.assertFalse(response.json()["deleted"]) # thread still exists self.assertTrue(Thread.objects.get(pk=self.thread.pk)) # leave event has valid type event = self.thread.post_set.order_by("id").last() self.assertTrue(event.is_event) self.assertTrue(event.event_type, "participant_left") # valid users were flagged for sync self.user.refresh_from_db() self.assertTrue(self.user.sync_unread_private_threads) self.other_user.refresh_from_db() self.assertTrue(self.other_user.sync_unread_private_threads) # user was removed from participation self.assertEqual(self.thread.participants.count(), 1) self.assertEqual(self.thread.participants.filter(pk=self.user.pk).count(), 0) # thread was removed from user subscriptions self.assertEqual(self.user.subscription_set.count(), 0) def test_user_leave_closed_thread(self): """api allows user to remove themself from closed thread""" ThreadParticipant.objects.set_owner(self.thread, self.other_user) ThreadParticipant.objects.add_participants(self.thread, [self.user]) self.thread.is_closed = True self.thread.save() response = self.patch( self.api_link, [{"op": "remove", "path": "participants", "value": self.user.pk}], ) self.assertEqual(response.status_code, 200) self.assertFalse(response.json()["deleted"]) # thread still exists self.assertTrue(Thread.objects.get(pk=self.thread.pk)) # leave event has valid type event = self.thread.post_set.order_by("id").last() self.assertTrue(event.is_event) self.assertTrue(event.event_type, "participant_left") # valid users were flagged for sync self.user.refresh_from_db() self.assertTrue(self.user.sync_unread_private_threads) self.other_user.refresh_from_db() self.assertTrue(self.other_user.sync_unread_private_threads) # user was removed from participation self.assertEqual(self.thread.participants.count(), 1) self.assertEqual(self.thread.participants.filter(pk=self.user.pk).count(), 0) @patch_user_acl({"can_moderate_private_threads": True}) def test_moderator_remove_user(self): """api allows moderator to remove other user""" removed_user = create_test_user("RemovedUser", "removeduser@example.com") ThreadParticipant.objects.set_owner(self.thread, self.other_user) ThreadParticipant.objects.add_participants( self.thread, [self.user, removed_user] ) response = self.patch( self.api_link, [{"op": "remove", "path": "participants", "value": removed_user.pk}], ) self.assertEqual(response.status_code, 200) self.assertFalse(response.json()["deleted"]) # thread still exists self.assertTrue(Thread.objects.get(pk=self.thread.pk)) # leave event has valid type event = self.thread.post_set.order_by("id").last() self.assertTrue(event.is_event) self.assertTrue(event.event_type, "participant_removed") # valid users were flagged for sync self.user.refresh_from_db() self.assertTrue(self.user.sync_unread_private_threads) self.other_user.refresh_from_db() self.assertTrue(self.other_user.sync_unread_private_threads) removed_user.refresh_from_db() self.assertTrue(removed_user.sync_unread_private_threads) # user was removed from participation self.assertEqual(self.thread.participants.count(), 2) self.assertEqual(self.thread.participants.filter(pk=removed_user.pk).count(), 0) def test_owner_remove_user(self): """api allows owner to remove other user""" ThreadParticipant.objects.set_owner(self.thread, self.user) ThreadParticipant.objects.add_participants(self.thread, [self.other_user]) response = self.patch( self.api_link, [{"op": "remove", "path": "participants", "value": self.other_user.pk}], ) self.assertEqual(response.status_code, 200) self.assertFalse(response.json()["deleted"]) # thread still exists self.assertTrue(Thread.objects.get(pk=self.thread.pk)) # leave event has valid type event = self.thread.post_set.order_by("id").last() self.assertTrue(event.is_event) self.assertTrue(event.event_type, "participant_removed") # valid users were flagged for sync self.user.refresh_from_db() self.assertTrue(self.user.sync_unread_private_threads) self.other_user.refresh_from_db() self.assertTrue(self.other_user.sync_unread_private_threads) # user was removed from participation self.assertEqual(self.thread.participants.count(), 1) self.assertEqual( self.thread.participants.filter(pk=self.other_user.pk).count(), 0 ) def test_owner_leave_thread(self): """api allows owner to remove hisemf from thread, causing thread to close""" ThreadParticipant.objects.set_owner(self.thread, self.user) ThreadParticipant.objects.add_participants(self.thread, [self.other_user]) response = self.patch( self.api_link, [{"op": "remove", "path": "participants", "value": self.user.pk}], ) self.assertEqual(response.status_code, 200) self.assertFalse(response.json()["deleted"]) # thread still exists and is closed self.assertTrue(Thread.objects.get(pk=self.thread.pk).is_closed) # leave event has valid type event = self.thread.post_set.order_by("id").last() self.assertTrue(event.is_event) self.assertTrue(event.event_type, "owner_left") # valid users were flagged for sync self.user.refresh_from_db() self.assertTrue(self.user.sync_unread_private_threads) self.other_user.refresh_from_db() self.assertTrue(self.other_user.sync_unread_private_threads) # user was removed from participation self.assertEqual(self.thread.participants.count(), 1) self.assertEqual(self.thread.participants.filter(pk=self.user.pk).count(), 0) def test_last_user_leave_thread(self): """api allows last user leave thread, causing thread to delete""" ThreadParticipant.objects.set_owner(self.thread, self.user) response = self.patch( self.api_link, [{"op": "remove", "path": "participants", "value": self.user.pk}], ) self.assertEqual(response.status_code, 200) self.assertTrue(response.json()["deleted"]) # thread is gone with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk) # valid users were flagged for sync self.user.refresh_from_db() self.assertTrue(self.user.sync_unread_private_threads) class PrivateThreadTakeOverApiTests(PrivateThreadPatchApiTestCase): def test_empty_user_id(self): """api handles empty user id""" ThreadParticipant.objects.set_owner(self.thread, self.user) response = self.patch( self.api_link, [{"op": "replace", "path": "owner", "value": ""}] ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"id": self.thread.pk, "detail": ["A valid integer is required."]}, ) def test_invalid_user_id(self): """api handles invalid user id""" ThreadParticipant.objects.set_owner(self.thread, self.user) response = self.patch( self.api_link, [{"op": "replace", "path": "owner", "value": "dsadsa"}] ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"id": self.thread.pk, "detail": ["A valid integer is required."]}, ) def test_nonexistant_user_id(self): """api handles nonexistant user id""" ThreadParticipant.objects.set_owner(self.thread, self.user) response = self.patch( self.api_link, [{"op": "replace", "path": "owner", "value": self.other_user.pk}], ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"id": self.thread.pk, "detail": ["Participant doesn't exist."]}, ) def test_no_permission(self): """non-moderator/owner can't change owner""" ThreadParticipant.objects.set_owner(self.thread, self.other_user) ThreadParticipant.objects.add_participants(self.thread, [self.user]) response = self.patch( self.api_link, [{"op": "replace", "path": "owner", "value": self.user.pk}] ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "id": self.thread.pk, "detail": [ "Only thread owner and moderators can appoint a new thread owner." ], }, ) def test_no_change(self): """api validates that new owner id is same as current owner""" ThreadParticipant.objects.set_owner(self.thread, self.user) ThreadParticipant.objects.add_participants(self.thread, [self.other_user]) response = self.patch( self.api_link, [{"op": "replace", "path": "owner", "value": self.user.pk}] ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"id": self.thread.pk, "detail": ["This user already is thread owner."]}, ) def test_change_closed_thread_owner(self): """non-moderator can't change owner in closed thread""" ThreadParticipant.objects.set_owner(self.thread, self.user) ThreadParticipant.objects.add_participants(self.thread, [self.other_user]) self.thread.is_closed = True self.thread.save() response = self.patch( self.api_link, [{"op": "replace", "path": "owner", "value": self.other_user.pk}], ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "id": self.thread.pk, "detail": [ "Only moderators can appoint a new thread owner in a closed thread." ], }, ) def test_owner_change_thread_owner(self): """owner can pass thread ownership to other participant""" ThreadParticipant.objects.set_owner(self.thread, self.user) ThreadParticipant.objects.add_participants(self.thread, [self.other_user]) response = self.patch( self.api_link, [{"op": "replace", "path": "owner", "value": self.other_user.pk}], ) self.assertEqual(response.status_code, 200) # valid users were flagged for sync self.user.refresh_from_db() self.assertFalse(self.user.sync_unread_private_threads) self.other_user.refresh_from_db() self.assertTrue(self.other_user.sync_unread_private_threads) # ownership was transfered self.assertEqual(self.thread.participants.count(), 2) self.assertTrue(ThreadParticipant.objects.get(user=self.other_user).is_owner) self.assertFalse(ThreadParticipant.objects.get(user=self.user).is_owner) # change was recorded in event event = self.thread.post_set.order_by("id").last() self.assertTrue(event.is_event) self.assertTrue(event.event_type, "changed_owner") @patch_user_acl({"can_moderate_private_threads": True}) def test_moderator_change_owner(self): """moderator can change thread owner to other user""" new_owner = create_test_user("NewOwner", "newowner@example.com") ThreadParticipant.objects.set_owner(self.thread, self.other_user) ThreadParticipant.objects.add_participants(self.thread, [self.user, new_owner]) response = self.patch( self.api_link, [{"op": "replace", "path": "owner", "value": new_owner.pk}] ) self.assertEqual(response.status_code, 200) # valid users were flagged for sync new_owner.refresh_from_db() self.assertTrue(new_owner.sync_unread_private_threads) self.user.refresh_from_db() self.assertFalse(self.user.sync_unread_private_threads) self.other_user.refresh_from_db() self.assertTrue(self.other_user.sync_unread_private_threads) # ownership was transferred self.assertEqual(self.thread.participants.count(), 3) self.assertTrue(ThreadParticipant.objects.get(user=new_owner).is_owner) self.assertFalse(ThreadParticipant.objects.get(user=self.user).is_owner) self.assertFalse(ThreadParticipant.objects.get(user=self.other_user).is_owner) # change was recorded in event event = self.thread.post_set.order_by("id").last() self.assertTrue(event.is_event) self.assertTrue(event.event_type, "changed_owner") @patch_user_acl({"can_moderate_private_threads": True}) def test_moderator_takeover(self): """moderator can takeover the thread""" ThreadParticipant.objects.set_owner(self.thread, self.other_user) ThreadParticipant.objects.add_participants(self.thread, [self.user]) response = self.patch( self.api_link, [{"op": "replace", "path": "owner", "value": self.user.pk}] ) self.assertEqual(response.status_code, 200) # valid users were flagged for sync self.user.refresh_from_db() self.assertFalse(self.user.sync_unread_private_threads) self.other_user.refresh_from_db() self.assertTrue(self.other_user.sync_unread_private_threads) # ownership was transfered self.assertEqual(self.thread.participants.count(), 2) self.assertTrue(ThreadParticipant.objects.get(user=self.user).is_owner) self.assertFalse(ThreadParticipant.objects.get(user=self.other_user).is_owner) # change was recorded in event event = self.thread.post_set.order_by("id").last() self.assertTrue(event.is_event) self.assertTrue(event.event_type, "tookover") @patch_user_acl({"can_moderate_private_threads": True}) def test_moderator_closed_thread_takeover(self): """moderator can takeover closed thread thread""" ThreadParticipant.objects.set_owner(self.thread, self.other_user) ThreadParticipant.objects.add_participants(self.thread, [self.user]) self.thread.is_closed = True self.thread.save() response = self.patch( self.api_link, [{"op": "replace", "path": "owner", "value": self.user.pk}] ) self.assertEqual(response.status_code, 200) # valid users were flagged for sync self.user.refresh_from_db() self.assertFalse(self.user.sync_unread_private_threads) self.other_user.refresh_from_db() self.assertTrue(self.other_user.sync_unread_private_threads) # ownership was transferred self.assertEqual(self.thread.participants.count(), 2) self.assertTrue(ThreadParticipant.objects.get(user=self.user).is_owner) self.assertFalse(ThreadParticipant.objects.get(user=self.other_user).is_owner) # change was recorded in event event = self.thread.post_set.order_by("id").last() self.assertTrue(event.is_event) self.assertTrue(event.event_type, "tookover")
27,928
Python
.py
598
36.755853
88
0.626104
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,154
test_thread_polledit_api.py
rafalp_Misago/misago/threads/tests/test_thread_polledit_api.py
from datetime import timedelta from django.urls import reverse from django.utils import timezone from ...acl.test import patch_user_acl from ..serializers.poll import MAX_POLL_OPTIONS from ..test import patch_category_acl from .test_thread_poll_api import ThreadPollApiTestCase class ThreadPollEditTests(ThreadPollApiTestCase): def setUp(self): super().setUp() self.mock_poll() def test_anonymous(self): """api requires you to sign in to edit poll""" self.logout_user() response = self.put(self.api_link) self.assertEqual(response.status_code, 403) def test_invalid_thread_id(self): """api validates that thread id is integer""" api_link = reverse( "misago:api:thread-poll-detail", kwargs={"thread_pk": "kjha6dsa687sa", "pk": self.poll.pk}, ) response = self.put(api_link) self.assertEqual(response.status_code, 404) def test_nonexistant_thread_id(self): """api validates that thread exists""" api_link = reverse( "misago:api:thread-poll-detail", kwargs={"thread_pk": self.thread.pk + 1, "pk": self.poll.pk}, ) response = self.put(api_link) self.assertEqual(response.status_code, 404) def test_invalid_poll_id(self): """api validates that poll id is integer""" api_link = reverse( "misago:api:thread-poll-detail", kwargs={"thread_pk": self.thread.pk, "pk": "sad98as7d97sa98"}, ) response = self.put(api_link) self.assertEqual(response.status_code, 404) def test_nonexistant_poll_id(self): """api validates that poll exists""" api_link = reverse( "misago:api:thread-poll-detail", kwargs={"thread_pk": self.thread.pk, "pk": self.poll.pk + 123}, ) response = self.put(api_link) self.assertEqual(response.status_code, 404) @patch_user_acl({"can_edit_polls": 0}) def test_no_permission(self): """api validates that user has permission to edit poll in thread""" response = self.put(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual(response.json(), {"detail": "You can't edit polls."}) @patch_user_acl({"can_edit_polls": 1, "poll_edit_time": 5}) def test_no_permission_timeout(self): """api validates that user's window to edit poll in thread has closed""" self.poll.posted_on = timezone.now() - timedelta(minutes=15) self.poll.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't edit polls that are older than 5 minutes."}, ) @patch_user_acl({"can_edit_polls": 1}) def test_no_permission_poll_closed(self): """api validates that user's window to edit poll in thread has closed""" self.poll.posted_on = timezone.now() - timedelta(days=15) self.poll.length = 5 self.poll.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This poll is over. You can't edit it."} ) @patch_user_acl({"can_edit_polls": 1}) def test_no_permission_other_user_poll(self): """api validates that user has permission to edit other user poll in thread""" self.poll.poster = None self.poll.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't edit other users polls in this category."}, ) @patch_user_acl({"can_edit_polls": 1}) @patch_category_acl({"can_close_threads": False}) def test_no_permission_closed_thread(self): """api validates that user has permission to edit poll in closed thread""" self.thread.is_closed = True self.thread.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This thread is closed. You can't edit polls in it."}, ) @patch_user_acl({"can_edit_polls": 1}) @patch_category_acl({"can_close_threads": True}) def test_closed_thread(self): """api validates that user has permission to edit poll in closed thread""" self.thread.is_closed = True self.thread.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 400) @patch_user_acl({"can_edit_polls": 1}) @patch_category_acl({"can_close_threads": False}) def test_no_permission_closed_category(self): """api validates that user has permission to edit poll in closed category""" self.category.is_closed = True self.category.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This category is closed. You can't edit polls in it."}, ) @patch_user_acl({"can_edit_polls": 1}) @patch_category_acl({"can_close_threads": True}) def test_closed_category(self): """api validates that user has permission to edit poll in closed category""" self.category.is_closed = True self.category.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 400) def test_empty_data(self): """api handles empty request data""" response = self.put(self.api_link) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual(len(response_json), 4) def test_length_validation(self): """api validates poll's length""" response = self.put(self.api_link, data={"length": -1}) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["length"], ["Ensure this value is greater than or equal to 0."], ) response = self.put(self.api_link, data={"length": 200}) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["length"], ["Ensure this value is less than or equal to 180."] ) def test_question_validation(self): """api validates question length""" response = self.put(self.api_link, data={"question": "abcd" * 255}) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["question"], ["Ensure this field has no more than 255 characters."], ) def test_validate_choice_length(self): """api validates single choice length""" response = self.put( self.api_link, data={"choices": [{"hash": "qwertyuiopas", "label": ""}]} ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["choices"], ["One or more poll choices are invalid."] ) response = self.put( self.api_link, data={"choices": [{"hash": "qwertyuiopas", "label": "abcd" * 255}]}, ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["choices"], ["One or more poll choices are invalid."] ) def test_validate_two_choices(self): """api validates that there are at least two choices in poll""" response = self.put(self.api_link, data={"choices": [{"label": "Choice"}]}) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["choices"], ["You need to add at least two choices to a poll."], ) def test_validate_max_choices(self): """api validates that there are no more choices in poll than allowed number""" response = self.put( self.api_link, data={"choices": [{"label": "Choice"}] * (MAX_POLL_OPTIONS + 1)}, ) self.assertEqual(response.status_code, 400) error_formats = (MAX_POLL_OPTIONS, MAX_POLL_OPTIONS + 1) response_json = response.json() self.assertEqual( response_json["choices"], [ "You can't add more than %s options to a single poll (added %s)." % error_formats ], ) def test_allowed_choices_validation(self): """api validates allowed choices number""" response = self.put(self.api_link, data={"allowed_choices": 0}) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["allowed_choices"], ["Ensure this value is greater than or equal to 1."], ) response = self.put( self.api_link, data={ "length": 0, "question": "Lorem ipsum", "allowed_choices": 3, "choices": [{"label": "Choice"}, {"label": "Choice"}], }, ) self.assertEqual(response.status_code, 400) response_json = response.json() self.assertEqual( response_json["non_field_errors"], ["Number of allowed choices can't be greater than number of all choices."], ) def test_poll_all_choices_replaced(self): """api edits all poll choices out""" response = self.put( self.api_link, data={ "length": 40, "question": "Select two best colors", "allowed_choices": 2, "allow_revotes": True, "is_public": True, "choices": [ {"label": "\nRed "}, {"label": "Green"}, {"label": "Blue"}, ], }, ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["poster_name"], self.user.username) self.assertEqual(response_json["length"], 40) self.assertEqual(response_json["question"], "Select two best colors") self.assertEqual(response_json["allowed_choices"], 2) self.assertTrue(response_json["allow_revotes"]) # you can't change poll's type after its posted self.assertFalse(response_json["is_public"]) # choices were updated self.assertEqual(len(response_json["choices"]), 3) self.assertEqual(len({c["hash"] for c in response_json["choices"]}), 3) self.assertEqual( [c["label"] for c in response_json["choices"]], ["Red", "Green", "Blue"] ) self.assertEqual([c["votes"] for c in response_json["choices"]], [0, 0, 0]) self.assertEqual( [c["selected"] for c in response_json["choices"]], [False, False, False] ) # votes were removed self.assertEqual(response_json["votes"], 0) self.assertEqual(self.poll.pollvote_set.count(), 0) self.assertEqual(self.user.audittrail_set.count(), 1) def test_poll_current_choices_edited(self): """api edits current poll choices""" response = self.put( self.api_link, data={ "length": 40, "question": "Select two best colors", "allowed_choices": 2, "allow_revotes": True, "is_public": True, "choices": [ {"hash": "aaaaaaaaaaaa", "label": "\nFirst ", "votes": 5555}, {"hash": "bbbbbbbbbbbb", "label": "Second", "votes": 5555}, {"hash": "gggggggggggg", "label": "Third", "votes": 5555}, {"hash": "dddddddddddd", "label": "Fourth", "votes": 5555}, ], }, ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["poster_name"], self.user.username) self.assertEqual(response_json["length"], 40) self.assertEqual(response_json["question"], "Select two best colors") self.assertEqual(response_json["allowed_choices"], 2) self.assertTrue(response_json["allow_revotes"]) # you can't change poll's type after its posted self.assertFalse(response_json["is_public"]) # choices were updated self.assertEqual(len(response_json["choices"]), 4) self.assertEqual( response_json["choices"], [ { "hash": "aaaaaaaaaaaa", "label": "First", "votes": 1, "selected": False, }, { "hash": "bbbbbbbbbbbb", "label": "Second", "votes": 0, "selected": False, }, { "hash": "gggggggggggg", "label": "Third", "votes": 2, "selected": True, }, { "hash": "dddddddddddd", "label": "Fourth", "votes": 1, "selected": True, }, ], ) # no votes were removed self.assertEqual(response_json["votes"], 4) self.assertEqual(self.poll.pollvote_set.count(), 4) self.assertEqual(self.user.audittrail_set.count(), 1) def test_poll_some_choices_edited(self): """api edits some poll choices""" response = self.put( self.api_link, data={ "length": 40, "question": "Select two best colors", "allowed_choices": 2, "allow_revotes": True, "is_public": True, "choices": [ {"hash": "aaaaaaaaaaaa", "label": "\nFirst ", "votes": 5555}, {"hash": "bbbbbbbbbbbb", "label": "Second", "votes": 5555}, {"hash": "dsadsadsa788", "label": "New Option", "votes": 5555}, ], }, ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["poster_name"], self.user.username) self.assertEqual(response_json["length"], 40) self.assertEqual(response_json["question"], "Select two best colors") self.assertEqual(response_json["allowed_choices"], 2) self.assertTrue(response_json["allow_revotes"]) # you can't change poll's type after its posted self.assertFalse(response_json["is_public"]) # choices were updated self.assertEqual(len(response_json["choices"]), 3) self.assertEqual( response_json["choices"], [ { "hash": "aaaaaaaaaaaa", "label": "First", "votes": 1, "selected": False, }, { "hash": "bbbbbbbbbbbb", "label": "Second", "votes": 0, "selected": False, }, { "hash": response_json["choices"][2]["hash"], "label": "New Option", "votes": 0, "selected": False, }, ], ) # no votes were removed self.assertEqual(response_json["votes"], 1) self.assertEqual(self.poll.pollvote_set.count(), 1) self.assertEqual(self.user.audittrail_set.count(), 1) @patch_user_acl({"can_edit_polls": 2, "poll_edit_time": 5}) def test_moderate_user_poll(self): """api edits all poll choices out in other users poll, even if its over""" self.poll.poster = None self.poll.posted_on = timezone.now() - timedelta(days=15) self.poll.length = 5 self.poll.save() response = self.put( self.api_link, data={ "length": 40, "question": "Select two best colors", "allowed_choices": 2, "allow_revotes": True, "is_public": True, "choices": [ {"label": "\nRed "}, {"label": "Green"}, {"label": "Blue"}, ], }, ) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["poster_name"], self.user.username) self.assertEqual(response_json["length"], 40) self.assertEqual(response_json["question"], "Select two best colors") self.assertEqual(response_json["allowed_choices"], 2) self.assertTrue(response_json["allow_revotes"]) # you can't change poll's type after its posted self.assertFalse(response_json["is_public"]) # choices were updated self.assertEqual(len(response_json["choices"]), 3) self.assertEqual(len({c["hash"] for c in response_json["choices"]}), 3) self.assertEqual( [c["label"] for c in response_json["choices"]], ["Red", "Green", "Blue"] ) self.assertEqual([c["votes"] for c in response_json["choices"]], [0, 0, 0]) self.assertEqual( [c["selected"] for c in response_json["choices"]], [False, False, False] ) # votes were removed self.assertEqual(response_json["votes"], 0) self.assertEqual(self.poll.pollvote_set.count(), 0) self.assertEqual(self.user.audittrail_set.count(), 1)
18,243
Python
.py
427
31.400468
88
0.560498
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,155
test_thread_postbulkdelete_api.py
rafalp_Misago/misago/threads/tests/test_thread_postbulkdelete_api.py
import json from datetime import timedelta from django.urls import reverse from django.utils import timezone from .. import test from ..models import Post, Thread from ..test import patch_category_acl from .test_threads_api import ThreadsApiTestCase class PostBulkDeleteApiTests(ThreadsApiTestCase): def setUp(self): super().setUp() self.posts = [ test.reply_thread(self.thread, poster=self.user), test.reply_thread(self.thread), test.reply_thread(self.thread, poster=self.user), ] self.api_link = reverse( "misago:api:thread-post-list", kwargs={"thread_pk": self.thread.pk} ) def delete(self, url, data=None): return self.client.delete( url, json.dumps(data), content_type="application/json" ) def test_delete_anonymous(self): """api validates if deleting user is authenticated""" self.logout_user() response = self.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This action is not available to guests."} ) def test_delete_no_data(self): """api handles empty data""" response = self.client.delete(self.api_link, content_type="application/json") self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": 'Expected a list of items but got type "dict".'} ) def test_delete_no_ids(self): """api requires ids to delete""" response = self.delete(self.api_link) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You have to specify at least one post to delete."}, ) def test_delete_empty_ids(self): """api requires ids to delete""" response = self.delete(self.api_link, []) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You have to specify at least one post to delete."}, ) @patch_category_acl({"can_hide_posts": 2}) def test_validate_ids(self): """api validates that ids are list of ints""" response = self.delete(self.api_link, True) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": 'Expected a list of items but got type "bool".'} ) response = self.delete(self.api_link, "abbss") self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": 'Expected a list of items but got type "str".'} ) response = self.delete(self.api_link, [1, 2, 3, "a", "b", "x"]) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "One or more post ids received were invalid."} ) @patch_category_acl({"can_hide_posts": 2}) def test_validate_ids_length(self): """api validates that ids are list of ints""" response = self.delete(self.api_link, list(range(100))) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "No more than 24 posts can be deleted at a single time."}, ) @patch_category_acl({"can_hide_posts": 2}) def test_validate_posts_exist(self): """api validates that ids are visible posts""" response = self.delete(self.api_link, [p.id * 10 for p in self.posts]) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "One or more posts to delete could not be found."}, ) @patch_category_acl({"can_hide_posts": 2}) def test_validate_posts_visibility(self): """api validates that ids are visible posts""" self.posts[1].is_unapproved = True self.posts[1].save() response = self.delete(self.api_link, [p.id for p in self.posts]) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "One or more posts to delete could not be found."}, ) @patch_category_acl({"can_hide_posts": 2}) def test_validate_posts_same_thread(self): """api validates that ids are same thread posts""" other_thread = test.post_thread(category=self.category) self.posts.append(test.reply_thread(other_thread, poster=self.user)) response = self.delete(self.api_link, [p.id for p in self.posts]) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "One or more posts to delete could not be found."}, ) @patch_category_acl({"can_hide_posts": 1, "can_hide_own_posts": 1}) def test_no_permission(self): """api validates permission to delete""" response = self.delete(self.api_link, [p.id for p in self.posts]) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't delete posts in this category."} ) @patch_category_acl( {"can_hide_posts": 0, "can_hide_own_posts": 2, "post_edit_time": 10} ) def test_delete_other_user_post_no_permission(self): """api valdiates if user can delete other users posts""" response = self.delete(self.api_link, [p.id for p in self.posts]) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't delete other users posts in this category."}, ) @patch_category_acl( {"can_hide_posts": 0, "can_hide_own_posts": 2, "can_protect_posts": False} ) def test_delete_protected_post_no_permission(self): """api validates if user can delete protected post""" self.posts[0].is_protected = True self.posts[0].save() response = self.delete(self.api_link, [p.id for p in self.posts]) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This post is protected. You can't delete it."} ) @patch_category_acl( {"can_hide_posts": 0, "can_hide_own_posts": 2, "post_edit_time": 1} ) def test_delete_protected_post_after_edit_time(self): """api validates if user can delete delete post after edit time""" self.posts[0].posted_on = timezone.now() - timedelta(minutes=10) self.posts[0].save() response = self.delete(self.api_link, [p.id for p in self.posts]) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't delete posts that are older than 1 minute."}, ) @patch_category_acl( {"can_hide_posts": 2, "can_hide_own_posts": 2, "can_close_threads": False} ) def test_delete_post_closed_thread_no_permission(self): """api valdiates if user can delete posts in closed threads""" self.thread.is_closed = True self.thread.save() response = self.delete(self.api_link, [p.id for p in self.posts]) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This thread is closed. You can't delete posts in it."}, ) @patch_category_acl( {"can_hide_posts": 2, "can_hide_own_posts": 2, "can_close_threads": False} ) def test_delete_post_closed_category_no_permission(self): """api valdiates if user can delete posts in closed categories""" self.category.is_closed = True self.category.save() response = self.delete(self.api_link, [p.id for p in self.posts]) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This category is closed. You can't delete posts in it."}, ) @patch_category_acl({"can_hide_posts": 2, "can_hide_own_posts": 2}) def test_delete_first_post(self): """api disallows first post's deletion""" ids = [p.id for p in self.posts] ids.append(self.thread.first_post_id) response = self.delete(self.api_link, ids) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "Thread's first post can only be deleted together with thread."}, ) @patch_category_acl({"can_hide_posts": 2, "can_hide_own_posts": 2}) def test_delete_best_answer(self): """api disallows best answer deletion""" self.thread.set_best_answer(self.user, self.posts[0]) self.thread.save() response = self.delete(self.api_link, [p.id for p in self.posts]) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't delete this post because its marked as best answer."}, ) @patch_category_acl( {"can_hide_posts": 2, "can_hide_own_posts": 2, "can_hide_events": 0} ) def test_delete_event(self): """api differs posts from events""" self.posts[1].is_event = True self.posts[1].save() response = self.delete(self.api_link, [p.id for p in self.posts]) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't delete events in this category."} ) @patch_category_acl( {"can_hide_posts": 0, "can_hide_own_posts": 2, "post_edit_time": 10} ) def test_delete_owned_posts(self): """api deletes owned thread posts""" ids = [self.posts[0].id, self.posts[-1].id] response = self.delete(self.api_link, ids) self.assertEqual(response.status_code, 200) self.thread = Thread.objects.get(pk=self.thread.pk) self.assertNotEqual(self.thread.last_post_id, ids[-1]) for post in ids: with self.assertRaises(Post.DoesNotExist): self.thread.post_set.get(pk=post) @patch_category_acl({"can_hide_posts": 2, "can_hide_own_posts": 0}) def test_delete_posts(self): """api deletes thread posts""" response = self.delete(self.api_link, [p.id for p in self.posts]) self.assertEqual(response.status_code, 200) self.thread = Thread.objects.get(pk=self.thread.pk) self.assertNotEqual(self.thread.last_post_id, self.posts[-1].pk) for post in self.posts: with self.assertRaises(Post.DoesNotExist): self.thread.post_set.get(pk=post.pk)
10,795
Python
.py
239
36.317992
88
0.620814
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,156
test_threads_bulkdelete_api.py
rafalp_Misago/misago/threads/tests/test_threads_bulkdelete_api.py
import json from django.urls import reverse from .. import test from ...categories import PRIVATE_THREADS_ROOT_NAME from ...categories.models import Category from ...conf.test import override_dynamic_settings from ..models import Thread from ..test import patch_category_acl from ..threadtypes import trees_map from .test_threads_api import ThreadsApiTestCase class ThreadsBulkDeleteApiTests(ThreadsApiTestCase): def setUp(self): super().setUp() self.api_link = reverse("misago:api:thread-list") self.threads = [ test.post_thread(category=self.category, poster=self.user), test.post_thread(category=self.category), test.post_thread(category=self.category, poster=self.user), ] def delete(self, url, data=None): return self.client.delete( url, json.dumps(data), content_type="application/json" ) def test_delete_anonymous(self): """anonymous users can't bulk delete threads""" self.logout_user() response = self.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This action is not available to guests."} ) @patch_category_acl({"can_hide_threads": 2, "can_hide_own_threads": 2}) def test_delete_no_ids(self): """api requires ids to delete""" response = self.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You have to specify at least one thread to delete."}, ) @patch_category_acl({"can_hide_threads": 2, "can_hide_own_threads": 2}) def test_validate_ids(self): response = self.delete(self.api_link, True) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": 'Expected a list of items but got type "bool".'} ) response = self.delete(self.api_link, "abbss") self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": 'Expected a list of items but got type "str".'} ) response = self.delete(self.api_link, [1, 2, 3, "a", "b", "x"]) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "One or more thread ids received were invalid."} ) @override_dynamic_settings(threads_per_page=4) @patch_category_acl({"can_hide_threads": 2, "can_hide_own_threads": 2}) def test_validate_ids_length(self): """api validates that ids are list of ints""" response = self.delete(self.api_link, list(range(5))) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "No more than 4 threads can be deleted at a single time."}, ) @patch_category_acl({"can_hide_threads": 2, "can_hide_own_threads": 2}) def test_validate_thread_visibility(self): """api valdiates if user can see deleted thread""" unapproved_thread = self.threads[1] unapproved_thread.is_unapproved = True unapproved_thread.save() threads_ids = [p.id for p in self.threads] response = self.delete(self.api_link, threads_ids) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "One or more threads to delete could not be found."}, ) # no thread was deleted for thread in self.threads: Thread.objects.get(pk=thread.pk) @patch_category_acl({"can_hide_threads": 0, "can_hide_own_threads": 2}) def test_delete_other_user_thread_no_permission(self): """api valdiates if user can delete other users threads""" other_thread = self.threads[1] response = self.delete(self.api_link, [p.id for p in self.threads]) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), [ { "thread": {"id": other_thread.pk, "title": other_thread.title}, "error": "You can't delete other users theads in this category.", } ], ) # no threads are removed on failed attempt for thread in self.threads: Thread.objects.get(pk=thread.pk) @patch_category_acl( {"can_hide_threads": 2, "can_hide_own_threads": 2, "can_close_threads": False} ) def test_delete_thread_closed_category_no_permission(self): """api tests category's closed state""" self.category.is_closed = True self.category.save() response = self.delete(self.api_link, [p.id for p in self.threads]) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), [ { "thread": {"id": thread.pk, "title": thread.title}, "error": "This category is closed. You can't delete threads in it.", } for thread in sorted(self.threads, key=lambda i: i.pk) ], ) @patch_category_acl( {"can_hide_threads": 2, "can_hide_own_threads": 2, "can_close_threads": False} ) def test_delete_thread_closed_no_permission(self): """api tests thread's closed state""" closed_thread = self.threads[1] closed_thread.is_closed = True closed_thread.save() response = self.delete(self.api_link, [p.id for p in self.threads]) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), [ { "thread": {"id": closed_thread.pk, "title": closed_thread.title}, "error": "This thread is closed. You can't delete it.", } ], ) @patch_category_acl({"can_hide_threads": 2, "can_hide_own_threads": 2}) def test_delete_private_thread(self): """attempt to delete private thread fails""" private_thread = self.threads[0] private_thread.category = Category.objects.get( tree_id=trees_map.get_tree_id_for_root(PRIVATE_THREADS_ROOT_NAME) ) private_thread.save() private_thread.threadparticipant_set.create(user=self.user, is_owner=True) threads_ids = [p.id for p in self.threads] response = self.delete(self.api_link, threads_ids) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "One or more threads to delete could not be found."}, ) Thread.objects.get(pk=private_thread.pk)
6,844
Python
.py
156
34.24359
88
0.61076
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,157
test_threads_lists_flags.py
rafalp_Misago/misago/threads/tests/test_threads_lists_flags.py
from django.urls import reverse from ...conf.test import override_dynamic_settings from ...test import assert_contains, assert_not_contains from ..test import post_thread @override_dynamic_settings(index_view="categories") def test_site_threads_list_shows_thread_globally_pinned_flag(default_category, client): thread = post_thread(default_category, title="Global Thread", is_global=True) response = client.get(reverse("misago:threads")) assert_contains(response, thread.title) assert_contains(response, "thread-flags") assert_contains(response, "thread-flag-pinned-globally") def test_category_threads_list_shows_thread_globally_pinned_flag( default_category, client ): thread = post_thread(default_category, title="Global Thread", is_global=True) response = client.get(default_category.get_absolute_url()) assert_contains(response, thread.title) assert_contains(response, "thread-flags") assert_contains(response, "thread-flag-pinned-globally") @override_dynamic_settings(index_view="categories") def test_site_threads_list_doesnt_show_users_thread_ghost_pinned_flag( default_category, user_client ): thread = post_thread(default_category, title="Pinned Thread", is_pinned=True) response = user_client.get(reverse("misago:threads")) assert_contains(response, thread.title) assert_not_contains(response, "thread-flags") assert_not_contains(response, "thread-flag-pinned-locally") def test_category_threads_list_doesnt_show_users_ghost_thread_ghost_pinned_flag( default_category, child_category, user_client ): thread = post_thread(child_category, title="Pinned Thread", is_pinned=True) response = user_client.get(default_category.get_absolute_url()) assert_contains(response, thread.title) assert_not_contains(response, "thread-flags") assert_not_contains(response, "thread-flag-pinned-locally") @override_dynamic_settings(index_view="categories") def test_site_threads_list_shows_moderators_thread_ghost_pinned_flag( default_category, moderator_client ): thread = post_thread(default_category, title="Pinned Thread", is_pinned=True) response = moderator_client.get(reverse("misago:threads")) assert_contains(response, thread.title) assert_contains(response, "thread-flags") assert_contains(response, "thread-flag-pinned-locally-elsewhere") def test_category_threads_list_shows_moderators_thread_ghost_pinned_flag( default_category, child_category, moderator_client ): thread = post_thread(child_category, title="Pinned Thread", is_pinned=True) response = moderator_client.get(default_category.get_absolute_url()) assert_contains(response, thread.title) assert_contains(response, "thread-flags") assert_contains(response, "thread-flag-pinned-locally-elsewhere") def test_category_threads_list_shows_thread_pinned_flag( default_category, moderator_client ): thread = post_thread(default_category, title="Pinned Thread", is_pinned=True) response = moderator_client.get(default_category.get_absolute_url()) assert_contains(response, thread.title) assert_contains(response, "thread-flags") assert_contains(response, "thread-flag-pinned-locally") @override_dynamic_settings(index_view="categories") def test_site_threads_list_doesnt_show_thread_pinned_flag_for_unpinned_thread( default_category, client ): thread = post_thread(default_category, title="Regular Thread") response = client.get(reverse("misago:threads")) assert_contains(response, thread.title) assert_not_contains(response, "thread-flags") assert_not_contains(response, "thread-flag-pinned") def test_category_threads_list_shows_thread_globally_pinned_flag( default_category, client ): thread = post_thread(default_category, title="Regular Thread") response = client.get(default_category.get_absolute_url()) assert_contains(response, thread.title) assert_not_contains(response, "thread-flags") assert_not_contains(response, "thread-flag-pinned") @override_dynamic_settings(index_view="categories") def test_site_threads_list_shows_moderators_thread_has_unapproved_posts_flag( default_category, moderator_client ): thread = post_thread(default_category, title="Thread With Unapproved Posts") thread.has_unapproved_posts = True thread.save() response = moderator_client.get(reverse("misago:threads")) assert_contains(response, thread.title) assert_contains(response, "thread-flags") assert_contains(response, "thread-flag-unapproved") def test_category_threads_list_shows_moderators_thread_has_unapproved_posts_flag( default_category, moderator_client ): thread = post_thread(default_category, title="Thread With Unapproved Posts") thread.has_unapproved_posts = True thread.save() response = moderator_client.get(default_category.get_absolute_url()) assert_contains(response, thread.title) assert_contains(response, "thread-flags") assert_contains(response, "thread-flag-unapproved") @override_dynamic_settings(index_view="categories") def test_site_threads_list_shows_moderators_thread_is_unapproved_flag( default_category, moderator_client ): thread = post_thread( default_category, title="Unapproved Thread", is_unapproved=True ) response = moderator_client.get(reverse("misago:threads")) assert_contains(response, thread.title) assert_contains(response, "thread-flags") assert_contains(response, "thread-flag-unapproved") def test_category_threads_list_shows_moderators_thread_is_unapproved_flag( default_category, moderator_client ): thread = post_thread( default_category, title="Unapproved Thread", is_unapproved=True ) response = moderator_client.get(default_category.get_absolute_url()) assert_contains(response, thread.title) assert_contains(response, "thread-flags") assert_contains(response, "thread-flag-unapproved") @override_dynamic_settings(index_view="categories") def test_site_threads_list_shows_moderators_thread_has_unapproved_posts_flag( default_category, moderator_client ): thread = post_thread(default_category, title="Thread With Unapproved Posts") thread.has_unapproved_posts = True thread.save() response = moderator_client.get(reverse("misago:threads")) assert_contains(response, thread.title) assert_contains(response, "thread-flags") assert_contains(response, "thread-flag-unapproved") def test_category_threads_list_shows_moderators_thread_has_unapproved_posts_flag( default_category, moderator_client ): thread = post_thread(default_category, title="Thread With Unapproved Posts") thread.has_unapproved_posts = True thread.save() response = moderator_client.get(default_category.get_absolute_url()) assert_contains(response, thread.title) assert_contains(response, "thread-flags") assert_contains(response, "thread-flag-unapproved") @override_dynamic_settings(index_view="categories") def test_site_threads_list_doesnt_show_user_thread_has_unapproved_posts_flag( default_category, user_client ): thread = post_thread(default_category, title="Thread With Unapproved Posts") thread.has_unapproved_posts = True thread.save() response = user_client.get(reverse("misago:threads")) assert_contains(response, thread.title) assert_not_contains(response, "thread-flags") assert_not_contains(response, "thread-flag-unapproved") def test_category_threads_list_doesnt_show_user_thread_has_unapproved_posts_flag( default_category, user_client ): thread = post_thread(default_category, title="Thread With Unapproved Posts") thread.has_unapproved_posts = True thread.save() response = user_client.get(default_category.get_absolute_url()) assert_contains(response, thread.title) assert_not_contains(response, "thread-flags") assert_not_contains(response, "thread-flag-unapproved")
7,984
Python
.py
162
45.024691
87
0.765637
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,158
test_thread_editreply_api.py
rafalp_Misago/misago/threads/tests/test_thread_editreply_api.py
from datetime import timedelta from django.test.client import BOUNDARY, MULTIPART_CONTENT, encode_multipart from django.urls import reverse from django.utils import timezone from .. import test from ...acl.test import patch_user_acl from ...categories.models import Category from ...users.test import AuthenticatedUserTestCase from ..models import Post, Thread from ..test import patch_category_acl class EditReplyTests(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.get(slug="first-category") self.thread = test.post_thread(category=self.category) self.post = test.reply_thread(self.thread, poster=self.user) self.api_link = reverse( "misago:api:thread-post-detail", kwargs={"thread_pk": self.thread.pk, "pk": self.post.pk}, ) def put(self, url, data=None): content = encode_multipart(BOUNDARY, data or {}) return self.client.put(url, content, content_type=MULTIPART_CONTENT) def test_cant_edit_reply_as_guest(self): """user has to be authenticated to be able to edit reply""" self.logout_user() response = self.put(self.api_link) self.assertEqual(response.status_code, 403) def test_thread_visibility(self): """thread's visibility is validated""" with patch_category_acl({"can_see": False}): response = self.put(self.api_link) self.assertEqual(response.status_code, 404) with patch_category_acl({"can_browse": False}): response = self.put(self.api_link) self.assertEqual(response.status_code, 404) with patch_category_acl({"can_see_all_threads": False}): response = self.put(self.api_link) self.assertEqual(response.status_code, 404) @patch_category_acl({"can_edit_posts": 0}) def test_cant_edit_reply(self): """permission to edit reply is validated""" response = self.put(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't edit posts in this category."} ) @patch_category_acl({"can_edit_posts": 1}) def test_cant_edit_other_user_reply(self): """permission to edit reply by other users is validated""" self.post.poster = None self.post.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't edit other users posts in this category."}, ) @patch_category_acl({"can_edit_posts": 1, "post_edit_time": 1}) def test_edit_too_old(self): """permission to edit reply within timelimit is validated""" self.post.posted_on = timezone.now() - timedelta(minutes=5) self.post.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't edit posts that are older than 1 minute."}, ) @patch_category_acl({"can_edit_posts": 1, "can_close_threads": False}) def test_closed_category_no_permission(self): """permssion to edit reply in closed category is validated""" self.category.is_closed = True self.category.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This category is closed. You can't edit posts in it."}, ) @patch_category_acl({"can_edit_posts": 1, "can_close_threads": True}) def test_closed_category(self): """permssion to edit reply in closed category is validated""" self.category.is_closed = True self.category.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 400) @patch_category_acl({"can_edit_posts": 1, "can_close_threads": False}) def test_closed_thread_no_permission(self): """permssion to edit reply in closed thread is validated""" self.thread.is_closed = True self.thread.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This thread is closed. You can't edit posts in it."}, ) @patch_category_acl({"can_edit_posts": 1, "can_close_threads": True}) def test_closed_thread(self): """permssion to edit reply in closed thread is validated""" self.thread.is_closed = True self.thread.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 400) @patch_category_acl({"can_edit_posts": 1, "can_protect_posts": False}) def test_protected_post_no_permission(self): """permssion to edit protected post is validated""" self.post.is_protected = True self.post.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This post is protected. You can't edit it."} ) @patch_category_acl({"can_edit_posts": 1, "can_protect_posts": True}) def test_protected_post_no(self): """permssion to edit protected post is validated""" self.post.is_protected = True self.post.save() response = self.put(self.api_link) self.assertEqual(response.status_code, 400) @patch_category_acl({"can_edit_posts": 1}) def test_empty_data(self): """no data sent handling has no showstoppers""" response = self.put(self.api_link, data={}) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"post": ["You have to enter a message."]}) @patch_category_acl({"can_edit_posts": 1}) def test_invalid_data(self): """api errors for invalid request data""" response = self.client.put( self.api_link, "false", content_type="application/json" ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "non_field_errors": [ "Invalid data. Expected a dictionary, but got bool." ] }, ) @patch_category_acl({"can_edit_posts": 1}) def test_edit_event(self): """events can't be edited""" self.post.is_event = True self.post.save() response = self.put(self.api_link, data={}) self.assertEqual(response.status_code, 403) self.assertEqual(response.json(), {"detail": "Events can't be edited."}) @patch_category_acl({"can_edit_posts": 1}) def test_post_is_validated(self): """post is validated""" response = self.put(self.api_link, data={"post": "a"}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "post": [ "Posted message should be at least 5 characters long (it has 1)." ] }, ) @patch_category_acl({"can_edit_posts": 1}) def test_edit_reply_no_change(self): """endpoint isn't bumping edits count if no change was made to post's body""" self.assertEqual(self.post.edits_record.count(), 0) response = self.put(self.api_link, data={"post": self.post.original}) self.assertEqual(response.status_code, 200) response = self.client.get(self.thread.get_absolute_url()) self.assertContains(response, self.post.parsed) post = self.thread.post_set.order_by("id").last() self.assertEqual(post.edits, 0) self.assertEqual(post.original, self.post.original) self.assertIsNone(post.last_editor_id, self.user.id) self.assertIsNone(post.last_editor_name, self.user.username) self.assertIsNone(post.last_editor_slug, self.user.slug) self.assertEqual(self.post.edits_record.count(), 0) @patch_category_acl({"can_edit_posts": 1}) def test_edit_reply(self): """endpoint updates reply""" self.assertEqual(self.post.edits_record.count(), 0) response = self.put(self.api_link, data={"post": "This is test edit!"}) self.assertEqual(response.status_code, 200) response = self.client.get(self.thread.get_absolute_url()) self.assertContains(response, "<p>This is test edit!</p>") self.assertEqual(self.user.audittrail_set.count(), 1) post = self.thread.post_set.order_by("id").last() self.assertEqual(post.edits, 1) self.assertEqual(post.original, "This is test edit!") self.assertEqual(post.last_editor_id, self.user.id) self.assertEqual(post.last_editor_name, self.user.username) self.assertEqual(post.last_editor_slug, self.user.slug) self.assertEqual(self.post.edits_record.count(), 1) post_edit = post.edits_record.last() self.assertEqual(post_edit.edited_from, self.post.original) self.assertEqual(post_edit.edited_to, post.original) self.assertEqual(post_edit.editor_id, self.user.id) self.assertEqual(post_edit.editor_name, self.user.username) self.assertEqual(post_edit.editor_slug, self.user.slug) @patch_category_acl({"can_edit_posts": 2, "can_hide_threads": 1}) def test_edit_first_post_hidden(self): """endpoint updates hidden thread's first post""" self.thread.is_hidden = True self.thread.save() self.thread.first_post.is_hidden = True self.thread.first_post.save() api_link = reverse( "misago:api:thread-post-detail", kwargs={"thread_pk": self.thread.pk, "pk": self.thread.first_post.pk}, ) response = self.put(api_link, data={"post": "This is test edit!"}) self.assertEqual(response.status_code, 200) @patch_category_acl({"can_edit_posts": 1, "can_protect_posts": True}) def test_protect_post(self): """can protect post""" response = self.put( self.api_link, data={"post": "Lorem ipsum dolor met!", "protect": 1} ) self.assertEqual(response.status_code, 200) post = self.user.post_set.order_by("id").last() self.assertTrue(post.is_protected) @patch_category_acl({"can_edit_posts": 1, "can_protect_posts": False}) def test_protect_post_no_permission(self): """cant protect post without permission""" response = self.put( self.api_link, data={"post": "Lorem ipsum dolor met!", "protect": 1} ) self.assertEqual(response.status_code, 200) post = self.user.post_set.order_by("id").last() self.assertFalse(post.is_protected) @patch_category_acl({"can_edit_posts": 1}) def test_post_unicode(self): """unicode characters can be posted""" response = self.put( self.api_link, data={"post": "Chrzążczyżewoszyce, powiat Łękółody."} ) self.assertEqual(response.status_code, 200) @patch_category_acl({"can_edit_posts": 1}) def test_reply_category_moderation_queue(self): """edit sends reply to queue due to category setup""" self.category.require_edits_approval = True self.category.save() response = self.put(self.api_link, data={"post": "Lorem ipsum dolor met!"}) self.assertEqual(response.status_code, 200) post = self.user.post_set.all()[:1][0] self.assertTrue(post.is_unapproved) @patch_category_acl({"can_edit_posts": 1}) @patch_user_acl({"can_approve_content": True}) def test_reply_category_moderation_queue_bypass(self): """bypass moderation queue due to user's acl""" self.category.require_edits_approval = True self.category.save() response = self.put(self.api_link, data={"post": "Lorem ipsum dolor met!"}) self.assertEqual(response.status_code, 200) post = self.user.post_set.all()[:1][0] self.assertFalse(post.is_unapproved) @patch_category_acl({"can_edit_posts": 1, "require_edits_approval": True}) def test_reply_user_moderation_queue(self): """edit sends reply to queue due to user acl""" response = self.put(self.api_link, data={"post": "Lorem ipsum dolor met!"}) self.assertEqual(response.status_code, 200) post = self.user.post_set.all()[:1][0] self.assertTrue(post.is_unapproved) @patch_category_acl({"can_edit_posts": 1, "require_edits_approval": True}) @patch_user_acl({"can_approve_content": True}) def test_reply_user_moderation_queue_bypass(self): """bypass moderation queue due to user's acl""" response = self.put(self.api_link, data={"post": "Lorem ipsum dolor met!"}) self.assertEqual(response.status_code, 200) post = self.user.post_set.all()[:1][0] self.assertFalse(post.is_unapproved) @patch_category_acl( { "can_edit_posts": 1, "require_threads_approval": True, "require_replies_approval": True, } ) def test_reply_omit_other_moderation_queues(self): """other queues are omitted""" self.category.require_threads_approval = True self.category.require_replies_approval = True self.category.save() response = self.put(self.api_link, data={"post": "Lorem ipsum dolor met!"}) self.assertEqual(response.status_code, 200) post = self.user.post_set.all()[:1][0] self.assertFalse(post.is_unapproved) def setUpFirstReplyTest(self): self.post = self.thread.first_post self.post.poster = self.user self.post.save() self.api_link = reverse( "misago:api:thread-post-detail", kwargs={"thread_pk": self.thread.pk, "pk": self.post.pk}, ) @patch_category_acl({"can_edit_posts": 1}) def test_first_reply_category_moderation_queue(self): """edit sends thread to queue due to category setup""" self.setUpFirstReplyTest() self.category.require_edits_approval = True self.category.save() response = self.put(self.api_link, data={"post": "Lorem ipsum dolor met!"}) self.assertEqual(response.status_code, 200) thread = Thread.objects.get(pk=self.thread.pk) self.assertTrue(thread.is_unapproved) self.assertTrue(thread.has_unapproved_posts) post = Post.objects.get(pk=self.post.pk) self.assertTrue(post.is_unapproved) @patch_category_acl({"can_edit_posts": 1}) @patch_user_acl({"can_approve_content": True}) def test_first_reply_category_moderation_queue_bypass(self): """bypass moderation queue due to user's acl""" self.setUpFirstReplyTest() self.category.require_edits_approval = True self.category.save() response = self.put(self.api_link, data={"post": "Lorem ipsum dolor met!"}) self.assertEqual(response.status_code, 200) thread = Thread.objects.get(pk=self.thread.pk) self.assertFalse(thread.is_unapproved) self.assertFalse(thread.has_unapproved_posts) post = Post.objects.get(pk=self.post.pk) self.assertFalse(post.is_unapproved) @patch_category_acl({"can_edit_posts": 1, "require_edits_approval": True}) def test_first_reply_user_moderation_queue(self): """edit sends thread to queue due to user acl""" self.setUpFirstReplyTest() response = self.put(self.api_link, data={"post": "Lorem ipsum dolor met!"}) self.assertEqual(response.status_code, 200) thread = Thread.objects.get(pk=self.thread.pk) self.assertTrue(thread.is_unapproved) self.assertTrue(thread.has_unapproved_posts) post = Post.objects.get(pk=self.post.pk) self.assertTrue(post.is_unapproved) @patch_category_acl({"can_edit_posts": 1, "require_edits_approval": True}) @patch_user_acl({"can_approve_content": True}) def test_first_reply_user_moderation_queue_bypass(self): """bypass moderation queue due to user's acl""" self.setUpFirstReplyTest() response = self.put(self.api_link, data={"post": "Lorem ipsum dolor met!"}) self.assertEqual(response.status_code, 200) thread = Thread.objects.get(pk=self.thread.pk) self.assertFalse(thread.is_unapproved) self.assertFalse(thread.has_unapproved_posts) post = Post.objects.get(pk=self.post.pk) self.assertFalse(post.is_unapproved) @patch_category_acl( { "can_edit_posts": 1, "require_threads_approval": True, "require_replies_approval": True, } ) def test_first_reply_omit_other_moderation_queues(self): """other queues are omitted""" self.setUpFirstReplyTest() self.category.require_threads_approval = True self.category.require_replies_approval = True self.category.save() response = self.put(self.api_link, data={"post": "Lorem ipsum dolor met!"}) self.assertEqual(response.status_code, 200) thread = Thread.objects.get(pk=self.thread.pk) self.assertFalse(thread.is_unapproved) self.assertFalse(thread.has_unapproved_posts) post = Post.objects.get(pk=self.post.pk) self.assertFalse(post.is_unapproved)
17,604
Python
.py
367
39.117166
85
0.641865
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,159
test_watch_started_thread.py
rafalp_Misago/misago/threads/tests/test_watch_started_thread.py
from django.urls import reverse from ...notifications.models import WatchedThread from ...notifications.threads import ThreadNotifications def test_started_thread_is_watched_by_user_with_option_enabled( user, user_client, default_category ): user.watch_started_threads = ThreadNotifications.SITE_ONLY user.save() response = user_client.post( reverse("misago:api:thread-list"), data={ "category": default_category.pk, "title": "Test thread", "post": "Lorem ipsum dolor met", }, ) assert response.status_code == 200 data = response.json() WatchedThread.objects.get( user=user, category=default_category, thread_id=data["id"], send_emails=False, ) def test_started_thread_is_not_watched_by_user_with_option_disabled( user, user_client, default_category ): user.watch_started_threads = ThreadNotifications.NONE user.save() response = user_client.post( reverse("misago:api:thread-list"), data={ "category": default_category.pk, "title": "Test thread", "post": "Lorem ipsum dolor met", }, ) assert response.status_code == 200 assert not WatchedThread.objects.exists() def test_started_private_thread_is_watched_by_user_with_option_enabled( notify_on_new_private_thread_mock, user, user_client, other_user, private_threads_category, ): user.watch_started_threads = ThreadNotifications.SITE_ONLY user.save() response = user_client.post( reverse("misago:api:private-thread-list"), data={ "to": [other_user.username], "title": "Test thread", "post": "Lorem ipsum dolor met", }, ) assert response.status_code == 200 data = response.json() WatchedThread.objects.get( user=user, category=private_threads_category, thread_id=data["id"], send_emails=False, ) def test_started_private_thread_is_not_watched_by_user_with_option_disabled( notify_on_new_private_thread_mock, user, user_client, other_user ): user.watch_started_threads = ThreadNotifications.NONE user.save() response = user_client.post( reverse("misago:api:private-thread-list"), data={ "to": [other_user.username], "title": "Test thread", "post": "Lorem ipsum dolor met", }, ) assert response.status_code == 200 assert not WatchedThread.objects.exists()
2,571
Python
.py
79
25.607595
76
0.645488
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,160
test_thread_poll_api.py
rafalp_Misago/misago/threads/tests/test_thread_poll_api.py
import json from django.urls import reverse from .. import test from ...categories.models import Category from ...users.test import AuthenticatedUserTestCase class ThreadPollApiTestCase(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.category = Category.objects.get(slug="first-category") self.thread = test.post_thread(self.category, poster=self.user) self.api_link = reverse( "misago:api:thread-poll-list", kwargs={"thread_pk": self.thread.pk} ) def post(self, url, data=None): return self.client.post( url, json.dumps(data or {}), content_type="application/json" ) def put(self, url, data=None): return self.client.put( url, json.dumps(data or {}), content_type="application/json" ) def mock_poll(self): self.poll = self.thread.poll = test.post_poll(self.thread, self.user) self.api_link = reverse( "misago:api:thread-poll-detail", kwargs={"thread_pk": self.thread.pk, "pk": self.poll.pk}, )
1,095
Python
.py
27
32.814815
79
0.646503
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,161
test_threads_lists_start_thread.py
rafalp_Misago/misago/threads/tests/test_threads_lists_start_thread.py
from django.urls import reverse from ...conf.test import override_dynamic_settings from ...permissions.enums import CategoryPermission from ...permissions.models import CategoryGroupPermission from ...test import assert_contains, assert_not_contains @override_dynamic_settings(index_view="categories") def test_threads_list_displays_start_thread_button_to_guest_with_permission( guests_group, client, default_category ): response = client.get(reverse("misago:threads")) assert_contains(response, reverse("misago:start-thread")) @override_dynamic_settings(index_view="categories") def test_threads_list_displays_start_thread_button_to_user_with_permission(user_client): response = user_client.get(reverse("misago:threads")) assert_contains(response, reverse("misago:start-thread")) def test_category_threads_list_displays_start_thread_button_to_guest_with_permission( guests_group, client, default_category ): response = client.get( reverse( "misago:category", kwargs={"id": default_category.id, "slug": default_category.slug}, ) ) assert_contains(response, reverse("misago:start-thread")) def test_category_threads_list_displays_start_thread_button_to_user_with_permission( user_client, default_category ): response = user_client.get( reverse( "misago:category", kwargs={"id": default_category.id, "slug": default_category.slug}, ) ) assert_contains(response, reverse("misago:start-thread")) def test_private_threads_list_displays_start_thread_button_to_user_with_permission( user_client, ): response = user_client.get(reverse("misago:private-threads")) assert_contains(response, reverse("misago:start-private-thread")) @override_dynamic_settings(index_view="categories") def test_threads_list_hides_start_thread_button_from_guest_without_permission( client, guests_group ): CategoryGroupPermission.objects.filter( group=guests_group, permission=CategoryPermission.START, ).delete() response = client.get(reverse("misago:threads")) assert_not_contains(response, reverse("misago:start-thread")) @override_dynamic_settings(index_view="categories") def test_threads_list_hides_start_thread_button_from_user_without_permission( user, user_client ): CategoryGroupPermission.objects.filter( group=user.group, permission=CategoryPermission.START, ).delete() response = user_client.get(reverse("misago:threads")) assert_not_contains(response, reverse("misago:start-thread")) def test_category_threads_list_hides_start_thread_button_from_guest_without_permission( client, guests_group, default_category ): CategoryGroupPermission.objects.filter( group=guests_group, permission=CategoryPermission.START, ).delete() response = client.get( reverse( "misago:category", kwargs={"id": default_category.id, "slug": default_category.slug}, ) ) assert_not_contains(response, reverse("misago:start-thread")) def test_category_threads_list_hides_start_thread_button_from_user_without_permission( user, user_client, default_category ): CategoryGroupPermission.objects.filter( group=user.group, permission=CategoryPermission.START, ).delete() response = user_client.get( reverse( "misago:category", kwargs={"id": default_category.id, "slug": default_category.slug}, ) ) assert_not_contains(response, reverse("misago:start-thread")) def test_private_threads_list_hides_start_thread_button_from_user_without_permission( user, user_client ): user.group.can_start_private_threads = False user.group.save() response = user_client.get(reverse("misago:private-threads")) assert_not_contains(response, reverse("misago:start-private-thread")) def test_closed_category_threads_list_hides_start_thread_button_from_user_without_permission( user_client, default_category ): default_category.is_closed = True default_category.save() response = user_client.get( reverse( "misago:category", kwargs={"id": default_category.id, "slug": default_category.slug}, ) ) assert_not_contains(response, reverse("misago:start-thread")) def test_closed_category_threads_list_shows_start_thread_button_to_user_with_permission( user, user_client, default_category, members_group, moderators_group ): default_category.is_closed = True default_category.save() user.set_groups(members_group, [moderators_group]) user.save() response = user_client.get( reverse( "misago:category", kwargs={"id": default_category.id, "slug": default_category.slug}, ) ) assert_contains(response, reverse("misago:start-thread"))
4,918
Python
.py
121
34.975207
93
0.720193
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,162
test_thread_merge_api.py
rafalp_Misago/misago/threads/tests/test_thread_merge_api.py
from unittest.mock import patch import pytest from django.urls import reverse from ...notifications.models import Notification from .. import test from ...categories.models import Category from ..models import Poll, PollVote, Thread from ..test import patch_category_acl, patch_other_category_acl from .test_threads_api import ThreadsApiTestCase class ThreadMergeApiTests(ThreadsApiTestCase): def setUp(self): super().setUp() Category(name="Other Category", slug="other-category").insert_at( self.category, position="last-child", save=True ) self.other_category = Category.objects.get(slug="other-category") self.api_link = reverse( "misago:api:thread-merge", kwargs={"pk": self.thread.pk} ) @patch_category_acl({"can_merge_threads": False}) def test_merge_no_permission(self): """api validates if thread can be merged with other one""" response = self.client.post(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't merge threads in this category."} ) @patch_category_acl({"can_merge_threads": True}) def test_merge_no_url(self): """api validates if thread url was given""" response = self.client.post(self.api_link) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"detail": "Enter link to new thread."}) @patch_category_acl({"can_merge_threads": True}) def test_invalid_url(self): """api validates thread url""" response = self.client.post( self.api_link, {"other_thread": self.user.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "This is not a valid thread link."} ) @patch_category_acl({"can_merge_threads": True}) def test_current_other_thread(self): """api validates if thread url given is to current thread""" response = self.client.post( self.api_link, {"other_thread": self.thread.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You can't merge thread with itself."} ) @patch_other_category_acl() @patch_category_acl({"can_merge_threads": True}) def test_other_thread_exists(self): """api validates if other thread exists""" other_thread = test.post_thread(self.other_category) other_other_thread = other_thread.get_absolute_url() other_thread.delete() response = self.client.post(self.api_link, {"other_thread": other_other_thread}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "detail": ( "The thread you have entered link to doesn't exist " "or you don't have permission to see it." ) }, ) @patch_other_category_acl({"can_see": False}) @patch_category_acl({"can_merge_threads": True}) def test_other_thread_is_invisible(self): """api validates if other thread is visible""" other_thread = test.post_thread(self.other_category) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "detail": ( "The thread you have entered link to doesn't exist " "or you don't have permission to see it." ) }, ) @patch_other_category_acl({"can_merge_threads": False}) @patch_category_acl({"can_merge_threads": True}) def test_other_thread_is_not_mergeable(self): """api validates if other thread can be merged""" other_thread = test.post_thread(self.other_category) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Other thread can't be merged with."} ) @patch_other_category_acl({"can_merge_threads": True, "can_close_threads": False}) @patch_category_acl({"can_merge_threads": True}) def test_thread_category_is_closed(self): """api validates if thread's category is open""" other_thread = test.post_thread(self.other_category) self.category.is_closed = True self.category.save() response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This category is closed. You can't merge it's threads."}, ) @patch_other_category_acl({"can_merge_threads": True, "can_close_threads": False}) @patch_category_acl({"can_merge_threads": True}) def test_thread_is_closed(self): """api validates if thread is open""" other_thread = test.post_thread(self.other_category) self.thread.is_closed = True self.thread.save() response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "This thread is closed. You can't merge it with other threads."}, ) @patch_other_category_acl({"can_merge_threads": True, "can_close_threads": False}) @patch_category_acl({"can_merge_threads": True}) def test_other_thread_category_is_closed(self): """api validates if other thread's category is open""" other_thread = test.post_thread(self.other_category) self.other_category.is_closed = True self.other_category.save() response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Other thread's category is closed. You can't merge with it."}, ) @patch_other_category_acl({"can_merge_threads": True, "can_close_threads": False}) @patch_category_acl({"can_merge_threads": True}) def test_other_thread_is_closed(self): """api validates if other thread is open""" other_thread = test.post_thread(self.other_category) other_thread.is_closed = True other_thread.save() response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "Other thread is closed and can't be merged with."}, ) @patch_other_category_acl({"can_merge_threads": True, "can_reply_threads": False}) @patch_category_acl({"can_merge_threads": True}) def test_other_thread_isnt_replyable(self): """api validates if other thread can be replied, which is condition for merge""" other_thread = test.post_thread(self.other_category) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"detail": "You can't merge this thread into thread you can't reply."}, ) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_merge_threads(self, delete_duplicate_watched_threads_mock): """api merges two threads successfully""" other_thread = test.post_thread(self.other_category) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # other thread has two posts and an event now self.assertEqual(other_thread.post_set.count(), 3) # first thread is gone with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_merge_threads_kept_reads(self, delete_duplicate_watched_threads_mock): """api keeps both threads readtrackers after merge""" other_thread = test.post_thread(self.other_category) poststracker.save_read(self.user, self.thread.first_post) poststracker.save_read(self.user, other_thread.first_post) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # posts reads are kept postreads = self.user.postread_set.filter(post__is_event=False).order_by("id") self.assertEqual( list(postreads.values_list("post_id", flat=True)), [self.thread.first_post_id, other_thread.first_post_id], ) self.assertEqual(postreads.filter(thread=other_thread).count(), 2) self.assertEqual(postreads.filter(category=self.other_category).count(), 2) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_merge_threads_kept_subs(self, delete_duplicate_watched_threads_mock): """api keeps other thread's subscription after merge""" other_thread = test.post_thread(self.other_category) self.user.subscription_set.create( thread=self.thread, category=self.thread.category, last_read_on=self.thread.last_post_on, send_email=False, ) self.assertEqual(self.user.subscription_set.count(), 1) self.user.subscription_set.get(thread=self.thread) self.user.subscription_set.get(category=self.category) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # subscriptions are kept self.assertEqual(self.user.subscription_set.count(), 1) self.user.subscription_set.get(thread=other_thread) self.user.subscription_set.get(category=self.other_category) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_merge_threads_moved_subs(self, delete_duplicate_watched_threads_mock): """api keeps other thread's subscription after merge""" other_thread = test.post_thread(self.other_category) self.user.subscription_set.create( thread=other_thread, category=other_thread.category, last_read_on=other_thread.last_post_on, send_email=False, ) self.assertEqual(self.user.subscription_set.count(), 1) self.user.subscription_set.get(thread=other_thread) self.user.subscription_set.get(category=self.other_category) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # subscriptions are kept self.assertEqual(self.user.subscription_set.count(), 1) self.user.subscription_set.get(thread=other_thread) self.user.subscription_set.get(category=self.other_category) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_merge_threads_handle_subs_conflict( self, delete_duplicate_watched_threads_mock ): """api resolves conflicting thread subscriptions after merge""" self.user.subscription_set.create( thread=self.thread, category=self.thread.category, last_read_on=self.thread.last_post_on, send_email=False, ) other_thread = test.post_thread(self.other_category) self.user.subscription_set.create( thread=other_thread, category=other_thread.category, last_read_on=other_thread.last_post_on, send_email=False, ) self.assertEqual(self.user.subscription_set.count(), 2) self.user.subscription_set.get(thread=self.thread) self.user.subscription_set.get(category=self.category) self.user.subscription_set.get(thread=other_thread) self.user.subscription_set.get(category=self.other_category) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # subscriptions are kept self.assertEqual(self.user.subscription_set.count(), 1) self.user.subscription_set.get(thread=other_thread) self.user.subscription_set.get(category=self.other_category) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_merge_threads_kept_best_answer( self, delete_duplicate_watched_threads_mock ): """api merges two threads successfully, keeping best answer from old thread""" other_thread = test.post_thread(self.other_category) best_answer = test.reply_thread(other_thread) other_thread.set_best_answer(self.user, best_answer) other_thread.save() response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # other thread has three posts and an event now self.assertEqual(other_thread.post_set.count(), 4) # first thread is gone with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk) # best answer is kept in other thread other_thread = Thread.objects.get(pk=other_thread.pk) self.assertEqual(other_thread.best_answer, best_answer) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_merge_threads_moved_best_answer( self, delete_duplicate_watched_threads_mock ): """api merges two threads successfully, moving best answer to old thread""" other_thread = test.post_thread(self.other_category) best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.save() response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # other thread has three posts and an event now self.assertEqual(other_thread.post_set.count(), 4) # first thread is gone with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk) # best answer is kept in other thread other_thread = Thread.objects.get(pk=other_thread.pk) self.assertEqual(other_thread.best_answer, best_answer) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) def test_merge_threads_merge_conflict_best_answer(self): """api errors on merge conflict, returning list of available best answers""" best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.save() other_thread = test.post_thread(self.other_category) other_best_answer = test.reply_thread(other_thread) other_thread.set_best_answer(self.user, other_best_answer) other_thread.save() response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "best_answers": [ ["0", "Unmark all best answers"], [str(self.thread.id), self.thread.title], [str(other_thread.id), other_thread.title], ] }, ) # best answers were untouched self.assertEqual(self.thread.post_set.count(), 2) self.assertEqual(other_thread.post_set.count(), 2) self.assertEqual( Thread.objects.get(pk=self.thread.pk).best_answer_id, best_answer.id ) self.assertEqual( Thread.objects.get(pk=other_thread.pk).best_answer_id, other_best_answer.id ) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) def test_threads_merge_conflict_best_answer_invalid_resolution(self): """api errors on invalid merge conflict resolution""" best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.save() other_thread = test.post_thread(self.other_category) other_best_answer = test.reply_thread(other_thread) other_thread.set_best_answer(self.user, other_best_answer) other_thread.save() response = self.client.post( self.api_link, { "other_thread": other_thread.get_absolute_url(), "best_answer": other_thread.id + 10, }, ) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"detail": "Invalid choice."}) # best answers were untouched self.assertEqual(self.thread.post_set.count(), 2) self.assertEqual(other_thread.post_set.count(), 2) self.assertEqual( Thread.objects.get(pk=self.thread.pk).best_answer_id, best_answer.id ) self.assertEqual( Thread.objects.get(pk=other_thread.pk).best_answer_id, other_best_answer.id ) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_threads_merge_conflict_unmark_all_best_answers( self, delete_duplicate_watched_threads_mock ): """api unmarks all best answers when unmark all choice is selected""" best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.save() other_thread = test.post_thread(self.other_category) other_best_answer = test.reply_thread(other_thread) other_thread.set_best_answer(self.user, other_best_answer) other_thread.save() response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url(), "best_answer": 0}, ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # other thread has four posts and an event now self.assertEqual(other_thread.post_set.count(), 5) # first thread is gone with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk) # final thread has no marked best answer self.assertIsNone(Thread.objects.get(pk=other_thread.pk).best_answer_id) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_threads_merge_conflict_keep_first_best_answer( self, delete_duplicate_watched_threads_mock ): """api unmarks other best answer on merge""" best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.save() other_thread = test.post_thread(self.other_category) other_best_answer = test.reply_thread(other_thread) other_thread.set_best_answer(self.user, other_best_answer) other_thread.save() response = self.client.post( self.api_link, { "other_thread": other_thread.get_absolute_url(), "best_answer": self.thread.pk, }, ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # other thread has four posts and an event now self.assertEqual(other_thread.post_set.count(), 5) # first thread is gone with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk) # other thread's best answer was unchanged self.assertEqual( Thread.objects.get(pk=other_thread.pk).best_answer_id, best_answer.id ) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_threads_merge_conflict_keep_other_best_answer( self, delete_duplicate_watched_threads_mock ): """api unmarks first best answer on merge""" best_answer = test.reply_thread(self.thread) self.thread.set_best_answer(self.user, best_answer) self.thread.save() other_thread = test.post_thread(self.other_category) other_best_answer = test.reply_thread(other_thread) other_thread.set_best_answer(self.user, other_best_answer) other_thread.save() response = self.client.post( self.api_link, { "other_thread": other_thread.get_absolute_url(), "best_answer": other_thread.pk, }, ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # other thread has four posts and an event now self.assertEqual(other_thread.post_set.count(), 5) # first thread is gone with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk) # other thread's best answer was changed to merged in thread's answer self.assertEqual( Thread.objects.get(pk=other_thread.pk).best_answer_id, other_best_answer.id ) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_merge_threads_kept_poll(self, delete_duplicate_watched_threads_mock): """api merges two threads successfully, keeping poll from other thread""" other_thread = test.post_thread(self.other_category) poll = test.post_poll(other_thread, self.user) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # other thread has two posts and an event now self.assertEqual(other_thread.post_set.count(), 3) # first thread is gone with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk) # poll and its votes were kept self.assertEqual( Poll.objects.filter(pk=poll.pk, thread=other_thread).count(), 1 ) self.assertEqual( PollVote.objects.filter(poll=poll, thread=other_thread).count(), 4 ) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_merge_threads_moved_poll(self, delete_duplicate_watched_threads_mock): """api merges two threads successfully, moving poll from old thread""" other_thread = test.post_thread(self.other_category) poll = test.post_poll(self.thread, self.user) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # other thread has two posts and an event now self.assertEqual(other_thread.post_set.count(), 3) # first thread is gone with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk) # poll and its votes were moved self.assertEqual( Poll.objects.filter(pk=poll.pk, thread=other_thread).count(), 1 ) self.assertEqual( PollVote.objects.filter(poll=poll, thread=other_thread).count(), 4 ) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) def test_threads_merge_conflict_polls(self): """api errors on merge conflict, returning list of available polls""" other_thread = test.post_thread(self.other_category) poll = test.post_poll(self.thread, self.user) other_poll = test.post_poll(other_thread, self.user) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url()} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "polls": [ ["0", "Delete all polls"], [str(poll.pk), "%s (%s)" % (poll.question, poll.thread.title)], [ str(other_poll.pk), "%s (%s)" % (other_poll.question, other_poll.thread.title), ], ] }, ) # polls and votes were untouched self.assertEqual(Poll.objects.count(), 2) self.assertEqual(PollVote.objects.count(), 8) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) def test_threads_merge_conflict_poll_invalid_resolution(self): """api errors on invalid merge conflict resolution""" other_thread = test.post_thread(self.other_category) test.post_poll(self.thread, self.user) test.post_poll(other_thread, self.user) response = self.client.post( self.api_link, { "other_thread": other_thread.get_absolute_url(), "poll": Poll.objects.all()[0].pk + 10, }, ) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), {"detail": "Invalid choice."}) # polls and votes were untouched self.assertEqual(Poll.objects.count(), 2) self.assertEqual(PollVote.objects.count(), 8) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_threads_merge_conflict_delete_all_polls( self, delete_duplicate_watched_threads_mock ): """api deletes all polls when delete all choice is selected""" other_thread = test.post_thread(self.other_category) test.post_poll(self.thread, self.user) test.post_poll(other_thread, self.user) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url(), "poll": 0} ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # other thread has two posts and an event now self.assertEqual(other_thread.post_set.count(), 3) # first thread is gone with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk) # polls and votes are gone self.assertEqual(Poll.objects.count(), 0) self.assertEqual(PollVote.objects.count(), 0) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_threads_merge_conflict_keep_first_poll( self, delete_duplicate_watched_threads_mock ): """api deletes other poll on merge""" other_thread = test.post_thread(self.other_category) poll = test.post_poll(self.thread, self.user) other_poll = test.post_poll(other_thread, self.user) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url(), "poll": poll.pk}, ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # other thread has two posts and an event now self.assertEqual(other_thread.post_set.count(), 3) # first thread is gone with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk) # other poll and its votes are gone self.assertEqual(Poll.objects.filter(thread=self.thread).count(), 0) self.assertEqual(PollVote.objects.filter(thread=self.thread).count(), 0) self.assertEqual(Poll.objects.filter(thread=other_thread).count(), 1) self.assertEqual(PollVote.objects.filter(thread=other_thread).count(), 4) Poll.objects.get(pk=poll.pk) with self.assertRaises(Poll.DoesNotExist): Poll.objects.get(pk=other_poll.pk) @patch_other_category_acl({"can_merge_threads": True}) @patch_category_acl({"can_merge_threads": True}) @patch("misago.threads.moderation.threads.delete_duplicate_watched_threads") def test_threads_merge_conflict_keep_other_poll( self, delete_duplicate_watched_threads_mock ): """api deletes first poll on merge""" other_thread = test.post_thread(self.other_category) poll = test.post_poll(self.thread, self.user) other_poll = test.post_poll(other_thread, self.user) response = self.client.post( self.api_link, {"other_thread": other_thread.get_absolute_url(), "poll": other_poll.pk}, ) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "id": other_thread.id, "title": other_thread.title, "url": other_thread.get_absolute_url(), }, ) # other thread has two posts and an event now self.assertEqual(other_thread.post_set.count(), 3) # first thread is gone with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk) # other poll and its votes are gone self.assertEqual(Poll.objects.filter(thread=self.thread).count(), 0) self.assertEqual(PollVote.objects.filter(thread=self.thread).count(), 0) self.assertEqual(Poll.objects.filter(thread=other_thread).count(), 1) self.assertEqual(PollVote.objects.filter(thread=other_thread).count(), 4) Poll.objects.get(pk=other_poll.pk) with self.assertRaises(Poll.DoesNotExist): Poll.objects.get(pk=poll.pk) @pytest.fixture def delete_duplicate_watched_threads_mock(mocker): return mocker.patch( "misago.threads.moderation.threads.delete_duplicate_watched_threads" ) @patch_category_acl({"can_merge_threads": True}) def test_thread_merge_api_merges_notifications( delete_duplicate_watched_threads_mock, user, user_client, thread, other_thread, ): notification = Notification.objects.create( user=user, verb="TEST", category=other_thread.category, thread=other_thread, thread_title=other_thread.title, post=other_thread.first_post, ) response = user_client.post( reverse("misago:api:thread-merge", kwargs={"pk": thread.pk}), json={ "other_thread": other_thread.get_absolute_url(), }, ) assert response.status_code == 200 notification.refresh_from_db() assert notification.category_id == other_thread.category_id assert notification.thread_id == other_thread.id assert notification.thread_title == other_thread.title @patch_category_acl({"can_merge_threads": True}) def test_thread_merge_api_merges_watched_threads( delete_duplicate_watched_threads_mock, user, user_client, thread, other_thread, watched_thread_factory, ): watched_thread = watched_thread_factory(user, thread, send_emails=True) response = user_client.post( reverse("misago:api:thread-merge", kwargs={"pk": thread.pk}), json={ "other_thread": other_thread.get_absolute_url(), }, ) assert response.status_code == 200 watched_thread.refresh_from_db() assert watched_thread.category_id == other_thread.category_id assert watched_thread.thread_id == other_thread.id delete_duplicate_watched_threads_mock.delay.assert_called_once_with(other_thread.id)
37,105
Python
.py
828
34.97343
88
0.625367
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,163
test_threads_api.py
rafalp_Misago/misago/threads/tests/test_threads_api.py
from datetime import timedelta from django.utils import timezone from .. import test from ...categories import THREADS_ROOT_NAME from ...categories.models import Category from ...users.test import AuthenticatedUserTestCase from ..models import Thread from ..test import patch_category_acl from ..threadtypes import trees_map class ThreadsApiTestCase(AuthenticatedUserTestCase): def setUp(self): super().setUp() threads_tree_id = trees_map.get_tree_id_for_root(THREADS_ROOT_NAME) self.root = Category.objects.get(tree_id=threads_tree_id, level=0) self.category = Category.objects.get(slug="first-category") self.thread = test.post_thread(category=self.category) self.api_link = self.thread.get_api_url() def get_thread_json(self): response = self.client.get(self.thread.get_api_url()) self.assertEqual(response.status_code, 200) return response.json() class ThreadRetrieveApiTests(ThreadsApiTestCase): def setUp(self): super().setUp() self.tested_links = [ self.api_link, "%sposts/" % self.api_link, "%sposts/?page=1" % self.api_link, ] @patch_category_acl() def test_api_returns_thread(self): """api has no showstoppers""" for link in self.tested_links: response = self.client.get(link) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["id"], self.thread.pk) self.assertEqual(response_json["title"], self.thread.title) if "posts" in link: self.assertIn("post_set", response_json) @patch_category_acl({"can_see_all_threads": False}) def test_api_shows_owned_thread(self): """api handles "owned threads only""" for link in self.tested_links: response = self.client.get(link) self.assertEqual(response.status_code, 404) self.thread.starter = self.user self.thread.save() for link in self.tested_links: response = self.client.get(link) self.assertEqual(response.status_code, 200) @patch_category_acl({"can_see": False}) def test_api_validates_category_see_permission(self): """api validates category visiblity""" for link in self.tested_links: response = self.client.get(link) self.assertEqual(response.status_code, 404) @patch_category_acl({"can_browse": False}) def test_api_validates_category_browse_permission(self): """api validates category browsability""" for link in self.tested_links: response = self.client.get(link) self.assertEqual(response.status_code, 404) def test_api_validates_posts_visibility(self): """api validates posts visiblity""" hidden_post = test.reply_thread( self.thread, is_hidden=True, message="I'am hidden test message!" ) with patch_category_acl({"can_hide_posts": 0}): response = self.client.get(self.tested_links[1]) self.assertNotContains( response, hidden_post.parsed ) # post's body is hidden # add permission to see hidden posts with patch_category_acl({"can_hide_posts": 1}): response = self.client.get(self.tested_links[1]) self.assertContains( response, hidden_post.parsed ) # hidden post's body is visible with permission # unapproved posts shouldn't show at all unapproved_post = test.reply_thread(self.thread, is_unapproved=True) with patch_category_acl({"can_approve_content": False}): response = self.client.get(self.tested_links[1]) self.assertNotContains(response, unapproved_post.get_absolute_url()) # add permission to see unapproved posts with patch_category_acl({"can_approve_content": True}): response = self.client.get(self.tested_links[1]) self.assertContains(response, unapproved_post.get_absolute_url()) def test_api_validates_has_unapproved_posts_visibility(self): """api checks acl before exposing unapproved flag""" self.thread.has_unapproved_posts = True self.thread.save() with patch_category_acl({"can_approve_content": False}): for link in self.tested_links: response = self.client.get(link) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["id"], self.thread.pk) self.assertEqual(response_json["title"], self.thread.title) self.assertFalse(response_json["has_unapproved_posts"]) with patch_category_acl({"can_approve_content": True}): for link in self.tested_links: response = self.client.get(link) self.assertEqual(response.status_code, 200) response_json = response.json() self.assertEqual(response_json["id"], self.thread.pk) self.assertEqual(response_json["title"], self.thread.title) self.assertTrue(response_json["has_unapproved_posts"]) class ThreadDeleteApiTests(ThreadsApiTestCase): def setUp(self): super().setUp() self.last_thread = test.post_thread(category=self.category) self.api_link = self.last_thread.get_api_url() def test_delete_thread_no_permission(self): """api tests permission to delete threads""" with patch_category_acl({"can_hide_threads": 0}): response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json()["detail"], "You can't delete threads in this category." ) with patch_category_acl({"can_hide_threads": 1}): response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json()["detail"], "You can't delete threads in this category." ) @patch_category_acl({"can_hide_threads": 1, "can_hide_own_threads": 2}) def test_delete_other_user_thread_no_permission(self): """api tests thread owner when deleting own thread""" response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json()["detail"], "You can't delete other users theads in this category.", ) @patch_category_acl( {"can_hide_threads": 2, "can_hide_own_threads": 2, "can_close_threads": False} ) def test_delete_thread_closed_category_no_permission(self): """api tests category's closed state""" self.category.is_closed = True self.category.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json()["detail"], "This category is closed. You can't delete threads in it.", ) @patch_category_acl( {"can_hide_threads": 2, "can_hide_own_threads": 2, "can_close_threads": False} ) def test_delete_thread_closed_no_permission(self): """api tests thread's closed state""" self.last_thread.is_closed = True self.last_thread.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json()["detail"], "This thread is closed. You can't delete it." ) @patch_category_acl( {"can_hide_threads": 1, "can_hide_own_threads": 2, "thread_edit_time": 1} ) def test_delete_owned_thread_no_time(self): """api tests permission to delete owned thread within time limit""" self.last_thread.starter = self.user self.last_thread.started_on = timezone.now() - timedelta(minutes=10) self.last_thread.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json()["detail"], "You can't delete threads that are older than 1 minute.", ) @patch_category_acl({"can_hide_threads": 2}) def test_delete_thread(self): """DELETE to API link with permission deletes thread""" category = Category.objects.get(slug="first-category") self.assertEqual(category.last_thread_id, self.last_thread.pk) response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 200) with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.last_thread.pk) # category was synchronised after deletion category = Category.objects.get(slug="first-category") self.assertEqual(category.last_thread_id, self.thread.pk) # test that last thread's deletion triggers category sync response = self.client.delete(self.thread.get_api_url()) self.assertEqual(response.status_code, 200) with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=self.thread.pk) category = Category.objects.get(slug="first-category") self.assertIsNone(category.last_thread_id) @patch_category_acl( {"can_hide_threads": 1, "can_hide_own_threads": 2, "thread_edit_time": 30} ) def test_delete_owned_thread(self): """api lets owner to delete owned thread within time limit""" self.last_thread.starter = self.user self.last_thread.started_on = timezone.now() - timedelta(minutes=10) self.last_thread.save() response = self.client.delete(self.api_link) self.assertEqual(response.status_code, 200)
9,975
Python
.py
204
39.132353
87
0.643893
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,164
rebuildpostssearch.py
rafalp_Misago/misago/threads/management/commands/rebuildpostssearch.py
import time from django.core.management.base import BaseCommand from ....core.management.progressbar import show_progress from ...models import Post class Command(BaseCommand): help = "Rebuilds posts search" def handle(self, *args, **options): posts_to_reindex = Post.objects.filter(is_event=False).count() if not posts_to_reindex: self.stdout.write("\n\nNo posts were found") else: self.rebuild_posts_search(posts_to_reindex) def rebuild_posts_search(self, posts_to_reindex): self.stdout.write("Rebuilding search for %s posts...\n" % posts_to_reindex) rebuild_count = 0 show_progress(self, rebuild_count, posts_to_reindex) start_time = time.time() queryset = Post.objects.select_related("thread").filter(is_event=False) for post in queryset.iterator(chunk_size=50): if post.id == post.thread.first_post_id: post.set_search_document(post.thread.title) else: post.set_search_document() post.save(update_fields=["search_document"]) post.update_search_vector() post.save(update_fields=["search_vector"]) rebuild_count += 1 show_progress(self, rebuild_count, posts_to_reindex, start_time) self.stdout.write("\n\nRebuild search for %s posts" % rebuild_count)
1,398
Python
.py
29
38.793103
83
0.6507
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,165
clearattachments.py
rafalp_Misago/misago/threads/management/commands/clearattachments.py
import time from datetime import timedelta from django.core.management.base import BaseCommand from django.utils import timezone from ....conf.shortcuts import get_dynamic_settings from ....core.management.progressbar import show_progress from ...models import Attachment class Command(BaseCommand): help = "Deletes attachments not associated with any posts" def handle(self, *args, **options): settings = get_dynamic_settings() cutoff = timezone.now() - timedelta(hours=settings.unused_attachments_lifetime) queryset = Attachment.objects.filter(post__isnull=True, uploaded_on__lt=cutoff) attachments_to_sync = queryset.count() if not attachments_to_sync: self.stdout.write("\n\nNo unused attachments were cleared") else: self.sync_attachments(queryset, attachments_to_sync) def sync_attachments(self, queryset, attachments_to_sync): self.stdout.write("Clearing %s attachments...\n" % attachments_to_sync) cleared_count = 0 show_progress(self, cleared_count, attachments_to_sync) start_time = time.time() for attachment in queryset.iterator(chunk_size=50): attachment.delete() cleared_count += 1 show_progress(self, cleared_count, attachments_to_sync, start_time) self.stdout.write("\n\nCleared %s attachments" % cleared_count)
1,409
Python
.py
28
42.857143
87
0.706871
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,166
updatepostschecksums.py
rafalp_Misago/misago/threads/management/commands/updatepostschecksums.py
import time from django.core.management.base import BaseCommand from ....core.management.progressbar import show_progress from ...checksums import update_post_checksum from ...models import Post class Command(BaseCommand): help = "Updates posts checksums" def handle(self, *args, **options): posts_to_update = Post.objects.filter(is_event=False).count() if not posts_to_update: self.stdout.write("\n\nNo posts were found") else: self.update_posts_checksums(posts_to_update) def update_posts_checksums(self, posts_to_update): self.stdout.write("Updating %s posts checksums...\n" % posts_to_update) updated_count = 0 show_progress(self, updated_count, posts_to_update) start_time = time.time() queryset = Post.objects.filter(is_event=False) for post in queryset.iterator(chunk_size=50): update_post_checksum(post) post.save(update_fields=["checksum"]) updated_count += 1 show_progress(self, updated_count, posts_to_update, start_time) self.stdout.write("\n\nUpdated %s posts checksums" % updated_count)
1,176
Python
.py
25
39.04
79
0.675439
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,167
synchronizethreads.py
rafalp_Misago/misago/threads/management/commands/synchronizethreads.py
import time from django.core.management.base import BaseCommand from ....core.management.progressbar import show_progress from ...models import Thread class Command(BaseCommand): help = "Synchronizes threads" def handle(self, *args, **options): threads_to_sync = Thread.objects.count() if not threads_to_sync: self.stdout.write("\n\nNo threads were found") else: self.sync_threads(threads_to_sync) def sync_threads(self, threads_to_sync): self.stdout.write("Synchronizing %s threads...\n" % threads_to_sync) synchronized_count = 0 show_progress(self, synchronized_count, threads_to_sync) start_time = time.time() for thread in Thread.objects.iterator(chunk_size=50): thread.synchronize() thread.save() synchronized_count += 1 show_progress(self, synchronized_count, threads_to_sync, start_time) self.stdout.write("\n\nSynchronized %s threads" % synchronized_count)
1,032
Python
.py
23
36.608696
80
0.670341
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,168
__init__.py
rafalp_Misago/misago/threads/admin/__init__.py
from django.urls import path from django.utils.translation import pgettext_lazy from .views.attachments import AttachmentsList, DeleteAttachment from .views.attachmenttypes import ( AttachmentTypesList, DeleteAttachmentType, EditAttachmentType, NewAttachmentType, ) class MisagoAdminExtension: def register_urlpatterns(self, urlpatterns): # Attachment urlpatterns.namespace("attachments/", "attachments") urlpatterns.patterns( "attachments", path("", AttachmentsList.as_view(), name="index"), path("<int:page>/", AttachmentsList.as_view(), name="index"), path("delete/<int:pk>/", DeleteAttachment.as_view(), name="delete"), ) # AttachmentType urlpatterns.namespace("attachment-types/", "attachment-types", "settings") urlpatterns.patterns( "settings:attachment-types", path("", AttachmentTypesList.as_view(), name="index"), path("new/", NewAttachmentType.as_view(), name="new"), path("edit/<int:pk>/", EditAttachmentType.as_view(), name="edit"), path("delete/<int:pk>/", DeleteAttachmentType.as_view(), name="delete"), ) def register_navigation_nodes(self, site): site.add_node( name=pgettext_lazy("admin node", "Attachments"), icon="fas fa-paperclip", after="permissions:index", namespace="attachments", ) site.add_node( name=pgettext_lazy("admin node", "Attachment types"), description=pgettext_lazy( "admin node", "Specify what files may be uploaded as part of user posts.", ), parent="settings", namespace="attachment-types", )
1,806
Python
.py
44
31.545455
84
0.619021
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,169
forms.py
rafalp_Misago/misago/threads/admin/forms.py
from django import forms from django.utils.translation import pgettext, pgettext_lazy from ..models import AttachmentType def get_searchable_filetypes(): choices = [(0, pgettext_lazy("admin attachments type filter choice", "All types"))] choices += [(a.id, a.name) for a in AttachmentType.objects.order_by("name")] return choices class FilterAttachmentsForm(forms.Form): uploader = forms.CharField( label=pgettext_lazy("admin attachments filter form", "Uploader name contains"), required=False, ) filename = forms.CharField( label=pgettext_lazy("admin attachments filter form", "Filename contains"), required=False, ) filetype = forms.TypedChoiceField( label=pgettext_lazy("admin attachments filter form", "File type"), coerce=int, choices=get_searchable_filetypes, empty_value=0, required=False, ) is_orphan = forms.ChoiceField( label=pgettext_lazy("admin attachments filter form", "State"), required=False, choices=[ ( "", pgettext_lazy( "admin attachments orphan filter choice", "All", ), ), ( "yes", pgettext_lazy( "admin attachments orphan filter choice", "Only orphaned", ), ), ( "no", pgettext_lazy( "admin attachments orphan filter choice", "Not orphaned", ), ), ], ) def filter_queryset(self, criteria, queryset): if criteria.get("uploader"): queryset = queryset.filter( uploader_slug__contains=criteria["uploader"].lower() ) if criteria.get("filename"): queryset = queryset.filter(filename__icontains=criteria["filename"]) if criteria.get("filetype"): queryset = queryset.filter(filetype_id=criteria["filetype"]) if criteria.get("is_orphan") == "yes": queryset = queryset.filter(post__isnull=True) elif criteria.get("is_orphan") == "no": queryset = queryset.filter(post__isnull=False) return queryset class AttachmentTypeForm(forms.ModelForm): class Meta: model = AttachmentType fields = [ "name", "extensions", "mimetypes", "size_limit", "status", "limit_uploads_to", "limit_downloads_to", ] labels = { "name": pgettext_lazy("admin attachment type form", "Type name"), "extensions": pgettext_lazy( "admin attachment type form", "File extensions" ), "mimetypes": pgettext_lazy("admin attachment type form", "Mimetypes"), "size_limit": pgettext_lazy( "admin attachment type form", "Maximum allowed uploaded file size" ), "status": pgettext_lazy("admin attachment type form", "Status"), "limit_uploads_to": pgettext_lazy( "admin attachment type form", "Limit uploads to" ), "limit_downloads_to": pgettext_lazy( "admin attachment type form", "Limit downloads to" ), } help_texts = { "extensions": pgettext_lazy( "admin attachment type form", "List of comma separated file extensions associated with this attachment type.", ), "mimetypes": pgettext_lazy( "admin attachment type form", "Optional list of comma separated mime types associated with this attachment type.", ), "size_limit": pgettext_lazy( "admin attachment type form", "Maximum allowed uploaded file size for this type, in kb. This setting is deprecated and has no effect. It will be deleted in Misago 1.0.", ), "status": pgettext_lazy( "admin attachment type form", "Controls this attachment type availability on your site.", ), "limit_uploads_to": pgettext_lazy( "admin attachment type form", "If you wish to limit option to upload files of this type to users with specific roles, select them on this list. Otherwise don't select any roles to allow all users with permission to upload attachments to be able to upload attachments of this type.", ), "limit_downloads_to": pgettext_lazy( "admin attachment type form", "If you wish to limit option to download files of this type to users with specific roles, select them on this list. Otherwise don't select any roles to allow all users with permission to download attachments to be able to download attachments of this type.", ), } widgets = { "limit_uploads_to": forms.CheckboxSelectMultiple, "limit_downloads_to": forms.CheckboxSelectMultiple, } def clean_extensions(self): data = self.clean_list(self.cleaned_data["extensions"]) if not data: raise forms.ValidationError( pgettext("admin attachment type form", "This field is required.") ) return data def clean_mimetypes(self): data = self.cleaned_data["mimetypes"] if data: return self.clean_list(data) def clean_list(self, value): items = [v.lstrip(".") for v in value.lower().replace(" ", "").split(",")] return ",".join(set(filter(bool, items)))
5,793
Python
.py
137
30.547445
274
0.573605
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,170
attachmenttypes.py
rafalp_Misago/misago/threads/admin/views/attachmenttypes.py
from django.contrib import messages from django.db.models import Count from django.utils.translation import pgettext, pgettext_lazy from ....admin.views import generic from ...models import AttachmentType from ..forms import AttachmentTypeForm class AttachmentTypeAdmin(generic.AdminBaseMixin): root_link = "misago:admin:settings:attachment-types:index" model = AttachmentType form_class = AttachmentTypeForm templates_dir = "misago/admin/attachmenttypes" message_404 = pgettext_lazy( "admin attachments types", "Requested attachment type does not exist." ) def update_roles(self, target, roles): target.roles.clear() if roles: target.roles.add(*roles) def handle_form(self, form, request, target): super().handle_form(form, request, target) form.save() class AttachmentTypesList(AttachmentTypeAdmin, generic.ListView): ordering = (("name", None),) def get_queryset(self): queryset = super().get_queryset() return queryset.annotate(num_files=Count("attachment")) class NewAttachmentType(AttachmentTypeAdmin, generic.ModelFormView): message_submit = pgettext_lazy( "admin attachments types", 'New type "%(name)s" has been saved.' ) class EditAttachmentType(AttachmentTypeAdmin, generic.ModelFormView): message_submit = pgettext_lazy( "admin attachments types", 'Attachment type "%(name)s" has been edited.' ) class DeleteAttachmentType(AttachmentTypeAdmin, generic.ButtonView): def check_permissions(self, request, target): if target.attachment_set.exists(): message = pgettext( "admin attachments types", 'Attachment type "%(name)s" has associated attachments and can\'t be deleted.', ) return message % {"name": target.name} def button_action(self, request, target): target.delete() message = pgettext( "admin attachments types", 'Attachment type "%(name)s" has been deleted.' ) messages.success(request, message % {"name": target.name})
2,122
Python
.py
48
37.3125
95
0.69694
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,171
attachments.py
rafalp_Misago/misago/threads/admin/views/attachments.py
from django.contrib import messages from django.db import transaction from django.utils.translation import pgettext, pgettext_lazy from ....admin.views import generic from ...models import Attachment, Post from ..forms import FilterAttachmentsForm class AttachmentAdmin(generic.AdminBaseMixin): root_link = "misago:admin:attachments:index" model = Attachment templates_dir = "misago/admin/attachments" message_404 = pgettext_lazy( "admin attachments", "Requested attachment does not exist." ) def get_queryset(self): qs = super().get_queryset() return qs.select_related( "filetype", "uploader", "post", "post__thread", "post__category" ) class AttachmentsList(AttachmentAdmin, generic.ListView): items_per_page = 20 ordering = [ ("-id", pgettext_lazy("admin attachments ordering choice", "From newest")), ("id", pgettext_lazy("admin attachments ordering choice", "From oldest")), ("filename", pgettext_lazy("admin attachments ordering choice", "A to z")), ("-filename", pgettext_lazy("admin attachments ordering choice", "Z to a")), ("size", pgettext_lazy("admin attachments ordering choice", "Smallest files")), ("-size", pgettext_lazy("admin attachments ordering choice", "Largest files")), ] selection_label = pgettext_lazy("admin attachments", "With attachments: 0") empty_selection_label = pgettext_lazy("admin attachments", "Select attachments") mass_actions = [ { "action": "delete", "name": pgettext_lazy("admin attachments", "Delete attachments"), "confirmation": pgettext_lazy( "admin attachments", "Are you sure you want to delete selected attachments?", ), "is_atomic": False, } ] filter_form = FilterAttachmentsForm def action_delete(self, request, attachments): deleted_attachments = [] desynced_posts = [] for attachment in attachments: if attachment.post: deleted_attachments.append(attachment.pk) desynced_posts.append(attachment.post_id) if desynced_posts: with transaction.atomic(): for post in Post.objects.filter(id__in=desynced_posts): self.delete_from_cache(post, deleted_attachments) for attachment in attachments: attachment.delete() message = pgettext( "admin attachments", "Selected attachments have been deleted." ) messages.success(request, message) def delete_from_cache(self, post, attachments): if not post.attachments_cache: return # admin action may be taken due to desynced state clean_cache = [] for a in post.attachments_cache: if a["id"] not in attachments: clean_cache.append(a) post.attachments_cache = clean_cache or None post.save(update_fields=["attachments_cache"]) class DeleteAttachment(AttachmentAdmin, generic.ButtonView): def button_action(self, request, target): if target.post: self.delete_from_cache(target) target.delete() message = pgettext( "admin attachments", 'Attachment "%(filename)s" has been deleted.' ) messages.success(request, message % {"filename": target.filename}) def delete_from_cache(self, attachment): if not attachment.post.attachments_cache: return # admin action may be taken due to desynced state clean_cache = [] for a in attachment.post.attachments_cache: if a["id"] != attachment.id: clean_cache.append(a) attachment.post.attachments_cache = clean_cache or None attachment.post.save(update_fields=["attachments_cache"])
3,895
Python
.py
86
36.209302
87
0.64591
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,172
test_attachments_views.py
rafalp_Misago/misago/threads/admin/tests/test_attachments_views.py
from django.urls import reverse from ... import test from ....admin.test import AdminTestCase from ....categories.models import Category from ...models import Attachment, AttachmentType class AttachmentAdminViewsTests(AdminTestCase): def setUp(self): super().setUp() self.category = Category.objects.get(slug="first-category") self.post = test.post_thread(category=self.category).first_post self.filetype = AttachmentType.objects.order_by("id").first() self.admin_link = reverse("misago:admin:attachments:index") def mock_attachment(self, post=None, file=None, image=None, thumbnail=None): return Attachment.objects.create( secret=Attachment.generate_new_secret(), filetype=self.filetype, post=post, size=1000, uploader=self.user, uploader_name=self.user.username, uploader_slug=self.user.slug, filename="testfile_%s.zip" % (Attachment.objects.count() + 1), file=None, image=None, thumbnail=None, ) def test_link_registered(self): """admin nav contains attachments link""" response = self.client.get(reverse("misago:admin:settings:index")) self.assertContains(response, self.admin_link) def test_list_view(self): """attachments list returns 200 and renders all attachments""" final_link = self.client.get(self.admin_link)["location"] response = self.client.get(final_link) self.assertEqual(response.status_code, 200) attachments = [ self.mock_attachment(self.post, file="somefile.pdf"), self.mock_attachment(image="someimage.jpg"), self.mock_attachment( self.post, image="somelargeimage.png", thumbnail="somethumb.png" ), ] response = self.client.get(final_link) self.assertEqual(response.status_code, 200) for attachment in attachments: delete_link = reverse( "misago:admin:attachments:delete", kwargs={"pk": attachment.pk} ) self.assertContains(response, attachment.filename) self.assertContains(response, delete_link) self.assertContains(response, attachment.get_absolute_url()) self.assertContains(response, attachment.uploader.username) self.assertContains(response, attachment.uploader.get_absolute_url()) if attachment.thumbnail: self.assertContains(response, attachment.get_thumbnail_url()) def test_delete_multiple(self): """mass delete tool on list works""" attachments = [ self.mock_attachment(self.post, file="somefile.pdf"), self.mock_attachment(image="someimage.jpg"), self.mock_attachment( self.post, image="somelargeimage.png", thumbnail="somethumb.png" ), ] self.post.attachments_cache = [{"id": attachments[-1].pk}] self.post.save() response = self.client.post( self.admin_link, data={"action": "delete", "selected_items": [a.pk for a in attachments]}, ) self.assertEqual(response.status_code, 302) self.assertEqual(Attachment.objects.count(), 0) # assert attachments were removed from post's cache attachments_cache = self.category.post_set.get( pk=self.post.pk ).attachments_cache self.assertIsNone(attachments_cache) def test_delete_view(self): """delete attachment view has no showstoppers""" attachment = self.mock_attachment(self.post) self.post.attachments_cache = [ {"id": attachment.pk + 1}, {"id": attachment.pk}, {"id": attachment.pk + 2}, ] self.post.save() action_link = reverse( "misago:admin:attachments:delete", kwargs={"pk": attachment.pk} ) response = self.client.post(action_link) self.assertEqual(response.status_code, 302) # clean alert about item, grab final list url final_link = self.client.get(self.admin_link)["location"] response = self.client.get(final_link) self.assertEqual(response.status_code, 200) self.assertNotContains(response, action_link) # assert it was removed from post's attachments cache attachments_cache = self.category.post_set.get( pk=self.post.pk ).attachments_cache self.assertEqual( attachments_cache, [{"id": attachment.pk + 1}, {"id": attachment.pk + 2}] )
4,680
Python
.py
103
35.184466
85
0.629833
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,173
test_attachment_types_views.py
rafalp_Misago/misago/threads/admin/tests/test_attachment_types_views.py
from django.urls import reverse from ....acl.models import Role from ....admin.test import AdminTestCase from ...models import AttachmentType class AttachmentTypeAdminViewsTests(AdminTestCase): def setUp(self): super().setUp() self.admin_link = reverse("misago:admin:settings:attachment-types:index") def test_link_registered(self): """admin nav contains attachment types link""" response = self.client.get(reverse("misago:admin:settings:index")) self.assertContains(response, self.admin_link) def test_list_view(self): """attachment types list returns 200 and renders all attachment types""" response = self.client.get(self.admin_link) self.assertEqual(response.status_code, 200) for attachment_type in AttachmentType.objects.all(): self.assertContains(response, attachment_type.name) for file_extension in attachment_type.extensions_list: self.assertContains(response, file_extension) for mimename in attachment_type.mimetypes_list: self.assertContains(response, mimename) def test_new_view(self): """new attachment type view has no showstoppers""" form_link = reverse("misago:admin:settings:attachment-types:new") response = self.client.get(form_link) self.assertEqual(response.status_code, 200) response = self.client.post(form_link, data={}) self.assertEqual(response.status_code, 200) response = self.client.post( form_link, data={ "name": "Test type", "extensions": ".test", "size_limit": 0, "status": AttachmentType.ENABLED, }, ) self.assertEqual(response.status_code, 302) # clean alert about new item created self.client.get(self.admin_link) response = self.client.get(self.admin_link) self.assertEqual(response.status_code, 200) self.assertContains(response, "Test type") self.assertContains(response, "test") def test_edit_view(self): """edit attachment type view has no showstoppers""" self.client.post( reverse("misago:admin:settings:attachment-types:new"), data={ "name": "Test type", "extensions": ".test", "size_limit": 0, "status": AttachmentType.ENABLED, }, ) test_type = AttachmentType.objects.order_by("id").last() self.assertEqual(test_type.name, "Test type") form_link = reverse( "misago:admin:settings:attachment-types:edit", kwargs={"pk": test_type.pk} ) response = self.client.get(form_link) self.assertEqual(response.status_code, 200) response = self.client.post(form_link, data={}) self.assertEqual(response.status_code, 200) response = self.client.post( form_link, data={ "name": "Test type edited", "extensions": ".test.extension", "mimetypes": "test/edited-mime", "size_limit": 512, "status": AttachmentType.DISABLED, "limit_uploads_to": [r.pk for r in Role.objects.all()], "limit_downloads_to": [r.pk for r in Role.objects.all()], }, ) self.assertEqual(response.status_code, 302) test_type = AttachmentType.objects.order_by("id").last() self.assertEqual(test_type.name, "Test type edited") # clean alert about new item created self.client.get(self.admin_link) response = self.client.get(self.admin_link) self.assertEqual(response.status_code, 200) self.assertContains(response, test_type.name) self.assertContains(response, test_type.extensions) self.assertContains(response, test_type.mimetypes) self.assertEqual(test_type.limit_uploads_to.count(), Role.objects.count()) self.assertEqual(test_type.limit_downloads_to.count(), Role.objects.count()) # remove limits from type response = self.client.post( form_link, data={ "name": "Test type edited", "extensions": ".test.extension", "mimetypes": "test/edited-mime", "size_limit": 512, "status": AttachmentType.DISABLED, "limit_uploads_to": [], "limit_downloads_to": [], }, ) self.assertEqual(response.status_code, 302) self.assertEqual(test_type.limit_uploads_to.count(), 0) self.assertEqual(test_type.limit_downloads_to.count(), 0) def test_clean_params_view(self): """admin form nicely cleans lists of extensions/mimetypes""" TEST_CASES = [ ("test", ["test"]), (".test", ["test"]), (".tar.gz", ["tar.gz"]), (". test", ["test"]), ("test, test", ["test"]), ("test, tEst", ["test"]), ("test, other, tEst", ["test", "other"]), ("test, other, tEst,OTher", ["test", "other"]), ] for raw, final in TEST_CASES: response = self.client.post( reverse("misago:admin:settings:attachment-types:new"), data={ "name": "Test type", "extensions": raw, "size_limit": 0, "status": AttachmentType.ENABLED, }, ) self.assertEqual(response.status_code, 302) test_type = AttachmentType.objects.order_by("id").last() self.assertEqual(set(test_type.extensions_list), set(final)) def test_delete_view(self): """delete attachment type view has no showstoppers""" self.client.post( reverse("misago:admin:settings:attachment-types:new"), data={ "name": "Test type", "extensions": ".test", "size_limit": 0, "status": AttachmentType.ENABLED, }, ) test_type = AttachmentType.objects.order_by("id").last() self.assertEqual(test_type.name, "Test type") action_link = reverse( "misago:admin:settings:attachment-types:delete", kwargs={"pk": test_type.pk} ) response = self.client.post(action_link) self.assertEqual(response.status_code, 302) # clean alert about item deleted self.client.get(self.admin_link) response = self.client.get(self.admin_link) self.assertEqual(response.status_code, 200) self.assertNotContains(response, test_type.name) def test_cant_delete_type_with_attachments_view(self): """delete attachment type is not allowed if it has attachments associated""" self.client.post( reverse("misago:admin:settings:attachment-types:new"), data={ "name": "Test type", "extensions": ".test", "size_limit": 0, "status": AttachmentType.ENABLED, }, ) test_type = AttachmentType.objects.order_by("id").last() self.assertEqual(test_type.name, "Test type") test_type.attachment_set.create( secret="loremipsum", filetype=test_type, uploader_name="User", uploader_slug="user", filename="test.zip", file="sad76asd678as687sa.zip", ) action_link = reverse( "misago:admin:settings:attachment-types:delete", kwargs={"pk": test_type.pk} ) response = self.client.post(action_link) self.assertEqual(response.status_code, 302) # get alert form database AttachmentType.objects.get(pk=test_type.pk)
7,950
Python
.py
181
32.342541
88
0.582406
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,174
post.py
rafalp_Misago/misago/threads/viewmodels/post.py
from django.shortcuts import get_object_or_404 from ...acl.objectacl import add_acl_to_obj from ...core.viewmodel import ViewModel as BaseViewModel from ..permissions import exclude_invisible_posts __all__ = ["ThreadPost"] class ViewModel(BaseViewModel): def __init__(self, request, thread, pk): model = self.get_post(request, thread, pk) add_acl_to_obj(request.user_acl, model) self._model = model def get_post(self, request, thread, pk): try: thread_model = thread.unwrap() except AttributeError: thread_model = thread queryset = self.get_queryset(request, thread_model).select_related( "poster", "poster__rank", "poster__ban_cache" ) post = get_object_or_404(queryset, pk=pk) post.thread = thread_model post.category = thread.category return post def get_queryset(self, request, thread): return exclude_invisible_posts( request.user_acl, thread.category, thread.post_set ) class ThreadPost(ViewModel): pass
1,092
Python
.py
28
31.5
75
0.659048
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,175
category.py
rafalp_Misago/misago/threads/viewmodels/category.py
from django.http import Http404 from ...acl.objectacl import add_acl_to_obj from ...categories.models import Category from ...categories.permissions import allow_browse_category, allow_see_category from ...categories.serializers import CategorySerializer from ...core.shortcuts import validate_slug from ...core.viewmodel import ViewModel as BaseViewModel from ..permissions import allow_use_private_threads __all__ = ["ThreadsRootCategory", "ThreadsCategory", "PrivateThreadsCategory"] class ViewModel(BaseViewModel): def __init__(self, request, **kwargs): self.request = request self._categories = self.get_categories(request) add_acl_to_obj(request.user_acl, self._categories) self._model = self.get_category(request, self._categories, **kwargs) self._subcategories = list(filter(self._model.has_child, self._categories)) self._children = list( filter(lambda s: s.parent_id == self._model.pk, self._subcategories) ) @property def categories(self): return self._categories @property def subcategories(self): return self._subcategories @property def children(self): return self._children def get_categories(self, request): raise NotImplementedError( "Category view model has to implement get_categories(request)" ) def get_category(self, request, categories, **kwargs): return categories[0] def get_frontend_context(self): return { "CATEGORIES": BasicCategorySerializer( self._categories, context={"settings": self.request.settings}, many=True, ).data } def get_template_context(self): top_category = None sub_category = None if self._model.level == 1: top_category = self._model elif self._model.level == 2: top_category = self._model.parent sub_category = self._model return { "category": self._model, "top_category": top_category, "sub_category": sub_category, "categories": self._categories, "subcategories": self._children, } class ThreadsRootCategory(ViewModel): def get_categories(self, request): return [Category.objects.root_category()] + list( Category.objects.all_categories() .filter(id__in=request.user_acl["visible_categories"]) .select_related("parent") ) class ThreadsCategory(ThreadsRootCategory): @property def level(self): return self._model.level def get_category(self, request, categories, **kwargs): for category in categories: if category.pk == int(kwargs["pk"]): if not category.special_role: # check permissions for non-special categories allow_see_category(request.user_acl, category) allow_browse_category(request.user_acl, category) if "slug" in kwargs: validate_slug(category, kwargs["slug"]) return category raise Http404() class PrivateThreadsCategory(ViewModel): def get_categories(self, request): return [Category.objects.private_threads()] def get_category(self, request, categories, **kwargs): allow_use_private_threads(request.user_acl) return categories[0] BasicCategorySerializer = CategorySerializer.subset_fields( "id", "parent", "name", "short_name", "color", "description", "is_closed", "css_class", "level", "lft", "rght", "is_read", "url", )
3,736
Python
.py
100
28.87
83
0.634877
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,176
thread.py
rafalp_Misago/misago/threads/viewmodels/thread.py
from django.shortcuts import get_object_or_404 from django.utils.translation import pgettext from ...acl.objectacl import add_acl_to_obj from ...categories import PRIVATE_THREADS_ROOT_NAME, THREADS_ROOT_NAME from ...categories.models import Category from ...core.shortcuts import validate_slug from ...core.viewmodel import ViewModel as BaseViewModel from ...notifications.models import WatchedThread from ...notifications.threads import get_watched_thread from ..models import Poll, Thread from ..participants import make_participants_aware from ..permissions import ( allow_see_private_thread, allow_see_thread, allow_use_private_threads, ) from ..serializers import PrivateThreadSerializer, ThreadSerializer from ..threadtypes import trees_map __all__ = ["ForumThread", "PrivateThread"] BASE_RELATIONS = [ "category", "poll", "starter", "starter__rank", "starter__ban_cache", "starter__online_tracker", ] class ViewModel(BaseViewModel): def __init__( self, request, pk, slug=None, path_aware=False, read_aware=False, watch_aware=False, poll_votes_aware=False, ): self.request = request model = self.get_thread(request, pk, slug) if path_aware: model.path = self.get_thread_path(model.category) add_acl_to_obj(request.user_acl, model.category) add_acl_to_obj(request.user_acl, model) if watch_aware and request.user.is_authenticated: self._watched_thread = get_watched_thread(request.user, model) else: self._watched_thread = None self._model = model try: self._poll = model.poll add_acl_to_obj(request.user_acl, self._poll) if poll_votes_aware: self._poll.make_choices_votes_aware(request.user) except Poll.DoesNotExist: self._poll = None @property def watched_thread(self) -> WatchedThread | None: return self._watched_thread @property def poll(self): return self._poll def get_thread(self, request, pk, slug=None): raise NotImplementedError( "Thread view model has to implement get_thread(request, pk, slug=None)" ) def get_thread_path(self, category): thread_path = [] if category.level: categories = Category.objects.filter( tree_id=category.tree_id, lft__lte=category.lft, rght__gte=category.rght ).order_by("level") thread_path = list(categories) else: thread_path = [category] thread_path[0].name = self.get_root_name() return thread_path def get_root_name(self): raise NotImplementedError("Thread view model has to implement get_root_name()") def get_frontend_context(self): raise NotImplementedError( "Thread view model has to implement get_frontend_context()" ) def get_template_context(self): thread_notifications = None if self._watched_thread: if self._watched_thread.send_emails: thread_notifications = "SITE_AND_EMAIL" else: thread_notifications = "SITE_ONLY" return { "thread": self._model, "thread_notifications": thread_notifications, "poll": self._poll, "category": self._model.category, "breadcrumbs": self._model.path, } class ForumThread(ViewModel): def get_thread(self, request, pk, slug=None): thread = get_object_or_404( Thread.objects.select_related(*BASE_RELATIONS), pk=pk, category__tree_id=trees_map.get_tree_id_for_root(THREADS_ROOT_NAME), ) allow_see_thread(request.user_acl, thread) if slug: validate_slug(thread, slug) return thread def get_root_name(self): return pgettext("threads root name", "Threads") def get_frontend_context(self): return ThreadSerializer( self._model, context={ "settings": self.request.settings, "watched_thread": self._watched_thread, }, ).data class PrivateThread(ViewModel): def get_thread(self, request, pk, slug=None): allow_use_private_threads(request.user_acl) thread = get_object_or_404( Thread.objects.select_related(*BASE_RELATIONS), pk=pk, category__tree_id=trees_map.get_tree_id_for_root(PRIVATE_THREADS_ROOT_NAME), ) make_participants_aware(request.user, thread) allow_see_private_thread(request.user_acl, thread) if slug: validate_slug(thread, slug) return thread def get_root_name(self): return pgettext("private threads root name", "Private threads") def get_frontend_context(self): return PrivateThreadSerializer( self._model, context={ "settings": self.request.settings, "watched_thread": self._watched_thread, }, ).data
5,191
Python
.py
141
28.078014
88
0.627318
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,177
__init__.py
rafalp_Misago/misago/threads/viewmodels/__init__.py
from .category import * from .post import * from .posts import * from .thread import * from .threads import *
110
Python
.py
5
21
23
0.761905
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,178
posts.py
rafalp_Misago/misago/threads/viewmodels/posts.py
from ...acl.objectacl import add_acl_to_obj from ...core.shortcuts import paginate, pagination_dict from ...users.online.utils import make_users_status_aware from ..paginator import PostsPaginator from ..permissions import exclude_invisible_posts from ..serializers import PostSerializer from ..utils import add_likes_to_posts __all__ = ["ThreadPosts"] class ViewModel: def __init__(self, request, thread, page): # pylint: disable=too-many-locals try: thread_model = thread.unwrap() except AttributeError: thread_model = thread posts_queryset = self.get_posts_queryset(request, thread_model) posts_limit = request.settings.posts_per_page posts_orphans = request.settings.posts_per_page_orphans list_page = paginate( posts_queryset, page, posts_limit, posts_orphans, paginator=PostsPaginator ) paginator = pagination_dict(list_page) posts = list(list_page.object_list) posters = [] for post in posts: post.category = thread.category post.thread = thread_model if post.poster: posters.append(post.poster) make_users_status_aware(request, posters) if thread.category.acl["can_see_posts_likes"]: add_likes_to_posts(request.user, posts) # add events to posts if thread_model.has_events: first_post = None if list_page.has_previous(): first_post = posts[0] last_post = None if list_page.has_next(): last_post = posts[-1] events_limit = request.settings.events_per_page posts += self.get_events_queryset( request, thread_model, events_limit, first_post, last_post ) # sort both by pk posts.sort(key=lambda p: p.pk) # make posts and events ACL aware add_acl_to_obj(request.user_acl, posts) self._user = request.user self.posts = posts self.paginator = paginator def get_posts_queryset(self, request, thread): queryset = ( thread.post_set.select_related( "category", "poster", "poster__rank", "poster__ban_cache", "poster__online_tracker", ) .filter(is_event=False) .order_by("id") ) return exclude_invisible_posts(request.user_acl, thread.category, queryset) def get_events_queryset( self, request, thread, limit, first_post=None, last_post=None ): queryset = thread.post_set.select_related( "category", "poster", "poster__rank", "poster__ban_cache", "poster__online_tracker", ).filter(is_event=True) if first_post: queryset = queryset.filter(pk__gt=first_post.pk) if last_post: queryset = queryset.filter(pk__lt=last_post.pk) queryset = exclude_invisible_posts(request.user_acl, thread.category, queryset) return list(queryset.order_by("-id")[:limit]) def get_frontend_context(self): context = { "results": PostSerializer( self.posts, many=True, context={"user": self._user} ).data } context.update(self.paginator) return context def get_template_context(self): return {"posts": self.posts, "paginator": self.paginator} class ThreadPosts(ViewModel): pass
3,591
Python
.py
91
29.208791
87
0.598446
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,179
threads.py
rafalp_Misago/misago/threads/viewmodels/threads.py
from django.core.exceptions import PermissionDenied from django.core.paginator import EmptyPage, InvalidPage from django.db.models import Q from django.http import Http404 from django.utils.translation import pgettext, pgettext_lazy from ...acl.objectacl import add_acl_to_obj from ...core.cursorpagination import get_page from ...notifications.models import WatchedThread from ...notifications.threads import get_watched_threads from ..models import Post, Thread from ..participants import make_participants_aware from ..permissions import exclude_invisible_posts, exclude_invisible_threads from ..serializers import ThreadsListSerializer from ..utils import add_categories_to_items __all__ = ["ForumThreads", "PrivateThreads", "filter_read_threads_queryset"] LISTS_NAMES = { "all": None, "my": pgettext_lazy("threads list", "Your threads"), "new": pgettext_lazy("threads list", "New threads"), "unread": pgettext_lazy("threads list", "Unread threads"), "watched": pgettext_lazy("threads list", "Watched threads"), "unapproved": pgettext_lazy("threads list", "Unapproved content"), } LIST_DENIED_MESSAGES = { "my": pgettext_lazy( "threads list", "You have to sign in to see list of threads that you have started.", ), "new": pgettext_lazy( "threads list", "You have to sign in to see list of threads you haven't read.", ), "unread": pgettext_lazy( "threads list", "You have to sign in to see list of threads with new replies.", ), "watched": pgettext_lazy( "threads list", "You have to sign in to see list of threads you are watching.", ), "unapproved": pgettext_lazy( "threads list", "You have to sign in to see list of threads with unapproved posts.", ), } class ViewModel: def __init__(self, request, category, list_type, start=0): self.request = request self.allow_see_list(request, category, list_type) category_model = category.unwrap() base_queryset = self.get_base_queryset(request, category.categories, list_type) base_queryset = base_queryset.select_related("starter", "last_poster") threads_categories = [category_model] + category.subcategories threads_queryset = self.get_remaining_threads_queryset( base_queryset, category_model, threads_categories ) try: list_page = get_page( threads_queryset, "-last_post_id", request.settings.threads_per_page, start, ) except (EmptyPage, InvalidPage): raise Http404() if list_page.first: pinned_threads = list( self.get_pinned_threads( base_queryset, category_model, threads_categories ) ) threads = list(pinned_threads) + list(list_page.object_list) else: threads = list(list_page.object_list) add_categories_to_items(category_model, category.categories, threads) add_acl_to_obj(request.user_acl, threads) if list_type == "watched" and request.user.is_authenticated: self.watched_threads = get_watched_threads(request.user, threads) else: self.watched_threads = {} if list_type in ("new", "unread"): # we already know all threads on list are unread for thread in threads: thread.is_read = False thread.is_new = True else: for thread in threads: thread.is_read = True thread.is_new = False self.filter_threads(request, threads) # set state on object for easy access from hooks self.category = category self.threads = threads self.list_type = list_type self.list_page = list_page def allow_see_list(self, request, category, list_type): if list_type not in LISTS_NAMES: raise Http404() if request.user.is_anonymous: if list_type in LIST_DENIED_MESSAGES: raise PermissionDenied(LIST_DENIED_MESSAGES[list_type]) else: has_permission = request.user_acl["can_see_unapproved_content_lists"] if list_type == "unapproved" and not has_permission: raise PermissionDenied( pgettext( "threads list", "You don't have permission to see unapproved content lists.", ) ) def get_list_name(self, list_type): return LISTS_NAMES[list_type] def get_base_queryset(self, request, threads_categories, list_type): return get_threads_queryset(request, threads_categories, list_type).order_by( "-last_post_id" ) def get_pinned_threads(self, queryset, category, threads_categories): return [] def get_remaining_threads_queryset(self, queryset, category, threads_categories): return [] def filter_threads(self, request, threads): pass # hook for custom thread types to add features to extend threads def get_frontend_context(self): return { "THREADS": { "results": ThreadsListSerializer( self.threads, many=True, context={ "settings": self.request.settings, "watched_threads": self.watched_threads, }, ).data, "subcategories": [c.pk for c in self.category.children], "next": self.list_page.next, } } def get_template_context(self): return { "list_name": self.get_list_name(self.list_type), "list_type": self.list_type, "list_page": self.list_page, "threads": self.threads, } class ForumThreads(ViewModel): def get_pinned_threads(self, queryset, category, threads_categories): if category.level: return list(queryset.filter(weight=2)) + list( queryset.filter(weight=1, category__in=threads_categories) ) return queryset.filter(weight=2) def get_remaining_threads_queryset(self, queryset, category, threads_categories): if category.level: return queryset.filter(weight=0, category__in=threads_categories) return queryset.filter(weight__lt=2, category__in=threads_categories) class PrivateThreads(ViewModel): def get_base_queryset(self, request, threads_categories, list_type): queryset = super().get_base_queryset(request, threads_categories, list_type) # limit queryset to threads we are participant of participated_threads = request.user.threadparticipant_set.values("thread_id") if request.user_acl["can_moderate_private_threads"]: queryset = queryset.filter( Q(id__in=participated_threads) | Q(has_reported_posts=True) ) else: queryset = queryset.filter(id__in=participated_threads) return queryset def get_remaining_threads_queryset(self, queryset, category, threads_categories): return queryset.filter(category__in=threads_categories) def filter_threads(self, request, threads): make_participants_aware(request.user, threads) def get_threads_queryset(request, categories, list_type): queryset = exclude_invisible_threads(request.user_acl, categories, Thread.objects) if list_type == "all": return queryset return filter_threads_queryset(request, categories, list_type, queryset) def filter_threads_queryset(request, categories, list_type, queryset): if list_type == "my": return queryset.filter(starter=request.user) if list_type == "watched": watched_threads = WatchedThread.objects.filter(user=request.user).values( "thread_id" ) return queryset.filter(id__in=watched_threads) if list_type == "unapproved": return queryset.filter(has_unapproved_posts=True) if list_type in ("new", "unread"): return filter_read_threads_queryset(request, categories, list_type, queryset) return queryset def filter_read_threads_queryset(request, categories, list_type, queryset): # grab cutoffs for categories cutoff_date = get_cutoff_date(request.settings, request.user) visible_posts = Post.objects.filter(posted_on__gt=cutoff_date) visible_posts = exclude_invisible_posts(request.user_acl, categories, visible_posts) queryset = queryset.filter(id__in=visible_posts.distinct().values("thread")) read_posts = visible_posts.filter(id__in=request.user.postread_set.values("post")) if list_type == "new": # new threads have no entry in reads table return queryset.exclude(id__in=read_posts.distinct().values("thread")) if list_type == "unread": # unread threads were read in past but have new posts unread_posts = visible_posts.exclude( id__in=request.user.postread_set.values("post") ) queryset = queryset.filter(id__in=read_posts.distinct().values("thread")) queryset = queryset.filter(id__in=unread_posts.distinct().values("thread")) return queryset
9,411
Python
.py
207
36.019324
88
0.642639
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,180
polls.py
rafalp_Misago/misago/threads/permissions/polls.py
from django import forms from django.core.exceptions import PermissionDenied from django.utils import timezone from django.utils.translation import npgettext, pgettext_lazy from ...acl import algebra from ...acl.decorators import return_boolean from ...acl.models import Role from ...admin.forms import YesNoSwitch from ..models import Poll, Thread __all__ = [ "allow_start_poll", "can_start_poll", "allow_edit_poll", "can_edit_poll", "allow_delete_poll", "can_delete_poll", "allow_vote_poll", "can_vote_poll", "allow_see_poll_votes", "can_see_poll_votes", ] class RolePermissionsForm(forms.Form): legend = pgettext_lazy("polls permission", "Polls") can_start_polls = forms.TypedChoiceField( label=pgettext_lazy("polls permission", "Can start polls"), coerce=int, initial=0, choices=[ (0, pgettext_lazy("polls start permission choice", "No")), (1, pgettext_lazy("polls start permission choice", "Own threads")), (2, pgettext_lazy("polls start permission choice", "All threads")), ], ) can_edit_polls = forms.TypedChoiceField( label=pgettext_lazy("polls permission", "Can edit polls"), coerce=int, initial=0, choices=[ (0, pgettext_lazy("polls edit permission choice", "No")), (1, pgettext_lazy("polls edit permission choice", "Own polls")), (2, pgettext_lazy("polls edit permission choice", "All polls")), ], ) can_delete_polls = forms.TypedChoiceField( label=pgettext_lazy("polls permission", "Can delete polls"), coerce=int, initial=0, choices=[ (0, pgettext_lazy("polls delete permission choice", "No")), (1, pgettext_lazy("polls delete permission choice", "Own polls")), (2, pgettext_lazy("polls delete permission choice", "All polls")), ], ) poll_edit_time = forms.IntegerField( label=pgettext_lazy( "polls permission", "Time limit for editing own polls, in minutes" ), help_text=pgettext_lazy( "polls permission", "Enter 0 to don't limit time for editing own polls." ), initial=0, min_value=0, ) can_always_see_poll_voters = YesNoSwitch( label=pgettext_lazy("polls permission", "Can always see polls voters"), help_text=pgettext_lazy( "polls permission", "Allows users to see who voted in poll even if voting was not public.", ), ) def change_permissions_form(role): if isinstance(role, Role) and role.special_role != "anonymous": return RolePermissionsForm def build_acl(acl, roles, key_name): acl.update( { "can_start_polls": 0, "can_edit_polls": 0, "can_delete_polls": 0, "poll_edit_time": 0, "can_always_see_poll_voters": 0, } ) return algebra.sum_acls( acl, roles=roles, key=key_name, can_start_polls=algebra.greater, can_edit_polls=algebra.greater, can_delete_polls=algebra.greater, poll_edit_time=algebra.greater_or_zero, can_always_see_poll_voters=algebra.greater, ) def add_acl_to_poll(user_acl, poll): poll.acl.update( { "can_vote": can_vote_poll(user_acl, poll), "can_edit": can_edit_poll(user_acl, poll), "can_delete": can_delete_poll(user_acl, poll), "can_see_votes": can_see_poll_votes(user_acl, poll), } ) def add_acl_to_thread(user_acl, thread): thread.acl.update({"can_start_poll": can_start_poll(user_acl, thread)}) def register_with(registry): registry.acl_annotator(Poll, add_acl_to_poll) registry.acl_annotator(Thread, add_acl_to_thread) def allow_start_poll(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("polls permission", "You have to sign in to start polls.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_close_threads": False} ) if not user_acl.get("can_start_polls"): raise PermissionDenied( pgettext_lazy("polls permission", "You can't start polls.") ) if user_acl.get("can_start_polls") < 2 and user_acl["user_id"] != target.starter_id: raise PermissionDenied( pgettext_lazy( "polls permission", "You can't start polls in other users threads." ) ) if not category_acl.get("can_close_threads"): if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "polls permission", "This category is closed. You can't start polls in it.", ) ) if target.is_closed: raise PermissionDenied( pgettext_lazy( "polls permission", "This thread is closed. You can't start polls in it.", ) ) can_start_poll = return_boolean(allow_start_poll) def allow_edit_poll(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("polls permission", "You have to sign in to edit polls.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_close_threads": False} ) if not user_acl.get("can_edit_polls"): raise PermissionDenied( pgettext_lazy("polls permission", "You can't edit polls.") ) if user_acl.get("can_edit_polls") < 2: if user_acl["user_id"] != target.poster_id: raise PermissionDenied( pgettext_lazy( "polls permission", "You can't edit other users polls in this category.", ) ) if not has_time_to_edit_poll(user_acl, target): message = npgettext( "polls permission", "You can't edit polls that are older than %(minutes)s minute.", "You can't edit polls that are older than %(minutes)s minutes.", user_acl["poll_edit_time"], ) raise PermissionDenied(message % {"minutes": user_acl["poll_edit_time"]}) if target.is_over: raise PermissionDenied( pgettext_lazy( "polls permission", "This poll is over. You can't edit it." ) ) if not category_acl.get("can_close_threads"): if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "polls permission", "This category is closed. You can't edit polls in it.", ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "polls permission", "This thread is closed. You can't edit polls in it.", ) ) can_edit_poll = return_boolean(allow_edit_poll) def allow_delete_poll(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("polls permission", "You have to sign in to delete polls.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_close_threads": False} ) if not user_acl.get("can_delete_polls"): raise PermissionDenied( pgettext_lazy("polls permission", "You can't delete polls.") ) if user_acl.get("can_delete_polls") < 2: if user_acl["user_id"] != target.poster_id: raise PermissionDenied( pgettext_lazy( "polls permission", "You can't delete other users polls in this category.", ) ) if not has_time_to_edit_poll(user_acl, target): message = npgettext( "polls permission", "You can't delete polls that are older than %(minutes)s minute.", "You can't delete polls that are older than %(minutes)s minutes.", user_acl["poll_edit_time"], ) raise PermissionDenied(message % {"minutes": user_acl["poll_edit_time"]}) if target.is_over: raise PermissionDenied( pgettext_lazy( "polls permission", "This poll is over. You can't delete it." ) ) if not category_acl.get("can_close_threads"): if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "polls permission", "This category is closed. You can't delete polls in it.", ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "polls permission", "This thread is closed. You can't delete polls in it.", ) ) can_delete_poll = return_boolean(allow_delete_poll) def allow_vote_poll(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("polls permission", "You have to sign in to vote in polls.") ) if target.has_selected_choices and not target.allow_revotes: raise PermissionDenied( pgettext_lazy("polls permission", "You have already voted in this poll.") ) if target.is_over: raise PermissionDenied( pgettext_lazy( "polls permission", "This poll is over. You can't vote in it." ) ) category_acl = user_acl["categories"].get( target.category_id, {"can_close_threads": False} ) if not category_acl.get("can_close_threads"): if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "polls permission", "This category is closed. You can't vote in it." ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "polls permission", "This thread is closed. You can't vote in it." ) ) can_vote_poll = return_boolean(allow_vote_poll) def allow_see_poll_votes(user_acl, target): if not target.is_public and not user_acl["can_always_see_poll_voters"]: raise PermissionDenied( pgettext_lazy( "polls permission", "You dont have permission to see this poll's voters.", ) ) can_see_poll_votes = return_boolean(allow_see_poll_votes) def has_time_to_edit_poll(user_acl, target): edit_time = user_acl["poll_edit_time"] if edit_time: diff = timezone.now() - target.posted_on diff_minutes = int(diff.total_seconds() / 60) return diff_minutes < edit_time return True
11,134
Python
.py
289
28.190311
88
0.576221
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,181
bestanswers.py
rafalp_Misago/misago/threads/permissions/bestanswers.py
from django import forms from django.core.exceptions import PermissionDenied from django.utils import timezone from django.utils.translation import npgettext, pgettext_lazy from ...acl import algebra from ...acl.decorators import return_boolean from ...categories.models import Category, CategoryRole from ...categories.permissions import get_categories_roles from ..models import Post, Thread __all__ = [ "allow_change_best_answer", "can_change_best_answer", "allow_mark_best_answer", "can_mark_best_answer", "allow_mark_as_best_answer", "can_mark_as_best_answer", "allow_unmark_best_answer", "can_unmark_best_answer", "allow_hide_best_answer", "can_hide_best_answer", "allow_delete_best_answer", "can_delete_best_answer", ] class CategoryPermissionsForm(forms.Form): legend = pgettext_lazy("best answers permission", "Best answers") can_mark_best_answers = forms.TypedChoiceField( label=pgettext_lazy( "best answers permission", "Can mark posts as best answers" ), coerce=int, initial=0, choices=[ (0, pgettext_lazy("best answers mark permission choice", "No")), (1, pgettext_lazy("best answers mark permission choice", "Own threads")), (2, pgettext_lazy("best answers mark permission choice", "All threads")), ], ) can_change_marked_answers = forms.TypedChoiceField( label=pgettext_lazy("best answers permission", "Can change marked answers"), coerce=int, initial=0, choices=[ (0, pgettext_lazy("best answers change permission choice", "No")), (1, pgettext_lazy("best answers change permission choice", "Own threads")), (2, pgettext_lazy("best answers change permission choice", "All threads")), ], ) best_answer_change_time = forms.IntegerField( label=pgettext_lazy( "best answers permission", "Time limit for changing marked best answer in owned thread, in minutes", ), help_text=pgettext_lazy( "best answers permission", "Enter 0 to don't limit time for changing marked best answer in owned thread.", ), initial=0, min_value=0, ) def change_permissions_form(role): if isinstance(role, CategoryRole): return CategoryPermissionsForm def build_acl(acl, roles, key_name): categories_roles = get_categories_roles(roles) categories = list(Category.objects.all_categories(include_root=True)) for category in categories: category_acl = acl["categories"].get(category.pk, {"can_browse": 0}) if category_acl["can_browse"]: acl["categories"][category.pk] = build_category_acl( category_acl, category, categories_roles, key_name ) private_category = Category.objects.private_threads() private_threads_acl = acl["categories"].get(private_category.pk) if private_threads_acl: private_threads_acl.update( { "can_mark_best_answers": 0, "can_change_marked_answers": 0, "best_answer_change_time": 0, } ) return acl def build_category_acl(acl, category, categories_roles, key_name): category_roles = categories_roles.get(category.pk, []) final_acl = { "can_mark_best_answers": 0, "can_change_marked_answers": 0, "best_answer_change_time": 0, } final_acl.update(acl) algebra.sum_acls( final_acl, roles=category_roles, key=key_name, can_mark_best_answers=algebra.greater, can_change_marked_answers=algebra.greater, best_answer_change_time=algebra.greater_or_zero, ) return final_acl def add_acl_to_thread(user_acl, thread): thread.acl.update( { "can_mark_best_answer": can_mark_best_answer(user_acl, thread), "can_change_best_answer": can_change_best_answer(user_acl, thread), "can_unmark_best_answer": can_unmark_best_answer(user_acl, thread), } ) def add_acl_to_post(user_acl, post): post.acl.update( { "can_mark_as_best_answer": can_mark_as_best_answer(user_acl, post), "can_hide_best_answer": can_hide_best_answer(user_acl, post), "can_delete_best_answer": can_delete_best_answer(user_acl, post), } ) def register_with(registry): registry.acl_annotator(Thread, add_acl_to_thread) registry.acl_annotator(Post, add_acl_to_post) def allow_mark_best_answer(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy( "best answers permission", "You have to sign in to mark best answers." ) ) category_acl = user_acl["categories"].get(target.category_id, {}) if not category_acl.get("can_mark_best_answers"): raise PermissionDenied( pgettext_lazy( "best answers permission", 'You don\'t have permission to mark best answers in the "%(category)s" category.', ) % {"category": target.category} ) if ( category_acl["can_mark_best_answers"] == 1 and user_acl["user_id"] != target.starter_id ): raise PermissionDenied( pgettext_lazy( "best answers permission", "You don't have permission to mark best answer in this thread because you didn't start it.", ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "best answers permission", 'You don\'t have permission to mark best answer in this thread because its category "%(category)s" is closed.', ) % {"category": target.category} ) if target.is_closed: raise PermissionDenied( pgettext_lazy( "best answers permission", "You can't mark best answer in this thread because it's closed and you don't have permission to open it.", ) ) can_mark_best_answer = return_boolean(allow_mark_best_answer) def allow_change_best_answer(user_acl, target): if not target.has_best_answer: return # shortcircut permission test category_acl = user_acl["categories"].get(target.category_id, {}) if not category_acl.get("can_change_marked_answers"): raise PermissionDenied( pgettext_lazy( "best answers permission", "You don't have permission to change this thread's marked answer because it's in the \"%(category)s\" category.", ) % {"category": target.category} ) if category_acl["can_change_marked_answers"] == 1: if user_acl["user_id"] != target.starter_id: raise PermissionDenied( pgettext_lazy( "best answers permission", "You don't have permission to change this thread's marked answer because you are not a thread starter.", ) ) if not has_time_to_change_answer(user_acl, target): # pylint: disable=line-too-long message = npgettext( "best answers permission", "You don't have permission to change best answer that was marked for more than %(minutes)s minute.", "You don't have permission to change best answer that was marked for more than %(minutes)s minutes.", category_acl["best_answer_change_time"], ) raise PermissionDenied( message % {"minutes": category_acl["best_answer_change_time"]} ) if target.best_answer_is_protected and not category_acl["can_protect_posts"]: raise PermissionDenied( pgettext_lazy( "best answers permission", "You don't have permission to change this thread's best answer because a moderator has protected it.", ) ) can_change_best_answer = return_boolean(allow_change_best_answer) def allow_unmark_best_answer(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy( "best answers permission", "You have to sign in to unmark best answers." ) ) if not target.has_best_answer: return # shortcircut test category_acl = user_acl["categories"].get(target.category_id, {}) if not category_acl.get("can_change_marked_answers"): raise PermissionDenied( pgettext_lazy( "best answers permission", 'You don\'t have permission to unmark threads answers in the "%(category)s" category.', ) % {"category": target.category} ) if category_acl["can_change_marked_answers"] == 1: if user_acl["user_id"] != target.starter_id: raise PermissionDenied( pgettext_lazy( "best answers permission", "You don't have permission to unmark this best answer because you are not a thread starter.", ) ) if not has_time_to_change_answer(user_acl, target): # pylint: disable=line-too-long message = npgettext( "best answers permission", "You don't have permission to unmark best answer that was marked for more than %(minutes)s minute.", "You don't have permission to unmark best answer that was marked for more than %(minutes)s minutes.", category_acl["best_answer_change_time"], ) raise PermissionDenied( message % {"minutes": category_acl["best_answer_change_time"]} ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "best answers permission", 'You don\'t have permission to unmark this best answer because its category "%(category)s" is closed.', ) % {"category": target.category} ) if target.is_closed: raise PermissionDenied( pgettext_lazy( "best answers permission", "You can't unmark this thread's best answer because it's closed and you don't have permission to open it.", ) ) if target.best_answer_is_protected and not category_acl["can_protect_posts"]: raise PermissionDenied( pgettext_lazy( "best answers permission", "You don't have permission to unmark this thread's best answer because a moderator has protected it.", ) ) can_unmark_best_answer = return_boolean(allow_unmark_best_answer) def allow_mark_as_best_answer(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy( "best answers permission", "You have to sign in to mark best answers." ) ) if target.is_event: raise PermissionDenied( pgettext_lazy( "best answers permission", "Events can't be marked as best answers." ) ) category_acl = user_acl["categories"].get(target.category_id, {}) if not category_acl.get("can_mark_best_answers"): raise PermissionDenied( pgettext_lazy( "best answers permission", 'You don\'t have permission to mark best answers in the "%(category)s" category.', ) % {"category": target.category} ) if ( category_acl["can_mark_best_answers"] == 1 and user_acl["user_id"] != target.thread.starter_id ): raise PermissionDenied( pgettext_lazy( "best answers permission", "You don't have permission to mark best answer in this thread because you didn't start it.", ) ) if target.is_first_post: raise PermissionDenied( pgettext_lazy( "best answers permission", "First post in a thread can't be marked as best answer.", ) ) if target.is_hidden: raise PermissionDenied( pgettext_lazy( "best answers permission", "Hidden posts can't be marked as best answers.", ) ) if target.is_unapproved: raise PermissionDenied( pgettext_lazy( "best answers permission", "Unapproved posts can't be marked as best answers.", ) ) if target.is_protected and not category_acl["can_protect_posts"]: raise PermissionDenied( pgettext_lazy( "best answers permission", "You don't have permission to mark this post as best answer because a moderator has protected it.", ) ) can_mark_as_best_answer = return_boolean(allow_mark_as_best_answer) def allow_hide_best_answer(user_acl, target): if target.is_best_answer: raise PermissionDenied( pgettext_lazy( "best answers permission", "You can't hide this post because its marked as best answer.", ) ) can_hide_best_answer = return_boolean(allow_hide_best_answer) def allow_delete_best_answer(user_acl, target): if target.is_best_answer: raise PermissionDenied( pgettext_lazy( "best answers permission", "You can't delete this post because its marked as best answer.", ) ) can_delete_best_answer = return_boolean(allow_delete_best_answer) def has_time_to_change_answer(user_acl, target): category_acl = user_acl["categories"].get(target.category_id, {}) change_time = category_acl.get("best_answer_change_time", 0) if change_time: diff = timezone.now() - target.best_answer_marked_on diff_minutes = int(diff.total_seconds() / 60) return diff_minutes < change_time return True
14,484
Python
.py
348
31.227011
131
0.601365
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,182
privatethreads.py
rafalp_Misago/misago/threads/permissions/privatethreads.py
from django import forms from django.core.exceptions import PermissionDenied from django.http import Http404 from django.utils.translation import pgettext_lazy from ...acl import algebra from ...acl.decorators import return_boolean from ...acl.models import Role from ...admin.forms import YesNoSwitch from ...categories import PRIVATE_THREADS_ROOT_NAME from ...categories.models import Category from ..models import Thread __all__ = [ "allow_use_private_threads", "can_use_private_threads", "allow_see_private_thread", "can_see_private_thread", "allow_change_owner", "can_change_owner", "allow_add_participants", "can_add_participants", "allow_remove_participant", "can_remove_participant", "allow_add_participant", "can_add_participant", "allow_message_user", "can_message_user", ] class PermissionsForm(forms.Form): legend = pgettext_lazy("private threads permission", "Private threads") can_use_private_threads = YesNoSwitch( label=pgettext_lazy("private threads permission", "Can use private threads") ) can_start_private_threads = YesNoSwitch( label=pgettext_lazy("private threads permission", "Can start private threads") ) max_private_thread_participants = forms.IntegerField( label=pgettext_lazy( "private threads permission", "Max number of users invited to private thread", ), help_text=pgettext_lazy( "private threads permission", "Enter 0 to don't limit number of participants.", ), initial=3, min_value=0, ) can_add_everyone_to_private_threads = YesNoSwitch( label=pgettext_lazy( "private threads permission", "Can add everyone to threads" ), help_text=pgettext_lazy( "private threads permission", "Allows user to add users that are blocking them to private threads.", ), ) can_report_private_threads = YesNoSwitch( label=pgettext_lazy("private threads permission", "Can report private threads"), help_text=pgettext_lazy( "private threads permission", "Allows user to report private threads they are participating in, making them accessible to moderators.", ), ) can_moderate_private_threads = YesNoSwitch( label=pgettext_lazy( "private threads permission", "Can moderate private threads" ), help_text=pgettext_lazy( "private threads permission", "Allows user to read, reply, edit and delete content in reported private threads.", ), ) def change_permissions_form(role): if isinstance(role, Role) and role.special_role != "anonymous": return PermissionsForm def build_acl(acl, roles, key_name): new_acl = { "can_use_private_threads": 0, "can_start_private_threads": 0, "max_private_thread_participants": 3, "can_add_everyone_to_private_threads": 0, "can_report_private_threads": 0, "can_moderate_private_threads": 0, } new_acl.update(acl) algebra.sum_acls( new_acl, roles=roles, key=key_name, can_use_private_threads=algebra.greater, can_start_private_threads=algebra.greater, max_private_thread_participants=algebra.greater_or_zero, can_add_everyone_to_private_threads=algebra.greater, can_report_private_threads=algebra.greater, can_moderate_private_threads=algebra.greater, ) if not new_acl["can_use_private_threads"]: new_acl["can_start_private_threads"] = 0 return new_acl private_category = Category.objects.private_threads() new_acl["visible_categories"].append(private_category.pk) new_acl["browseable_categories"].append(private_category.pk) if new_acl["can_moderate_private_threads"]: new_acl["can_see_reports"].append(private_category.pk) category_acl = { "can_see": 1, "can_browse": 1, "can_see_all_threads": 1, "can_see_own_threads": 0, "can_start_threads": new_acl["can_start_private_threads"], "can_reply_threads": 1, "can_edit_threads": 1, "can_edit_posts": 1, "can_hide_own_threads": 0, "can_hide_own_posts": 1, "thread_edit_time": 0, "post_edit_time": 0, "can_hide_threads": 0, "can_hide_posts": 0, "can_protect_posts": 0, "can_move_posts": 0, "can_merge_posts": 0, "can_pin_threads": 0, "can_close_threads": 0, "can_move_threads": 0, "can_merge_threads": 0, "can_approve_content": 0, "can_report_content": new_acl["can_report_private_threads"], "can_see_reports": 0, "can_see_posts_likes": 0, "can_like_posts": 0, "can_hide_events": 0, } if new_acl["can_moderate_private_threads"]: category_acl.update( { "can_edit_threads": 2, "can_edit_posts": 2, "can_hide_threads": 2, "can_hide_posts": 2, "can_protect_posts": 1, "can_merge_posts": 1, "can_see_reports": 1, "can_close_threads": 1, "can_hide_events": 2, } ) new_acl["categories"][private_category.pk] = category_acl return new_acl def add_acl_to_thread(user_acl, thread): if thread.thread_type.root_name != PRIVATE_THREADS_ROOT_NAME: return if not hasattr(thread, "participant"): thread.participants_list = [] thread.participant = None thread.acl.update( { "can_start_poll": False, "can_change_owner": can_change_owner(user_acl, thread), "can_add_participants": can_add_participants(user_acl, thread), } ) def register_with(registry): registry.acl_annotator(Thread, add_acl_to_thread) def allow_use_private_threads(user_acl): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy( "private threads permission", "You have to sign in to use private threads.", ) ) if not user_acl["can_use_private_threads"]: raise PermissionDenied( pgettext_lazy( "private threads permission", "You can't use private threads." ) ) can_use_private_threads = return_boolean(allow_use_private_threads) def allow_see_private_thread(user_acl, target, is_participant: bool | None = None): if user_acl["can_moderate_private_threads"]: can_see_reported = target.has_reported_posts else: can_see_reported = False if is_participant is not None: can_see_participating = is_participant else: can_see_participating = user_acl["user_id"] in [ p.user_id for p in target.participants_list ] if not (can_see_participating or can_see_reported): raise Http404() can_see_private_thread = return_boolean(allow_see_private_thread) def allow_change_owner(user_acl, target): is_moderator = user_acl["can_moderate_private_threads"] is_owner = target.participant and target.participant.is_owner if not (is_owner or is_moderator): raise PermissionDenied( pgettext_lazy( "private threads permission", "Only thread owner and moderators can appoint a new thread owner.", ) ) if not is_moderator and target.is_closed: raise PermissionDenied( pgettext_lazy( "private threads permission", "Only moderators can appoint a new thread owner in a closed thread.", ) ) can_change_owner = return_boolean(allow_change_owner) def allow_add_participants(user_acl, target): is_moderator = user_acl["can_moderate_private_threads"] if not is_moderator: if not target.participant or not target.participant.is_owner: raise PermissionDenied( pgettext_lazy( "private threads permission", "You have to be thread owner to add new participants to it.", ) ) if target.is_closed: raise PermissionDenied( pgettext_lazy( "private threads permission", "Only moderators can add participants to closed threads.", ) ) max_participants = user_acl["max_private_thread_participants"] current_participants = len(target.participants_list) - 1 if current_participants >= max_participants: raise PermissionDenied( pgettext_lazy( "private threads permission", "You can't add any more new users to this thread.", ) ) can_add_participants = return_boolean(allow_add_participants) def allow_remove_participant(user_acl, thread, target): if user_acl["can_moderate_private_threads"]: return if user_acl["user_id"] == target.id: return # we can always remove ourselves if thread.is_closed: raise PermissionDenied( pgettext_lazy( "private threads permission", "Only moderators can remove participants from closed threads.", ) ) if not thread.participant or not thread.participant.is_owner: raise PermissionDenied( pgettext_lazy( "private threads permission", "You have to be thread owner to remove participants from it.", ) ) can_remove_participant = return_boolean(allow_remove_participant) def allow_add_participant(user_acl, target, target_acl): message_format = {"user": target.username} if not can_use_private_threads(target_acl): raise PermissionDenied( pgettext_lazy( "private threads permission", "%(user)s can't participate in private threads.", ) % message_format ) if user_acl["can_add_everyone_to_private_threads"]: return if user_acl["can_be_blocked"] and target.is_blocking(user_acl["user_id"]): raise PermissionDenied( pgettext_lazy("private threads permission", "%(user)s is blocking you.") % message_format ) if target.can_be_messaged_by_nobody: raise PermissionDenied( pgettext_lazy( "private threads permission", "%(user)s has disabled invitations to private threads.", ) % message_format ) if target.can_be_messaged_by_followed and not target.is_following( user_acl["user_id"] ): message = pgettext_lazy( "private threads permission", "%(user)s limits invitations to private threads to followed users.", ) raise PermissionDenied(message % message_format) can_add_participant = return_boolean(allow_add_participant) def allow_message_user(user_acl, target, target_acl): allow_use_private_threads(user_acl) allow_add_participant(user_acl, target, target_acl) can_message_user = return_boolean(allow_message_user)
11,381
Python
.py
296
29.527027
117
0.623184
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,183
__init__.py
rafalp_Misago/misago/threads/permissions/__init__.py
from .bestanswers import * from .privatethreads import * from .threads import * from .polls import *
101
Python
.py
4
24.25
29
0.793814
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,184
threads.py
rafalp_Misago/misago/threads/permissions/threads.py
from django import forms from django.core.exceptions import PermissionDenied from django.db.models import Q from django.http import Http404 from django.utils import timezone from django.utils.translation import npgettext, pgettext_lazy from ...acl import algebra from ...acl.decorators import return_boolean from ...acl.models import Role from ...acl.objectacl import add_acl_to_obj from ...admin.forms import YesNoSwitch from ...categories.models import Category, CategoryRole from ...categories.permissions import get_categories_roles from ..models import Post, Thread __all__ = [ "allow_see_thread", "can_see_thread", "allow_start_thread", "can_start_thread", "allow_reply_thread", "can_reply_thread", "allow_edit_thread", "can_edit_thread", "allow_pin_thread", "can_pin_thread", "allow_unhide_thread", "can_unhide_thread", "allow_hide_thread", "can_hide_thread", "allow_delete_thread", "can_delete_thread", "allow_move_thread", "can_move_thread", "allow_merge_thread", "can_merge_thread", "allow_approve_thread", "can_approve_thread", "allow_see_post", "can_see_post", "allow_edit_post", "can_edit_post", "allow_unhide_post", "can_unhide_post", "allow_hide_post", "can_hide_post", "allow_delete_post", "can_delete_post", "allow_protect_post", "can_protect_post", "allow_approve_post", "can_approve_post", "allow_move_post", "can_move_post", "allow_merge_post", "can_merge_post", "allow_unhide_event", "can_unhide_event", "allow_split_post", "can_split_post", "allow_hide_event", "can_hide_event", "allow_delete_event", "can_delete_event", "exclude_invisible_threads", "exclude_invisible_posts", ] class RolePermissionsForm(forms.Form): legend = pgettext_lazy("threads permission", "Threads") can_see_unapproved_content_lists = YesNoSwitch( label=pgettext_lazy("threads permission", "Can see unapproved content list"), help_text=pgettext_lazy( "threads permission", 'Allows access to "unapproved" tab on threads lists for easy listing of threads that are unapproved or contain unapproved posts. Despite the tab being available on all threads lists, it will only display threads belonging to categories in which the user has permission to approve content.', ), ) can_see_reported_content_lists = YesNoSwitch( label=pgettext_lazy("threads permission", "Can see reported content list"), help_text=pgettext_lazy( "threads permission", 'Allows access to "reported" tab on threads lists for easy listing of threads that contain reported posts. Despite the tab being available on all categories threads lists, it will only display threads belonging to categories in which the user has permission to see posts reports.', ), ) can_omit_flood_protection = YesNoSwitch( label=pgettext_lazy("threads permission", "Can omit flood protection"), help_text=pgettext_lazy( "threads permission", "Allows posting more frequently than flood protection would.", ), ) class CategoryPermissionsForm(forms.Form): legend = pgettext_lazy("threads permission", "Threads") can_see_all_threads = forms.TypedChoiceField( label=pgettext_lazy("threads permission", "Can see threads"), coerce=int, initial=0, choices=[ (0, pgettext_lazy("threads see permission choice", "Started threads")), (1, pgettext_lazy("threads see permission choice", "All threads")), ], ) can_start_threads = YesNoSwitch( label=pgettext_lazy("threads permission", "Can start threads") ) can_reply_threads = YesNoSwitch( label=pgettext_lazy("threads permission", "Can reply to threads") ) can_edit_threads = forms.TypedChoiceField( label=pgettext_lazy("threads permission", "Can edit threads"), coerce=int, initial=0, choices=[ (0, pgettext_lazy("threads edit permission choice", "No")), (1, pgettext_lazy("threads edit permission choice", "Own threads")), (2, pgettext_lazy("threads edit permission choice", "All threads")), ], ) can_hide_own_threads = forms.TypedChoiceField( label=pgettext_lazy("threads permission", "Can hide own threads"), help_text=pgettext_lazy( "threads permission", "Only threads started within time limit and with no replies can be hidden.", ), coerce=int, initial=0, choices=[ (0, pgettext_lazy("threads hide own permission choice", "No")), (1, pgettext_lazy("threads hide own permission choice", "Hide threads")), (2, pgettext_lazy("threads hide own permission choice", "Delete threads")), ], ) thread_edit_time = forms.IntegerField( label=pgettext_lazy( "threads permission", "Time limit for editing own threads, in minutes" ), help_text=pgettext_lazy( "threads permission", "Enter 0 to don't limit time for editing own threads." ), initial=0, min_value=0, ) can_hide_threads = forms.TypedChoiceField( label=pgettext_lazy("threads permission", "Can hide all threads"), coerce=int, initial=0, choices=[ (0, pgettext_lazy("threads hide permission choice", "No")), (1, pgettext_lazy("threads hide permission choice", "Hide threads")), (2, pgettext_lazy("threads hide permission choice", "Delete threads")), ], ) can_pin_threads = forms.TypedChoiceField( label=pgettext_lazy("threads permission", "Can pin threads"), coerce=int, initial=0, choices=[ (0, pgettext_lazy("threads pin permission choice", "No")), (1, pgettext_lazy("threads pin permission choice", "In category")), (2, pgettext_lazy("threads pin permission choice", "Globally")), ], ) can_close_threads = YesNoSwitch( label=pgettext_lazy("threads permission", "Can close threads") ) can_move_threads = YesNoSwitch( label=pgettext_lazy("threads permission", "Can move threads") ) can_merge_threads = YesNoSwitch( label=pgettext_lazy("threads permission", "Can merge threads") ) can_edit_posts = forms.TypedChoiceField( label=pgettext_lazy("threads permission", "Can edit posts"), coerce=int, initial=0, choices=[ (0, pgettext_lazy("threads posts edit permission choice", "No")), (1, pgettext_lazy("threads posts edit permission choice", "Own posts")), (2, pgettext_lazy("threads posts edit permission choice", "All posts")), ], ) can_hide_own_posts = forms.TypedChoiceField( label=pgettext_lazy("threads permission", "Can hide own posts"), help_text=pgettext_lazy( "threads permission", "Only last posts to thread made within edit time limit can be hidden.", ), coerce=int, initial=0, choices=[ (0, pgettext_lazy("threads own posts hide permission choice", "No")), ( 1, pgettext_lazy("threads own posts hide permission choice", "Hide posts"), ), ( 2, pgettext_lazy( "threads own posts hide permission choice", "Delete posts" ), ), ], ) post_edit_time = forms.IntegerField( label=pgettext_lazy( "threads permission", "Time limit for editing own post, in minutes" ), help_text=pgettext_lazy( "threads permission", "Enter 0 to don't limit time for editing own posts." ), initial=0, min_value=0, ) can_hide_posts = forms.TypedChoiceField( label=pgettext_lazy("threads permission", "Can hide all posts"), coerce=int, initial=0, choices=[ (0, pgettext_lazy("threads hide posts permission choice", "No")), (1, pgettext_lazy("threads hide posts permission choice", "Hide posts")), (2, pgettext_lazy("threads hide posts permission choice", "Delete posts")), ], ) can_see_posts_likes = forms.TypedChoiceField( label=pgettext_lazy("threads permission", "Can see posts likes"), coerce=int, initial=0, choices=[ (0, pgettext_lazy("threads posts like see permission choice", "No")), ( 1, pgettext_lazy( "threads posts like see permission choice", "Number only" ), ), ( 2, pgettext_lazy( "threads posts like see permission choice", "Number and list of likers", ), ), ], ) can_like_posts = YesNoSwitch( label=pgettext_lazy("threads permission", "Can like posts"), help_text=pgettext_lazy( "threads permission", "Only users with this permission to see likes can like posts.", ), ) can_protect_posts = YesNoSwitch( label=pgettext_lazy("threads permission", "Can protect posts"), help_text=pgettext_lazy( "threads permission", "Only users with this permission can edit protected posts.", ), ) can_move_posts = YesNoSwitch( label=pgettext_lazy("threads permission", "Can move posts"), help_text=pgettext_lazy( "threads permission", "Will be able to move posts to other threads." ), ) can_merge_posts = YesNoSwitch( label=pgettext_lazy("threads permission", "Can merge posts") ) can_approve_content = YesNoSwitch( label=pgettext_lazy("threads permission", "Can approve content"), help_text=pgettext_lazy( "threads permission", "Will be able to see and approve unapproved content." ), ) can_report_content = YesNoSwitch( label=pgettext_lazy("threads permission", "Can report posts") ) can_see_reports = YesNoSwitch( label=pgettext_lazy("threads permission", "Can see reports") ) can_hide_events = forms.TypedChoiceField( label=pgettext_lazy("threads permission", "Can hide events"), coerce=int, initial=0, choices=[ (0, pgettext_lazy("threads events hide permission choice", "No")), (1, pgettext_lazy("threads events hide permission choice", "Hide events")), ( 2, pgettext_lazy("threads events hide permission choice", "Delete events"), ), ], ) require_threads_approval = YesNoSwitch( label=pgettext_lazy("threads permission", "Require threads approval") ) require_replies_approval = YesNoSwitch( label=pgettext_lazy("threads permission", "Require replies approval") ) require_edits_approval = YesNoSwitch( label=pgettext_lazy("threads permission", "Require edits approval") ) def change_permissions_form(role): if isinstance(role, Role) and role.special_role != "anonymous": return RolePermissionsForm if isinstance(role, CategoryRole): return CategoryPermissionsForm def build_acl(acl, roles, key_name): acl.update( { "can_see_unapproved_content_lists": False, "can_see_reported_content_lists": False, "can_omit_flood_protection": False, "can_approve_content": [], "can_see_reports": [], } ) acl = algebra.sum_acls( acl, roles=roles, key=key_name, can_see_unapproved_content_lists=algebra.greater, can_see_reported_content_lists=algebra.greater, can_omit_flood_protection=algebra.greater, ) categories_roles = get_categories_roles(roles) categories = list(Category.objects.all_categories(include_root=True)) for category in categories: category_acl = acl["categories"].get(category.pk, {"can_browse": 0}) if category_acl["can_browse"]: category_acl = acl["categories"][category.pk] = build_category_acl( category_acl, category, categories_roles, key_name ) if category_acl.get("can_approve_content"): acl["can_approve_content"].append(category.pk) if category_acl.get("can_see_reports"): acl["can_see_reports"].append(category.pk) return acl def build_category_acl(acl, category, categories_roles, key_name): category_roles = categories_roles.get(category.pk, []) final_acl = { "can_see_all_threads": 0, "can_start_threads": 0, "can_reply_threads": 0, "can_edit_threads": 0, "can_edit_posts": 0, "can_hide_own_threads": 0, "can_hide_own_posts": 0, "thread_edit_time": 0, "post_edit_time": 0, "can_hide_threads": 0, "can_hide_posts": 0, "can_protect_posts": 0, "can_move_posts": 0, "can_merge_posts": 0, "can_pin_threads": 0, "can_close_threads": 0, "can_move_threads": 0, "can_merge_threads": 0, "can_report_content": 0, "can_see_reports": 0, "can_see_posts_likes": 0, "can_like_posts": 0, "can_approve_content": 0, "require_threads_approval": 0, "require_replies_approval": 0, "require_edits_approval": 0, "can_hide_events": 0, } final_acl.update(acl) algebra.sum_acls( final_acl, roles=category_roles, key=key_name, can_see_all_threads=algebra.greater, can_start_threads=algebra.greater, can_reply_threads=algebra.greater, can_edit_threads=algebra.greater, can_edit_posts=algebra.greater, can_hide_threads=algebra.greater, can_hide_posts=algebra.greater, can_hide_own_threads=algebra.greater, can_hide_own_posts=algebra.greater, thread_edit_time=algebra.greater_or_zero, post_edit_time=algebra.greater_or_zero, can_protect_posts=algebra.greater, can_move_posts=algebra.greater, can_merge_posts=algebra.greater, can_pin_threads=algebra.greater, can_close_threads=algebra.greater, can_move_threads=algebra.greater, can_merge_threads=algebra.greater, can_report_content=algebra.greater, can_see_reports=algebra.greater, can_see_posts_likes=algebra.greater, can_like_posts=algebra.greater, can_approve_content=algebra.greater, require_threads_approval=algebra.greater, require_replies_approval=algebra.greater, require_edits_approval=algebra.greater, can_hide_events=algebra.greater, ) return final_acl def add_acl_to_category(user_acl, category): category_acl = user_acl["categories"].get(category.pk, {}) category.acl.update( { "can_see_all_threads": 0, "can_see_own_threads": 0, "can_start_threads": 0, "can_reply_threads": 0, "can_edit_threads": 0, "can_edit_posts": 0, "can_hide_own_threads": 0, "can_hide_own_posts": 0, "thread_edit_time": 0, "post_edit_time": 0, "can_hide_threads": 0, "can_hide_posts": 0, "can_protect_posts": 0, "can_move_posts": 0, "can_merge_posts": 0, "can_pin_threads": 0, "can_close_threads": 0, "can_move_threads": 0, "can_merge_threads": 0, "can_report_content": 0, "can_see_reports": 0, "can_see_posts_likes": 0, "can_like_posts": 0, "can_approve_content": 0, "require_threads_approval": category.require_threads_approval, "require_replies_approval": category.require_replies_approval, "require_edits_approval": category.require_edits_approval, "can_hide_events": 0, } ) algebra.sum_acls( category.acl, acls=[category_acl], can_see_all_threads=algebra.greater, can_see_posts_likes=algebra.greater, ) if user_acl["is_authenticated"]: algebra.sum_acls( category.acl, acls=[category_acl], can_start_threads=algebra.greater, can_reply_threads=algebra.greater, can_edit_threads=algebra.greater, can_edit_posts=algebra.greater, can_hide_threads=algebra.greater, can_hide_posts=algebra.greater, can_hide_own_threads=algebra.greater, can_hide_own_posts=algebra.greater, thread_edit_time=algebra.greater_or_zero, post_edit_time=algebra.greater_or_zero, can_protect_posts=algebra.greater, can_move_posts=algebra.greater, can_merge_posts=algebra.greater, can_pin_threads=algebra.greater, can_close_threads=algebra.greater, can_move_threads=algebra.greater, can_merge_threads=algebra.greater, can_report_content=algebra.greater, can_see_reports=algebra.greater, can_like_posts=algebra.greater, can_approve_content=algebra.greater, require_threads_approval=algebra.greater, require_replies_approval=algebra.greater, require_edits_approval=algebra.greater, can_hide_events=algebra.greater, ) if user_acl["can_approve_content"]: category.acl.update( { "require_threads_approval": 0, "require_replies_approval": 0, "require_edits_approval": 0, } ) category.acl["can_see_own_threads"] = not category.acl["can_see_all_threads"] def add_acl_to_thread(user_acl, thread): category_acl = user_acl["categories"].get(thread.category_id, {}) thread.acl.update( { "can_reply": can_reply_thread(user_acl, thread), "can_edit": can_edit_thread(user_acl, thread), "can_pin": can_pin_thread(user_acl, thread), "can_pin_globally": False, "can_hide": can_hide_thread(user_acl, thread), "can_unhide": can_unhide_thread(user_acl, thread), "can_delete": can_delete_thread(user_acl, thread), "can_close": category_acl.get("can_close_threads", False), "can_move": can_move_thread(user_acl, thread), "can_merge": can_merge_thread(user_acl, thread), "can_move_posts": category_acl.get("can_move_posts", False), "can_merge_posts": category_acl.get("can_merge_posts", False), "can_approve": can_approve_thread(user_acl, thread), "can_see_reports": category_acl.get("can_see_reports", False), } ) if thread.acl["can_pin"] and category_acl.get("can_pin_threads") == 2: thread.acl["can_pin_globally"] = True def add_acl_to_post(user_acl, post): if post.is_event: add_acl_to_event(user_acl, post) else: add_acl_to_reply(user_acl, post) def add_acl_to_event(user_acl, event): can_hide_events = 0 if user_acl["is_authenticated"]: category_acl = user_acl["categories"].get( event.category_id, {"can_hide_events": 0} ) can_hide_events = category_acl["can_hide_events"] event.acl.update( { "can_see_hidden": can_hide_events > 0, "can_hide": can_hide_event(user_acl, event), "can_delete": can_delete_event(user_acl, event), } ) def add_acl_to_reply(user_acl, post): category_acl = user_acl["categories"].get(post.category_id, {}) post.acl.update( { "can_reply": can_reply_thread(user_acl, post.thread), "can_edit": can_edit_post(user_acl, post), "can_see_hidden": post.is_first_post or category_acl.get("can_hide_posts"), "can_unhide": can_unhide_post(user_acl, post), "can_hide": can_hide_post(user_acl, post), "can_delete": can_delete_post(user_acl, post), "can_protect": can_protect_post(user_acl, post), "can_approve": can_approve_post(user_acl, post), "can_move": can_move_post(user_acl, post), "can_merge": can_merge_post(user_acl, post), "can_report": category_acl.get("can_report_content", False), "can_see_reports": category_acl.get("can_see_reports", False), "can_see_likes": category_acl.get("can_see_posts_likes", 0), "can_like": False, "can_see_protected": False, } ) if not post.acl["can_see_hidden"]: post.acl["can_see_hidden"] = post.id == post.thread.first_post_id if user_acl["is_authenticated"] and post.acl["can_see_likes"]: post.acl["can_like"] = category_acl.get("can_like_posts", False) if user_acl["is_authenticated"]: post.acl["can_see_protected"] = ( post.acl["can_protect"] or user_acl["user_id"] == post.poster_id ) def register_with(registry): registry.acl_annotator(Category, add_acl_to_category) registry.acl_annotator(Thread, add_acl_to_thread) registry.acl_annotator(Post, add_acl_to_post) def allow_see_thread(user_acl, target): category_acl = user_acl["categories"].get( target.category_id, {"can_see": False, "can_browse": False} ) if not (category_acl["can_see"] and category_acl["can_browse"]): raise Http404() if target.is_hidden and ( user_acl["is_anonymous"] or not category_acl["can_hide_threads"] ): raise Http404() if user_acl["is_anonymous"] or user_acl["user_id"] != target.starter_id: if not category_acl["can_see_all_threads"]: raise Http404() if target.is_unapproved and not category_acl["can_approve_content"]: raise Http404() can_see_thread = return_boolean(allow_see_thread) def allow_start_thread(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to start threads.") ) category_acl = user_acl["categories"].get(target.pk, {"can_start_threads": False}) if not category_acl["can_start_threads"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You don't have permission to start new threads in this category.", ) ) if target.is_closed and not category_acl["can_close_threads"]: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't start new threads in it.", ) ) can_start_thread = return_boolean(allow_start_thread) def allow_reply_thread(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to reply threads.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_reply_threads": False} ) if not category_acl["can_reply_threads"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't reply to threads in this category." ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't reply to threads in it.", ) ) if target.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't reply to closed threads in this category.", ) ) can_reply_thread = return_boolean(allow_reply_thread) def allow_edit_thread(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to edit threads.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_edit_threads": False} ) if not category_acl["can_edit_threads"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't edit threads in this category." ) ) if category_acl["can_edit_threads"] == 1: if user_acl["user_id"] != target.starter_id: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't edit other users threads in this category.", ) ) if not has_time_to_edit_thread(user_acl, target): message = npgettext( "threads permission", "You can't edit threads that are older than %(minutes)s minute.", "You can't edit threads that are older than %(minutes)s minutes.", category_acl["thread_edit_time"], ) raise PermissionDenied( message % {"minutes": category_acl["thread_edit_time"]} ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't edit threads in it.", ) ) if target.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't edit it." ) ) can_edit_thread = return_boolean(allow_edit_thread) def allow_pin_thread(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You have to sign in to change threads weights." ) ) category_acl = user_acl["categories"].get( target.category_id, {"can_pin_threads": 0} ) if not category_acl["can_pin_threads"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't change threads weights in this category.", ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't change threads weights in it.", ) ) if target.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't change its weight.", ) ) can_pin_thread = return_boolean(allow_pin_thread) def allow_unhide_thread(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to hide threads.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_close_threads": False} ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't reveal threads in it.", ) ) if target.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't reveal it." ) ) can_unhide_thread = return_boolean(allow_unhide_thread) def allow_hide_thread(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to hide threads.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_hide_threads": 0, "can_hide_own_threads": 0} ) if ( not category_acl["can_hide_threads"] and not category_acl["can_hide_own_threads"] ): raise PermissionDenied( pgettext_lazy( "threads permission", "You can't hide threads in this category." ) ) if not category_acl["can_hide_threads"] and category_acl["can_hide_own_threads"]: if user_acl["user_id"] != target.starter_id: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't hide other users theads in this category.", ) ) if not has_time_to_edit_thread(user_acl, target): message = npgettext( "threads permission", "You can't hide threads that are older than %(minutes)s minute.", "You can't hide threads that are older than %(minutes)s minutes.", category_acl["thread_edit_time"], ) raise PermissionDenied( message % {"minutes": category_acl["thread_edit_time"]} ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't hide threads in it.", ) ) if target.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't hide it." ) ) can_hide_thread = return_boolean(allow_hide_thread) def allow_delete_thread(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You have to sign in to delete threads." ) ) category_acl = user_acl["categories"].get( target.category_id, {"can_hide_threads": 0, "can_hide_own_threads": 0} ) if ( category_acl["can_hide_threads"] != 2 and category_acl["can_hide_own_threads"] != 2 ): raise PermissionDenied( pgettext_lazy( "threads permission", "You can't delete threads in this category." ) ) if ( category_acl["can_hide_threads"] != 2 and category_acl["can_hide_own_threads"] == 2 ): if user_acl["user_id"] != target.starter_id: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't delete other users theads in this category.", ) ) if not has_time_to_edit_thread(user_acl, target): message = npgettext( "threads permission", "You can't delete threads that are older than %(minutes)s minute.", "You can't delete threads that are older than %(minutes)s minutes.", category_acl["thread_edit_time"], ) raise PermissionDenied( message % {"minutes": category_acl["thread_edit_time"]} ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't delete threads in it.", ) ) if target.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't delete it." ) ) can_delete_thread = return_boolean(allow_delete_thread) def allow_move_thread(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to move threads.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_move_threads": 0} ) if not category_acl["can_move_threads"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't move threads in this category." ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't move it's threads.", ) ) if target.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't move it." ) ) can_move_thread = return_boolean(allow_move_thread) def allow_merge_thread(user_acl, target, otherthread=False): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to merge threads.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_merge_threads": 0} ) if not category_acl["can_merge_threads"]: if otherthread: raise PermissionDenied( pgettext_lazy( "threads permission", "Other thread can't be merged with." ) ) raise PermissionDenied( pgettext_lazy( "threads permission", "You can't merge threads in this category." ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: if otherthread: raise PermissionDenied( pgettext_lazy( "threads permission", "Other thread's category is closed. You can't merge with it.", ) ) raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't merge it's threads.", ) ) if target.is_closed: if otherthread: raise PermissionDenied( pgettext_lazy( "threads permission", "Other thread is closed and can't be merged with.", ) ) raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't merge it with other threads.", ) ) can_merge_thread = return_boolean(allow_merge_thread) def allow_approve_thread(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You have to sign in to approve threads." ) ) category_acl = user_acl["categories"].get( target.category_id, {"can_approve_content": 0} ) if not category_acl["can_approve_content"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't approve threads in this category." ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't approve threads in it.", ) ) if target.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't approve it." ) ) can_approve_thread = return_boolean(allow_approve_thread) def allow_see_post(user_acl, target): category_acl = user_acl["categories"].get( target.category_id, {"can_approve_content": False, "can_hide_events": False} ) if not target.is_event and target.is_unapproved: if user_acl["is_anonymous"]: raise Http404() if ( not category_acl["can_approve_content"] and user_acl["user_id"] != target.poster_id ): raise Http404() if target.is_event and target.is_hidden and not category_acl["can_hide_events"]: raise Http404() can_see_post = return_boolean(allow_see_post) def allow_edit_post(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to edit posts.") ) if target.is_event: raise PermissionDenied( pgettext_lazy("threads permission", "Events can't be edited.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_edit_posts": False} ) if not category_acl["can_edit_posts"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't edit posts in this category." ) ) if ( target.is_hidden and not target.is_first_post and not category_acl["can_hide_posts"] ): raise PermissionDenied( pgettext_lazy( "threads permission", "This post is hidden, you can't edit it." ) ) if category_acl["can_edit_posts"] == 1: if target.poster_id != user_acl["user_id"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't edit other users posts in this category.", ) ) if target.is_protected and not category_acl["can_protect_posts"]: raise PermissionDenied( pgettext_lazy( "threads permission", "This post is protected. You can't edit it." ) ) if not has_time_to_edit_post(user_acl, target): message = npgettext( "threads permission", "You can't edit posts that are older than %(minutes)s minute.", "You can't edit posts that are older than %(minutes)s minutes.", category_acl["post_edit_time"], ) raise PermissionDenied( message % {"minutes": category_acl["post_edit_time"]} ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't edit posts in it.", ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't edit posts in it.", ) ) can_edit_post = return_boolean(allow_edit_post) def allow_unhide_post(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to reveal posts.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_hide_posts": 0, "can_hide_own_posts": 0} ) if not category_acl["can_hide_posts"]: if not category_acl["can_hide_own_posts"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't reveal posts in this category." ) ) if user_acl["user_id"] != target.poster_id: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't reveal other users posts in this category.", ) ) if target.is_protected and not category_acl["can_protect_posts"]: raise PermissionDenied( pgettext_lazy( "threads permission", "This post is protected. You can't reveal it." ) ) if not has_time_to_edit_post(user_acl, target): message = npgettext( "threads permission", "You can't reveal posts that are older than %(minutes)s minute.", "You can't reveal posts that are older than %(minutes)s minutes.", category_acl["post_edit_time"], ) raise PermissionDenied( message % {"minutes": category_acl["post_edit_time"]} ) if target.is_first_post: raise PermissionDenied( pgettext_lazy( "threads permission", "Thread's first post can only be revealed using the reveal thread option.", ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't reveal posts in it.", ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't reveal posts in it.", ) ) can_unhide_post = return_boolean(allow_unhide_post) def allow_hide_post(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to hide posts.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_hide_posts": 0, "can_hide_own_posts": 0} ) if not category_acl["can_hide_posts"]: if not category_acl["can_hide_own_posts"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't hide posts in this category." ) ) if user_acl["user_id"] != target.poster_id: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't hide other users posts in this category.", ) ) if target.is_protected and not category_acl["can_protect_posts"]: raise PermissionDenied( pgettext_lazy( "threads permission", "This post is protected. You can't hide it." ) ) if not has_time_to_edit_post(user_acl, target): message = npgettext( "threads permission", "You can't hide posts that are older than %(minutes)s minute.", "You can't hide posts that are older than %(minutes)s minutes.", category_acl["post_edit_time"], ) raise PermissionDenied( message % {"minutes": category_acl["post_edit_time"]} ) if target.is_first_post: raise PermissionDenied( pgettext_lazy( "threads permission", "Thread's first post can only be hidden using the hide thread option.", ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't hide posts in it.", ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't hide posts in it.", ) ) can_hide_post = return_boolean(allow_hide_post) def allow_delete_post(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to delete posts.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_hide_posts": 0, "can_hide_own_posts": 0} ) if category_acl["can_hide_posts"] != 2: if category_acl["can_hide_own_posts"] != 2: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't delete posts in this category." ) ) if user_acl["user_id"] != target.poster_id: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't delete other users posts in this category.", ) ) if target.is_protected and not category_acl["can_protect_posts"]: raise PermissionDenied( pgettext_lazy( "threads permission", "This post is protected. You can't delete it." ) ) if not has_time_to_edit_post(user_acl, target): message = npgettext( "threads permission", "You can't delete posts that are older than %(minutes)s minute.", "You can't delete posts that are older than %(minutes)s minutes.", category_acl["post_edit_time"], ) raise PermissionDenied( message % {"minutes": category_acl["post_edit_time"]} ) if target.is_first_post: raise PermissionDenied( pgettext_lazy( "threads permission", "Thread's first post can only be deleted together with thread.", ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't delete posts in it.", ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't delete posts in it.", ) ) can_delete_post = return_boolean(allow_delete_post) def allow_protect_post(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to protect posts.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_protect_posts": False} ) if not category_acl["can_protect_posts"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't protect posts in this category." ) ) if not can_edit_post(user_acl, target): raise PermissionDenied( pgettext_lazy( "threads permission", "You can't protect posts you can't edit." ) ) can_protect_post = return_boolean(allow_protect_post) def allow_approve_post(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to approve posts.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_approve_content": False} ) if not category_acl["can_approve_content"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't approve posts in this category." ) ) if target.is_first_post: raise PermissionDenied( pgettext_lazy( "threads permission", "Thread's first post can only be approved together with thread.", ) ) if ( not target.is_first_post and not category_acl["can_hide_posts"] and target.is_hidden ): raise PermissionDenied( pgettext_lazy( "threads permission", "You can't approve posts the content you can't see.", ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't approve posts in it.", ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't approve posts in it.", ) ) can_approve_post = return_boolean(allow_approve_post) def allow_move_post(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to move posts.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_move_posts": False} ) if not category_acl["can_move_posts"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't move posts in this category." ) ) if target.is_event: raise PermissionDenied( pgettext_lazy("threads permission", "Events can't be moved.") ) if target.is_first_post: raise PermissionDenied( pgettext_lazy( "threads permission", "Thread's first post can only be moved together with thread.", ) ) if not category_acl["can_hide_posts"] and target.is_hidden: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't move posts the content you can't see." ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't move posts in it.", ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't move posts in it.", ) ) can_move_post = return_boolean(allow_move_post) def allow_merge_post(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to merge posts.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_merge_posts": False} ) if not category_acl["can_merge_posts"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't merge posts in this category." ) ) if target.is_event: raise PermissionDenied( pgettext_lazy("threads permission", "Events can't be merged.") ) if ( target.is_hidden and not category_acl["can_hide_posts"] and not target.is_first_post ): raise PermissionDenied( pgettext_lazy( "threads permission", "You can't merge posts the content you can't see." ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't merge posts in it.", ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't merge posts in it.", ) ) can_merge_post = return_boolean(allow_merge_post) def allow_split_post(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to split posts.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_move_posts": False} ) if not category_acl["can_move_posts"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't split posts in this category." ) ) if target.is_event: raise PermissionDenied( pgettext_lazy("threads permission", "Events can't be split.") ) if target.is_first_post: raise PermissionDenied( pgettext_lazy("threads permission", "Thread's first post can't be split.") ) if not category_acl["can_hide_posts"] and target.is_hidden: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't split posts the content you can't see." ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't split posts in it.", ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't split posts in it.", ) ) can_split_post = return_boolean(allow_split_post) def allow_unhide_event(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to reveal events.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_hide_events": 0} ) if not category_acl["can_hide_events"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't reveal events in this category." ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't reveal events in it.", ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't reveal events in it.", ) ) can_unhide_event = return_boolean(allow_unhide_event) def allow_hide_event(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to hide events.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_hide_events": 0} ) if not category_acl["can_hide_events"]: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't hide events in this category." ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't hide events in it.", ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't hide events in it.", ) ) can_hide_event = return_boolean(allow_hide_event) def allow_delete_event(user_acl, target): if user_acl["is_anonymous"]: raise PermissionDenied( pgettext_lazy("threads permission", "You have to sign in to delete events.") ) category_acl = user_acl["categories"].get( target.category_id, {"can_hide_events": 0} ) if category_acl["can_hide_events"] != 2: raise PermissionDenied( pgettext_lazy( "threads permission", "You can't delete events in this category." ) ) if not category_acl["can_close_threads"]: if target.category.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This category is closed. You can't delete events in it.", ) ) if target.thread.is_closed: raise PermissionDenied( pgettext_lazy( "threads permission", "This thread is closed. You can't delete events in it.", ) ) can_delete_event = return_boolean(allow_delete_event) def can_change_owned_thread(user_acl, target): if user_acl["is_anonymous"] or user_acl["user_id"] != target.starter_id: return False if target.category.is_closed or target.is_closed: return False return has_time_to_edit_thread(user_acl, target) def has_time_to_edit_thread(user_acl, target): edit_time = ( user_acl["categories"].get(target.category_id, {}).get("thread_edit_time", 0) ) if edit_time: diff = timezone.now() - target.started_on diff_minutes = int(diff.total_seconds() / 60) return diff_minutes < edit_time return True def has_time_to_edit_post(user_acl, target): edit_time = ( user_acl["categories"].get(target.category_id, {}).get("post_edit_time", 0) ) if edit_time: diff = timezone.now() - target.posted_on diff_minutes = int(diff.total_seconds() / 60) return diff_minutes < edit_time return True def exclude_invisible_threads( user_acl, categories, queryset ): # pylint: disable=too-many-branches show_all = [] show_accepted_visible = [] show_accepted = [] show_visible = [] show_owned = [] show_owned_visible = [] for category in categories: add_acl_to_obj(user_acl, category) if not (category.acl["can_see"] and category.acl["can_browse"]): continue can_hide = category.acl["can_hide_threads"] if category.acl["can_see_all_threads"]: can_mod = category.acl["can_approve_content"] if can_mod and can_hide: show_all.append(category) elif user_acl["is_authenticated"]: if not can_mod and not can_hide: show_accepted_visible.append(category) elif not can_mod: show_accepted.append(category) elif not can_hide: show_visible.append(category) else: show_accepted_visible.append(category) elif user_acl["is_authenticated"]: if can_hide: show_owned.append(category) else: show_owned_visible.append(category) conditions = None if show_all: conditions = Q(category__in=show_all) if show_accepted_visible: if user_acl["is_authenticated"]: condition = Q( Q(starter_id=user_acl["user_id"]) | Q(is_unapproved=False), category__in=show_accepted_visible, is_hidden=False, ) else: condition = Q( category__in=show_accepted_visible, is_hidden=False, is_unapproved=False ) if conditions: conditions = conditions | condition else: conditions = condition if show_accepted: condition = Q( Q(starter_id=user_acl["user_id"]) | Q(is_unapproved=False), category__in=show_accepted, ) if conditions: conditions = conditions | condition else: conditions = condition if show_visible: condition = Q(category__in=show_visible, is_hidden=False) if conditions: conditions = conditions | condition else: conditions = condition if show_owned: condition = Q(category__in=show_owned, starter_id=user_acl["user_id"]) if conditions: conditions = conditions | condition else: conditions = condition if show_owned_visible: condition = Q( category__in=show_owned_visible, starter_id=user_acl["user_id"], is_hidden=False, ) if conditions: conditions = conditions | condition else: conditions = condition if not conditions: return Thread.objects.none() return queryset.filter(conditions) def exclude_invisible_posts(user_acl, categories, queryset): if hasattr(categories, "__iter__"): return exclude_invisible_posts_in_categories(user_acl, categories, queryset) return exclude_invisible_posts_in_category(user_acl, categories, queryset) def exclude_invisible_posts_in_categories( user_acl, categories, queryset ): # pylint: disable=too-many-branches show_all = [] show_approved = [] show_approved_owned = [] hide_invisible_events = [] for category in categories: add_acl_to_obj(user_acl, category) if category.acl["can_approve_content"]: show_all.append(category.pk) else: if user_acl["is_authenticated"]: show_approved_owned.append(category.pk) else: show_approved.append(category.pk) if not category.acl["can_hide_events"]: hide_invisible_events.append(category.pk) conditions = None if show_all: conditions = Q(category__in=show_all) if show_approved: condition = Q(category__in=show_approved, is_unapproved=False) if conditions: conditions = conditions | condition else: conditions = condition if show_approved_owned: condition = Q( Q(poster_id=user_acl["user_id"]) | Q(is_unapproved=False), category__in=show_approved_owned, ) if conditions: conditions = conditions | condition else: conditions = condition if hide_invisible_events: queryset = queryset.exclude( category__in=hide_invisible_events, is_event=True, is_hidden=True ) if not conditions: return Post.objects.none() return queryset.filter(conditions) def exclude_invisible_posts_in_category(user_acl, category, queryset): add_acl_to_obj(user_acl, category) if not category.acl["can_approve_content"]: if user_acl["is_authenticated"]: queryset = queryset.filter( Q(is_unapproved=False) | Q(poster_id=user_acl["user_id"]) ) else: queryset = queryset.exclude(is_unapproved=True) if not category.acl["can_hide_events"]: queryset = queryset.exclude(is_event=True, is_hidden=True) return queryset
64,478
Python
.py
1,665
27.864865
302
0.57285
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,185
attachments.py
rafalp_Misago/misago/threads/permissions/attachments.py
from django import forms from django.utils.translation import pgettext_lazy from ...acl import algebra from ...acl.models import Role from ...admin.forms import YesNoSwitch from ..models import Attachment # Admin Permissions Forms class PermissionsForm(forms.Form): legend = pgettext_lazy("attachments permission", "Attachments") max_attachment_size = forms.IntegerField( label=pgettext_lazy("attachments permission", "Max attached file size (in kb)"), help_text=pgettext_lazy( "permissions", "Enter 0 to don't allow uploading end deleting attachments." ), initial=500, min_value=0, ) can_download_other_users_attachments = YesNoSwitch( label=pgettext_lazy( "attachments permission", "Can download other users attachments" ) ) can_delete_other_users_attachments = YesNoSwitch( label=pgettext_lazy( "attachments permission", "Can delete other users attachments" ) ) class AnonymousPermissionsForm(forms.Form): legend = pgettext_lazy("attachments permission", "Attachments") can_download_other_users_attachments = YesNoSwitch( label=pgettext_lazy("attachments permission", "Can download attachments") ) def change_permissions_form(role): if isinstance(role, Role): if role.special_role == "anonymous": return AnonymousPermissionsForm return PermissionsForm def build_acl(acl, roles, key_name): new_acl = { "max_attachment_size": 0, "can_download_other_users_attachments": False, "can_delete_other_users_attachments": False, } new_acl.update(acl) return algebra.sum_acls( new_acl, roles=roles, key=key_name, max_attachment_size=algebra.greater, can_download_other_users_attachments=algebra.greater, can_delete_other_users_attachments=algebra.greater, ) def add_acl_to_attachment(user_acl, attachment): if user_acl["is_authenticated"] and user_acl["user_id"] == attachment.uploader_id: attachment.acl.update({"can_delete": True}) else: user_can_delete = user_acl["can_delete_other_users_attachments"] attachment.acl.update( {"can_delete": user_acl["is_authenticated"] and user_can_delete} ) def register_with(registry): registry.acl_annotator(Attachment, add_acl_to_attachment)
2,427
Python
.py
62
32.451613
88
0.690375
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,186
get_private_thread_replies_page_context_data.py
rafalp_Misago/misago/threads/hooks/get_private_thread_replies_page_context_data.py
from typing import Protocol from django.http import HttpRequest from ...plugins.hooks import FilterHook from ..models import Thread class GetPrivateThreadRepliesPageContextDataHookAction(Protocol): """ A standard Misago function used to get the template context data for the private thread replies page. # Arguments ## `request: HttpRequest` The request object. ## `thread: Thread` A `Thread` instance. ## `page: int | None = None` An `int` with page number or `None`. # Return value A Python `dict` with context data to use to `render` the private thread replies page. """ def __call__( self, request: HttpRequest, thread: Thread, page: int | None = None, ) -> dict: ... class GetPrivateThreadRepliesPageContextDataHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetPrivateThreadRepliesPageContextDataHookAction` A standard Misago function used to get the template context data for the private thread replies page. See the [action](#action) section for details. ## `request: HttpRequest` The request object. ## `thread: Thread` A `Thread` instance. ## `page: int | None = None` An `int` with page number or `None`. # Return value A Python `dict` with context data to use to `render` the private thread replies page. """ def __call__( self, action: GetPrivateThreadRepliesPageContextDataHookAction, request: HttpRequest, thread: Thread, page: int | None = None, ) -> dict: ... class GetPrivateThreadRepliesPageContextDataHook( FilterHook[ GetPrivateThreadRepliesPageContextDataHookAction, GetPrivateThreadRepliesPageContextDataHookFilter, ] ): """ This hook wraps the standard function that Misago uses to get the template context data for the private thread replies page. # Example The code below implements a custom filter function that adds custom context data to the thread replies page: ```python from django.http import HttpRequest from misago.threads.hooks import get_private_thread_replies_page_context_data_hook from misago.threads.models import Thread @get_private_thread_replies_page_context_data_hook.append_filter def include_custom_context( action, request: HttpRequest, thread: dict, page: int | None = None, ) -> dict: context = action(request, thread, page) context["plugin_data"] = "..." return context ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetPrivateThreadRepliesPageContextDataHookAction, request: HttpRequest, thread: Thread, page: int | None = None, ) -> dict: return super().__call__(action, request, thread, page) get_private_thread_replies_page_context_data_hook = ( GetPrivateThreadRepliesPageContextDataHook() )
3,102
Python
.py
90
28.377778
86
0.685185
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,187
get_thread_url.py
rafalp_Misago/misago/threads/hooks/get_thread_url.py
from typing import Protocol from django.db.models import QuerySet from django.http import HttpRequest from ...categories.models import Category from ...plugins.hooks import FilterHook from ..models import Thread class GetThreadUrlHookAction(Protocol): """ A standard Misago function used to retrieve a thread URL based on its category type. # Arguments ## `thread: Thread` A `Thread` instance. ## `category: Category` A `Category` instance, if `thread.category` was not populated using `select_related` or `prefetch_related`. Otherwise it's `None` and `thread.category` should be used instead. # Return value An `str` with URL. """ def __call__( self, thread: Thread, category: Category | None = None ) -> QuerySet: ... class GetThreadUrlHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetThreadUrlHookAction` A standard Misago function used to retrieve a thread URL based on its category type. See the [action](#action) section for details. ## `thread: Thread` A `Thread` instance. ## `category: Category` A `Category` instance, if `thread.category` was not populated using `select_related` or `prefetch_related`. Otherwise it's `None` and `thread.category` should be used instead. # Return value An `str` with URL. """ def __call__( self, action: GetThreadUrlHookAction, thread: Thread, category: Category | None = None, ) -> QuerySet: ... class GetThreadUrlHook( FilterHook[ GetThreadUrlHookAction, GetThreadUrlHookFilter, ] ): """ This hook wraps the standard function that Misago useds to retrieve a thread URL based on its category type. # Example The code below implements a custom filter function that returns thread's URL for custom category type: ```python from django.urls import reverse from misago.categories.models import Category from misago.threads.hooks import get_thread_url_hook from misago.threads.models import Thread @get_thread_url_hook.append_filter def get_thread_blog_url( action, thread: Thread, category: Category | None = None ): if (category or thread.category).plugin_data.get("is_blog"): return reverse( "blog", kwargs={"id": thread.id, "slug": thread.slug} ) return = action(thread, category) ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetThreadUrlHookAction, thread: Thread, category: Category | None = None, ) -> dict: return super().__call__(action, thread, category) get_thread_url_hook = GetThreadUrlHook()
2,850
Python
.py
81
29.185185
88
0.674597
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,188
get_private_thread_replies_page_thread_queryset.py
rafalp_Misago/misago/threads/hooks/get_private_thread_replies_page_thread_queryset.py
from typing import Protocol from django.db.models import QuerySet from django.http import HttpRequest from ...plugins.hooks import FilterHook class GetPrivateThreadRepliesPageThreadQuerysetHookAction(Protocol): """ A standard Misago function used to get a queryset used to get a thread for the private thread replies page. # Arguments ## `request: HttpRequest` The request object. # Return value A `QuerySet` instance to use in the `get_object_or_404` call. """ def __call__(self, request: HttpRequest) -> QuerySet: ... class GetPrivateThreadRepliesPageThreadQuerysetHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetPrivateThreadRepliesPageThreadQuerysetHookAction` A standard Misago function used to get a queryset used to get a thread for the private thread replies page. See the [action](#action) section for details. ## `request: HttpRequest` The request object. # Return value A `QuerySet` instance to use in the `get_object_or_404` call. """ def __call__( self, action: GetPrivateThreadRepliesPageThreadQuerysetHookAction, request: HttpRequest, ) -> QuerySet: ... class GetPrivateThreadRepliesPageThreadQuerysetHook( FilterHook[ GetPrivateThreadRepliesPageThreadQuerysetHookAction, GetPrivateThreadRepliesPageThreadQuerysetHookFilter, ] ): """ This hook wraps the standard function that Misago uses to get a queryset used to get a thread for the private thread replies page. # Example The code below implements a custom filter function that joins plugin's table with `select_related`: ```python from django.http import HttpRequest from misago.threads.hooks import get_private_thread_replies_page_thread_queryset_hook @get_private_thread_replies_page_thread_queryset_hook.append_filter def select_related_plugin_data(action, request: HttpRequest): queryset = action(request) return queryset.select_related("plugin") ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetPrivateThreadRepliesPageThreadQuerysetHookAction, request: HttpRequest, ) -> dict: return super().__call__(action, request) get_private_thread_replies_page_thread_queryset_hook = ( GetPrivateThreadRepliesPageThreadQuerysetHook() )
2,492
Python
.py
64
33.375
89
0.732471
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,189
get_thread_replies_page_posts_queryset.py
rafalp_Misago/misago/threads/hooks/get_thread_replies_page_posts_queryset.py
from typing import Protocol from django.db.models import QuerySet from django.http import HttpRequest from ...plugins.hooks import FilterHook from ..models import Thread class GetThreadRepliesPagePostsQuerysetHookAction(Protocol): """ A standard Misago function used to get a queryset used to get posts displayed on the thread replies page. # Arguments ## `request: HttpRequest` The request object. ## `thread: Thread` A `Thread` instance. # Return value An unfiltered `QuerySet` instance to use to get posts displayed on the thread replies page. """ def __call__(self, request: HttpRequest, thread: Thread) -> QuerySet: ... class GetThreadRepliesPagePostsQuerysetHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetThreadRepliesPagePostsQuerysetHookAction` A standard Misago function used to get a queryset used to get posts displayed on the thread replies page. See the [action](#action) section for details. ## `request: HttpRequest` The request object. # Return value An unfiltered `QuerySet` instance to use to get posts displayed on the thread replies page. """ def __call__( self, action: GetThreadRepliesPagePostsQuerysetHookAction, request: HttpRequest, thread: Thread, ) -> QuerySet: ... class GetThreadRepliesPagePostsQuerysetHook( FilterHook[ GetThreadRepliesPagePostsQuerysetHookAction, GetThreadRepliesPagePostsQuerysetHookFilter, ] ): """ This hook wraps the standard function that Misago uses to get a queryset with posts to display on the thread replies page. This hook should be used only to add new joins with `select_related`. To filter posts, use the `filter_thread_posts_queryset` hook instead. # Example The code below implements a custom filter function that joins plugin's table with `select_related`: ```python from django.http import HttpRequest from misago.threads.hooks import get_thread_replies_page_posts_queryset_hook from misago.threads.models import Thread @get_thread_replies_page_posts_queryset_hook.append_filter def select_related_plugin_data( action, request: HttpRequest, thread: Thread ): queryset = action(request, thread) return queryset.select_related("plugin") ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetThreadRepliesPagePostsQuerysetHookAction, request: HttpRequest, thread: Thread, ) -> dict: return super().__call__(action, request, thread) get_thread_replies_page_posts_queryset_hook = GetThreadRepliesPagePostsQuerysetHook()
2,824
Python
.py
74
32.472973
85
0.722652
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,190
get_threads_page_moderation_actions.py
rafalp_Misago/misago/threads/hooks/get_threads_page_moderation_actions.py
from typing import Protocol, Type from django.http import HttpRequest from ...moderation.threads import ThreadsBulkModerationAction from ...plugins.hooks import FilterHook class GetThreadsPageModerationActionsHookAction(Protocol): """ A standard Misago function used to get available moderation actions for the threads list. # Arguments ## `request: HttpRequest` The request object. # Return value A Python `list` with `ThreadsBulkModerationAction` types. """ def __call__( self, request: HttpRequest ) -> list[Type[ThreadsBulkModerationAction]]: ... class GetThreadsPageModerationActionsHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetThreadsPageModerationActionsHookAction` A standard Misago function used to get available filters for the threads list. See the [action](#action) section for details. ## `request: HttpRequest` The request object. # Return value A Python `list` with `ThreadsBulkModerationAction` types. """ def __call__( self, action: GetThreadsPageModerationActionsHookAction, request: HttpRequest, ) -> list[Type[ThreadsBulkModerationAction]]: ... class GetThreadsPageModerationActionsHook( FilterHook[ GetThreadsPageModerationActionsHookAction, GetThreadsPageModerationActionsHookFilter, ] ): """ This hook wraps the standard function that Misago uses to get available moderation actions for the threads list. # Example The code below implements a custom filter function that includes a new moderation action for users with a special permission only: ```python from django.http import HttpRequest from misago.moderation.threads import ModerationResult, ThreadsBulkModerationAction from misago.threads.hooks import get_threads_page_moderation_actions_hook from misago.threads.models import Thread class CustomModerationAction(ThreadsBulkModerationAction): id: str = "custom" name: str = "Custom" def __call__( self, request: HttpRequest, threads: list[Thread] ) -> ModerationResult | None: ... @get_threads_page_moderation_actions_hook.append_filter def include_custom_moderation_action( action, request: HttpRequest ) -> list[Type[ThreadsBulkModerationAction]]: moderation_actions = action(request) if request.user_permissions.is_global_moderator: moderation_actions.append(ThreadsBulkModerationAction) return moderation_actions ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetThreadsPageModerationActionsHookAction, request: HttpRequest, ) -> list[Type[ThreadsBulkModerationAction]]: return super().__call__(action, request) get_threads_page_moderation_actions_hook = GetThreadsPageModerationActionsHook()
3,032
Python
.py
77
33.142857
87
0.725342
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,191
get_threads_page_context_data.py
rafalp_Misago/misago/threads/hooks/get_threads_page_context_data.py
from typing import Protocol from django.http import HttpRequest from ...plugins.hooks import FilterHook class GetThreadsPageContextDataHookAction(Protocol): """ A standard Misago function used to get the template context data for the threads page. # Arguments ## `request: HttpRequest` The request object. ## `kwargs: dict` A Python `dict` with view's keyword arguments. # Return value A Python `dict` with context data to use to `render` the threads page. """ def __call__(self, request: HttpRequest, kwargs: dict) -> dict: ... class GetThreadsPageContextDataHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetThreadsPageContextDataHookAction` A standard Misago function used to get the template context data for the threads page. See the [action](#action) section for details. ## `request: HttpRequest` The request object. ## `kwargs: dict` A Python `dict` with view's keyword arguments. # Return value A Python `dict` with context data to use to `render` the threads page. """ def __call__( self, action: GetThreadsPageContextDataHookAction, request: HttpRequest, kwargs: dict, ) -> dict: ... class GetThreadsPageContextDataHook( FilterHook[ GetThreadsPageContextDataHookAction, GetThreadsPageContextDataHookFilter, ] ): """ This hook wraps the standard function that Misago uses to get the template context data for the threads page. # Example The code below implements a custom filter function that adds custom context data to the threads page: ```python from django.http import HttpRequest from misago.threads.hooks import get_threads_page_context_data_hook @get_threads_page_context_data_hook.append_filter def include_custom_context(action, request: HttpRequest, kwargs: dict) -> dict: context = action(request, kwargs) context["plugin_data"] = "..." return context ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetThreadsPageContextDataHookAction, request: HttpRequest, kwargs: dict, ) -> dict: return super().__call__(action, request, kwargs) get_threads_page_context_data_hook = GetThreadsPageContextDataHook()
2,453
Python
.py
68
30.161765
83
0.696634
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,192
get_thread_posts_feed_users.py
rafalp_Misago/misago/threads/hooks/get_thread_posts_feed_users.py
from typing import TYPE_CHECKING, Protocol from django.http import HttpRequest from ...plugins.hooks import FilterHook if TYPE_CHECKING: from ...users.models import User class GetThreadPostsFeedUsersHookAction(Protocol): """ A standard Misago function used to get a `dict` of `User` instances used to display thread posts feed. Users have their `group` field already populated. # Arguments ## `request: HttpRequest` The request object. ## `user_ids: set[int]` A set of IDs of `User` objects to retrieve from the database ## Return value A `dict` of `User` instances, indexed by their IDs. """ def __call__( self, request: HttpRequest, user_ids: set[int], ) -> dict[int, "User"]: ... class FetThreadPostFeedUsersHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetThreadPostsFeedUsersHookAction` A standard Misago function used to get a `dict` of `User` instances used to display thread posts feed. Users have their `group` field populated. See the [action](#action) section for details. ## `request: HttpRequest` The request object. ## `user_ids: set[int]` A set of IDs of `User` objects to retrieve from the database ## Return value A `dict` of `User` instances, indexed by their IDs. """ def __call__( self, action: GetThreadPostsFeedUsersHookAction, request: HttpRequest, user_ids: set[int], ) -> dict[int, "User"]: ... class FetThreadPostFeedUsersHook( FilterHook[GetThreadPostsFeedUsersHookAction, FetThreadPostFeedUsersHookFilter] ): """ This hook wraps the standard function that Misago uses to get a `dict` of `User` instances used to display thread posts feed. Users have their `group` field already populated. # Example The code below implements a custom filter function that removes some users from the dictionary, making them display on a posts feed as deleted users. ```python from typing import TYPE_CHECKING from django.http import HttpRequest from misago.threads.hooks import get_thread_posts_feed_users_hook if TYPE_CHECKING: from misago.users.models import User @get_thread_posts_feed_users_hook.append_filter def replace_post_poster( action, request: HttpRequest, user_ids: set[int] ) -> dict[int, "User"]: users = action(request, user_ids) for user_id, user in list(users.items()) if user.plugin_data.get("is_hidden"): del users[user_id] return users ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetThreadPostsFeedUsersHookAction, request: HttpRequest, user_ids: set[int], ) -> dict[int, "User"]: return super().__call__(action, request, user_ids) get_thread_posts_feed_users_hook = FetThreadPostFeedUsersHook()
3,038
Python
.py
79
32.278481
83
0.683345
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,193
get_category_threads_page_queryset.py
rafalp_Misago/misago/threads/hooks/get_category_threads_page_queryset.py
from typing import Protocol from django.http import HttpRequest from django.db.models import QuerySet from ...plugins.hooks import FilterHook class GetCategoryThreadsPageQuerysetHookAction(Protocol): """ A standard Misago function used to get the base threads queryset for the category threads page. # Arguments ## `request: HttpRequest` The request object. # Return value A `QuerySet` instance that will return `Threads`. """ def __call__(self, request: HttpRequest) -> QuerySet: ... class GetCategoryThreadsPageQuerysetHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetCategoryThreadsPageQuerysetHookAction` A standard Misago function used to get the base threads queryset for the category threads page. See the [action](#action) section for details. ## `request: HttpRequest` The request object. # Return value A `QuerySet` instance that will return `Threads`. """ def __call__( self, action: GetCategoryThreadsPageQuerysetHookAction, request: HttpRequest, ) -> QuerySet: ... class GetCategoryThreadsPageQuerysetHook( FilterHook[ GetCategoryThreadsPageQuerysetHookAction, GetCategoryThreadsPageQuerysetHookFilter, ] ): """ This hook wraps the standard function that Misago uses to get base threads queryset for the category threads page. # Example The code below implements a custom filter function that joins first post to every returned thread. ```python from django.db.models import QuerySet from django.http import HttpRequest from misago.threads.hooks import get_category_threads_page_queryset_hook @get_category_threads_page_queryset_hook.append_filter def select_first_post(action, request: HttpRequest) -> QuerySet: queryset = action(request) return queryset.select_related("first_post") ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetCategoryThreadsPageQuerysetHookAction, request: HttpRequest, ) -> QuerySet: return super().__call__(action, request) get_category_threads_page_queryset_hook = GetCategoryThreadsPageQuerysetHook()
2,334
Python
.py
63
31.412698
79
0.724431
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,194
get_category_threads_page_threads.py
rafalp_Misago/misago/threads/hooks/get_category_threads_page_threads.py
from typing import Protocol from django.http import HttpRequest from ...categories.models import Category from ...plugins.hooks import FilterHook class GetCategoryThreadsPageThreadsHookAction(Protocol): """ A standard Misago function used to get the complete threads data for the category threads page. Returns a `dict` that is included in the template context under the `threads` key. # Arguments ## `request: HttpRequest` The request object. ## `category: Category` A category instance. ## `kwargs: dict` A `dict` with `kwargs` this view was called with. # Return value A `dict` with the template context. """ def __call__( self, request: HttpRequest, category: Category, kwargs: dict, ) -> dict: ... class GetCategoryThreadsPageThreadsHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetCategoryThreadsPageThreadsHookAction` A standard Misago function used to get the complete threads data for the category threads page. Returns a `dict` that is included in the template context under the `threads` key. See the [action](#action) section for details. ## `request: HttpRequest` The request object. ## `category: Category` A category instance. ## `kwargs: dict` A `dict` with `kwargs` this view was called with. # Return value A `dict` with the template context. """ def __call__( self, action: GetCategoryThreadsPageThreadsHookAction, request: HttpRequest, category: Category, kwargs: dict, ) -> dict: ... class GetCategoryThreadsPageThreadsHook( FilterHook[ GetCategoryThreadsPageThreadsHookAction, GetCategoryThreadsPageThreadsHookFilter, ] ): """ This hook wraps the standard function that Misago uses to get complete threads data for the category threads page. # Example The code below implements a custom filter function makes view use a different threads list template instead of the default one. ```python from django.http import HttpRequest from misago.categories.models import Category from misago.threads.hooks import get_category_threads_page_threads_hook @get_category_threads_page_threads_hook.append_filter def replace_threads_list_template( action, request: HttpRequest, category: Category, kwargs: dict ) -> dict: data = action(request, kwargs) data["template_name"] = "plugin/threads_list.html" return data ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetCategoryThreadsPageThreadsHookAction, request: HttpRequest, category: Category, kwargs: dict, ) -> dict: return super().__call__(action, request, category, kwargs) get_category_threads_page_threads_hook = GetCategoryThreadsPageThreadsHook()
3,040
Python
.py
85
29.729412
81
0.69777
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,195
get_threads_users.py
rafalp_Misago/misago/threads/hooks/get_threads_users.py
from typing import TYPE_CHECKING, Protocol from django.http import HttpRequest from ...plugins.hooks import FilterHook from ..models import Thread if TYPE_CHECKING: from ...users.models import User class GetThreadsUsersHookAction(Protocol): """ A standard Misago function used to get `User` objects to display on threads list. # Arguments ## `request: HttpRequest` The request object. ## `threads: list[Thread]` A Python list with `Thread` instances to pull starters and last posters for. # Return value A Python `dict` with `User` instances. """ def __call__( self, request: HttpRequest, threads: list[Thread] ) -> dict[int, "User"]: ... class GetThreadsUsersHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetThreadsUsersHookAction` A standard Misago function used to get `User` objects to display on threads list. See the [action](#action) section for details. ## `request: HttpRequest` The request object. ## `threads: list[Thread]` A Python list with `Thread` instances to pull starters and last posters for. # Return value A Python `dict` with `User` instances. """ def __call__( self, action: GetThreadsUsersHookAction, request: HttpRequest, threads: list[Thread], ) -> dict[int, "User"]: ... class GetThreadsUsersHook( FilterHook[GetThreadsUsersHookAction, GetThreadsUsersHookFilter] ): """ This hook wraps the standard function that Misago uses to get `User` objects to display on threads list. # Example The code below implements a custom filter function that excludes users with plugin status from the users list: ```python from django.http import HttpRequest from misago.threads.hooks import get_threads_users_hook @get_threads_users_hook.append_filter def include_custom_context(action, request: HttpRequest, kwargs: dict) -> dict: context = action(request, kwargs) context["plugin_data"] = "..." return context ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetThreadsUsersHookAction, request: HttpRequest, threads: list[Thread], ) -> dict[int, "User"]: return super().__call__(action, request, threads) get_threads_users_hook = GetThreadsUsersHook()
2,484
Python
.py
68
30.779412
85
0.687842
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,196
get_category_threads_page_filters.py
rafalp_Misago/misago/threads/hooks/get_category_threads_page_filters.py
from typing import Protocol from django.http import HttpRequest from ...categories.models import Category from ...plugins.hooks import FilterHook from ..filters import ThreadsFilter class GetCategoryThreadsPageFiltersHookAction(Protocol): """ A standard Misago function used to get available filters for a category's threads list. # Arguments ## `request: HttpRequest` The request object. ## `category: Category` A category instance. # Return value A Python `list` with `ThreadsFilter` instances. """ def __call__( self, request: HttpRequest, category: Category, ) -> list[ThreadsFilter]: ... class GetCategoryThreadsPageFiltersHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetCategoryThreadsPageFiltersHookAction` A standard Misago function used to get available filters for a category's threads list. See the [action](#action) section for details. ## `request: HttpRequest` The request object. ## `category: Category` A category instance. # Return value A Python `list` with `ThreadsFilter` instances. """ def __call__( self, action: GetCategoryThreadsPageFiltersHookAction, request: HttpRequest, category: Category, ) -> list[ThreadsFilter]: ... class GetCategoryThreadsPageFiltersHook( FilterHook[ GetCategoryThreadsPageFiltersHookAction, GetCategoryThreadsPageFiltersHookFilter, ] ): """ This hook wraps the standard function that Misago uses to get available filters for a category's threads list. # Example The code below implements a custom filter function that includes a new filter available to signed-in users only: ```python from django.http import HttpRequest from misago.categories.models import Category from misago.threads.filters import ThreadsFilter from misago.threads.hooks import get_category_threads_page_filters_hook class CustomFilter(ThreadsFilter): name: str = "Custom filter" slug: str = "custom" def __callable__(self, queryset): if not self.request.user.is_authenticated: return queryset return queryset.filter(plugin_data__custom=True) @get_category_threads_page_filters_hook.append_filter def include_custom_filter( action, request: HttpRequest, category: Category ) -> list[ThreadsFilter]: filters = action(request, category) filters.append(CustomFilter(request)) return filters ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetCategoryThreadsPageFiltersHookAction, request: HttpRequest, category: Category, ) -> list[ThreadsFilter]: return super().__call__(action, request, category) get_category_threads_page_filters_hook = GetCategoryThreadsPageFiltersHook()
3,045
Python
.py
85
29.505882
81
0.70274
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,197
get_thread_replies_page_context_data.py
rafalp_Misago/misago/threads/hooks/get_thread_replies_page_context_data.py
from typing import Protocol from django.http import HttpRequest from ...plugins.hooks import FilterHook from ..models import Thread class GetThreadRepliesPageContextDataHookAction(Protocol): """ A standard Misago function used to get the template context data for the thread replies page. # Arguments ## `request: HttpRequest` The request object. ## `thread: Thread` A `Thread` instance. ## `page: int | None = None` An `int` with page number or `None`. # Return value A Python `dict` with context data to use to `render` the thread replies page. """ def __call__( self, request: HttpRequest, thread: Thread, page: int | None = None, ) -> dict: ... class GetThreadRepliesPageContextDataHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetThreadRepliesPageContextDataHookAction` A standard Misago function used to get the template context data for the thread replies page. See the [action](#action) section for details. ## `request: HttpRequest` The request object. ## `thread: Thread` A `Thread` instance. ## `page: int | None = None` An `int` with page number or `None`. # Return value A Python `dict` with context data to use to `render` the thread replies page. """ def __call__( self, action: GetThreadRepliesPageContextDataHookAction, request: HttpRequest, thread: Thread, page: int | None = None, ) -> dict: ... class GetThreadRepliesPageContextDataHook( FilterHook[ GetThreadRepliesPageContextDataHookAction, GetThreadRepliesPageContextDataHookFilter, ] ): """ This hook wraps the standard function that Misago uses to get the template context data for the thread replies page. # Example The code below implements a custom filter function that adds custom context data to the thread replies page: ```python from django.http import HttpRequest from misago.threads.hooks import get_thread_replies_page_context_data_hook from misago.threads.models import Thread @get_thread_replies_page_context_data_hook.append_filter def include_custom_context( action, request: HttpRequest, thread: dict, page: int | None = None, ) -> dict: context = action(request, thread, page) context["plugin_data"] = "..." return context ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetThreadRepliesPageContextDataHookAction, request: HttpRequest, thread: Thread, page: int | None = None, ) -> dict: return super().__call__(action, request, thread, page) get_thread_replies_page_context_data_hook = GetThreadRepliesPageContextDataHook()
2,959
Python
.py
86
28.22093
81
0.676793
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,198
get_threads_page_subcategories.py
rafalp_Misago/misago/threads/hooks/get_threads_page_subcategories.py
from typing import Protocol from django.http import HttpRequest from ...plugins.hooks import FilterHook class GetThreadsPageSubcategoriesHookAction(Protocol): """ A standard Misago function used to build a `dict` with data for the categories list component, used to display the list of subcategories on the threads page. # Arguments ## `request: HttpRequest` The request object. # Return value A Python `dict` with data for the categories list component. Must have at least two keys: `categories` and `template_name`: ```python { "categories": ..., "template_name": "misago/category/subcategories.html" } ``` To suppress categories lists on a page, return `None`. """ def __call__(self, request: HttpRequest) -> dict | None: ... class GetThreadsPageSubcategoriesHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetThreadsPageSubcategoriesHookAction` A standard Misago function used to build a `dict` with data for the categories list component, used to display the list of subcategories on the threads page. See the [action](#action) section for details. ## `request: HttpRequest` The request object. # Return value A Python `dict` with data for the categories list component. Must have at least two keys: `categories` and `template_name`: ```python { "categories": ..., "template_name": "misago/threads/subcategories.html" } ``` To suppress categories lists on a page, return `None`. """ def __call__( self, action: GetThreadsPageSubcategoriesHookAction, request: HttpRequest, ) -> dict | None: ... class GetThreadsPageSubcategoriesHook( FilterHook[ GetThreadsPageSubcategoriesHookAction, GetThreadsPageSubcategoriesHookFilter, ] ): """ This hook wraps the standard function that Misago uses to build a `dict` with data for the categories list component, used to display the list of subcategories on the threads page. # Example The code below implements a custom filter function that replaces full subcategories component's template with a custom one ```python from django.http import HttpRequest from misago.categories.models import Category from misago.threads.hooks import get_threads_page_subcategories_hook @get_threads_page_subcategories_hook.append_filter def customize_subcategories_template(action, request: HttpRequest) -> dict | None: data = action(request) data["template_name"] = "plugin/subcategories.html" return data ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetThreadsPageSubcategoriesHookAction, request: HttpRequest, ) -> dict | None: return super().__call__(action, request) get_threads_page_subcategories_hook = GetThreadsPageSubcategoriesHook()
3,066
Python
.py
82
31.536585
86
0.702648
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,199
get_threads_page_filters.py
rafalp_Misago/misago/threads/hooks/get_threads_page_filters.py
from typing import Protocol from django.http import HttpRequest from ...plugins.hooks import FilterHook from ..filters import ThreadsFilter class GetThreadsPageFiltersHookAction(Protocol): """ A standard Misago function used to get available filters for the threads list. # Arguments ## `request: HttpRequest` The request object. # Return value A Python `list` with `ThreadsFilter` instances. """ def __call__(self, request: HttpRequest) -> list[ThreadsFilter]: ... class GetThreadsPageFiltersHookFilter(Protocol): """ A function implemented by a plugin that can be registered in this hook. # Arguments ## `action: GetThreadsPageFiltersHookAction` A standard Misago function used to get available filters for the threads list. See the [action](#action) section for details. ## `request: HttpRequest` The request object. # Return value A Python `list` with `ThreadsFilter` instances. """ def __call__( self, action: GetThreadsPageFiltersHookAction, request: HttpRequest, ) -> list[ThreadsFilter]: ... class GetThreadsPageFiltersHook( FilterHook[GetThreadsPageFiltersHookAction, GetThreadsPageFiltersHookFilter] ): """ This hook wraps the standard function that Misago uses to get available filters for the threads list. # Example The code below implements a custom filter function that includes a new filter available to signed-in users only: ```python from django.http import HttpRequest from misago.threads.filters import ThreadsFilter from misago.threads.hooks import get_threads_page_filters_hook class CustomFilter(ThreadsFilter): name: str = "Custom filter" slug: str = "custom" def __callable__(self, queryset): if not self.request.user.is_authenticated: return queryset return queryset.filter(plugin_data__custom=True) @get_threads_page_filters_hook.append_filter def include_custom_filter(action, request: HttpRequest) -> list[ThreadsFilter]: filters = action(request) filters.append(CustomFilter(request)) return filters ``` """ __slots__ = FilterHook.__slots__ def __call__( self, action: GetThreadsPageFiltersHookAction, request: HttpRequest, ) -> list[ThreadsFilter]: return super().__call__(action, request) get_threads_page_filters_hook = GetThreadsPageFiltersHook()
2,525
Python
.py
66
32.045455
83
0.7078
rafalp/Misago
2,519
524
136
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)