mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-12-03 17:58:41 +00:00
* Fix: stop full document saves from writing file path columns A full save() of a Document instance loaded before another process moved its file wrote the old filename back. The DB then pointed at a path that no longer existed, and recovery only worked when the recomputed path happened to match the file's real location. Document.save() now leaves filename and archive_filename out of full saves on existing rows. Writers that own those columns opt in with write_file_paths=True or an explicit update_fields. A full save of a row deleted elsewhere now raises instead of re-inserting it. * Fix: make the global media lock reentrant within a thread Every caller built its own FileLock on media.lock, so code already holding it could not call into code that takes it again without blocking itself. That made it impossible to take media.lock before opening a transaction in paths that also attach files or move files inside that transaction. media_lock() hands out one FileLock instance per path with per-thread hold counts, so a thread re-enters while other threads and processes stay excluded. All media.lock call sites now use it. * Fix: extract document file moves out of the signal receiver The file move receiver refreshed the caller's own instance from the database, which wiped unsaved in-memory changes. It ran on every m2m_changed action including pre_add and pre_remove, wrote modified even when nothing moved, and its no-move branch skipped trashed documents. The move body now lives in documents.file_moves.move_files_for_document. It skips documents without a filename before taking media.lock, then takes the lock with a 300 second timeout, loads a fresh instance by pk, writes only when a filename column changes, and returns the instance. The receiver ignores reverse and pre_* m2m actions and copies just the final filename columns back onto the caller's instance. * Fix: collect document file moves per scope and move once on exit Each save of a document moved its files on the spot, so one logical change could move them several times, and moves could run inside another open transaction. defer_file_moves() opens a ContextVar-backed scope. Inside it, move requests are recorded and the outermost scope moves each document once on exit, or on commit if a transaction is still open. A failing move is logged and does not stop the others. Outside any scope moves stay immediate. * Fix: move document files once per request, after its writes commit A tag PATCH moved files from inside the tags.set() transaction while holding the document row lock. A concurrent save holding media.lock and waiting on that row deadlocked with it, and every later save on the instance queued behind media.lock until the webserver restarted. FileMoveMiddleware opens a file move scope around every request, in sync or async mode, so each changed document is moved once after the view returns and never while a transaction holds row locks. * Fix: move document files once per Celery task Tasks such as bulk_update_documents moved a document's files once for its manual post_save and again for every save its workflows made, each time taking the global media lock. All tasks now run through FileMoveScopedTask, which opens a file move scope around the task body, including when the task raises. bulk_update_documents flushes after each document so long bulk edits still make steady progress. * Fix: take media.lock before the archiver's transaction The archiver updated the document row inside a transaction and then waited on media.lock. A concurrent file move holding media.lock and updating the same row could deadlock with it, and the unique archive filename was generated outside the lock from an instance loaded before the parse. The archiver now acquires media.lock before opening its transaction, refreshes the document under the lock, and moves the archive and thumbnail inside that block, so it never waits on media.lock while holding the row. * Fix: take media.lock before emptying the trash Emptying the trash deleted documents inside Django's delete transaction, and the post_delete file cleanup waited on media.lock while the deleted rows were locked. A concurrent file move holding media.lock and updating one of those rows could deadlock with it. empty_trash now holds media.lock around the delete, so the cleanup handler re-enters the lock instead of waiting while rows are locked. * Fix: take media.lock before the consumer's storage transaction Consuming a new version locked the root document row with select_for_update and then waited on media.lock to place the file, the same lock ordering that let concurrent saves deadlock. On MariaDB even the version row's foreign key check holds a shared lock on the root. The consumer's storage phase now takes media.lock before opening its transaction and runs inside its own file move scope. File placement and workflow email actions inside the transaction re-enter the lock instead of waiting, and filename follow-ups run once after commit. * Fix: keep Celery's Django task base for file move scoped tasks Passing task_cls to Celery replaces the Django fixup's default DjangoTask, so FileMoveScopedTask, built on the plain Task, left every task without delay_on_commit. The workflow AI suggestions trigger failed with an AttributeError. FileMoveScopedTask now subclasses DjangoTask, which only needs django.db.transaction and is safe to import before apps load. The task scope test also asserts tasks are DjangoTask instances. * Fix: rename and retag documents one file move at a time document_renamer sent a fake post_save per document to trigger the move, and document_retagger moved a document once for each field it assigned. The renamer calls move_files_for_document directly for each document, so progress reflects real work. The retagger opens a file move scope per document, so each document is moved once after all of its assignments. * Fix: move files per document during scheduled workflow runs check_scheduled_workflows runs the workflow once per matched document inside the task-wide file move scope, so every rename it triggered was deferred to the end of the task. A long run killed by the Celery time limit would then discard all of the renames. The task now flushes the pending file moves after each document's workflow run and websocket notification, the same way bulk_update_documents does, so renames land document by document while the scope stays open. * Fix: place consumed files before running the post-consume script The consumer's storage phase opens its own file move scope, which nests under the consume task's scope. Moves requested while storing the document therefore stayed pending until the task ended, and the post-consume script could be handed a path from before the move. The consumer now flushes the pending file moves once after the storage block, outside the media lock and the transaction, and before the post-consume script runs. * Fix: skip the thread hop for async file move scopes with nothing to move adefer_file_moves hopped to a worker thread on every exit, even when no file move had been requested, which costs an executor round trip for most async requests. The collector is now closed on the event loop, which touches no database, and the flush only runs through sync_to_async when something was collected. The transaction check still happens inside the flush in the sync thread. The comment above the lock-free filename precheck in move_files_for_document now gives the real reason it uses values_list(): it keeps the check off Document.global_objects.filter(), which tests patch to inject database errors and observe the mover's writes. * Fix: return the post-move modified time from document updates Editing a document in a way that renames its file returned a response carrying the modified time from before the move. The deferred file move runs after the response is built and bumps modified, so the stored value was newer than the one the client received. The frontend then saw a newer server modified time and showed a spurious "document was updated" prompt whose reload discarded local edits. DocumentViewSet.update now flushes pending file moves right after saving and before reading the document back, so the response reflects the final filename and modified time. * Trimming and simpliciation * Fix: refresh the document after placing files, before the post-consume script * Fix: move documents when tags change through the reverse relation * Fix: move versions of trashed documents * Fix: rename only root documents in document_renamer * Improves test coverage even for the exception cases * Fix: move documents when a tag is cleared through the reverse relation * Fix: flush file moves before the scheduled workflow websocket notification * Fix: move files before the bulk update websocket notification * Fix: bump modified for documents changed by a bulk edit * Fix: defer unscoped file moves to commit inside a transaction * Fix: allow deferred file move callback in zone OCR reindex test * Fix: return 404 instead of 500 when a document is trashed during its own update DocumentViewSet.update saves the change and then re-reads the document through the default manager, which excludes soft deleted rows. A concurrent request that moved the document to the trash in between made that read raise DoesNotExist, so the client got a 500 for a document that no longer exists. Raise Http404 instead, the same answer get_object() gives when the document is already trashed at the start of the request. The committed change is kept. Found while hammering the API with concurrent PATCH and delete requests. * Fix: remove the superseded archive file when a reprocess changes its path Reprocessing a document writes the new archive to the path its current metadata generates and updates archive_filename, but never removed the file the old archive_filename pointed at. Normally both are the same path. They differ when a committed edit has not had its file move applied yet, which deferred file moves make a real window: the new archive lands at the new path and the old one stays on disk with no document referencing it. The deferred move then finds the archive already at its target and only moves the original. Delete the replaced archive, and its directory if that leaves it empty, once the new one is in place and only when the two paths differ. * Fix: keep the trash cleanup handler connected while any empty_trash call runs empty_trash connects cleanup_document_deletion to post_delete before deleting and disconnects it in a finally block. The signal is process wide and the trash endpoint calls empty_trash directly in the web process, so overlapping calls interfere. One caller finishing disconnects the handler while another is still waiting for media.lock; the waiter then hard deletes its documents with no handler attached and their files stay on disk, unreferenced. Hold the connection with a lock protected reference count, connecting for the first active caller and disconnecting after the last one finishes.
2368 lines
83 KiB
Python
2368 lines
83 KiB
Python
import shutil
|
|
from collections.abc import Callable
|
|
from datetime import date
|
|
from pathlib import Path
|
|
from unittest import mock
|
|
|
|
import pytest
|
|
from django.contrib.auth.models import Group
|
|
from django.contrib.auth.models import Permission
|
|
from django.contrib.auth.models import User
|
|
from django.db import connection
|
|
from django.test import TestCase
|
|
from django.test.utils import CaptureQueriesContext
|
|
from guardian.shortcuts import get_groups_with_perms
|
|
from guardian.shortcuts import get_users_with_perms
|
|
from pytest_mock import MockerFixture
|
|
|
|
from documents import bulk_edit
|
|
from documents.models import Correspondent
|
|
from documents.models import CustomField
|
|
from documents.models import CustomFieldInstance
|
|
from documents.models import Document
|
|
from documents.models import DocumentType
|
|
from documents.models import StoragePath
|
|
from documents.models import Tag
|
|
from documents.pdf_ops import PageSpec
|
|
from documents.permissions import PermissionsSpec
|
|
from documents.permissions import set_permissions_for_objects
|
|
from documents.zone_ocr import ZoneOcrReason
|
|
from documents.zone_ocr import ZoneOcrResult
|
|
from paperless_testing.dirs import DirectoriesMixin
|
|
from paperless_testing.factories import DocumentFactory
|
|
from paperless_testing.factories import OcrTemplateFactory
|
|
from paperless_testing.factories import UserFactory
|
|
from paperless_testing.permissions import grant_object
|
|
from paperless_testing.samples import MULTI_PAGE_DIGITAL_PDF
|
|
from paperless_testing.samples import SIMPLE_DIGITAL_PDF
|
|
from paperless_testing.samples import WITH_FORM_PDF
|
|
|
|
|
|
class TestBulkEdit(DirectoriesMixin, TestCase):
|
|
def setUp(self) -> None:
|
|
super().setUp()
|
|
|
|
self.owner = User.objects.create(username="test_owner")
|
|
self.user1 = User.objects.create(username="user1")
|
|
self.user2 = User.objects.create(username="user2")
|
|
self.group1 = Group.objects.create(name="group1")
|
|
self.group2 = Group.objects.create(name="group2")
|
|
|
|
patcher = mock.patch("documents.bulk_edit.bulk_update_documents.apply_async")
|
|
self.async_task = patcher.start()
|
|
self.addCleanup(patcher.stop)
|
|
self.c1 = Correspondent.objects.create(name="c1")
|
|
self.c2 = Correspondent.objects.create(name="c2")
|
|
self.dt1 = DocumentType.objects.create(name="dt1")
|
|
self.dt2 = DocumentType.objects.create(name="dt2")
|
|
self.t1 = Tag.objects.create(name="t1")
|
|
self.t2 = Tag.objects.create(name="t2")
|
|
self.doc1 = Document.objects.create(
|
|
checksum="A",
|
|
title="A",
|
|
created=date(2023, 1, 1),
|
|
)
|
|
self.doc2 = Document.objects.create(
|
|
checksum="B",
|
|
title="B",
|
|
correspondent=self.c1,
|
|
document_type=self.dt1,
|
|
created=date(2023, 1, 2),
|
|
)
|
|
self.doc3 = Document.objects.create(
|
|
checksum="C",
|
|
title="C",
|
|
correspondent=self.c2,
|
|
document_type=self.dt2,
|
|
created=date(2023, 1, 3),
|
|
)
|
|
self.doc4 = Document.objects.create(checksum="D", title="D")
|
|
self.doc5 = Document.objects.create(checksum="E", title="E")
|
|
self.doc2.tags.add(self.t1)
|
|
self.doc3.tags.add(self.t2)
|
|
self.doc4.tags.add(self.t1, self.t2)
|
|
self.sp1 = StoragePath.objects.create(name="sp1", path="Something/{checksum}")
|
|
|
|
def test_set_correspondent(self) -> None:
|
|
self.assertEqual(Document.objects.filter(correspondent=self.c2).count(), 1)
|
|
bulk_edit.set_correspondent(
|
|
[self.doc1.id, self.doc2.id, self.doc3.id],
|
|
self.c2.id,
|
|
)
|
|
self.assertEqual(Document.objects.filter(correspondent=self.c2).count(), 3)
|
|
self.async_task.assert_called_once()
|
|
kwargs = self.async_task.call_args.kwargs["kwargs"]
|
|
self.assertCountEqual(kwargs["document_ids"], [self.doc1.id, self.doc2.id])
|
|
|
|
def test_unset_correspondent(self) -> None:
|
|
self.assertEqual(Document.objects.filter(correspondent=self.c2).count(), 1)
|
|
bulk_edit.set_correspondent([self.doc1.id, self.doc2.id, self.doc3.id], None)
|
|
self.assertEqual(Document.objects.filter(correspondent=self.c2).count(), 0)
|
|
self.async_task.assert_called_once()
|
|
kwargs = self.async_task.call_args.kwargs["kwargs"]
|
|
self.assertCountEqual(kwargs["document_ids"], [self.doc2.id, self.doc3.id])
|
|
|
|
def test_set_document_type(self) -> None:
|
|
self.assertEqual(Document.objects.filter(document_type=self.dt2).count(), 1)
|
|
bulk_edit.set_document_type(
|
|
[self.doc1.id, self.doc2.id, self.doc3.id],
|
|
self.dt2.id,
|
|
)
|
|
self.assertEqual(Document.objects.filter(document_type=self.dt2).count(), 3)
|
|
self.async_task.assert_called_once()
|
|
kwargs = self.async_task.call_args.kwargs["kwargs"]
|
|
self.assertCountEqual(kwargs["document_ids"], [self.doc1.id, self.doc2.id])
|
|
|
|
def test_unset_document_type(self) -> None:
|
|
self.assertEqual(Document.objects.filter(document_type=self.dt2).count(), 1)
|
|
bulk_edit.set_document_type([self.doc1.id, self.doc2.id, self.doc3.id], None)
|
|
self.assertEqual(Document.objects.filter(document_type=self.dt2).count(), 0)
|
|
self.async_task.assert_called_once()
|
|
kwargs = self.async_task.call_args.kwargs["kwargs"]
|
|
self.assertCountEqual(kwargs["document_ids"], [self.doc2.id, self.doc3.id])
|
|
|
|
def test_set_document_storage_path(self) -> None:
|
|
"""
|
|
GIVEN:
|
|
- 5 documents without defined storage path
|
|
WHEN:
|
|
- Bulk edit called to add storage path to 1 document
|
|
THEN:
|
|
- Single document storage path update
|
|
"""
|
|
self.assertEqual(Document.objects.filter(storage_path=None).count(), 5)
|
|
|
|
bulk_edit.set_storage_path(
|
|
[self.doc1.id],
|
|
self.sp1.id,
|
|
)
|
|
|
|
self.assertEqual(Document.objects.filter(storage_path=None).count(), 4)
|
|
|
|
self.async_task.assert_called_once()
|
|
kwargs = self.async_task.call_args.kwargs["kwargs"]
|
|
|
|
self.assertCountEqual(kwargs["document_ids"], [self.doc1.id])
|
|
|
|
def test_unset_document_storage_path(self) -> None:
|
|
"""
|
|
GIVEN:
|
|
- 4 documents without defined storage path
|
|
- 1 document with a defined storage
|
|
WHEN:
|
|
- Bulk edit called to remove storage path from 1 document
|
|
THEN:
|
|
- Single document storage path removed
|
|
"""
|
|
self.assertEqual(Document.objects.filter(storage_path=None).count(), 5)
|
|
|
|
bulk_edit.set_storage_path(
|
|
[self.doc1.id],
|
|
self.sp1.id,
|
|
)
|
|
|
|
self.assertEqual(Document.objects.filter(storage_path=None).count(), 4)
|
|
|
|
bulk_edit.set_storage_path(
|
|
[self.doc1.id],
|
|
None,
|
|
)
|
|
|
|
self.assertEqual(Document.objects.filter(storage_path=None).count(), 5)
|
|
|
|
self.async_task.assert_called()
|
|
kwargs = self.async_task.call_args.kwargs["kwargs"]
|
|
|
|
self.assertCountEqual(kwargs["document_ids"], [self.doc1.id])
|
|
|
|
def test_add_tag(self) -> None:
|
|
self.assertEqual(Document.objects.filter(tags__id=self.t1.id).count(), 2)
|
|
bulk_edit.add_tag(
|
|
[self.doc1.id, self.doc2.id, self.doc3.id, self.doc4.id],
|
|
self.t1.id,
|
|
)
|
|
self.assertEqual(Document.objects.filter(tags__id=self.t1.id).count(), 4)
|
|
self.async_task.assert_called_once()
|
|
kwargs = self.async_task.call_args.kwargs["kwargs"]
|
|
self.assertCountEqual(kwargs["document_ids"], [self.doc1.id, self.doc3.id])
|
|
|
|
def test_remove_tag(self) -> None:
|
|
self.assertEqual(Document.objects.filter(tags__id=self.t1.id).count(), 2)
|
|
bulk_edit.remove_tag([self.doc1.id, self.doc3.id, self.doc4.id], self.t1.id)
|
|
self.assertEqual(Document.objects.filter(tags__id=self.t1.id).count(), 1)
|
|
self.async_task.assert_called_once()
|
|
kwargs = self.async_task.call_args.kwargs["kwargs"]
|
|
self.assertCountEqual(kwargs["document_ids"], [self.doc4.id])
|
|
|
|
def test_modify_tags(self) -> None:
|
|
tag_unrelated = Tag.objects.create(name="unrelated")
|
|
self.doc2.tags.add(tag_unrelated)
|
|
self.doc3.tags.add(tag_unrelated)
|
|
bulk_edit.modify_tags(
|
|
[self.doc2.id, self.doc3.id],
|
|
add_tags=[self.t2.id],
|
|
remove_tags=[self.t1.id],
|
|
)
|
|
|
|
self.assertCountEqual(list(self.doc2.tags.all()), [self.t2, tag_unrelated])
|
|
self.assertCountEqual(list(self.doc3.tags.all()), [self.t2, tag_unrelated])
|
|
|
|
self.async_task.assert_called_once()
|
|
kwargs = self.async_task.call_args.kwargs["kwargs"]
|
|
# TODO: doc3 should not be affected, but the query for that is rather complicated
|
|
self.assertCountEqual(kwargs["document_ids"], [self.doc2.id, self.doc3.id])
|
|
|
|
def test_modify_custom_fields(self) -> None:
|
|
"""
|
|
GIVEN:
|
|
- 2 documents with custom fields
|
|
- 3 custom fields
|
|
WHEN:
|
|
- Custom fields are modified using old format (list of ids)
|
|
THEN:
|
|
- Custom fields are modified for the documents
|
|
"""
|
|
cf = CustomField.objects.create(
|
|
name="cf1",
|
|
data_type=CustomField.FieldDataType.STRING,
|
|
)
|
|
cf2 = CustomField.objects.create(
|
|
name="cf2",
|
|
data_type=CustomField.FieldDataType.INT,
|
|
)
|
|
cf3 = CustomField.objects.create(
|
|
name="cf3",
|
|
data_type=CustomField.FieldDataType.STRING,
|
|
)
|
|
CustomFieldInstance.objects.create(
|
|
document=self.doc1,
|
|
field=cf,
|
|
)
|
|
CustomFieldInstance.objects.create(
|
|
document=self.doc2,
|
|
field=cf,
|
|
)
|
|
CustomFieldInstance.objects.create(
|
|
document=self.doc2,
|
|
field=cf3,
|
|
)
|
|
bulk_edit.modify_custom_fields(
|
|
[self.doc1.id, self.doc2.id],
|
|
add_custom_fields=[cf2.id],
|
|
remove_custom_fields=[cf.id],
|
|
)
|
|
|
|
self.doc1.refresh_from_db()
|
|
self.doc2.refresh_from_db()
|
|
|
|
self.assertEqual(
|
|
self.doc1.custom_fields.count(),
|
|
1,
|
|
)
|
|
self.assertEqual(
|
|
self.doc2.custom_fields.count(),
|
|
2,
|
|
)
|
|
|
|
self.async_task.assert_called_once()
|
|
kwargs = self.async_task.call_args.kwargs["kwargs"]
|
|
self.assertCountEqual(kwargs["document_ids"], [self.doc1.id, self.doc2.id])
|
|
|
|
def test_modify_custom_fields_with_values(self) -> None:
|
|
"""
|
|
GIVEN:
|
|
- 2 documents with custom fields
|
|
- 3 custom fields
|
|
WHEN:
|
|
- Custom fields are modified using new format (dict)
|
|
THEN:
|
|
- Custom fields are modified for the documents
|
|
"""
|
|
cf = CustomField.objects.create(
|
|
name="cf",
|
|
data_type=CustomField.FieldDataType.STRING,
|
|
)
|
|
cf1 = CustomField.objects.create(
|
|
name="cf1",
|
|
data_type=CustomField.FieldDataType.STRING,
|
|
)
|
|
cf2 = CustomField.objects.create(
|
|
name="cf2",
|
|
data_type=CustomField.FieldDataType.MONETARY,
|
|
)
|
|
cf3 = CustomField.objects.create(
|
|
name="cf3",
|
|
data_type=CustomField.FieldDataType.DOCUMENTLINK,
|
|
)
|
|
CustomFieldInstance.objects.create(
|
|
document=self.doc2,
|
|
field=cf,
|
|
)
|
|
CustomFieldInstance.objects.create(
|
|
document=self.doc2,
|
|
field=cf1,
|
|
)
|
|
CustomFieldInstance.objects.create(
|
|
document=self.doc2,
|
|
field=cf3,
|
|
)
|
|
bulk_edit.modify_custom_fields(
|
|
[self.doc1.id, self.doc2.id],
|
|
add_custom_fields={cf2.id: None, cf3.id: [self.doc3.id]},
|
|
remove_custom_fields=[cf.id],
|
|
)
|
|
|
|
self.doc1.refresh_from_db()
|
|
self.doc2.refresh_from_db()
|
|
|
|
self.assertEqual(
|
|
self.doc1.custom_fields.count(),
|
|
2,
|
|
)
|
|
self.assertEqual(
|
|
self.doc1.custom_fields.get(field=cf2).value,
|
|
None,
|
|
)
|
|
self.assertEqual(
|
|
self.doc1.custom_fields.get(field=cf3).value,
|
|
[self.doc3.id],
|
|
)
|
|
self.assertEqual(
|
|
self.doc2.custom_fields.count(),
|
|
3,
|
|
)
|
|
self.assertEqual(
|
|
self.doc2.custom_fields.get(field=cf3).value,
|
|
[self.doc3.id],
|
|
)
|
|
# assert reflect document link
|
|
_cf_1 = self.doc3.custom_fields.first()
|
|
assert _cf_1 is not None
|
|
self.assertEqual(
|
|
_cf_1.value,
|
|
[self.doc2.id, self.doc1.id],
|
|
)
|
|
|
|
self.async_task.assert_called_once()
|
|
kwargs = self.async_task.call_args.kwargs["kwargs"]
|
|
self.assertCountEqual(kwargs["document_ids"], [self.doc1.id, self.doc2.id])
|
|
|
|
# removal of document link cf, should also remove symmetric link
|
|
bulk_edit.modify_custom_fields(
|
|
[self.doc3.id],
|
|
add_custom_fields={},
|
|
remove_custom_fields=[cf3.id],
|
|
)
|
|
_cf_2 = self.doc1.custom_fields.filter(field=cf3).first()
|
|
assert _cf_2 is not None
|
|
self.assertNotIn(self.doc3.id, _cf_2.value)
|
|
_cf_3 = self.doc2.custom_fields.filter(field=cf3).first()
|
|
assert _cf_3 is not None
|
|
self.assertNotIn(self.doc3.id, _cf_3.value)
|
|
|
|
def test_modify_custom_fields_doclink_self_link(self) -> None:
|
|
"""
|
|
GIVEN:
|
|
- 2 existing documents
|
|
- Existing doc link custom field
|
|
WHEN:
|
|
- Doc link field is modified to include self link
|
|
THEN:
|
|
- Self link should not be created
|
|
"""
|
|
cf = CustomField.objects.create(
|
|
name="cf",
|
|
data_type=CustomField.FieldDataType.DOCUMENTLINK,
|
|
)
|
|
bulk_edit.modify_custom_fields(
|
|
[self.doc1.id, self.doc2.id],
|
|
add_custom_fields={cf.id: [self.doc1.id]},
|
|
remove_custom_fields=[],
|
|
)
|
|
|
|
_cf_4 = self.doc1.custom_fields.first()
|
|
assert _cf_4 is not None
|
|
self.assertEqual(_cf_4.value, [self.doc2.id])
|
|
_cf_5 = self.doc2.custom_fields.first()
|
|
assert _cf_5 is not None
|
|
self.assertEqual(_cf_5.value, [self.doc1.id])
|
|
|
|
def test_delete(self) -> None:
|
|
self.assertEqual(Document.objects.count(), 5)
|
|
bulk_edit.delete([self.doc1.id, self.doc2.id])
|
|
self.assertEqual(Document.objects.count(), 3)
|
|
self.assertCountEqual(
|
|
[doc.id for doc in Document.objects.all()],
|
|
[self.doc3.id, self.doc4.id, self.doc5.id],
|
|
)
|
|
|
|
def test_delete_root_document_deletes_all_versions(self) -> None:
|
|
version = Document.objects.create(
|
|
checksum="A-v1",
|
|
title="A version",
|
|
root_document=self.doc1,
|
|
)
|
|
|
|
bulk_edit.delete([self.doc1.id])
|
|
|
|
self.assertFalse(Document.objects.filter(id=self.doc1.id).exists())
|
|
self.assertFalse(Document.objects.filter(id=version.id).exists())
|
|
|
|
Document.deleted_objects.get(id=self.doc1.id).restore(strict=False)
|
|
|
|
self.assertTrue(Document.objects.filter(id=self.doc1.id).exists())
|
|
self.assertTrue(Document.objects.filter(id=version.id).exists())
|
|
|
|
def test_delete_version_document_keeps_root(self) -> None:
|
|
version = Document.objects.create(
|
|
checksum="A-v1",
|
|
title="A version",
|
|
root_document=self.doc1,
|
|
)
|
|
|
|
bulk_edit.delete([version.id])
|
|
|
|
self.assertTrue(Document.objects.filter(id=self.doc1.id).exists())
|
|
self.assertFalse(Document.objects.filter(id=version.id).exists())
|
|
|
|
def test_resolve_root_and_source_doc_latest_version_prefers_newest_version(
|
|
self,
|
|
) -> None:
|
|
version1 = Document.objects.create(
|
|
checksum="B-v1",
|
|
title="B version 1",
|
|
root_document=self.doc2,
|
|
)
|
|
version2 = Document.objects.create(
|
|
checksum="B-v2",
|
|
title="B version 2",
|
|
root_document=self.doc2,
|
|
)
|
|
|
|
root_doc, source_doc = bulk_edit._resolve_root_and_source_doc(
|
|
self.doc2,
|
|
source_mode="latest_version",
|
|
)
|
|
|
|
self.assertEqual(root_doc.id, self.doc2.id)
|
|
self.assertEqual(source_doc.id, version2.id)
|
|
self.assertNotEqual(source_doc.id, version1.id)
|
|
|
|
@mock.patch("documents.tasks.bulk_update_documents.apply_async")
|
|
def test_set_permissions(self, m) -> None:
|
|
doc_ids = [self.doc1.id, self.doc2.id, self.doc3.id]
|
|
|
|
grant_object(self.group1, self.doc1, "view_document")
|
|
|
|
permissions: PermissionsSpec = {
|
|
"view": {
|
|
"users": [self.user1.id, self.user2.id],
|
|
"groups": [self.group2.id],
|
|
},
|
|
"change": {
|
|
"users": [self.user1.id],
|
|
"groups": [self.group2.id],
|
|
},
|
|
}
|
|
|
|
bulk_edit.set_permissions(
|
|
doc_ids,
|
|
set_permissions=permissions,
|
|
owner=self.owner,
|
|
merge=False,
|
|
)
|
|
m.assert_called_once()
|
|
|
|
self.assertEqual(Document.objects.filter(owner=self.owner).count(), 3)
|
|
self.assertEqual(Document.objects.filter(id__in=doc_ids).count(), 3)
|
|
|
|
users_with_perms = get_users_with_perms(
|
|
self.doc1,
|
|
)
|
|
self.assertEqual(users_with_perms.count(), 2)
|
|
|
|
# group1 should be replaced by group2
|
|
groups_with_perms = get_groups_with_perms(
|
|
self.doc1,
|
|
)
|
|
self.assertEqual(groups_with_perms.count(), 1)
|
|
|
|
@mock.patch("documents.tasks.bulk_update_documents.apply_async")
|
|
def test_set_permissions_merge(self, m) -> None:
|
|
doc_ids = [self.doc1.id, self.doc2.id, self.doc3.id]
|
|
|
|
self.doc1.owner = self.user1
|
|
self.doc1.save()
|
|
|
|
grant_object(self.user1, self.doc1, "view_document")
|
|
grant_object(self.group1, self.doc1, "view_document")
|
|
|
|
permissions: PermissionsSpec = {
|
|
"view": {
|
|
"users": [self.user2.id],
|
|
"groups": [self.group2.id],
|
|
},
|
|
"change": {
|
|
"users": [self.user2.id],
|
|
"groups": [self.group2.id],
|
|
},
|
|
}
|
|
bulk_edit.set_permissions(
|
|
doc_ids,
|
|
set_permissions=permissions,
|
|
owner=self.owner,
|
|
merge=True,
|
|
)
|
|
m.assert_called_once()
|
|
|
|
# when merge is true owner doesn't get replaced if its not empty
|
|
self.assertEqual(Document.objects.filter(owner=self.owner).count(), 2)
|
|
self.assertEqual(Document.objects.filter(id__in=doc_ids).count(), 3)
|
|
|
|
# merge of user1 which was pre-existing and user2
|
|
users_with_perms = get_users_with_perms(
|
|
self.doc1,
|
|
)
|
|
self.assertEqual(users_with_perms.count(), 2)
|
|
|
|
# group1 should be merged by group2
|
|
groups_with_perms = get_groups_with_perms(
|
|
self.doc1,
|
|
)
|
|
self.assertEqual(groups_with_perms.count(), 2)
|
|
|
|
@mock.patch("documents.tasks.bulk_update_documents.apply_async")
|
|
def test_set_permissions_batched_across_document_count(
|
|
self,
|
|
m,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Many documents are being bulk-edited to set permissions at once
|
|
WHEN:
|
|
- set_permissions runs over a small batch vs. a much larger one
|
|
THEN:
|
|
- Permissions are applied correctly at both scales
|
|
- Query count does not grow with the number of documents, i.e.
|
|
each user/group is applied across all documents with one
|
|
batched call rather than one call per (document, identity)
|
|
pair
|
|
"""
|
|
permissions: PermissionsSpec = {
|
|
"view": {
|
|
"users": [self.user1.id, self.user2.id],
|
|
"groups": [self.group2.id],
|
|
},
|
|
"change": {
|
|
"users": [self.user1.id],
|
|
"groups": [self.group2.id],
|
|
},
|
|
}
|
|
|
|
def run_with_n_documents(n: int) -> int:
|
|
docs = [
|
|
Document.objects.create(checksum=f"perm-{n}-{i}", title=f"perm-{n}-{i}")
|
|
for i in range(n)
|
|
]
|
|
with CaptureQueriesContext(connection) as ctx:
|
|
bulk_edit.set_permissions(
|
|
[doc.id for doc in docs],
|
|
set_permissions=permissions,
|
|
owner=self.owner,
|
|
merge=False,
|
|
)
|
|
for doc in docs:
|
|
self.assertEqual(get_users_with_perms(doc).count(), 2)
|
|
self.assertEqual(get_groups_with_perms(doc).count(), 1)
|
|
return len(ctx.captured_queries)
|
|
|
|
small_batch_queries = run_with_n_documents(5)
|
|
large_batch_queries = run_with_n_documents(50)
|
|
|
|
# A tolerance rather than equality, matching the N+1 check in
|
|
# test_views.py: bulk_create's batch_size caps rows per INSERT, so a
|
|
# large enough selection does legitimately add statements, and the
|
|
# per-process ContentType cache makes the first run carry an extra
|
|
# query. Neither can hide a regression to per-document assignment,
|
|
# which would be ~10x the small-batch count here.
|
|
self.assertLessEqual(
|
|
large_batch_queries,
|
|
small_batch_queries + 5,
|
|
"Permission assignment appears to scale with document count: "
|
|
f"{small_batch_queries} queries for 5 documents vs. "
|
|
f"{large_batch_queries} for 50",
|
|
)
|
|
|
|
@mock.patch("documents.tasks.bulk_update_documents.apply_async")
|
|
def test_set_permissions_grants_direct_perm_even_if_already_granted_via_group(
|
|
self,
|
|
m,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- A user already has view access to a document via group
|
|
membership, with no direct grant of their own
|
|
WHEN:
|
|
- set_permissions explicitly grants that same user direct view
|
|
access via bulk_edit
|
|
THEN:
|
|
- A direct permission grant is created for the user, not skipped
|
|
because they already have equivalent access via the group
|
|
|
|
Regression test: guardian's queryset-aware assign_perm() (routed to
|
|
when the target is a list/queryset) skips creating a direct row for
|
|
anyone whose ObjectPermissionChecker.has_perm() already returns True
|
|
-- which includes group-derived access. The single-object assign_perm
|
|
this bulk path replaces has no such check; it always ensures a
|
|
direct row via get_or_create. Losing that guarantee would mean
|
|
revoking the group's grant later silently strips access that was
|
|
supposed to be explicit.
|
|
"""
|
|
self.doc1.owner = self.user1
|
|
self.doc1.save()
|
|
self.user1.groups.add(self.group1)
|
|
grant_object(self.group1, self.doc1, "view_document")
|
|
|
|
bulk_edit.set_permissions(
|
|
[self.doc1.id],
|
|
set_permissions={
|
|
"view": {"users": [self.user1.id], "groups": []},
|
|
},
|
|
merge=True,
|
|
)
|
|
|
|
direct_users = get_users_with_perms(
|
|
self.doc1,
|
|
only_with_perms_in=["view_document"],
|
|
with_group_users=False,
|
|
)
|
|
self.assertIn(self.user1, direct_users)
|
|
|
|
def test_set_permissions_for_objects_raises_for_unknown_action(self) -> None:
|
|
"""
|
|
GIVEN:
|
|
- An unrecognized permission action name with users to grant it
|
|
to
|
|
WHEN:
|
|
- set_permissions_for_objects is called
|
|
THEN:
|
|
- Permission.DoesNotExist is raised, not a silent no-op
|
|
|
|
The API rejects unknown action names before they get here, but a
|
|
direct caller could still pass one. Resolving the Permission via a
|
|
bare `.filter()` (which returns empty instead of raising) would
|
|
silently drop the grant and report success.
|
|
"""
|
|
with self.assertRaises(Permission.DoesNotExist):
|
|
set_permissions_for_objects(
|
|
{"not_a_real_action": {"users": [self.user1.id], "groups": []}}, # type: ignore[bad-assignment]
|
|
Document,
|
|
[self.doc1.pk],
|
|
)
|
|
|
|
def test_set_permissions_for_objects_unknown_action_applies_nothing(
|
|
self,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- A permissions dict with a valid action ordered ahead of an
|
|
unrecognized one
|
|
WHEN:
|
|
- set_permissions_for_objects is called
|
|
THEN:
|
|
- Permission.DoesNotExist is raised
|
|
- The valid action ahead of it is not applied either
|
|
|
|
Every action is resolved before any row is written, so a bad action
|
|
name cannot leave a half-applied change behind. That matters because
|
|
BulkEditObjectsView turns this exception into a 400: without the
|
|
up-front resolution the client would be told the request failed
|
|
while the leading action had already been committed.
|
|
"""
|
|
with self.assertRaises(Permission.DoesNotExist):
|
|
set_permissions_for_objects(
|
|
{
|
|
"view": {"users": [self.user1.id], "groups": []},
|
|
"not_a_real_action": {"users": [self.user1.id], "groups": []}, # type: ignore[bad-assignment]
|
|
},
|
|
Document,
|
|
[self.doc1.pk],
|
|
)
|
|
|
|
self.assertNotIn(
|
|
self.user1,
|
|
get_users_with_perms(
|
|
self.doc1,
|
|
only_with_perms_in=["view_document"],
|
|
with_group_users=False,
|
|
),
|
|
)
|
|
|
|
@mock.patch("documents.models.Document.delete")
|
|
def test_delete_documents_old_uuid_field(self, m) -> None:
|
|
m.side_effect = Exception("Data too long for column 'transaction_id' at row 1")
|
|
doc_ids = [self.doc1.id, self.doc2.id, self.doc3.id]
|
|
with self.assertLogs(level="WARNING") as cm:
|
|
with self.assertRaisesRegex(Exception, "Data too long for column"):
|
|
bulk_edit.delete(doc_ids)
|
|
self.assertIn("possible incompatible database column", cm.output[0])
|
|
|
|
|
|
class TestPDFActions(DirectoriesMixin, TestCase):
|
|
def setUp(self) -> None:
|
|
super().setUp()
|
|
sample1 = self.dirs.scratch_dir / "sample.pdf"
|
|
shutil.copy(
|
|
SIMPLE_DIGITAL_PDF,
|
|
sample1,
|
|
)
|
|
sample1_archive = self.dirs.archive_dir / "sample_archive.pdf"
|
|
shutil.copy(
|
|
SIMPLE_DIGITAL_PDF,
|
|
sample1_archive,
|
|
)
|
|
sample2 = self.dirs.scratch_dir / "sample2.pdf"
|
|
shutil.copy(
|
|
MULTI_PAGE_DIGITAL_PDF,
|
|
sample2,
|
|
)
|
|
sample2_archive = self.dirs.archive_dir / "sample2_archive.pdf"
|
|
shutil.copy(
|
|
MULTI_PAGE_DIGITAL_PDF,
|
|
sample2_archive,
|
|
)
|
|
sample3 = self.dirs.scratch_dir / "sample3.pdf"
|
|
shutil.copy(
|
|
WITH_FORM_PDF,
|
|
sample3,
|
|
)
|
|
self.doc1 = Document.objects.create(
|
|
checksum="A",
|
|
title="A",
|
|
filename=sample1,
|
|
mime_type="application/pdf",
|
|
)
|
|
self.doc1.archive_filename = sample1_archive
|
|
self.doc1.save(write_file_paths=True)
|
|
self.doc2 = Document.objects.create(
|
|
checksum="B",
|
|
title="B",
|
|
filename=sample2,
|
|
mime_type="application/pdf",
|
|
page_count=8,
|
|
created=date(2023, 1, 2),
|
|
)
|
|
self.doc2.archive_filename = sample2_archive
|
|
self.doc2.save(write_file_paths=True)
|
|
self.doc3 = Document.objects.create(
|
|
checksum="C",
|
|
title="C",
|
|
filename=sample3,
|
|
mime_type="application/pdf",
|
|
)
|
|
img_doc = self.dirs.scratch_dir / "sample_image.jpg"
|
|
shutil.copy(
|
|
Path(__file__).parent / "samples" / "simple.jpg",
|
|
img_doc,
|
|
)
|
|
img_doc_archive = self.dirs.archive_dir / "sample_image.pdf"
|
|
shutil.copy(
|
|
SIMPLE_DIGITAL_PDF,
|
|
img_doc_archive,
|
|
)
|
|
self.img_doc = Document.objects.create(
|
|
checksum="D",
|
|
title="D",
|
|
filename=img_doc,
|
|
mime_type="image/jpeg",
|
|
created=date(2023, 1, 3),
|
|
)
|
|
self.img_doc.archive_filename = img_doc_archive
|
|
self.img_doc.save(write_file_paths=True)
|
|
|
|
@staticmethod
|
|
def fake_decrypt(
|
|
src: Path,
|
|
make_dst: Callable[[], Path],
|
|
password: str,
|
|
) -> Path:
|
|
dst = make_dst()
|
|
dst.write_bytes(b"password removed")
|
|
return dst
|
|
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_merge(self, mock_consume_file) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Merge action is called with 3 documents
|
|
THEN:
|
|
- Consume file should be called
|
|
"""
|
|
doc_ids = [self.doc1.id, self.doc2.id, self.doc3.id]
|
|
metadata_document_id = self.doc2.id
|
|
user = User.objects.create(username="test_user")
|
|
|
|
result = bulk_edit.merge(
|
|
doc_ids,
|
|
metadata_document_id=None,
|
|
delete_originals=False,
|
|
user=user,
|
|
)
|
|
|
|
expected_filename = (
|
|
f"{'_'.join([str(doc_id) for doc_id in doc_ids])[:100]}_merged.pdf"
|
|
)
|
|
|
|
mock_consume_file.assert_called()
|
|
call_kwargs = mock_consume_file.call_args.kwargs
|
|
self.assertEqual(
|
|
Path(call_kwargs["input_doc"].original_file).name,
|
|
expected_filename,
|
|
)
|
|
self.assertEqual(call_kwargs["overrides"].title, None)
|
|
# No metadata_document_id, delete_originals False, so ASN should be None
|
|
self.assertIsNone(call_kwargs["overrides"].asn)
|
|
|
|
# With metadata_document_id overrides
|
|
result = bulk_edit.merge(doc_ids, metadata_document_id=metadata_document_id)
|
|
call_kwargs = mock_consume_file.call_args.kwargs
|
|
self.assertEqual(call_kwargs["overrides"].title, "B (merged)")
|
|
self.assertEqual(call_kwargs["overrides"].created, self.doc2.created)
|
|
|
|
self.assertEqual(result, "OK")
|
|
|
|
@mock.patch("documents.pdf_ops.PdfMerger")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_merge_uses_latest_version_source_for_root_selection(
|
|
self,
|
|
mock_consume_file,
|
|
mock_merger,
|
|
) -> None:
|
|
version_file = self.dirs.scratch_dir / "sample2_version_merge.pdf"
|
|
shutil.copy(self.doc2.source_path, version_file)
|
|
version = Document.objects.create(
|
|
checksum="B-v1",
|
|
title="B version 1",
|
|
root_document=self.doc2,
|
|
filename=version_file,
|
|
mime_type="application/pdf",
|
|
)
|
|
merger = mock_merger.return_value.__enter__.return_value
|
|
merger.save.side_effect = lambda dst: shutil.copy(version.source_path, dst)
|
|
|
|
result = bulk_edit.merge([self.doc2.id])
|
|
|
|
self.assertEqual(result, "OK")
|
|
merger.add.assert_called_once_with(version.source_path)
|
|
mock_consume_file.assert_called_once()
|
|
|
|
@mock.patch("documents.bulk_edit.delete.si")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_merge_and_delete_originals(
|
|
self,
|
|
mock_consume_file,
|
|
mock_delete_documents,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Merge action with deleting documents is called with 3 documents
|
|
THEN:
|
|
- Consume file task should be called
|
|
- Document deletion task should be called
|
|
"""
|
|
doc_ids = [self.doc1.id, self.doc2.id, self.doc3.id]
|
|
self.doc1.archive_serial_number = 101
|
|
self.doc2.archive_serial_number = 102
|
|
self.doc3.archive_serial_number = 103
|
|
self.doc1.save()
|
|
self.doc2.save()
|
|
self.doc3.save()
|
|
|
|
result = bulk_edit.merge(doc_ids, delete_originals=True)
|
|
self.assertEqual(result, "OK")
|
|
|
|
expected_filename = (
|
|
f"{'_'.join([str(doc_id) for doc_id in doc_ids])[:100]}_merged.pdf"
|
|
)
|
|
|
|
mock_consume_file.assert_called()
|
|
mock_delete_documents.assert_called()
|
|
mock_consume_file.return_value.set.return_value.apply_async.assert_called_once()
|
|
|
|
call_kwargs = mock_consume_file.call_args.kwargs
|
|
self.assertEqual(
|
|
Path(call_kwargs["input_doc"].original_file).name,
|
|
expected_filename,
|
|
)
|
|
self.assertEqual(call_kwargs["overrides"].title, None)
|
|
self.assertEqual(call_kwargs["overrides"].asn, 101)
|
|
|
|
delete_documents_args, _ = mock_delete_documents.call_args
|
|
self.assertEqual(
|
|
delete_documents_args[0],
|
|
doc_ids,
|
|
)
|
|
|
|
self.doc1.refresh_from_db()
|
|
self.doc2.refresh_from_db()
|
|
self.doc3.refresh_from_db()
|
|
self.assertIsNone(self.doc1.archive_serial_number)
|
|
self.assertIsNone(self.doc2.archive_serial_number)
|
|
self.assertIsNone(self.doc3.archive_serial_number)
|
|
|
|
@mock.patch("documents.bulk_edit.delete.si")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_merge_and_delete_originals_restore_on_failure(
|
|
self,
|
|
mock_consume_file,
|
|
mock_delete_documents,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Merge action with deleting documents is called with 1 document
|
|
- Error occurs when queuing consume file task
|
|
THEN:
|
|
- Archive serial numbers are restored
|
|
"""
|
|
doc_ids = [self.doc1.id]
|
|
self.doc1.archive_serial_number = 111
|
|
self.doc1.save()
|
|
sig = mock.Mock()
|
|
sig.set.return_value.apply_async.side_effect = Exception("boom")
|
|
mock_consume_file.return_value = sig
|
|
|
|
with self.assertRaises(Exception):
|
|
bulk_edit.merge(doc_ids, delete_originals=True)
|
|
|
|
self.doc1.refresh_from_db()
|
|
self.assertEqual(self.doc1.archive_serial_number, 111)
|
|
|
|
@mock.patch("documents.bulk_edit.delete.si")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_merge_and_delete_originals_metadata_handoff(
|
|
self,
|
|
mock_consume_file,
|
|
mock_delete_documents,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents with ASNs
|
|
WHEN:
|
|
- Merge with delete_originals=True and metadata_document_id set
|
|
THEN:
|
|
- Handoff ASN uses metadata document ASN
|
|
"""
|
|
doc_ids = [self.doc1.id, self.doc2.id]
|
|
self.doc1.archive_serial_number = 101
|
|
self.doc2.archive_serial_number = 202
|
|
self.doc1.save()
|
|
self.doc2.save()
|
|
|
|
result = bulk_edit.merge(
|
|
doc_ids,
|
|
metadata_document_id=self.doc2.id,
|
|
delete_originals=True,
|
|
)
|
|
self.assertEqual(result, "OK")
|
|
|
|
self.assertEqual(mock_consume_file.call_args.kwargs["overrides"].asn, 202)
|
|
|
|
def test_restore_archive_serial_numbers_task(self) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing document with no archive serial number
|
|
WHEN:
|
|
- Restore archive serial number task is called with backup data
|
|
THEN:
|
|
- Document archive serial number is restored
|
|
"""
|
|
self.doc1.archive_serial_number = 444
|
|
self.doc1.save()
|
|
Document.objects.filter(pk=self.doc1.id).update(archive_serial_number=None)
|
|
|
|
backup: dict[int, int | None] = {self.doc1.id: 444}
|
|
bulk_edit.restore_archive_serial_numbers_task(backup)
|
|
|
|
self.doc1.refresh_from_db()
|
|
self.assertEqual(self.doc1.archive_serial_number, 444)
|
|
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_merge_with_archive_fallback(self, mock_consume_file) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Merge action is called with 2 documents, one of which is an image and archive_fallback is set to True
|
|
THEN:
|
|
- Image document should be included
|
|
"""
|
|
doc_ids = [self.doc2.id, self.img_doc.id]
|
|
|
|
result = bulk_edit.merge(doc_ids, archive_fallback=True)
|
|
self.assertEqual(result, "OK")
|
|
|
|
expected_filename = (
|
|
f"{'_'.join([str(doc_id) for doc_id in doc_ids])[:100]}_merged.pdf"
|
|
)
|
|
|
|
mock_consume_file.assert_called()
|
|
self.assertEqual(
|
|
Path(mock_consume_file.call_args.kwargs["input_doc"].original_file).name,
|
|
expected_filename,
|
|
)
|
|
|
|
@mock.patch("documents.tasks.consume_file.delay")
|
|
@mock.patch("documents.pdf_ops.PdfMerger.add")
|
|
def test_merge_with_errors(self, mock_add, mock_consume_file) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Merge action is called with 2 documents
|
|
- Error occurs when adding both files
|
|
THEN:
|
|
- Consume file should not be called
|
|
"""
|
|
mock_add.side_effect = Exception("Error opening PDF")
|
|
doc_ids = [self.doc2.id, self.doc3.id]
|
|
|
|
with self.assertLogs("paperless.bulk_edit", level="ERROR") as cm:
|
|
bulk_edit.merge(doc_ids)
|
|
error_str = cm.output[0]
|
|
expected_str = (
|
|
"Error merging document 2, it will not be included in the merge"
|
|
)
|
|
self.assertIn(expected_str, error_str)
|
|
|
|
mock_consume_file.assert_not_called()
|
|
|
|
@mock.patch("documents.bulk_edit.group")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_split(self, mock_consume_file, mock_group) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Split action is called with 1 document and 2 pages
|
|
THEN:
|
|
- Consume file should be called twice
|
|
"""
|
|
doc_ids = [self.doc2.id]
|
|
pages = [[1, 2], [3]]
|
|
user = User.objects.create(username="test_user")
|
|
result = bulk_edit.split(doc_ids, pages, delete_originals=False, user=user)
|
|
self.assertEqual(mock_consume_file.call_count, 2)
|
|
self.assertEqual(
|
|
mock_consume_file.call_args.kwargs["overrides"].title,
|
|
"B (split 2)",
|
|
)
|
|
self.assertIsNone(mock_consume_file.call_args.kwargs["overrides"].asn)
|
|
|
|
self.assertEqual(result, "OK")
|
|
mock_group.return_value.delay.assert_called_once()
|
|
|
|
@mock.patch("documents.bulk_edit.group")
|
|
@mock.patch("documents.pdf_ops.build_pdfs")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_split_uses_latest_version_source_for_root_selection(
|
|
self,
|
|
mock_consume_file,
|
|
mock_build_pdfs,
|
|
mock_group,
|
|
) -> None:
|
|
version_file = self.dirs.scratch_dir / "sample2_version_split.pdf"
|
|
shutil.copy(self.doc2.source_path, version_file)
|
|
version = Document.objects.create(
|
|
checksum="B-v1",
|
|
title="B version 1",
|
|
root_document=self.doc2,
|
|
filename=version_file,
|
|
mime_type="application/pdf",
|
|
)
|
|
mock_build_pdfs.return_value = [version.source_path, version.source_path]
|
|
mock_group.return_value.delay.return_value = None
|
|
|
|
result = bulk_edit.split([self.doc2.id], [[1], [2]])
|
|
|
|
self.assertEqual(result, "OK")
|
|
self.assertEqual(mock_build_pdfs.call_args.args[0], version.source_path)
|
|
self.assertEqual(mock_consume_file.call_count, 2)
|
|
mock_group.return_value.delay.assert_called_once()
|
|
|
|
@mock.patch("documents.bulk_edit.delete.si")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
@mock.patch("documents.bulk_edit.chord")
|
|
def test_split_and_delete_originals(
|
|
self,
|
|
mock_chord,
|
|
mock_consume_file,
|
|
mock_delete_documents,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Split action with deleting documents is called with 1 document and 2 page groups
|
|
- delete_originals is set to True
|
|
THEN:
|
|
- Consume file should be called twice
|
|
- Document deletion task should be called
|
|
"""
|
|
doc_ids = [self.doc2.id]
|
|
pages = [[1, 2], [3]]
|
|
self.doc2.archive_serial_number = 200
|
|
self.doc2.save()
|
|
errback = bulk_edit.restore_archive_serial_numbers_task.s(
|
|
{self.doc2.id: 200},
|
|
)
|
|
mock_chord.return_value.on_error.return_value = mock_chord.return_value
|
|
|
|
result = bulk_edit.split(doc_ids, pages, delete_originals=True)
|
|
self.assertEqual(result, "OK")
|
|
|
|
self.assertEqual(mock_consume_file.call_count, 2)
|
|
self.assertEqual(
|
|
mock_consume_file.call_args.kwargs["overrides"].title,
|
|
"B (split 2)",
|
|
)
|
|
|
|
mock_delete_documents.assert_called()
|
|
mock_chord.assert_called_once()
|
|
mock_chord.return_value.on_error.assert_called_once_with(errback)
|
|
mock_chord.return_value.apply_async.assert_called_once_with()
|
|
|
|
delete_documents_args, _ = mock_delete_documents.call_args
|
|
self.assertEqual(
|
|
delete_documents_args[0],
|
|
doc_ids,
|
|
)
|
|
|
|
self.doc2.refresh_from_db()
|
|
self.assertIsNone(self.doc2.archive_serial_number)
|
|
|
|
@mock.patch("documents.bulk_edit.delete.si")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
@mock.patch("documents.bulk_edit.chord")
|
|
def test_split_restore_on_failure(
|
|
self,
|
|
mock_chord,
|
|
mock_consume_file,
|
|
mock_delete_documents,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Split action with deleting documents is called with 1 document and 2 page groups
|
|
- Error occurs when queuing chord task
|
|
THEN:
|
|
- Archive serial numbers are restored
|
|
"""
|
|
doc_ids = [self.doc2.id]
|
|
pages = [[1, 2]]
|
|
self.doc2.archive_serial_number = 222
|
|
self.doc2.save()
|
|
|
|
sig = mock.Mock()
|
|
sig.on_error.return_value = sig
|
|
sig.apply_async.side_effect = Exception("boom")
|
|
mock_chord.return_value = sig
|
|
|
|
with self.assertRaisesMessage(Exception, "boom"):
|
|
bulk_edit.split(doc_ids, pages, delete_originals=True)
|
|
|
|
self.doc2.refresh_from_db()
|
|
self.assertEqual(self.doc2.archive_serial_number, 222)
|
|
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
@mock.patch("documents.pdf_ops.build_pdfs")
|
|
def test_split_with_errors(self, mock_build_pdfs, mock_consume_file) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Split action is called with 1 document and 2 page groups
|
|
- Error occurs when building the files
|
|
THEN:
|
|
- Consume file should not be called
|
|
"""
|
|
mock_build_pdfs.side_effect = Exception("Error building PDFs")
|
|
doc_ids = [self.doc2.id]
|
|
pages = [[1, 2], [3]]
|
|
|
|
with self.assertLogs("paperless.bulk_edit", level="ERROR") as cm:
|
|
with self.assertRaisesMessage(Exception, "Error building PDFs"):
|
|
bulk_edit.split(doc_ids, pages)
|
|
error_str = cm.output[0]
|
|
expected_str = "Error splitting document 2"
|
|
self.assertIn(expected_str, error_str)
|
|
|
|
mock_consume_file.assert_not_called()
|
|
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
def test_rotate(self, mock_consume_delay) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Rotate action is called with 2 documents
|
|
THEN:
|
|
- Rotate action should be called twice
|
|
"""
|
|
doc_ids = [self.doc1.id, self.doc2.id]
|
|
result = bulk_edit.rotate(doc_ids, 90)
|
|
self.assertEqual(mock_consume_delay.call_count, 2)
|
|
for call, expected_id in zip(
|
|
mock_consume_delay.call_args_list,
|
|
doc_ids,
|
|
):
|
|
task_kwargs = call.kwargs["kwargs"]
|
|
self.assertEqual(task_kwargs["input_doc"].root_document_id, expected_id)
|
|
self.assertIsNotNone(task_kwargs["overrides"])
|
|
self.assertEqual(result, "OK")
|
|
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
@mock.patch("documents.pdf_ops.rotate_pdf")
|
|
def test_rotate_with_error(
|
|
self,
|
|
mock_rotate_pdf,
|
|
mock_consume_delay,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Rotate action is called with 2 documents
|
|
- Rotating the PDF raises an error
|
|
THEN:
|
|
- Rotate action should be called 0 times
|
|
"""
|
|
mock_rotate_pdf.side_effect = Exception("Error rotating PDF")
|
|
doc_ids = [self.doc2.id, self.doc3.id]
|
|
|
|
with self.assertLogs("paperless.bulk_edit", level="ERROR") as cm:
|
|
with self.assertRaisesMessage(
|
|
RuntimeError,
|
|
f"Rotation failed for document(s): {doc_ids}",
|
|
):
|
|
bulk_edit.rotate(doc_ids, 90)
|
|
error_str = cm.output[0]
|
|
expected_str = "Error rotating document"
|
|
self.assertIn(expected_str, error_str)
|
|
self.assertEqual(mock_rotate_pdf.call_count, 2)
|
|
mock_consume_delay.assert_not_called()
|
|
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
@mock.patch("documents.pdf_ops.rotate_pdf")
|
|
def test_rotate_continues_after_preparation_failure(
|
|
self,
|
|
mock_rotate_pdf,
|
|
mock_consume,
|
|
) -> None:
|
|
def rotate(source, destination, degrees):
|
|
if source == self.doc2.source_path:
|
|
raise RuntimeError("Invalid PDF")
|
|
shutil.copy(source, destination)
|
|
|
|
mock_rotate_pdf.side_effect = rotate
|
|
with self.assertRaisesMessage(
|
|
RuntimeError,
|
|
f"Rotation failed for document(s): [{self.doc2.id}]",
|
|
):
|
|
bulk_edit.rotate([self.doc2.id, self.doc3.id], 90)
|
|
|
|
self.assertEqual(mock_rotate_pdf.call_count, 2)
|
|
mock_consume.assert_called_once()
|
|
self.assertEqual(
|
|
mock_consume.call_args.kwargs["kwargs"]["input_doc"].root_document_id,
|
|
self.doc3.id,
|
|
)
|
|
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
@mock.patch("documents.pdf_ops.rotate_pdf")
|
|
def test_rotate_continues_after_queue_failure(
|
|
self,
|
|
mock_rotate_pdf,
|
|
mock_consume,
|
|
) -> None:
|
|
mock_rotate_pdf.side_effect = lambda source, destination, degrees: shutil.copy(
|
|
source,
|
|
destination,
|
|
)
|
|
mock_consume.side_effect = [RuntimeError("Broker unavailable"), None]
|
|
with self.assertRaisesMessage(
|
|
RuntimeError,
|
|
f"Rotation failed for document(s): [{self.doc2.id}]",
|
|
):
|
|
bulk_edit.rotate([self.doc2.id, self.doc3.id], 90)
|
|
|
|
self.assertEqual(mock_rotate_pdf.call_count, 2)
|
|
self.assertEqual(mock_consume.call_count, 2)
|
|
self.assertEqual(
|
|
mock_consume.call_args.kwargs["kwargs"]["input_doc"].root_document_id,
|
|
self.doc3.id,
|
|
)
|
|
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
def test_rotate_non_pdf(
|
|
self,
|
|
mock_consume_delay,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Rotate action is called with 2 documents, one of which is not a PDF
|
|
THEN:
|
|
- Rotate action should be performed 1 time, with the non-PDF document skipped
|
|
"""
|
|
with self.assertLogs("paperless.bulk_edit", level="INFO") as cm:
|
|
result = bulk_edit.rotate([self.doc2.id, self.img_doc.id], 90)
|
|
expected_str = f"Document {self.img_doc.id} is not a PDF, skipping rotation"
|
|
self.assertTrue(any(expected_str in line for line in cm.output))
|
|
self.assertEqual(mock_consume_delay.call_count, 1)
|
|
task_kwargs = mock_consume_delay.call_args.kwargs["kwargs"]
|
|
self.assertEqual(task_kwargs["input_doc"].root_document_id, self.doc2.id)
|
|
self.assertIsNotNone(task_kwargs["overrides"])
|
|
self.assertEqual(result, "OK")
|
|
|
|
@mock.patch("documents.data_models.magic.from_file", return_value="application/pdf")
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
@mock.patch("documents.pdf_ops.rotate_pdf")
|
|
def test_rotate_explicit_selection_uses_root_source_when_root_selected(
|
|
self,
|
|
mock_rotate_pdf,
|
|
mock_consume_delay,
|
|
mock_magic,
|
|
) -> None:
|
|
Document.objects.create(
|
|
checksum="B-v1",
|
|
title="B version 1",
|
|
root_document=self.doc2,
|
|
)
|
|
|
|
result = bulk_edit.rotate(
|
|
[self.doc2.id],
|
|
90,
|
|
source_mode="explicit_selection",
|
|
)
|
|
|
|
self.assertEqual(result, "OK")
|
|
self.assertEqual(mock_rotate_pdf.call_args.args[0], self.doc2.source_path)
|
|
mock_consume_delay.assert_called_once()
|
|
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
@mock.patch("documents.pdf_ops.remove_pages")
|
|
@mock.patch("documents.data_models.magic.from_file", return_value="application/pdf")
|
|
def test_delete_pages(
|
|
self,
|
|
mock_magic,
|
|
mock_remove_pages,
|
|
mock_consume_delay,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Delete pages action is called with 1 document and 2 pages
|
|
THEN:
|
|
- The pages are removed from the document's source PDF
|
|
- A new version should be enqueued via consume_file
|
|
"""
|
|
doc_ids = [self.doc2.id]
|
|
pages = [1, 3]
|
|
result = bulk_edit.delete_pages(doc_ids, pages)
|
|
mock_remove_pages.assert_called_once_with(
|
|
self.doc2.source_path,
|
|
mock.ANY,
|
|
[1, 3],
|
|
)
|
|
mock_consume_delay.assert_called_once()
|
|
task_kwargs = mock_consume_delay.call_args.kwargs["kwargs"]
|
|
self.assertEqual(task_kwargs["input_doc"].root_document_id, self.doc2.id)
|
|
self.assertTrue(
|
|
str(task_kwargs["input_doc"].original_file).endswith("_pages_deleted.pdf"),
|
|
)
|
|
self.assertIsNotNone(task_kwargs["overrides"])
|
|
self.assertEqual(result, "OK")
|
|
|
|
@mock.patch("documents.data_models.magic.from_file", return_value="application/pdf")
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
@mock.patch("documents.pdf_ops.remove_pages")
|
|
def test_delete_pages_explicit_selection_uses_root_source_when_root_selected(
|
|
self,
|
|
mock_remove_pages,
|
|
mock_consume_delay,
|
|
mock_magic,
|
|
) -> None:
|
|
Document.objects.create(
|
|
checksum="B-v1",
|
|
title="B version 1",
|
|
root_document=self.doc2,
|
|
)
|
|
|
|
result = bulk_edit.delete_pages(
|
|
[self.doc2.id],
|
|
[1],
|
|
source_mode="explicit_selection",
|
|
)
|
|
|
|
self.assertEqual(result, "OK")
|
|
self.assertEqual(mock_remove_pages.call_args.args[0], self.doc2.source_path)
|
|
mock_consume_delay.assert_called_once()
|
|
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
@mock.patch("documents.pdf_ops.remove_pages")
|
|
def test_delete_pages_with_error(
|
|
self,
|
|
mock_remove_pages,
|
|
mock_consume_delay,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing documents
|
|
WHEN:
|
|
- Delete pages action is called with 1 document and 2 pages
|
|
- Removing the pages raises an error
|
|
THEN:
|
|
- No new version should be enqueued
|
|
"""
|
|
mock_remove_pages.side_effect = Exception("Error removing pages")
|
|
doc_ids = [self.doc2.id]
|
|
pages = [1, 3]
|
|
|
|
with self.assertLogs("paperless.bulk_edit", level="ERROR") as cm:
|
|
with self.assertRaisesMessage(Exception, "Error removing pages"):
|
|
bulk_edit.delete_pages(doc_ids, pages)
|
|
error_str = cm.output[0]
|
|
expected_str = "Error deleting pages from document"
|
|
self.assertIn(expected_str, error_str)
|
|
mock_consume_delay.assert_not_called()
|
|
|
|
@mock.patch("documents.bulk_edit.group")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_edit_pdf_basic_operations(self, mock_consume_file, mock_group) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing document
|
|
WHEN:
|
|
- edit_pdf is called with two operations to split the doc and rotate pages
|
|
THEN:
|
|
- A grouped task is generated and delay() is called
|
|
"""
|
|
mock_group.return_value.delay.return_value = None
|
|
doc_ids = [self.doc2.id]
|
|
operations = [{"page": 1, "doc": 0}, {"page": 2, "doc": 1, "rotate": 90}]
|
|
|
|
result = bulk_edit.edit_pdf(doc_ids, operations)
|
|
self.assertEqual(result, "OK")
|
|
mock_group.return_value.delay.assert_called_once()
|
|
|
|
@mock.patch("documents.bulk_edit.group")
|
|
@mock.patch("documents.pdf_ops.build_pdfs")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_edit_pdf_maps_operations_to_outputs(
|
|
self,
|
|
mock_consume_file: mock.Mock,
|
|
mock_build_pdfs: mock.Mock,
|
|
mock_group: mock.Mock,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing document
|
|
WHEN:
|
|
- edit_pdf is called with operations interleaved across two outputs,
|
|
some of them rotated
|
|
THEN:
|
|
- Each output is built from its own operations, in operation order,
|
|
with the requested rotation
|
|
"""
|
|
mock_build_pdfs.return_value = [self.doc2.source_path, self.doc2.source_path]
|
|
mock_group.return_value.delay.return_value = None
|
|
operations = [
|
|
{"page": 3, "doc": 1},
|
|
{"page": 1, "doc": 0, "rotate": 90},
|
|
{"page": 2, "doc": 1, "rotate": 180},
|
|
]
|
|
|
|
bulk_edit.edit_pdf([self.doc2.id], operations)
|
|
|
|
outputs = mock_build_pdfs.call_args.args[1]
|
|
self.assertEqual(
|
|
[specs for specs, _ in outputs],
|
|
[[PageSpec(1, 90)], [PageSpec(3), PageSpec(2, 180)]],
|
|
)
|
|
|
|
@mock.patch("documents.bulk_edit.group")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_edit_pdf_with_user_override(self, mock_consume_file, mock_group) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing document
|
|
WHEN:
|
|
- edit_pdf is called with user override
|
|
THEN:
|
|
- Task is created with user context
|
|
"""
|
|
mock_group.return_value.delay.return_value = None
|
|
doc_ids = [self.doc2.id]
|
|
operations = [{"page": 1, "doc": 0}, {"page": 2, "doc": 1}]
|
|
user = User.objects.create(username="editor")
|
|
|
|
result = bulk_edit.edit_pdf(doc_ids, operations, user=user)
|
|
self.assertEqual(result, "OK")
|
|
mock_group.return_value.delay.assert_called_once()
|
|
|
|
@mock.patch("documents.bulk_edit.chord")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_edit_pdf_with_delete_original(self, mock_consume_file, mock_chord) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing document
|
|
WHEN:
|
|
- edit_pdf is called with delete_original=True
|
|
THEN:
|
|
- Task group is triggered
|
|
"""
|
|
mock_chord.return_value.delay.return_value = None
|
|
doc_ids = [self.doc2.id]
|
|
operations = [{"page": 1}, {"page": 2}]
|
|
self.doc2.archive_serial_number = 250
|
|
self.doc2.save()
|
|
errback = bulk_edit.restore_archive_serial_numbers_task.s(
|
|
{self.doc2.id: 250},
|
|
)
|
|
mock_chord.return_value.on_error.return_value = mock_chord.return_value
|
|
|
|
result = bulk_edit.edit_pdf(doc_ids, operations, delete_original=True)
|
|
self.assertEqual(result, "OK")
|
|
mock_chord.assert_called_once()
|
|
mock_chord.return_value.on_error.assert_called_once_with(errback)
|
|
mock_chord.return_value.apply_async.assert_called_once_with()
|
|
self.assertEqual(mock_consume_file.call_args.kwargs["overrides"].asn, 250)
|
|
self.doc2.refresh_from_db()
|
|
self.assertIsNone(self.doc2.archive_serial_number)
|
|
|
|
@mock.patch("documents.bulk_edit.delete.si")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
@mock.patch("documents.bulk_edit.chord")
|
|
def test_edit_pdf_restore_on_failure(
|
|
self,
|
|
mock_chord: mock.Mock,
|
|
mock_consume_file: mock.Mock,
|
|
mock_delete_documents: mock.Mock,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing document
|
|
WHEN:
|
|
- edit_pdf is called with delete_original=True
|
|
- Error occurs when queuing chord task
|
|
THEN:
|
|
- Archive serial numbers are restored
|
|
"""
|
|
doc_ids = [self.doc2.id]
|
|
operations = [{"page": 1}]
|
|
self.doc2.archive_serial_number = 333
|
|
self.doc2.save()
|
|
|
|
sig = mock.Mock()
|
|
sig.on_error.return_value = sig
|
|
sig.apply_async.side_effect = Exception("boom")
|
|
mock_chord.return_value = sig
|
|
|
|
with self.assertRaises(Exception):
|
|
bulk_edit.edit_pdf(doc_ids, operations, delete_original=True)
|
|
|
|
self.doc2.refresh_from_db()
|
|
self.assertEqual(self.doc2.archive_serial_number, 333)
|
|
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
def test_edit_pdf_with_update_document(self, mock_consume_delay) -> None:
|
|
"""
|
|
GIVEN:
|
|
- A single existing PDF document
|
|
WHEN:
|
|
- edit_pdf is called with update_document=True and a single output
|
|
THEN:
|
|
- A version update is enqueued targeting the existing document
|
|
"""
|
|
doc_ids = [self.doc2.id]
|
|
operations = [{"page": 1}, {"page": 2}]
|
|
|
|
result = bulk_edit.edit_pdf(
|
|
doc_ids,
|
|
operations=operations,
|
|
update_document=True,
|
|
delete_original=False,
|
|
)
|
|
|
|
self.assertEqual(result, "OK")
|
|
mock_consume_delay.assert_called_once()
|
|
task_kwargs = mock_consume_delay.call_args.kwargs["kwargs"]
|
|
self.assertEqual(task_kwargs["input_doc"].root_document_id, self.doc2.id)
|
|
self.assertTrue(
|
|
str(task_kwargs["input_doc"].original_file).endswith("_edited.pdf"),
|
|
)
|
|
self.assertIsNotNone(task_kwargs["overrides"])
|
|
|
|
@mock.patch("documents.data_models.magic.from_file", return_value="application/pdf")
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
@mock.patch("documents.pdf_ops.build_pdfs")
|
|
def test_edit_pdf_explicit_selection_uses_root_source_when_root_selected(
|
|
self,
|
|
mock_build_pdfs,
|
|
mock_consume_delay,
|
|
mock_magic,
|
|
) -> None:
|
|
Document.objects.create(
|
|
checksum="B-v1",
|
|
title="B version 1",
|
|
root_document=self.doc2,
|
|
)
|
|
mock_build_pdfs.return_value = [Path("edited.pdf")]
|
|
|
|
result = bulk_edit.edit_pdf(
|
|
[self.doc2.id],
|
|
operations=[{"page": 1}],
|
|
update_document=True,
|
|
source_mode="explicit_selection",
|
|
)
|
|
|
|
self.assertEqual(result, "OK")
|
|
self.assertEqual(mock_build_pdfs.call_args.args[0], self.doc2.source_path)
|
|
mock_consume_delay.assert_called_once()
|
|
|
|
@mock.patch("documents.bulk_edit.group")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_edit_pdf_without_metadata(
|
|
self,
|
|
mock_consume_file: mock.Mock,
|
|
mock_group: mock.Mock,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing document
|
|
WHEN:
|
|
- edit_pdf is called with include_metadata=False
|
|
THEN:
|
|
- Tasks are created with empty metadata
|
|
"""
|
|
mock_group.return_value.delay.return_value = None
|
|
doc_ids = [self.doc2.id]
|
|
operations = [{"page": 1}]
|
|
|
|
result = bulk_edit.edit_pdf(doc_ids, operations, include_metadata=False)
|
|
self.assertEqual(result, "OK")
|
|
mock_group.return_value.delay.assert_called_once()
|
|
|
|
@mock.patch("documents.bulk_edit.group")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
def test_edit_pdf_multiple_outputs_with_update_flag_errors(
|
|
self,
|
|
mock_consume_file,
|
|
mock_group,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Existing document
|
|
WHEN:
|
|
- edit_pdf is called with multiple outputs and update_document=True
|
|
THEN:
|
|
- An error is logged and task group is not called
|
|
"""
|
|
doc_ids = [self.doc2.id]
|
|
operations = [
|
|
{"page": 1, "doc": 0},
|
|
{"page": 2, "doc": 1},
|
|
]
|
|
with self.assertLogs("paperless.bulk_edit", level="ERROR"):
|
|
with self.assertRaises(ValueError):
|
|
bulk_edit.edit_pdf(doc_ids, operations, update_document=True)
|
|
mock_group.assert_not_called()
|
|
mock_consume_file.assert_not_called()
|
|
|
|
@mock.patch("documents.bulk_edit.update_document_content_maybe_archive_file.delay")
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
@mock.patch("documents.bulk_edit.tempfile.mkdtemp")
|
|
@mock.patch("documents.pdf_ops.decrypt_pdf")
|
|
@mock.patch("documents.pdf_ops.needs_decrypt", return_value=True)
|
|
def test_remove_password_update_document(
|
|
self,
|
|
mock_needs_decrypt,
|
|
mock_decrypt,
|
|
mock_mkdtemp,
|
|
mock_consume_delay,
|
|
mock_update_document,
|
|
) -> None:
|
|
doc = self.doc1
|
|
temp_dir = self.dirs.scratch_dir / "remove-password-update"
|
|
temp_dir.mkdir(parents=True, exist_ok=True)
|
|
mock_mkdtemp.return_value = str(temp_dir)
|
|
mock_decrypt.side_effect = self.fake_decrypt
|
|
|
|
result = bulk_edit.remove_password(
|
|
[doc.id],
|
|
password="secret",
|
|
update_document=True,
|
|
)
|
|
|
|
self.assertEqual(result, "OK")
|
|
mock_needs_decrypt.assert_called_once_with(doc.source_path)
|
|
mock_decrypt.assert_called_once_with(doc.source_path, mock.ANY, "secret")
|
|
mock_update_document.assert_not_called()
|
|
mock_consume_delay.assert_called_once()
|
|
task_kwargs = mock_consume_delay.call_args.kwargs["kwargs"]
|
|
expected_path = temp_dir / f"{doc.id}_unprotected.pdf"
|
|
self.assertTrue(expected_path.exists())
|
|
self.assertEqual(
|
|
Path(task_kwargs["input_doc"].original_file).resolve(),
|
|
expected_path.resolve(),
|
|
)
|
|
self.assertEqual(task_kwargs["input_doc"].root_document_id, doc.id)
|
|
self.assertIsNotNone(task_kwargs["overrides"])
|
|
|
|
@mock.patch("documents.bulk_edit.update_document_content_maybe_archive_file.delay")
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
@mock.patch("documents.bulk_edit.tempfile.mkdtemp")
|
|
@mock.patch("documents.pdf_ops.decrypt_pdf")
|
|
@mock.patch("documents.pdf_ops.needs_decrypt", return_value=True)
|
|
def test_remove_password_update_document_uses_source_paths(
|
|
self,
|
|
mock_needs_decrypt,
|
|
mock_decrypt,
|
|
mock_mkdtemp,
|
|
mock_consume_delay,
|
|
mock_update_document,
|
|
) -> None:
|
|
doc = self.doc1
|
|
source_file = self.dirs.scratch_dir / "consumption-source.pdf"
|
|
source_file.write_bytes(b"protected pdf content")
|
|
temp_dir = self.dirs.scratch_dir / "remove-password-source-file"
|
|
temp_dir.mkdir(parents=True, exist_ok=True)
|
|
mock_mkdtemp.return_value = str(temp_dir)
|
|
mock_decrypt.side_effect = self.fake_decrypt
|
|
|
|
result = bulk_edit.remove_password(
|
|
[doc.id],
|
|
password="secret",
|
|
update_document=True,
|
|
source_paths_by_id={doc.id: source_file},
|
|
)
|
|
|
|
self.assertEqual(result, "OK")
|
|
mock_needs_decrypt.assert_called_once_with(source_file)
|
|
mock_decrypt.assert_called_once_with(source_file, mock.ANY, "secret")
|
|
mock_update_document.assert_not_called()
|
|
mock_consume_delay.assert_called_once()
|
|
|
|
@mock.patch("documents.data_models.magic.from_file", return_value="application/pdf")
|
|
@mock.patch("documents.tasks.consume_file.apply_async")
|
|
@mock.patch("documents.pdf_ops.decrypt_pdf")
|
|
@mock.patch("documents.pdf_ops.needs_decrypt", return_value=True)
|
|
def test_remove_password_explicit_selection_uses_root_source_when_root_selected(
|
|
self,
|
|
mock_needs_decrypt,
|
|
mock_decrypt,
|
|
mock_consume_delay,
|
|
mock_magic,
|
|
) -> None:
|
|
Document.objects.create(
|
|
checksum="A-v1",
|
|
title="A version 1",
|
|
root_document=self.doc1,
|
|
)
|
|
mock_decrypt.return_value = Path("unprotected.pdf")
|
|
|
|
result = bulk_edit.remove_password(
|
|
[self.doc1.id],
|
|
password="secret",
|
|
update_document=True,
|
|
source_mode="explicit_selection",
|
|
)
|
|
|
|
self.assertEqual(result, "OK")
|
|
mock_needs_decrypt.assert_called_once_with(self.doc1.source_path)
|
|
mock_decrypt.assert_called_once_with(
|
|
self.doc1.source_path,
|
|
mock.ANY,
|
|
"secret",
|
|
)
|
|
mock_consume_delay.assert_called_once()
|
|
|
|
@mock.patch("documents.bulk_edit.chord")
|
|
@mock.patch("documents.bulk_edit.group")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
@mock.patch("documents.bulk_edit.tempfile.mkdtemp")
|
|
@mock.patch("documents.pdf_ops.decrypt_pdf")
|
|
@mock.patch("documents.pdf_ops.needs_decrypt", return_value=True)
|
|
def test_remove_password_creates_consumable_document(
|
|
self,
|
|
mock_needs_decrypt: mock.Mock,
|
|
mock_decrypt: mock.Mock,
|
|
mock_mkdtemp: mock.Mock,
|
|
mock_consume_file: mock.Mock,
|
|
mock_group: mock.Mock,
|
|
mock_chord: mock.Mock,
|
|
) -> None:
|
|
doc = self.doc2
|
|
temp_dir = self.dirs.scratch_dir / "remove-password"
|
|
temp_dir.mkdir(parents=True, exist_ok=True)
|
|
mock_mkdtemp.return_value = str(temp_dir)
|
|
mock_decrypt.side_effect = self.fake_decrypt
|
|
mock_group.return_value.delay.return_value = None
|
|
|
|
user = User.objects.create(username="owner")
|
|
|
|
result = bulk_edit.remove_password(
|
|
[doc.id],
|
|
password="secret",
|
|
include_metadata=False,
|
|
update_document=False,
|
|
delete_original=False,
|
|
user=user,
|
|
)
|
|
|
|
self.assertEqual(result, "OK")
|
|
mock_decrypt.assert_called_once_with(doc.source_path, mock.ANY, "secret")
|
|
mock_consume_file.assert_called_once()
|
|
call_kwargs = mock_consume_file.call_args.kwargs
|
|
consumable_document = call_kwargs["input_doc"]
|
|
overrides = call_kwargs["overrides"]
|
|
expected_path = temp_dir / f"{doc.id}_unprotected.pdf"
|
|
self.assertTrue(expected_path.exists())
|
|
self.assertEqual(
|
|
Path(consumable_document.original_file).resolve(),
|
|
expected_path.resolve(),
|
|
)
|
|
self.assertEqual(overrides.owner_id, user.id)
|
|
mock_group.assert_called_once_with(
|
|
[mock_consume_file.return_value.set.return_value],
|
|
)
|
|
mock_group.return_value.delay.assert_called_once()
|
|
mock_chord.assert_not_called()
|
|
|
|
@mock.patch("documents.bulk_edit.delete")
|
|
@mock.patch("documents.bulk_edit.chord")
|
|
@mock.patch("documents.bulk_edit.group")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
@mock.patch("documents.pdf_ops.decrypt_pdf")
|
|
@mock.patch("documents.pdf_ops.needs_decrypt", return_value=False)
|
|
def test_remove_password_skips_unencrypted_pdf_without_queueing(
|
|
self,
|
|
mock_needs_decrypt: mock.Mock,
|
|
mock_decrypt: mock.Mock,
|
|
mock_consume_file: mock.Mock,
|
|
mock_group: mock.Mock,
|
|
mock_chord: mock.Mock,
|
|
mock_delete: mock.Mock,
|
|
) -> None:
|
|
doc = self.doc2
|
|
|
|
result = bulk_edit.remove_password(
|
|
[doc.id],
|
|
password="secret",
|
|
update_document=False,
|
|
delete_original=True,
|
|
)
|
|
|
|
self.assertEqual(result, "OK")
|
|
mock_needs_decrypt.assert_called_once_with(doc.source_path)
|
|
mock_decrypt.assert_not_called()
|
|
mock_consume_file.assert_not_called()
|
|
mock_group.assert_not_called()
|
|
mock_chord.assert_not_called()
|
|
mock_delete.si.assert_not_called()
|
|
|
|
@mock.patch("documents.bulk_edit.delete")
|
|
@mock.patch("documents.bulk_edit.chord")
|
|
@mock.patch("documents.bulk_edit.group")
|
|
@mock.patch("documents.tasks.consume_file.s")
|
|
@mock.patch("documents.bulk_edit.tempfile.mkdtemp")
|
|
@mock.patch("documents.pdf_ops.decrypt_pdf")
|
|
@mock.patch("documents.pdf_ops.needs_decrypt", return_value=True)
|
|
def test_remove_password_deletes_original(
|
|
self,
|
|
mock_needs_decrypt: mock.Mock,
|
|
mock_decrypt: mock.Mock,
|
|
mock_mkdtemp: mock.Mock,
|
|
mock_consume_file: mock.Mock,
|
|
mock_group: mock.Mock,
|
|
mock_chord: mock.Mock,
|
|
mock_delete: mock.Mock,
|
|
) -> None:
|
|
doc = self.doc2
|
|
temp_dir = self.dirs.scratch_dir / "remove-password-delete"
|
|
temp_dir.mkdir(parents=True, exist_ok=True)
|
|
mock_mkdtemp.return_value = str(temp_dir)
|
|
mock_decrypt.side_effect = self.fake_decrypt
|
|
mock_chord.return_value.delay.return_value = None
|
|
|
|
result = bulk_edit.remove_password(
|
|
[doc.id],
|
|
password="secret",
|
|
include_metadata=False,
|
|
update_document=False,
|
|
delete_original=True,
|
|
)
|
|
|
|
self.assertEqual(result, "OK")
|
|
mock_decrypt.assert_called_once_with(doc.source_path, mock.ANY, "secret")
|
|
mock_consume_file.assert_called_once()
|
|
mock_group.assert_not_called()
|
|
mock_chord.assert_called_once()
|
|
mock_chord.return_value.delay.assert_called_once()
|
|
mock_delete.si.assert_called_once_with([doc.id])
|
|
|
|
@mock.patch(
|
|
"documents.pdf_ops.decrypt_pdf",
|
|
side_effect=RuntimeError("wrong password"),
|
|
)
|
|
@mock.patch("documents.pdf_ops.needs_decrypt", return_value=True)
|
|
def test_remove_password_failure_raises_value_error(
|
|
self,
|
|
mock_needs_decrypt: mock.Mock,
|
|
mock_decrypt: mock.Mock,
|
|
) -> None:
|
|
with self.assertLogs("paperless.bulk_edit", level="ERROR") as cm:
|
|
with self.assertRaises(ValueError) as exc:
|
|
bulk_edit.remove_password([self.doc1.id], password="secret")
|
|
|
|
self.assertIn("wrong password", str(exc.exception))
|
|
self.assertIn("Error removing password from document", cm.output[0])
|
|
|
|
|
|
def _written_result() -> ZoneOcrResult:
|
|
return ZoneOcrResult(template="t", zone="z", custom_field="", reason=None)
|
|
|
|
|
|
def _unwritten_result() -> ZoneOcrResult:
|
|
return ZoneOcrResult(
|
|
template="t",
|
|
zone="z",
|
|
custom_field="",
|
|
reason=ZoneOcrReason.NO_VALUE,
|
|
)
|
|
|
|
|
|
@pytest.mark.django_db
|
|
class TestBulkEditRunZoneOcr:
|
|
"""Bulk run_zone_ocr runs zone extraction for each selected document."""
|
|
|
|
@pytest.fixture
|
|
def mock_extract(self, mocker: MockerFixture) -> mock.MagicMock:
|
|
return mocker.patch("documents.bulk_edit.run_zone_extraction", return_value=[])
|
|
|
|
@pytest.fixture
|
|
def mock_finish(self, mocker: MockerFixture) -> mock.MagicMock:
|
|
return mocker.patch("documents.bulk_edit.bulk_update_documents")
|
|
|
|
def test_selects_templates_for_the_requester(
|
|
self,
|
|
mock_extract: mock.MagicMock,
|
|
mocker: MockerFixture,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Two selected documents and a user
|
|
WHEN:
|
|
- run_zone_ocr is called for the documents without a template
|
|
THEN:
|
|
- Templates are selected for each document with the requester
|
|
- Extraction runs inline for each document
|
|
"""
|
|
select = mocker.patch("documents.bulk_edit.get_templates_for_document")
|
|
docs = DocumentFactory.create_batch(2)
|
|
user = UserFactory()
|
|
|
|
result = bulk_edit.run_zone_ocr([doc.id for doc in docs], user=user)
|
|
|
|
assert result == "OK"
|
|
assert select.call_args_list == [
|
|
mocker.call(doc, requester=user) for doc in docs
|
|
]
|
|
assert mock_extract.call_args_list == [
|
|
mocker.call(doc, templates=select.return_value) for doc in docs
|
|
]
|
|
|
|
def test_runs_the_chosen_template(
|
|
self,
|
|
mock_extract: mock.MagicMock,
|
|
mocker: MockerFixture,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Two documents and an OCR template
|
|
WHEN:
|
|
- run_zone_ocr is called for the documents with the template
|
|
THEN:
|
|
- Extraction runs for each document with only that template
|
|
- Template matching is not used
|
|
"""
|
|
select = mocker.patch("documents.bulk_edit.get_templates_for_document")
|
|
docs = DocumentFactory.create_batch(2)
|
|
template = OcrTemplateFactory()
|
|
|
|
bulk_edit.run_zone_ocr([doc.id for doc in docs], template=template.pk)
|
|
|
|
select.assert_not_called()
|
|
assert mock_extract.call_args_list == [
|
|
mocker.call(doc, templates=[template]) for doc in docs
|
|
]
|
|
|
|
def test_deleted_template_runs_nothing(
|
|
self,
|
|
mock_extract: mock.MagicMock,
|
|
mock_finish: mock.MagicMock,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- A chosen template that no longer exists
|
|
WHEN:
|
|
- run_zone_ocr is called
|
|
THEN:
|
|
- OK is returned without running extraction or finishing
|
|
"""
|
|
doc = DocumentFactory()
|
|
|
|
result = bulk_edit.run_zone_ocr([doc.pk], template=999)
|
|
|
|
assert result == "OK"
|
|
mock_extract.assert_not_called()
|
|
mock_finish.assert_not_called()
|
|
|
|
def test_missing_document_does_not_abort_the_others(
|
|
self,
|
|
mock_extract: mock.MagicMock,
|
|
mock_finish: mock.MagicMock,
|
|
mocker: MockerFixture,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- A selection holding a nonexistent id and a trashed document
|
|
alongside a live document
|
|
WHEN:
|
|
- run_zone_ocr is called
|
|
THEN:
|
|
- Only the live document is extracted
|
|
- The live document is finished
|
|
"""
|
|
live = DocumentFactory()
|
|
trashed = DocumentFactory()
|
|
trashed.delete()
|
|
template = OcrTemplateFactory()
|
|
mock_extract.return_value = [_written_result()]
|
|
|
|
bulk_edit.run_zone_ocr([999999, trashed.pk, live.pk], template=template.pk)
|
|
|
|
mock_extract.assert_called_once_with(live, templates=[template])
|
|
mock_finish.assert_called_once_with([live.pk])
|
|
|
|
def test_failing_document_does_not_abort_the_others(
|
|
self,
|
|
mock_extract: mock.MagicMock,
|
|
mock_finish: mock.MagicMock,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Three selected documents, the second of which raises during extraction
|
|
WHEN:
|
|
- run_zone_ocr is called
|
|
THEN:
|
|
- The failure is logged and the remaining document still runs
|
|
- bulk_update_documents runs once with the written documents
|
|
- The task then fails, naming the number of failed documents
|
|
"""
|
|
docs = DocumentFactory.create_batch(3)
|
|
template = OcrTemplateFactory()
|
|
mock_extract.side_effect = [
|
|
[_written_result()],
|
|
RuntimeError("boom"),
|
|
[_written_result()],
|
|
]
|
|
|
|
with pytest.raises(RuntimeError, match="1 of 3 documents"):
|
|
bulk_edit.run_zone_ocr([d.pk for d in docs], template=template.pk)
|
|
|
|
assert mock_extract.call_count == 3
|
|
mock_finish.assert_called_once_with([docs[0].pk, docs[2].pk])
|
|
|
|
def test_finishes_each_root_once(
|
|
self,
|
|
mock_extract: mock.MagicMock,
|
|
mock_finish: mock.MagicMock,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Two documents whose extraction writes, one being a version of the other
|
|
when not resolving the latest version
|
|
WHEN:
|
|
- run_zone_ocr is called without resolving the latest version
|
|
THEN:
|
|
- bulk_update_documents runs once with the root id listed once
|
|
"""
|
|
root = DocumentFactory()
|
|
version = DocumentFactory(root_document=root, version_index=1)
|
|
template = OcrTemplateFactory()
|
|
mock_extract.return_value = [_written_result()]
|
|
|
|
bulk_edit.run_zone_ocr(
|
|
[root.pk, version.pk],
|
|
template=template.pk,
|
|
resolve_latest=False,
|
|
)
|
|
|
|
assert mock_extract.call_count == 2
|
|
mock_finish.assert_called_once_with([root.pk])
|
|
|
|
def test_does_not_finish_when_nothing_was_written(
|
|
self,
|
|
mock_extract: mock.MagicMock,
|
|
mock_finish: mock.MagicMock,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Selected documents with no successful write
|
|
WHEN:
|
|
- run_zone_ocr is called
|
|
THEN:
|
|
- bulk_update_documents is not run
|
|
"""
|
|
docs = DocumentFactory.create_batch(2)
|
|
template = OcrTemplateFactory()
|
|
mock_extract.return_value = [_unwritten_result()]
|
|
|
|
bulk_edit.run_zone_ocr([d.pk for d in docs], template=template.pk)
|
|
|
|
mock_finish.assert_not_called()
|
|
|
|
def test_finishes_written_documents_when_the_run_is_interrupted(
|
|
self,
|
|
mock_extract: mock.MagicMock,
|
|
mock_finish: mock.MagicMock,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- Two selected documents, the second of which raises an exception
|
|
that is not an Exception subclass
|
|
WHEN:
|
|
- run_zone_ocr is called
|
|
THEN:
|
|
- The interruption propagates
|
|
- bulk_update_documents still runs with the first document's id
|
|
"""
|
|
docs = DocumentFactory.create_batch(2)
|
|
template = OcrTemplateFactory()
|
|
mock_extract.side_effect = [[_written_result()], KeyboardInterrupt()]
|
|
|
|
with pytest.raises(KeyboardInterrupt):
|
|
bulk_edit.run_zone_ocr([d.pk for d in docs], template=template.pk)
|
|
|
|
mock_finish.assert_called_once_with([docs[0].pk])
|
|
|
|
@pytest.mark.parametrize(
|
|
("resolve_latest", "processes_root"),
|
|
[
|
|
pytest.param(True, False, id="resolves-latest"),
|
|
pytest.param(False, True, id="exact-document"),
|
|
],
|
|
)
|
|
def test_resolves_latest_only_when_asked(
|
|
self,
|
|
mock_extract: mock.MagicMock,
|
|
resolve_latest: bool, # noqa: FBT001
|
|
processes_root: bool, # noqa: FBT001
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- A root document with a newer version and a template
|
|
WHEN:
|
|
- run_zone_ocr runs for the root id with resolve_latest on or off
|
|
THEN:
|
|
- The newest version is processed when resolve_latest is on
|
|
- The root document itself is processed when it is off
|
|
"""
|
|
root = DocumentFactory()
|
|
newest = DocumentFactory(root_document=root, version_index=1)
|
|
template = OcrTemplateFactory()
|
|
|
|
bulk_edit.run_zone_ocr(
|
|
[root.pk],
|
|
template=template.pk,
|
|
resolve_latest=resolve_latest,
|
|
)
|
|
|
|
mock_extract.assert_called_once_with(
|
|
root if processes_root else newest,
|
|
templates=[template],
|
|
)
|
|
|
|
def test_root_and_its_version_are_processed_once(
|
|
self,
|
|
mock_extract: mock.MagicMock,
|
|
mock_finish: mock.MagicMock,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- A root document with a version, both listed in the selection
|
|
WHEN:
|
|
- run_zone_ocr runs with resolve_latest on
|
|
THEN:
|
|
- The newest version is extracted once
|
|
- The root is finished once
|
|
"""
|
|
root = DocumentFactory()
|
|
version = DocumentFactory(root_document=root, version_index=1)
|
|
template = OcrTemplateFactory()
|
|
mock_extract.return_value = [_written_result()]
|
|
|
|
bulk_edit.run_zone_ocr([root.pk, version.pk], template=template.pk)
|
|
|
|
mock_extract.assert_called_once_with(version, templates=[template])
|
|
mock_finish.assert_called_once_with([root.pk])
|
|
|
|
def test_a_version_reports_its_root(
|
|
self,
|
|
mock_extract: mock.MagicMock,
|
|
mock_finish: mock.MagicMock,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- A root with two versions and the older version selected
|
|
WHEN:
|
|
- run_zone_ocr runs without resolving the latest version
|
|
THEN:
|
|
- Extraction runs on that version, not the newest
|
|
- The root is finished
|
|
"""
|
|
root = DocumentFactory()
|
|
older = DocumentFactory(root_document=root, version_index=1)
|
|
DocumentFactory(root_document=root, version_index=2)
|
|
template = OcrTemplateFactory()
|
|
mock_extract.return_value = [_written_result()]
|
|
|
|
bulk_edit.run_zone_ocr([older.pk], template=template.pk, resolve_latest=False)
|
|
|
|
mock_extract.assert_called_once_with(older, templates=[template])
|
|
mock_finish.assert_called_once_with([root.pk])
|
|
|
|
|
|
@pytest.mark.django_db
|
|
class TestBulkEditReprocess:
|
|
@pytest.fixture
|
|
def mock_task(self, mocker: MockerFixture) -> mock.MagicMock:
|
|
return mocker.patch(
|
|
"documents.bulk_edit.update_document_content_maybe_archive_file",
|
|
)
|
|
|
|
@staticmethod
|
|
def _queued_ids(mock_task: mock.MagicMock) -> list[int]:
|
|
return [
|
|
call.kwargs["kwargs"]["document_id"]
|
|
for call in mock_task.apply_async.call_args_list
|
|
]
|
|
|
|
def test_reprocess_defaults_to_local(self, mock_task: mock.MagicMock) -> None:
|
|
"""
|
|
GIVEN:
|
|
- A reprocess request that says nothing about remote OCR
|
|
WHEN:
|
|
- reprocess is called
|
|
THEN:
|
|
- The task is queued without asking for the remote engine
|
|
"""
|
|
doc = DocumentFactory()
|
|
|
|
assert bulk_edit.reprocess([doc.id]) == "OK"
|
|
|
|
mock_task.apply_async.assert_called_once()
|
|
assert mock_task.apply_async.call_args.kwargs["kwargs"] == {
|
|
"document_id": doc.id,
|
|
"remote_ocr": False,
|
|
}
|
|
|
|
def test_reprocess_passes_remote_ocr(self, mock_task: mock.MagicMock) -> None:
|
|
"""
|
|
GIVEN:
|
|
- A reprocess request that explicitly asks for remote OCR
|
|
WHEN:
|
|
- reprocess is called
|
|
THEN:
|
|
- The request is forwarded to the task for every document
|
|
"""
|
|
docs = DocumentFactory.create_batch(2)
|
|
|
|
bulk_edit.reprocess([doc.id for doc in docs], remote_ocr=True)
|
|
|
|
assert mock_task.apply_async.call_count == 2
|
|
for call in mock_task.apply_async.call_args_list:
|
|
assert call.kwargs["kwargs"]["remote_ocr"]
|
|
|
|
def test_reprocess_root_uses_latest_version(
|
|
self,
|
|
mock_task: mock.MagicMock,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- A root document with two versions
|
|
WHEN:
|
|
- reprocess is called with the root document
|
|
THEN:
|
|
- The latest version is reprocessed, not the root's original file
|
|
"""
|
|
root = DocumentFactory()
|
|
DocumentFactory(root_document=root, version_index=1)
|
|
latest = DocumentFactory(root_document=root, version_index=2)
|
|
|
|
bulk_edit.reprocess([root.id])
|
|
|
|
assert self._queued_ids(mock_task) == [latest.id]
|
|
|
|
def test_reprocess_explicit_version(self, mock_task: mock.MagicMock) -> None:
|
|
"""
|
|
GIVEN:
|
|
- A root document with two versions
|
|
WHEN:
|
|
- reprocess is called with the older version
|
|
THEN:
|
|
- That version is reprocessed
|
|
"""
|
|
root = DocumentFactory()
|
|
older = DocumentFactory(root_document=root, version_index=1)
|
|
DocumentFactory(root_document=root, version_index=2)
|
|
|
|
bulk_edit.reprocess([older.id])
|
|
|
|
assert self._queued_ids(mock_task) == [older.id]
|
|
|
|
def test_reprocess_root_and_latest_version_dispatches_once(
|
|
self,
|
|
mock_task: mock.MagicMock,
|
|
) -> None:
|
|
"""
|
|
GIVEN:
|
|
- A root document with two versions, the latest created on a
|
|
different date than the root
|
|
WHEN:
|
|
- reprocess is called with both the root and its latest version
|
|
THEN:
|
|
- The latest version is reprocessed only once
|
|
"""
|
|
root = DocumentFactory(created=date(2024, 1, 1))
|
|
DocumentFactory(root_document=root, version_index=1)
|
|
latest = DocumentFactory(
|
|
root_document=root,
|
|
version_index=2,
|
|
created=date(2025, 1, 1),
|
|
)
|
|
|
|
bulk_edit.reprocess([root.id, latest.id])
|
|
|
|
assert self._queued_ids(mock_task) == [latest.id]
|