Skip to content

Commit

Permalink
Fix GetOrCreateSerializerMixin not working with pulp_domain
Browse files Browse the repository at this point in the history
  • Loading branch information
gerrod3 committed Nov 26, 2024
1 parent c2b648e commit cf42aea
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed `GetOrCreateSerializerMixin` not accepting pulp_domain for the natural key creation.
4 changes: 4 additions & 0 deletions pulpcore/app/serializers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,8 @@ def get_or_create(cls, natural_key, default_values=None):
if default_values:
data.update(default_values)
data.update(natural_key)
if "pulp_domain" in natural_key:
del data["pulp_domain"]
serializer = cls(data=data)
try:
serializer.is_valid(raise_exception=True)
Expand All @@ -402,6 +404,8 @@ def get_or_create(cls, natural_key, default_values=None):
# validation failed with 400 'unique' error code only
result = cls.Meta.model.objects.get(**natural_key)
try:
if "pulp_domain" in natural_key:
serializer.validated_data["pulp_domain"] = natural_key["pulp_domain"]
result = result or serializer.create(serializer.validated_data)
except IntegrityError:
# recover from a race condition, where another thread just created the object
Expand Down
32 changes: 31 additions & 1 deletion pulpcore/tests/unit/serializers/test_base.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import pytest

from django.test import TestCase
from rest_framework import serializers

from pulpcore.app.serializers import validate_unknown_fields
from pulpcore.app.serializers import (
validate_unknown_fields,
RBACContentGuardSerializer,
GetOrCreateSerializerMixin,
)
from pulpcore.app.models import RBACContentGuard
from pulpcore.app.util import get_domain


def test_unknown_field():
Expand Down Expand Up @@ -108,3 +115,26 @@ def test_ignored_fields_no_side_effects():
initial_data = {"field1": 1, "csrfmiddlewaretoken": 2}
defined_fields = {"field1": 1}
validate_unknown_fields(initial_data, defined_fields)


class TestGetOrCreateSerializerMixin(TestCase):
"""
Test's get_or_create method on the mixin.
"""
class GuardSerializer(GetOrCreateSerializerMixin, RBACContentGuardSerializer):
pass

def setUp(self):
self.guard, _ = RBACContentGuard.objects.get_or_create(name="test")

def test_get(self):
natural_key = {"name": "test", "pulp_domain": get_domain()}
guard = self.GuardSerializer.get_or_create(natural_key)
assert guard.pk == self.guard.pk

def test_create(self):
natural_key = {"name": "test2", "pulp_domain": get_domain()}
default_data = {"description": "hello"}
guard = self.GuardSerializer.get_or_create(natural_key, default_data)
assert guard.pk != self.guard.pk
assert guard.description == default_data["description"]

0 comments on commit cf42aea

Please sign in to comment.