From 184589fac4ff36b5583541f40dff91296c33370a Mon Sep 17 00:00:00 2001 From: Rob Crittenden Date: Mon, 2 Dec 2024 10:23:29 -0500 Subject: [PATCH] Allow looking up constants.Group by gid in addition to name This adds flexibility so we can look up groups by both gid and by name in order to have a more consistent API for management. Related: https://pagure.io/freeipa/issue/9709 Signed-off-by: Rob Crittenden Reviewed-By: Alexander Bokovoy Reviewed-By: Florence Blanc-Renaud --- ipaplatform/base/constants.py | 5 ++++- ipatests/test_ipaplatform/test_constants.py | 11 +++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/ipaplatform/base/constants.py b/ipaplatform/base/constants.py index 1689efe52466f00fd8b014f720e1d21ebdbf2504..f1ef7efff502573bab82e890bcdf87c0ec52a399 100644 --- a/ipaplatform/base/constants.py +++ b/ipaplatform/base/constants.py @@ -86,7 +86,10 @@ class Group(_Entity): try: self._entity = entity = grp.getgrnam(self) except KeyError: - raise ValueError(f"group '{self!s}' not found") from None + try: + self._entity = entity = grp.getgrgid(int(self)) + except (TypeError, ValueError): + raise ValueError(f"group '{self!s}' not found") from None return entity @property diff --git a/ipatests/test_ipaplatform/test_constants.py b/ipatests/test_ipaplatform/test_constants.py index b57bfa48e5ccefe2b22cb00aca8436e0edc01a30..9bb12283609f87bcd875a2c55ee1e8b714dd8b3a 100644 --- a/ipatests/test_ipaplatform/test_constants.py +++ b/ipatests/test_ipaplatform/test_constants.py @@ -1,6 +1,7 @@ # # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # +import grp import pytest from ipaplatform.base.constants import User, Group @@ -40,6 +41,16 @@ def test_group(): assert Group(str(group)) is not group +def test_numeric_group(): + g = grp.getgrnam('apache') + group = Group(g.gr_gid) + assert group.gid == g.gr_gid + assert type(str(group)) is str + assert repr(group) == '' % g.gr_gid + assert group.gid == g.gr_gid + assert group.entity.gr_gid == g.gr_gid + + def test_group_invalid(): invalid = Group("invalid") with pytest.raises(ValueError) as e: -- 2.47.1