Compare commits

..
4 changed files with 42 additions and 113 deletions

No files matched your search

@@ -1,8 +1,10 @@
import json
import os
from io import BytesIO
from pathlib import Path
from unittest.mock import patch
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import override_settings
from PIL import Image
@@ -507,6 +509,39 @@ class TestApiAppConfig(DirectoriesMixin, APITestCase):
self.assertEqual(stored_text, {})
def test_api_accepts_a_logo_too_large_to_hold_in_memory(self) -> None:
"""
GIVEN:
- A PNG logo larger than Django's in memory upload limit, which is
stored in a temporary file while it is received
WHEN:
- Uploaded via PATCH to app config
THEN:
- The upload is accepted and the stored logo is a valid image
"""
# Random pixels do not compress, so this is a few megabytes as a PNG
image = Image.frombytes("RGB", (1100, 1100), os.urandom(1100 * 1100 * 3))
logo = BytesIO()
image.save(logo, format="PNG")
assert logo.getbuffer().nbytes > settings.FILE_UPLOAD_MAX_MEMORY_SIZE
response = self.client.patch(
f"{self.ENDPOINT}1/",
{
"app_logo": SimpleUploadedFile(
name="large-logo.png",
content=logo.getvalue(),
content_type="image/png",
),
},
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
config = ApplicationConfiguration.objects.first()
assert config is not None
with Image.open(config.app_logo.path) as stored_logo:
self.assertEqual(stored_logo.size, (1100, 1100))
def test_api_accepts_valid_gif_logo(self) -> None:
"""
GIVEN:
@@ -1,99 +0,0 @@
import pytest
from pytest_mock import MockerFixture
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import Document
from documents.models import Tag
from paperless_testing.factories import DocumentFactory
from paperless_testing.factories import TagFactory
class TestBulkSelectionRejectsInvalidFilters:
@pytest.mark.parametrize(
"filters",
[{"created__year": "abc"}, {"correspondent__id": "abc"}],
)
def test_documents_are_not_selected(
self,
admin_client: APIClient,
mocker: MockerFixture,
filters: dict[str, str],
) -> None:
"""
GIVEN:
- Documents exist
WHEN:
- A bulk delete of all documents is requested with a filter that is invalid
THEN:
- The response is a 400 and nothing is queued, a filter that is dropped
would select every document
"""
DocumentFactory.create()
execute = mocker.patch("documents.views.execute_bulk_operation")
# A real id, so a request that is wrongly accepted fails the assertions
# below instead of failing to render a mock as JSON
execute.apply_async.return_value.id = "task-id"
response = admin_client.post(
"/api/documents/delete/",
{"all": True, "filters": filters},
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
execute.apply_async.assert_not_called()
assert Document.objects.count() == 1
def test_objects_are_not_selected(self, admin_client: APIClient) -> None:
"""
GIVEN:
- Tags exist
WHEN:
- A bulk delete of all tags is requested with a filter that is invalid
THEN:
- The response is a 400 and no tag is deleted
"""
TagFactory.create()
response = admin_client.post(
"/api/bulk_edit_objects/",
{
"object_type": "tags",
"operation": "delete",
"all": True,
"filters": {"id": "abc"},
},
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert Tag.objects.count() == 1
def test_a_valid_filter_still_selects_its_documents(
self,
admin_client: APIClient,
mocker: MockerFixture,
) -> None:
"""
GIVEN:
- Two documents
WHEN:
- A bulk delete of all documents is requested with a valid filter
THEN:
- Only the matching document is queued
"""
keep = DocumentFactory.create(title="keep")
DocumentFactory.create(title="other")
execute = mocker.patch("documents.views.execute_bulk_operation")
execute.apply_async.return_value.id = "task-id"
response = admin_client.post(
"/api/documents/delete/",
{"all": True, "filters": {"title__iexact": "keep"}},
format="json",
)
assert response.status_code == status.HTTP_200_OK
queued = execute.apply_async.call_args.kwargs["kwargs"]["document_ids"]
assert queued == [keep.pk]
+4 -13
View File
@@ -72,7 +72,6 @@ from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.http import condition
from django.views.generic import TemplateView
from django_filters.rest_framework import DjangoFilterBackend
from django_filters.utils import translate_validation
from drf_spectacular.openapi import AutoSchema
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter
@@ -3070,15 +3069,11 @@ class DocumentSelectionMixin:
root_document__isnull=True,
)
# orm-filtered docs
filterset = DocumentFilterSet(
filtered_documents = DocumentFilterSet(
data=orm_filters,
queryset=permitted_documents,
user=user,
)
# .qs silently drops an invalid filter, which would select every document
if not filterset.is_valid():
raise translate_validation(filterset.errors)
filtered_documents = filterset.qs.distinct()
).qs.distinct()
# tantivy-filtered docs (if search params provided)
search_filtered_ids = self._get_search_document_ids(
user=user,
@@ -5339,14 +5334,10 @@ class BulkEditObjectsView(PassUserMixin):
user_permitted_objects = object_class.objects.filter(
id__in=permitted_object_ids(user, object_class, perm_codename),
)
filterset = filterset_class(
objs = filterset_class(
data=filters,
queryset=user_permitted_objects,
)
# .qs silently drops an invalid filter, which would select every object
if not filterset.is_valid():
raise translate_validation(filterset.errors)
objs = filterset.qs
).qs
if object_type == "tags":
editable_ids = set(user_permitted_objects.values_list("pk", flat=True))
all_ids = set(objs.values_list("pk", flat=True))
+3 -1
View File
@@ -303,7 +303,9 @@ class ApplicationConfigurationSerializer(
return InMemoryUploadedFile(
file=data,
field_name=file.field_name,
# An upload past the in memory limit is a temporary file, which has no
# field name of its own
field_name="app_logo",
name=file.name,
content_type=file.content_type,
size=data.getbuffer().nbytes,