Skip to content

Commit

Permalink
Stop processing validators after fail
Browse files Browse the repository at this point in the history
  • Loading branch information
Spawin committed Jul 13, 2024
1 parent c0825ff commit a1a45eb
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
18 changes: 8 additions & 10 deletions menu_generator/menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,18 @@ def _is_validated(self, item_dict):
if not isinstance(validators, (list, tuple)):
raise ImproperlyConfigured("validators must be a list")

result_validations = []
for validator in validators:
if isinstance(validator, tuple):
if len(validator) <= 1:
func_or_path, *args = validator
if not args:
raise ImproperlyConfigured("You are passing a tuple validator without args %s" % str(validator))
func = get_callable(validator[0])
# Using a python slice to get all items after the first to build function args
args = validator[1:]
# Pass the request as first arg by default
result_validations.append(func(self.request, *args))
else:
func = get_callable(validator)
result_validations.append(func(self.request)) # pragma: no cover
return all(result_validations)
func_or_path, args = validator, []

func = get_callable(func_or_path)
if not func(self.request, *args):
return False
return True

def _has_attr(self, item_dict, attr):
"""
Expand Down
8 changes: 8 additions & 0 deletions menu_generator/tests/test_menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,3 +362,11 @@ def test_subsequent_requests(self):
nav2 = get_menu(ctx, 'NAV_MENU')
# Both menus should be equal
self.assertEqual(nav1, nav2)

def test_menu_multiple_validators_skip_on_false(self):
menu_dict = {
"validators": ["menu_generator.validators.is_staff", "this-is-never-evaluated"],
}
self.request.user = TestUser(authenticated=True)
self.menu.save_user_state(self.request)
self.assertFalse(self.menu._is_validated(menu_dict))

0 comments on commit a1a45eb

Please sign in to comment.