diff --git a/oxrlib/cache.py b/oxrlib/cache.py index d19703201152cf1b364f1a15b350fc441438a7c1..03511d49d7f5de148ae2e9611226160bf291a97c 100644 --- a/oxrlib/cache.py +++ b/oxrlib/cache.py @@ -33,6 +33,10 @@ class CacheBase: def __init__(self, dir_path, **kwargs): self.dir_path = dir_path + try: + self.CacheFile = kwargs.pop('file_class') + except KeyError: + pass self.fn_patterns = {} self.setup(**kwargs) @@ -62,3 +66,14 @@ class CacheBase: @_wrap_api_method def historical(self, date, base): return {'date': date.isoformat(), 'base': base} + + +class WriteCacheFile(CacheFileBase): + ERRORS_MAP = [] + + +class CacheWriter(CacheBase): + CacheFile = WriteCacheFile + + def open(self, path): + return self.CacheFile(path, 'w') diff --git a/oxrlib/loaders.py b/oxrlib/loaders.py index 750ec3f58dde46f48b0e216b5348f8e112da27c2..2a600ed36a010e9e3e8dbd62e342f9c50efeaff5 100644 --- a/oxrlib/loaders.py +++ b/oxrlib/loaders.py @@ -14,10 +14,11 @@ class ReadCacheFile(cache.CacheFileBase): class FileCache(cache.CacheBase): + CacheFile = ReadCacheFile ConfigurationError = errors.CacheLoaderConfigurationError def open(self, path): - return ReadCacheFile(path) + return self.CacheFile(path) class OXRAPIRequest: diff --git a/tests/test_CacheWriter.py b/tests/test_CacheWriter.py new file mode 100644 index 0000000000000000000000000000000000000000..b9330757e412328ce149382f35c15dd38a21e4d3 --- /dev/null +++ b/tests/test_CacheWriter.py @@ -0,0 +1,35 @@ +import datetime +import io +import pathlib + +import pytest + +from . import any_date, relpath +import oxrlib.cache +import oxrlib.errors + +CACHE_PATH = relpath('writecache') +HISTORICAL_PATTERN = '{date}_{base}_cache.json' + +class TestCacheFile(oxrlib.cache.WriteCacheFile): + def __init__(self, path, *args, **kwargs): + self.path = path + assert args[0].startswith('w') + + def open(self): + open_file = io.StringIO() + open_file.name = self.path.as_posix() + return open_file + + +@pytest.fixture +def dummycache(): + cache = oxrlib.cache.CacheWriter(CACHE_PATH, file_class=TestCacheFile) + cache.setup(historical=HISTORICAL_PATTERN) + return cache + +def test_cache_success(dummycache, any_date): + base = 'USD' + expect_name = CACHE_PATH / HISTORICAL_PATTERN.format(date=any_date.isoformat(), base=base) + with dummycache.historical(any_date, base) as cache_file: + assert pathlib.Path(cache_file.name) == expect_name