From 22223da910b7365ff061855af62b2f24a5b6eccf Mon Sep 17 00:00:00 2001 From: Zach Aysan Date: Fri, 31 Jan 2025 09:44:32 -0500 Subject: [PATCH] fix: Force environments to be different names (#5058) --- api/environments/serializers.py | 9 +++++++ .../test_unit_environments_views.py | 27 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/api/environments/serializers.py b/api/environments/serializers.py index 70ac6f9be8cc..e00788ec5089 100644 --- a/api/environments/serializers.py +++ b/api/environments/serializers.py @@ -111,6 +111,15 @@ class CreateUpdateEnvironmentSerializer( invalid_plans = ("free",) field_names = ("minimum_change_request_approvals",) + class Meta(EnvironmentSerializerWithMetadata.Meta): + validators = [ + serializers.UniqueTogetherValidator( + queryset=EnvironmentSerializerWithMetadata.Meta.model.objects.all(), + fields=("name", "project"), + message="An environment with this name already exists.", + ) + ] + def get_subscription(self) -> typing.Optional[Subscription]: view = self.context["view"] diff --git a/api/tests/unit/environments/test_unit_environments_views.py b/api/tests/unit/environments/test_unit_environments_views.py index 41c39911b4e6..6c0d6f6e5eed 100644 --- a/api/tests/unit/environments/test_unit_environments_views.py +++ b/api/tests/unit/environments/test_unit_environments_views.py @@ -588,6 +588,33 @@ def test_should_create_environments( ).exists() +def test_environment_matches_existing_environment_name( + project: Project, + admin_client: APIClient, +) -> None: + # Given + url = reverse("api-v1:environments:environment-list") + description = "This is the description" + name = "Test environment" + data = { + "name": name, + "project": project.id, + "description": description, + } + Environment.objects.create(name=name, description=description, project=project) + + # When + response = admin_client.post( + url, data=json.dumps(data), content_type="application/json" + ) + + # Then + assert response.status_code == 400 + assert response.json() == { + "non_field_errors": ["An environment with this name already exists."] + } + + def test_create_environment_without_required_metadata_returns_400( project, admin_client_new,