Skip to content

Commit

Permalink
Fix default arguments are not respected when crafting cache key (#172)
Browse files Browse the repository at this point in the history
  • Loading branch information
Galtozzy authored Jan 9, 2025
2 parents 7e6b892 + 86c1817 commit b469bfe
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
9 changes: 6 additions & 3 deletions py_cachify/_backend/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,18 @@


def get_full_key_from_signature(bound_args: inspect.BoundArguments, key: str) -> str:
bound_args.apply_defaults()
_args_repr = f'{bound_args}'

args_dict = bound_args.arguments
args: Tuple[str, Any] = args_dict.pop('args', ())
args: Tuple[Any, ...] = args_dict.pop('args', ())
kwargs: Dict[str, Any] = args_dict.pop('kwargs', {})
kwargs.update(args_dict)

try:
return key.format(*args, **kwargs)
except IndexError:
raise ValueError('Arguments in a key do not match function signature') from None
except (IndexError, KeyError):
raise ValueError(f'Arguments in a key({key}) do not match function signature params({_args_repr})') from None


def is_coroutine(
Expand Down
20 changes: 17 additions & 3 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import inspect
import re

import pytest
from pytest_mock import MockerFixture
Expand All @@ -23,7 +24,12 @@ def test_get_full_key_valid_arguments(args_kwargs_signature):

def test_get_full_key_invalid_key_format(args_kwargs_signature):
bound_args = args_kwargs_signature.bind('value1', 'value2')
with pytest.raises(ValueError, match='Arguments in a key do not match function signature'):
bound_args.apply_defaults()

with pytest.raises(
ValueError,
match=re.escape(f'Arguments in a key(key_{{}}_{{}}_{{}}) do not match function signature params({bound_args})'),
):
get_full_key_from_signature(bound_args, 'key_{}_{}_{}')


Expand All @@ -35,8 +41,16 @@ def test_get_full_key_empty_key_and_arguments(args_kwargs_signature):

def test_get_full_key_mixed_placeholders(args_kwargs_signature):
bound_args = args_kwargs_signature.bind('value1', 'value2', arg3='value3')
with pytest.raises(ValueError, match='Arguments in a key do not match function signature'):
get_full_key_from_signature(bound_args, 'key_{}_{}_{}_{invalid_arg}')
bound_args.apply_defaults()

with pytest.raises(
ValueError,
match=re.escape(
'Arguments in a key(key_{}_{}_{}_{invalid_arg}) '
+ f'do not match function signature params({bound_args})'
),
):
_ = get_full_key_from_signature(bound_args, 'key_{}_{}_{}_{invalid_arg}')


def test_reset_calls_delete_with_key(init_cachify_fixture, args_kwargs_signature, mocker: MockerFixture):
Expand Down

0 comments on commit b469bfe

Please sign in to comment.