"""Test cacheable.""" from unittest.mock import patch import pytest from accounting.cacheable import cache_item from accounting.cacheable import get_cache_prefix from accounting.cacheable import get_cached_item from accounting.cacheable import pack_key_value_list_for_cache @patch('accounting.cacheable.get_cache_adapter') def test_get_cached_item_found(adapter_getter, mock_cache_adapter): """Test get_cached_item.""" adapter_getter.return_value = mock_cache_adapter test_val = '1' cache_item('data', 'fake', test_val) loaded_val = get_cached_item('data', 'fake') assert loaded_val == test_val @patch('accounting.cacheable.get_cache_adapter') def test_get_cached_item_not_found(adapter_getter, mock_cache_adapter): """Test get_cached_item on a non-existant key.""" adapter_getter.return_value = mock_cache_adapter loaded_val = get_cached_item('data', 'fake2') assert loaded_val is None @patch('accounting.cacheable.get_cache_adapter') def test_cache_item_not_found(cache_adapter_getter, mock_cache_adapter): """Test attempting to get a cache value that is not set.""" cache_adapter_getter.return_value = mock_cache_adapter mock_cache_adapter.flushall() returned_data = get_cached_item('data', 'test_value') assert returned_data is None def test_get_cache_prefix(): """Test getting the cache prefix by type.""" data_prefix = get_cache_prefix('data') assert data_prefix == 'dt_' statement_prefix = get_cache_prefix('statement') assert statement_prefix == 'st_' ap_prefix = get_cache_prefix('appended_fields') assert ap_prefix == 'af_' with pytest.raises(ValueError): bad_prefix = get_cache_prefix('fake') assert bad_prefix is None def test_pack_key_value_list_for_cache(): """Test packing a dict into a string for caching.""" data = { 'int': 15, 'float': 17.434324234, 'bool': False, 'bool2': True, 'str': 'abcdeFG' } known = 'int:15\tfloat:17.434324\tbool:0\tbool2:1\tstr:abcdeFG' cacheable_string = pack_key_value_list_for_cache(data) assert cacheable_string == known