Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
test_auth: Refactor an abstract class for attributes sync tests.
PieterCKbce1e2adf4f7
diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex 747a0c90ae9..36f3c239b13 100644--- a/zerver/tests/test_auth_backends.py+++ b/zerver/tests/test_auth_backends.py@@ -2204,7 +2204,111 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase, ABC):self.assertEqual(created_user.role, UserProfile.ROLE_MEMBER)-class SAMLAuthBackendTest(SocialAuthBase):+class SocialAuthBaseWithSyncAttrTest(SocialAuthBase, ABC):+ """+ Abstract test class for providers that supports user attribute+ sync through SOCIAL_AUTH_SYNC_ATTRS_DICT.+ """++ @staticmethod+ def derive_extra_attrs_from_config(sync_attrs_config: dict[str, Any]) -> list[str]:+ """+ Derive the extra_attrs list from the sync config.+ """+ declared = []+ for key, value in sync_attrs_config.items():+ if key == "groups":+ continue+ if isinstance(value, str):+ declared.append(value)+ return declared++ @abstractmethod+ def social_auth_test_with_sync_attrs(+ self,+ account_data_dict: dict[str, str],+ *,+ subdomain: str,+ is_signup: bool = False,+ extra_attrs: dict[str, Any],+ sync_attrs_config: dict[str, Any],+ multiuse_object_key: str = "",+ ) -> "TestHttpResponse":+ """+ Run social_auth_test with provider-specific settings applied.++ Implementations must:+ 1. Apply SOCIAL_AUTH_SYNC_ATTRS_DICT (via sync_attrs_config) using+ self.settings() internally.+ 2. Plumb extra_attrs to social_auth_test.+ 3. Call self.social_auth_test() and return the result.++ Callers wrap this in assertLogs if they need to capture log output.+ """+ raise NotImplementedError++ def test_social_auth_full_name_sync(self) -> None:+ sync_attrs_dict = {"zulip": {self.BACKEND_CLASS.name: {"full_name": True}}}+ new_name = "Updated Name"++ account_data_dict = self.get_account_data_dict(email=self.email, name=new_name)+ with self.assertLogs(self.logger_string, level="INFO"):+ result = self.social_auth_test_with_sync_attrs(+ account_data_dict,+ subdomain="zulip",+ extra_attrs={},+ sync_attrs_config=sync_attrs_dict,+ )+ data = load_subdomain_token(result)+ self.assertEqual(data["email"], self.email)+ self.assertEqual(result.status_code, 302)+ self.user_profile.refresh_from_db()+ self.assertEqual(self.user_profile.full_name, new_name)++ # Without full_name sync configured, the name should not be updated.+ account_data_dict = self.get_account_data_dict(email=self.email, name="Another Name")+ result = self.social_auth_test_with_sync_attrs(+ account_data_dict,+ subdomain="zulip",+ extra_attrs={},+ sync_attrs_config={},+ )+ data = load_subdomain_token(result)+ self.assertEqual(data["email"], self.email)+ self.assertEqual(result.status_code, 302)+ self.user_profile.refresh_from_db()+ self.assertEqual(self.user_profile.full_name, new_name)++ # Name with invalid characters should be rejected with a warning.+ account_data_dict = self.get_account_data_dict(email=self.email, name="Invalid* Name")+ with (+ self.assertLogs(self.logger_string, level="WARNING") as m,+ ):+ result = self.social_auth_test_with_sync_attrs(+ account_data_dict,+ subdomain="zulip",+ extra_attrs={},+ sync_attrs_config=sync_attrs_dict,+ )+ # Logging in succeeds.+ data = load_subdomain_token(result)+ self.assertEqual(data["email"], self.email)+ self.assertEqual(result.status_code, 302)+ self.user_profile.refresh_from_db()+ # The name doesn't get synced however, and we log a warning.+ self.assertEqual(self.user_profile.full_name, new_name)+ self.assertEqual(+ m.output,+ [+ self.logger_output(+ f"Failed to sync full_name for user {self.user_profile.id}: Invalid characters in name!",+ type="warning",+ )+ ],+ )+++class SAMLAuthBackendTest(SocialAuthBaseWithSyncAttrTest):BACKEND_CLASS = SAMLAuthBackendLOGIN_URL = "/accounts/login/social/saml/test_idp"SIGNUP_URL = "/accounts/register/social/saml/test_idp"@@ -2289,6 +2393,41 @@ class SAMLAuthBackendTest(SocialAuthBase):return result+ @override+ def social_auth_test_with_sync_attrs(+ self,+ account_data_dict: dict[str, str],+ *,+ subdomain: str,+ is_signup: bool = False,+ extra_attrs: dict[str, Any],+ sync_attrs_config: dict[str, Any],+ multiuse_object_key: str = "",+ ) -> "TestHttpResponse":+ saml_extra_attrs = {}+ for key, value in extra_attrs.items():+ if isinstance(value, list):+ saml_extra_attrs[key] = value+ else:+ saml_extra_attrs[key] = [value]+ idps_dict = copy.deepcopy(settings.SOCIAL_AUTH_SAML_ENABLED_IDPS)+ if saml_sync_attrs_dict := sync_attrs_config.get(subdomain, {}).get("saml"):+ idps_dict["test_idp"]["extra_attrs"] = self.derive_extra_attrs_from_config(+ saml_sync_attrs_dict+ )++ with self.settings(+ SOCIAL_AUTH_SAML_ENABLED_IDPS=idps_dict,+ SOCIAL_AUTH_SYNC_ATTRS_DICT=sync_attrs_config,+ ):+ return self.social_auth_test(+ account_data_dict,+ subdomain=subdomain,+ is_signup=is_signup,+ multiuse_object_key=multiuse_object_key,+ extra_attributes=saml_extra_attrs,+ )+def generate_saml_response(self,email: str,@@ -3644,63 +3783,6 @@ class SAMLAuthBackendTest(SocialAuthBase):).valueself.assertEqual(phone_field_value, expected_value)- def test_social_auth_full_name_sync(self) -> None:- sync_attrs_dict = {"zulip": {"saml": {"full_name": True}}}- new_name = "Updated Name"-- with self.settings(SOCIAL_AUTH_SYNC_ATTRS_DICT=sync_attrs_dict):- account_data_dict = self.get_account_data_dict(email=self.email, name=new_name)- with self.assertLogs(self.logger_string, level="INFO"):- result = self.social_auth_test(- account_data_dict,- subdomain="zulip",- )- data = load_subdomain_token(result)- self.assertEqual(data["email"], self.email)- self.assertEqual(result.status_code, 302)- self.user_profile.refresh_from_db()- self.assertEqual(self.user_profile.full_name, new_name)-- # Without full_name sync configured, the name should not be updated.- with self.settings(SOCIAL_AUTH_SYNC_ATTRS_DICT={}):- account_data_dict = self.get_account_data_dict(email=self.email, name="Another Name")- result = self.social_auth_test(- account_data_dict,- subdomain="zulip",- )- data = load_subdomain_token(result)- self.assertEqual(data["email"], self.email)- self.assertEqual(result.status_code, 302)- self.user_profile.refresh_from_db()- self.assertEqual(self.user_profile.full_name, new_name)-- # Name with invalid characters should be rejected with a warning.- with (- self.settings(SOCIAL_AUTH_SYNC_ATTRS_DICT=sync_attrs_dict),- self.assertLogs(self.logger_string, level="WARNING") as m,- ):- account_data_dict = self.get_account_data_dict(email=self.email, name="Invalid* Name")- result = self.social_auth_test(- account_data_dict,- subdomain="zulip",- )- # Logging in succeeds.- data = load_subdomain_token(result)- self.assertEqual(data["email"], self.email)- self.assertEqual(result.status_code, 302)- self.user_profile.refresh_from_db()- # The name doesn't get synced however, and we log a warning.- self.assertEqual(self.user_profile.full_name, new_name)- self.assertEqual(- m.output,- [- self.logger_output(- f"Failed to sync full_name for user {self.user_profile.id}: Invalid characters in name!",- type="warning",- )- ],- )-def test_social_auth_group_sync(self) -> None:realm = get_realm("zulip")hamlet = self.example_user("hamlet")@@ -9866,6 +9948,7 @@ class LDAPGroupSyncTest(ZulipTestCase):# Don't load the base class as a test: https://bugs.python.org/issue17519.del SocialAuthBase+del SocialAuthBaseWithSyncAttrTestclass TestCustomAuthDecorator(ZulipTestCase):