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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17,700
|
get_categories_query_values.py
|
rafalp_Misago/misago/categories/hooks/get_categories_query_values.py
|
from typing import Protocol
from ...plugins.hooks import FilterHook
class GetCategoriesQueryValuesHookAction(Protocol):
"""
A standard Misago function used to retrieve a set of arguments for the `values`
call on the categories queryset.
# Return value
A Python `set` with names of the `Category` model fields to include in the queryset.
"""
def __call__(self) -> set[str]: ...
class GetCategoriesQueryValuesHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
# Return value
A Python `set` with names of the `Category` model fields to include in the queryset.
"""
def __call__(self, action: GetCategoriesQueryValuesHookAction) -> set[str]: ...
class GetCategoriesQueryValuesHook(
FilterHook[GetCategoriesQueryValuesHookAction, GetCategoriesQueryValuesHookFilter]
):
"""
This hook wraps the standard Misago function used to retrieve a set of arguments for
the `values` call on the categories queryset.
# Example
The code below implements a custom filter function that includes the `plugin_data`
field in the queryset.
```python
from misago.categories.hooks import get_categories_query_values_hook
@get_categories_query_values_hook.append_filter
def include_plugin_data_in_query(action) -> set[str]:
fields = action(groups)
fields.add("plugin_data")
return fields
```
"""
__slots__ = FilterHook.__slots__
def __call__(self, action: GetCategoriesQueryValuesHookAction) -> dict:
return super().__call__(action)
get_categories_query_values_hook = GetCategoriesQueryValuesHook()
| 1,684
|
Python
|
.py
| 39
| 37.923077
| 88
| 0.727049
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,701
|
get_category_data.py
|
rafalp_Misago/misago/categories/hooks/get_category_data.py
|
from typing import Any, Protocol
from ...plugins.hooks import FilterHook
class GetCategoryDataHookAction(Protocol):
"""
A standard Misago function used to build a `dict` with category result from queryset's
result.
# Arguments
## `result: dict[str, Any]`
A `dict` with category data returned by the queryset.
# Return value
A Python `dict` with category data to cache and use by Misago.
"""
def __call__(self, result: dict[str, Any]) -> dict[str, Any]: ...
class GetCategoryDataHookFilter(Protocol):
"""
A function implemented by a plugin that can be registered in this hook.
## `result: dict[str, Any]`
A `dict` with category data returned by the queryset.
# Return value
A Python `dict` with category data to cache and use by Misago.
"""
def __call__(
self, action: GetCategoryDataHookAction, result: dict[str, Any]
) -> dict[str, Any]: ...
class GetCategoryDataHook(
FilterHook[GetCategoryDataHookAction, GetCategoryDataHookFilter]
):
"""
This hook wraps the standard function that Misago uses to build a `dict` with
category data from queryset's result.
# Example
The code below implements a custom filter function that includes a custom
dict entry using `plugin_data`:
```python
from typing import Any
from misago.categories.hooks import get_category_data_hook
@get_category_data_hook.append_filter
def include_plugin_permission_in_data(action, result: result[str, Any]) -> dict:
data = action(groups)
if result.get("plugin_data"):
data["plugin_flag"] = result["plugin_data"].get("plugin_flag")
return data
```
"""
__slots__ = FilterHook.__slots__
def __call__(
self, action: GetCategoryDataHookAction, result: dict[str, Any]
) -> dict[str, Any]:
return super().__call__(action, result)
get_category_data_hook = GetCategoryDataHook()
| 1,971
|
Python
|
.py
| 50
| 33.78
| 90
| 0.684628
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,702
|
urls.py
|
rafalp_Misago/misago/apiv2/urls.py
|
from django.urls import include, path
app_name = "apiv2"
urlpatterns = [
path("", include("misago.apiv2.notifications.urls")),
path("", include("misago.apiv2.threads.urls")),
]
| 187
|
Python
|
.py
| 6
| 28.5
| 57
| 0.703911
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,703
|
decorators.py
|
rafalp_Misago/misago/apiv2/decorators.py
|
from functools import wraps
from django.core.exceptions import PermissionDenied
from django.utils.translation import pgettext
def require_auth(f):
@wraps(f)
def auth_only_view(request, *args, **kwargs):
if request.user.is_anonymous:
if request.method in ("GET", "HEAD", "OPTIONS"):
raise PermissionDenied(
pgettext("apiv2", "You have to sign in to access this page.")
)
raise PermissionDenied(
pgettext("apiv2", "You have to sign in to perform this action.")
)
return f(request, *args, **kwargs)
return auth_only_view
| 655
|
Python
|
.py
| 16
| 31.375
| 81
| 0.619874
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,704
|
pagination.py
|
rafalp_Misago/misago/apiv2/pagination/pagination.py
|
from dataclasses import dataclass
from typing import Any, List, Optional
from django.http import Http404
from rest_framework.exceptions import ValidationError
class PaginationError(ValidationError):
pass
@dataclass
class PaginationResult:
items: List[Any]
has_next: bool
has_previous: bool
first_cursor: Optional[Any]
last_cursor: Optional[Any]
def paginate_queryset(
request,
queryset,
order_by: str,
max_limit: int,
raise_404: bool = False,
) -> PaginationResult:
after = get_query_value(request, "after")
before = get_query_value(request, "before")
limit = get_query_value(request, "limit") or max_limit
if after and before:
raise PaginationError(
{"after": "'after' and 'before' can't be used at same time"}
)
if limit > max_limit:
raise PaginationError({"limit": f"can't be greater than '{max_limit}'"})
queryset = queryset.order_by(order_by)
if before:
return paginate_with_before(queryset, before, order_by, limit, raise_404)
return paginate_with_after(queryset, after or 0, order_by, limit, raise_404)
def get_query_value(request, name: str, default: int | None = None) -> int | None:
value = request.GET[name] if name in request.GET else default
if value is None:
return value
try:
value = int(value)
if value < 1:
raise ValueError()
except (TypeError, ValueError):
raise PaginationError({name: "must be a positive integer"})
return value
def paginate_with_after(
queryset,
after: int,
order_by: str,
limit: int,
raise_404: bool,
) -> PaginationResult:
order_desc = order_by[0] == "-"
col_name = order_by.lstrip("-")
if after:
if order_desc:
filter_kwarg = {f"{col_name}__lt": after}
else:
filter_kwarg = {f"{col_name}__gt": after}
items_queryset = queryset.filter(**filter_kwarg)
else:
items_queryset = queryset
items = list(items_queryset[: limit + 1])
has_next = False
has_previous = False
if after and not items and raise_404:
raise Http404()
if len(items) > limit:
has_next = True
items = items[:limit]
if items:
cursor = getattr(items[0], col_name)
if order_desc:
filter_kwarg = {f"{col_name}__gt": cursor}
else:
filter_kwarg = {f"{col_name}__lt": cursor}
has_previous = queryset.filter(**filter_kwarg).order_by(col_name).exists()
return create_pagination_result(
col_name,
items,
has_next,
has_previous,
)
def paginate_with_before(
queryset,
before: int,
order_by: str,
limit: int,
raise_404: bool,
) -> PaginationResult:
order_desc = order_by[0] == "-"
col_name = order_by.lstrip("-")
if order_desc:
filter_kwarg = {f"{col_name}__gt": before}
else:
filter_kwarg = {f"{col_name}__lt": before}
items_queryset = queryset.filter(**filter_kwarg).order_by(
col_name if order_desc else f"-{col_name}"
)
items = list(reversed(items_queryset[: limit + 1]))
has_next = False
has_previous = False
if not items and raise_404:
raise Http404()
if len(items) > limit:
items = items[1:]
has_previous = True
if items:
cursor = getattr(items[-1], col_name)
if order_desc:
filter_kwarg = {f"{col_name}__lt": cursor}
else:
filter_kwarg = {f"{col_name}__gt": cursor}
has_next = queryset.filter(**filter_kwarg).order_by(col_name).exists()
return create_pagination_result(
col_name,
items,
has_next,
has_previous,
)
def create_pagination_result(
col_name: str,
items: List[Any],
has_next: bool,
has_previous: bool,
) -> PaginationResult:
if items:
first_cursor = getattr(items[0], col_name)
last_cursor = getattr(items[-1], col_name)
else:
first_cursor = None
last_cursor = None
return PaginationResult(
items=items,
has_next=has_next,
has_previous=has_previous,
first_cursor=first_cursor,
last_cursor=last_cursor,
)
| 4,282
|
Python
|
.py
| 138
| 24.442029
| 82
| 0.619372
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,705
|
__init__.py
|
rafalp_Misago/misago/apiv2/pagination/__init__.py
|
from .pagination import PaginationError, PaginationResult, paginate_queryset
__all__ = ["PaginationError", "PaginationResult", "paginate_queryset"]
| 149
|
Python
|
.py
| 2
| 73
| 76
| 0.80137
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,706
|
conftest.py
|
rafalp_Misago/misago/apiv2/pagination/tests/conftest.py
|
import pytest
from ....notifications.models import Notification
@pytest.fixture
def notifications(user):
objects = Notification.objects.bulk_create(
[Notification(user=user, verb=f"test_{i}") for i in range(15)]
)
return sorted([obj.id for obj in objects])
| 281
|
Python
|
.py
| 8
| 31.125
| 70
| 0.732342
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,707
|
test_paginate_queryset_with_before.py
|
rafalp_Misago/misago/apiv2/pagination/tests/test_paginate_queryset_with_before.py
|
from unittest.mock import Mock
import pytest
from django.http import Http404
from ....notifications.models import Notification
from ..pagination import paginate_queryset
def test_pagination_with_before_returns_items_up_to_max_limit(notifications):
request = Mock(GET={"before": notifications[10]})
page = paginate_queryset(request, Notification.objects, "id", 4)
assert len(page.items) == 4
assert page.has_next
assert page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_6", "test_7", "test_8", "test_9"]
def test_pagination_with_before_returns_items_up_to_given_limit(notifications):
request = Mock(GET={"before": notifications[10], "limit": 5})
page = paginate_queryset(request, Notification.objects, "id", 10)
assert len(page.items) == 5
assert page.has_next
assert page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_5", "test_6", "test_7", "test_8", "test_9"]
def test_pagination_with_before_returns_last_items(notifications):
request = Mock(GET={"before": notifications[5]})
page = paginate_queryset(request, Notification.objects, "id", 10)
assert len(page.items) == 5
assert page.has_next
assert not page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_0", "test_1", "test_2", "test_3", "test_4"]
def test_pagination_with_before_raises_404_for_empty_item(notifications):
request = Mock(GET={"before": notifications[0]})
with pytest.raises(Http404):
paginate_queryset(request, Notification.objects, "id", 10, raise_404=True)
def test_pagination_with_before_returns_items_up_to_max_limit_in_reverse_order(
notifications,
):
request = Mock(GET={"before": notifications[4]})
page = paginate_queryset(request, Notification.objects, "-id", 4)
assert len(page.items) == 4
assert page.has_next
assert page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_8", "test_7", "test_6", "test_5"]
def test_pagination_with_before_returns_items_up_to_given_limit_in_reverse_order(
notifications,
):
request = Mock(GET={"before": notifications[4], "limit": 5})
page = paginate_queryset(request, Notification.objects, "-id", 10)
assert len(page.items) == 5
assert page.has_next
assert page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_9", "test_8", "test_7", "test_6", "test_5"]
def test_pagination_with_before_returns_last_items_in_reverse_order(notifications):
request = Mock(GET={"before": notifications[10]})
page = paginate_queryset(request, Notification.objects, "-id", 10)
assert len(page.items) == 4
assert page.has_next
assert not page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_14", "test_13", "test_12", "test_11"]
| 3,000
|
Python
|
.py
| 61
| 44.57377
| 83
| 0.703538
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,708
|
test_paginate_queryset.py
|
rafalp_Misago/misago/apiv2/pagination/tests/test_paginate_queryset.py
|
from unittest.mock import Mock
from ....notifications.models import Notification
from ..pagination import paginate_queryset
def test_pagination_returns_all_items(notifications):
request = Mock(GET={})
page = paginate_queryset(request, Notification.objects, "id", 20)
assert len(page.items) == 15
assert not page.has_next
assert not page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == [f"test_{i}" for i in range(15)]
assert page.first_cursor == page.items[0].id
assert page.last_cursor == page.items[-1].id
def test_pagination_returns_no_items(db):
request = Mock(GET={})
page = paginate_queryset(request, Notification.objects, "id", 20)
assert len(page.items) == 0
assert not page.has_next
assert not page.has_previous
assert page.first_cursor is None
assert page.last_cursor is None
def test_pagination_returns_firsts_and_last_cursor(notifications):
request = Mock(GET={})
page = paginate_queryset(request, Notification.objects, "id", 20)
assert len(page.items) == 15
assert page.first_cursor == page.items[0].id
assert page.last_cursor == page.items[-1].id
def test_pagination_returns_all_items_in_reverse_order(notifications):
request = Mock(GET={})
page = paginate_queryset(request, Notification.objects, "-id", 20)
assert len(page.items) == 15
assert not page.has_next
assert not page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == [f"test_{i}" for i in reversed(range(15))]
def test_pagination_returns_first_items_up_to_max_limit(notifications):
request = Mock(GET={})
page = paginate_queryset(request, Notification.objects, "id", 4)
assert len(page.items) == 4
assert page.has_next
assert not page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_0", "test_1", "test_2", "test_3"]
def test_pagination_returns_first_items_up_to_given_limit(notifications):
request = Mock(GET={"limit": 5})
page = paginate_queryset(request, Notification.objects, "id", 10)
assert len(page.items) == 5
assert page.has_next
assert not page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_0", "test_1", "test_2", "test_3", "test_4"]
def test_pagination_returns_first_items_up_to_max_limit_in_reverse_order(
notifications,
):
request = Mock(GET={})
page = paginate_queryset(request, Notification.objects, "-id", 4)
assert len(page.items) == 4
assert page.has_next
assert not page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_14", "test_13", "test_12", "test_11"]
def test_pagination_returns_first_items_up_to_given_limit_in_reverse_order(
notifications,
):
request = Mock(GET={"limit": 5})
page = paginate_queryset(request, Notification.objects, "-id", 10)
assert len(page.items) == 5
assert page.has_next
assert not page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_14", "test_13", "test_12", "test_11", "test_10"]
| 3,215
|
Python
|
.py
| 71
| 40.577465
| 81
| 0.699325
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,709
|
test_paginate_queryset_with_after.py
|
rafalp_Misago/misago/apiv2/pagination/tests/test_paginate_queryset_with_after.py
|
from unittest.mock import Mock
import pytest
from django.http import Http404
from ....notifications.models import Notification
from ..pagination import paginate_queryset
def test_pagination_with_after_returns_items_up_to_max_limit(notifications):
request = Mock(GET={"after": notifications[4]})
page = paginate_queryset(request, Notification.objects, "id", 4)
assert len(page.items) == 4
assert page.has_next
assert page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_5", "test_6", "test_7", "test_8"]
def test_pagination_with_after_returns_items_up_to_given_limit(notifications):
request = Mock(GET={"after": notifications[4], "limit": 5})
page = paginate_queryset(request, Notification.objects, "id", 10)
assert len(page.items) == 5
assert page.has_next
assert page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_5", "test_6", "test_7", "test_8", "test_9"]
def test_pagination_with_after_returns_last_items(notifications):
request = Mock(GET={"after": notifications[9]})
page = paginate_queryset(request, Notification.objects, "id", 10)
assert len(page.items) == 5
assert not page.has_next
assert page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_10", "test_11", "test_12", "test_13", "test_14"]
def test_pagination_with_after_returns_empty_items(notifications):
request = Mock(GET={"after": notifications[14]})
page = paginate_queryset(request, Notification.objects, "id", 10, raise_404=False)
assert len(page.items) == 0
assert not page.has_next
assert not page.has_previous
def test_pagination_with_after_raises_404_for_empty_item(notifications):
request = Mock(GET={"after": notifications[14]})
with pytest.raises(Http404):
paginate_queryset(request, Notification.objects, "id", 10, raise_404=True)
def test_pagination_with_after_returns_items_up_to_max_limit_in_reverse_order(
notifications,
):
request = Mock(GET={"after": notifications[9]})
page = paginate_queryset(request, Notification.objects, "-id", 4)
assert len(page.items) == 4
assert page.has_next
assert page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_8", "test_7", "test_6", "test_5"]
def test_pagination_with_after_returns_items_up_to_given_limit_in_reverse_order(
notifications,
):
request = Mock(GET={"after": notifications[9], "limit": 5})
page = paginate_queryset(request, Notification.objects, "-id", 10)
assert len(page.items) == 5
assert page.has_next
assert page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_8", "test_7", "test_6", "test_5", "test_4"]
def test_pagination_with_after_returns_last_items_in_reverse_order(notifications):
request = Mock(GET={"after": notifications[4]})
page = paginate_queryset(request, Notification.objects, "-id", 10)
assert len(page.items) == 4
assert not page.has_next
assert page.has_previous
items_verbs = [item.verb for item in page.items]
assert items_verbs == ["test_3", "test_2", "test_1", "test_0"]
| 3,289
|
Python
|
.py
| 67
| 44.462687
| 86
| 0.704795
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,710
|
test_query_values_validation.py
|
rafalp_Misago/misago/apiv2/pagination/tests/test_query_values_validation.py
|
from unittest.mock import Mock
import pytest
from ....notifications.models import Notification
from ..pagination import PaginationError, paginate_queryset
def test_pagination_raises_error_if_after_is_not_a_number():
request = Mock(GET={"after": "str"})
with pytest.raises(PaginationError) as excinfo:
paginate_queryset(request, Notification.objects, "id", 100)
assert "must be a positive integer" in str(excinfo)
def test_pagination_raises_error_if_before_is_not_a_number():
request = Mock(GET={"before": "str"})
with pytest.raises(PaginationError) as excinfo:
paginate_queryset(request, Notification.objects, "id", 100)
assert "must be a positive integer" in str(excinfo)
def test_pagination_raises_error_if_limit_is_not_a_number():
request = Mock(GET={"limit": "str"})
with pytest.raises(PaginationError) as excinfo:
paginate_queryset(request, Notification.objects, "id", 100)
assert "must be a positive integer" in str(excinfo)
def test_pagination_raises_error_if_after_is_zero():
request = Mock(GET={"after": 0})
with pytest.raises(PaginationError) as excinfo:
paginate_queryset(request, Notification.objects, "id", 100)
assert "must be a positive integer" in str(excinfo)
def test_pagination_raises_error_if_before_is_zero():
request = Mock(GET={"before": 0})
with pytest.raises(PaginationError) as excinfo:
paginate_queryset(request, Notification.objects, "id", 100)
assert "must be a positive integer" in str(excinfo)
def test_pagination_raises_error_if_limit_is_zero():
request = Mock(GET={"limit": 0})
with pytest.raises(PaginationError) as excinfo:
paginate_queryset(request, Notification.objects, "id", 100)
assert "must be a positive integer" in str(excinfo)
def test_pagination_raises_error_if_after_is_negative():
request = Mock(GET={"after": -1})
with pytest.raises(PaginationError) as excinfo:
paginate_queryset(request, Notification.objects, "id", 100)
assert "must be a positive integer" in str(excinfo)
def test_pagination_raises_error_if_before_is_negative():
request = Mock(GET={"before": -1})
with pytest.raises(PaginationError) as excinfo:
paginate_queryset(request, Notification.objects, "id", 100)
assert "must be a positive integer" in str(excinfo)
def test_pagination_raises_error_if_limit_is_negative():
request = Mock(GET={"limit": -1})
with pytest.raises(PaginationError) as excinfo:
paginate_queryset(request, Notification.objects, "id", 100)
assert "must be a positive integer" in str(excinfo)
def test_pagination_raises_error_if_after_and_before_are_both_set():
request = Mock(GET={"after": 1, "before": 5})
with pytest.raises(PaginationError) as excinfo:
paginate_queryset(request, Notification.objects, "id", 100)
assert "'after' and 'before' can't be used at same time" in str(excinfo)
def test_pagination_raises_error_if_limit_exceeds_max_value():
request = Mock(GET={"limit": 200})
with pytest.raises(PaginationError) as excinfo:
paginate_queryset(request, Notification.objects, "id", 100)
assert "can't be greater than '100'" in str(excinfo)
| 3,247
|
Python
|
.py
| 59
| 49.525424
| 76
| 0.725971
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,711
|
urls.py
|
rafalp_Misago/misago/apiv2/threads/urls.py
|
from django.urls import path
from .views import watch_private_thread, watch_thread
urlpatterns = [
path(
"private-threads/<int:thread_id>/watch/",
watch_private_thread,
name="private-thread-watch",
),
path("threads/<int:thread_id>/watch/", watch_thread, name="thread-watch"),
]
| 316
|
Python
|
.py
| 10
| 26.8
| 78
| 0.677632
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,712
|
views.py
|
rafalp_Misago/misago/apiv2/threads/views.py
|
from django.http import HttpRequest, JsonResponse, Http404
from django.shortcuts import get_object_or_404
from rest_framework import serializers
from rest_framework.decorators import api_view
from ...categories.models import Category
from ...notifications.models import WatchedThread
from ...notifications.threads import ThreadNotifications, get_watched_thread
from ...threads.models import Thread
from ...threads.participants import make_thread_participants_aware
from ...threads.permissions import (
allow_see_private_thread,
allow_see_thread,
allow_use_private_threads,
)
from ..decorators import require_auth
class ThreadWatchSerializer(serializers.Serializer):
notifications = serializers.ChoiceField(
choices=ThreadNotifications.choices,
)
@api_view(["POST"])
@require_auth
def watch_thread(request: HttpRequest, thread_id: int) -> JsonResponse:
thread = get_object_or_404(Thread.objects.select_related("category"), id=thread_id)
if not Category.objects.root_category().has_child(thread.category):
raise Http404()
allow_see_thread(request.user_acl, thread)
return watch_thread_shared_logic(request, thread)
@api_view(["POST"])
@require_auth
def watch_private_thread(request: HttpRequest, thread_id: int) -> JsonResponse:
allow_use_private_threads(request.user_acl)
thread = get_object_or_404(Thread, id=thread_id)
if Category.objects.private_threads().id != thread.category_id:
raise Http404()
make_thread_participants_aware(request.user, thread)
allow_see_private_thread(request.user_acl, thread)
return watch_thread_shared_logic(request, thread)
def watch_thread_shared_logic(request: HttpRequest, thread: Thread) -> JsonResponse:
serializer = ThreadWatchSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
notifications = serializer.data["notifications"]
if not notifications:
WatchedThread.objects.filter(user=request.user, thread=thread).delete()
return JsonResponse(serializer.data)
send_emails = notifications == ThreadNotifications.SITE_AND_EMAIL
watched_thread = get_watched_thread(request.user, thread)
if watched_thread:
if watched_thread.send_emails != send_emails:
watched_thread.send_emails = send_emails
watched_thread.save(update_fields=["send_emails"])
else:
WatchedThread.objects.create(
user=request.user,
category_id=thread.category_id,
thread=thread,
send_emails=send_emails,
)
return JsonResponse(serializer.data)
| 2,611
|
Python
|
.py
| 58
| 39.724138
| 87
| 0.748817
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,713
|
test_thread_watch.py
|
rafalp_Misago/misago/apiv2/threads/tests/test_thread_watch.py
|
from django.urls import reverse
from ....acl.test import patch_user_acl
from ....notifications.models import WatchedThread
from ....notifications.threads import ThreadNotifications
def test_thread_watch_api_doesnt_create_watched_thread_for_disabled_notifications(
user, thread, user_client
):
response = user_client.post(
reverse("misago:apiv2:thread-watch", kwargs={"thread_id": thread.id}),
json={"notifications": ThreadNotifications.NONE.value},
)
assert response.status_code == 200
assert response.json() == {"notifications": ThreadNotifications.NONE.value}
assert not WatchedThread.objects.exists()
def test_thread_watch_api_creates_watched_thread_without_email_notifications(
user, thread, user_client
):
response = user_client.post(
reverse("misago:apiv2:thread-watch", kwargs={"thread_id": thread.id}),
json={"notifications": ThreadNotifications.SITE_ONLY.value},
)
assert response.status_code == 200
assert response.json() == {"notifications": ThreadNotifications.SITE_ONLY.value}
watched_thread = WatchedThread.objects.get(user=user, thread=thread)
assert watched_thread.category_id == thread.category_id
assert not watched_thread.send_emails
def test_thread_watch_api_creates_watched_thread_with_email_notifications(
user, thread, user_client
):
response = user_client.post(
reverse("misago:apiv2:thread-watch", kwargs={"thread_id": thread.id}),
json={"notifications": ThreadNotifications.SITE_AND_EMAIL.value},
)
assert response.status_code == 200
assert response.json() == {
"notifications": ThreadNotifications.SITE_AND_EMAIL.value
}
watched_thread = WatchedThread.objects.get(user=user, thread=thread)
assert watched_thread.category_id == thread.category_id
assert watched_thread.send_emails
def test_thread_watch_api_enables_watched_thread_email_notifications(
user, thread, user_client, django_assert_num_queries
):
existing_watched_thread = WatchedThread.objects.create(
user=user,
category_id=thread.category_id,
thread=thread,
send_emails=False,
)
with django_assert_num_queries(25):
response = user_client.post(
reverse("misago:apiv2:thread-watch", kwargs={"thread_id": thread.id}),
json={"notifications": ThreadNotifications.SITE_AND_EMAIL.value},
)
assert response.status_code == 200
assert response.json() == {
"notifications": ThreadNotifications.SITE_AND_EMAIL.value
}
watched_thread = WatchedThread.objects.get(user=user, thread=thread)
assert watched_thread.id == existing_watched_thread.id
assert watched_thread.send_emails
def test_thread_watch_api_disables_watched_thread_email_notifications(
user, thread, user_client, django_assert_num_queries
):
existing_watched_thread = WatchedThread.objects.create(
user=user,
category_id=thread.category_id,
thread=thread,
send_emails=True,
)
with django_assert_num_queries(25):
response = user_client.post(
reverse("misago:apiv2:thread-watch", kwargs={"thread_id": thread.id}),
json={"notifications": ThreadNotifications.SITE_ONLY.value},
)
assert response.status_code == 200
assert response.json() == {"notifications": ThreadNotifications.SITE_ONLY.value}
watched_thread = WatchedThread.objects.get(user=user, thread=thread)
assert watched_thread.id == existing_watched_thread.id
assert not watched_thread.send_emails
def test_thread_watch_api_skips_update_if_notifications_are_not_changed(
user, thread, user_client, django_assert_num_queries
):
existing_watched_thread = WatchedThread.objects.create(
user=user,
category_id=thread.category_id,
thread=thread,
send_emails=True,
)
with django_assert_num_queries(24):
response = user_client.post(
reverse("misago:apiv2:thread-watch", kwargs={"thread_id": thread.id}),
json={"notifications": ThreadNotifications.SITE_AND_EMAIL.value},
)
assert response.status_code == 200
assert response.json() == {
"notifications": ThreadNotifications.SITE_AND_EMAIL.value
}
watched_thread = WatchedThread.objects.get(user=user, thread=thread)
assert watched_thread.id == existing_watched_thread.id
assert watched_thread.send_emails
def test_thread_watch_api_deletes_watched_thread_if_notifications_are_disabled(
user, thread, user_client
):
WatchedThread.objects.create(
user=user,
category_id=thread.category_id,
thread=thread,
send_emails=True,
)
response = user_client.post(
reverse("misago:apiv2:thread-watch", kwargs={"thread_id": thread.id}),
json={"notifications": ThreadNotifications.NONE.value},
)
assert response.status_code == 200
assert response.json() == {"notifications": ThreadNotifications.NONE.value}
assert not WatchedThread.objects.exists()
def test_thread_watch_api_returns_404_error_if_thread_doesnt_exist(user, user_client):
response = user_client.post(
reverse("misago:apiv2:thread-watch", kwargs={"thread_id": 404}),
json={"notifications": ThreadNotifications.SITE_AND_EMAIL.value},
)
assert response.status_code == 404
assert WatchedThread.objects.count() == 0
def test_thread_watch_api_returns_404_error_if_thread_is_not_accessible(
user, other_user_hidden_thread, user_client
):
response = user_client.post(
reverse(
"misago:apiv2:thread-watch",
kwargs={"thread_id": other_user_hidden_thread.id},
),
json={"notifications": ThreadNotifications.SITE_AND_EMAIL.value},
)
assert response.status_code == 404
assert WatchedThread.objects.count() == 0
def test_thread_watch_api_returns_400_error_if_notifications_are_not_provided(
user, thread, user_client
):
response = user_client.post(
reverse("misago:apiv2:thread-watch", kwargs={"thread_id": thread.id}), json={}
)
assert response.status_code == 400
assert response.json() == {"notifications": ["This field is required."]}
assert WatchedThread.objects.count() == 0
def test_thread_watch_api_returns_400_error_if_notifications_are_invalid(
user, thread, user_client
):
response = user_client.post(
reverse("misago:apiv2:thread-watch", kwargs={"thread_id": thread.id}),
json={"notifications": 42},
)
assert response.status_code == 400
assert response.json() == {"notifications": ['"42" is not a valid choice.']}
assert WatchedThread.objects.count() == 0
def test_thread_watch_api_returns_403_error_if_client_is_no_authenticated(
thread, client
):
response = client.post(
reverse("misago:apiv2:thread-watch", kwargs={"thread_id": thread.id}),
json={"notifications": ThreadNotifications.SITE_AND_EMAIL.value},
)
assert response.status_code == 403
assert WatchedThread.objects.count() == 0
def test_thread_watch_api_returns_404_error_if_thread_is_private(
user, private_thread, user_client
):
response = user_client.post(
reverse("misago:apiv2:thread-watch", kwargs={"thread_id": private_thread.id}),
json={"notifications": ThreadNotifications.SITE_AND_EMAIL.value},
)
assert response.status_code == 404
assert WatchedThread.objects.count() == 0
def test_private_thread_watch_api_creates_watched_thread_with_notifications(
user, private_thread, user_client
):
private_thread.threadparticipant_set.create(user=user)
response = user_client.post(
reverse(
"misago:apiv2:private-thread-watch", kwargs={"thread_id": private_thread.id}
),
json={"notifications": ThreadNotifications.SITE_ONLY.value},
)
assert response.status_code == 200
assert response.json() == {"notifications": ThreadNotifications.SITE_ONLY.value}
watched_thread = WatchedThread.objects.get(user=user, thread=private_thread)
assert watched_thread.category_id == private_thread.category_id
assert not watched_thread.send_emails
def test_private_thread_watch_api_returns_404_error_if_user_has_no_access_to_thread(
user, private_thread, user_client
):
response = user_client.post(
reverse(
"misago:apiv2:private-thread-watch", kwargs={"thread_id": private_thread.id}
),
json={"notifications": ThreadNotifications.SITE_ONLY.value},
)
assert response.status_code == 404
assert WatchedThread.objects.count() == 0
def test_private_thread_watch_api_returns_404_error_if_thread_is_not_private_thread(
user, thread, user_client
):
response = user_client.post(
reverse("misago:apiv2:private-thread-watch", kwargs={"thread_id": thread.id}),
json={"notifications": ThreadNotifications.SITE_ONLY.value},
)
assert response.status_code == 404
assert WatchedThread.objects.count() == 0
def test_private_thread_watch_api_returns_403_error_if_client_is_no_authenticated(
user, private_thread, client
):
private_thread.threadparticipant_set.create(user=user)
response = client.post(
reverse(
"misago:apiv2:private-thread-watch", kwargs={"thread_id": private_thread.id}
),
json={"notifications": ThreadNotifications.SITE_ONLY.value},
)
assert response.status_code == 403
assert WatchedThread.objects.count() == 0
@patch_user_acl({"can_use_private_threads": False})
def test_private_thread_watch_api_returns_403_if_user_cant_use_private_threads(
user, private_thread, user_client
):
private_thread.threadparticipant_set.create(user=user)
response = user_client.post(
reverse(
"misago:apiv2:private-thread-watch", kwargs={"thread_id": private_thread.id}
),
json={"notifications": ThreadNotifications.SITE_ONLY.value},
)
assert response.status_code == 403
assert WatchedThread.objects.count() == 0
| 10,091
|
Python
|
.py
| 233
| 37.261803
| 88
| 0.705702
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,714
|
serializers.py
|
rafalp_Misago/misago/apiv2/notifications/serializers.py
|
from django.contrib.auth import get_user_model
from rest_framework import serializers
from ...notifications.models import Notification
from ...notifications.registry import registry
User = get_user_model()
class NotificationActorSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = [
"id",
"username",
"avatars",
]
def to_representation(self, obj: User) -> dict:
data = super().to_representation(obj)
data["url"] = obj.get_absolute_url()
return data
class NotificationSerializer(serializers.ModelSerializer):
class Meta:
model = Notification
fields = ["created_at"]
def to_representation(self, obj: Notification) -> dict:
data = super().to_representation(obj)
if obj.actor:
actor_data = NotificationActorSerializer(obj.actor).data
else:
actor_data = None
return {
"id": obj.id,
"isRead": obj.is_read,
"createdAt": data["created_at"],
"actor": actor_data,
"actorName": obj.actor_name,
"message": registry.get_message(obj),
"url": obj.get_absolute_url(),
}
| 1,251
|
Python
|
.py
| 36
| 26.138889
| 68
| 0.610788
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,715
|
urls.py
|
rafalp_Misago/misago/apiv2/notifications/urls.py
|
from django.urls import path
from .views import notifications, notifications_read_all
urlpatterns = [
path(
"notifications/",
notifications,
name="notifications",
),
path(
"notifications/read-all/",
notifications_read_all,
name="notifications-read-all",
),
]
| 325
|
Python
|
.py
| 14
| 17.5
| 56
| 0.640777
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,716
|
views.py
|
rafalp_Misago/misago/apiv2/notifications/views.py
|
from typing import List
from django.http import HttpRequest, HttpResponse, JsonResponse
from rest_framework.decorators import api_view
from ...conf import settings
from ...notifications.models import Notification
from ...notifications.permissions import allow_use_notifications
from ..pagination import paginate_queryset
from .serializers import NotificationSerializer
@api_view(["GET"])
def notifications(request: HttpRequest) -> JsonResponse:
allow_use_notifications(request.user)
queryset = (
Notification.objects.filter(user=request.user)
.select_related("actor")
.order_by("-id")
)
filter_by = request.GET.get("filter")
if filter_by == "unread":
queryset = queryset.filter(is_read=False)
if filter_by == "read":
queryset = queryset.filter(is_read=True)
page = paginate_queryset(
request,
queryset,
"-id",
settings.MISAGO_NOTIFICATIONS_PAGE_LIMIT,
)
# Update user unread notifications counter if its first page of notifications
# and the counter is obviously invalid
if (
"after" not in request.GET
and "before" not in request.GET
and filter_by != "read"
):
# Unread notifications counter is non-zero but no notifications exist
if request.user.unread_notifications and not page.items:
request.user.unread_notifications = 0
request.user.save(update_fields=["unread_notifications"])
# Only page of results, sync unread notifications counter with
# real count if those don't match
elif not page.has_next:
real_unread_notifications = len(
[
notification
for notification in page.items
if not notification.is_read
]
)
if real_unread_notifications != request.user.unread_notifications:
request.user.unread_notifications = real_unread_notifications
request.user.save(update_fields=["unread_notifications"])
# Recount unread unread notifications if counter shows 0 but unread
# notifications exist
elif not request.user.unread_notifications and unread_items_exist(
filter_by, page.items
):
count_limit = settings.MISAGO_UNREAD_NOTIFICATIONS_LIMIT + 1
real_unread_notifications = Notification.objects.filter(
user=request.user, is_read=False
)[:count_limit].count()
if real_unread_notifications:
request.user.unread_notifications = real_unread_notifications
request.user.save(update_fields=["unread_notifications"])
return JsonResponse(
{
"results": NotificationSerializer(page.items, many=True).data,
"hasNext": page.has_next,
"hasPrevious": page.has_previous,
"firstCursor": page.first_cursor,
"lastCursor": page.last_cursor,
"unreadNotifications": (
request.user.get_unread_notifications_for_display()
),
}
)
def unread_items_exist(filter_by: str, items: List[Notification]) -> bool:
if filter_by == "unread":
return bool(items)
if filter_by != "read":
for notification in items:
if not notification.is_read:
return True
return False
@api_view(["POST"])
def notifications_read_all(request: HttpRequest) -> HttpResponse:
allow_use_notifications(request.user)
Notification.objects.filter(
user=request.user,
is_read=False,
).update(
is_read=True,
)
request.user.unread_notifications = 0
request.user.save(update_fields=["unread_notifications"])
return HttpResponse(status=204)
| 3,782
|
Python
|
.py
| 95
| 31.347368
| 81
| 0.656676
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,717
|
test_notifications.py
|
rafalp_Misago/misago/apiv2/notifications/tests/test_notifications.py
|
from django.urls import reverse
from ....notifications.models import Notification
def test_notifications_api_returns_403_error_if_client_is_no_authenticated(db, client):
response = client.get(reverse("misago:apiv2:notifications"))
assert response.status_code == 403
def test_notifications_api_returns_empty_list_if_user_has_no_notifications(user_client):
response = user_client.get(reverse("misago:apiv2:notifications"))
assert response.status_code == 200
assert response.json() == {
"results": [],
"hasNext": False,
"hasPrevious": False,
"firstCursor": None,
"lastCursor": None,
"unreadNotifications": None,
}
def test_notifications_api_returns_list_with_all_user_notifications(user, user_client):
read_notification = Notification.objects.create(
user=user, verb="TEST", is_read=True
)
notification = Notification.objects.create(user=user, verb="TEST", is_read=False)
response = user_client.get(reverse("misago:apiv2:notifications"))
assert response.status_code == 200
response_json = response.json()
assert [result["id"] for result in response_json["results"]] == [
notification.id,
read_notification.id,
]
assert not response_json["hasNext"]
assert not response_json["hasPrevious"]
def test_notifications_api_returns_list_with_read_user_notifications(user, user_client):
read_notification = Notification.objects.create(
user=user, verb="TEST", is_read=True
)
Notification.objects.create(user=user, verb="TEST", is_read=False)
response = user_client.get(reverse("misago:apiv2:notifications") + "?filter=read")
assert response.status_code == 200
response_json = response.json()
assert [result["id"] for result in response_json["results"]] == [
read_notification.id
]
assert not response_json["hasNext"]
assert not response_json["hasPrevious"]
def test_notifications_api_returns_list_with_unread_user_notifications(
user, user_client
):
Notification.objects.create(user=user, verb="TEST", is_read=True)
notification = Notification.objects.create(user=user, verb="TEST", is_read=False)
response = user_client.get(reverse("misago:apiv2:notifications") + "?filter=unread")
assert response.status_code == 200
response_json = response.json()
assert [result["id"] for result in response_json["results"]] == [notification.id]
assert not response_json["hasNext"]
assert not response_json["hasPrevious"]
def test_notifications_api_returns_list_with_notification_by_actor(
user, other_user, user_client
):
notification = Notification.objects.create(
user=user,
actor=other_user,
actor_name=other_user.username,
verb="TEST",
is_read=False,
)
response = user_client.get(reverse("misago:apiv2:notifications"))
assert response.status_code == 200
response_json = response.json()
assert [result["id"] for result in response_json["results"]] == [notification.id]
assert not response_json["hasNext"]
assert not response_json["hasPrevious"]
def test_notifications_api_excludes_other_users_notifications(
user, other_user, user_client
):
Notification.objects.create(user=other_user, verb="TEST", is_read=True)
notification = Notification.objects.create(user=user, verb="TEST", is_read=False)
response = user_client.get(reverse("misago:apiv2:notifications"))
assert response.status_code == 200
response_json = response.json()
assert [result["id"] for result in response_json["results"]] == [notification.id]
assert not response_json["hasNext"]
assert not response_json["hasPrevious"]
def test_notifications_api_supports_limiting_results_count(user, user_client):
Notification.objects.create(user=user, verb="TEST", is_read=False)
Notification.objects.create(user=user, verb="TEST", is_read=False)
Notification.objects.create(user=user, verb="TEST", is_read=False)
response = user_client.get(reverse("misago:apiv2:notifications") + "?limit=2")
assert response.status_code == 200
response_json = response.json()
assert len(response_json["results"]) == 2
assert response_json["hasNext"]
assert not response_json["hasPrevious"]
def test_notifications_api_returns_400_error_if_too_many_results_are_requested(
user, user_client
):
response = user_client.get(reverse("misago:apiv2:notifications") + "?limit=2000")
assert response.status_code == 400
def test_notifications_api_clears_unread_notifications_if_user_has_no_notifications(
user, user_client
):
user.unread_notifications = 10
user.save()
response = user_client.get(reverse("misago:apiv2:notifications"))
assert response.status_code == 200
response_json = response.json()
assert not response_json["results"]
assert not response_json["hasNext"]
assert not response_json["hasPrevious"]
assert response_json["unreadNotifications"] is None
user.refresh_from_db()
assert user.unread_notifications == 0
def test_notifications_api_clears_unread_notifications_if_unread_list_is_empty(
user, user_client
):
user.unread_notifications = 10
user.save()
response = user_client.get(reverse("misago:apiv2:notifications") + "?filter=unread")
assert response.status_code == 200
response_json = response.json()
assert not response_json["results"]
assert not response_json["hasNext"]
assert not response_json["hasPrevious"]
assert response_json["unreadNotifications"] is None
user.refresh_from_db()
assert user.unread_notifications == 0
def test_notifications_api_recounts_unread_notifications_if_only_page_has_unread_items(
user, user_client
):
user.unread_notifications = 0
user.save()
Notification.objects.create(user=user, verb="TEST", is_read=False)
response = user_client.get(reverse("misago:apiv2:notifications"))
assert response.status_code == 200
response_json = response.json()
assert response_json["results"]
assert response_json["unreadNotifications"] == "1"
user.refresh_from_db()
assert user.unread_notifications == 1
def test_notifications_api_recounts_unread_notifications_if_unread_list_has_items(
user, user_client
):
user.unread_notifications = 0
user.save()
notification = Notification.objects.create(user=user, verb="TEST", is_read=False)
response = user_client.get(
reverse("misago:apiv2:notifications")
+ f"?filter=unread&before={notification.id - 1}"
)
assert response.status_code == 200
response_json = response.json()
assert response_json["results"]
assert response_json["unreadNotifications"] == "1"
user.refresh_from_db()
assert user.unread_notifications == 1
def test_notifications_api_recounts_unread_notifications_if_user_has_new_notifications(
user, user_client
):
user.unread_notifications = 0
user.save()
notification = Notification.objects.create(user=user, verb="TEST", is_read=False)
response = user_client.get(
reverse("misago:apiv2:notifications") + f"?before={notification.id - 1}"
)
assert response.status_code == 200
response_json = response.json()
assert response_json["results"]
assert response_json["unreadNotifications"] == "1"
user.refresh_from_db()
assert user.unread_notifications == 1
| 7,454
|
Python
|
.py
| 168
| 39.160714
| 88
| 0.720769
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,718
|
test_notifications_read_all.py
|
rafalp_Misago/misago/apiv2/notifications/tests/test_notifications_read_all.py
|
from django.urls import reverse
from ....notifications.models import Notification
def test_notifications_read_all_api_returns_403_error_if_client_is_no_authenticated(
db, client
):
response = client.post(reverse("misago:apiv2:notifications-read-all"))
assert response.status_code == 403
def test_notifications_read_all_api_marks_users_notifications_as_read(
user, user_client
):
notification = Notification.objects.create(user=user, verb="TEST", is_read=False)
user.unread_notifications = 10
user.save()
response = user_client.post(reverse("misago:apiv2:notifications-read-all"))
assert response.status_code == 204
notification.refresh_from_db()
assert notification.is_read
# User unread notifications counter is zeroed
user.refresh_from_db()
assert user.unread_notifications == 0
def test_notifications_read_all_api_excludes_other_users_notifications(
other_user, user_client
):
notification = Notification.objects.create(
user=other_user, verb="TEST", is_read=False
)
other_user.unread_notifications = 10
other_user.save()
response = user_client.post(reverse("misago:apiv2:notifications-read-all"))
assert response.status_code == 204
notification.refresh_from_db()
assert not notification.is_read
other_user.refresh_from_db()
assert other_user.unread_notifications == 10
def test_notifications_read_all_api_works_when_user_has_no_unread_notifications(
user, user_client
):
notification = Notification.objects.create(user=user, verb="TESt", is_read=True)
user.unread_notifications = 0
user.save()
response = user_client.post(reverse("misago:apiv2:notifications-read-all"))
assert response.status_code == 204
notification.refresh_from_db()
assert notification.is_read
# User unread notifications counter is zeroed
user.refresh_from_db()
assert user.unread_notifications == 0
def test_notifications_read_all_api_works_when_user_has_no_notifications(
user, user_client
):
user.unread_notifications = 0
user.save()
response = user_client.post(reverse("misago:apiv2:notifications-read-all"))
assert response.status_code == 204
# User unread notifications counter is zeroed
user.refresh_from_db()
assert user.unread_notifications == 0
| 2,339
|
Python
|
.py
| 57
| 36.368421
| 85
| 0.746566
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,719
|
models.py
|
rafalp_Misago/misago/themes/models.py
|
from django.db import models
from django.utils.translation import pgettext
from mptt.models import MPTTModel, TreeForeignKey
from .uploadto import (
generate_theme_dirname,
upload_build_css_to,
upload_source_css_to,
upload_media_to,
upload_media_thumbnail_to,
)
class Theme(MPTTModel):
parent = TreeForeignKey(
"self", on_delete=models.PROTECT, null=True, blank=True, related_name="children"
)
name = models.CharField(max_length=255)
dirname = models.CharField(max_length=8, default=generate_theme_dirname)
is_default = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
version = models.CharField(max_length=255, null=True, blank=True)
author = models.CharField(max_length=255, null=True, blank=True)
url = models.URLField(max_length=255, null=True, blank=True)
class MPTTMeta:
order_insertion_by = ["-is_default", "name"]
def delete(self, *args, **kwargs):
for css in self.css.all():
css.delete()
for media in self.media.all():
media.delete()
super().delete(*args, **kwargs)
def __str__(self):
if self.is_default:
return pgettext("default theme name", "Default Misago Theme")
return self.name
@property
def level_range(self):
return range(self.level)
class Css(models.Model):
theme = models.ForeignKey(Theme, on_delete=models.PROTECT, related_name="css")
name = models.CharField(max_length=255)
url = models.URLField(max_length=255, null=True, blank=True)
source_file = models.FileField(
upload_to=upload_source_css_to, max_length=255, null=True, blank=True
)
source_hash = models.CharField(max_length=8, null=True, blank=True)
source_needs_building = models.BooleanField(default=False)
build_file = models.FileField(
upload_to=upload_build_css_to, max_length=255, null=True, blank=True
)
build_hash = models.CharField(max_length=8, null=True, blank=True)
size = models.PositiveIntegerField(default=0)
order = models.IntegerField(default=0)
modified_on = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["order"]
def delete(self, *args, **kwargs):
if self.source_file:
self.source_file.delete(save=False)
if self.build_file:
self.build_file.delete(save=False)
super().delete(*args, **kwargs)
def __str__(self):
return self.name
class Media(models.Model):
theme = models.ForeignKey(Theme, on_delete=models.PROTECT, related_name="media")
name = models.CharField(max_length=255)
file = models.ImageField(upload_to=upload_media_to, max_length=255)
hash = models.CharField(max_length=8)
type = models.CharField(max_length=255)
width = models.PositiveIntegerField(default=0)
height = models.PositiveIntegerField(default=0)
size = models.PositiveIntegerField()
thumbnail = models.ImageField(
upload_to=upload_media_thumbnail_to, max_length=255, null=True, blank=True
)
modified_on = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["name"]
def delete(self, *args, **kwargs):
self.file.delete(save=False)
if self.thumbnail:
self.thumbnail.delete(save=False)
super().delete(*args, **kwargs)
def __str__(self):
return self.name
| 3,432
|
Python
|
.py
| 84
| 34.392857
| 88
| 0.683609
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,720
|
apps.py
|
rafalp_Misago/misago/themes/apps.py
|
from django.apps import AppConfig
class MisagoThemesConfig(AppConfig):
name = "misago.themes"
label = "misago_themes"
verbose_name = "Misago Theming"
def ready(self):
# pylint: disable=unused-import
from .admin import tasks
| 259
|
Python
|
.py
| 8
| 27
| 39
| 0.705645
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,721
|
context_processors.py
|
rafalp_Misago/misago/themes/context_processors.py
|
from .activetheme import get_active_theme
from .cache import get_theme_cache, set_theme_cache
def theme(request):
active_theme = get_theme_cache(request.cache_versions)
if active_theme is None:
active_theme = get_active_theme()
set_theme_cache(request.cache_versions, active_theme)
return {"theme": active_theme}
| 344
|
Python
|
.py
| 8
| 38.125
| 61
| 0.735736
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,722
|
uploadto.py
|
rafalp_Misago/misago/themes/uploadto.py
|
from django.utils.crypto import get_random_string
def generate_theme_dirname():
return get_random_string(8)
def upload_source_css_to(instance, filename):
filename = add_hash_to_filename(instance.source_hash, filename)
return "themes/%s/css/%s" % (instance.theme.dirname, filename)
def upload_build_css_to(instance, filename):
filename = add_hash_to_filename(instance.build_hash, filename)
return "themes/%s/css/%s" % (instance.theme.dirname, filename)
def upload_media_to(instance, filename):
filename = add_hash_to_filename(instance.hash, filename)
return "themes/%s/media/%s" % (instance.theme.dirname, filename)
def upload_media_thumbnail_to(instance, filename):
return "themes/%s/media/%s" % (instance.theme.dirname, filename)
def add_hash_to_filename(hash, filename): # pylint: disable=redefined-builtin
if ".%s." % hash in filename:
return filename
extension_start = filename.rfind(".")
return "%s.%s%s" % (filename[:extension_start], hash, filename[extension_start:])
| 1,040
|
Python
|
.py
| 19
| 50.368421
| 85
| 0.730426
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,723
|
cache.py
|
rafalp_Misago/misago/themes/cache.py
|
from django.core.cache import cache
from . import THEME_CACHE
from ..cache.versions import invalidate_cache
def get_theme_cache(cache_versions):
key = get_cache_key(cache_versions)
return cache.get(key)
def set_theme_cache(cache_versions, theme):
key = get_cache_key(cache_versions)
cache.set(key, theme)
def get_cache_key(cache_versions):
return "%s_%s" % (THEME_CACHE, cache_versions[THEME_CACHE])
def clear_theme_cache():
invalidate_cache(THEME_CACHE)
| 488
|
Python
|
.py
| 13
| 34
| 63
| 0.748927
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,724
|
activetheme.py
|
rafalp_Misago/misago/themes/activetheme.py
|
from .models import Theme
def get_active_theme():
active_theme = Theme.objects.get(is_active=True)
themes = active_theme.get_ancestors(include_self=True)
themes = themes.prefetch_related("css")
include_defaults = False
styles = []
for theme in themes:
if theme.is_default:
include_defaults = True
for css in theme.css.all():
if css.url:
styles.append(css.url)
elif css.source_needs_building:
if css.build_file:
styles.append(css.build_file.url)
else:
styles.append(css.source_file.url)
return {"include_defaults": include_defaults, "styles": styles}
| 715
|
Python
|
.py
| 19
| 27.947368
| 67
| 0.606368
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,725
|
0002_create_default_theme_and_cache_version.py
|
rafalp_Misago/misago/themes/migrations/0002_create_default_theme_and_cache_version.py
|
# Generated by Django 1.11.16 on 2018-12-26 16:11
from django.db import migrations
from .. import THEME_CACHE
from ...cache.operations import StartCacheVersioning
def create_default_theme(apps, schema_editor):
Theme = apps.get_model("misago_themes", "Theme")
Theme.objects.create(
name="default",
is_default=True,
is_active=True,
lft=1,
rght=2,
tree_id=0,
level=0,
)
class Migration(migrations.Migration):
dependencies = [("misago_themes", "0001_initial")]
operations = [
StartCacheVersioning(THEME_CACHE),
migrations.RunPython(create_default_theme),
]
| 655
|
Python
|
.py
| 21
| 25.333333
| 54
| 0.670382
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,726
|
0001_initial.py
|
rafalp_Misago/misago/themes/migrations/0001_initial.py
|
# Generated by Django 1.11.17 on 2019-01-03 21:15
from django.db import migrations, models
import django.db.models.deletion
import misago.themes.uploadto
import mptt.fields
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Css",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=255)),
("url", models.URLField(blank=True, max_length=255, null=True)),
(
"source_file",
models.FileField(
blank=True,
max_length=255,
null=True,
upload_to=misago.themes.uploadto.upload_source_css_to,
),
),
("source_hash", models.CharField(blank=True, max_length=8, null=True)),
("source_needs_building", models.BooleanField(default=False)),
(
"build_file",
models.FileField(
blank=True,
max_length=255,
null=True,
upload_to=misago.themes.uploadto.upload_build_css_to,
),
),
("build_hash", models.CharField(blank=True, max_length=8, null=True)),
("size", models.PositiveIntegerField(default=0)),
("order", models.IntegerField(default=0)),
("modified_on", models.DateTimeField(auto_now=True)),
],
options={"ordering": ["order"]},
),
migrations.CreateModel(
name="Media",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=255)),
(
"file",
models.ImageField(
max_length=255, upload_to=misago.themes.uploadto.upload_media_to
),
),
("hash", models.CharField(max_length=8)),
("type", models.CharField(max_length=255)),
("width", models.PositiveIntegerField(default=0)),
("height", models.PositiveIntegerField(default=0)),
("size", models.PositiveIntegerField()),
(
"thumbnail",
models.ImageField(
blank=True,
max_length=255,
null=True,
upload_to=misago.themes.uploadto.upload_media_thumbnail_to,
),
),
("modified_on", models.DateTimeField(auto_now=True)),
],
options={"ordering": ["name"]},
),
migrations.CreateModel(
name="Theme",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=255)),
(
"dirname",
models.CharField(
default=misago.themes.uploadto.generate_theme_dirname,
max_length=8,
),
),
("is_default", models.BooleanField(default=False)),
("is_active", models.BooleanField(default=False)),
("version", models.CharField(blank=True, max_length=255, null=True)),
("author", models.CharField(blank=True, max_length=255, null=True)),
("url", models.URLField(blank=True, max_length=255, null=True)),
("lft", models.PositiveIntegerField(db_index=True, editable=False)),
("rght", models.PositiveIntegerField(db_index=True, editable=False)),
("tree_id", models.PositiveIntegerField(db_index=True, editable=False)),
("level", models.PositiveIntegerField(db_index=True, editable=False)),
(
"parent",
mptt.fields.TreeForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.PROTECT,
related_name="children",
to="misago_themes.Theme",
),
),
],
options={"abstract": False},
),
migrations.AddField(
model_name="media",
name="theme",
field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="media",
to="misago_themes.Theme",
),
),
migrations.AddField(
model_name="css",
name="theme",
field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="css",
to="misago_themes.Theme",
),
),
]
| 5,816
|
Python
|
.py
| 148
| 21.864865
| 88
| 0.437677
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,727
|
0003_auto_20190518_1659.py
|
rafalp_Misago/misago/themes/migrations/0003_auto_20190518_1659.py
|
# Generated by Django 2.2.1 on 2019-05-18 16:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("misago_themes", "0002_create_default_theme_and_cache_version")]
operations = [
migrations.AlterField(
model_name="theme",
name="level",
field=models.PositiveIntegerField(editable=False),
),
migrations.AlterField(
model_name="theme",
name="lft",
field=models.PositiveIntegerField(editable=False),
),
migrations.AlterField(
model_name="theme",
name="rght",
field=models.PositiveIntegerField(editable=False),
),
]
| 729
|
Python
|
.py
| 21
| 25.52381
| 85
| 0.610795
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,728
|
test_adding_hash_to_filename.py
|
rafalp_Misago/misago/themes/tests/test_adding_hash_to_filename.py
|
from ..uploadto import add_hash_to_filename
def test_hash_is_added_before_file_extension():
filename = add_hash_to_filename("hash", "test.jpg")
assert filename == "test.hash.jpg"
def test_hash_is_added_before_file_extension_in_filename_with_multiple_dots():
filename = add_hash_to_filename("hash", "test.image.jpg")
assert filename == "test.image.hash.jpg"
def test_hash_is_not_added_to_filename_if_it_already_contains_it():
filename = add_hash_to_filename("hash", "test.hash.jpg")
assert filename == "test.hash.jpg"
| 547
|
Python
|
.py
| 10
| 50.7
| 78
| 0.723164
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,729
|
conftest.py
|
rafalp_Misago/misago/themes/tests/conftest.py
|
import pytest
from ..models import Theme
@pytest.fixture
def default_theme(db):
return Theme.objects.get(is_default=True)
@pytest.fixture
def theme(db):
return Theme.objects.create(name="Custom theme")
@pytest.fixture
def other_theme(db):
return Theme.objects.create(name="Other theme")
@pytest.fixture
def active_theme(theme):
Theme.objects.update(is_active=False)
theme.is_active = True
theme.save()
return theme
| 452
|
Python
|
.py
| 17
| 23.411765
| 52
| 0.762911
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,730
|
test_styles_are_included_on_page.py
|
rafalp_Misago/misago/themes/tests/test_styles_are_included_on_page.py
|
from ...test import assert_contains
def test_active_theme_styles_are_included_in_page_html(client, active_theme):
css = active_theme.css.create(name="test", url="https://cdn.example.com/style.css")
response = client.get("/")
assert_contains(response, 'link href="%s" rel="stylesheet"' % css.url)
| 310
|
Python
|
.py
| 5
| 58.2
| 87
| 0.716172
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,731
|
test_context_processors.py
|
rafalp_Misago/misago/themes/tests/test_context_processors.py
|
from unittest.mock import Mock
import pytest
from .. import THEME_CACHE
from ..context_processors import theme as context_processor
@pytest.fixture
def mock_request(cache_versions):
return Mock(cache_versions=cache_versions)
def test_theme_data_is_included_in_template_context(db, mock_request):
assert context_processor(mock_request)["theme"]
def test_theme_is_loaded_from_database_if_cache_is_not_available(
db, mocker, mock_request, django_assert_num_queries
):
mocker.patch("django.core.cache.cache.get", return_value=None)
with django_assert_num_queries(3):
context_processor(mock_request)
def test_theme_is_loaded_from_cache_if_it_is_set(
db, mocker, mock_request, django_assert_num_queries
):
cache_get = mocker.patch("django.core.cache.cache.get", return_value={})
with django_assert_num_queries(0):
context_processor(mock_request)
cache_get.assert_called_once()
def test_theme_cache_is_set_if_none_exists(db, mocker, mock_request):
cache_set = mocker.patch("django.core.cache.cache.set")
mocker.patch("django.core.cache.cache.get", return_value=None)
context_processor(mock_request)
cache_set.assert_called_once()
def test_theme_cache_is_not_set_if_it_already_exists(
db, mocker, mock_request, django_assert_num_queries
):
cache_set = mocker.patch("django.core.cache.cache.set")
mocker.patch("django.core.cache.cache.get", return_value={})
with django_assert_num_queries(0):
context_processor(mock_request)
cache_set.assert_not_called()
def test_theme_cache_key_includes_cache_name_and_version(
db, mocker, mock_request, cache_versions
):
cache_set = mocker.patch("django.core.cache.cache.set")
mocker.patch("django.core.cache.cache.get", return_value=None)
context_processor(mock_request)
cache_key = cache_set.call_args[0][0]
assert THEME_CACHE in cache_key
assert cache_versions[THEME_CACHE] in cache_key
| 1,958
|
Python
|
.py
| 44
| 40.295455
| 76
| 0.745915
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,732
|
test_getting_active_theme.py
|
rafalp_Misago/misago/themes/tests/test_getting_active_theme.py
|
from django.core.files.base import ContentFile
from ..activetheme import get_active_theme
from ..models import Theme
def test_active_theme_data_can_be_obtained(db):
assert get_active_theme()
def test_if_active_theme_is_default_theme_include_defaults_flag_is_set(db):
assert get_active_theme()["include_defaults"]
def test_if_active_theme_is_default_themes_child_include_defaults_flag_is_set(
default_theme, active_theme
):
active_theme.parent = default_theme
active_theme.save()
assert get_active_theme()["include_defaults"]
def test_if_active_theme_is_not_default_themes_child_include_defaults_flag_is_not_set(
active_theme,
):
assert not get_active_theme()["include_defaults"]
def test_active_theme_styles_are_included(active_theme):
active_theme.css.create(name="test", url="https://example.com")
assert get_active_theme()["styles"]
def test_active_theme_parents_styles_are_included(active_theme):
parent_theme = Theme.objects.create(name="Parent theme")
parent_theme.css.create(name="test", url="https://example.com")
active_theme.move_to(parent_theme)
active_theme.save()
assert get_active_theme()["styles"]
def test_active_theme_child_themes_styles_are_not_included(active_theme):
child_theme = Theme.objects.create(parent=active_theme, name="Child theme")
child_theme.css.create(name="test", url="https://example.com")
assert not get_active_theme()["styles"]
def test_active_theme_styles_are_ordered(active_theme):
last_css = active_theme.css.create(
name="test", url="https://last-example.com", order=1
)
first_css = active_theme.css.create(
name="test", url="https://first-example.com", order=0
)
assert get_active_theme()["styles"] == [first_css.url, last_css.url]
def test_active_theme_styles_list_includes_url_to_remote_css(active_theme):
css = active_theme.css.create(name="test", url="https://last-example.com")
assert get_active_theme()["styles"] == [css.url]
def test_active_theme_styles_list_contains_url_to_local_css(active_theme):
css = active_theme.css.create(
name="test",
source_file=ContentFile("body {}", name="test.css"),
source_hash="abcdefgh",
)
assert get_active_theme()["styles"] == [css.source_file.url]
def test_active_theme_styles_list_contains_url_to_local_built_css(active_theme):
css = active_theme.css.create(
name="test",
source_needs_building=True,
build_file=ContentFile("body {}", name="test.css"),
build_hash="abcdefgh",
)
assert get_active_theme()["styles"] == [css.build_file.url]
def test_active_theme_styles_list_exclude_url_to_css_that_has_not_been_built(
active_theme,
):
active_theme.css.create(
name="test",
source_file=ContentFile("body {}", name="test.css"),
source_hash="abcdefgh",
source_needs_building=True,
)
assert not get_active_theme()["styles"]
| 2,976
|
Python
|
.py
| 66
| 39.969697
| 86
| 0.703678
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,733
|
exporter.py
|
rafalp_Misago/misago/themes/admin/exporter.py
|
import json
import os
import shutil
from tempfile import TemporaryDirectory
from django.http import FileResponse
from ...core.utils import slugify
def export_theme(theme):
with TemporaryDirectory() as tmp_dir:
export_dir = create_export_directory(tmp_dir, theme)
manifest = create_theme_manifest(theme)
manifest["css"] = write_theme_css(export_dir, theme)
manifest["media"] = write_theme_media(export_dir, theme)
write_theme_manifest(export_dir, manifest)
export_file = zip_theme_export(tmp_dir, export_dir)
export_filename = os.path.split(export_file)[-1]
response = FileResponse(open(export_file, "rb"), content_type="application/zip")
response["Content-Length"] = os.path.getsize(export_file)
response["Content-Disposition"] = "inline; filename=%s" % export_filename
return response
def create_export_directory(tmp_dir, theme):
export_name = get_export_name(theme)
export_dir = os.path.join(tmp_dir, export_name)
os.mkdir(export_dir)
return export_dir
def get_export_name(theme):
if theme.version:
return "%s-%s" % (slugify(theme.name), theme.version.replace(".", "-"))
return slugify(theme.name)
def create_theme_manifest(theme):
return {
"name": theme.name,
"version": theme.version,
"author": theme.author,
"url": theme.url,
"css": [],
"media": [],
}
def write_theme_css(export_dir, theme):
files_dir = create_sub_directory(export_dir, "css")
files = []
for css in theme.css.all():
if css.url:
files.append({"name": css.name, "url": css.url})
else:
files.append(
{"name": css.name, "path": copy_asset_file(files_dir, css.source_file)}
)
return files
def write_theme_media(export_dir, theme):
files_dir = create_sub_directory(export_dir, "media")
files = []
for media in theme.media.all():
files.append(
{
"name": media.name,
"type": media.type,
"path": copy_asset_file(files_dir, media.file),
}
)
return files
def create_sub_directory(export_dir, dirname):
new_dir = os.path.join(export_dir, dirname)
os.mkdir(new_dir)
return new_dir
def copy_asset_file(export_dir, asset_file):
filename = os.path.split(asset_file.name)[-1]
dst_path = os.path.join(export_dir, filename)
with open(dst_path, "wb") as fp:
for chunk in asset_file.chunks():
fp.write(chunk)
return filename
def write_theme_manifest(export_dir, manifest):
manifest_path = os.path.join(export_dir, "manifest.json")
with open(manifest_path, "w") as fp:
json.dump(manifest, fp, ensure_ascii=False, indent=2)
def zip_theme_export(tmp_dir, export_dir):
dir_name = os.path.split(export_dir)[-1]
return shutil.make_archive(export_dir, "zip", tmp_dir, dir_name)
| 2,993
|
Python
|
.py
| 78
| 31.333333
| 88
| 0.64147
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,734
|
importer.py
|
rafalp_Misago/misago/themes/admin/importer.py
|
import json
import os
from tempfile import TemporaryDirectory
from zipfile import BadZipFile, ZipFile
from django.core.files.uploadedfile import UploadedFile
from django.utils.translation import pgettext, pgettext_lazy
from ..models import Theme
from .css import create_css
from .forms import (
ThemeCssUrlManifest,
ThemeManifest,
create_css_file_manifest,
create_media_file_manifest,
)
from .media import create_media
from .tasks import build_theme_css, update_remote_css_size
INVALID_MANIFEST_ERROR = pgettext_lazy(
"admin theme import",
'"manifest.json" contained by ZIP file is not a valid theme manifest file.',
)
class ThemeImportError(BaseException):
pass
class InvalidThemeManifest(ThemeImportError):
def __init__(self):
super().__init__(INVALID_MANIFEST_ERROR)
def import_theme(name, parent, zipfile):
with TemporaryDirectory() as tmp_dir:
extract_zipfile_to_tmp_dir(zipfile, tmp_dir)
validate_zipfile_contains_single_directory(tmp_dir)
theme_dir = os.path.join(tmp_dir, os.listdir(tmp_dir)[0])
cleaned_manifest = clean_theme_contents(theme_dir)
theme = create_theme_from_manifest(name, parent, cleaned_manifest)
try:
create_css_from_manifest(theme_dir, theme, cleaned_manifest["css"])
create_media_from_manifest(theme_dir, theme, cleaned_manifest["media"])
except Exception:
theme.delete()
raise InvalidThemeManifest()
else:
for css in theme.css.filter(url__isnull=False):
update_remote_css_size.delay(css.pk)
build_theme_css.delay(theme.pk)
return theme
def extract_zipfile_to_tmp_dir(zipfile, tmp_dir):
try:
ZipFile(zipfile).extractall(tmp_dir)
except BadZipFile:
raise ThemeImportError(
pgettext("admin theme import", "Uploaded ZIP file could not be extracted.")
)
def validate_zipfile_contains_single_directory(tmp_dir):
dir_contents = os.listdir(tmp_dir)
if not dir_contents:
raise ThemeImportError(
pgettext("admin theme import", "Uploaded ZIP file is empty.")
)
if len(dir_contents) > 1:
raise ThemeImportError(
pgettext(
"admin theme import",
"Uploaded ZIP file should contain single directory.",
)
)
if not os.path.isdir(os.path.join(tmp_dir, dir_contents[0])):
raise ThemeImportError(
pgettext(
"admin theme import", "Uploaded ZIP file didn't contain a directory."
)
)
def clean_theme_contents(theme_dir):
manifest = read_manifest(theme_dir)
return clean_manifest(theme_dir, manifest)
def read_manifest(theme_dir):
try:
with open(os.path.join(theme_dir, "manifest.json")) as fp:
return json.load(fp)
except FileNotFoundError:
raise ThemeImportError(
pgettext(
"admin theme import",
'Uploaded ZIP file didn\'t contain a "manifest.json".',
)
)
except json.decoder.JSONDecodeError:
raise ThemeImportError(
pgettext(
"admin theme import",
'"manifest.json" contained by ZIP file is not a valid JSON file.',
)
)
def clean_manifest(theme_dir, manifest):
if not isinstance(manifest, dict):
raise InvalidThemeManifest()
form = ThemeManifest(manifest)
if not form.is_valid():
raise InvalidThemeManifest()
cleaned_manifest = form.cleaned_data.copy()
cleaned_manifest["css"] = clean_css_list(theme_dir, manifest.get("css"))
cleaned_manifest["media"] = clean_media_list(theme_dir, manifest.get("media"))
return cleaned_manifest
def clean_css_list(theme_dir, manifest):
if not isinstance(manifest, list):
raise InvalidThemeManifest()
theme_css_dir = os.path.join(theme_dir, "css")
if not os.path.isdir(theme_css_dir):
raise InvalidThemeManifest()
cleaned_data = []
for item in manifest:
cleaned_data.append(clean_css_list_item(theme_css_dir, item))
return cleaned_data
def clean_css_list_item(theme_css_dir, item):
if not isinstance(item, dict):
raise InvalidThemeManifest()
if item.get("url"):
return clean_css_url(item)
if item.get("path"):
return clean_css_file(theme_css_dir, item)
raise InvalidThemeManifest()
def clean_css_url(data):
form = ThemeCssUrlManifest(data)
if not form.is_valid():
raise InvalidThemeManifest()
return form.cleaned_data
def clean_css_file(theme_css_dir, data):
file_manifest = create_css_file_manifest(theme_css_dir)
if data.get("path"):
data["path"] = os.path.join(theme_css_dir, str(data["path"]))
form = file_manifest(data)
if not form.is_valid():
raise InvalidThemeManifest()
return form.cleaned_data
def clean_media_list(theme_dir, manifest):
if not isinstance(manifest, list):
raise InvalidThemeManifest()
theme_media_dir = os.path.join(theme_dir, "media")
if not os.path.isdir(theme_media_dir):
raise InvalidThemeManifest()
cleaned_data = []
for item in manifest:
cleaned_data.append(clean_media_list_item(theme_media_dir, item))
return cleaned_data
def clean_media_list_item(theme_media_dir, data):
if not isinstance(data, dict):
raise InvalidThemeManifest()
file_manifest = create_media_file_manifest(theme_media_dir)
if data.get("path"):
data["path"] = os.path.join(theme_media_dir, str(data["path"]))
form = file_manifest(data)
if not form.is_valid():
raise InvalidThemeManifest()
return form.cleaned_data
def create_theme_from_manifest(name, parent, cleaned_data):
return Theme.objects.create(
name=name or cleaned_data["name"],
parent=parent,
version=cleaned_data.get("version") or None,
author=cleaned_data.get("author") or None,
url=cleaned_data.get("url") or None,
)
def create_css_from_manifest(tmp_dir, theme, manifest):
for item in manifest:
if "url" in item:
theme.css.create(**item, order=theme.css.count())
else:
with open(item["path"], "rb") as fp:
file_obj = UploadedFile(
fp,
name=item["name"],
content_type="text/css",
size=os.path.getsize(item["path"]),
)
create_css(theme, file_obj)
def create_media_from_manifest(tmp_dir, theme, manifest):
for item in manifest:
with open(item["path"], "rb") as fp:
file_obj = UploadedFile(
fp,
name=item["name"],
content_type=item["type"],
size=os.path.getsize(item["path"]),
)
create_media(theme, file_obj)
| 6,983
|
Python
|
.py
| 182
| 30.362637
| 87
| 0.646161
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,735
|
tasks.py
|
rafalp_Misago/misago/themes/admin/tasks.py
|
import requests
from celery import shared_task
from requests.exceptions import RequestException
from ..cache import clear_theme_cache
from ..models import Theme, Css
from .css import get_theme_media_map, rebuild_css
@shared_task
def update_remote_css_size(pk):
try:
css = Css.objects.get(pk=pk, url__isnull=False)
except Css.DoesNotExist:
pass
else:
css.size = get_remote_css_size(css.url)
css.save(update_fields=["size"])
def get_remote_css_size(url):
try:
with requests.get(url, stream=True) as response:
response.raise_for_status()
return sum(len(chunk) for chunk in response.iter_content(4096))
except RequestException:
return 0
@shared_task
def build_single_theme_css(pk):
try:
css = Css.objects.get(pk=pk, source_needs_building=True)
except Css.DoesNotExist:
pass
else:
media_map = get_theme_media_map(css.theme)
rebuild_css(media_map, css)
clear_theme_cache()
@shared_task
def build_theme_css(pk):
try:
theme = Theme.objects.get(pk=pk)
except Theme.DoesNotExist:
pass
else:
media_map = get_theme_media_map(theme)
for css in theme.css.filter(source_needs_building=True):
rebuild_css(media_map, css)
clear_theme_cache()
| 1,342
|
Python
|
.py
| 43
| 25.162791
| 75
| 0.671318
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,736
|
__init__.py
|
rafalp_Misago/misago/themes/admin/__init__.py
|
from django.urls import path
from django.utils.translation import pgettext_lazy
from .views import (
ActivateTheme,
DeleteTheme,
DeleteThemeCss,
DeleteThemeMedia,
EditTheme,
EditThemeCss,
EditThemeCssLink,
MoveThemeCssDown,
MoveThemeCssUp,
NewTheme,
NewThemeCss,
NewThemeCssLink,
ExportTheme,
ImportTheme,
ThemeAssets,
ThemesList,
UploadThemeCss,
UploadThemeMedia,
)
class MisagoAdminExtension:
def register_urlpatterns(self, urlpatterns):
# Themes
urlpatterns.namespace("themes/", "themes")
urlpatterns.patterns(
"themes",
path("", ThemesList.as_view(), name="index"),
path("new/", NewTheme.as_view(), name="new"),
path("edit/<int:pk>/", EditTheme.as_view(), name="edit"),
path("delete/<int:pk>/", DeleteTheme.as_view(), name="delete"),
path("activate/<int:pk>/", ActivateTheme.as_view(), name="activate"),
path("export/<int:pk>/", ExportTheme.as_view(), name="export"),
path("import/", ImportTheme.as_view(), name="import"),
path("assets/<int:pk>/", ThemeAssets.as_view(), name="assets"),
path(
"assets/<int:pk>/delete-css/",
DeleteThemeCss.as_view(),
name="delete-css",
),
path(
"assets/<int:pk>/delete-media/",
DeleteThemeMedia.as_view(),
name="delete-media",
),
path(
"assets/<int:pk>/upload-css/",
UploadThemeCss.as_view(),
name="upload-css",
),
path(
"assets/<int:pk>/upload-media/",
UploadThemeMedia.as_view(),
name="upload-media",
),
path(
"assets/<int:pk>/move-css-down/<int:css_pk>/",
MoveThemeCssDown.as_view(),
name="move-css-down",
),
path(
"assets/<int:pk>/move-css-up/<int:css_pk>/",
MoveThemeCssUp.as_view(),
name="move-css-up",
),
path(
"assets/<int:pk>/new-css/",
NewThemeCss.as_view(),
name="new-css-file",
),
path(
"assets/<int:pk>/edit-css/<int:css_pk>/",
EditThemeCss.as_view(),
name="edit-css-file",
),
path(
"assets/<int:pk>/new-css-link/",
NewThemeCssLink.as_view(),
name="new-css-link",
),
path(
"assets/<int:pk>/edit-css-link/<int:css_pk>/",
EditThemeCssLink.as_view(),
name="edit-css-link",
),
)
def register_navigation_nodes(self, site):
site.add_node(
name=pgettext_lazy("admin node", "Themes"),
icon="fa fa-paint-brush",
after="attachments:index",
namespace="themes",
)
| 3,110
|
Python
|
.py
| 94
| 21.361702
| 81
| 0.495352
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,737
|
validators.py
|
rafalp_Misago/misago/themes/admin/validators.py
|
import re
from django.forms import ValidationError
from django.utils.translation import pgettext
FILENAME_CONTENT = re.compile(r"([a-zA-Z0-9]|\.|_|-)+")
FILENAME_TANGIBILITY = re.compile(r"[a-zA-Z0-9]")
def validate_css_name(filename):
if not filename.lower().endswith(".css"):
raise ValidationError(
pgettext("admin css name validator", "Name is missing an .css extension.")
)
if filename.startswith("."):
raise ValidationError(
pgettext("admin css name validator", 'Name can\'t start with period (".").')
)
if not FILENAME_CONTENT.fullmatch(filename[:-4]):
raise ValidationError(
pgettext(
"admin css name validator",
"Name can contain only latin alphabet characters, digits, dots, underscores and dashes.",
)
)
if not FILENAME_TANGIBILITY.match(filename[:-4]):
raise ValidationError(
pgettext(
"admin css name validator",
"Name has to contain at least one latin alphabet character or digit.",
)
)
def validate_css_name_is_available(instance, name):
queryset = instance.theme.css.filter(name=name)
if instance.pk:
queryset = queryset.exclude(pk=instance.pk)
if queryset.exists():
raise ValidationError(
pgettext(
"admin css name unique validator",
"This name is already in use by other asset.",
)
)
| 1,518
|
Python
|
.py
| 39
| 29.794872
| 105
| 0.614966
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,738
|
media.py
|
rafalp_Misago/misago/themes/admin/media.py
|
import io
from PIL import Image
from django.core.files.images import ImageFile
from ...core.utils import get_file_hash
IMAGE_TYPES = ("image/gif", "image/png", "image/jpeg", "image/bmp", "image/webp")
THUMBNAIL_SIZE = (32, 32)
def create_media(theme, media):
if media_exists(theme, media):
delete_media(theme, media)
if media_is_image(media):
save_image(theme, media)
else:
save_media(theme, media)
def media_exists(theme, media):
return theme.media.filter(name=media.name).exists()
def delete_media(theme, media):
theme.media.get(name=media.name).delete()
def media_is_image(image):
return image.content_type in IMAGE_TYPES
def save_image(theme, image):
try:
img = Image.open(image.file)
except Exception: # pylint: disable=broad-except
return
else:
width, height = img.size
theme.media.create(
name=image.name,
file=image,
hash=get_file_hash(image),
type=image.content_type,
width=width,
height=height,
size=image.size,
thumbnail=get_image_thumbnail(img, image.name),
)
img.close()
def get_image_thumbnail(image, src_name):
img = image.copy()
img.thumbnail(THUMBNAIL_SIZE)
file = io.BytesIO()
img.save(file, format="png")
img.close()
filename = ".".join(src_name.split(".")[:1])
return ImageFile(file, name="thumb_%s.png" % filename)
def save_media(theme, media):
theme.media.create(
name=media.name,
file=media,
hash=get_file_hash(media),
type=media.content_type,
size=media.size,
)
| 1,644
|
Python
|
.py
| 53
| 25.169811
| 81
| 0.655414
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,739
|
css.py
|
rafalp_Misago/misago/themes/admin/css.py
|
import json
import re
from django.core.files.base import ContentFile
from ...core.utils import get_file_hash
def create_css(theme, css):
order = None
if css_exists(theme, css):
order = get_css_order(theme, css)
delete_css(theme, css)
save_css(theme, css, order)
def css_exists(theme, css):
return theme.css.filter(name=css.name).exists()
def get_css_order(theme, css):
return theme.css.get(name=css.name).order
def delete_css(theme, css):
theme.css.get(name=css.name).delete()
def save_css(theme, css, order=None):
if order is None:
order = get_next_css_order(theme)
theme.css.create(
name=css.name,
source_file=css,
source_hash=get_file_hash(css),
source_needs_building=css_needs_rebuilding(css),
size=css.size,
order=order,
)
def css_needs_rebuilding(css):
css.seek(0)
css_source = css.read().decode("utf-8")
return "url(" in css_source
def get_theme_media_map(theme):
media_map = {}
for media in theme.media.all():
escaped_url = json.dumps(media.file.url)
media_map[media.name] = escaped_url
media_filename = str(media.file).split("/")[-1]
media_map[media_filename] = escaped_url
return media_map
def rebuild_css(media_map, css):
if css.build_file:
css.build_file.delete(save=False)
css_source = css.source_file.read().decode("utf-8")
build_source = change_css_source(media_map, css_source).encode()
build_file_name = css.name
if css.source_hash in build_file_name:
build_file_name = build_file_name.replace(".%s" % css.source_hash, "")
build_file = ContentFile(build_source, build_file_name)
css.build_file = build_file
css.build_hash = get_file_hash(build_file)
css.size = len(build_source)
css.save()
CSS_URL_REGEX = re.compile(r"url\((.+)\)")
def change_css_source(media_map, css_source):
url_replacer = get_url_replacer(media_map)
return CSS_URL_REGEX.sub(url_replacer, css_source).strip()
def get_url_replacer(media_map):
def replacer(matchobj):
url = matchobj.group(1).strip("\"'").strip()
if is_url_absolute(url):
return matchobj.group(0)
media_name = url.split("/")[-1]
if media_name in media_map:
return "url(%s)" % media_map[media_name]
return matchobj.group(0)
return replacer
def is_url_absolute(url):
if url.startswith("//") or url.startswith("://"):
return True
if url.lower().startswith("https://"):
return True
if url.lower().startswith("http://"):
return True
return False
def get_next_css_order(theme):
last_css = theme.css.order_by("order").last()
if last_css:
return last_css.order + 1
return 0
def move_css_up(theme, css):
previous_css = theme.css.filter(order__lt=css.order).order_by("-order").first()
if not previous_css:
return False
css.order, previous_css.order = previous_css.order, css.order
css.save(update_fields=["order"])
previous_css.save(update_fields=["order"])
return True
def move_css_down(theme, css):
next_css = theme.css.filter(order__gt=css.order).order_by("order").first()
if not next_css:
return False
css.order, next_css.order = next_css.order, css.order
css.save(update_fields=["order"])
next_css.save(update_fields=["order"])
return True
| 3,459
|
Python
|
.py
| 95
| 30.452632
| 83
| 0.656014
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,740
|
forms.py
|
rafalp_Misago/misago/themes/admin/forms.py
|
import re
from django import forms
from django.core.files.base import ContentFile
from django.utils.translation import pgettext, pgettext_lazy
from mptt.forms import TreeNodeChoiceField
from ...core.utils import get_file_hash
from ..models import Theme, Css
from .css import css_needs_rebuilding, create_css, get_next_css_order
from .media import create_media
from .validators import validate_css_name, validate_css_name_is_available
class ThemeChoiceField(TreeNodeChoiceField):
level_indicator = "- - "
def __init__(self, *args, **kwargs):
kwargs.setdefault("queryset", Theme.objects.all())
kwargs.setdefault(
"empty_label", pgettext_lazy("admin theme parent empty label", "No parent")
)
kwargs.setdefault("level_indicator", self.level_indicator)
super().__init__(*args, **kwargs)
class ThemeForm(forms.ModelForm):
name = forms.CharField(label=pgettext_lazy("admin theme form", "Name"))
parent = ThemeChoiceField(
label=pgettext_lazy("admin theme form", "Parent"), required=False
)
version = forms.CharField(
label=pgettext_lazy("admin theme form", "Version"), required=False
)
author = forms.CharField(
label=pgettext_lazy("admin theme form", "Author(s)"), required=False
)
url = forms.URLField(label=pgettext_lazy("admin theme form", "Url"), required=False)
class Meta:
model = Theme
fields = ["name", "parent", "version", "author", "url"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.limit_parent_choices()
def limit_parent_choices(self):
if not self.instance or not self.instance.pk:
return
self.fields["parent"].queryset = Theme.objects.exclude(
tree_id=self.instance.tree_id,
lft__gte=self.instance.lft,
rght__lte=self.instance.rght,
)
class ImportForm(forms.Form):
name = forms.CharField(
label=pgettext_lazy("admin theme form", "Name"),
help_text=pgettext_lazy(
"admin theme form",
"Leave this field empty to use theme name from imported file.",
),
max_length=255,
required=False,
)
parent = ThemeChoiceField(
label=pgettext_lazy("admin theme form", "Parent"), required=False
)
upload = forms.FileField(
label=pgettext_lazy("admin theme form", "Theme file"),
help_text=pgettext_lazy("admin theme form", "Theme file should be a ZIP file."),
)
def clean_upload(self):
data = self.cleaned_data["upload"]
error_message = pgettext(
"admin theme form", "Uploaded file is not a valid ZIP file."
)
if not data.name.lower().endswith(".zip"):
raise forms.ValidationError(error_message)
if data.content_type not in ("application/zip", "application/octet-stream"):
raise forms.ValidationError(error_message)
return data
class ThemeManifest(forms.Form):
name = forms.CharField(max_length=255)
version = forms.CharField(max_length=255, required=False)
author = forms.CharField(max_length=255, required=False)
url = forms.URLField(max_length=255, required=False)
class ThemeCssUrlManifest(forms.Form):
name = forms.CharField(max_length=255)
url = forms.URLField(max_length=255)
def create_css_file_manifest(allowed_path):
class ThemeCssFileManifest(forms.Form):
name = forms.CharField(max_length=255, validators=[validate_css_name])
path = forms.FilePathField(
allowed_path, match=re.compile(r"\.css$", re.IGNORECASE)
)
return ThemeCssFileManifest
def create_media_file_manifest(allowed_path):
class ThemeMediaFileManifest(forms.Form):
name = forms.CharField(max_length=255)
type = forms.CharField(max_length=255)
path = forms.FilePathField(allowed_path)
return ThemeMediaFileManifest
# Multiple file support from Django docs
class MultipleFileInput(forms.ClearableFileInput):
allow_multiple_selected = True
class MultipleFileField(forms.FileField):
def __init__(self, *args, **kwargs):
kwargs.setdefault("widget", MultipleFileInput())
super().__init__(*args, **kwargs)
def clean(self, data, initial=None):
if self.required and not data:
raise forms.ValidationError(
self.error_messages["required"], code="required"
)
single_file_clean = super().clean
if isinstance(data, (list, tuple)):
return [single_file_clean(d, initial) for d in data]
return [single_file_clean(data, initial)]
class UploadAssetsForm(forms.Form):
allowed_content_types = []
allowed_extensions = []
assets = MultipleFileField(
error_messages={
"required": pgettext_lazy(
"admin theme assets form", "No files have been uploaded."
)
},
)
def __init__(self, *args, instance=None):
self.instance = instance
super().__init__(*args)
def clean_assets(self):
assets = []
for asset in self.files.getlist("assets"):
try:
if self.allowed_content_types:
self.validate_asset_content_type(asset)
if self.allowed_extensions:
self.validate_asset_extension(asset)
except forms.ValidationError as e:
self.add_error("assets", e)
else:
assets.append(asset)
return assets
def validate_asset_content_type(self, asset):
if asset.content_type in self.allowed_content_types:
return
message = pgettext(
"admin theme assets form",
'File "%(file)s" content type "%(content_type)s" is not allowed.',
)
details = {"file": asset.name, "content_type": asset.content_type}
raise forms.ValidationError(message % details)
def validate_asset_extension(self, asset):
filename = asset.name.lower()
for extension in self.allowed_extensions:
if filename.endswith(".%s" % extension):
return
message = pgettext(
"admin theme assets form", 'File "%(file)s" extension is invalid.'
)
details = {"file": asset.name}
raise forms.ValidationError(message % details)
def save(self):
for asset in self.cleaned_data["assets"]:
self.save_asset(asset)
class UploadCssForm(UploadAssetsForm):
allowed_content_types = ["text/css"]
allowed_extensions = ["css"]
def save_asset(self, asset):
create_css(self.instance, asset)
class UploadMediaForm(UploadAssetsForm):
def save_asset(self, asset):
create_media(self.instance, asset)
class CssEditorForm(forms.ModelForm):
name = forms.CharField(
label=pgettext_lazy("admin theme css form", "Name"),
help_text=pgettext_lazy(
"admin theme css form",
"Should be a correct filename and include the .css extension. It will be lowercased.",
),
validators=[validate_css_name],
)
source = forms.CharField(widget=forms.Textarea(), required=False)
class Meta:
model = Css
fields = ["name"]
def clean_name(self):
data = self.cleaned_data["name"]
validate_css_name_is_available(self.instance, data)
return data
def clean(self):
cleaned_data = super().clean()
if not cleaned_data.get("source"):
raise forms.ValidationError(
pgettext("admin theme css form", "You need to enter CSS for this file.")
)
return cleaned_data
def save(self):
name = self.cleaned_data["name"]
source = self.cleaned_data["source"].encode()
source_file = ContentFile(source, name)
self.instance.name = name
if self.instance.source_file:
self.instance.source_file.delete(save=False)
self.instance.source_file = source_file
self.instance.source_hash = get_file_hash(source_file)
self.instance.source_needs_building = css_needs_rebuilding(source_file)
self.instance.size = len(source)
if not self.instance.pk:
self.instance.order = get_next_css_order(self.instance.theme)
self.instance.save()
return self.instance
class CssLinkForm(forms.ModelForm):
name = forms.CharField(
label=pgettext_lazy("admin theme css link form", "Link name"),
help_text=pgettext_lazy(
"admin theme css link form",
'Can be descriptive (e.g. "roboto from fonts.google.com").',
),
)
url = forms.URLField(
label=pgettext_lazy("admin theme css link form", "Remote CSS URL")
)
class Meta:
model = Css
fields = ["name", "url"]
def clean_name(self):
data = self.cleaned_data["name"]
validate_css_name_is_available(self.instance, data)
return data
def save(self):
if not self.instance.pk:
self.instance.order = get_next_css_order(self.instance.theme)
self.instance.save()
else:
self.instance.save(update_fields=["name", "url", "modified_on"])
return self.instance
| 9,361
|
Python
|
.py
| 229
| 32.497817
| 98
| 0.639974
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,741
|
views.py
|
rafalp_Misago/misago/themes/admin/views.py
|
from django.contrib import messages
from django.db.models import ObjectDoesNotExist
from django.shortcuts import redirect
from django.utils.translation import pgettext, pgettext_lazy
from ...admin.views import generic
from ..cache import clear_theme_cache
from ..models import Theme, Css
from .css import move_css_down, move_css_up
from .exporter import export_theme
from .forms import (
CssEditorForm,
CssLinkForm,
ImportForm,
ThemeForm,
UploadCssForm,
UploadMediaForm,
)
from .importer import ThemeImportError, import_theme
from .tasks import build_single_theme_css, build_theme_css, update_remote_css_size
class ThemeAdmin(generic.AdminBaseMixin):
root_link = "misago:admin:themes:index"
model = Theme
form_class = ThemeForm
templates_dir = "misago/admin/themes"
message_404 = pgettext_lazy("admin themes", "Requested theme does not exist.")
class ThemesList(ThemeAdmin, generic.ListView):
pass
class NewTheme(ThemeAdmin, generic.ModelFormView):
message_submit = pgettext_lazy(
"admin themes", 'New theme "%(name)s" has been saved.'
)
def get_form(self, form_class, request, target):
if request.method == "POST":
return form_class(request.POST, request.FILES, instance=target)
try:
initial = {"parent": int(request.GET.get("parent"))}
except (TypeError, ValueError):
initial = {}
return form_class(initial=initial)
class EditTheme(ThemeAdmin, generic.ModelFormView):
message_submit = pgettext_lazy("admin themes", 'Theme "%(name)s" has been updated.')
def check_permissions(self, request, target):
if target.is_default:
return pgettext("admin themes", "Default theme can't be edited.")
def handle_form(self, form, request, target):
super().handle_form(form, request, target)
if "parent" in form.changed_data:
clear_theme_cache()
class DeleteTheme(ThemeAdmin, generic.ButtonView):
message_submit = pgettext_lazy("admin themes", 'Theme "%(name)s" has been deleted.')
def check_permissions(self, request, target):
if target.is_default:
return pgettext("admin themes", "Default theme can't be deleted.")
if target.is_active:
return pgettext("admin themes", "Active theme can't be deleted.")
if target.get_descendants().filter(is_active=True).exists():
message = pgettext(
"admin themes",
'Theme "%(name)s" can\'t be deleted because one of its child themes is set as an active theme.',
)
return message % {"name": target}
def button_action(self, request, target):
for theme in reversed(target.get_descendants(include_self=True)):
theme.delete()
clear_theme_cache()
messages.success(request, self.message_submit % {"name": target})
class ActivateTheme(ThemeAdmin, generic.ButtonView):
def button_action(self, request, target):
set_theme_as_active(request, target)
message = pgettext(
"admin themes", 'Active theme has been changed to "%(name)s".'
)
messages.success(request, message % {"name": target})
def set_theme_as_active(request, theme):
Theme.objects.update(is_active=False)
Theme.objects.filter(pk=theme.pk).update(is_active=True)
clear_theme_cache()
class ExportTheme(ThemeAdmin, generic.ButtonView):
def check_permissions(self, request, target):
if target.is_default:
return pgettext("admin themes", "Default theme can't be exported.")
def button_action(self, request, target):
return export_theme(target)
class ImportTheme(ThemeAdmin, generic.FormView):
form_class = ImportForm
template_name = "import.html"
def handle_form(self, form, request):
try:
self.import_theme(request, **form.cleaned_data)
return redirect(self.root_link)
except ThemeImportError as e:
form.add_error("upload", str(e))
return self.render(request, {"form": form})
def import_theme(self, request, *_, name, parent, upload):
theme = import_theme(name, parent, upload)
message = pgettext("admin themes", 'Theme "%(name)s" has been imported.')
messages.success(request, message % {"name": theme})
class ThemeAssetsAdmin(ThemeAdmin):
def check_permissions(self, request, theme):
if theme.is_default:
return pgettext("admin themes", "Default theme assets can't be edited.")
def redirect_to_theme_assets(self, theme):
return redirect("misago:admin:themes:assets", pk=theme.pk)
class ThemeAssets(ThemeAssetsAdmin, generic.TargetedView):
template_name = "assets/list.html"
def real_dispatch(self, request, theme):
return self.render(request, {"theme": theme})
class ThemeAssetsActionAdmin(ThemeAssetsAdmin):
def real_dispatch(self, request, theme):
if request.method == "POST":
self.action(request, theme)
return self.redirect_to_theme_assets(theme)
def action(self, request, theme):
raise NotImplementedError(
"action method must be implemented in inheriting class"
)
class UploadThemeAssets(ThemeAssetsActionAdmin, generic.TargetedView):
message_partial_success = pgettext_lazy(
"admin themes", "Some css files could not have been added to the theme."
)
message_submit = None
form_class = None
def action(self, request, theme):
form = self.form_class( # pylint: disable=not-callable
request.POST, request.FILES, instance=theme
)
if not form.is_valid():
if form.cleaned_data.get("assets"):
messages.info(request, self.message_partial_success)
for error in form.errors["assets"]:
messages.error(request, error)
if form.cleaned_data.get("assets"):
form.save()
build_theme_css.delay(theme.pk)
messages.success(request, self.message_success)
class UploadThemeCss(UploadThemeAssets):
message_success = pgettext_lazy(
"admin themes", "New CSS files have been added to the theme."
)
form_class = UploadCssForm
class UploadThemeMedia(UploadThemeAssets):
message_success = pgettext_lazy(
"admin themes", "New media files have been added to the theme."
)
form_class = UploadMediaForm
class DeleteThemeAssets(ThemeAssetsActionAdmin, generic.TargetedView):
message_submit = None
queryset_attr = None
def action(self, request, theme):
items = self.clean_items_list(request)
if items:
queryset = getattr(theme, self.queryset_attr)
for item in items:
self.delete_asset(queryset, item)
messages.success(request, self.message_submit)
def clean_items_list(self, request):
try:
return {int(i) for i in request.POST.getlist("item")[:20]}
except (ValueError, TypeError):
pass
def delete_asset(self, queryset, item):
try:
queryset.get(pk=item).delete()
except ObjectDoesNotExist:
pass
class DeleteThemeCss(DeleteThemeAssets):
message_submit = pgettext_lazy(
"admin themes", "Selected CSS files have been deleted."
)
queryset_attr = "css"
def action(self, request, theme):
super().action(request, theme)
clear_theme_cache()
class DeleteThemeMedia(DeleteThemeAssets):
message_submit = pgettext_lazy("admin themes", "Selected media have been deleted.")
queryset_attr = "media"
class ThemeCssAdmin(ThemeAssetsAdmin, generic.TargetedView):
def wrapped_dispatch(self, request, pk, css_pk=None):
theme = self.get_target_or_none(request, {"pk": pk})
if not theme:
messages.error(request, self.message_404)
return redirect(self.root_link)
error = self.check_permissions( # pylint: disable=assignment-from-no-return
request, theme
)
if error:
messages.error(request, error)
return redirect(self.root_link)
css = self.get_theme_css_or_none(theme, css_pk)
if css_pk and not css:
css_error = pgettext(
"admin themes", "Requested CSS could not be found in the theme."
)
messages.error(request, css_error)
return self.redirect_to_theme_assets(theme)
return self.real_dispatch(request, theme, css)
def get_theme_css_or_none(self, theme, css_pk):
if not css_pk:
return None
try:
return theme.css.select_for_update().get(pk=css_pk)
except ObjectDoesNotExist:
return None
def real_dispatch(self, request, theme, css):
raise NotImplementedError(
"Admin views extending the ThemeCssAdmin"
"should define real_dispatch(request, theme, css)"
)
class MoveThemeCssUp(ThemeCssAdmin):
def real_dispatch(self, request, theme, css):
if request.method == "POST" and move_css_up(theme, css):
clear_theme_cache()
messages.success(
request, pgettext("admin themes", '"%s" was moved up.') % css
)
return self.redirect_to_theme_assets(theme)
class MoveThemeCssDown(ThemeCssAdmin):
def real_dispatch(self, request, theme, css):
if request.method == "POST" and move_css_down(theme, css):
clear_theme_cache()
messages.success(
request, pgettext("admin themes", '"%s" was moved down.') % css
)
return self.redirect_to_theme_assets(theme)
class ThemeCssFormAdmin(ThemeCssAdmin, generic.ModelFormView):
is_atomic = False # atomic updates cause race condition with celery tasks
def real_dispatch(self, request, theme, css=None):
form = self.get_form(self.form_class, request, theme, css)
if request.method == "POST" and form.is_valid():
response = self.handle_form( # pylint: disable=assignment-from-no-return
form, request, theme, css
)
if response:
return response
if "stay" in request.POST:
return self.redirect_to_edit_form(theme, form.instance)
return self.redirect_to_theme_assets(theme)
template_name = self.get_template_name(request, css)
return self.render(
request, {"form": form, "theme": theme, "target": css}, template_name
)
def get_form(self, form_class, request, theme, css):
raise NotImplementedError(
"Admin views extending the ThemeCssFormAdmin "
"should define the get_form(form_class, request, theme, css)"
)
def handle_form(self, form, request, theme, css):
form.save()
if css.source_needs_building:
build_single_theme_css.delay(css.pk)
else:
clear_theme_cache()
messages.success(request, self.message_submit % {"name": css.name})
class NewThemeCss(ThemeCssFormAdmin):
message_submit = pgettext_lazy("admin themes", 'New CSS "%(name)s" has been saved.')
form_class = CssEditorForm
template_name = "assets/css-editor-form.html"
def get_theme_css_or_none(self, theme, _):
return Css(theme=theme)
def get_form(self, form_class, request, theme, css):
if request.method == "POST":
return form_class(request.POST, instance=css)
return form_class(instance=css)
def redirect_to_edit_form(self, theme, css):
return redirect("misago:admin:themes:edit-css-file", pk=theme.pk, css_pk=css.pk)
class EditThemeCss(NewThemeCss):
message_submit = pgettext_lazy("admin themes", 'CSS "%(name)s" has been updated.')
def get_theme_css_or_none(self, theme, css_pk):
try:
return theme.css.get(pk=css_pk, url__isnull=True)
except ObjectDoesNotExist:
return None
def get_form(self, form_class, request, theme, css):
if request.method == "POST":
return form_class(request.POST, instance=css)
initial_data = {"source": css.source_file.read().decode("utf-8")}
return form_class(instance=css, initial=initial_data)
def handle_form(self, form, request, theme, css):
if "source" in form.changed_data:
form.save()
if css.source_needs_building:
build_single_theme_css.delay(css.pk)
else:
clear_theme_cache()
messages.success(request, self.message_submit % {"name": css.name})
else:
message = pgettext(
"admin themes", 'No changes have been made to "%(css)s".'
)
messages.info(request, message % {"name": css.name})
class NewThemeCssLink(ThemeCssFormAdmin):
message_submit = pgettext_lazy(
"admin themes", 'New CSS link "%(name)s" has been saved.'
)
form_class = CssLinkForm
template_name = "assets/css-link-form.html"
def get_theme_css_or_none(self, theme, _):
return Css(theme=theme)
def get_form(self, form_class, request, theme, css):
if request.method == "POST":
return form_class(request.POST, instance=css)
return form_class(instance=css)
def handle_form(self, form, request, theme, css):
super().handle_form(form, request, theme, css)
if "url" in form.changed_data:
update_remote_css_size.delay(css.pk)
clear_theme_cache()
def redirect_to_edit_form(self, theme, css):
return redirect("misago:admin:themes:new-css-link", pk=theme.pk)
class EditThemeCssLink(NewThemeCssLink):
message_submit = pgettext_lazy(
"admin themes", 'CSS link "%(name)s" has been updated.'
)
def get_theme_css_or_none(self, theme, css_pk):
try:
return theme.css.get(pk=css_pk, url__isnull=False)
except ObjectDoesNotExist:
return None
def redirect_to_edit_form(self, theme, css):
return redirect("misago:admin:themes:edit-css-link", pk=theme.pk, css_pk=css.pk)
| 14,262
|
Python
|
.py
| 320
| 36.009375
| 112
| 0.651564
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,742
|
conftest.py
|
rafalp_Misago/misago/themes/admin/tests/conftest.py
|
import os
import pytest
from django.urls import reverse
from ...models import Theme
@pytest.fixture
def default_theme(db):
return Theme.objects.get(is_default=True)
@pytest.fixture
def theme(db):
return Theme.objects.create(name="Custom theme")
@pytest.fixture
def other_theme(db):
return Theme.objects.create(name="Other theme")
@pytest.fixture
def nonexisting_theme(mocker, default_theme):
return mocker.Mock(pk=default_theme.pk + 1)
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture
def css(admin_client, theme, mock_build_theme_css):
url = reverse("misago:admin:themes:upload-css", kwargs={"pk": theme.pk})
with open(os.path.join(TESTS_DIR, "css", "test.css")) as fp:
admin_client.post(url, {"assets": [fp]})
return theme.css.get(name="test.css")
@pytest.fixture
def css_link(admin_client, theme):
return theme.css.create(
name="CSS link", url="https://example.com/cdn.css", order=theme.css.count()
)
@pytest.fixture
def css_needing_build(admin_client, theme, mock_build_theme_css):
url = reverse("misago:admin:themes:upload-css", kwargs={"pk": theme.pk})
with open(os.path.join(TESTS_DIR, "css", "test.needs-build.css")) as fp:
admin_client.post(url, {"assets": [fp]})
return theme.css.get(name="test.needs-build.css")
@pytest.fixture
def media(admin_client, theme):
url = reverse("misago:admin:themes:upload-media", kwargs={"pk": theme.pk})
with open(os.path.join(TESTS_DIR, "images", "test.svg")) as fp:
admin_client.post(url, {"assets": [fp]})
return theme.media.get(name="test.svg")
@pytest.fixture
def image(admin_client, theme):
url = reverse("misago:admin:themes:upload-media", kwargs={"pk": theme.pk})
with open(os.path.join(TESTS_DIR, "images", "test.png"), "rb") as fp:
admin_client.post(url, {"assets": [fp]})
return theme.media.get(name="test.png")
@pytest.fixture(autouse=True)
def mock_build_single_theme_css(mocker):
delay = mocker.Mock()
mocker.patch(
"misago.themes.admin.views.build_single_theme_css", mocker.Mock(delay=delay)
)
return delay
@pytest.fixture(autouse=True)
def mock_build_theme_css(mocker):
delay = mocker.Mock()
mocker.patch("misago.themes.admin.views.build_theme_css", mocker.Mock(delay=delay))
mocker.patch(
"misago.themes.admin.importer.build_theme_css", mocker.Mock(delay=delay)
)
return delay
@pytest.fixture(autouse=True)
def mock_update_remote_css_size(mocker):
delay = mocker.Mock()
mocker.patch(
"misago.themes.admin.views.update_remote_css_size", mocker.Mock(delay=delay)
)
mocker.patch(
"misago.themes.admin.importer.update_remote_css_size", mocker.Mock(delay=delay)
)
return delay
| 2,785
|
Python
|
.py
| 71
| 34.957746
| 87
| 0.704765
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,743
|
test_uploading_media.py
|
rafalp_Misago/misago/themes/admin/tests/test_uploading_media.py
|
import os
import pytest
from django.core.files.uploadedfile import UploadedFile
from django.urls import reverse
from ....test import assert_has_error_message
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture
def png_file():
return os.path.join(TESTS_DIR, "images", "test.png")
@pytest.fixture
def svg_file():
return os.path.join(TESTS_DIR, "images", "test.svg")
@pytest.fixture
def hashable_file():
return os.path.join(TESTS_DIR, "css", "test.css")
@pytest.fixture
def hashed_file():
return os.path.join(TESTS_DIR, "css", "test.4846cb3b.css")
@pytest.fixture
def upload(admin_client):
def post_upload(theme, asset_files=None):
url = reverse("misago:admin:themes:upload-media", kwargs={"pk": theme.pk})
if asset_files is not None:
data = asset_files if isinstance(asset_files, list) else [asset_files]
else:
data = ""
return admin_client.post(url, {"assets": data})
return post_upload
def test_font_file_can_be_uploaded(upload, theme):
font_file = os.path.join(TESTS_DIR, "font", "Lato.ttf")
with open(font_file, "rb") as fp:
upload(theme, fp)
assert theme.media.exists()
def test_text_file_can_be_uploaded(upload, theme):
text_file = os.path.join(TESTS_DIR, "font", "OFL.txt")
with open(text_file) as fp:
upload(theme, fp)
assert theme.media.exists()
def test_svg_file_can_be_uploaded(upload, theme):
svg_file = os.path.join(TESTS_DIR, "images", "test.svg")
with open(svg_file) as fp:
upload(theme, fp)
assert theme.media.exists()
def test_png_file_can_be_uploaded(upload, theme, png_file):
with open(png_file, "rb") as fp:
upload(theme, fp)
assert theme.media.exists()
def test_media_file_name_is_set_as_asset_name(upload, theme, svg_file):
with open(svg_file) as fp:
upload(theme, fp)
media = theme.media.last()
expected_filename = str(svg_file).split("/")[-1]
assert media.name == expected_filename
def test_media_file_is_uploaded_to_theme_directory(upload, theme, svg_file):
with open(svg_file) as fp:
upload(theme, fp)
media = theme.media.last()
assert theme.dirname in str(media.file)
def test_hash_is_added_to_uploaded_media_file_name(
upload, theme, hashable_file, hashed_file
):
with open(hashable_file) as fp:
upload(theme, fp)
media = theme.media.last()
filename = str(media.file.path).split("/")[-1]
expected_filename = str(hashed_file).split("/")[-1]
assert filename == expected_filename
def test_hash_is_set_on_media_asset(upload, theme, hashed_file):
with open(hashed_file) as fp:
upload(theme, fp)
media = theme.media.last()
assert media.hash
def test_media_file_name_is_preserved_if_it_already_contains_correct_hash(
upload, theme, hashed_file
):
with open(hashed_file) as fp:
upload(theme, fp)
media = theme.media.last()
filename = str(media.file.path).split("/")[-1]
expected_filename = str(hashed_file).split("/")[-1]
assert filename == expected_filename
def test_new_hash_is_added_to_media_file_name_if_it_contains_incorrect_hash(
upload, theme
):
incorrectly_hashed_file = os.path.join(TESTS_DIR, "css", "test.0046cb3b.css")
with open(incorrectly_hashed_file) as fp:
upload(theme, fp)
media = theme.media.last()
filename = str(media.file.path).split("/")[-1]
assert media.hash in filename
def test_newly_uploaded_media_file_replaces_old_one_if_file_names_are_same(
upload, theme, hashable_file
):
with open(hashable_file) as fp:
upload(theme, fp)
original_media = theme.media.get()
with open(os.path.join(TESTS_DIR, "css", "test-changed.css")) as fp:
size = len(fp.read())
fp.seek(0)
upload(
theme, UploadedFile(fp, name="test.css", content_type="text/css", size=size)
)
updated_media = theme.media.last()
assert updated_media.name == original_media.name
assert updated_media.hash != original_media.hash
assert theme.media.count() == 1
def test_image_dimensions_are_set_for_uploaded_image_file(upload, theme, png_file):
with open(png_file, "rb") as fp:
upload(theme, fp)
media = theme.media.last()
assert media.width
assert media.height
def test_thumbnail_is_generated_in_theme_directory_for_uploaded_image_file(
upload, theme, png_file
):
with open(png_file, "rb") as fp:
upload(theme, fp)
media = theme.media.last()
assert theme.dirname in str(media.thumbnail)
def test_uploading_media_triggers_css_build(
upload, theme, png_file, mock_build_theme_css
):
with open(png_file, "rb") as fp:
upload(theme, fp)
mock_build_theme_css.assert_called_once_with(theme.pk)
def test_error_message_is_set_if_no_media_was_uploaded(upload, theme):
response = upload(theme)
assert_has_error_message(response)
def test_error_message_is_set_if_user_attempts_to_upload_file_to_default_theme(
upload, default_theme
):
response = upload(default_theme)
assert_has_error_message(response)
def test_error_message_is_set_if_user_attempts_to_upload_file_to_nonexisting_theme(
upload, nonexisting_theme
):
response = upload(nonexisting_theme)
assert_has_error_message(response)
| 5,370
|
Python
|
.py
| 138
| 33.746377
| 88
| 0.688575
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,744
|
test_reordering_css.py
|
rafalp_Misago/misago/themes/admin/tests/test_reordering_css.py
|
import pytest
from django.urls import reverse
from ....cache.test import assert_invalidates_cache
from ....test import assert_has_error_message
from ... import THEME_CACHE
from ..css import get_next_css_order
FIRST = 0
MIDDLE = 1
LAST = 2
@pytest.fixture
def css_list(theme):
return [
theme.css.create(name="CSS", url="https://test.cdn/font.css", order=FIRST),
theme.css.create(name="CSS", url="https://test.cdn/font.css", order=MIDDLE),
theme.css.create(name="CSS", url="https://test.cdn/font.css", order=LAST),
]
@pytest.fixture
def move_up(admin_client):
def move_up_client(theme, css):
url = reverse(
"misago:admin:themes:move-css-up", kwargs={"pk": theme.pk, "css_pk": css.pk}
)
return admin_client.post(url)
return move_up_client
@pytest.fixture
def move_down(admin_client):
def move_down_client(theme, css):
url = reverse(
"misago:admin:themes:move-css-down",
kwargs={"pk": theme.pk, "css_pk": css.pk},
)
return admin_client.post(url)
return move_down_client
def test_first_css_cant_be_moved_up(move_up, theme, css_list):
first_css = css_list[FIRST]
move_up(theme, first_css)
first_css.refresh_from_db()
assert first_css.order == FIRST
def test_last_css_cant_be_moved_down(move_down, theme, css_list):
last_css = css_list[LAST]
move_down(theme, last_css)
last_css.refresh_from_db()
assert last_css.order == LAST
def test_first_css_can_be_moved_down(move_down, theme, css_list):
first_css = css_list[FIRST]
move_down(theme, first_css)
first_css.refresh_from_db()
assert first_css.order == MIDDLE
def test_last_css_can_be_moved_up(move_up, theme, css_list):
last_css = css_list[LAST]
move_up(theme, last_css)
last_css.refresh_from_db()
assert last_css.order == MIDDLE
def test_middle_css_can_be_moved_down(move_down, theme, css_list):
middle_css = css_list[MIDDLE]
move_down(theme, middle_css)
middle_css.refresh_from_db()
assert middle_css.order == LAST
def test_middle_css_can_be_moved_up(move_up, theme, css_list):
middle_css = css_list[MIDDLE]
move_up(theme, middle_css)
middle_css.refresh_from_db()
assert middle_css.order == FIRST
def test_first_css_changes_order_with_middle_css_when_moved_down(
move_down, theme, css_list
):
move_down(theme, css_list[FIRST])
middle_css = css_list[MIDDLE]
middle_css.refresh_from_db()
assert middle_css.order == FIRST
def test_last_css_changes_order_with_middle_css_when_moved_up(move_up, theme, css_list):
move_up(theme, css_list[LAST])
middle_css = css_list[MIDDLE]
middle_css.refresh_from_db()
assert middle_css.order == LAST
def test_middle_css_changes_order_with_last_css_when_moved_down(
move_down, theme, css_list
):
move_down(theme, css_list[MIDDLE])
last_css = css_list[LAST]
last_css.refresh_from_db()
assert last_css.order == MIDDLE
def test_middle_css_changes_order_with_first_css_when_moved_up(
move_up, theme, css_list
):
move_up(theme, css_list[MIDDLE])
first_css = css_list[FIRST]
first_css.refresh_from_db()
assert first_css.order == MIDDLE
def test_first_css_changes_order_with_last_css_when_moved_down_after_middle_deletion(
move_down, theme, css_list
):
css_list[MIDDLE].delete()
move_down(theme, css_list[FIRST])
last_css = css_list[LAST]
last_css.refresh_from_db()
assert last_css.order == FIRST
def test_last_css_changes_order_with_first_css_when_moved_up_after_middle_deletion(
move_up, theme, css_list
):
css_list[MIDDLE].delete()
move_up(theme, css_list[LAST])
first_css = css_list[FIRST]
first_css.refresh_from_db()
assert first_css.order == LAST
def test_if_css_doesnt_belong_to_theme_move_down_action_sets_error_message(
move_down, other_theme, css_list
):
response = move_down(other_theme, css_list[MIDDLE])
assert_has_error_message(response)
def test_if_css_doesnt_belong_to_theme_move_up_action_sets_error_message(
move_up, other_theme, css_list
):
response = move_up(other_theme, css_list[MIDDLE])
assert_has_error_message(response)
def test_if_ran_for_default_theme_move_down_action_sets_error_message(
move_down, default_theme, css_list
):
response = move_down(default_theme, css_list[MIDDLE])
assert_has_error_message(response)
def test_if_ran_for_default_theme_move_up_action_sets_error_message(
move_up, default_theme, css_list
):
response = move_up(default_theme, css_list[MIDDLE])
assert_has_error_message(response)
def test_if_given_nonexisting_css_id_move_down_action_sets_error_message(
mocker, move_down, theme, css_list
):
response = move_down(theme, mocker.Mock(pk=css_list[LAST].pk + 1))
assert_has_error_message(response)
def test_if_given_nonexisting_css_id_move_up_action_sets_error_message(
mocker, move_up, theme, css_list
):
response = move_up(theme, mocker.Mock(pk=css_list[LAST].pk + 1))
assert_has_error_message(response)
def test_if_given_nonexisting_theme_id_move_down_action_sets_error_message(
mocker, move_down, nonexisting_theme, css_list
):
response = move_down(nonexisting_theme, css_list[FIRST])
assert_has_error_message(response)
def test_if_given_nonexisting_theme_id_move_up_action_sets_error_message(
mocker, move_up, nonexisting_theme, css_list
):
response = move_up(nonexisting_theme, css_list[LAST])
assert_has_error_message(response)
def test_next_new_css_order_is_larger_than_largest_existing_css_order(theme):
theme.css.create(name="CSS", url="https://test.cdn/font.css", order=4)
assert get_next_css_order(theme) == 5
def test_moving_css_up_invalidates_theme_cache(move_up, theme, css_list):
with assert_invalidates_cache(THEME_CACHE):
move_up(theme, css_list[LAST])
def test_moving_css_down_invalidates_theme_cache(move_down, theme, css_list):
with assert_invalidates_cache(THEME_CACHE):
move_down(theme, css_list[FIRST])
| 6,081
|
Python
|
.py
| 154
| 35.006494
| 88
| 0.708227
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,745
|
test_browsing_theme_assets.py
|
rafalp_Misago/misago/themes/admin/tests/test_browsing_theme_assets.py
|
import pytest
from django.urls import reverse
from ....test import assert_contains, assert_not_contains, assert_has_error_message
@pytest.fixture
def assets_client(admin_client):
def get_theme_assets(theme):
url = reverse("misago:admin:themes:assets", kwargs={"pk": theme.pk})
return admin_client.get(url)
return get_theme_assets
def test_theme_assets_list_is_displayed(assets_client, theme):
response = assets_client(theme)
assert_contains(response, theme.name)
def test_css_file_is_displayed_on_theme_asset_list(assets_client, theme, css):
response = assets_client(theme)
assert_contains(response, css.name)
def test_css_link_is_displayed_on_theme_asset_list(assets_client, theme, css_link):
response = assets_client(theme)
assert_contains(response, css_link.name)
def test_media_is_displayed_on_themes_asset_list(assets_client, theme, media):
response = assets_client(theme)
assert_contains(response, media.name)
def test_image_is_displayed_on_themes_asset_list(assets_client, theme, image):
response = assets_client(theme)
assert_contains(response, image.name)
def test_image_thumbnail_is_displayed_on_themes_asset_list(assets_client, theme, image):
response = assets_client(theme)
assert_contains(response, image.thumbnail.url)
def test_other_theme_assets_are_not_displayed(
assets_client, other_theme, css, css_link, media, image
):
response = assets_client(other_theme)
assert_not_contains(response, css.name)
assert_not_contains(response, css_link.name)
assert_not_contains(response, media.name)
assert_not_contains(response, image.name)
def test_user_is_redirected_away_with_message_from_default_theme_assets_list(
assets_client, default_theme
):
response = assets_client(default_theme)
assert response.status_code == 302
assert_has_error_message(response)
def test_user_is_redirected_away_with_message_from_nonexisting_theme(
assets_client, nonexisting_theme
):
response = assets_client(nonexisting_theme)
assert response.status_code == 302
assert_has_error_message(response)
| 2,136
|
Python
|
.py
| 47
| 41.255319
| 88
| 0.760522
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,746
|
test_deleting_themes.py
|
rafalp_Misago/misago/themes/admin/tests/test_deleting_themes.py
|
from pathlib import Path
import pytest
from django.core.files.base import ContentFile
from django.urls import reverse
from ....cache.test import assert_invalidates_cache
from ....test import assert_has_error_message
from ... import THEME_CACHE
from ...models import Theme, Css, Media
@pytest.fixture
def delete_link(theme):
return reverse("misago:admin:themes:delete", kwargs={"pk": theme.pk})
def test_theme_without_children_can_be_deleted(admin_client, delete_link, theme):
admin_client.post(delete_link)
with pytest.raises(Theme.DoesNotExist):
theme.refresh_from_db()
def test_theme_css_are_deleted_together_with_theme(admin_client, delete_link, css):
admin_client.post(delete_link)
with pytest.raises(Css.DoesNotExist):
css.refresh_from_db()
def test_theme_source_css_files_are_deleted_together_with_theme(
admin_client, delete_link, css
):
admin_client.post(delete_link)
assert not Path(css.source_file.path).exists()
def test_theme_build_css_files_are_deleted_together_with_theme(
admin_client, delete_link, css
):
css.build_file = ContentFile("body {}", name="test.css")
css.build_hash = "abcdefgh"
css.save()
admin_client.post(delete_link)
assert not Path(css.build_file.path).exists()
def test_theme_media_are_deleted_together_with_theme(admin_client, delete_link, media):
admin_client.post(delete_link)
with pytest.raises(Media.DoesNotExist):
media.refresh_from_db()
def test_theme_images_are_deleted_together_with_theme(admin_client, delete_link, image):
admin_client.post(delete_link)
with pytest.raises(Media.DoesNotExist):
image.refresh_from_db()
def test_theme_media_files_are_deleted_together_with_theme(
admin_client, delete_link, media
):
admin_client.post(delete_link)
assert not Path(media.file.path).exists()
def test_theme_image_files_are_deleted_together_with_theme(
admin_client, delete_link, image
):
admin_client.post(delete_link)
assert not Path(image.thumbnail.path).exists()
def test_theme_is_deleted_with_children(admin_client, delete_link, theme):
Theme.objects.create(name="Child Theme", parent=theme)
admin_client.post(delete_link)
assert Theme.objects.count() == 1
def test_theme_children_are_deleted_recursively(admin_client, delete_link, theme):
child_theme = Theme.objects.create(name="Child Theme", parent=theme)
Theme.objects.create(name="Descendant Theme", parent=child_theme)
Theme.objects.create(name="Descendant Theme", parent=child_theme)
admin_client.post(delete_link)
assert Theme.objects.count() == 1
def test_children_theme_can_be_deleted(admin_client, delete_link, theme, other_theme):
theme.move_to(other_theme)
theme.save()
admin_client.post(delete_link)
with pytest.raises(Theme.DoesNotExist):
theme.refresh_from_db()
def test_deleting_children_theme_doesnt_delete_parent_themes(
admin_client, delete_link, theme, other_theme
):
theme.move_to(other_theme)
theme.save()
admin_client.post(delete_link)
other_theme.refresh_from_db()
def test_deleting_theme_invalidates_themes_cache(admin_client, delete_link):
with assert_invalidates_cache(THEME_CACHE):
admin_client.post(delete_link)
def test_deleting_default_theme_sets_error_message(admin_client, default_theme):
delete_link = reverse("misago:admin:themes:delete", kwargs={"pk": default_theme.pk})
response = admin_client.post(delete_link)
assert_has_error_message(response)
def test_default_theme_is_not_deleted(admin_client, default_theme):
delete_link = reverse("misago:admin:themes:delete", kwargs={"pk": default_theme.pk})
admin_client.post(delete_link)
default_theme.refresh_from_db()
def test_deleting_active_theme_sets_error_message(admin_client, theme):
theme.is_active = True
theme.save()
delete_link = reverse("misago:admin:themes:delete", kwargs={"pk": theme.pk})
response = admin_client.post(delete_link)
assert_has_error_message(response)
def test_active_theme_is_not_deleted(admin_client, theme):
theme.is_active = True
theme.save()
delete_link = reverse("misago:admin:themes:delete", kwargs={"pk": theme.pk})
admin_client.post(delete_link)
theme.refresh_from_db()
def test_deleting_theme_containing_active_child_theme_sets_error_message(
admin_client, theme, other_theme
):
other_theme.move_to(theme)
other_theme.is_active = True
other_theme.save()
delete_link = reverse("misago:admin:themes:delete", kwargs={"pk": theme.pk})
response = admin_client.post(delete_link)
assert_has_error_message(response)
def test_theme_containing_active_child_theme_is_not_deleted(
admin_client, theme, other_theme
):
other_theme.move_to(theme)
other_theme.is_active = True
other_theme.save()
delete_link = reverse("misago:admin:themes:delete", kwargs={"pk": theme.pk})
admin_client.post(delete_link)
theme.refresh_from_db()
| 5,011
|
Python
|
.py
| 114
| 39.570175
| 88
| 0.742109
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,747
|
test_creating_and_deleting_css_links.py
|
rafalp_Misago/misago/themes/admin/tests/test_creating_and_deleting_css_links.py
|
import pytest
from django.urls import reverse
from ....cache.test import assert_invalidates_cache
from ....test import assert_contains, assert_has_error_message
from ... import THEME_CACHE
@pytest.fixture
def create_link(theme):
return reverse("misago:admin:themes:new-css-link", kwargs={"pk": theme.pk})
@pytest.fixture
def edit_link(theme, css_link):
return reverse(
"misago:admin:themes:edit-css-link",
kwargs={"pk": theme.pk, "css_pk": css_link.pk},
)
@pytest.fixture
def data():
return {"name": "CSS link", "url": "https://example.com/cdn.css"}
def test_css_link_creation_form_is_displayed(admin_client, create_link):
response = admin_client.get(create_link)
assert response.status_code == 200
assert_contains(response, "New CSS link")
def test_css_link_can_be_created(theme, admin_client, create_link, data):
admin_client.post(create_link, data)
assert theme.css.exists()
def test_css_link_is_created_with_entered_name(theme, admin_client, create_link, data):
admin_client.post(create_link, data)
assert theme.css.last().name == data["name"]
def test_css_link_name_can_be_descriptive(theme, admin_client, create_link, data):
data["name"] = "font (from font.hosting.com)"
admin_client.post(create_link, data)
assert theme.css.last().name == data["name"]
def test_css_link_creation_fails_if_name_is_not_given(
theme, admin_client, create_link, data
):
data["name"] = ""
admin_client.post(create_link, data)
assert not theme.css.exists()
def test_css_link_creation_fails_if_name_is_already_taken_by_other_css_in_theme(
theme, admin_client, create_link, data, css
):
data["name"] = css.name
admin_client.post(create_link, data)
assert theme.css.count() == 1
def test_css_link_name_usage_check_passess_if_name_is_used_by_other_theme_css(
other_theme, admin_client, data, css
):
create_link = reverse(
"misago:admin:themes:new-css-link", kwargs={"pk": other_theme.pk}
)
data["name"] = css.name
admin_client.post(create_link, data)
assert other_theme.css.exists()
def test_css_link_creation_fails_if_url_is_not_given(
theme, admin_client, create_link, data
):
data["url"] = ""
admin_client.post(create_link, data)
assert not theme.css.exists()
def test_css_link_creation_fails_if_url_is_not_valid(
theme, admin_client, create_link, data
):
data["url"] = "invalid-url"
admin_client.post(create_link, data)
assert not theme.css.exists()
def test_css_link_is_created_with_correct_order(
theme, admin_client, create_link, css, data
):
admin_client.post(create_link, data)
css_link = theme.css.get(name=data["name"])
assert css_link.order == 1
def test_css_link_creation_queues_task_to_download_remote_css_size(
theme, admin_client, create_link, data, mock_update_remote_css_size
):
admin_client.post(create_link, data)
css_link = theme.css.last()
mock_update_remote_css_size.assert_called_once_with(css_link.pk)
def test_css_link_creation_invalidates_theme_cache(
theme, admin_client, create_link, data
):
with assert_invalidates_cache(THEME_CACHE):
admin_client.post(create_link, data)
def test_error_message_is_set_if_user_attempts_to_create_css_link_in_default_theme(
default_theme, admin_client
):
create_link = reverse(
"misago:admin:themes:new-css-link", kwargs={"pk": default_theme.pk}
)
response = admin_client.get(create_link)
assert_has_error_message(response)
def test_error_message_is_set_if_user_attempts_to_create_css_link_in_nonexisting_theme(
nonexisting_theme, admin_client
):
create_link = reverse(
"misago:admin:themes:new-css-link", kwargs={"pk": nonexisting_theme.pk}
)
response = admin_client.get(create_link)
assert_has_error_message(response)
def test_css_link_creation_form_redirects_user_to_new_creation_form_after_creation(
theme, admin_client, create_link, data
):
data["stay"] = "1"
response = admin_client.post(create_link, data)
assert response["location"] == reverse(
"misago:admin:themes:new-css-link", kwargs={"pk": theme.pk}
)
def test_css_link_edition_form_is_displayed(admin_client, edit_link, css_link):
response = admin_client.get(edit_link)
assert response.status_code == 200
assert_contains(response, css_link.name)
def test_css_link_name_can_be_changed(admin_client, edit_link, css_link, data):
data["name"] = "new link name"
admin_client.post(edit_link, data)
css_link.refresh_from_db()
assert css_link.name == data["name"]
def test_css_link_url_can_be_changed(admin_client, edit_link, css_link, data):
data["url"] = "https://new.css-link.com/test.css"
admin_client.post(edit_link, data)
css_link.refresh_from_db()
assert css_link.url == data["url"]
def test_changing_css_link_url_queues_task_to_download_remote_css_size(
admin_client, edit_link, css_link, data, mock_update_remote_css_size
):
data["url"] = "https://new.css-link.com/test.css"
admin_client.post(edit_link, data)
css_link.refresh_from_db()
mock_update_remote_css_size.assert_called_once_with(css_link.pk)
def test_not_changing_css_link_url_doesnt_queue_task_to_download_remote_css_size(
admin_client, edit_link, css_link, data, mock_update_remote_css_size
):
admin_client.post(edit_link, data)
css_link.refresh_from_db()
mock_update_remote_css_size.assert_not_called()
def test_changing_css_link_invalidates_theme_cache(admin_client, edit_link, data):
with assert_invalidates_cache(THEME_CACHE):
admin_client.post(edit_link, data)
def test_css_order_stays_the_same_after_edit(admin_client, edit_link, css_link, data):
original_order = css_link.order
data["name"] = "changed link"
admin_client.post(edit_link, data)
css_link.refresh_from_db()
assert css_link.order == original_order
def test_error_message_is_set_if_user_attempts_to_edit_css_file_with_link_form(
theme, admin_client, css
):
edit_link = reverse(
"misago:admin:themes:edit-css-link", kwargs={"pk": theme.pk, "css_pk": css.pk}
)
response = admin_client.get(edit_link)
assert_has_error_message(response)
| 6,266
|
Python
|
.py
| 149
| 37.724832
| 87
| 0.712589
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,748
|
test_getting_remote_css_size.py
|
rafalp_Misago/misago/themes/admin/tests/test_getting_remote_css_size.py
|
import responses
from ..tasks import update_remote_css_size
@responses.activate
def test_task_uses_response_body_to_set_css_size(css_link):
content = "html {}"
content_bytes = content.encode()
responses.add(
responses.GET,
css_link.url,
headers={
"Content-Type": "text/css;charset=utf-8",
"Content-Length": str(len(content_bytes)),
},
body=content_bytes,
)
update_remote_css_size(css_link.pk)
css_link.refresh_from_db()
assert css_link.size == len(content)
@responses.activate
def test_task_doesnt_change_css_size_if_http_request_failed(css_link):
responses.add(responses.GET, css_link.url, status=404)
update_remote_css_size(css_link.pk)
def test_task_handles_css_without_url(css):
update_remote_css_size(css.pk)
def test_task_handles_nonexisting_css(db):
update_remote_css_size(1)
| 903
|
Python
|
.py
| 26
| 29.115385
| 70
| 0.689017
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,749
|
test_uploading_css.py
|
rafalp_Misago/misago/themes/admin/tests/test_uploading_css.py
|
import os
import pytest
from django.core.files.uploadedfile import UploadedFile
from django.urls import reverse
from ....test import assert_has_error_message
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture
def css_file():
return os.path.join(TESTS_DIR, "css", "test.css")
@pytest.fixture
def other_file():
return os.path.join(TESTS_DIR, "images", "test.png")
@pytest.fixture
def hashed_css_file():
return os.path.join(TESTS_DIR, "css", "test.4846cb3b.css")
@pytest.fixture
def upload(admin_client):
def post_upload(theme, asset_files=None):
url = reverse("misago:admin:themes:upload-css", kwargs={"pk": theme.pk})
if asset_files is not None:
data = asset_files if isinstance(asset_files, list) else [asset_files]
else:
data = ""
return admin_client.post(url, {"assets": data})
return post_upload
def test_css_file_can_be_uploaded(upload, theme, css_file):
with open(css_file) as fp:
upload(theme, fp)
assert theme.css.exists()
def test_multiple_css_files_can_be_uploaded_at_once(
upload, theme, css_file, hashed_css_file
):
with open(css_file) as fp1:
with open(hashed_css_file) as fp2:
upload(theme, [fp1, fp2])
assert theme.css.exists()
assert theme.css.count() == 2
def test_css_files_uploaded_one_after_another_are_ordered(
upload, theme, css_file, hashed_css_file
):
with open(css_file) as fp:
upload(theme, fp)
first_css = theme.css.last()
assert first_css.name == str(css_file).split("/")[-1]
assert first_css.order == 0
with open(hashed_css_file) as fp:
upload(theme, fp)
last_css = theme.css.last()
assert last_css.name == str(hashed_css_file).split("/")[-1]
assert last_css.order == 1
def test_multiple_css_files_uploaded_at_once_are_ordered(
upload, theme, css_file, hashed_css_file
):
with open(css_file) as fp1:
with open(hashed_css_file) as fp2:
upload(theme, [fp1, fp2])
assert list(theme.css.values_list("name", flat=True)) == [
str(css_file).split("/")[-1],
str(hashed_css_file).split("/")[-1],
]
assert list(theme.css.values_list("order", flat=True)) == [0, 1]
def test_uploaded_file_is_rejected_if_its_not_css_file(upload, theme, other_file):
with open(other_file, "rb") as fp:
upload(theme, fp)
assert not theme.css.exists()
def test_error_message_is_set_if_uploaded_file_is_not_css(upload, theme, other_file):
with open(other_file, "rb") as fp:
response = upload(theme, fp)
assert_has_error_message(response)
def test_if_some_of_uploaded_files_are_incorrect_only_css_files_are_added_to_theme(
upload, theme, css_file, other_file
):
with open(css_file) as fp1:
with open(other_file, "rb") as fp2:
upload(theme, [fp1, fp2])
assert theme.css.exists()
assert theme.css.count() == 1
css = theme.css.last()
expected_filename = str(css_file).split("/")[-1]
assert css.name == expected_filename
def test_css_file_is_uploaded_to_theme_directory(upload, theme, css_file):
with open(css_file) as fp:
upload(theme, fp)
css = theme.css.last()
assert theme.dirname in str(css.source_file)
def test_css_file_name_is_set_as_asset_name(upload, theme, css_file):
with open(css_file) as fp:
upload(theme, fp)
css = theme.css.last()
expected_filename = str(css_file).split("/")[-1]
assert css.name == expected_filename
def test_hash_is_added_to_uploaded_css_file_name(
upload, theme, css_file, hashed_css_file
):
with open(css_file) as fp:
upload(theme, fp)
css = theme.css.last()
filename = str(css.source_file.path).split("/")[-1]
expected_filename = str(hashed_css_file).split("/")[-1]
assert filename == expected_filename
def test_hash_is_set_on_css_source_asset(upload, theme, css_file):
with open(css_file) as fp:
upload(theme, fp)
css = theme.css.last()
assert css.source_hash
def test_css_file_name_is_preserved_if_it_already_contains_correct_hash(
upload, theme, hashed_css_file
):
with open(hashed_css_file) as fp:
upload(theme, fp)
css = theme.css.last()
filename = str(css.source_file.path).split("/")[-1]
expected_filename = str(hashed_css_file).split("/")[-1]
assert filename == expected_filename
def test_new_hash_is_added_to_css_file_name_if_it_contains_incorrect_hash(
upload, theme
):
incorrectly_hashed_css_file = os.path.join(TESTS_DIR, "css", "test.0046cb3b.css")
with open(incorrectly_hashed_css_file) as fp:
upload(theme, fp)
css = theme.css.last()
filename = str(css.source_file.path).split("/")[-1]
assert css.source_hash in filename
def test_newly_uploaded_css_file_replaces_old_one_if_file_names_are_same(
upload, theme, css_file
):
with open(css_file) as fp:
upload(theme, fp)
original_css = theme.css.get()
with open(os.path.join(TESTS_DIR, "css", "test-changed.css")) as fp:
size = len(fp.read())
fp.seek(0)
upload(
theme, UploadedFile(fp, name="test.css", content_type="text/css", size=size)
)
updated_css = theme.css.last()
assert updated_css.name == original_css.name
assert updated_css.source_hash != original_css.source_hash
assert theme.css.count() == 1
def test_newly_uploaded_css_file_reuses_replaced_file_order_if_names_are_same(
upload, theme, css_file, hashed_css_file
):
with open(css_file) as fp:
upload(theme, fp)
original_css = theme.css.last()
with open(hashed_css_file) as fp:
upload(theme, fp)
with open(os.path.join(TESTS_DIR, "css", "test-changed.css")) as fp:
size = len(fp.read())
fp.seek(0)
upload(
theme, UploadedFile(fp, name="test.css", content_type="text/css", size=size)
)
updated_css = theme.css.get(order=original_css.order)
assert updated_css.name == original_css.name
def test_if_uploaded_css_file_contains_no_image_urls_rebuild_flag_is_not_set(
upload, theme, css_file
):
with open(css_file) as fp:
upload(theme, fp)
css = theme.css.last()
assert not css.source_needs_building
def test_if_uploaded_css_file_contains_image_url_it_has_rebuild_flag_set(upload, theme):
css_file = os.path.join(TESTS_DIR, "css", "test.needs-build.css")
with open(css_file) as fp:
upload(theme, fp)
css = theme.css.last()
assert css.source_needs_building
def test_uploading_css_file_triggers_css_build(
upload, theme, css_file, mock_build_theme_css
):
with open(css_file) as fp:
upload(theme, fp)
mock_build_theme_css.assert_called_once_with(theme.pk)
def test_error_message_is_set_if_no_css_file_was_uploaded(upload, theme):
response = upload(theme)
assert_has_error_message(response)
def test_error_message_is_set_if_user_attempts_to_upload_css_file_to_default_theme(
upload, default_theme
):
response = upload(default_theme)
assert_has_error_message(response)
def test_error_message_is_set_if_user_attempts_to_upload_css_file_to_nonexisting_theme(
upload, nonexisting_theme
):
response = upload(nonexisting_theme)
assert_has_error_message(response)
| 7,380
|
Python
|
.py
| 187
| 33.850267
| 88
| 0.67116
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,750
|
test_changing_active_theme.py
|
rafalp_Misago/misago/themes/admin/tests/test_changing_active_theme.py
|
import pytest
from django.urls import reverse
from ....cache.test import assert_invalidates_cache
from ....test import assert_has_error_message
from ... import THEME_CACHE
from ...models import Theme
@pytest.fixture
def activate_link(theme):
return reverse("misago:admin:themes:activate", kwargs={"pk": theme.pk})
def test_active_theme_can_changed(admin_client, activate_link, theme):
admin_client.post(activate_link)
theme.refresh_from_db()
assert theme.is_active
def test_default_theme_can_be_set_as_active_theme(admin_client, default_theme):
activate_link = reverse(
"misago:admin:themes:activate", kwargs={"pk": default_theme.pk}
)
admin_client.post(activate_link)
default_theme.refresh_from_db()
assert default_theme.is_active
def test_changing_active_theme_removes_active_status_from_previous_active_theme(
admin_client, activate_link, theme
):
admin_client.post(activate_link)
# objets.get() will raise if more than one theme is active
assert Theme.objects.get(is_active=True) == theme
def test_changing_active_theme_to_nonexisting_theme_sets_error_message(
admin_client, nonexisting_theme
):
activate_link = reverse(
"misago:admin:themes:activate", kwargs={"pk": nonexisting_theme.pk}
)
response = admin_client.post(activate_link)
assert_has_error_message(response)
def test_changing_active_theme_invalidates_themes_cache(admin_client, activate_link):
with assert_invalidates_cache(THEME_CACHE):
admin_client.post(activate_link)
| 1,550
|
Python
|
.py
| 37
| 37.837838
| 85
| 0.752667
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,751
|
test_exporting_themes.py
|
rafalp_Misago/misago/themes/admin/tests/test_exporting_themes.py
|
from django.urls import reverse
from ....test import assert_has_error_message
def test_exporting_default_theme_sets_error_message(admin_client, default_theme):
export_link = reverse("misago:admin:themes:export", kwargs={"pk": default_theme.pk})
response = admin_client.post(export_link)
assert_has_error_message(response)
def test_exporting_nonexisting_theme_sets_error_message(
admin_client, nonexisting_theme
):
export_link = reverse(
"misago:admin:themes:export", kwargs={"pk": nonexisting_theme.pk}
)
response = admin_client.post(export_link)
assert_has_error_message(response)
| 627
|
Python
|
.py
| 14
| 40.571429
| 88
| 0.75
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,752
|
test_deleting_assets.py
|
rafalp_Misago/misago/themes/admin/tests/test_deleting_assets.py
|
from pathlib import Path
import pytest
from django.core.files.base import ContentFile
from django.urls import reverse
from ....cache.test import assert_invalidates_cache
from ....test import assert_has_success_message
from ... import THEME_CACHE
@pytest.fixture
def delete_css(admin_client):
def delete_assets(theme, assets):
url = reverse("misago:admin:themes:delete-css", kwargs={"pk": theme.pk})
return admin_client.post(url, {"item": [i.pk for i in assets]})
return delete_assets
@pytest.fixture
def delete_media(admin_client):
def delete_assets(theme, assets):
url = reverse("misago:admin:themes:delete-media", kwargs={"pk": theme.pk})
return admin_client.post(url, {"item": [i.pk for i in assets]})
return delete_assets
def test_theme_css_can_be_deleted(theme, delete_css, css):
delete_css(theme, [css])
assert not theme.css.exists()
def test_deleting_css_also_deletes_css_source_files(theme, delete_css, css):
delete_css(theme, [css])
assert not Path(css.source_file.path).exists()
def test_deleting_css_also_deletes_css_build_files(theme, delete_css, css):
css.build_file = ContentFile("body {}", name="test.css")
css.build_hash = "abcdefgh"
css.save()
delete_css(theme, [css])
assert not Path(css.build_file.path).exists()
def test_theme_css_link_can_be_deleted(theme, delete_css, css_link):
delete_css(theme, [css_link])
assert not theme.css.exists()
def test_multiple_theme_css_can_be_deleted_at_single_time(
theme, delete_css, css, css_link
):
delete_css(theme, [css, css_link])
assert not theme.css.exists()
def test_theme_media_can_be_deleted(theme, delete_media, media):
delete_media(theme, [media])
assert not theme.media.exists()
def test_deleting_media_also_deletes_files(theme, delete_media, media):
delete_media(theme, [media])
assert not Path(media.file.path).exists()
def test_theme_images_can_be_deleted(theme, delete_media, image):
delete_media(theme, [image])
assert not theme.media.exists()
def test_deleting_image_also_deletes_files(theme, delete_media, image):
delete_media(theme, [image])
assert not Path(image.thumbnail.path).exists()
def test_multiple_theme_media_can_be_deleted_at_single_time(
theme, delete_media, media, image
):
delete_media(theme, [media, image])
assert not theme.media.exists()
def test_success_message_is_set_after_css_is_deleted(theme, delete_css, css):
response = delete_css(theme, [css])
assert_has_success_message(response)
def test_success_message_is_set_after_media_is_deleted(theme, delete_media, media):
response = delete_media(theme, [media])
assert_has_success_message(response)
def test_selecting_no_css_to_delete_causes_no_errors(theme, delete_css, css):
delete_css(theme, [])
assert theme.css.exists()
def test_selecting_no_media_to_delete_causes_no_errors(theme, delete_media, media):
delete_media(theme, [])
assert theme.media.exists()
def test_selecting_invalid_css_id_to_delete_causes_no_errors(
mocker, theme, delete_css, css
):
delete_css(theme, [mocker.Mock(pk="str")])
assert theme.css.exists()
def test_selecting_invalid_media_id_to_delete_causes_no_errors(
mocker, theme, delete_media, media
):
delete_media(theme, [mocker.Mock(pk="str")])
assert theme.media.exists()
def test_selecting_nonexisting_css_id_to_delete_causes_no_errors(
mocker, theme, delete_css, css
):
delete_css(theme, [mocker.Mock(pk=css.pk + 1)])
assert theme.css.exists()
def test_selecting_nonexisting_media_id_to_delete_causes_no_errors(
mocker, theme, delete_media, media
):
delete_media(theme, [mocker.Mock(pk=media.pk + 1)])
assert theme.media.exists()
def test_other_theme_css_is_not_deleted(delete_css, theme, other_theme, css):
delete_css(other_theme, [css])
assert theme.css.exists()
def test_other_theme_media_is_not_deleted(delete_media, theme, other_theme, media):
delete_media(other_theme, [media])
assert theme.media.exists()
def test_deleting_css_invalidates_theme_cache(theme, delete_css, css):
with assert_invalidates_cache(THEME_CACHE):
delete_css(theme, [css])
| 4,234
|
Python
|
.py
| 97
| 39.484536
| 83
| 0.726383
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,753
|
test_importing_themes.py
|
rafalp_Misago/misago/themes/admin/tests/test_importing_themes.py
|
import os
import pytest
from django.urls import reverse
from ....test import assert_contains
from ...models import Theme
import_link = reverse("misago:admin:themes:import")
class MockThemeExport:
def __init__(self, response):
self.name = "theme-export.zip"
self.content_type = response["content-type"]
self.size = response["content-length"]
self._response = response
def read(self):
return self._response.getvalue()
@pytest.fixture
def reimport_theme(admin_client):
def export_import_theme(theme, extra_data=None):
export_link = reverse("misago:admin:themes:export", kwargs={"pk": theme.pk})
theme_export = MockThemeExport(admin_client.post(export_link))
data = extra_data or {}
data["upload"] = theme_export
admin_client.post(import_link, data)
return Theme.objects.filter(pk__gt=theme.pk).last()
return export_import_theme
def assert_filenames_are_same(src, dst):
source_filename = os.path.split(src.path)[-1]
imported_filename = os.path.split(dst.path)[-1]
assert source_filename == imported_filename
def test_import_theme_form_is_displayed(admin_client):
response = admin_client.get(import_link)
assert_contains(response, "Import theme")
def test_theme_import_fails_if_export_was_not_uploaded(admin_client):
admin_client.post(import_link, {"upload": ""})
assert Theme.objects.count() == 1
def test_empty_theme_export_can_be_imported_back(reimport_theme, theme):
assert reimport_theme(theme)
def test_theme_can_be_imported_with_custom_name(reimport_theme, theme):
imported_theme = reimport_theme(theme, {"name": "Imported theme"})
assert imported_theme.name == "Imported theme"
def test_theme_can_be_imported_without_parent(reimport_theme, theme):
imported_theme = reimport_theme(theme)
assert imported_theme.parent is None
def test_theme_can_be_imported_with_custom_parent(reimport_theme, theme):
imported_theme = reimport_theme(theme, {"parent": theme.pk})
assert imported_theme.parent == theme
def test_theme_can_be_imported_with_default_theme_asparent(
reimport_theme, theme, default_theme
):
imported_theme = reimport_theme(theme, {"parent": default_theme.pk})
assert imported_theme.parent == default_theme
def test_theme_import_fails_if_parent_is_nonexisisting(
reimport_theme, theme, nonexisting_theme
):
assert not reimport_theme(theme, {"parent": nonexisting_theme.pk})
def test_importing_theme_under_parent_rebuilds_themes_tree(reimport_theme, theme):
imported_theme = reimport_theme(theme, {"parent": theme.pk})
theme.refresh_from_db()
assert imported_theme.tree_id == theme.tree_id
assert theme.lft == 1
assert theme.rght == 4
assert imported_theme.lft == 2
assert imported_theme.rght == 3
def test_theme_details_are_exported_and_imported_back(reimport_theme, theme):
theme.name = "Exported Theme"
theme.version = "0.1.2 FINAL"
theme.author = "John Doe"
theme.url = "https://example.com"
theme.save()
imported_theme = reimport_theme(theme)
assert imported_theme.name == theme.name
assert imported_theme.version == theme.version
assert imported_theme.author == theme.author
assert imported_theme.url == theme.url
def test_imported_theme_has_own_dirname(reimport_theme, theme):
imported_theme = reimport_theme(theme)
assert theme.dirname != imported_theme.dirname
def test_css_file_is_exported_and_imported_back(reimport_theme, theme, css):
imported_theme = reimport_theme(theme)
imported_css = imported_theme.css.last()
assert imported_css.name == css.name
assert imported_css.source_hash == css.source_hash
assert imported_css.size == css.size
assert_filenames_are_same(css.source_file, imported_css.source_file)
def test_css_link_is_exported_and_imported_back(reimport_theme, theme, css_link):
imported_theme = reimport_theme(theme)
imported_css = imported_theme.css.last()
assert imported_css.name == css_link.name
assert imported_css.url == css_link.url
def test_importing_css_link_triggers_getting_remote_css_size_task(
reimport_theme, theme, css_link, mock_update_remote_css_size
):
reimport_theme(theme)
mock_update_remote_css_size.assert_called_once()
def test_theme_export_containing_css_file_and_link_can_be_imported_back(
reimport_theme, theme, css, css_link
):
imported_theme = reimport_theme(theme)
css_names = list(imported_theme.css.values_list("name", flat=True))
assert css_names == [css.name, css_link.name]
def test_theme_css_order_is_preserved_after_import(
reimport_theme, theme, css, css_link
):
css_link.order = 1
css_link.save()
css.order = 2
css.save()
imported_theme = reimport_theme(theme)
css_names = list(imported_theme.css.values_list("name", flat=True))
assert css_names == [css_link.name, css.name]
def test_theme_export_containing_media_file_can_be_imported_back(
reimport_theme, theme, media
):
imported_theme = reimport_theme(theme)
imported_media = imported_theme.media.last()
assert imported_media.name == media.name
assert imported_media.hash == media.hash
assert imported_media.type == media.type
assert imported_media.size == media.size
assert_filenames_are_same(media.file, imported_media.file)
def test_theme_export_containing_image_file_can_be_imported_back(
reimport_theme, theme, image
):
imported_theme = reimport_theme(theme)
imported_image = imported_theme.media.last()
assert imported_image.name == image.name
assert imported_image.hash == image.hash
assert imported_image.type == image.type
assert imported_image.width == image.width
assert imported_image.height == image.height
assert imported_image.size == image.size
assert_filenames_are_same(image.file, imported_image.file)
def test_theme_export_containing_different_files_can_be_imported_back(
reimport_theme, theme, css, css_link, media, image
):
imported_theme = reimport_theme(theme)
css_names = list(imported_theme.css.values_list("name", flat=True))
assert css_names == [css.name, css_link.name]
media_names = list(imported_theme.media.values_list("name", flat=True))
assert media_names == [image.name, media.name]
def test_importing_theme_triggers_css_build(
reimport_theme, theme, css_link, mock_build_theme_css
):
imported_theme = reimport_theme(theme)
mock_build_theme_css.assert_called_once_with(imported_theme.pk)
| 6,576
|
Python
|
.py
| 144
| 40.979167
| 84
| 0.731186
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,754
|
test_creating_and_deleting_css_files.py
|
rafalp_Misago/misago/themes/admin/tests/test_creating_and_deleting_css_files.py
|
import pytest
from django.urls import reverse
from ....cache.test import assert_invalidates_cache
from ....test import assert_contains, assert_has_error_message
from ... import THEME_CACHE
@pytest.fixture
def create_link(theme):
return reverse("misago:admin:themes:new-css-file", kwargs={"pk": theme.pk})
@pytest.fixture
def edit_link(theme, css):
return reverse(
"misago:admin:themes:edit-css-file", kwargs={"pk": theme.pk, "css_pk": css.pk}
)
@pytest.fixture
def data():
return {"name": "test.css", "source": ".page-header { padding: 0}"}
def test_css_creation_form_is_displayed(admin_client, create_link):
response = admin_client.get(create_link)
assert response.status_code == 200
assert_contains(response, "New CSS")
def test_css_can_be_created(theme, admin_client, create_link, data):
admin_client.post(create_link, data)
assert theme.css.exists()
def test_css_is_created_with_entered_name(theme, admin_client, create_link, data):
admin_client.post(create_link, data)
assert theme.css.last().name == data["name"]
def test_created_source_file_contains_css_entered_by_user(
theme, admin_client, create_link, data
):
admin_client.post(create_link, data)
css = theme.css.last()
assert css.source_file.read().decode("utf-8") == data["source"]
def test_source_file_is_created_in_theme_directory(
theme, admin_client, create_link, data
):
admin_client.post(create_link, data)
css = theme.css.last()
assert theme.dirname in str(css.source_file)
def test_created_source_file_name_starts_with_asset_name(
theme, admin_client, create_link, data
):
admin_client.post(create_link, data)
css = theme.css.last()
source_filename = str(css.source_file).split("/")[-1]
assert source_filename.startswith("test.")
def test_created_source_file_has_css_extension(theme, admin_client, create_link, data):
admin_client.post(create_link, data)
css = theme.css.last()
source_filename = str(css.source_file).split("/")[-1]
assert source_filename.endswith(".css")
def test_created_source_file_is_hashed(theme, admin_client, create_link, data):
admin_client.post(create_link, data)
css = theme.css.last()
source_filename = str(css.source_file).split("/")[-1]
assert ".%s." % css.source_hash in source_filename
def test_css_creation_fails_if_name_is_not_given(
theme, admin_client, create_link, data
):
data["name"] = ""
admin_client.post(create_link, data)
assert not theme.css.exists()
def test_css_creation_fails_if_name_is_not_valid(
theme, admin_client, create_link, data
):
data["name"] = "missing-extension"
admin_client.post(create_link, data)
assert not theme.css.exists()
def test_css_creation_fails_if_name_is_already_taken_by_other_css_in_theme(
theme, admin_client, create_link, data, css
):
data["name"] = css.name
admin_client.post(create_link, data)
assert theme.css.count() == 1
def test_css_name_usage_check_passess_if_name_is_used_by_other_theme_css(
other_theme, admin_client, data, css
):
create_link = reverse(
"misago:admin:themes:new-css-file", kwargs={"pk": other_theme.pk}
)
data["name"] = css.name
admin_client.post(create_link, data)
assert other_theme.css.exists()
def test_css_creation_fails_if_source_is_not_given(
theme, admin_client, create_link, data
):
data["source"] = ""
admin_client.post(create_link, data)
assert not theme.css.exists()
def test_css_file_without_url_is_created_without_rebuilding_flag(
theme, admin_client, create_link, data
):
admin_client.post(create_link, data)
css = theme.css.last()
assert not css.source_needs_building
def test_css_file_with_image_url_is_created_with_rebuilding_flag(
theme, admin_client, create_link, data, image
):
data["source"] = "body { background-image: url(/static/%s); }" % image.name
admin_client.post(create_link, data)
css = theme.css.last()
assert css.source_needs_building
def test_creating_css_file_without_image_url_doesnt_trigger_single_css_file_rebuild(
theme, admin_client, create_link, data, image, mock_build_single_theme_css
):
admin_client.post(create_link, data)
mock_build_single_theme_css.assert_not_called()
def test_creating_css_file_with_image_url_triggers_single_css_file_rebuild(
theme, admin_client, create_link, data, image, mock_build_single_theme_css
):
data["source"] = "body { background-image: url(/static/%s); }" % image.name
admin_client.post(create_link, data)
css = theme.css.last()
mock_build_single_theme_css.assert_called_once_with(css.pk)
def test_css_file_is_created_with_correct_order(
theme, admin_client, create_link, css_link, data
):
admin_client.post(create_link, data)
css = theme.css.get(name=data["name"])
assert css.order == 1
def test_creating_css_file_invalidates_theme_cache(admin_client, create_link, data):
with assert_invalidates_cache(THEME_CACHE):
admin_client.post(create_link, data)
def test_error_message_is_set_if_user_attempts_to_create_css_in_default_theme(
default_theme, admin_client
):
create_link = reverse(
"misago:admin:themes:new-css-file", kwargs={"pk": default_theme.pk}
)
response = admin_client.get(create_link)
assert_has_error_message(response)
def test_error_message_is_set_if_user_attempts_to_create_css_in_nonexisting_theme(
nonexisting_theme, admin_client
):
create_link = reverse(
"misago:admin:themes:new-css-file", kwargs={"pk": nonexisting_theme.pk}
)
response = admin_client.get(create_link)
assert_has_error_message(response)
def test_css_creation_form_redirects_user_to_edition_after_creation(
theme, admin_client, create_link, data
):
data["stay"] = "1"
response = admin_client.post(create_link, data)
assert response["location"] == reverse(
"misago:admin:themes:edit-css-file",
kwargs={"pk": theme.pk, "css_pk": theme.css.last().pk},
)
def test_css_edition_form_is_displayed(admin_client, edit_link, css):
response = admin_client.get(edit_link)
assert response.status_code == 200
assert_contains(response, css.name)
def test_css_edition_form_contains_source_file_contents(admin_client, edit_link, css):
response = admin_client.get(edit_link)
assert_contains(response, css.source_file.read().decode("utf-8"))
def test_css_name_can_be_changed(admin_client, edit_link, css, data):
data["name"] = "new-name.css"
admin_client.post(edit_link, data)
css.refresh_from_db()
assert css.name == data["name"]
def test_css_name_change_also_changes_source_file_name(
admin_client, edit_link, css, data
):
data["name"] = "new-name.css"
admin_client.post(edit_link, data)
css.refresh_from_db()
assert "new-name" in str(css.source_file)
def test_css_source_can_be_changed(admin_client, edit_link, css, data):
data["source"] = ".misago-footer { display: none; }"
admin_client.post(edit_link, data)
css.refresh_from_db()
assert css.source_file.read().decode("utf-8") == data["source"]
def test_changing_css_source_also_changes_source_hash(
admin_client, edit_link, css, data
):
original_hash = css.source_hash
data["source"] = ".misago-footer { display: none; }"
admin_client.post(edit_link, data)
css.refresh_from_db()
assert css.source_hash != original_hash
def test_changing_css_source_also_changes_hash_in_filename(
admin_client, edit_link, css, data
):
original_hash = css.source_hash
data["source"] = ".misago-footer { display: none; }"
admin_client.post(edit_link, data)
css.refresh_from_db()
assert original_hash not in str(css.source_file)
assert css.source_hash in str(css.source_file)
def test_hash_stays_same_if_source_is_not_changed(admin_client, edit_link, css, data):
original_hash = css.source_hash
data["name"] = "changed.css"
data["source"] = css.source_file.read().decode("utf-8")
admin_client.post(edit_link, data)
css.refresh_from_db()
assert original_hash == css.source_hash
def test_file_is_not_updated_if_form_data_has_no_changes(
admin_client, edit_link, css, data
):
original_source_file = str(css.source_file)
data["name"] = css.name
data["source"] = css.source_file.read().decode("utf-8")
admin_client.post(edit_link, data)
css.refresh_from_db()
assert original_source_file == str(css.source_file)
def test_adding_image_url_to_edited_file_sets_rebuilding_flag(
theme, admin_client, edit_link, css, data, image
):
data["source"] = "body { background-image: url(/static/%s); }" % image.name
admin_client.post(edit_link, data)
css.refresh_from_db()
assert css.source_needs_building
def test_removing_url_from_edited_file_removes_rebuilding_flag(
theme, admin_client, edit_link, css, data
):
css.source_needs_building = True
css.save()
data["source"] = "body { background-image: none; }"
admin_client.post(edit_link, data)
css.refresh_from_db()
assert not css.source_needs_building
def test_adding_image_url_to_edited_file_triggers_single_css_file_rebuild(
theme, admin_client, edit_link, css, data, image, mock_build_single_theme_css
):
data["source"] = "body { background-image: url(/static/%s); }" % image.name
admin_client.post(edit_link, data)
mock_build_single_theme_css.assert_called_once_with(css.pk)
def test_removing_url_from_edited_file_deosnt_trigger_single_css_file_rebuild(
theme, admin_client, edit_link, css, data, mock_build_single_theme_css
):
data["source"] = "body { background-image: none; }"
admin_client.post(edit_link, data)
mock_build_single_theme_css.assert_not_called()
def test_css_order_stays_the_same_after_edit(admin_client, edit_link, css, data):
original_order = css.order
data["name"] = "changed.css"
admin_client.post(edit_link, data)
css.refresh_from_db()
assert css.order == original_order
def test_editing_css_file_invalidates_theme_cache(admin_client, edit_link, css, data):
with assert_invalidates_cache(THEME_CACHE):
admin_client.post(edit_link, data)
def test_css_edit_form_redirects_user_to_edition_after_saving(
theme, admin_client, edit_link, css, data
):
data["stay"] = "1"
response = admin_client.post(edit_link, data)
assert response["location"] == edit_link
def test_error_message_is_set_if_user_attempts_to_edit_css_file_in_default_theme(
default_theme, admin_client
):
edit_link = reverse(
"misago:admin:themes:edit-css-file",
kwargs={"pk": default_theme.pk, "css_pk": 1},
)
response = admin_client.get(edit_link)
assert_has_error_message(response)
def test_error_message_is_set_if_user_attempts_to_edit_css_file_in_nonexisting_theme(
nonexisting_theme, admin_client
):
edit_link = reverse(
"misago:admin:themes:edit-css-file",
kwargs={"pk": nonexisting_theme.pk, "css_pk": 1},
)
response = admin_client.get(edit_link)
assert_has_error_message(response)
def test_error_message_is_set_if_user_attempts_to_edit_css_belonging_to_other_theme(
other_theme, admin_client, css
):
edit_link = reverse(
"misago:admin:themes:edit-css-file",
kwargs={"pk": other_theme.pk, "css_pk": css.pk},
)
response = admin_client.get(edit_link)
assert_has_error_message(response)
def test_error_message_is_set_if_user_attempts_to_edit_nonexisting_css(
theme, admin_client
):
edit_link = reverse(
"misago:admin:themes:edit-css-file", kwargs={"pk": theme.pk, "css_pk": 1}
)
response = admin_client.get(edit_link)
assert_has_error_message(response)
def test_error_message_is_set_if_user_attempts_to_edit_css_link_with_file_form(
theme, admin_client, css_link
):
edit_link = reverse(
"misago:admin:themes:edit-css-file",
kwargs={"pk": theme.pk, "css_pk": css_link.pk},
)
response = admin_client.get(edit_link)
assert_has_error_message(response)
| 12,124
|
Python
|
.py
| 291
| 37.223368
| 87
| 0.705832
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,755
|
test_building_css_files.py
|
rafalp_Misago/misago/themes/admin/tests/test_building_css_files.py
|
import pytest
from ....cache.test import assert_invalidates_cache
from ... import THEME_CACHE
from ..css import change_css_source, get_theme_media_map, rebuild_css
from ..tasks import build_single_theme_css, build_theme_css
@pytest.fixture
def assert_snapshot_match(snapshot, theme):
def _assert_snapshot_match(result):
result = result.replace(theme.dirname, "themedir")
assert snapshot == result
return _assert_snapshot_match
@pytest.fixture
def media_map(theme, image):
return get_theme_media_map(theme)
def test_tasks_builds_single_css_file(theme, image, css_needing_build):
build_single_theme_css(css_needing_build.pk)
css_needing_build.refresh_from_db()
assert css_needing_build.build_file
def test_tasks_skips_single_css_file_that_doesnt_require_build(theme, css):
build_single_theme_css(css.pk)
css.refresh_from_db()
assert not css.build_file
def test_tasks_handles_nonexisting_css_file(db):
build_single_theme_css(1)
def test_tasks_builds_theme_css_files_that_require_it(theme, image, css_needing_build):
build_theme_css(theme.pk)
css_needing_build.refresh_from_db()
assert css_needing_build.build_file
def test_tasks_skips_theme_css_files_that_dont_require_build(theme, css):
build_theme_css(theme.pk)
css.refresh_from_db()
assert not css.build_file
def test_tasks_handles_nonexisting_theme(nonexisting_theme):
build_theme_css(nonexisting_theme.pk)
def test_media_map_for_theme_without_any_media_files_returns_empty_dict(theme):
assert get_theme_media_map(theme) == {}
def test_media_map_for_theme_with_media_files_returns_dict_with_data(
theme, image, media
):
assert get_theme_media_map(theme)
def test_css_file_is_build(media_map, css_needing_build):
rebuild_css(media_map, css_needing_build)
css_needing_build.refresh_from_db()
assert css_needing_build.build_file
def test_build_css_file_is_hashed(media_map, css_needing_build):
rebuild_css(media_map, css_needing_build)
css_needing_build.refresh_from_db()
assert css_needing_build.build_hash
def test_build_css_file_includes_hash_in_filename(media_map, css_needing_build):
rebuild_css(media_map, css_needing_build)
css_needing_build.refresh_from_db()
assert css_needing_build.build_hash in str(css_needing_build.build_file)
def test_build_css_file_has_size_set(media_map, css_needing_build):
rebuild_css(media_map, css_needing_build)
css_needing_build.refresh_from_db()
assert css_needing_build.size
def test_simple_url_to_file_is_replaced_with_valid_url(
assert_snapshot_match, media_map, image
):
css = ".page-header { background-image: url(%s); }" % image.name
result = change_css_source(media_map, css)
assert_snapshot_match(result)
def test_relative_url_to_file_is_replaced_with_valid_url(
assert_snapshot_match, media_map, image
):
css = ".page-header { background-image: url(./%s); }" % image.name
result = change_css_source(media_map, css)
assert_snapshot_match(result)
def test_url_to_file_from_create_react_app_is_replaced_with_valid_url(
assert_snapshot_match, media_map, image
):
hashed_name = str(image.file).split("/")[-1]
css = ".page-header { background-image: url(/static/media/%s); }" % hashed_name
result = change_css_source(media_map, css)
assert_snapshot_match(result)
def test_quoted_url_to_file_is_replaced_with_valid_url(
assert_snapshot_match, media_map, image
):
css = '.page-header { background-image: url("%s"); }' % image.name
result = change_css_source(media_map, css)
assert_snapshot_match(result)
def test_single_quoted_url_to_file_is_replaced_with_valid_url(
assert_snapshot_match, media_map, image
):
css = ".page-header { background-image: url('%s'); }" % image.name
result = change_css_source(media_map, css)
assert_snapshot_match(result)
def test_absolute_https_url_to_file_is_not_replaced(media_map):
css = ".page-header { background-image: url(https://cdn.example.com/bg.png); }"
result = change_css_source(media_map, css)
assert result == css
def test_absolute_http_url_to_file_is_not_replaced(media_map):
css = ".page-header { background-image: url(http://cdn.example.com/bg.png); }"
result = change_css_source(media_map, css)
assert result == css
def test_absolute_protocol_relative_url_to_file_is_not_replaced(media_map):
css = ".page-header { background-image: url(://cdn.example.com/bg.png); }"
result = change_css_source(media_map, css)
assert result == css
def test_css_file_with_multiple_different_urls_is_correctly_replaced(
assert_snapshot_match, media_map, image
):
css = (
".page-header { background-image: url(http://cdn.example.com/bg.png); }"
'\n.container { background-image: url("%s"); }'
'\n.alert { background-image: url("%s"); }'
) % (image.name, str(image.file).strip("/")[-1])
result = change_css_source(media_map, css)
assert_snapshot_match(result)
def test_building_single_theme_css_invalidates_theme_cache(
theme, image, css_needing_build
):
with assert_invalidates_cache(THEME_CACHE):
build_single_theme_css(css_needing_build.pk)
def test_building_theme_css_invalidates_theme_cache(theme):
with assert_invalidates_cache(THEME_CACHE):
build_theme_css(theme.pk)
| 5,379
|
Python
|
.py
| 117
| 41.649573
| 87
| 0.724899
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,756
|
test_creating_and_editing_themes.py
|
rafalp_Misago/misago/themes/admin/tests/test_creating_and_editing_themes.py
|
import pytest
from django.urls import reverse
from ....cache.test import assert_invalidates_cache
from ....test import assert_contains, assert_has_error_message
from ... import THEME_CACHE
from ...models import Theme
@pytest.fixture
def create_link():
return reverse("misago:admin:themes:new")
@pytest.fixture
def edit_link(theme):
return reverse("misago:admin:themes:edit", kwargs={"pk": theme.pk})
def test_theme_creation_form_is_displayed(admin_client, create_link):
response = admin_client.get(create_link)
assert response.status_code == 200
assert_contains(response, "New theme")
def test_theme_creation_form_reads_parent_from_url_and_preselects_it_in_parent_select(
admin_client, create_link, theme
):
response = admin_client.get("%s?parent=%s" % (create_link, theme.pk))
assert_contains(response, '<option value="%s" selected>' % theme.pk)
def test_theme_creation_form_reads_parent_from_url_and_discards_invalid_value(
admin_client, create_link, theme
):
response = admin_client.get("%s?parent=%s" % (create_link, theme.pk + 1))
assert response.status_code == 200
def test_theme_can_be_created(admin_client, create_link):
admin_client.post(create_link, {"name": "New Theme"})
Theme.objects.get(name="New Theme")
def test_child_theme_for_custom_theme_can_be_created(admin_client, create_link, theme):
admin_client.post(create_link, {"name": "New Theme", "parent": theme.pk})
child_theme = Theme.objects.get(name="New Theme")
assert child_theme.parent == theme
def test_child_theme_for_default_theme_can_be_created(
admin_client, create_link, default_theme
):
admin_client.post(create_link, {"name": "New Theme", "parent": default_theme.pk})
child_theme = Theme.objects.get(name="New Theme")
assert child_theme.parent == default_theme
def test_creating_child_theme_updates_themes_tree(admin_client, create_link, theme):
admin_client.post(create_link, {"name": "New Theme", "parent": theme.pk})
child_theme = Theme.objects.get(name="New Theme")
assert child_theme.tree_id == theme.tree_id
assert child_theme.lft == 2
assert child_theme.rght == 3
theme.refresh_from_db()
assert theme.lft == 1
assert theme.rght == 4
def test_theme_creation_fails_if_name_is_not_given(admin_client, create_link):
admin_client.post(create_link, {"name": ""})
assert Theme.objects.count() == 1
def test_theme_creation_fails_if_parent_theme_doesnt_exist(
admin_client, create_link, nonexisting_theme
):
admin_client.post(
create_link, {"name": "New Theme", "parent": nonexisting_theme.pk}
)
assert Theme.objects.count() == 1
def test_theme_edition_form_is_displayed(admin_client, edit_link, theme):
response = admin_client.get(edit_link)
assert response.status_code == 200
assert_contains(response, theme.name)
def test_theme_name_can_be_edited(admin_client, edit_link, theme):
admin_client.post(edit_link, {"name": "Edited Theme"})
theme.refresh_from_db()
assert theme.name == "Edited Theme"
def test_theme_can_be_moved_under_other_theme(
admin_client, edit_link, theme, default_theme
):
admin_client.post(edit_link, {"name": theme.name, "parent": default_theme.pk})
theme.refresh_from_db()
assert theme.parent == default_theme
def test_moving_theme_under_other_theme_updates_themes_tree(
admin_client, edit_link, theme, default_theme
):
admin_client.post(edit_link, {"name": theme.name, "parent": default_theme.pk})
default_theme.refresh_from_db()
theme.refresh_from_db()
assert theme.tree_id == default_theme.tree_id
assert theme.lft == 2
assert theme.rght == 3
assert default_theme.lft == 1
assert default_theme.rght == 4
def test_theme_cant_be_moved_under_itself(admin_client, edit_link, theme):
admin_client.post(edit_link, {"name": theme.name, "parent": theme.pk})
theme.refresh_from_db()
assert not theme.parent
def test_theme_cant_be_moved_under_its_child_theme(admin_client, edit_link, theme):
child_theme = Theme.objects.create(name="Child Theme", parent=theme)
admin_client.post(edit_link, {"name": theme.name, "parent": child_theme.pk})
theme.refresh_from_db()
assert not theme.parent
def test_moving_child_theme_under_other_theme_updates_both_themes_trees(
admin_client, theme, default_theme
):
child_theme = Theme.objects.create(name="Child Theme", parent=theme)
edit_link = reverse("misago:admin:themes:edit", kwargs={"pk": child_theme.pk})
admin_client.post(edit_link, {"name": child_theme.name, "parent": default_theme.pk})
default_theme.refresh_from_db()
child_theme.refresh_from_db()
theme.refresh_from_db()
assert child_theme.parent == default_theme
assert child_theme.tree_id == default_theme.tree_id
assert child_theme.lft == 2
assert child_theme.rght == 3
assert default_theme.lft == 1
assert default_theme.rght == 4
assert theme.tree_id != default_theme.tree_id
assert theme.lft == 1
assert theme.rght == 2
def test_moving_theme_under_root_updates_theme_tree_and_creates_new_one(
admin_client, edit_link, theme, default_theme
):
theme.parent = default_theme
theme.save()
admin_client.post(edit_link, {"name": theme.name})
default_theme.refresh_from_db()
theme.refresh_from_db()
assert theme.parent is None
assert theme.tree_id != default_theme.tree_id
assert theme.lft == 1
assert theme.rght == 2
assert default_theme.lft == 1
assert default_theme.rght == 2
def test_moving_theme_with_child_under_root_updates_theme_tree_and_creates_new_one(
admin_client, edit_link, theme, default_theme
):
theme.parent = default_theme
theme.save()
child_theme = Theme.objects.create(name="Child Theme", parent=theme)
admin_client.post(edit_link, {"name": theme.name})
default_theme.refresh_from_db()
child_theme.refresh_from_db()
theme.refresh_from_db()
assert theme.tree_id != default_theme.tree_id
assert theme.lft == 1
assert theme.rght == 4
assert child_theme.parent == theme
assert child_theme.tree_id == theme.tree_id
assert child_theme.lft == 2
assert child_theme.rght == 3
assert default_theme.lft == 1
assert default_theme.rght == 2
def test_theme_edition_fails_if_parent_theme_doesnt_exist(
admin_client, edit_link, theme, nonexisting_theme
):
admin_client.post(
edit_link, {"name": "Edited Theme", "parent": nonexisting_theme.pk}
)
theme.refresh_from_db()
assert theme.name != "Edited Theme"
def test_error_message_is_set_if_user_attempts_to_edit_default_theme(
admin_client, default_theme
):
edit_link = reverse("misago:admin:themes:edit", kwargs={"pk": default_theme.pk})
response = admin_client.get(edit_link)
assert_has_error_message(response)
def test_error_message_is_set_if_user_attempts_to_edit_nonexisting_theme(
admin_client, nonexisting_theme
):
edit_link = reverse("misago:admin:themes:edit", kwargs={"pk": nonexisting_theme.pk})
response = admin_client.get(edit_link)
assert_has_error_message(response)
def test_moving_theme_invalidates_themes_cache(
admin_client, edit_link, theme, default_theme
):
with assert_invalidates_cache(THEME_CACHE):
admin_client.post(edit_link, {"name": theme.name, "parent": default_theme.pk})
| 7,412
|
Python
|
.py
| 168
| 39.708333
| 88
| 0.715958
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,757
|
test_css_name_validation.py
|
rafalp_Misago/misago/themes/admin/tests/test_css_name_validation.py
|
import pytest
from django.forms import ValidationError
from ..validators import validate_css_name
def test_validation_fails_if_name_is_missing_css_extension():
with pytest.raises(ValidationError):
validate_css_name("filename")
def test_extension_validation_is_case_insensitive():
validate_css_name("filename.CsS")
def test_validation_fails_if_name_starts_with_period():
with pytest.raises(ValidationError):
validate_css_name(".filename.css")
def test_validation_fails_if_name_contains_css_extension_only():
with pytest.raises(ValidationError):
validate_css_name(".css")
def test_validation_fails_if_name_contains_special_characters():
with pytest.raises(ValidationError):
validate_css_name("test().css")
def test_validation_fails_if_name_lacks_latin_characters_or_numbers():
with pytest.raises(ValidationError):
validate_css_name("_-.css")
def test_name_can_contain_underscores_scores_and_periods():
validate_css_name("some_css-final2.dark.css")
| 1,029
|
Python
|
.py
| 22
| 42
| 70
| 0.758065
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,758
|
apps.py
|
rafalp_Misago/misago/htmx/apps.py
|
from django.apps import AppConfig
class MisagoHTMXConfig(AppConfig):
name = "misago.htmx"
label = "misago_htmx"
verbose_name = "Misago HTMX utils"
| 161
|
Python
|
.py
| 5
| 28.4
| 38
| 0.74026
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,759
|
request.py
|
rafalp_Misago/misago/htmx/request.py
|
from django.http import HttpRequest
def is_request_htmx(request: HttpRequest) -> bool:
return request.headers.get("hx-request") == "true"
| 144
|
Python
|
.py
| 3
| 45
| 54
| 0.755396
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,760
|
tests.py
|
rafalp_Misago/misago/htmx/tests.py
|
from .request import is_request_htmx
def test_is_request_htmx_returns_true_for_htmx_request(rf):
request = rf.get("/", headers={"hx-request": "true"})
assert is_request_htmx(request)
def test_is_request_htmx_returns_false_for_non_htmx_request(rf):
request = rf.get("/", headers={})
assert not is_request_htmx(request)
| 338
|
Python
|
.py
| 7
| 44.428571
| 64
| 0.715596
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,761
|
models.py
|
rafalp_Misago/misago/menus/models.py
|
from django.db import models
from django.utils.translation import pgettext_lazy
class MenuItem(models.Model):
MENU_BOTH = "both"
MENU_NAVBAR = "navbar"
MENU_FOOTER = "footer"
MENU_CHOICES = [
(MENU_BOTH, pgettext_lazy("menu choice", "Navbar and footer")),
(MENU_NAVBAR, pgettext_lazy("menu choice", "Navbar")),
(MENU_FOOTER, pgettext_lazy("menu choice", "Footer")),
]
menu = models.CharField(max_length=6, choices=MENU_CHOICES)
title = models.CharField(max_length=255)
url = models.URLField()
order = models.IntegerField(default=0)
css_class = models.CharField(max_length=255, null=True, blank=True)
target_blank = models.BooleanField(default=False)
rel = models.CharField(max_length=255, null=True, blank=True)
class Meta:
ordering = ("order",)
get_latest_by = "order"
def __str__(self):
return self.title
| 916
|
Python
|
.py
| 23
| 34.086957
| 71
| 0.673423
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,762
|
apps.py
|
rafalp_Misago/misago/menus/apps.py
|
from django.apps import AppConfig
class MisagoMenusConfig(AppConfig):
name = "misago.menus"
label = "misago_menus"
verbose_name = "Misago Menus"
| 159
|
Python
|
.py
| 5
| 28
| 35
| 0.743421
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,763
|
context_processors.py
|
rafalp_Misago/misago/menus/context_processors.py
|
from typing import List
from .menuitems import get_footer_menu_items, get_navbar_menu_items
from .models import MenuItem
def menus(request):
navbar_items = get_navbar_menu_items(request.cache_versions)
footer_items = get_footer_menu_items(request.cache_versions)
navbarItemsJson = serialize_items(navbar_items)
footerItemsJson = []
navbarUrls = [item["url"] for item in navbarItemsJson]
for footerItem in serialize_items(footer_items):
if footerItem["url"] not in navbarUrls:
footerItemsJson.append(footerItem)
request.frontend_context.update(
{
"extraMenuItems": navbarItemsJson,
"extraFooterItems": footerItemsJson,
}
)
return {
"navbar_menu": navbar_items,
"footer_menu": footer_items,
}
def serialize_items(items: List[MenuItem]) -> List[dict]:
serialized = []
for item in items:
serialized.append(
{
"title": item["title"],
"url": item["url"],
"className": item["css_class"],
"targetBlank": item["target_blank"],
"rel": item["rel"],
}
)
return serialized
| 1,217
|
Python
|
.py
| 35
| 26.428571
| 67
| 0.617221
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,764
|
cache.py
|
rafalp_Misago/misago/menus/cache.py
|
from django.core.cache import cache
from ..cache.versions import invalidate_cache
from . import MENU_ITEMS_CACHE
def get_menus_cache(cache_versions):
key = get_cache_key(cache_versions)
return cache.get(key)
def set_menus_cache(cache_versions, menus):
key = get_cache_key(cache_versions)
cache.set(key, menus)
def get_cache_key(cache_versions):
return "%s_%s" % (MENU_ITEMS_CACHE, cache_versions[MENU_ITEMS_CACHE])
def clear_menus_cache():
invalidate_cache(MENU_ITEMS_CACHE)
| 508
|
Python
|
.py
| 13
| 35.538462
| 73
| 0.751029
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,765
|
menu.py
|
rafalp_Misago/misago/menus/menu.py
|
from dataclasses import dataclass
from typing import Callable, Optional
from django.http import HttpRequest
from django.urls import reverse
class Menu:
__slots__ = ("items",)
def __init__(self):
self.items: list["MenuItem"] = []
def add_item(
self,
*,
key: str,
url_name: str,
label: str,
icon: str | None = None,
after: str | None = None,
before: str | None = None,
visible: Callable[[HttpRequest], bool] | None = None,
) -> "MenuItem":
if after and before:
raise ValueError("'after' and 'before' can't be used together.")
item = MenuItem(
key=key,
url_name=url_name,
label=label,
icon=icon,
visible=visible,
)
if after or before:
new_items: list["MenuItem"] = []
for other_item in self.items:
if other_item.key == after:
new_items.append(other_item)
new_items.append(item)
elif other_item.key == before:
new_items.append(item)
new_items.append(other_item)
else:
new_items.append(other_item)
self.items = new_items
if item not in self.items:
other_key = after or before
raise ValueError(f"Item with key '{other_key}' doesn't exist.")
else:
self.items.append(item)
return item
def bind_to_request(self, request: HttpRequest) -> "BoundMenu":
bound_items: list["BoundMenuItem"] = []
for item in self.items:
if bound_item := item.bind_to_request(request):
bound_items.append(bound_item)
return BoundMenu(bound_items)
class BoundMenu:
__slots__ = ("active", "items")
active: Optional["BoundMenuItem"]
items: list["BoundMenuItem"]
def __init__(self, items: list["BoundMenuItem"]):
self.active: Optional["BoundMenuItem"] = None
self.items: list["BoundMenuItem"] = items
for item in items:
if item.active:
self.active = item
break
@dataclass(frozen=True)
class MenuItem:
__slots__ = ("key", "url_name", "label", "icon", "visible")
key: str
url_name: str
label: str
icon: str | None
visible: Callable[[HttpRequest], bool] | None
def bind_to_request(self, request: HttpRequest) -> Optional["BoundMenuItem"] | None:
if self.visible and not self.visible(request):
return None
reversed_url = reverse(self.url_name)
return BoundMenuItem(
active=request.path_info.startswith(reversed_url),
key=self.key,
url=reversed_url,
label=str(self.label),
icon=self.icon,
)
@dataclass(frozen=True)
class BoundMenuItem:
__slots__ = ("active", "key", "url", "label", "icon")
active: bool
key: str
url: str
label: str
icon: str | None
| 3,084
|
Python
|
.py
| 90
| 24.633333
| 88
| 0.560458
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,766
|
menuitems.py
|
rafalp_Misago/misago/menus/menuitems.py
|
from .cache import set_menus_cache, get_menus_cache
from .models import MenuItem
def get_navbar_menu_items(cache_versions):
return get_items(cache_versions).get(MenuItem.MENU_NAVBAR)
def get_footer_menu_items(cache_versions):
return get_items(cache_versions).get(MenuItem.MENU_FOOTER)
def get_items(cache_versions):
items = get_menus_cache(cache_versions)
if items is None:
items = get_items_from_db()
set_menus_cache(cache_versions, items)
return items
def get_items_from_db():
return {
MenuItem.MENU_NAVBAR: get_navbar_menu_items_from_db(),
MenuItem.MENU_FOOTER: get_footer_menu_items_from_db(),
}
def get_navbar_menu_items_from_db():
return MenuItem.objects.exclude(menu=MenuItem.MENU_FOOTER).values()
def get_footer_menu_items_from_db():
return MenuItem.objects.exclude(menu=MenuItem.MENU_NAVBAR).values()
| 890
|
Python
|
.py
| 21
| 37.571429
| 71
| 0.736289
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,767
|
0001_initial.py
|
rafalp_Misago/misago/menus/migrations/0001_initial.py
|
# Generated by Django 2.2.3 on 2019-09-15 19:15
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="MenuItem",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("title", models.CharField(max_length=255)),
("url", models.URLField()),
(
"menu",
models.CharField(
choices=[
("both", "Navbar and footer"),
("navbar", "Navbar"),
("footer", "Footer"),
],
max_length=6,
),
),
("order", models.IntegerField(default=0)),
("css_class", models.CharField(blank=True, max_length=255, null=True)),
("target_blank", models.BooleanField(default=False)),
("rel", models.CharField(blank=True, max_length=255, null=True)),
],
options={"ordering": ("order",), "get_latest_by": "order"},
)
]
| 1,459
|
Python
|
.py
| 39
| 20.589744
| 87
| 0.410601
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,768
|
0002_cache_version.py
|
rafalp_Misago/misago/menus/migrations/0002_cache_version.py
|
# Generated by Django 1.11.16 on 2018-12-02 15:54
from django.db import migrations
from .. import MENU_ITEMS_CACHE
from ...cache.operations import StartCacheVersioning
class Migration(migrations.Migration):
dependencies = [("misago_menus", "0001_initial"), ("misago_cache", "0001_initial")]
operations = [StartCacheVersioning(MENU_ITEMS_CACHE)]
| 357
|
Python
|
.py
| 7
| 48.285714
| 87
| 0.768786
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,769
|
conftest.py
|
rafalp_Misago/misago/menus/tests/conftest.py
|
import pytest
from ..menuitems import get_footer_menu_items, get_navbar_menu_items
from ..models import MenuItem
@pytest.fixture
def navar_menu_item(db):
return MenuItem.objects.create(
title="Top Menu Item",
url="https://navbar_menu_item.com",
menu=MenuItem.MENU_NAVBAR,
)
@pytest.fixture
def footer_menu_item(db):
return MenuItem.objects.create(
title="Footer Menu Item",
url="https://footer_menu_item.com",
menu=MenuItem.MENU_FOOTER,
)
@pytest.fixture
def both_menus_item(db):
return MenuItem.objects.create(
title="Both Positions Menu Item",
url="https://both_menus_menu_item.com",
menu=MenuItem.MENU_BOTH,
)
@pytest.fixture
def menu_item_with_attributes(db):
return MenuItem.objects.create(
title="Menu item with attributes",
url="https://menu_item_with_attributes.com",
menu=MenuItem.MENU_BOTH,
rel="noopener nofollow",
target_blank=True,
css_class="test-item-css-class",
)
@pytest.fixture
def navbar_menu_items(
db, cache_versions, navar_menu_item, both_menus_item, menu_item_with_attributes
):
return get_navbar_menu_items(cache_versions)
@pytest.fixture
def footer_menu_items(
db, cache_versions, footer_menu_item, both_menus_item, menu_item_with_attributes
):
return get_footer_menu_items(cache_versions)
| 1,396
|
Python
|
.py
| 44
| 26.613636
| 84
| 0.699776
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,770
|
test_menu.py
|
rafalp_Misago/misago/menus/tests/test_menu.py
|
from unittest.mock import Mock
import pytest
from ..menu import Menu
@pytest.fixture
def menu():
return Menu()
def test_add_item_adds_item(menu):
menu.add_item(
key="test",
url_name="misago:account-details",
label="Test",
)
assert len(menu.items) == 1
assert menu.items[0].key == "test"
def test_add_item_after_adds_item_in_right_position(menu):
menu.add_item(
key="test",
url_name="misago:account-details",
label="Test",
)
menu.add_item(
key="test2",
url_name="misago:account-username",
label="Test 2",
)
menu.add_item(
key="test3",
url_name="misago:account-email",
label="Test 3",
after="test",
)
assert len(menu.items) == 3
assert menu.items[0].key == "test"
assert menu.items[1].key == "test3"
assert menu.items[2].key == "test2"
def test_add_item_before_adds_item_in_right_position(menu):
menu.add_item(
key="test",
url_name="misago:account-details",
label="Test",
)
menu.add_item(
key="test2",
url_name="misago:account-username",
label="Test 2",
)
menu.add_item(
key="test3",
url_name="misago:account-email",
label="Test 3",
before="test2",
)
assert len(menu.items) == 3
assert menu.items[0].key == "test"
assert menu.items[1].key == "test3"
assert menu.items[2].key == "test2"
def test_add_item_invalid_after_raises_value_error(menu):
menu.add_item(
key="test",
url_name="misago:account-details",
label="Test",
)
menu.add_item(
key="test2",
url_name="misago:account-username",
label="Test 2",
)
with pytest.raises(ValueError) as exc_info:
menu.add_item(
key="test3",
url_name="misago:account-email",
label="Test 3",
after="invalid",
)
assert "Item with key 'invalid' doesn't exist." == str(exc_info.value)
def test_add_item_invalid_before_raises_value_error(menu):
menu.add_item(
key="test",
url_name="misago:account-details",
label="Test",
)
menu.add_item(
key="test2",
url_name="misago:account-username",
label="Test 2",
)
with pytest.raises(ValueError) as exc_info:
menu.add_item(
key="test3",
url_name="misago:account-email",
label="Test 3",
before="invalid",
)
assert "Item with key 'invalid' doesn't exist." == str(exc_info.value)
def test_bind_to_request_returns_bound_menu(menu):
menu.add_item(
key="test",
url_name="misago:account-details",
label="Test",
)
menu.add_item(
key="test2",
url_name="misago:account-username",
label="Test 2",
)
menu.add_item(
key="test3",
url_name="misago:account-email",
label="Test 3",
)
bound_menu = menu.bind_to_request(Mock(path_info="/account/username/"))
assert bound_menu.active.url == "/account/username/"
assert len(bound_menu.items) == 3
assert not bound_menu.items[0].active
assert bound_menu.items[0].url == "/account/details/"
assert bound_menu.items[1].active
assert bound_menu.items[1].url == "/account/username/"
assert not bound_menu.items[2].active
assert bound_menu.items[2].url == "/account/email/"
def test_bind_to_request__filters_items_visibility(menu):
menu.add_item(
key="test",
url_name="misago:account-details",
label="Test",
)
menu.add_item(
key="test2",
url_name="misago:account-username",
label="Test 2",
visible=lambda r: r.user is False,
)
menu.add_item(
key="test3",
url_name="misago:account-email",
label="Test 3",
visible=lambda r: r.user,
)
bound_menu = menu.bind_to_request(Mock(path_info="/account/username/", user=False))
assert bound_menu.active.url == "/account/username/"
assert len(bound_menu.items) == 2
assert bound_menu.items[0].key == "test"
assert not bound_menu.items[0].active
assert bound_menu.items[0].url == "/account/details/"
assert bound_menu.items[1].key == "test2"
assert bound_menu.items[1].active
assert bound_menu.items[1].url == "/account/username/"
| 4,429
|
Python
|
.py
| 146
| 23.363014
| 87
| 0.59854
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,771
|
test_menus_rendering.py
|
rafalp_Misago/misago/menus/tests/test_menus_rendering.py
|
from django.urls import reverse
from ...test import assert_contains
def test_custom_menu_items_are_rendered_in_navbar(client, navar_menu_item):
response = client.get(reverse("misago:index"))
assert_contains(response, navar_menu_item.url)
def test_custom_menu_items_are_rendered_in_footer(client, footer_menu_item):
response = client.get(reverse("misago:index"))
assert_contains(response, footer_menu_item.url)
def test_custom_menu_items_are_rendered_in_both_menus(client, both_menus_item):
response = client.get(reverse("misago:index"))
assert_contains(response, both_menus_item.url)
| 615
|
Python
|
.py
| 11
| 52.090909
| 79
| 0.768844
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,772
|
test_context_processor.py
|
rafalp_Misago/misago/menus/tests/test_context_processor.py
|
from unittest.mock import Mock
from ..context_processors import menus
def test_context_processor_adds_navbar_menu_to_context(
navbar_menu_items, cache_versions
):
result = menus(Mock(cache_versions=cache_versions))
assert isinstance(result, dict)
assert len(navbar_menu_items) == len(result["navbar_menu"])
def test_context_processor_adds_footer_menu_to_context(
footer_menu_items, cache_versions
):
result = menus(Mock(cache_versions=cache_versions))
assert isinstance(result, dict)
assert len(footer_menu_items) == len(result["footer_menu"])
| 581
|
Python
|
.py
| 14
| 37.857143
| 63
| 0.758007
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,773
|
ordering.py
|
rafalp_Misago/misago/menus/admin/ordering.py
|
from ..models import MenuItem
def get_next_free_order():
last = MenuItem.objects.last()
if last:
return last.order + 1
return 0
| 150
|
Python
|
.py
| 6
| 20.333333
| 34
| 0.669014
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,774
|
__init__.py
|
rafalp_Misago/misago/menus/admin/__init__.py
|
from django.urls import path
from django.utils.translation import pgettext_lazy
from .views import (
DeleteMenuItem,
EditMenuItem,
MenuItemsList,
MoveDownMenuItem,
MoveUpMenuItem,
NewMenuItem,
)
class MisagoAdminExtension:
def register_urlpatterns(self, urlpatterns):
# Menu items
urlpatterns.namespace("menu-items/", "menu-items", "settings")
urlpatterns.patterns(
"settings:menu-items",
path("", MenuItemsList.as_view(), name="index"),
path("<int:page>/", MenuItemsList.as_view(), name="index"),
path("new/", NewMenuItem.as_view(), name="new"),
path("edit/<int:pk>/", EditMenuItem.as_view(), name="edit"),
path("delete/<int:pk>/", DeleteMenuItem.as_view(), name="delete"),
path("down/<int:pk>/", MoveDownMenuItem.as_view(), name="down"),
path("up/<int:pk>/", MoveUpMenuItem.as_view(), name="up"),
)
def register_navigation_nodes(self, site):
site.add_node(
name=pgettext_lazy("admin node", "Menu items"),
description=pgettext_lazy(
"admin node",
"Use those options to add custom items to the navbar and footer menus.",
),
parent="settings",
namespace="menu-items",
)
| 1,341
|
Python
|
.py
| 34
| 30.441176
| 88
| 0.599386
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,775
|
forms.py
|
rafalp_Misago/misago/menus/admin/forms.py
|
from django import forms
from django.utils.translation import pgettext_lazy
from ...admin.forms import YesNoSwitch
from ..models import MenuItem
from ..cache import clear_menus_cache
class MenuItemForm(forms.ModelForm):
title = forms.CharField(label=pgettext_lazy("admin menu item form", "Title"))
url = forms.URLField(
label=pgettext_lazy("admin menu item form", "URL"),
help_text=pgettext_lazy(
"admin menu item form", "URL where this item will point to."
),
)
menu = forms.ChoiceField(
label=pgettext_lazy("admin menu item form", "Menu"),
choices=MenuItem.MENU_CHOICES,
help_text=pgettext_lazy(
"admin menu item form", "Menu in which this item will be displayed."
),
)
css_class = forms.CharField(
label=pgettext_lazy("admin menu item form", "CSS class"),
help_text=pgettext_lazy(
"admin menu item form",
'Optional. Additional CSS class to include in link\'s "class" HTML attribute.',
),
required=False,
)
target_blank = YesNoSwitch(
label=pgettext_lazy("admin menu item form", "Open this link in new window"),
help_text=pgettext_lazy(
"admin menu item form",
'Enabling this option will result in the target="_blank" attribute being added to this link\'s HTML element.',
),
required=False,
)
rel = forms.CharField(
label=pgettext_lazy("admin menu item form", "Rel attribute"),
help_text=pgettext_lazy(
"admin menu item form",
'Optional "rel" attribute that this item will use (ex. "nofollow").',
),
required=False,
)
class Meta:
model = MenuItem
fields = ["title", "url", "menu", "css_class", "target_blank", "rel"]
def save(self):
item = super().save()
clear_menus_cache()
return item
| 1,934
|
Python
|
.py
| 51
| 30.156863
| 122
| 0.624068
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,776
|
views.py
|
rafalp_Misago/misago/menus/admin/views.py
|
from django.contrib import messages
from django.utils.translation import pgettext_lazy
from ...admin.views import generic
from ..models import MenuItem
from ..cache import clear_menus_cache
from .forms import MenuItemForm
from .ordering import get_next_free_order
class MenuItemAdmin(generic.AdminBaseMixin):
root_link = "misago:admin:settings:menu-items:index"
model = MenuItem
form_class = MenuItemForm
templates_dir = "misago/admin/menuitems"
message_404 = pgettext_lazy(
"admin menu items", "Requested menu item does not exist."
)
def handle_form(self, form, request, target):
form.save()
if self.message_submit:
messages.success(request, self.message_submit % {"item": target})
class MenuItemsList(MenuItemAdmin, generic.ListView):
ordering = (("order", None),)
mass_actions = [
{
"action": "delete",
"name": pgettext_lazy("admin menu items", "Delete items"),
"confirmation": pgettext_lazy(
"admin menu items", "Are you sure you want to delete those menu items?"
),
}
]
def action_delete(self, request, items):
items.delete()
clear_menus_cache()
messages.success(
request,
pgettext_lazy("admin menu items", "Selected menu items have been deleted."),
)
class NewMenuItem(MenuItemAdmin, generic.ModelFormView):
message_submit = pgettext_lazy(
"admin menu items", "New menu item %(item)s has been saved."
)
def handle_form(self, form, request, target):
super().handle_form(form, request, target)
form.instance.order = get_next_free_order()
form.instance.save()
clear_menus_cache()
class EditMenuItem(MenuItemAdmin, generic.ModelFormView):
message_submit = pgettext_lazy(
"admin menu items", "Menu item %(item)s has been edited."
)
def handle_form(self, form, request, target):
super().handle_form(form, request, target)
form.instance.save()
clear_menus_cache()
class DeleteMenuItem(MenuItemAdmin, generic.ButtonView):
def button_action(self, request, target):
target.delete()
clear_menus_cache()
message = pgettext_lazy(
"admin menu items", "Menu item %(item)s has been deleted."
)
messages.success(request, message % {"item": target})
class MoveDownMenuItem(MenuItemAdmin, generic.ButtonView):
def button_action(self, request, target):
try:
other_target = MenuItem.objects.filter(order__gt=target.order)
other_target = other_target.earliest("order")
except MenuItem.DoesNotExist:
other_target = None
if other_target:
other_target.order, target.order = target.order, other_target.order
other_target.save(update_fields=["order"])
target.save(update_fields=["order"])
clear_menus_cache()
message = pgettext_lazy(
"admin menu items", "Menu item %(item)s has been moved after %(other)s."
)
targets_names = {"item": target, "other": other_target}
messages.success(request, message % targets_names)
class MoveUpMenuItem(MenuItemAdmin, generic.ButtonView):
def button_action(self, request, target):
try:
other_target = MenuItem.objects.filter(order__lt=target.order)
other_target = other_target.latest("order")
except MenuItem.DoesNotExist:
other_target = None
if other_target:
other_target.order, target.order = target.order, other_target.order
other_target.save(update_fields=["order"])
target.save(update_fields=["order"])
clear_menus_cache()
message = pgettext_lazy(
"admin menu items",
"Menu item %(item)s has been moved before %(other)s.",
)
targets_names = {"item": target, "other": other_target}
messages.success(request, message % targets_names)
| 4,110
|
Python
|
.py
| 97
| 33.536082
| 88
| 0.637503
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,777
|
conftest.py
|
rafalp_Misago/misago/menus/admin/tests/conftest.py
|
import pytest
from django.urls import reverse
from ...models import MenuItem
@pytest.fixture
def list_url():
return reverse("misago:admin:settings:menu-items:index")
@pytest.fixture
def menu_item(db):
return MenuItem.objects.create(
menu=MenuItem.MENU_NAVBAR,
title="Test TMLA",
url="https://top_menu_item_admin.com",
order=0,
)
@pytest.fixture
def other_menu_item(db):
return MenuItem.objects.create(
menu=MenuItem.MENU_BOTH,
title="Other Menu Item",
url="https://other_menu_item.com",
order=1,
)
| 589
|
Python
|
.py
| 22
| 21.636364
| 60
| 0.676786
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,778
|
test_ordering_menu_links.py
|
rafalp_Misago/misago/menus/admin/tests/test_ordering_menu_links.py
|
from django.urls import reverse
from ....cache.test import assert_invalidates_cache
from ... import MENU_ITEMS_CACHE
def test_top_menu_item_can_be_moved_down(admin_client, menu_item, other_menu_item):
menu_item.order = 0
menu_item.save()
other_menu_item.order = 1
other_menu_item.save()
admin_client.post(
reverse("misago:admin:settings:menu-items:down", kwargs={"pk": menu_item.pk})
)
menu_item.refresh_from_db()
assert menu_item.order == 1
other_menu_item.refresh_from_db()
assert other_menu_item.order == 0
def test_top_menu_item_cant_be_moved_up(admin_client, menu_item, other_menu_item):
menu_item.order = 0
menu_item.save()
other_menu_item.order = 1
other_menu_item.save()
admin_client.post(
reverse("misago:admin:settings:menu-items:up", kwargs={"pk": menu_item.pk})
)
menu_item.refresh_from_db()
assert menu_item.order == 0
other_menu_item.refresh_from_db()
assert other_menu_item.order == 1
def test_bottom_menu_item_cant_be_moved_down(admin_client, menu_item, other_menu_item):
menu_item.order = 1
menu_item.save()
other_menu_item.order = 0
other_menu_item.save()
admin_client.post(
reverse("misago:admin:settings:menu-items:down", kwargs={"pk": menu_item.pk})
)
menu_item.refresh_from_db()
assert menu_item.order == 1
other_menu_item.refresh_from_db()
assert other_menu_item.order == 0
def test_bottom_menu_item_can_be_moved_up(admin_client, menu_item, other_menu_item):
menu_item.order = 1
menu_item.save()
other_menu_item.order = 0
other_menu_item.save()
admin_client.post(
reverse("misago:admin:settings:menu-items:up", kwargs={"pk": menu_item.pk})
)
menu_item.refresh_from_db()
assert menu_item.order == 0
other_menu_item.refresh_from_db()
assert other_menu_item.order == 1
def test_moving_menu_item_down_invalidates_menu_items_cache(
admin_client, menu_item, other_menu_item
):
menu_item.order = 0
menu_item.save()
other_menu_item.order = 1
other_menu_item.save()
with assert_invalidates_cache(MENU_ITEMS_CACHE):
admin_client.post(
reverse(
"misago:admin:settings:menu-items:down", kwargs={"pk": menu_item.pk}
)
)
def test_moving_menu_item_up_invalidates_menu_items_cache(
admin_client, menu_item, other_menu_item
):
menu_item.order = 1
menu_item.save()
other_menu_item.order = 0
other_menu_item.save()
with assert_invalidates_cache(MENU_ITEMS_CACHE):
admin_client.post(
reverse("misago:admin:settings:menu-items:up", kwargs={"pk": menu_item.pk})
)
| 2,718
|
Python
|
.py
| 75
| 30.533333
| 87
| 0.673298
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,779
|
test_admin_views.py
|
rafalp_Misago/misago/menus/admin/tests/test_admin_views.py
|
import pytest
from django.urls import reverse
from ....test import assert_contains
from ...models import MenuItem
def test_nav_contains_menus_item(admin_client, list_url):
response = admin_client.get(list_url)
assert_contains(response, reverse("misago:admin:settings:menu-items:index"))
def test_empty_list_renders(admin_client, list_url):
response = admin_client.get(list_url)
assert response.status_code == 200
def test_list_renders_menu_item(admin_client, list_url, menu_item):
response = admin_client.get(list_url)
assert_contains(response, menu_item.title)
def test_menu_items_can_be_mass_deleted(admin_client, list_url):
items = []
for _ in range(10):
item = MenuItem.objects.create(
menu=MenuItem.MENU_FOOTER,
title="Test Item {}".format(_),
url="https://items{}.com".format(_),
)
items.append(item.pk)
assert MenuItem.objects.count() == 10
response = admin_client.post(
list_url, data={"action": "delete", "selected_items": items}
)
assert response.status_code == 302
assert MenuItem.objects.count() == 0
def test_creation_form_renders(admin_client):
response = admin_client.get(reverse("misago:admin:settings:menu-items:new"))
assert response.status_code == 200
def test_form_creates_new_menu_item(admin_client):
response = admin_client.post(
reverse("misago:admin:settings:menu-items:new"),
{
"menu": MenuItem.MENU_FOOTER,
"title": "Test Item",
"url": "https://admin.com/items/",
},
)
item = MenuItem.objects.get()
assert item.menu == MenuItem.MENU_FOOTER
assert item.title == "Test Item"
assert item.url == "https://admin.com/items/"
def test_edit_form_renders(admin_client, menu_item):
response = admin_client.get(
reverse("misago:admin:settings:menu-items:edit", kwargs={"pk": menu_item.pk})
)
assert_contains(response, menu_item.title)
def test_edit_form_updates_menu_items(admin_client, menu_item):
response = admin_client.post(
reverse("misago:admin:settings:menu-items:edit", kwargs={"pk": menu_item.pk}),
data={
"menu": menu_item.MENU_BOTH,
"title": "Test Edited",
"url": "https://example.com/edited/",
},
)
assert response.status_code == 302
menu_item.refresh_from_db()
assert menu_item.menu == MenuItem.MENU_BOTH
assert menu_item.title == "Test Edited"
assert menu_item.url == "https://example.com/edited/"
def test_menu_item_can_be_deleted(admin_client, menu_item):
response = admin_client.post(
reverse("misago:admin:settings:menu-items:delete", kwargs={"pk": menu_item.pk})
)
assert response.status_code == 302
with pytest.raises(MenuItem.DoesNotExist):
menu_item.refresh_from_db()
| 2,881
|
Python
|
.py
| 70
| 34.785714
| 87
| 0.665949
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,780
|
results.py
|
rafalp_Misago/misago/moderation/results.py
|
from dataclasses import dataclass
class ModerationResult:
pass
@dataclass(frozen=True)
class ModerationTemplateResult:
context: dict
template_name: str
def update_context(self, context: dict):
self.context.update(context)
class ModerationBulkResult:
updated: set[int]
def __init__(self, updated: set[int]):
self.updated = updated
| 378
|
Python
|
.py
| 13
| 24.384615
| 44
| 0.739496
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,781
|
threads.py
|
rafalp_Misago/misago/moderation/threads.py
|
from django.contrib import messages
from django.forms import ValidationError
from django.http import HttpRequest
from django.utils.translation import pgettext, pgettext_lazy
from ..categories.models import Category
from ..threads.models import Thread
from .forms import MoveThreads
from .results import ModerationResult, ModerationBulkResult, ModerationTemplateResult
class ThreadsBulkModerationAction:
id: str
name: str
full_name: str | None
submit_btn: str | None
multistage: bool = False
def __call__(
self, request: HttpRequest, threads: list[Thread]
) -> ModerationResult | None:
raise NotImplementedError()
def get_context_data(self):
return {
"id": self.id,
"name": str(self.name),
"full_name": str(getattr(self, "full_name", self.name)),
"submit_btn": str(getattr(self, "submit_btn", self.name)),
}
def create_bulk_result(self, threads: list[Thread]) -> ModerationBulkResult:
return ModerationBulkResult(set(thread.id for thread in threads))
class MoveThreadsBulkModerationAction(ThreadsBulkModerationAction):
id: str = "move"
name: str = pgettext_lazy("threads bulk moderation action", "Move")
full_name: str = pgettext_lazy("threads bulk moderation action", "Move threads")
multistage: bool = True
def __call__(self, request: HttpRequest, threads: list[Thread]) -> ModerationResult:
if request.POST.get("confirm") == self.id:
form = MoveThreads(
request.POST,
threads=threads,
request=request,
)
if form.is_valid():
category = Category.objects.get(id=form.cleaned_data["category"])
result = self.execute(request, threads, category)
if result.updated:
messages.success(
request,
pgettext("threads bulk open", "Threads moved"),
)
return result
else:
form = MoveThreads(threads=threads, request=request)
return ModerationTemplateResult(
template_name="misago/moderation/move_threads.html",
context={"form": form},
)
def execute(
self, request: HttpRequest, threads: list[Thread], category: Category
) -> ModerationBulkResult | None:
updated: list[Thread] = []
for thread in threads:
if thread.category_id != category.id:
thread.move(category)
thread.save()
updated.append(thread)
return self.create_bulk_result(updated)
class OpenThreadsBulkModerationAction(ThreadsBulkModerationAction):
id: str = "open"
name: str = pgettext_lazy("threads bulk moderation action", "Open")
def __call__(
self, request: HttpRequest, threads: list[Thread]
) -> ModerationBulkResult:
closed_threads = [thread for thread in threads if thread.is_closed]
updated = Thread.objects.filter(
id__in=[thread.id for thread in closed_threads]
).update(is_closed=False)
if updated:
messages.success(
request,
pgettext("threads bulk open", "Threads opened"),
)
return self.create_bulk_result(closed_threads)
class CloseThreadsBulkModerationAction(ThreadsBulkModerationAction):
id: str = "close"
name: str = pgettext_lazy("threads bulk moderation action", "Close")
def __call__(
self, request: HttpRequest, threads: list[Thread]
) -> ModerationBulkResult:
open_threads = [thread for thread in threads if not thread.is_closed]
updated = Thread.objects.filter(
id__in=[thread.id for thread in open_threads]
).update(is_closed=True)
if updated:
messages.success(
request,
pgettext("threads bulk open", "Threads closed"),
)
return self.create_bulk_result(open_threads)
| 4,075
|
Python
|
.py
| 96
| 32.739583
| 88
| 0.631606
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,782
|
forms.py
|
rafalp_Misago/misago/moderation/forms.py
|
from django import forms
from django.http import HttpRequest
from django.utils.translation import pgettext_lazy
from ..categories.proxy import CategoriesProxy
from ..permissions.enums import CategoryPermission
from ..permissions.proxy import UserPermissionsProxy
from ..threads.models import Thread
def get_category_choices(
categories: CategoriesProxy, *, allow_empty: bool = True
) -> list[tuple[int, str]]:
choices: list[tuple[int, str]] = []
if allow_empty:
choices.append(
("", pgettext_lazy("moderation form empty_category", "Select category"))
)
for category in categories.categories_list:
prefix = " → " * category["level"]
choices.append((category["id"], prefix + category["name"]))
return choices
def get_disabled_category_choices(
user_permissions: UserPermissionsProxy,
categories: CategoriesProxy,
) -> set[int]:
choices: set[int] = set()
categories_browse = user_permissions.categories[CategoryPermission.BROWSE]
categories_start = user_permissions.categories[CategoryPermission.START]
categories_moderator = user_permissions.categories_moderator
for category in categories.categories_list:
if (
category["is_vanilla"]
or category["id"] not in categories_browse
or category["id"] not in categories_start
or (category["is_closed"] and category["id"] not in categories_moderator)
):
choices.add(category["id"])
return choices
class MoveThreads(forms.Form):
threads: list[Thread]
request: HttpRequest
category = forms.TypedChoiceField(
label=pgettext_lazy("moderation move threads form", "Move to category"),
coerce=int,
choices=[],
)
def __init__(
self,
data: dict | None = None,
*,
threads: list[Thread],
request: HttpRequest,
):
super().__init__(data, prefix="moderation")
self.fields["category"].choices = get_category_choices(request.categories)
self.disabled_choices = get_disabled_category_choices(
request.user_permissions, request.categories
)
self.threads = threads
self.request = request
| 2,247
|
Python
|
.py
| 58
| 31.965517
| 85
| 0.679853
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,783
|
apps.py
|
rafalp_Misago/misago/forumindex/apps.py
|
from django.apps import AppConfig
class MisagoForumIndexConfig(AppConfig):
name = "misago.forumindex"
label = "misago_forumindex"
verbose_name = "Misago Forum Index"
| 180
|
Python
|
.py
| 5
| 32.2
| 40
| 0.768786
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,784
|
menus.py
|
rafalp_Misago/misago/forumindex/menus.py
|
from dataclasses import replace
from django.http import HttpRequest
from django.urls import reverse
from django.utils.translation import pgettext_lazy
from ..menus.menu import BoundMenuItem, Menu
main_menu = Menu()
main_menu.add_item(
key="threads",
url_name="misago:threads",
label=pgettext_lazy("main menu item", "Threads"),
)
main_menu.add_item(
key="categories",
url_name="misago:categories",
label=pgettext_lazy("main menu item", "Categories"),
)
def get_main_menu_items(request: HttpRequest) -> list[BoundMenuItem]:
menu = main_menu.bind_to_request(request)
menu_items = {item.key: item for item in menu.items}
final_menu: list[BoundMenuItem] = []
if forum_index := menu_items.pop(request.settings.index_view, None):
final_menu.append(replace(forum_index, url=reverse("misago:index")))
final_menu += menu_items.values()
return final_menu
| 911
|
Python
|
.py
| 24
| 34.166667
| 76
| 0.734018
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,785
|
views.py
|
rafalp_Misago/misago/forumindex/views.py
|
from typing import Tuple
from django.http import Http404
from django.utils.translation import pgettext_lazy
from ..categories.views import index as categories
from ..threads.views.list import threads
IndexView = Tuple[str, callable]
class IndexViews:
views: dict[str, IndexView] = {}
def __init__(self):
self.views: dict[str, IndexView] = {}
def add_index_view(self, id_: str, name: str, view: callable):
self.views[id_] = (name, view)
def get_choices(self) -> Tuple[Tuple[str, str]]:
return tuple((key, self.views[key][0]) for key in self.views)
def get_view(self, id_: str) -> callable:
return self.views[id_][1]
index_views = IndexViews()
index_views.add_index_view(
"threads",
pgettext_lazy("index view choice", "Threads"),
threads,
)
index_views.add_index_view(
"categories",
pgettext_lazy("index view choice", "Categories"),
categories,
)
def forum_index(request, *args, **kwargs):
try:
view = index_views.get_view(request.settings.index_view)
except KeyError:
raise Http404()
else:
return view(request, *args, **kwargs, is_index=True)
| 1,169
|
Python
|
.py
| 34
| 29.647059
| 69
| 0.68125
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,786
|
test_forum_index_view.py
|
rafalp_Misago/misago/forumindex/tests/test_forum_index_view.py
|
from django.urls import reverse
from ...conf.test import override_dynamic_settings
from ...test import assert_contains
@override_dynamic_settings(index_view="categories")
def test_forum_index_displays_categories(db, client):
response = client.get(reverse("misago:index"))
assert_contains(response, "page-categories")
@override_dynamic_settings(index_view="threads")
def test_forum_index_displays_threads(db, client):
response = client.get(reverse("misago:index"))
assert_contains(response, "page-threads")
@override_dynamic_settings(index_view="invalid")
def test_forum_index_displays_404_for_invalid_index_view(db, client):
response = client.get(reverse("misago:index"))
assert response.status_code == 404
@override_dynamic_settings(index_view="categories")
def test_categories_view_redirects_to_index_when_its_homepage(db, client):
response = client.get(reverse("misago:categories"))
assert response.status_code == 302
assert response.headers["location"] == reverse("misago:index")
@override_dynamic_settings(index_view="threads")
def test_categories_view_returns_response_when_its_not_homepage(db, client):
response = client.get(reverse("misago:categories"))
assert_contains(response, "page-categories")
@override_dynamic_settings(index_view="threads")
def test_threads_view_redirects_to_index_when_its_homepage(db, client):
response = client.get(reverse("misago:threads"))
assert response.status_code == 302
assert response.headers["location"] == reverse("misago:index")
@override_dynamic_settings(index_view="categories")
def test_threads_view_returns_response_when_its_not_homepage(db, client):
response = client.get(reverse("misago:threads"))
assert_contains(response, "page-threads")
| 1,771
|
Python
|
.py
| 33
| 50.272727
| 76
| 0.769588
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,787
|
test_index_views.py
|
rafalp_Misago/misago/forumindex/tests/test_index_views.py
|
import pytest
from ..views import IndexViews
index_views = IndexViews()
index_views.add_index_view("threads", "Threads", lambda: "threads")
index_views.add_index_view("categories", "Categories", lambda: "categories")
def test_index_views_get_choices_returns_django_form_choices_tuple():
choices = index_views.get_choices()
assert choices == (
("threads", "Threads"),
("categories", "Categories"),
)
def test_index_views_get_view_returns_view_callable():
view = index_views.get_view("threads")
assert view() == "threads"
def test_index_views_get_view_raises_key_error_for_invalid_view():
with pytest.raises(KeyError):
index_views.get_view("invalid")
| 705
|
Python
|
.py
| 17
| 37.176471
| 76
| 0.708824
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,788
|
test_get_main_menu_items.py
|
rafalp_Misago/misago/forumindex/tests/test_get_main_menu_items.py
|
from unittest.mock import Mock
from ..menus import get_main_menu_items
def test_get_main_menu_items_returns_categories_as_first_item():
main_menu = get_main_menu_items(
Mock(path_info="/", settings=Mock(index_view="categories"))
)
assert main_menu[0].key == "categories"
assert main_menu[1].key == "threads"
def test_get_main_menu_items_returns_threads_as_first_item():
main_menu = get_main_menu_items(
Mock(path_info="/", settings=Mock(index_view="threads"))
)
assert main_menu[0].key == "threads"
assert main_menu[1].key == "categories"
def test_get_main_menu_items_returns_threads_as_first_item_if_setting_is_invalid():
main_menu = get_main_menu_items(
Mock(path_info="/", settings=Mock(index_view="invalid"))
)
assert main_menu[0].key == "threads"
assert main_menu[1].key == "categories"
| 874
|
Python
|
.py
| 20
| 38.6
| 83
| 0.682464
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,789
|
privatethreads.py
|
rafalp_Misago/misago/middleware/privatethreads.py
|
from typing import TYPE_CHECKING
from django.http import HttpRequest
from ..categories.enums import CategoryTree
from ..categories.models import Category
from ..readtracker.privatethreads import get_unread_private_threads
from ..readtracker.tracker import annotate_categories_read_time
if TYPE_CHECKING:
from ..users.models import User
def sync_user_unread_private_threads(get_response):
def middleware(request):
if request.user.is_authenticated and request.user.sync_unread_private_threads:
user = request.user
category = get_private_threads_category(user)
queryset = get_unread_private_threads(request, category, category.read_time)
update_user_unread_private_threads(user, queryset.count())
return get_response(request)
return middleware
def get_private_threads_category(user: "User") -> Category:
return annotate_categories_read_time(
user,
Category.objects.filter(tree_id=CategoryTree.PRIVATE_THREADS),
).first()
def update_user_unread_private_threads(user: "User", unread_count: int):
user.unread_private_threads = unread_count
user.sync_unread_private_threads = False
user.save(
update_fields=[
"unread_private_threads",
"sync_unread_private_threads",
],
)
| 1,331
|
Python
|
.py
| 31
| 36.548387
| 88
| 0.725369
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,790
|
apps.py
|
rafalp_Misago/misago/middleware/apps.py
|
from django.apps import AppConfig
class MisagoMiddlewareConfig(AppConfig):
name = "misago.middleware"
label = "misago_middleware"
verbose_name = "Misago Middleware"
| 179
|
Python
|
.py
| 5
| 32
| 40
| 0.773256
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,791
|
permissions.py
|
rafalp_Misago/misago/middleware/permissions.py
|
from ..permissions.proxy import UserPermissionsProxy
def permissions_middleware(get_response):
def middleware(request):
request.user_permissions = UserPermissionsProxy(
request.user, request.cache_versions
)
return get_response(request)
return middleware
| 303
|
Python
|
.py
| 8
| 30.875
| 56
| 0.735395
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,792
|
categories.py
|
rafalp_Misago/misago/middleware/categories.py
|
from ..categories.proxy import CategoriesProxy
def categories_middleware(get_response):
def middleware(request):
request.categories = CategoriesProxy(
request.user_permissions, request.cache_versions
)
return get_response(request)
return middleware
| 297
|
Python
|
.py
| 8
| 30.125
| 60
| 0.729825
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,793
|
htmx.py
|
rafalp_Misago/misago/middleware/htmx.py
|
from ..htmx.request import is_request_htmx
def htmx_middleware(get_response):
def middleware(request):
request.is_htmx = is_request_htmx(request)
return get_response(request)
return middleware
| 220
|
Python
|
.py
| 6
| 31.166667
| 50
| 0.734597
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,794
|
test_sync_user_unread_private_threads.py
|
rafalp_Misago/misago/middleware/tests/test_sync_user_unread_private_threads.py
|
from datetime import timedelta
from unittest.mock import Mock
from django.utils import timezone
from ...categories.proxy import CategoriesProxy
from ...permissions.proxy import UserPermissionsProxy
from ...threads.models import ThreadParticipant
from ...threads.test import post_thread
from ...readtracker.models import ReadThread
from ..privatethreads import sync_user_unread_private_threads
def test_sync_user_unread_private_threads_middleware_updates_user_with_unread_threads(
dynamic_settings, cache_versions, user, user_private_thread
):
user.unread_private_threads = 0
user.sync_unread_private_threads = True
user.joined_on = user.joined_on.replace(year=2010)
user.save()
user_permissions = UserPermissionsProxy(user, cache_versions)
request = Mock(
categories=CategoriesProxy(user_permissions, cache_versions),
settings=dynamic_settings,
user=user,
user_permissions=user_permissions,
)
middleware = sync_user_unread_private_threads(Mock())
middleware(request)
user.refresh_from_db()
assert user.unread_private_threads == 1
assert not user.sync_unread_private_threads
def test_sync_user_unread_private_threads_middleware_updates_user_without_unread_threads(
dynamic_settings, cache_versions, user
):
user.unread_private_threads = 100
user.sync_unread_private_threads = True
user.joined_on = user.joined_on.replace(year=2010)
user.save()
user_permissions = UserPermissionsProxy(user, cache_versions)
request = Mock(
categories=CategoriesProxy(user_permissions, cache_versions),
settings=dynamic_settings,
user=user,
user_permissions=user_permissions,
)
middleware = sync_user_unread_private_threads(Mock())
middleware(request)
user.refresh_from_db()
assert user.unread_private_threads == 0
assert not user.sync_unread_private_threads
def test_sync_user_unread_private_threads_middleware_skips_anonymous_user(
dynamic_settings, cache_versions, anonymous_user
):
user_permissions = UserPermissionsProxy(anonymous_user, cache_versions)
request = Mock(
categories=CategoriesProxy(user_permissions, cache_versions),
settings=dynamic_settings,
user=anonymous_user,
user_permissions=user_permissions,
)
middleware = sync_user_unread_private_threads(Mock())
middleware(request)
def test_sync_user_unread_private_threads_middleware_skips_user_without_sync_flag(
dynamic_settings, cache_versions, user
):
user.unread_private_threads = 100
user.sync_unread_private_threads = False
user.joined_on = user.joined_on.replace(year=2010)
user.save()
user_permissions = UserPermissionsProxy(user, cache_versions)
request = Mock(
categories=CategoriesProxy(user_permissions, cache_versions),
settings=dynamic_settings,
user=user,
user_permissions=user_permissions,
)
middleware = sync_user_unread_private_threads(Mock())
middleware(request)
user.refresh_from_db()
assert user.unread_private_threads == 100
assert not user.sync_unread_private_threads
| 3,164
|
Python
|
.py
| 78
| 35.358974
| 89
| 0.749837
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,795
|
cursor.py
|
rafalp_Misago/misago/pagination/cursor.py
|
from dataclasses import dataclass
from typing import Any, List
from django.http import Http404
class PaginationError(Http404):
pass
class EmptyPageError(PaginationError):
last_cursor: int | None
def __init__(self, last_cursor: int | None):
self.last_cursor = last_cursor
@dataclass
class CursorPaginationResult:
items: List[Any]
cursor: int | None
has_next: bool
has_previous: bool
next_cursor: Any | None
previous_cursor: Any | None
@property
def next_cursor_query(self) -> str:
if self.next_cursor:
return f"?cursor={self.next_cursor}"
return ""
@property
def previous_cursor_query(self) -> str:
if self.previous_cursor:
return f"?cursor={self.previous_cursor}"
return ""
def paginate_queryset(
request,
queryset,
per_page: int,
order_by: str,
) -> CursorPaginationResult:
cursor = get_query_value(request, "cursor")
queryset = queryset.order_by(order_by)
order_desc = order_by[0] == "-"
col_name = order_by.lstrip("-")
if cursor:
if order_desc:
filter_kwarg = {f"{col_name}__lt": cursor}
else:
filter_kwarg = {f"{col_name}__gt": cursor}
items_queryset = queryset.filter(**filter_kwarg)
else:
items_queryset = queryset
items = list(items_queryset[: per_page + 1])
has_next = False
has_previous = False
next_cursor = None
previous_cursor = None
if cursor and not items:
last_cursor = get_last_cursor(queryset, per_page, order_by)
raise EmptyPageError(last_cursor)
if len(items) > per_page:
has_next = True
items = items[:per_page]
next_cursor = getattr(items[-1], col_name)
if cursor and items:
first_cursor = getattr(items[0], col_name)
if order_desc:
filter_kwarg = {f"{col_name}__gt": first_cursor}
else:
filter_kwarg = {f"{col_name}__lt": first_cursor}
previous_items = list(
queryset.filter(**filter_kwarg)
.select_related(None)
.prefetch_related(None)
.order_by(col_name if order_desc else f"-{col_name}")
.values_list(col_name, flat=True)[: per_page + 1]
)
has_previous = bool(previous_items)
if len(previous_items) > per_page:
previous_cursor = previous_items[-1]
return CursorPaginationResult(
items=items,
cursor=cursor,
has_next=has_next,
has_previous=has_previous,
next_cursor=next_cursor,
previous_cursor=previous_cursor,
)
def get_query_value(request, name: str, default: int | None = None) -> int | None:
value = request.GET[name] if name in request.GET else default
if value is None:
return value
try:
value = int(value)
if value < 1:
raise ValueError()
except (TypeError, ValueError):
raise PaginationError({name: "must be a positive integer"})
return value
def get_last_cursor(queryset, per_page: int, order_by: str) -> int | None:
if order_by[0] == "-":
col_name = reversed_order_by = order_by[1:]
else:
reversed_order_by = f"-{order_by}"
col_name = order_by
last_items = list(
queryset.select_related(None)
.prefetch_related(None)
.order_by(reversed_order_by)
.values_list(col_name, flat=True)[: per_page + 1]
)
if len(last_items) > per_page:
return last_items[-1]
return None
| 3,571
|
Python
|
.py
| 107
| 26.084112
| 82
| 0.616012
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,796
|
apps.py
|
rafalp_Misago/misago/pagination/apps.py
|
from django.apps import AppConfig
class MisagoPaginationConfig(AppConfig):
name = "misago.pagination"
label = "misago_pagination"
verbose_name = "Misago pagination utils"
| 185
|
Python
|
.py
| 5
| 33.2
| 44
| 0.775281
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,797
|
redirect.py
|
rafalp_Misago/misago/pagination/redirect.py
|
from urllib.parse import urlencode
from django.http import HttpRequest, HttpResponseRedirect
from django.shortcuts import redirect
from .cursor import EmptyPageError
def redirect_to_last_page(
request: HttpRequest, empty_page_error: EmptyPageError
) -> HttpResponseRedirect:
last_page_url = request.path_info
new_querystring = request.GET.dict()
if empty_page_error.last_cursor:
new_querystring["cursor"] = empty_page_error.last_cursor
else:
new_querystring.pop("cursor", None)
if new_querystring:
last_page_url += "?" + urlencode(new_querystring)
return redirect(last_page_url)
| 637
|
Python
|
.py
| 16
| 35.1875
| 64
| 0.749593
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,798
|
conftest.py
|
rafalp_Misago/misago/pagination/tests/conftest.py
|
import pytest
from ...notifications.models import Notification
@pytest.fixture
def notifications(user):
objects = Notification.objects.bulk_create(
[Notification(user=user, verb=f"test_{i}") for i in range(15)]
)
return sorted([obj.id for obj in objects])
| 280
|
Python
|
.py
| 8
| 31
| 70
| 0.735075
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
17,799
|
test_redirect_to_last_page.py
|
rafalp_Misago/misago/pagination/tests/test_redirect_to_last_page.py
|
from unittest.mock import Mock
from ..cursor import EmptyPageError
from ..redirect import redirect_to_last_page
def test_redirect_to_last_page_builds_redirect_without_cursor_for_first_page():
request = Mock(
path_info="/path-info/",
GET=Mock(dict=Mock(return_value={"cursor": 100})),
)
redirect = redirect_to_last_page(request, EmptyPageError(None))
assert redirect.status_code == 302
assert redirect["location"] == "/path-info/"
def test_redirect_to_last_page_builds_redirect_with_cursor_for_first_page():
request = Mock(
path_info="/path-info/",
GET=Mock(dict=Mock(return_value={"cursor": 100})),
)
redirect = redirect_to_last_page(request, EmptyPageError(40))
assert redirect.status_code == 302
assert redirect["location"] == "/path-info/?cursor=40"
def test_redirect_to_last_page_with_cursor_keeps_other_querystring_items():
request = Mock(
path_info="/path-info/",
GET=Mock(dict=Mock(return_value={"cursor": 100, "search": "query"})),
)
redirect = redirect_to_last_page(request, EmptyPageError(40))
assert redirect.status_code == 302
assert redirect["location"] == "/path-info/?cursor=40&search=query"
def test_redirect_to_last_page_without_cursor_keeps_other_querystring_items():
request = Mock(
path_info="/path-info/",
GET=Mock(dict=Mock(return_value={"cursor": 100, "search": "query"})),
)
redirect = redirect_to_last_page(request, EmptyPageError(None))
assert redirect.status_code == 302
assert redirect["location"] == "/path-info/?search=query"
| 1,613
|
Python
|
.py
| 35
| 40.6
| 79
| 0.688818
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|