From f9d02a605ceece9fc4135480599b68ee5bbabeb9 Mon Sep 17 00:00:00 2001 From: Jesper Hodge Date: Tue, 25 Feb 2025 12:54:22 -0500 Subject: [PATCH] feat: ensure user_fk gets set on save --- enterprise/models.py | 2 ++ tests/test_models.py | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/enterprise/models.py b/enterprise/models.py index 40376c96f..767e7bc61 100644 --- a/enterprise/models.py +++ b/enterprise/models.py @@ -1147,6 +1147,8 @@ def save(self, *args, **kwargs): enterprise_customer=self.enterprise_customer, ) + self.user_fk = self.user_id + return super().save(*args, **kwargs) @property diff --git a/tests/test_models.py b/tests/test_models.py index 94121e5b2..aaf3fd300 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -814,6 +814,29 @@ def test_user_email_property_user_missing(self): enterprise_customer_user = factories.EnterpriseCustomerUserFactory(user_id=42) assert enterprise_customer_user.user_email is None + def test_on_create_should_set_user_fk_to_user_id(self): + """Test that user_fk is set to user_id when creating a record.""" + user_id = 123 + enterprise_customer_user = factories.EnterpriseCustomerUserFactory(user_id=user_id) + enterprise_customer_user.refresh_from_db() + + assert enterprise_customer_user.user_fk == user_id, ( + f"Expected user_fk to be {user_id}, but got {enterprise_customer_user.user_fk}" + ) + + def test_on_update_should_set_user_fk_to_user_id(self): + """Test that user_fk updates when user_id is modified and saved.""" + enterprise_customer_user = factories.EnterpriseCustomerUserFactory(user_id=100) + + new_user_id = 200 + enterprise_customer_user.user_id = new_user_id + enterprise_customer_user.save() + enterprise_customer_user.refresh_from_db() + + assert enterprise_customer_user.user_fk == new_user_id, ( + f"Expected user_fk to update to {new_user_id}, but got {enterprise_customer_user.user_fk}" + ) + @ddt.data("alberteinstein", "richardfeynman", "leosusskind") def test_username_property_user_exists(self, username): user_instance = factories.UserFactory(username=username)