Skip to content

Commit

Permalink
override_containers: delete afterwards when type was not there.
Browse files Browse the repository at this point in the history
And add tests for this context manager.
  • Loading branch information
mauritsvanrees authored and Michael Howitz committed Feb 1, 2017
1 parent fc1bb71 commit c0422f0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/AccessControl/SimpleObjectPolicies.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
'''

_noroles = [] # this is imported in various places
_marker = object()

from contextlib import contextmanager
import Record
Expand Down Expand Up @@ -125,8 +126,10 @@ def allow_type(Type, allowed=1):
@contextmanager
def override_containers(type_, assertions):
"""Temporarily override the container assertions."""
orig_container = Containers(type_)
orig_container = Containers(type_, _marker)
ContainerAssertions[type_] = assertions
yield
if orig_container is not None:
if orig_container is _marker:
del ContainerAssertions[type_]
else:
ContainerAssertions[type_] = orig_container
21 changes: 21 additions & 0 deletions src/AccessControl/tests/testZopeSecurityPolicy.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,27 @@ def testUnicodeRolesForPermission(self):
v = self.policy.checkPermission(u'View', r_item, o_context)
self.assert_(v, '_View_Permission should grant access to theowner')

def testContainersContextManager(self):
from AccessControl.SimpleObjectPolicies import override_containers
from AccessControl.SimpleObjectPolicies import ContainerAssertions
from AccessControl.SimpleObjectPolicies import Containers
from types import EllipsisType
# Surely we have no assertions for this type. There might be a good
# reason to have then, but I have not even heard of this type.
self.assertFalse(EllipsisType in ContainerAssertions)
with override_containers(EllipsisType, 1):
self.assertTrue(EllipsisType in ContainerAssertions)
self.assertEqual(Containers(EllipsisType), 1)
# Override it again.
with override_containers(EllipsisType, {}):
self.assertEqual(Containers(EllipsisType), {})
# We are outside the nested override, so the first override should
# have been restored.
self.assertEqual(Containers(EllipsisType), 1)
# We are outside all overrides, so the type should no longer be in the
# assertions.
self.assertFalse(EllipsisType in ContainerAssertions)

def testAqNames(self):
policy = self.policy
names = {
Expand Down

0 comments on commit c0422f0

Please sign in to comment.