From da058724149c92c4cc933035e186265c3f28d72c Mon Sep 17 00:00:00 2001 From: therealjozbert Date: Tue, 9 Dec 2025 14:09:09 +0300 Subject: [PATCH] Add tests for .data access before .is_valid() in relation serializers - Add test_data_cannot_be_accessed_prior_to_is_valid to HyperlinkedManyToManyTests - Add test_data_cannot_be_accessed_prior_to_is_valid to PKManyToManyTests - Remove TODO comments that were addressed - Ensures AssertionError is raised when accessing .data before validation Fixes TODO items in: - tests/test_relations_hyperlink.py (line 71) - tests/test_relations_pk.py (line 97) --- tests/test_relations_hyperlink.py | 11 ++++++++++- tests/test_relations_pk.py | 11 +++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/tests/test_relations_hyperlink.py b/tests/test_relations_hyperlink.py index 77e4cd95f6..f48bb98af8 100644 --- a/tests/test_relations_hyperlink.py +++ b/tests/test_relations_hyperlink.py @@ -1,3 +1,4 @@ +import pytest from django.test import TestCase, override_settings from django.urls import path @@ -68,7 +69,6 @@ class Meta: fields = ('url', 'name', 'nullable_source') -# TODO: Add test that .data cannot be accessed prior to .is_valid @override_settings(ROOT_URLCONF='tests.test_relations_hyperlink') class HyperlinkedManyToManyTests(TestCase): def setUp(self): @@ -193,6 +193,15 @@ def test_reverse_many_to_many_create(self): ] assert serializer.data == expected + def test_data_cannot_be_accessed_prior_to_is_valid(self): + """Test that .data cannot be accessed prior to .is_valid for hyperlinked serializers.""" + serializer = ManyToManySourceSerializer( + data={'name': 'test-source', 'targets': ['http://testserver/manytomanytarget/1/']}, + context={'request': request} + ) + with pytest.raises(AssertionError): + serializer.data + @override_settings(ROOT_URLCONF='tests.test_relations_hyperlink') class HyperlinkedForeignKeyTests(TestCase): diff --git a/tests/test_relations_pk.py b/tests/test_relations_pk.py index 14513f2bb2..3ca3726e24 100644 --- a/tests/test_relations_pk.py +++ b/tests/test_relations_pk.py @@ -1,3 +1,4 @@ +import pytest from django.test import TestCase from rest_framework import serializers @@ -94,8 +95,6 @@ class Meta: fields = '__all__' -# TODO: Add test that .data cannot be accessed prior to .is_valid - class PKManyToManyTests(TestCase): def setUp(self): for idx in range(1, 4): @@ -218,6 +217,14 @@ def test_reverse_many_to_many_create(self): ] assert serializer.data == expected + def test_data_cannot_be_accessed_prior_to_is_valid(self): + """Test that .data cannot be accessed prior to .is_valid for primary key serializers.""" + serializer = ManyToManySourceSerializer( + data={'name': 'test-source', 'targets': [1]} + ) + with pytest.raises(AssertionError): + serializer.data + class PKForeignKeyTests(TestCase): def setUp(self):