Compare commits

...
4 changed files with 116 additions and 4 deletions

No files matched your search

+4 -4
View File
@@ -11,6 +11,7 @@ from typing import Final
import magic
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import transaction
from django.db.models import Max
from django.db.models import Q
@@ -1273,10 +1274,9 @@ class AsnCheckPlugin(
return
# Validate the range is above zero and less than uint32_t max
# otherwise, Whoosh can't handle it in the index
if (
self.metadata.asn < Document.ARCHIVE_SERIAL_NUMBER_MIN
or self.metadata.asn > Document.ARCHIVE_SERIAL_NUMBER_MAX
):
try:
Document.validate_archive_serial_number(self.metadata.asn)
except DjangoValidationError:
self._fail(
ConsumerStatusShortMessage.ASN_RANGE,
f"Not consuming {self.filename}: "
+9
View File
@@ -422,6 +422,15 @@ class Document(SoftDeleteModel, ModelWithOwner): # type: ignore[django-manager-
res += f" {self.title}"
return res
@classmethod
def validate_archive_serial_number(cls, value: int) -> None:
"""
Run every validator of the ASN field. Besides the fixed range above, Django
adds the range of the column for the database in use (a signed 32 bit
integer on PostgreSQL), which a serializer built from the field does not apply
"""
cls._meta.get_field("archive_serial_number").run_validators(value)
def get_effective_barcodes(self) -> list["DocumentBarcode"]:
"""
Returns the stored barcodes for the document, like
+6
View File
@@ -1152,6 +1152,11 @@ class DocumentSerializer(
data["created"] = parsed.astimezone().date()
return super().to_internal_value(data)
def validate_archive_serial_number(self, value):
if value is not None:
Document.validate_archive_serial_number(value)
return value
def validate(self, attrs):
if (
"archive_serial_number" in attrs
@@ -2407,6 +2412,7 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
required=False,
min_value=Document.ARCHIVE_SERIAL_NUMBER_MIN,
max_value=Document.ARCHIVE_SERIAL_NUMBER_MAX,
validators=[Document.validate_archive_serial_number],
)
# Accept either a list of custom field ids or a dict mapping id -> value
@@ -0,0 +1,97 @@
from collections.abc import Generator
import pytest
from django.core.exceptions import ValidationError
from django.db import connection
from pytest_mock import MockerFixture
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import Document
from paperless_testing.factories import DocumentFactory
SIGNED_INT32_RANGE = (-(2**31), 2**31 - 1)
@pytest.fixture
def signed_int32_column(mocker: MockerFixture) -> Generator[None, None, None]:
"""
Make the database report a signed 32 bit integer range for the column, as
PostgreSQL does. Django caches the validators of a field, so the cache is
dropped before and after.
"""
field = Document._meta.get_field("archive_serial_number")
field.__dict__.pop("validators", None)
mocker.patch.object(
connection.ops,
"integer_field_range",
return_value=SIGNED_INT32_RANGE,
)
yield
field.__dict__.pop("validators", None)
class TestArchiveSerialNumberRange:
@pytest.mark.usefixtures("signed_int32_column")
@pytest.mark.parametrize("value", [2**31, 3_000_000_000, 0xFF_FF_FF_FF])
def test_value_beyond_the_column_is_rejected(self, value: int) -> None:
"""
GIVEN:
- A database whose integer column stops at 2**31 - 1
WHEN:
- An ASN inside the fixed range but beyond the column is validated
THEN:
- It is rejected, the database would have raised an error
"""
with pytest.raises(ValidationError):
Document.validate_archive_serial_number(value)
@pytest.mark.usefixtures("signed_int32_column")
@pytest.mark.parametrize("value", [0, 1, 2**31 - 1])
def test_value_within_the_column_is_accepted(self, value: int) -> None:
"""
GIVEN:
- A database whose integer column stops at 2**31 - 1
WHEN:
- An ASN inside the column is validated
THEN:
- It is accepted
"""
Document.validate_archive_serial_number(value)
@pytest.mark.parametrize("value", [-1, 0xFF_FF_FF_FF + 1])
def test_value_outside_the_fixed_range_is_rejected(self, value: int) -> None:
"""
GIVEN:
- The fixed ASN range
WHEN:
- A value outside of it is validated
THEN:
- It is rejected whatever the database
"""
with pytest.raises(ValidationError):
Document.validate_archive_serial_number(value)
@pytest.mark.usefixtures("signed_int32_column")
def test_api_answers_400_for_a_value_beyond_the_column(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- A document and a database whose integer column stops at 2**31 - 1
WHEN:
- The document is patched with a larger ASN
THEN:
- The response is a 400 naming the field, not a database error
"""
document = DocumentFactory.create()
response = admin_client.patch(
f"/api/documents/{document.pk}/",
{"archive_serial_number": 3_000_000_000},
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "archive_serial_number" in response.data