Compare commits

..
4 changed files with 95 additions and 157 deletions

No files matched your search

+13 -18
View File
@@ -448,19 +448,7 @@ class OwnedObjectSerializer(
def validate_unique_together(self, validated_data, instance=None) -> None: def validate_unique_together(self, validated_data, instance=None) -> None:
# workaround for https://github.com/encode/django-rest-framework/issues/9358 # workaround for https://github.com/encode/django-rest-framework/issues/9358
if "name" not in self.Meta.fields: if "owner" in validated_data and "name" in self.Meta.fields:
return
if instance is not None:
owner = validated_data.get("owner", instance.owner)
if owner == instance.owner and (
validated_data.get("name", instance.name) == instance.name
):
# Nothing the constraint covers changes, and rows saved before it
# was enforced can already be duplicates
return
# An update that does not mention the owner keeps the current one
validated_data = {**validated_data, "owner": owner}
if "owner" in validated_data:
name = validated_data.get("name", instance.name if instance else None) name = validated_data.get("name", instance.name if instance else None)
objects = ( objects = (
self.Meta.model.objects.exclude(pk=instance.pk) self.Meta.model.objects.exclude(pk=instance.pk)
@@ -1342,6 +1330,11 @@ class SavedViewFilterRuleSerializer(serializers.ModelSerializer[SavedViewFilterR
class SavedViewSerializer(OwnedObjectSerializer): class SavedViewSerializer(OwnedObjectSerializer):
filter_rules = SavedViewFilterRuleSerializer(many=True) filter_rules = SavedViewFilterRuleSerializer(many=True)
display_fields = serializers.ListField(
child=serializers.CharField(),
required=False,
allow_null=True,
)
class Meta: class Meta:
model = SavedView model = SavedView
@@ -1483,11 +1476,13 @@ class SavedViewSerializer(OwnedObjectSerializer):
attrs = super().validate(attrs) attrs = super().validate(attrs)
if "display_fields" in attrs and attrs["display_fields"] is not None: if "display_fields" in attrs and attrs["display_fields"] is not None:
for field in attrs["display_fields"]: for field in attrs["display_fields"]:
if ( # i.e. 'custom_field_' followed by the id of a custom field
SavedView.DisplayFields.CUSTOM_FIELD[:-2] in field custom_field = re.fullmatch(
): # i.e. check for 'custom_field_' prefix rf"{re.escape(SavedView.DisplayFields.CUSTOM_FIELD[:-2])}(\d+)",
field_id = int(re.search(r"\d+", field)[0]) field,
if not CustomField.objects.filter(id=field_id).exists(): )
if custom_field:
if not CustomField.objects.filter(id=custom_field[1]).exists():
raise serializers.ValidationError( raise serializers.ValidationError(
f"Invalid field: {field}", f"Invalid field: {field}",
) )
@@ -0,0 +1,82 @@
import pytest
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import CustomField
from documents.models import SavedView
class TestSavedViewDisplayFields:
@pytest.mark.parametrize(
"value",
[
pytest.param(["custom_field_abc"], id="no-id"),
pytest.param(["custom_field_"], id="empty-id"),
pytest.param(["xcustom_field_{id}"], id="prefixed"),
pytest.param(["custom_field_{id}x"], id="suffixed"),
pytest.param([1], id="not-a-string"),
],
)
def test_malformed_display_fields_are_a_400(
self,
admin_client: APIClient,
admin_user: User,
value: object,
) -> None:
"""
GIVEN:
- A saved view and a custom field
WHEN:
- Its display fields are patched to something that names no field
THEN:
- The response is a 400 and the stored display fields are unchanged
"""
custom_field = CustomField.objects.create(
name="cf",
data_type=CustomField.FieldDataType.STRING,
)
view = SavedView.objects.create(
name="view",
owner=admin_user,
sort_field="created",
display_fields=["title"],
)
if isinstance(value, list):
value = [
item.format(id=custom_field.pk) if isinstance(item, str) else item
for item in value
]
response = admin_client.patch(
f"/api/saved_views/{view.pk}/",
{"display_fields": value},
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
view.refresh_from_db()
assert view.display_fields == ["title"]
def test_a_custom_field_display_name_is_accepted(
self,
admin_client: APIClient,
admin_user: User,
) -> None:
custom_field = CustomField.objects.create(
name="cf",
data_type=CustomField.FieldDataType.STRING,
)
view = SavedView.objects.create(
name="view",
owner=admin_user,
sort_field="created",
)
response = admin_client.patch(
f"/api/saved_views/{view.pk}/",
{"display_fields": ["title", f"custom_field_{custom_field.pk}"]},
format="json",
)
assert response.status_code == status.HTTP_200_OK
@@ -1,130 +0,0 @@
import pytest
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient
from paperless_testing.factories import CorrespondentFactory
from paperless_testing.factories import SavedViewFactory
class TestUniqueNameOnUpdate:
@pytest.mark.parametrize(
"owner_kind",
[
pytest.param("owned", id="owned"),
pytest.param("unowned", id="unowned"),
],
)
def test_patching_to_an_existing_name_is_a_400(
self,
admin_client: APIClient,
admin_user: User,
owner_kind: str,
) -> None:
"""
GIVEN:
- Two correspondents with the same owner, or none
WHEN:
- One is patched to the other's name without mentioning the owner
THEN:
- The response is a 400, as it is when creating a duplicate
"""
owner = admin_user if owner_kind == "owned" else None
CorrespondentFactory.create(name="taken", owner=owner)
other = CorrespondentFactory.create(name="free", owner=owner)
response = admin_client.patch(
f"/api/correspondents/{other.pk}/",
{"name": "taken"},
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
other.refresh_from_db()
assert other.name == "free"
def test_the_same_name_under_a_different_owner_is_allowed(
self,
admin_client: APIClient,
admin_user: User,
regular_user: User,
) -> None:
"""
GIVEN:
- Correspondents with the same name but different owners are allowed
WHEN:
- One correspondent is renamed to a name another owner already uses
THEN:
- The request succeeds
"""
CorrespondentFactory.create(name="shared name", owner=regular_user)
mine = CorrespondentFactory.create(name="mine", owner=admin_user)
response = admin_client.patch(
f"/api/correspondents/{mine.pk}/",
{"name": "shared name"},
format="json",
)
assert response.status_code == status.HTTP_200_OK
def test_saving_another_field_of_a_legacy_duplicate_still_works(
self,
admin_client: APIClient,
admin_user: User,
) -> None:
"""
GIVEN:
- Two saved views with the same name and owner, which the database
allows and an older version could create
WHEN:
- One is patched without changing its name, or with the name it already has
THEN:
- Both requests succeed, and renaming it to a free name works too
"""
view = SavedViewFactory.create(name="dup", owner=admin_user)
SavedViewFactory.create(name="dup", owner=admin_user)
other_field = admin_client.patch(
f"/api/saved_views/{view.pk}/",
{"sort_reverse": True},
format="json",
)
same_name = admin_client.patch(
f"/api/saved_views/{view.pk}/",
{"name": "dup", "sort_reverse": False},
format="json",
)
renamed = admin_client.patch(
f"/api/saved_views/{view.pk}/",
{"name": "unique now"},
format="json",
)
assert other_field.status_code == status.HTTP_200_OK
assert same_name.status_code == status.HTTP_200_OK
assert renamed.status_code == status.HTTP_200_OK
def test_a_new_duplicate_saved_view_name_is_a_400(
self,
admin_client: APIClient,
admin_user: User,
) -> None:
"""
GIVEN:
- Two saved views with different names
WHEN:
- One is renamed to the other's name
THEN:
- The response is a 400
"""
SavedViewFactory.create(name="taken", owner=admin_user)
other = SavedViewFactory.create(name="free", owner=admin_user)
response = admin_client.patch(
f"/api/saved_views/{other.pk}/",
{"name": "taken"},
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
-9
View File
@@ -16,7 +16,6 @@ from documents.models import MatchingModel
from documents.models import OcrTemplate from documents.models import OcrTemplate
from documents.models import OcrTemplateZone from documents.models import OcrTemplateZone
from documents.models import PaperlessTask from documents.models import PaperlessTask
from documents.models import SavedView
from documents.models import StoragePath from documents.models import StoragePath
from documents.models import Tag from documents.models import Tag
from paperless_testing.typed_factory import TypedModelFactory from paperless_testing.typed_factory import TypedModelFactory
@@ -144,11 +143,3 @@ class OcrTemplateZoneFactory(TypedModelFactory[OcrTemplateZone]):
y = 0 y = 0
width = 100 width = 100
height = 50 height = 50
class SavedViewFactory(TypedModelFactory[SavedView]):
class Meta:
model = SavedView
name = factory.Sequence(lambda n: f"Saved view {n}")
sort_field = "created"