Compare commits

..
3 changed files with 125 additions and 113 deletions

No files matched your search

@@ -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]
@@ -0,0 +1,114 @@
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import Document
from paperless_testing.dirs import PaperlessDirs
from paperless_testing.factories import DocumentFactory
@pytest.fixture
def archived_document(paperless_dirs: PaperlessDirs) -> Document:
document = DocumentFactory.create(
title="title",
filename="source.pdf",
archive_filename="archived.pdf",
mime_type="application/pdf",
)
document.source_path.write_bytes(b"source")
document.archive_path.write_bytes(b"archive")
return document
class TestDownloadFollowFormatting:
@pytest.mark.parametrize("value", ["false", "0", "no", "off"])
def test_false_values_use_the_public_filename(
self,
admin_client: APIClient,
archived_document: Document,
value: str,
) -> None:
"""
GIVEN:
- A document whose name on disk differs from its public name
WHEN:
- It is downloaded with follow_formatting set to a false value
THEN:
- The public name is used, the string "false" is not true
"""
response = admin_client.get(
f"/api/documents/{archived_document.pk}/download/?follow_formatting={value}",
)
assert response.status_code == status.HTTP_200_OK
assert "title.pdf" in response["Content-Disposition"]
response.close()
@pytest.mark.parametrize("value", ["true", "True", "1", "yes", "on"])
def test_true_values_use_the_name_on_disk(
self,
admin_client: APIClient,
archived_document: Document,
value: str,
) -> None:
"""
GIVEN:
- A document whose name on disk differs from its public name
WHEN:
- It is downloaded with follow_formatting set to a true value
THEN:
- The name on disk is used
"""
response = admin_client.get(
f"/api/documents/{archived_document.pk}/download/?follow_formatting={value}",
)
assert "archived.pdf" in response["Content-Disposition"]
response.close()
def test_a_value_that_is_not_a_boolean_is_a_400(
self,
admin_client: APIClient,
archived_document: Document,
) -> None:
response = admin_client.get(
f"/api/documents/{archived_document.pk}/download/?follow_formatting=maybe",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
class TestDownloadFilenameControlCharacters:
def test_control_characters_do_not_fail_the_download(
self,
admin_client: APIClient,
paperless_dirs: PaperlessDirs,
) -> None:
"""
GIVEN:
- A document whose name on disk holds control characters, a title can
WHEN:
- It is downloaded following the name on disk
THEN:
- The download works and no control character is in the header
"""
document = DocumentFactory.create(
filename="source.pdf",
archive_filename="ar\r\nchi\x12ved.pdf",
mime_type="application/pdf",
)
document.source_path.write_bytes(b"source")
document.archive_path.parent.mkdir(parents=True, exist_ok=True)
document.archive_path.write_bytes(b"archive")
response = admin_client.get(
f"/api/documents/{document.pk}/download/?follow_formatting=true",
)
assert response.status_code == status.HTTP_200_OK
assert 'filename="archived.pdf"' in response["Content-Disposition"]
assert not any(
ord(char) < 32 or ord(char) == 127
for char in response["Content-Disposition"]
)
response.close()
+11 -14
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
@@ -1462,7 +1461,10 @@ class DocumentViewSet(
use_archive=not self.original_requested(request)
and file_doc.has_archive_version,
disposition=disposition,
follow_formatting=request.query_params.get("follow_formatting", False),
# The query value is a string, "false" must not count as true
follow_formatting=serializers.BooleanField(default=False).run_validation(
request.query_params.get("follow_formatting", serializers.empty),
),
)
def get_metadata(self, file, mime_type):
@@ -3070,15 +3072,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,
@@ -5277,6 +5275,9 @@ def serve_file(
.replace("\\", "_")
.replace('"', "_")
)
# A name can hold control characters, which a header cannot carry. The encoded
# form below percent encodes them, only this plain fallback needs them removed
filename_normalized = "".join(c for c in filename_normalized if c.isprintable())
filename_encoded = quote(filename)
content_disposition = (
f"{disposition}; "
@@ -5339,14 +5340,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))