| 1 |
from django.core.exceptions import ImproperlyConfigured |
| 2 |
|
| 3 |
import pytest |
| 4 |
|
| 5 |
try: |
| 6 |
from rest_framework import serializers |
| 7 |
from rest_framework.test import APIClient |
| 8 |
|
| 9 |
from polymorphic.contrib.drf.serializers import PolymorphicSerializer |
| 10 |
from .serializers import ( |
| 11 |
BlogBaseSerializer, |
| 12 |
BlogOneSerializer, |
| 13 |
BlogPolymorphicSerializer, |
| 14 |
) |
| 15 |
|
| 16 |
from .models import ( |
| 17 |
BlogBase, |
| 18 |
BlogOne, |
| 19 |
BlogTwo, |
| 20 |
Project, |
| 21 |
ArtProject, |
| 22 |
ResearchProject, |
| 23 |
) |
| 24 |
except ImportError: |
| 25 |
pytest.skip("djangorestframework is not installed", allow_module_level=True) |
| 26 |
|
| 27 |
|
| 28 |
pytestmark = pytest.mark.django_db |
| 29 |
|
| 30 |
|
| 31 |
class TestPolymorphicSerializer: |
| 32 |
def test_model_serializer_mapping_is_none(self): |
| 33 |
class EmptyPolymorphicSerializer(PolymorphicSerializer): |
| 34 |
pass |
| 35 |
|
| 36 |
with pytest.raises(ImproperlyConfigured) as excinfo: |
| 37 |
EmptyPolymorphicSerializer() |
| 38 |
|
| 39 |
assert str(excinfo.value) == ( |
| 40 |
"`EmptyPolymorphicSerializer` is missing a " |
| 41 |
"`EmptyPolymorphicSerializer.model_serializer_mapping` attribute" |
| 42 |
) |
| 43 |
|
| 44 |
def test_resource_type_field_name_is_not_string(self, mocker): |
| 45 |
class NotStringPolymorphicSerializer(PolymorphicSerializer): |
| 46 |
model_serializer_mapping = mocker.MagicMock |
| 47 |
resource_type_field_name = 1 |
| 48 |
|
| 49 |
with pytest.raises(ImproperlyConfigured) as excinfo: |
| 50 |
NotStringPolymorphicSerializer() |
| 51 |
|
| 52 |
assert str(excinfo.value) == ( |
| 53 |
"`NotStringPolymorphicSerializer.resource_type_field_name` must be a string" |
| 54 |
) |
| 55 |
|
| 56 |
def test_each_serializer_has_context(self, mocker): |
| 57 |
context = mocker.MagicMock() |
| 58 |
serializer = BlogPolymorphicSerializer(context=context) |
| 59 |
for inner_serializer in serializer.model_serializer_mapping.values(): |
| 60 |
assert inner_serializer.context == context |
| 61 |
|
| 62 |
def test_non_callable_serializer_in_mapping(self): |
| 63 |
# Test the case where serializer is already instantiated (not callable) |
| 64 |
# This tests the else branch of the callable(serializer) check |
| 65 |
|
| 66 |
# Create an already-instantiated serializer |
| 67 |
blog_base_serializer_instance = BlogBaseSerializer() |
| 68 |
|
| 69 |
class TestPolymorphicSerializer(PolymorphicSerializer): |
| 70 |
model_serializer_mapping = { |
| 71 |
BlogBase: blog_base_serializer_instance, # Already an instance |
| 72 |
BlogOne: BlogOneSerializer, # Still a class (callable) |
| 73 |
} |
| 74 |
|
| 75 |
serializer = TestPolymorphicSerializer() |
| 76 |
|
| 77 |
# The instance should be used directly without re-instantiation |
| 78 |
assert ( |
| 79 |
serializer.model_serializer_mapping[BlogBase] |
| 80 |
is blog_base_serializer_instance |
| 81 |
) |
| 82 |
|
| 83 |
# The callable should be instantiated |
| 84 |
assert isinstance( |
| 85 |
serializer.model_serializer_mapping[BlogOne], BlogOneSerializer |
| 86 |
) |
| 87 |
assert ( |
| 88 |
serializer.model_serializer_mapping[BlogOne] |
| 89 |
is not BlogOneSerializer |
| 90 |
) |
| 91 |
|
| 92 |
# Both should be in resource_type_model_mapping |
| 93 |
assert serializer.resource_type_model_mapping["BlogBase"] == BlogBase |
| 94 |
assert serializer.resource_type_model_mapping["BlogOne"] == BlogOne |
| 95 |
|
| 96 |
# Now test that serialization actually works with the non-callable serializer |
| 97 |
base_instance = BlogBase.objects.create(name="base", slug="base-slug") |
| 98 |
one_instance = BlogOne.objects.create( |
| 99 |
name="one", slug="one-slug", info="info" |
| 100 |
) |
| 101 |
|
| 102 |
# Serialize BlogBase (using the pre-instantiated serializer) |
| 103 |
base_serializer = TestPolymorphicSerializer(base_instance) |
| 104 |
base_data = base_serializer.data |
| 105 |
assert base_data == { |
| 106 |
"name": "base", |
| 107 |
"slug": "base-slug", |
| 108 |
"resourcetype": "BlogBase", |
| 109 |
} |
| 110 |
|
| 111 |
# Serialize BlogOne (using the callable serializer that was instantiated) |
| 112 |
one_serializer = TestPolymorphicSerializer(one_instance) |
| 113 |
one_data = one_serializer.data |
| 114 |
assert one_data == { |
| 115 |
"name": "one", |
| 116 |
"slug": "one-slug", |
| 117 |
"info": "info", |
| 118 |
"resourcetype": "BlogOne", |
| 119 |
} |
| 120 |
|
| 121 |
# Test serialization of multiple instances (many=True) |
| 122 |
instances = [base_instance, one_instance] |
| 123 |
many_serializer = TestPolymorphicSerializer(instances, many=True) |
| 124 |
many_data = many_serializer.data |
| 125 |
assert len(many_data) == 2 |
| 126 |
assert many_data[0]["resourcetype"] == "BlogBase" |
| 127 |
assert many_data[1]["resourcetype"] == "BlogOne" |
| 128 |
assert many_data[0]["name"] == "base" |
| 129 |
assert many_data[1]["name"] == "one" |
| 130 |
assert many_data[1]["info"] == "info" |
| 131 |
|
| 132 |
def test_serialize(self): |
| 133 |
instance = BlogBase.objects.create(name="blog", slug="blog") |
| 134 |
serializer = BlogPolymorphicSerializer(instance) |
| 135 |
assert serializer.data == { |
| 136 |
"name": "blog", |
| 137 |
"slug": "blog", |
| 138 |
"resourcetype": "BlogBase", |
| 139 |
} |
| 140 |
|
| 141 |
def test_deserialize(self): |
| 142 |
data = { |
| 143 |
"name": "blog", |
| 144 |
"slug": "blog", |
| 145 |
"resourcetype": "BlogBase", |
| 146 |
} |
| 147 |
serializers = BlogPolymorphicSerializer(data=data) |
| 148 |
assert serializers.is_valid() |
| 149 |
assert serializers.data == data |
| 150 |
|
| 151 |
def test_deserialize_with_invalid_resourcetype(self): |
| 152 |
data = { |
| 153 |
"name": "blog", |
| 154 |
"resourcetype": "Invalid", |
| 155 |
} |
| 156 |
serializers = BlogPolymorphicSerializer(data=data) |
| 157 |
assert not serializers.is_valid() |
| 158 |
|
| 159 |
def test_create(self): |
| 160 |
data = [ |
| 161 |
{"name": "a", "slug": "a", "resourcetype": "BlogBase"}, |
| 162 |
{ |
| 163 |
"name": "b", |
| 164 |
"slug": "b", |
| 165 |
"info": "info", |
| 166 |
"resourcetype": "BlogOne", |
| 167 |
}, |
| 168 |
{"name": "c", "slug": "c", "resourcetype": "BlogTwo"}, |
| 169 |
] |
| 170 |
serializer = BlogPolymorphicSerializer(data=data, many=True) |
| 171 |
assert serializer.is_valid() |
| 172 |
|
| 173 |
instances = serializer.save() |
| 174 |
assert len(instances) == 3 |
| 175 |
assert [item.name for item in instances] == ["a", "b", "c"] |
| 176 |
|
| 177 |
assert BlogBase.objects.count() == 3 |
| 178 |
assert BlogBase.objects.instance_of(BlogOne).count() == 1 |
| 179 |
assert BlogBase.objects.instance_of(BlogTwo).count() == 1 |
| 180 |
|
| 181 |
assert serializer.data == data |
| 182 |
|
| 183 |
def test_update(self): |
| 184 |
instance = BlogBase.objects.create(name="blog", slug="blog") |
| 185 |
data = { |
| 186 |
"name": "new-blog", |
| 187 |
"slug": "blog", |
| 188 |
"resourcetype": "BlogBase", |
| 189 |
} |
| 190 |
|
| 191 |
serializer = BlogPolymorphicSerializer(instance, data=data) |
| 192 |
assert serializer.is_valid() |
| 193 |
|
| 194 |
serializer.save() |
| 195 |
assert instance.name == "new-blog" |
| 196 |
assert instance.slug == "blog" |
| 197 |
|
| 198 |
def test_partial_update(self): |
| 199 |
instance = BlogBase.objects.create(name="blog", slug="blog") |
| 200 |
data = {"name": "new-blog", "resourcetype": "BlogBase"} |
| 201 |
|
| 202 |
serializer = BlogPolymorphicSerializer( |
| 203 |
instance, data=data, partial=True |
| 204 |
) |
| 205 |
assert serializer.is_valid() |
| 206 |
|
| 207 |
serializer.save() |
| 208 |
assert instance.name == "new-blog" |
| 209 |
assert instance.slug == "blog" |
| 210 |
|
| 211 |
def test_partial_update_without_resourcetype(self): |
| 212 |
instance = BlogBase.objects.create(name="blog", slug="blog") |
| 213 |
data = {"name": "new-blog"} |
| 214 |
|
| 215 |
serializer = BlogPolymorphicSerializer( |
| 216 |
instance, data=data, partial=True |
| 217 |
) |
| 218 |
assert serializer.is_valid() |
| 219 |
|
| 220 |
serializer.save() |
| 221 |
assert instance.name == "new-blog" |
| 222 |
assert instance.slug == "blog" |
| 223 |
|
| 224 |
def test_object_validators_are_applied(self): |
| 225 |
data = { |
| 226 |
"name": "test-blog", |
| 227 |
"slug": "test-blog-slug", |
| 228 |
"info": "test-blog-info", |
| 229 |
"about": "test-blog-about", |
| 230 |
"resourcetype": "BlogThree", |
| 231 |
} |
| 232 |
serializer = BlogPolymorphicSerializer(data=data) |
| 233 |
assert serializer.is_valid() |
| 234 |
serializer.save() |
| 235 |
|
| 236 |
data["slug"] = "test-blog-slug-new" |
| 237 |
duplicate = BlogPolymorphicSerializer(data=data) |
| 238 |
|
| 239 |
assert not duplicate.is_valid() |
| 240 |
assert "non_field_errors" in duplicate.errors |
| 241 |
err = duplicate.errors["non_field_errors"] |
| 242 |
|
| 243 |
assert err == ["The fields info, about must make a unique set."] |
| 244 |
|
| 245 |
def test_to_internal_value_with_valid_data(self): |
| 246 |
data = { |
| 247 |
"name": "blog", |
| 248 |
"slug": "blog", |
| 249 |
"resourcetype": "BlogBase", |
| 250 |
} |
| 251 |
serializer = BlogPolymorphicSerializer(data=data) |
| 252 |
internal_value = serializer.to_internal_value(data) |
| 253 |
|
| 254 |
assert internal_value["name"] == "blog" |
| 255 |
assert internal_value["slug"] == "blog" |
| 256 |
assert internal_value["resourcetype"] == "BlogBase" |
| 257 |
|
| 258 |
def test_to_internal_value_with_missing_resourcetype(self): |
| 259 |
from rest_framework.exceptions import ValidationError |
| 260 |
|
| 261 |
data = { |
| 262 |
"name": "blog", |
| 263 |
"slug": "blog", |
| 264 |
} |
| 265 |
serializer = BlogPolymorphicSerializer(data=data) |
| 266 |
|
| 267 |
with pytest.raises(ValidationError) as excinfo: |
| 268 |
serializer.to_internal_value(data) |
| 269 |
|
| 270 |
assert "resourcetype" in excinfo.value.detail |
| 271 |
assert excinfo.value.detail["resourcetype"] == "This field is required" |
| 272 |
|
| 273 |
def test_to_internal_value_with_partial_update(self): |
| 274 |
instance = BlogBase.objects.create(name="blog", slug="blog") |
| 275 |
data = {"name": "new-blog"} |
| 276 |
|
| 277 |
serializer = BlogPolymorphicSerializer( |
| 278 |
instance, data=data, partial=True |
| 279 |
) |
| 280 |
internal_value = serializer.to_internal_value(data) |
| 281 |
|
| 282 |
assert internal_value["name"] == "new-blog" |
| 283 |
assert internal_value["resourcetype"] == "BlogBase" |
| 284 |
|
| 285 |
def test_get_serializer_from_model_or_instance_raises_keyerror(self): |
| 286 |
from polymorphic.models import PolymorphicModel |
| 287 |
|
| 288 |
# Create a model that is not in the mapping |
| 289 |
class UnmappedModel(PolymorphicModel): |
| 290 |
class Meta: |
| 291 |
app_label = "drf" |
| 292 |
|
| 293 |
serializer = BlogPolymorphicSerializer() |
| 294 |
|
| 295 |
with pytest.raises(KeyError) as excinfo: |
| 296 |
serializer._get_serializer_from_model_or_instance(UnmappedModel) |
| 297 |
|
| 298 |
assert "model_serializer_mapping" in str(excinfo.value) |
| 299 |
assert "UnmappedModel" in str(excinfo.value) |
| 300 |
|
| 301 |
def test_get_serializer_from_resource_type_keyerror_propagation(self): |
| 302 |
# This tests the case where _get_serializer_from_resource_type |
| 303 |
# successfully finds a resource_type in the mapping, but then |
| 304 |
# _get_serializer_from_model_or_instance raises a KeyError |
| 305 |
# when trying to find the serializer for that model. |
| 306 |
# |
| 307 |
# However, looking at the code, this scenario is actually not possible |
| 308 |
# in normal operation because resource_type_model_mapping and |
| 309 |
# model_serializer_mapping are populated together in __init__. |
| 310 |
# |
| 311 |
# The KeyError in _get_serializer_from_resource_type would only |
| 312 |
# occur if the resource_type is not in resource_type_model_mapping, |
| 313 |
# which is already caught and converted to ValidationError at line 149. |
| 314 |
# |
| 315 |
# So we'll test that the ValidationError is raised properly instead. |
| 316 |
from rest_framework.exceptions import ValidationError |
| 317 |
|
| 318 |
data = { |
| 319 |
"name": "blog", |
| 320 |
"slug": "blog", |
| 321 |
"resourcetype": "InvalidResourceType", |
| 322 |
} |
| 323 |
serializer = BlogPolymorphicSerializer(data=data) |
| 324 |
|
| 325 |
with pytest.raises(ValidationError) as excinfo: |
| 326 |
serializer._get_serializer_from_resource_type("InvalidResourceType") |
| 327 |
|
| 328 |
assert "resourcetype" in excinfo.value.detail |
| 329 |
assert "Invalid resourcetype" in str( |
| 330 |
excinfo.value.detail["resourcetype"] |
| 331 |
) |
| 332 |
|
| 333 |
def test_validate_method_modifications_are_preserved(self): |
| 334 |
"""Test that modifications made in child serializer's validate() method are preserved.""" |
| 335 |
# Track whether the extra_field was present during create |
| 336 |
created_with_extra_field = [] |
| 337 |
|
| 338 |
# Create a custom serializer that adds a field in validate() |
| 339 |
class CustomBlogOneSerializer(BlogOneSerializer): |
| 340 |
extra_field = serializers.CharField(required=False, allow_null=True) |
| 341 |
|
| 342 |
class Meta(BlogOneSerializer.Meta): |
| 343 |
fields = BlogOneSerializer.Meta.fields + ("extra_field",) |
| 344 |
|
| 345 |
def validate(self, attrs): |
| 346 |
attrs = super().validate(attrs) |
| 347 |
# Simulate adding data in validate(), like adding the current user |
| 348 |
attrs["extra_field"] = "added_in_validate" |
| 349 |
return attrs |
| 350 |
|
| 351 |
def create(self, validated_data): |
| 352 |
# Record whether extra_field was in validated_data |
| 353 |
created_with_extra_field.append("extra_field" in validated_data) |
| 354 |
# Remove extra_field before creating the model instance |
| 355 |
validated_data.pop("extra_field", None) |
| 356 |
return super().create(validated_data) |
| 357 |
|
| 358 |
class CustomBlogPolymorphicSerializer(PolymorphicSerializer): |
| 359 |
model_serializer_mapping = { |
| 360 |
BlogBase: BlogBaseSerializer, |
| 361 |
BlogOne: CustomBlogOneSerializer, |
| 362 |
} |
| 363 |
|
| 364 |
# Create data without the extra_field |
| 365 |
data = { |
| 366 |
"name": "test", |
| 367 |
"slug": "test-slug", |
| 368 |
"info": "test-info", |
| 369 |
"resourcetype": "BlogOne", |
| 370 |
} |
| 371 |
|
| 372 |
serializer = CustomBlogPolymorphicSerializer(data=data) |
| 373 |
assert serializer.is_valid(), f"Validation errors: {serializer.errors}" |
| 374 |
|
| 375 |
# Verify that the extra_field added in validate() is in validated_data |
| 376 |
assert "extra_field" in serializer.validated_data |
| 377 |
assert serializer.validated_data["extra_field"] == "added_in_validate" |
| 378 |
|
| 379 |
# Verify that resource_type field is still preserved in parent's validated_data |
| 380 |
assert "resourcetype" in serializer.validated_data |
| 381 |
assert serializer.validated_data["resourcetype"] == "BlogOne" |
| 382 |
|
| 383 |
# Save and verify that the field was present during create |
| 384 |
# Note: This would fail before the fix because the parent's _validated_data |
| 385 |
# wasn't updated with the child's _validated_data after calling child.is_valid() |
| 386 |
instance = serializer.save() |
| 387 |
|
| 388 |
# Verify that extra_field was indeed present when create() was called |
| 389 |
assert created_with_extra_field == [True], ( |
| 390 |
"extra_field should have been in validated_data when create() was called" |
| 391 |
) |
| 392 |
|
| 393 |
# Verify the instance was created successfully |
| 394 |
assert instance.name == "test" |
| 395 |
assert instance.slug == "test-slug" |
| 396 |
assert instance.info == "test-info" |
| 397 |
|
| 398 |
|
| 399 |
class TestProjectViewSet: |
| 400 |
"""Test the example Project ViewSet with polymorphic serializers.""" |
| 401 |
|
| 402 |
@pytest.fixture |
| 403 |
def client(self): |
| 404 |
return APIClient() |
| 405 |
|
| 406 |
@pytest.fixture |
| 407 |
def base_project(self): |
| 408 |
return Project.objects.create(topic="General Project") |
| 409 |
|
| 410 |
@pytest.fixture |
| 411 |
def art_project(self): |
| 412 |
return ArtProject.objects.create(topic="Art", artist="Picasso") |
| 413 |
|
| 414 |
@pytest.fixture |
| 415 |
def research_project(self): |
| 416 |
return ResearchProject.objects.create( |
| 417 |
topic="Research", supervisor="Dr. Smith" |
| 418 |
) |
| 419 |
|
| 420 |
def test_list_projects( |
| 421 |
self, client, base_project, art_project, research_project |
| 422 |
): |
| 423 |
response = client.get("/examples/integrations/drf/projects/") |
| 424 |
assert response.status_code == 200 |
| 425 |
assert len(response.data) == 3 |
| 426 |
|
| 427 |
topics = {item["topic"] for item in response.data} |
| 428 |
assert topics == {"General Project", "Art", "Research"} |
| 429 |
|
| 430 |
def test_retrieve_base_project(self, client, base_project): |
| 431 |
response = client.get( |
| 432 |
f"/examples/integrations/drf/projects/{base_project.pk}/" |
| 433 |
) |
| 434 |
assert response.status_code == 200 |
| 435 |
assert response.data["topic"] == "General Project" |
| 436 |
assert response.data["resourcetype"] == "Project" |
| 437 |
|
| 438 |
def test_retrieve_art_project(self, client, art_project): |
| 439 |
response = client.get( |
| 440 |
f"/examples/integrations/drf/projects/{art_project.pk}/" |
| 441 |
) |
| 442 |
assert response.status_code == 200 |
| 443 |
assert response.data["topic"] == "Art" |
| 444 |
assert response.data["artist"] == "Picasso" |
| 445 |
assert response.data["resourcetype"] == "ArtProject" |
| 446 |
assert "url" in response.data |
| 447 |
|
| 448 |
def test_retrieve_research_project(self, client, research_project): |
| 449 |
response = client.get( |
| 450 |
f"/examples/integrations/drf/projects/{research_project.pk}/" |
| 451 |
) |
| 452 |
assert response.status_code == 200 |
| 453 |
assert response.data["topic"] == "Research" |
| 454 |
assert response.data["supervisor"] == "Dr. Smith" |
| 455 |
assert response.data["resourcetype"] == "ResearchProject" |
| 456 |
|
| 457 |
def test_create_base_project(self, client): |
| 458 |
data = {"topic": "New Project", "resourcetype": "Project"} |
| 459 |
response = client.post( |
| 460 |
"/examples/integrations/drf/projects/", data, format="json" |
| 461 |
) |
| 462 |
assert response.status_code == 201 |
| 463 |
assert response.data["topic"] == "New Project" |
| 464 |
assert response.data["resourcetype"] == "Project" |
| 465 |
|
| 466 |
assert Project.objects.count() == 1 |
| 467 |
project = Project.objects.first() |
| 468 |
assert project.topic == "New Project" |
| 469 |
assert type(project) is Project |
| 470 |
|
| 471 |
def test_create_art_project(self, client): |
| 472 |
data = { |
| 473 |
"topic": "Sculpture", |
| 474 |
"artist": "Michelangelo", |
| 475 |
"resourcetype": "ArtProject", |
| 476 |
} |
| 477 |
response = client.post( |
| 478 |
"/examples/integrations/drf/projects/", data, format="json" |
| 479 |
) |
| 480 |
assert response.status_code == 201 |
| 481 |
assert response.data["topic"] == "Sculpture" |
| 482 |
assert response.data["artist"] == "Michelangelo" |
| 483 |
assert response.data["resourcetype"] == "ArtProject" |
| 484 |
assert "url" in response.data |
| 485 |
|
| 486 |
assert Project.objects.count() == 1 |
| 487 |
project = Project.objects.first() |
| 488 |
assert isinstance(project, ArtProject) |
| 489 |
assert project.artist == "Michelangelo" |
| 490 |
|
| 491 |
def test_create_research_project(self, client): |
| 492 |
data = { |
| 493 |
"topic": "AI Research", |
| 494 |
"supervisor": "Dr. Johnson", |
| 495 |
"resourcetype": "ResearchProject", |
| 496 |
} |
| 497 |
response = client.post( |
| 498 |
"/examples/integrations/drf/projects/", data, format="json" |
| 499 |
) |
| 500 |
assert response.status_code == 201 |
| 501 |
assert response.data["topic"] == "AI Research" |
| 502 |
assert response.data["supervisor"] == "Dr. Johnson" |
| 503 |
assert response.data["resourcetype"] == "ResearchProject" |
| 504 |
|
| 505 |
assert Project.objects.count() == 1 |
| 506 |
project = Project.objects.first() |
| 507 |
assert isinstance(project, ResearchProject) |
| 508 |
assert project.supervisor == "Dr. Johnson" |
| 509 |
|
| 510 |
def test_update_project(self, client, base_project): |
| 511 |
data = {"topic": "Updated Project", "resourcetype": "Project"} |
| 512 |
response = client.put( |
| 513 |
f"/examples/integrations/drf/projects/{base_project.pk}/", |
| 514 |
data, |
| 515 |
format="json", |
| 516 |
) |
| 517 |
assert response.status_code == 200 |
| 518 |
assert response.data["topic"] == "Updated Project" |
| 519 |
|
| 520 |
base_project.refresh_from_db() |
| 521 |
assert base_project.topic == "Updated Project" |
| 522 |
|
| 523 |
def test_partial_update_art_project(self, client, art_project): |
| 524 |
data = {"artist": "Van Gogh"} |
| 525 |
response = client.patch( |
| 526 |
f"/examples/integrations/drf/projects/{art_project.pk}/", |
| 527 |
data, |
| 528 |
format="json", |
| 529 |
) |
| 530 |
assert response.status_code == 200 |
| 531 |
assert response.data["artist"] == "Van Gogh" |
| 532 |
assert response.data["topic"] == "Art" # unchanged |
| 533 |
|
| 534 |
art_project.refresh_from_db() |
| 535 |
assert art_project.artist == "Van Gogh" |
| 536 |
assert art_project.topic == "Art" |
| 537 |
|
| 538 |
def test_partial_update_research_project(self, client, research_project): |
| 539 |
data = {"supervisor": "Dr. Williams"} |
| 540 |
response = client.patch( |
| 541 |
f"/examples/integrations/drf/projects/{research_project.pk}/", |
| 542 |
data, |
| 543 |
format="json", |
| 544 |
) |
| 545 |
assert response.status_code == 200 |
| 546 |
assert response.data["supervisor"] == "Dr. Williams" |
| 547 |
assert response.data["topic"] == "Research" # unchanged |
| 548 |
|
| 549 |
research_project.refresh_from_db() |
| 550 |
assert research_project.supervisor == "Dr. Williams" |
| 551 |
assert research_project.topic == "Research" |
| 552 |
|
| 553 |
def test_delete_project(self, client, base_project): |
| 554 |
project_id = base_project.pk |
| 555 |
response = client.delete( |
| 556 |
f"/examples/integrations/drf/projects/{project_id}/" |
| 557 |
) |
| 558 |
assert response.status_code == 204 |
| 559 |
|
| 560 |
assert not Project.objects.filter(pk=project_id).exists() |
| 561 |
|
| 562 |
def test_create_with_invalid_resourcetype(self, client): |
| 563 |
data = {"topic": "Test", "resourcetype": "InvalidType"} |
| 564 |
response = client.post( |
| 565 |
"/examples/integrations/drf/projects/", data, format="json" |
| 566 |
) |
| 567 |
assert response.status_code == 400 |
| 568 |
|
| 569 |
|
| 570 |
class TestDjangoFiltersViewSet: |
| 571 |
"""Test django-filter integration with polymorphic models (issue #520).""" |
| 572 |
|
| 573 |
@pytest.fixture |
| 574 |
def client(self): |
| 575 |
return APIClient() |
| 576 |
|
| 577 |
@pytest.fixture |
| 578 |
def user(self, django_user_model): |
| 579 |
return django_user_model.objects.create_user( |
| 580 |
username="testuser", password="testpass" |
| 581 |
) |
| 582 |
|
| 583 |
@pytest.fixture |
| 584 |
def user_annotator(self, user): |
| 585 |
from .models import UserAnnotator |
| 586 |
|
| 587 |
return UserAnnotator.objects.create(user=user) |
| 588 |
|
| 589 |
@pytest.fixture |
| 590 |
def ai_annotator_gpt4(self): |
| 591 |
from .models import AiModelAnnotator |
| 592 |
|
| 593 |
return AiModelAnnotator.objects.create(ai_model="gpt-4", version="1.0") |
| 594 |
|
| 595 |
@pytest.fixture |
| 596 |
def ai_annotator_claude(self): |
| 597 |
from .models import AiModelAnnotator |
| 598 |
|
| 599 |
return AiModelAnnotator.objects.create( |
| 600 |
ai_model="claude-3", version="2.0" |
| 601 |
) |
| 602 |
|
| 603 |
@pytest.fixture |
| 604 |
def data_by_user(self, user_annotator): |
| 605 |
from .models import Data |
| 606 |
|
| 607 |
return Data.objects.create(annotator=user_annotator) |
| 608 |
|
| 609 |
@pytest.fixture |
| 610 |
def data_by_gpt4(self, ai_annotator_gpt4): |
| 611 |
from .models import Data |
| 612 |
|
| 613 |
return Data.objects.create(annotator=ai_annotator_gpt4) |
| 614 |
|
| 615 |
@pytest.fixture |
| 616 |
def data_by_claude(self, ai_annotator_claude): |
| 617 |
from .models import Data |
| 618 |
|
| 619 |
return Data.objects.create(annotator=ai_annotator_claude) |
| 620 |
|
| 621 |
def test_list_all_annotations( |
| 622 |
self, client, data_by_user, data_by_gpt4, data_by_claude |
| 623 |
): |
| 624 |
"""Test listing all annotation data without filters.""" |
| 625 |
response = client.get("/examples/integrations/drf/annotations/") |
| 626 |
assert response.status_code == 200 |
| 627 |
assert len(response.data) == 3 |
| 628 |
|
| 629 |
def test_filter_by_annotator( |
| 630 |
self, client, data_by_user, data_by_gpt4, ai_annotator_gpt4 |
| 631 |
): |
| 632 |
"""Test filtering by annotator ID.""" |
| 633 |
response = client.get( |
| 634 |
f"/examples/integrations/drf/annotations/?annotator={ai_annotator_gpt4.pk}" |
| 635 |
) |
| 636 |
assert response.status_code == 200 |
| 637 |
assert len(response.data) == 1 |
| 638 |
assert response.data[0]["id"] == data_by_gpt4.pk |
| 639 |
|
| 640 |
def test_filter_by_ai_model( |
| 641 |
self, client, data_by_user, data_by_gpt4, data_by_claude |
| 642 |
): |
| 643 |
"""Test filtering by annotator__ai_model field (issue #520).""" |
| 644 |
# This is the key test - filtering by a field on the polymorphic child model |
| 645 |
response = client.get( |
| 646 |
"/examples/integrations/drf/annotations/?annotator__ai_model=gpt-4" |
| 647 |
) |
| 648 |
assert response.status_code == 200 |
| 649 |
assert len(response.data) == 1 |
| 650 |
assert response.data[0]["id"] == data_by_gpt4.pk |
| 651 |
|
| 652 |
def test_filter_by_different_ai_model( |
| 653 |
self, client, data_by_user, data_by_gpt4, data_by_claude |
| 654 |
): |
| 655 |
"""Test filtering by a different AI model.""" |
| 656 |
response = client.get( |
| 657 |
"/examples/integrations/drf/annotations/?annotator__ai_model=claude-3" |
| 658 |
) |
| 659 |
assert response.status_code == 200 |
| 660 |
assert len(response.data) == 1 |
| 661 |
assert response.data[0]["id"] == data_by_claude.pk |
| 662 |
|
| 663 |
def test_filter_by_nonexistent_ai_model( |
| 664 |
self, client, data_by_user, data_by_gpt4, data_by_claude |
| 665 |
): |
| 666 |
"""Test filtering by an AI model that doesn't exist.""" |
| 667 |
response = client.get( |
| 668 |
"/examples/integrations/drf/annotations/?annotator__ai_model=nonexistent" |
| 669 |
) |
| 670 |
assert response.status_code == 200 |
| 671 |
assert len(response.data) == 0 |
| 672 |
|
| 673 |
def test_filter_excludes_non_ai_annotators( |
| 674 |
self, client, data_by_user, data_by_gpt4, data_by_claude |
| 675 |
): |
| 676 |
"""Test that filtering by ai_model excludes UserAnnotator instances.""" |
| 677 |
# When filtering by annotator__ai_model, only AiModelAnnotator results should be returned |
| 678 |
# UserAnnotator doesn't have ai_model field, so data_by_user should not appear |
| 679 |
response = client.get( |
| 680 |
"/examples/integrations/drf/annotations/?annotator__ai_model=gpt-4" |
| 681 |
) |
| 682 |
assert response.status_code == 200 |
| 683 |
assert len(response.data) == 1 |
| 684 |
# Verify the user-annotated data is not in results |
| 685 |
assert all(item["id"] != data_by_user.pk for item in response.data) |
| 686 |
|
| 687 |
def test_retrieve_annotation(self, client, data_by_gpt4): |
| 688 |
"""Test retrieving a single annotation.""" |
| 689 |
response = client.get( |
| 690 |
f"/examples/integrations/drf/annotations/{data_by_gpt4.pk}/" |
| 691 |
) |
| 692 |
assert response.status_code == 200 |
| 693 |
assert response.data["id"] == data_by_gpt4.pk |
| 694 |
|
| 695 |
def test_create_annotation_with_user_annotator( |
| 696 |
self, client, user_annotator |
| 697 |
): |
| 698 |
"""Test creating annotation data with a UserAnnotator.""" |
| 699 |
data = {"annotator": user_annotator.pk} |
| 700 |
response = client.post( |
| 701 |
"/examples/integrations/drf/annotations/", data, format="json" |
| 702 |
) |
| 703 |
assert response.status_code == 201 |
| 704 |
assert response.data["annotator"] == user_annotator.pk |
| 705 |
|
| 706 |
from .models import Data |
| 707 |
|
| 708 |
assert Data.objects.count() == 1 |
| 709 |
created = Data.objects.first() |
| 710 |
assert created.annotator.pk == user_annotator.pk |
| 711 |
|
| 712 |
def test_create_annotation_with_ai_annotator( |
| 713 |
self, client, ai_annotator_gpt4 |
| 714 |
): |
| 715 |
"""Test creating annotation data with an AiModelAnnotator.""" |
| 716 |
data = {"annotator": ai_annotator_gpt4.pk} |
| 717 |
response = client.post( |
| 718 |
"/examples/integrations/drf/annotations/", data, format="json" |
| 719 |
) |
| 720 |
assert response.status_code == 201 |
| 721 |
assert response.data["annotator"] == ai_annotator_gpt4.pk |
| 722 |
|
| 723 |
from .models import Data |
| 724 |
|
| 725 |
assert Data.objects.count() == 1 |
| 726 |
created = Data.objects.first() |
| 727 |
assert created.annotator.pk == ai_annotator_gpt4.pk |