cache: Add CacheWriter class.

This commit is contained in:
Brett Smith 2017-05-12 13:27:45 -04:00
parent eba27c16ae
commit 2d482bb7b0
3 changed files with 52 additions and 1 deletions

View file

@ -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')

View file

@ -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:

35
tests/test_CacheWriter.py Normal file
View file

@ -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