Skip to content

Commit

Permalink
Add get_values_for_keys function to utils (#607)
Browse files Browse the repository at this point in the history
* Add get_values_for_keys function to utils
* Error text improvement and formatting
  • Loading branch information
FernandoKGA authored Jan 14, 2025
1 parent 0dc1321 commit 745fb6f
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
23 changes: 23 additions & 0 deletions constance/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,26 @@ def get_values():
default_initial = ((name, options[0]) for name, options in settings.CONFIG.items())
# Then update the mapping with actually values from the backend
return dict(default_initial, **dict(config._backend.mget(settings.CONFIG)))


def get_values_for_keys(keys):
"""
Retrieve values for specified keys from the backend.
:param keys: List of keys to retrieve.
:return: Dictionary with values for the specified keys.
:raises AttributeError: If any key is not found in the configuration.
"""
if not isinstance(keys, (list, tuple, set)):
raise TypeError('keys must be a list, tuple, or set of strings')

# Prepare default initial mapping
default_initial = {name: options[0] for name, options in settings.CONFIG.items() if name in keys}

# Check if all keys are present in the default_initial mapping
missing_keys = [key for key in keys if key not in default_initial]
if missing_keys:
raise AttributeError(f'"{", ".join(missing_keys)}" keys not found in configuration.')

# Merge default values and backend values, prioritizing backend values
return dict(default_initial, **dict(config._backend.mget(keys)))
28 changes: 27 additions & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from django.test import TestCase

from constance.management.commands.constance import _set_constance_value
from constance.utils import get_values
from constance.utils import get_values, get_values_for_keys


class UtilsTestCase(TestCase):
Expand Down Expand Up @@ -62,3 +62,29 @@ def test_get_values(self):
},
},
)

def test_get_values_for_keys(self):
self.assertEqual(
get_values_for_keys(['BOOL_VALUE', 'CHOICE_VALUE', 'LINEBREAK_VALUE']),
{
'BOOL_VALUE': True,
'CHOICE_VALUE': 'yes',
'LINEBREAK_VALUE': 'Spam spam',
},
)

def test_get_values_for_keys_empty_keys(self):
result = get_values_for_keys([])
self.assertEqual(result, {})

def test_get_values_for_keys_throw_error_if_no_key(self):
self.assertRaisesMessage(
AttributeError,
'"OLD_VALUE, BOLD_VALUE" keys not found in configuration.',
get_values_for_keys,
['BOOL_VALUE', 'OLD_VALUE', 'BOLD_VALUE'],
)

def test_get_values_for_keys_invalid_input_type(self):
with self.assertRaises(TypeError):
get_values_for_keys('key1')

0 comments on commit 745fb6f

Please sign in to comment.