From fc72aafeb844408c1f0993979e53e21e9f69efdf Mon Sep 17 00:00:00 2001 From: AlanCoding Date: Fri, 11 Nov 2016 17:15:33 -0500 Subject: [PATCH] introduce caching for is_system_auditor method --- awx/main/models/__init__.py | 6 +++- awx/main/tests/functional/test_rbac_user.py | 38 +++++++++++++++++++-- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/awx/main/models/__init__.py b/awx/main/models/__init__.py index 321c340a92..dc94eb0b93 100644 --- a/awx/main/models/__init__.py +++ b/awx/main/models/__init__.py @@ -74,7 +74,9 @@ User.add_to_class('auditor_of_organizations', user_get_auditor_of_organizations) @property def user_is_system_auditor(user): - return Role.singleton('system_auditor').members.filter(id=user.id).exists() + if not hasattr(user, '_is_system_auditor'): + user._is_system_auditor = Role.objects.filter(role_field='system_auditor', id=user.id).exists() + return user._is_system_auditor @user_is_system_auditor.setter @@ -82,8 +84,10 @@ def user_is_system_auditor(user, tf): if user.id: if tf: Role.singleton('system_auditor').members.add(user) + user._is_system_auditor = True else: Role.singleton('system_auditor').members.remove(user) + user._is_system_auditor = False User.add_to_class('is_system_auditor', user_is_system_auditor) diff --git a/awx/main/tests/functional/test_rbac_user.py b/awx/main/tests/functional/test_rbac_user.py index 19efd0859b..0b43ce2f1c 100644 --- a/awx/main/tests/functional/test_rbac_user.py +++ b/awx/main/tests/functional/test_rbac_user.py @@ -1,11 +1,45 @@ import pytest from django.apps import apps -from django.contrib.auth.models import User +from django.test import TransactionTestCase from awx.main.migrations import _rbac as rbac from awx.main.access import UserAccess -from awx.main.models import Role +from awx.main.models import Role, User, Organization, Inventory + + +@pytest.mark.django_db +class TestSysAuditor(TransactionTestCase): + def rando(self): + return User.objects.create(username='rando', password='rando', email='rando@com.com') + + def inventory(self): + org = Organization.objects.create(name='org') + inv = Inventory.objects.create(name='inv', organization=org) + return inv + + def test_auditor_caching(self): + rando = self.rando() + with self.assertNumQueries(1): + v = rando.is_system_auditor + assert not v + with self.assertNumQueries(0): + v = rando.is_system_auditor + assert not v + + def test_auditor_setter(self): + rando = self.rando() + inventory = self.inventory() + rando.is_system_auditor = True + assert rando in inventory.read_role + + def test_refresh_with_set(self): + rando = self.rando() + rando.is_system_auditor = True + assert rando.is_system_auditor + rando.is_system_auditor = False + assert not rando.is_system_auditor + @pytest.mark.django_db