authentik/passbook/policies/tests/test_engine.py

60 lines
2.2 KiB
Python

"""policy engine tests"""
from django.core.cache import cache
from django.test import TestCase
from passbook.core.models import User
from passbook.policies.dummy.models import DummyPolicy
from passbook.policies.engine import PolicyEngine
from passbook.policies.models import Policy
class PolicyTestEngine(TestCase):
"""PolicyEngine tests"""
def setUp(self):
cache.clear()
self.user = User.objects.create_user(username="policyuser")
self.policy_false = DummyPolicy.objects.create(
result=False, wait_min=0, wait_max=1
)
self.policy_true = DummyPolicy.objects.create(
result=True, wait_min=0, wait_max=1
)
self.policy_negate = DummyPolicy.objects.create(
negate=True, result=True, wait_min=0, wait_max=1
)
self.policy_raises = Policy.objects.create(name="raises")
def test_engine_empty(self):
"""Ensure empty policy list passes"""
engine = PolicyEngine([], self.user)
self.assertEqual(engine.build().passing, True)
def test_engine(self):
"""Ensure all policies passes (Mix of false and true -> false)"""
engine = PolicyEngine(
DummyPolicy.objects.filter(negate__exact=False), self.user
)
self.assertEqual(engine.build().passing, False)
def test_engine_negate(self):
"""Test negate flag"""
engine = PolicyEngine(DummyPolicy.objects.filter(negate__exact=True), self.user)
self.assertEqual(engine.build().passing, False)
def test_engine_policy_error(self):
"""Test negate flag"""
engine = PolicyEngine(Policy.objects.filter(name="raises"), self.user)
self.assertEqual(engine.build().passing, False)
def test_engine_cache(self):
"""Ensure empty policy list passes"""
engine = PolicyEngine(
DummyPolicy.objects.filter(negate__exact=False), self.user
)
self.assertEqual(len(cache.keys("policy_*")), 0)
self.assertEqual(engine.build().passing, False)
self.assertEqual(len(cache.keys("policy_*")), 2)
self.assertEqual(engine.build().passing, False)
self.assertEqual(len(cache.keys("policy_*")), 2)