rate: Initial commit.

This commit is contained in:
Brett Smith 2017-05-09 09:56:08 -04:00
commit a181166311
6 changed files with 88 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
__pycache__/

0
oxrlib/__init__.py Normal file
View file

47
oxrlib/rate.py Normal file
View file

@ -0,0 +1,47 @@
import datetime
import functools
import json
class Rate:
FIELDS = [
'base',
'disclaimer',
'license',
'rates',
'timestamp',
]
@classmethod
def walk_fields(cls, get_field, transform_prefix):
for fieldname in cls.FIELDS:
value = get_field(fieldname)
if value is not None:
try:
transformer = getattr(cls, '{}_{}'.format(transform_prefix, fieldname))
except AttributeError:
pass
else:
value = transformer(value)
yield (fieldname, value)
def __init__(self, base, rates, **kwargs):
for key, value in self.walk_fields(kwargs.get, 'deserialize'):
setattr(self, key, value)
self.base = base
self.rates = rates
@classmethod
def deserialize_timestamp(cls, value):
return datetime.datetime.fromtimestamp(value)
@classmethod
def serialize_timestamp(cls, value):
return int(value.timestamp())
@classmethod
def from_json_file(cls, json_file):
response = json.load(json_file)
return cls(**response)
def serialize(self):
return dict(self.walk_fields(functools.partial(getattr, self), 'serialize'))

6
tests/__init__.py Normal file
View file

@ -0,0 +1,6 @@
import pathlib
TEST_DIR = pathlib.Path(__file__).parent
def relpath(path):
return TEST_DIR / pathlib.Path(path)

11
tests/historical1.json Normal file
View file

@ -0,0 +1,11 @@
{
"disclaimer": "https://openexchangerates.org/terms/",
"license": "https://openexchangerates.org/license/",
"timestamp": 982342800,
"base": "USD",
"rates": {
"AED": 3.67246,
"ALL": 144.529793,
"ANG": 1.79
}
}

23
tests/test_Rate.py Normal file
View file

@ -0,0 +1,23 @@
import datetime
import io
import json
from . import relpath
import oxrlib.rate
import pytest
@pytest.fixture
def historical1_rate():
with open(relpath('historical1.json').as_posix()) as rate_file:
return oxrlib.rate.Rate.from_json_file(rate_file)
def test_rate_from_json(historical1_rate):
assert historical1_rate.base == 'USD'
assert historical1_rate.timestamp == datetime.datetime(2001, 2, 16, 12, 0, 0)
def test_serialize(historical1_rate):
with open(relpath('historical1.json').as_posix()) as rate_file:
expected = json.load(rate_file)
assert expected == historical1_rate.serialize()